File:
[LON-CAPA] /
loncom /
homework /
grades.pm
Revision
1.649:
download - view:
text,
annotated -
select for diffs
Tue Sep 13 21:42:58 2011 UTC (12 years, 11 months ago) by
raeburn
Branches:
MAIN
CVS tags:
HEAD
- Additional (eighteenth field) BubblesPerRow in Bubblesheet Format file.
- specify bubbles available for each question row (default is 10).
- Support case where question (or subquestion for optionresponse,
matchresponse, or rankresponse) requires more bubbles than in one line.
- Students prompted to bubble once in multiple lines.
- Numbering recognizes multiple lines per question.
- Also supports: imageresponse, stringresponse, formularesponse where
students leave link(s) blank if weight assigned is greater than
bubbles per line -- multiple lines also supported in this case.
For example:
- 15-bubble MSU Art History exams now supported on standard 10-bubble
bubblesheets used at MSU.
1: # The LearningOnline Network with CAPA
2: # The LON-CAPA Grading handler
3: #
4: # $Id: grades.pm,v 1.649 2011/09/13 21:42:58 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 $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
1412: $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1413:
1414: //===================== Show list of keywords ====================
1415: function keywords(formname) {
1416: var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1417: if (nret==null) return;
1418: formname.keywords.value = nret;
1419:
1420: if (formname.keywords.value != "") {
1421: formname.refresh.value = "on";
1422: formname.submit();
1423: }
1424: return;
1425: }
1426:
1427: //===================== Script to view submitted by ==================
1428: function viewSubmitter(submitter) {
1429: document.SCORE.refresh.value = "on";
1430: document.SCORE.NCT.value = "1";
1431: document.SCORE.unamedom0.value = submitter;
1432: document.SCORE.submit();
1433: return;
1434: }
1435:
1436: //===================== Script to add keyword(s) ==================
1437: function getSel() {
1438: if (document.getSelection) txt = document.getSelection();
1439: else if (document.selection) txt = document.selection.createRange().text;
1440: else return;
1441: var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
1442: if (cleantxt=="") {
1443: alert("$alertmsg");
1444: return;
1445: }
1446: var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
1447: if (nret==null) return;
1448: document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1449: if (document.SCORE.keywords.value != "") {
1450: document.SCORE.refresh.value = "on";
1451: document.SCORE.submit();
1452: }
1453: return;
1454: }
1455:
1456: //====================== Script for composing message ==============
1457: // preload images
1458: img1 = new Image();
1459: img1.src = "$iconpath/mailbkgrd.gif";
1460: img2 = new Image();
1461: img2.src = "$iconpath/mailto.gif";
1462:
1463: function msgCenter(msgform,usrctr,fullname) {
1464: var Nmsg = msgform.savemsgN.value;
1465: savedMsgHeader(Nmsg,usrctr,fullname);
1466: var subject = msgform.msgsub.value;
1467: var msgchk = document.SCORE["includemsg"+usrctr].value;
1468: re = /msgsub/;
1469: var shwsel = "";
1470: if (re.test(msgchk)) { shwsel = "checked" }
1471: subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
1472: displaySubject(checkEntities(subject),shwsel);
1473: for (var i=1; i<=Nmsg; i++) {
1474: var testmsg = "savemsg"+i+",";
1475: re = new RegExp(testmsg,"g");
1476: shwsel = "";
1477: if (re.test(msgchk)) { shwsel = "checked" }
1478: var message = document.SCORE["savemsg"+i].value;
1479: message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1480: displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
1481: //any < is already converted to <, etc. However, only once!!
1482: }
1483: newmsg = document.SCORE["newmsg"+usrctr].value;
1484: shwsel = "";
1485: re = /newmsg/;
1486: if (re.test(msgchk)) { shwsel = "checked" }
1487: newMsg(newmsg,shwsel);
1488: msgTail();
1489: return;
1490: }
1491:
1492: function checkEntities(strx) {
1493: if (strx.length == 0) return strx;
1494: var orgStr = ["&", "<", ">", '"'];
1495: var newStr = ["&", "<", ">", """];
1496: var counter = 0;
1497: while (counter < 4) {
1498: strx = strReplace(strx,orgStr[counter],newStr[counter]);
1499: counter++;
1500: }
1501: return strx;
1502: }
1503:
1504: function strReplace(strx, orgStr, newStr) {
1505: return strx.split(orgStr).join(newStr);
1506: }
1507:
1508: function savedMsgHeader(Nmsg,usrctr,fullname) {
1509: var height = 70*Nmsg+250;
1510: var scrollbar = "no";
1511: if (height > 600) {
1512: height = 600;
1513: scrollbar = "yes";
1514: }
1515: var xpos = (screen.width-600)/2;
1516: xpos = (xpos < 0) ? '0' : xpos;
1517: var ypos = (screen.height-height)/2-30;
1518: ypos = (ypos < 0) ? '0' : ypos;
1519:
1520: pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1521: pWin.focus();
1522: pDoc = pWin.document;
1523: pDoc.$docopen;
1524: pDoc.write('$start_page_msg_central');
1525:
1526: pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
1527: pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1528: pDoc.write("<h3><span class=\\"LC_info\\"> Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
1529:
1530: pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
1531: pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1532: pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
1533: }
1534: function displaySubject(msg,shwsel) {
1535: pDoc = pWin.document;
1536: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1537: pDoc.write("<td>Subject<\\/td>");
1538: pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1539: pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1540: }
1541:
1542: function displaySavedMsg(ctr,msg,shwsel) {
1543: pDoc = pWin.document;
1544: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1545: pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
1546: pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1547: pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1548: }
1549:
1550: function newMsg(newmsg,shwsel) {
1551: pDoc = pWin.document;
1552: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1553: pDoc.write("<td align=\\"center\\">New<\\/td>");
1554: pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1555: pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1556: }
1557:
1558: function msgTail() {
1559: pDoc = pWin.document;
1560: pDoc.write("<\\/table>");
1561: pDoc.write("<\\/td><\\/tr><\\/table> ");
1562: pDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:checkInput()\\"> ");
1563: pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
1564: pDoc.write("<\\/form>");
1565: pDoc.write('$end_page_msg_central');
1566: pDoc.close();
1567: }
1568:
1569: //====================== Script for keyword highlight options ==============
1570: function kwhighlight() {
1571: var kwclr = document.SCORE.kwclr.value;
1572: var kwsize = document.SCORE.kwsize.value;
1573: var kwstyle = document.SCORE.kwstyle.value;
1574: var redsel = "";
1575: var grnsel = "";
1576: var blusel = "";
1577: if (kwclr=="red") {var redsel="checked"};
1578: if (kwclr=="green") {var grnsel="checked"};
1579: if (kwclr=="blue") {var blusel="checked"};
1580: var sznsel = "";
1581: var sz1sel = "";
1582: var sz2sel = "";
1583: if (kwsize=="0") {var sznsel="checked"};
1584: if (kwsize=="+1") {var sz1sel="checked"};
1585: if (kwsize=="+2") {var sz2sel="checked"};
1586: var synsel = "";
1587: var syisel = "";
1588: var sybsel = "";
1589: if (kwstyle=="") {var synsel="checked"};
1590: if (kwstyle=="<i>") {var syisel="checked"};
1591: if (kwstyle=="<b>") {var sybsel="checked"};
1592: highlightCentral();
1593: highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
1594: highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
1595: highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
1596: highlightend();
1597: return;
1598: }
1599:
1600: function highlightCentral() {
1601: // if (window.hwdWin) window.hwdWin.close();
1602: var xpos = (screen.width-400)/2;
1603: xpos = (xpos < 0) ? '0' : xpos;
1604: var ypos = (screen.height-330)/2-30;
1605: ypos = (ypos < 0) ? '0' : ypos;
1606:
1607: hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1608: hwdWin.focus();
1609: var hDoc = hwdWin.document;
1610: hDoc.$docopen;
1611: hDoc.write('$start_page_highlight_central');
1612: hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1613: hDoc.write("<h3><span class=\\"LC_info\\"> Keyword Highlight Options<\\/span><\\/h3><br /><br />");
1614:
1615: hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
1616: hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1617: hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
1618: }
1619:
1620: function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) {
1621: var hDoc = hwdWin.document;
1622: hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1623: hDoc.write("<td align=\\"left\\">");
1624: hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+"> "+clrtxt+"<\\/td>");
1625: hDoc.write("<td align=\\"left\\">");
1626: hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+"> "+sztxt+"<\\/td>");
1627: hDoc.write("<td align=\\"left\\">");
1628: hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+"> "+sytxt+"<\\/td>");
1629: hDoc.write("<\\/tr>");
1630: }
1631:
1632: function highlightend() {
1633: var hDoc = hwdWin.document;
1634: hDoc.write("<\\/table>");
1635: hDoc.write("<\\/td><\\/tr><\\/table> ");
1636: hDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:updateChoice(1)\\"> ");
1637: hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
1638: hDoc.write("<\\/form>");
1639: hDoc.write('$end_page_highlight_central');
1640: hDoc.close();
1641: }
1642:
1643: SUBJAVASCRIPT
1644: }
1645:
1646: sub get_increment {
1647: my $increment = $env{'form.increment'};
1648: if ($increment != 1 && $increment != .5 && $increment != .25 &&
1649: $increment != .1) {
1650: $increment = 1;
1651: }
1652: return $increment;
1653: }
1654:
1655: sub gradeBox_start {
1656: return (
1657: &Apache::loncommon::start_data_table()
1658: .&Apache::loncommon::start_data_table_header_row()
1659: .'<th>'.&mt('Part').'</th>'
1660: .'<th>'.&mt('Points').'</th>'
1661: .'<th> </th>'
1662: .'<th>'.&mt('Assign Grade').'</th>'
1663: .'<th>'.&mt('Weight').'</th>'
1664: .'<th>'.&mt('Grade Status').'</th>'
1665: .&Apache::loncommon::end_data_table_header_row()
1666: );
1667: }
1668:
1669: sub gradeBox_end {
1670: return (
1671: &Apache::loncommon::end_data_table()
1672: );
1673: }
1674: #--- displays the grading box, used in essay type problem and grading by page/sequence
1675: sub gradeBox {
1676: my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1677: my $checkIcon = '<img alt="'.&mt('Check Mark').
1678: '" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1679: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1680: my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)')
1681: : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1682: $wgt = ($wgt > 0 ? $wgt : '1');
1683: my $score = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1684: '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1685: my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1686: my $display_part= &get_display_part($partid,$symb);
1687: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
1688: [$partid]);
1689: my $aggtries = $$record{'resource.'.$partid.'.tries'};
1690: if ($last_resets{$partid}) {
1691: $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
1692: }
1693: $result.=&Apache::loncommon::start_data_table_row();
1694: my $ctr = 0;
1695: my $thisweight = 0;
1696: my $increment = &get_increment();
1697:
1698: my $radio.='<table border="0"><tr>'."\n"; # display radio buttons in a nice table 10 across
1699: while ($thisweight<=$wgt) {
1700: $radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1701: 'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1702: $thisweight.')" value="'.$thisweight.'" '.
1703: ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1704: $radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1705: $thisweight += $increment;
1706: $ctr++;
1707: }
1708: $radio.='</tr></table>';
1709:
1710: my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1711: ($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1712: 'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1713: $wgt.')" /></td>'."\n";
1714: $line.='<td>/'.$wgt.' '.$wgtmsg.
1715: ($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? ' '.$checkIcon : '').
1716: ' </td>'."\n";
1717: $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1718: 'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1719: if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1720: $line.='<option></option>'.
1721: '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1722: } else {
1723: $line.='<option selected="selected"></option>'.
1724: '<option value="excused" >'.&mt('excused').'</option>';
1725: }
1726: $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
1727:
1728:
1729: $result .=
1730: '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
1731: $result.=&Apache::loncommon::end_data_table_row();
1732: $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
1733: '<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
1734: '<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1735: $$record{'resource.'.$partid.'.solved'}.'" />'."\n".
1736: '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
1737: $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
1738: '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
1739: $aggtries.'" />'."\n";
1740: my $res_error;
1741: $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1742: if ($res_error) {
1743: return &navmap_errormsg();
1744: }
1745: return $result;
1746: }
1747:
1748: sub handback_box {
1749: my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
1750: my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
1751: my (@respids);
1752: my @part_response_id = &flatten_responseType($responseType);
1753: foreach my $part_response_id (@part_response_id) {
1754: my ($part,$resp) = @{ $part_response_id };
1755: if ($part eq $partid) {
1756: push(@respids,$resp);
1757: }
1758: }
1759: my $result;
1760: foreach my $respid (@respids) {
1761: my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
1762: my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
1763: next if (!@$files);
1764: my $file_counter = 1;
1765: foreach my $file (@$files) {
1766: if ($file =~ /\/portfolio\//) {
1767: my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1768: my ($name,$version,$ext) = &file_name_version_ext($file_disp);
1769: $file_disp = "$name.$ext";
1770: $file = $file_path.$file_disp;
1771: $result.=&mt('Return commented version of [_1] to student.',
1772: '<span class="LC_filename">'.$file_disp.'</span>');
1773: $result.='<input type="file" name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1774: $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1775: $result.='('.&mt('File will be uploaded when you click on Save & Next below.').')<br />';
1776: $file_counter++;
1777: }
1778: }
1779: }
1780: return $result;
1781: }
1782:
1783: sub show_problem {
1784: my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1785: my $rendered;
1786: my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1787: &Apache::lonxml::remember_problem_counter();
1788: if ($mode eq 'both' or $mode eq 'text') {
1789: $rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1790: $env{'request.course.id'},
1791: undef,\%form);
1792: }
1793: if ($removeform) {
1794: $rendered=~s|<form(.*?)>||g;
1795: $rendered=~s|</form>||g;
1796: $rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1797: }
1798: my $companswer;
1799: if ($mode eq 'both' or $mode eq 'answer') {
1800: &Apache::lonxml::restore_problem_counter();
1801: $companswer=
1802: &Apache::loncommon::get_student_answers($symb,$uname,$udom,
1803: $env{'request.course.id'},
1804: %form);
1805: }
1806: if ($removeform) {
1807: $companswer=~s|<form(.*?)>||g;
1808: $companswer=~s|</form>||g;
1809: $companswer=~s|name="submit"|name="would_have_been_submit"|g;
1810: }
1811: $rendered=
1812: '<div class="LC_Box">'
1813: .'<h3 class="LC_hcell">'.&mt('View of the problem').'</h3>'
1814: .$rendered
1815: .'</div>';
1816: $companswer=
1817: '<div class="LC_Box">'
1818: .'<h3 class="LC_hcell">'.&mt('Correct answer').'</h3>'
1819: .$companswer
1820: .'</div>';
1821: my $result;
1822: if ($mode eq 'both') {
1823: $result=$rendered.$companswer;
1824: } elsif ($mode eq 'text') {
1825: $result=$rendered;
1826: } elsif ($mode eq 'answer') {
1827: $result=$companswer;
1828: }
1829: return $result;
1830: }
1831:
1832: sub files_exist {
1833: my ($r, $symb) = @_;
1834: my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1835:
1836: foreach my $student (@students) {
1837: my ($uname,$udom,$fullname) = split(/:/,$student);
1838: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
1839: $udom,$uname);
1840: my ($string,$timestamp)= &get_last_submission(\%record);
1841: foreach my $submission (@$string) {
1842: my ($partid,$respid) =
1843: ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1844: my $files=&get_submitted_files($udom,$uname,$partid,$respid,
1845: \%record);
1846: return 1 if (@$files);
1847: }
1848: }
1849: return 0;
1850: }
1851:
1852: sub download_all_link {
1853: my ($r,$symb) = @_;
1854: unless (&files_exist($r, $symb)) {
1855: $r->print(&mt('There are currently no submitted documents.'));
1856: return;
1857: }
1858:
1859: my $all_students =
1860: join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
1861:
1862: my $parts =
1863: join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
1864:
1865: my $identifier = &Apache::loncommon::get_cgi_id();
1866: &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
1867: 'cgi.'.$identifier.'.symb' => $symb,
1868: 'cgi.'.$identifier.'.parts' => $parts,});
1869: $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
1870: &mt('Download All Submitted Documents').'</a>');
1871: return;
1872: }
1873:
1874: sub submit_download_link {
1875: my ($request,$symb) = @_;
1876: if (!$symb) { return ''; }
1877: #FIXME: Figure out which type of problem this is and provide appropriate download
1878: &download_all_link($request,$symb);
1879: }
1880:
1881: sub build_section_inputs {
1882: my $section_inputs;
1883: if ($env{'form.section'} eq '') {
1884: $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
1885: } else {
1886: my @sections = &Apache::loncommon::get_env_multiple('form.section');
1887: foreach my $section (@sections) {
1888: $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
1889: }
1890: }
1891: return $section_inputs;
1892: }
1893:
1894: # --------------------------- show submissions of a student, option to grade
1895: sub submission {
1896: my ($request,$counter,$total,$symb) = @_;
1897: my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
1898: $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
1899: my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
1900: $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1901:
1902: my $probtitle=&Apache::lonnet::gettitle($symb);
1903: if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1904:
1905: if (!&canview($usec)) {
1906: $request->print('<span class="LC_warning">Unable to view requested student.('.
1907: $uname.':'.$udom.' in section '.$usec.' in course id '.
1908: $env{'request.course.id'}.')</span>');
1909: return;
1910: }
1911:
1912: if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
1913: if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
1914: if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
1915: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1916: my $checkIcon = '<img alt="'.&mt('Check Mark').
1917: '" src="'.$request->dir_config('lonIconsURL').
1918: '/check.gif" height="16" border="0" />';
1919:
1920: my %old_essays;
1921: # header info
1922: if ($counter == 0) {
1923: &sub_page_js($request);
1924: &sub_page_kw_js($request);
1925:
1926: # option to display problem, only once else it cause problems
1927: # with the form later since the problem has a form.
1928: if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1929: my $mode;
1930: if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1931: $mode='both';
1932: } elsif ($env{'form.vProb'} eq 'yes') {
1933: $mode='text';
1934: } elsif ($env{'form.vAns'} eq 'yes') {
1935: $mode='answer';
1936: }
1937: &Apache::lonxml::clear_problem_counter();
1938: $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1939: }
1940:
1941: # kwclr is the only variable that is guaranteed to be non blank
1942: # if this subroutine has been called once.
1943: my %keyhash = ();
1944: # if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1945: if (1) {
1946: %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1947: $env{'course.'.$env{'request.course.id'}.'.domain'},
1948: $env{'course.'.$env{'request.course.id'}.'.num'});
1949:
1950: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1951: $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
1952: $env{'form.kwclr'} = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
1953: $env{'form.kwsize'} = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
1954: $env{'form.kwstyle'} = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
1955: $env{'form.msgsub'} = $keyhash{$symb.'_subject'} ne '' ?
1956: $keyhash{$symb.'_subject'} : $probtitle;
1957: $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1958: }
1959: my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1960: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1961: $request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1962: '<input type="hidden" name="command" value="handgrade" />'."\n".
1963: '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
1964: '<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1965: '<input type="hidden" name="refresh" value="off" />'."\n".
1966: '<input type="hidden" name="studentNo" value="" />'."\n".
1967: '<input type="hidden" name="gradeOpt" value="" />'."\n".
1968: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1969: '<input type="hidden" name="vProb" value="'.$env{'form.vProb'}.'" />'."\n".
1970: '<input type="hidden" name="vAns" value="'.$env{'form.vAns'}.'" />'."\n".
1971: '<input type="hidden" name="lastSub" value="'.$env{'form.lastSub'}.'" />'."\n".
1972: &build_section_inputs().
1973: '<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1974: '<input type="hidden" name="NCT"'.
1975: ' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1976: # if ($env{'form.handgrade'} eq 'yes') {
1977: if (1) {
1978: $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
1979: '<input type="hidden" name="kwclr" value="'.$env{'form.kwclr'}.'" />'."\n".
1980: '<input type="hidden" name="kwsize" value="'.$env{'form.kwsize'}.'" />'."\n".
1981: '<input type="hidden" name="kwstyle" value="'.$env{'form.kwstyle'}.'" />'."\n".
1982: '<input type="hidden" name="msgsub" value="'.$env{'form.msgsub'}.'" />'."\n".
1983: '<input type="hidden" name="shownSub" value="0" />'."\n".
1984: '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1985: foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
1986: $request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
1987: }
1988: }
1989:
1990: my ($cts,$prnmsg) = (1,'');
1991: while ($cts <= $env{'form.savemsgN'}) {
1992: $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1993: (!exists($keyhash{$symb.'_savemsg'.$cts}) ?
1994: &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1995: &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1996: '" />'."\n".
1997: '<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1998: $cts++;
1999: }
2000: $request->print($prnmsg);
2001:
2002: # if ($env{'form.handgrade'} eq 'yes') {
2003: if (1) {
2004: #
2005: # Print out the keyword options line
2006: #
2007: $request->print(<<KEYWORDS);
2008: <b>Keyword Options:</b>
2009: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>
2010: <a href="#" onmousedown="javascript:getSel(); return false"
2011: CLASS="page">Paste Selection to List</a>
2012: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
2013: KEYWORDS
2014: #
2015: # Load the other essays for similarity check
2016: #
2017: my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
2018: my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
2019: $apath=&escape($apath);
2020: $apath=~s/\W/\_/gs;
2021: %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
2022: }
2023: }
2024:
2025: # This is where output for one specific student would start
2026: my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
2027: $request->print(
2028: "\n\n"
2029: .'<div class="LC_grade_show_user'.$add_class.'">'
2030: .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
2031: ."\n"
2032: );
2033:
2034: # Show additional functions if allowed
2035: if ($perm{'vgr'}) {
2036: $request->print(
2037: &Apache::loncommon::track_student_link(
2038: &mt('View recent activity'),
2039: $uname,$udom,'check')
2040: .' '
2041: );
2042: }
2043: if ($perm{'opa'}) {
2044: $request->print(
2045: &Apache::loncommon::pprmlink(
2046: &mt('Set/Change parameters'),
2047: $uname,$udom,$symb,'check'));
2048: }
2049:
2050: # Show Problem
2051: if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
2052: my $mode;
2053: if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
2054: $mode='both';
2055: } elsif ($env{'form.vProb'} eq 'all' ) {
2056: $mode='text';
2057: } elsif ($env{'form.vAns'} eq 'all') {
2058: $mode='answer';
2059: }
2060: &Apache::lonxml::clear_problem_counter();
2061: $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
2062: }
2063:
2064: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
2065: my $res_error;
2066: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
2067: if ($res_error) {
2068: $request->print(&navmap_errormsg());
2069: return;
2070: }
2071:
2072: # Display student info
2073: $request->print(($counter == 0 ? '' : '<br />'));
2074:
2075: my $result='<div class="LC_Box">'
2076: .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
2077: $result.='<input type="hidden" name="name'.$counter.
2078: '" value="'.$env{'form.fullname'}.'" />'."\n";
2079: # if ($env{'form.handgrade'} eq 'no') {
2080: if (1) {
2081: $result.='<p class="LC_info">'
2082: .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
2083: ."</p>\n";
2084: }
2085:
2086: # If any part of the problem is an essay-response (handgraded), then check for collaborators
2087: my $fullname;
2088: my $col_fullnames = [];
2089: # if ($env{'form.handgrade'} eq 'yes') {
2090: if (1) {
2091: (my $sub_result,$fullname,$col_fullnames)=
2092: &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
2093: $counter);
2094: $result.=$sub_result;
2095: }
2096: $request->print($result."\n");
2097:
2098: # print student answer/submission
2099: # Options are (1) Handgraded submission only
2100: # (2) Last submission, includes submission that is not handgraded
2101: # (for multi-response type part)
2102: # (3) Last submission plus the parts info
2103: # (4) The whole record for this student
2104: if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
2105: my ($string,$timestamp)= &get_last_submission(\%record);
2106:
2107: my $lastsubonly;
2108:
2109: if ($$timestamp eq '') {
2110: $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>';
2111: } else {
2112: $lastsubonly =
2113: '<div class="LC_grade_submissions_body">'
2114: .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
2115:
2116: my %seenparts;
2117: my @part_response_id = &flatten_responseType($responseType);
2118: foreach my $part (@part_response_id) {
2119: next if ($env{'form.lastSub'} eq 'hdgrade'
2120: && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
2121:
2122: my ($partid,$respid) = @{ $part };
2123: my $display_part=&get_display_part($partid,$symb);
2124: if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
2125: if (exists($seenparts{$partid})) { next; }
2126: $seenparts{$partid}=1;
2127: my $submitby='<b>Part:</b> '.$display_part.
2128: ' <b>Collaborative submission by:</b> '.
2129: '<a href="javascript:viewSubmitter(\''.
2130: $env{"form.$uname:$udom:$partid:submitted_by"}.
2131: '\');" target="_self">'.
2132: $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
2133: $request->print($submitby);
2134: next;
2135: }
2136: my $responsetype = $responseType->{$partid}->{$respid};
2137: if (!exists($record{"resource.$partid.$respid.submission"})) {
2138: $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
2139: '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
2140: ' <span class="LC_internal_info">'.
2141: '('.&mt('Response ID: [_1]',$respid).')'.
2142: '</span> '.
2143: '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
2144: next;
2145: }
2146: foreach my $submission (@$string) {
2147: my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
2148: if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
2149: my ($ressub,$hide,$subval) = split(/:/,$submission,3);
2150: # Similarity check
2151: my $similar='';
2152: my ($type,$trial,$rndseed);
2153: if ($hide eq 'rand') {
2154: $type = 'randomizetry';
2155: $trial = $record{"resource.$partid.tries"};
2156: $rndseed = $record{"resource.$partid.rndseed"};
2157: }
2158: if($env{'form.checkPlag'}){
2159: my ($oname,$odom,$ocrsid,$oessay,$osim)=
2160: &most_similar($uname,$udom,$subval,\%old_essays);
2161: if ($osim) {
2162: $osim=int($osim*100.0);
2163: my %old_course_desc =
2164: &Apache::lonnet::coursedescription($ocrsid,
2165: {'one_time' => 1});
2166:
2167: if ($hide eq 'anon') {
2168: $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
2169: &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
2170: } else {
2171: $similar="<hr /><h3><span class=\"LC_warning\">".
2172: &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
2173: $osim,
2174: &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
2175: $old_course_desc{'description'},
2176: $old_course_desc{'num'},
2177: $old_course_desc{'domain'}).
2178: '</span></h3><blockquote><i>'.
2179: &keywords_highlight($oessay).
2180: '</i></blockquote><hr />';
2181: }
2182: }
2183: }
2184: my $order=&get_order($partid,$respid,$symb,$uname,$udom,
2185: undef,$type,$trial,$rndseed);
2186: if ($env{'form.lastSub'} eq 'lastonly' ||
2187: ($env{'form.lastSub'} eq 'hdgrade' &&
2188: $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
2189: my $display_part=&get_display_part($partid,$symb);
2190: $lastsubonly.='<div class="LC_grade_submission_part">'.
2191: '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
2192: ' <span class="LC_internal_info">'.
2193: '('.&mt('Response ID: [_1]',$respid).')'.
2194: '</span> ';
2195: my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
2196: if (@$files) {
2197: if ($hide eq 'anon') {
2198: $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
2199: } else {
2200: $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
2201: foreach my $file (@$files) {
2202: &Apache::lonnet::allowuploaded('/adm/grades',$file);
2203: $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
2204: }
2205: }
2206: $lastsubonly.='<br />';
2207: }
2208: if ($hide eq 'anon') {
2209: $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>';
2210: } else {
2211: $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
2212: &cleanRecord($subval,$responsetype,$symb,$partid,
2213: $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
2214: }
2215: if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
2216: $lastsubonly.='</div>';
2217: }
2218: }
2219: }
2220: $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
2221: }
2222: $request->print($lastsubonly);
2223: } elsif ($env{'form.lastSub'} eq 'datesub') {
2224: my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
2225: $request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
2226: } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
2227: $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
2228: $env{'request.course.id'},
2229: $last,'.submission',
2230: 'Apache::grades::keywords_highlight'));
2231: }
2232: $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
2233: .$udom.'" />'."\n");
2234: # return if view submission with no grading option
2235: if (!&canmodify($usec)) {
2236: $request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
2237: return;
2238: } else {
2239: $request->print('</div>'."\n");
2240: }
2241:
2242: # essay grading message center
2243: # if ($env{'form.handgrade'} eq 'yes') {
2244: if (1) {
2245: my $result='<div class="LC_grade_message_center">';
2246:
2247: $result.='<div class="LC_grade_message_center_header">'.
2248: &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
2249: my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
2250: my $msgfor = $givenn.' '.$lastname;
2251: if (scalar(@$col_fullnames) > 0) {
2252: my $lastone = pop(@$col_fullnames);
2253: $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
2254: }
2255: $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
2256: $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
2257: '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
2258: $result.=' <a href="javascript:msgCenter(document.SCORE,'.$counter.
2259: ',\''.$msgfor.'\');" target="_self">'.
2260: &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
2261: &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
2262: '<img src="'.$request->dir_config('lonIconsURL').
2263: '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
2264: '<br /> ('.
2265: &mt('Message will be sent when you click on Save & Next below.').")\n";
2266: $result.='</div></div>';
2267: $request->print($result);
2268: }
2269:
2270: my %seen = ();
2271: my @partlist;
2272: my @gradePartRespid;
2273: my @part_response_id = &flatten_responseType($responseType);
2274: $request->print(
2275: '<div class="LC_Box">'
2276: .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
2277: );
2278: $request->print(&gradeBox_start());
2279: foreach my $part_response_id (@part_response_id) {
2280: my ($partid,$respid) = @{ $part_response_id };
2281: my $part_resp = join('_',@{ $part_response_id });
2282: next if ($seen{$partid} > 0);
2283: $seen{$partid}++;
2284: next if ($$handgrade{$part_resp} ne 'yes'
2285: && $env{'form.lastSub'} eq 'hdgrade');
2286: push(@partlist,$partid);
2287: push(@gradePartRespid,$partid.'.'.$respid);
2288: $request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
2289: }
2290: $request->print(&gradeBox_end()); # </div>
2291: $request->print('</div>');
2292:
2293: $request->print('<div class="LC_grade_info_links">');
2294: $request->print('</div>');
2295:
2296: $result='<input type="hidden" name="partlist'.$counter.
2297: '" value="'.(join ":",@partlist).'" />'."\n";
2298: $result.='<input type="hidden" name="gradePartRespid'.
2299: '" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
2300: my $ctr = 0;
2301: while ($ctr < scalar(@partlist)) {
2302: $result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
2303: $partlist[$ctr].'" />'."\n";
2304: $ctr++;
2305: }
2306: $request->print($result.''."\n");
2307:
2308: # Done with printing info for one student
2309:
2310: $request->print('</div>');#LC_grade_show_user
2311:
2312:
2313: # print end of form
2314: if ($counter == $total) {
2315: my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
2316: $endform.='<input type="button" value="'.&mt('Save & Next').'" '.
2317: 'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
2318: $total.','.scalar(@partlist).');" target="_self" /> '."\n";
2319: my $ntstu ='<select name="NTSTU">'.
2320: '<option>1</option><option>2</option>'.
2321: '<option>3</option><option>5</option>'.
2322: '<option>7</option><option>10</option></select>'."\n";
2323: my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
2324: $ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
2325: $endform.=&mt('[_1]student(s)',$ntstu);
2326: $endform.=' <input type="button" value="'.&mt('Previous').'" '.
2327: 'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> '."\n".
2328: '<input type="button" value="'.&mt('Next').'" '.
2329: 'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> ';
2330: $endform.='<span class="LC_warning">'.
2331: &mt('(Next and Previous (student) do not save the scores.)').
2332: '</span>'."\n" ;
2333: $endform.="<input type='hidden' value='".&get_increment().
2334: "' name='increment' />";
2335: $endform.='</td></tr></table></form>';
2336: $request->print($endform);
2337: }
2338: return '';
2339: }
2340:
2341: sub check_collaborators {
2342: my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
2343: my ($result,@col_fullnames);
2344: my ($classlist,undef,$fullname) = &getclasslist('all','0');
2345: foreach my $part (keys(%$handgrade)) {
2346: my $ncol = &Apache::lonnet::EXT('resource.'.$part.
2347: '.maxcollaborators',
2348: $symb,$udom,$uname);
2349: next if ($ncol <= 0);
2350: $part =~ s/\_/\./g;
2351: next if ($record->{'resource.'.$part.'.collaborators'} eq '');
2352: my (@good_collaborators, @bad_collaborators);
2353: foreach my $possible_collaborator
2354: (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) {
2355: $possible_collaborator =~ s/[\$\^\(\)]//g;
2356: next if ($possible_collaborator eq '');
2357: my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
2358: $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
2359: next if ($co_name eq $uname && $co_dom eq $udom);
2360: # Doing this grep allows 'fuzzy' specification
2361: my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i,
2362: keys(%$classlist));
2363: if (! scalar(@matches)) {
2364: push(@bad_collaborators, $possible_collaborator);
2365: } else {
2366: push(@good_collaborators, @matches);
2367: }
2368: }
2369: if (scalar(@good_collaborators) != 0) {
2370: $result.='<br />'.&mt('Collaborators:').'<ol>';
2371: foreach my $name (@good_collaborators) {
2372: my ($lastname,$givenn) = split(/,/,$$fullname{$name});
2373: push(@col_fullnames, $givenn.' '.$lastname);
2374: $result.='<li>'.$fullname->{$name}.'</li>';
2375: }
2376: $result.='</ol><br />'."\n";
2377: my ($part)=split(/\./,$part);
2378: $result.='<input type="hidden" name="collaborator'.$counter.
2379: '" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
2380: "\n";
2381: }
2382: if (scalar(@bad_collaborators) > 0) {
2383: $result.='<div class="LC_warning">';
2384: $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
2385: $result .= '</div>';
2386: }
2387: if (scalar(@bad_collaborators > $ncol)) {
2388: $result .= '<div class="LC_warning">';
2389: $result .= &mt('This student has submitted too many '.
2390: 'collaborators. Maximum is [_1].',$ncol);
2391: $result .= '</div>';
2392: }
2393: }
2394: return ($result,$fullname,\@col_fullnames);
2395: }
2396:
2397: #--- Retrieve the last submission for all the parts
2398: sub get_last_submission {
2399: my ($returnhash)=@_;
2400: my (@string,$timestamp,%lasthidden);
2401: if ($$returnhash{'version'}) {
2402: my %lasthash=();
2403: my ($version);
2404: for ($version=1;$version<=$$returnhash{'version'};$version++) {
2405: foreach my $key (sort(split(/\:/,
2406: $$returnhash{$version.':keys'}))) {
2407: $lasthash{$key}=$$returnhash{$version.':'.$key};
2408: $timestamp =
2409: &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
2410: }
2411: }
2412: my (%typeparts,%randombytry);
2413: my $showsurv =
2414: &Apache::lonnet::allowed('vas',$env{'request.course.id'});
2415: foreach my $key (sort(keys(%lasthash))) {
2416: if ($key =~ /\.type$/) {
2417: if (($lasthash{$key} eq 'anonsurvey') ||
2418: ($lasthash{$key} eq 'anonsurveycred') ||
2419: ($lasthash{$key} eq 'randomizetry')) {
2420: my ($ign,@parts) = split(/\./,$key);
2421: pop(@parts);
2422: my $id = join('.',@parts);
2423: if ($lasthash{$key} eq 'randomizetry') {
2424: $randombytry{$ign.'.'.$id} = $lasthash{$key};
2425: } else {
2426: unless ($showsurv) {
2427: $typeparts{$ign.'.'.$id} = $lasthash{$key};
2428: }
2429: }
2430: delete($lasthash{$key});
2431: }
2432: }
2433: }
2434: my @hidden = keys(%typeparts);
2435: my @randomize = keys(%randombytry);
2436: foreach my $key (keys(%lasthash)) {
2437: next if ($key !~ /\.submission$/);
2438: my $hide;
2439: if (@hidden) {
2440: foreach my $id (@hidden) {
2441: if ($key =~ /^\Q$id\E/) {
2442: $hide = 'anon';
2443: last;
2444: }
2445: }
2446: }
2447: unless ($hide) {
2448: if (@randomize) {
2449: foreach my $id (@hidden) {
2450: if ($key =~ /^\Q$id\E/) {
2451: $hide = 'rand';
2452: last;
2453: }
2454: }
2455: }
2456: }
2457: my ($partid,$foo) = split(/submission$/,$key);
2458: my $draft = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
2459: '<span class="LC_warning">Draft Copy</span> ' : '';
2460: push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
2461: }
2462: }
2463: if (!@string) {
2464: $string[0] =
2465: '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
2466: }
2467: return (\@string,\$timestamp);
2468: }
2469:
2470: #--- High light keywords, with style choosen by user.
2471: sub keywords_highlight {
2472: my $string = shift;
2473: my $size = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
2474: my $styleon = $env{'form.kwstyle'} eq '' ? '' : $env{'form.kwstyle'};
2475: (my $styleoff = $styleon) =~ s/\</\<\//;
2476: my @keylist = split(/[,\s+]/,$env{'form.keywords'});
2477: foreach my $keyword (@keylist) {
2478: $string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
2479: }
2480: return $string;
2481: }
2482:
2483: #--- Called from submission routine
2484: sub processHandGrade {
2485: my ($request,$symb) = @_;
2486: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
2487: my $button = $env{'form.gradeOpt'};
2488: my $ngrade = $env{'form.NCT'};
2489: my $ntstu = $env{'form.NTSTU'};
2490: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2491: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2492:
2493: if ($button eq 'Save & Next') {
2494: my $ctr = 0;
2495: while ($ctr < $ngrade) {
2496: my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
2497: my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
2498: if ($errorflag eq 'no_score') {
2499: $ctr++;
2500: next;
2501: }
2502: if ($errorflag eq 'not_allowed') {
2503: $request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
2504: $ctr++;
2505: next;
2506: }
2507: my $includemsg = $env{'form.includemsg'.$ctr};
2508: my ($subject,$message,$msgstatus) = ('','','');
2509: my $restitle = &Apache::lonnet::gettitle($symb);
2510: my ($feedurl,$showsymb) =
2511: &get_feedurl_and_symb($symb,$uname,$udom);
2512: my $messagetail;
2513: if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
2514: $subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
2515: unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
2516: $subject.=' ['.$restitle.']';
2517: my (@msgnum) = split(/,/,$includemsg);
2518: foreach (@msgnum) {
2519: $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
2520: }
2521: $message =&Apache::lonfeedback::clear_out_html($message);
2522: if ($env{'form.withgrades'.$ctr}) {
2523: $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
2524: $messagetail = " for <a href=\"".
2525: $feedurl."?symb=$showsymb\">$restitle</a>";
2526: }
2527: $msgstatus =
2528: &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
2529: $message.$messagetail,
2530: undef,$feedurl,undef,
2531: undef,undef,$showsymb,
2532: $restitle);
2533: $request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
2534: $msgstatus);
2535: }
2536: if ($env{'form.collaborator'.$ctr}) {
2537: my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
2538: foreach my $collabstr (@collabstrs) {
2539: my ($part,@collaborators) = split(/:/,$collabstr);
2540: foreach my $collaborator (@collaborators) {
2541: my ($errorflag,$pts,$wgt) =
2542: &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
2543: $env{'form.unamedom'.$ctr},$part);
2544: if ($errorflag eq 'not_allowed') {
2545: $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
2546: next;
2547: } elsif ($message ne '') {
2548: my ($baseurl,$showsymb) =
2549: &get_feedurl_and_symb($symb,$collaborator,
2550: $udom);
2551: if ($env{'form.withgrades'.$ctr}) {
2552: $messagetail = " for <a href=\"".
2553: $baseurl."?symb=$showsymb\">$restitle</a>";
2554: }
2555: $msgstatus =
2556: &Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
2557: }
2558: }
2559: }
2560: }
2561: $ctr++;
2562: }
2563: }
2564:
2565: # if ($env{'form.handgrade'} eq 'yes') {
2566: if (1) {
2567: # Keywords sorted in alphabatical order
2568: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
2569: my %keyhash = ();
2570: $env{'form.keywords'} =~ s/,\s{0,}|\s+/ /g;
2571: $env{'form.keywords'} =~ s/^\s+|\s+$//;
2572: my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
2573: $env{'form.keywords'} = join(' ',@keywords);
2574: $keyhash{$symb.'_keywords'} = $env{'form.keywords'};
2575: $keyhash{$symb.'_subject'} = $env{'form.msgsub'};
2576: $keyhash{$loginuser.'_kwclr'} = $env{'form.kwclr'};
2577: $keyhash{$loginuser.'_kwsize'} = $env{'form.kwsize'};
2578: $keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
2579:
2580: # message center - Order of message gets changed. Blank line is eliminated.
2581: # New messages are saved in env for the next student.
2582: # All messages are saved in nohist_handgrade.db
2583: my ($ctr,$idx) = (1,1);
2584: while ($ctr <= $env{'form.savemsgN'}) {
2585: if ($env{'form.savemsg'.$ctr} ne '') {
2586: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
2587: $idx++;
2588: }
2589: $ctr++;
2590: }
2591: $ctr = 0;
2592: while ($ctr < $ngrade) {
2593: if ($env{'form.newmsg'.$ctr} ne '') {
2594: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2595: $env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2596: $idx++;
2597: }
2598: $ctr++;
2599: }
2600: $env{'form.savemsgN'} = --$idx;
2601: $keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
2602: my $putresult = &Apache::lonnet::put
2603: ('nohist_handgrade',\%keyhash,$cdom,$cnum);
2604: }
2605: # Called by Save & Refresh from Highlight Attribute Window
2606: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
2607: if ($env{'form.refresh'} eq 'on') {
2608: my ($ctr,$total) = (0,0);
2609: while ($ctr < $ngrade) {
2610: $total++ if $env{'form.unamedom'.$ctr} ne '';
2611: $ctr++;
2612: }
2613: $env{'form.NTSTU'}=$ngrade;
2614: $ctr = 0;
2615: while ($ctr < $total) {
2616: my $processUser = $env{'form.unamedom'.$ctr};
2617: ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
2618: $env{'form.fullname'} = $$fullname{$processUser};
2619: &submission($request,$ctr,$total-1,$symb);
2620: $ctr++;
2621: }
2622: return '';
2623: }
2624:
2625: # Get the next/previous one or group of students
2626: my $firststu = $env{'form.unamedom0'};
2627: my $laststu = $env{'form.unamedom'.($ngrade-1)};
2628: my $ctr = 2;
2629: while ($laststu eq '') {
2630: $laststu = $env{'form.unamedom'.($ngrade-$ctr)};
2631: $ctr++;
2632: $laststu = $firststu if ($ctr > $ngrade);
2633: }
2634:
2635: my (@parsedlist,@nextlist);
2636: my ($nextflg) = 0;
2637: foreach my $item (sort
2638: {
2639: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
2640: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
2641: }
2642: return $a cmp $b;
2643: } (keys(%$fullname))) {
2644: # FIXME: this is fishy, looks like the button label
2645: if ($nextflg == 1 && $button =~ /Next$/) {
2646: push(@parsedlist,$item);
2647: }
2648: $nextflg = 1 if ($item eq $laststu);
2649: if ($button eq 'Previous') {
2650: last if ($item eq $firststu);
2651: push(@parsedlist,$item);
2652: }
2653: }
2654: $ctr = 0;
2655: # FIXME: this is fishy, looks like the button label
2656: @parsedlist = reverse @parsedlist if ($button eq 'Previous');
2657: my $res_error;
2658: my ($partlist) = &response_type($symb,\$res_error);
2659: if ($res_error) {
2660: $request->print(&navmap_errormsg());
2661: return;
2662: }
2663: foreach my $student (@parsedlist) {
2664: my $submitonly=$env{'form.submitonly'};
2665: my ($uname,$udom) = split(/:/,$student);
2666:
2667: if ($submitonly eq 'queued') {
2668: my %queue_status =
2669: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
2670: $udom,$uname);
2671: next if (!defined($queue_status{'gradingqueue'}));
2672: }
2673:
2674: if ($submitonly =~ /^(yes|graded|incorrect)$/) {
2675: # my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
2676: my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
2677: my $submitted = 0;
2678: my $ungraded = 0;
2679: my $incorrect = 0;
2680: foreach my $item (keys(%status)) {
2681: $submitted = 1 if ($status{$item} ne 'nothing');
2682: $ungraded = 1 if ($status{$item} =~ /^ungraded/);
2683: $incorrect = 1 if ($status{$item} =~ /^incorrect/);
2684: my ($foo,$partid,$foo1) = split(/\./,$item);
2685: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
2686: $submitted = 0;
2687: }
2688: }
2689: next if (!$submitted && ($submitonly eq 'yes' ||
2690: $submitonly eq 'incorrect' ||
2691: $submitonly eq 'graded'));
2692: next if (!$ungraded && ($submitonly eq 'graded'));
2693: next if (!$incorrect && $submitonly eq 'incorrect');
2694: }
2695: push(@nextlist,$student) if ($ctr < $ntstu);
2696: last if ($ctr == $ntstu);
2697: $ctr++;
2698: }
2699:
2700: $ctr = 0;
2701: my $total = scalar(@nextlist)-1;
2702:
2703: foreach (sort(@nextlist)) {
2704: my ($uname,$udom,$submitter) = split(/:/);
2705: $env{'form.student'} = $uname;
2706: $env{'form.userdom'} = $udom;
2707: $env{'form.fullname'} = $$fullname{$_};
2708: &submission($request,$ctr,$total,$symb);
2709: $ctr++;
2710: }
2711: if ($total < 0) {
2712: my $the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
2713: $request->print($the_end);
2714: }
2715: return '';
2716: }
2717:
2718: #---- Save the score and award for each student, if changed
2719: sub saveHandGrade {
2720: my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
2721: my @version_parts;
2722: my $usec = &Apache::lonnet::getsection($domain,$stuname,
2723: $env{'request.course.id'});
2724: if (!&canmodify($usec)) { return('not_allowed'); }
2725: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
2726: my @parts_graded;
2727: my %newrecord = ();
2728: my ($pts,$wgt) = ('','');
2729: my %aggregate = ();
2730: my $aggregateflag = 0;
2731: my @parts = split(/:/,$env{'form.partlist'.$newflg});
2732: foreach my $new_part (@parts) {
2733: #collaborator ($submi may vary for different parts
2734: if ($submitter && $new_part ne $part) { next; }
2735: my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
2736: if ($dropMenu eq 'excused') {
2737: if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
2738: $newrecord{'resource.'.$new_part.'.solved'} = 'excused';
2739: if (exists($record{'resource.'.$new_part.'.awarded'})) {
2740: $newrecord{'resource.'.$new_part.'.awarded'} = '';
2741: }
2742: $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
2743: }
2744: } elsif ($dropMenu eq 'reset status'
2745: && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
2746: foreach my $key (keys(%record)) {
2747: if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
2748: }
2749: $newrecord{'resource.'.$new_part.'.regrader'}=
2750: "$env{'user.name'}:$env{'user.domain'}";
2751: my $totaltries = $record{'resource.'.$part.'.tries'};
2752:
2753: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
2754: [$new_part]);
2755: my $aggtries =$totaltries;
2756: if ($last_resets{$new_part}) {
2757: $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
2758: $new_part);
2759: }
2760:
2761: my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
2762: if ($aggtries > 0) {
2763: &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
2764: $aggregateflag = 1;
2765: }
2766: } elsif ($dropMenu eq '') {
2767: $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ?
2768: $env{'form.GD_BOX'.$newflg.'_'.$new_part} :
2769: $env{'form.RADVAL'.$newflg.'_'.$new_part});
2770: if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
2771: next;
2772: }
2773: $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 :
2774: $env{'form.WGT'.$newflg.'_'.$new_part};
2775: my $partial= $pts/$wgt;
2776: if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
2777: #do not update score for part if not changed.
2778: &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
2779: next;
2780: } else {
2781: push(@parts_graded,$new_part);
2782: }
2783: if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
2784: $newrecord{'resource.'.$new_part.'.awarded'} = $partial;
2785: }
2786: my $reckey = 'resource.'.$new_part.'.solved';
2787: if ($partial == 0) {
2788: if ($record{$reckey} ne 'incorrect_by_override') {
2789: $newrecord{$reckey} = 'incorrect_by_override';
2790: }
2791: } else {
2792: if ($record{$reckey} ne 'correct_by_override') {
2793: $newrecord{$reckey} = 'correct_by_override';
2794: }
2795: }
2796: if ($submitter &&
2797: ($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
2798: $newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
2799: }
2800: $newrecord{'resource.'.$new_part.'.regrader'}=
2801: "$env{'user.name'}:$env{'user.domain'}";
2802: }
2803: # unless problem has been graded, set flag to version the submitted files
2804: unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/ ||
2805: $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
2806: $dropMenu eq 'reset status')
2807: {
2808: push(@version_parts,$new_part);
2809: }
2810: }
2811: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2812: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2813:
2814: if (%newrecord) {
2815: if (@version_parts) {
2816: my @changed_keys = &version_portfiles(\%record, \@parts_graded,
2817: $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
2818: @newrecord{@changed_keys} = @record{@changed_keys};
2819: foreach my $new_part (@version_parts) {
2820: &handback_files($request,$symb,$stuname,$domain,$newflg,
2821: $new_part,\%newrecord);
2822: }
2823: }
2824: &Apache::lonnet::cstore(\%newrecord,$symb,
2825: $env{'request.course.id'},$domain,$stuname);
2826: &check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
2827: $cdom,$cnum,$domain,$stuname);
2828: }
2829: if ($aggregateflag) {
2830: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
2831: $cdom,$cnum);
2832: }
2833: return ('',$pts,$wgt);
2834: }
2835:
2836: sub check_and_remove_from_queue {
2837: my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
2838: my @ungraded_parts;
2839: foreach my $part (@{$parts}) {
2840: if ( $record->{ 'resource.'.$part.'.awarded'} eq ''
2841: && $record->{ 'resource.'.$part.'.solved' } ne 'excused'
2842: && $newrecord->{'resource.'.$part.'.awarded'} eq ''
2843: && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
2844: ) {
2845: push(@ungraded_parts, $part);
2846: }
2847: }
2848: if ( !@ungraded_parts ) {
2849: &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
2850: $cnum,$domain,$stuname);
2851: }
2852: }
2853:
2854: sub handback_files {
2855: my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
2856: my $portfolio_root = '/userfiles/portfolio';
2857: my $res_error;
2858: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
2859: if ($res_error) {
2860: $request->print('<br />'.&navmap_errormsg().'<br />');
2861: return;
2862: }
2863: my @part_response_id = &flatten_responseType($responseType);
2864: foreach my $part_response_id (@part_response_id) {
2865: my ($part_id,$resp_id) = @{ $part_response_id };
2866: my $part_resp = join('_',@{ $part_response_id });
2867: if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
2868: # if multiple files are uploaded names will be 'returndoc2','returndoc3'
2869: my $file_counter = 1;
2870: my $file_msg;
2871: while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
2872: my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
2873: my ($directory,$answer_file) =
2874: ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
2875: my ($answer_name,$answer_ver,$answer_ext) =
2876: &file_name_version_ext($answer_file);
2877: my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
2878: my $getpropath = 1;
2879: my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
2880: my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
2881: # fix file name
2882: my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
2883: my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
2884: $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
2885: $save_file_name);
2886: if ($result !~ m|^/uploaded/|) {
2887: $request->print('<br /><span class="LC_error">'.
2888: &mt('An error occurred ([_1]) while trying to upload [_2].',
2889: $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
2890: '</span>');
2891: } else {
2892: # mark the file as read only
2893: my @files = ($save_file_name);
2894: my @what = ($symb,$env{'request.course.id'},'handback');
2895: &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
2896: if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
2897: $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
2898: }
2899: $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
2900: $file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
2901:
2902: }
2903: $request->print("<br />".$fname." will be the uploaded file name");
2904: $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
2905: $file_counter++;
2906: }
2907: my $subject = "File Handed Back by Instructor ";
2908: my $message = "A file has been returned that was originally submitted in reponse to: <br />";
2909: $message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
2910: $message .= ' The returned file(s) are named: '. $file_msg;
2911: $message .= " and can be found in your portfolio space.";
2912: my ($feedurl,$showsymb) =
2913: &get_feedurl_and_symb($symb,$domain,$stuname);
2914: my $restitle = &Apache::lonnet::gettitle($symb);
2915: my $msgstatus =
2916: &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
2917: ' (File Returned) ['.$restitle.']',$message,undef,
2918: $feedurl,undef,undef,undef,$showsymb,$restitle);
2919: }
2920: }
2921: return;
2922: }
2923:
2924: sub get_feedurl_and_symb {
2925: my ($symb,$uname,$udom) = @_;
2926: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
2927: $url = &Apache::lonnet::clutter($url);
2928: my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
2929: $symb,$udom,$uname);
2930: if ($encrypturl =~ /^yes$/i) {
2931: &Apache::lonenc::encrypted(\$url,1);
2932: &Apache::lonenc::encrypted(\$symb,1);
2933: }
2934: return ($url,$symb);
2935: }
2936:
2937: sub get_submitted_files {
2938: my ($udom,$uname,$partid,$respid,$record) = @_;
2939: my @files;
2940: if ($$record{"resource.$partid.$respid.portfiles"}) {
2941: my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
2942: foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
2943: push(@files,$file_url.$file);
2944: }
2945: }
2946: if ($$record{"resource.$partid.$respid.uploadedurl"}) {
2947: push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
2948: }
2949: return (\@files);
2950: }
2951:
2952: # ----------- Provides number of tries since last reset.
2953: sub get_num_tries {
2954: my ($record,$last_reset,$part) = @_;
2955: my $timestamp = '';
2956: my $num_tries = 0;
2957: if ($$record{'version'}) {
2958: for (my $version=$$record{'version'};$version>=1;$version--) {
2959: if (exists($$record{$version.':resource.'.$part.'.solved'})) {
2960: $timestamp = $$record{$version.':timestamp'};
2961: if ($timestamp > $last_reset) {
2962: $num_tries ++;
2963: } else {
2964: last;
2965: }
2966: }
2967: }
2968: }
2969: return $num_tries;
2970: }
2971:
2972: # ----------- Determine decrements required in aggregate totals
2973: sub decrement_aggs {
2974: my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
2975: my %decrement = (
2976: attempts => 0,
2977: users => 0,
2978: correct => 0
2979: );
2980: $decrement{'attempts'} = $aggtries;
2981: if ($solvedstatus =~ /^correct/) {
2982: $decrement{'correct'} = 1;
2983: }
2984: if ($aggtries == $totaltries) {
2985: $decrement{'users'} = 1;
2986: }
2987: foreach my $type (keys(%decrement)) {
2988: $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
2989: }
2990: return;
2991: }
2992:
2993: # ----------- Determine timestamps for last reset of aggregate totals for parts
2994: sub get_last_resets {
2995: my ($symb,$courseid,$partids) =@_;
2996: my %last_resets;
2997: my $cdom = $env{'course.'.$courseid.'.domain'};
2998: my $cname = $env{'course.'.$courseid.'.num'};
2999: my @keys;
3000: foreach my $part (@{$partids}) {
3001: push(@keys,"$symb\0$part\0resettime");
3002: }
3003: my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
3004: $cdom,$cname);
3005: foreach my $part (@{$partids}) {
3006: $last_resets{$part}=$results{"$symb\0$part\0resettime"};
3007: }
3008: return %last_resets;
3009: }
3010:
3011: # ----------- Handles creating versions for portfolio files as answers
3012: sub version_portfiles {
3013: my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
3014: my $version_parts = join('|',@$v_flag);
3015: my @returned_keys;
3016: my $parts = join('|', @$parts_graded);
3017: my $portfolio_root = '/userfiles/portfolio';
3018: foreach my $key (keys(%$record)) {
3019: my $new_portfiles;
3020: if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
3021: my @versioned_portfiles;
3022: my @portfiles = split(/\s*,\s*/,$$record{$key});
3023: foreach my $file (@portfiles) {
3024: &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
3025: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
3026: my ($answer_name,$answer_ver,$answer_ext) =
3027: &file_name_version_ext($answer_file);
3028: my $getpropath = 1;
3029: my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
3030: my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
3031: my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
3032: if ($new_answer ne 'problem getting file') {
3033: push(@versioned_portfiles, $directory.$new_answer);
3034: &Apache::lonnet::mark_as_readonly($domain,$stu_name,
3035: [$directory.$new_answer],
3036: [$symb,$env{'request.course.id'},'graded']);
3037: }
3038: }
3039: $$record{$key} = join(',',@versioned_portfiles);
3040: push(@returned_keys,$key);
3041: }
3042: }
3043: return (@returned_keys);
3044: }
3045:
3046: sub get_next_version {
3047: my ($answer_name, $answer_ext, $dir_list) = @_;
3048: my $version;
3049: foreach my $row (@$dir_list) {
3050: my ($file) = split(/\&/,$row,2);
3051: my ($file_name,$file_version,$file_ext) =
3052: &file_name_version_ext($file);
3053: if (($file_name eq $answer_name) &&
3054: ($file_ext eq $answer_ext)) {
3055: # gets here if filename and extension match, regardless of version
3056: if ($file_version ne '') {
3057: # a versioned file is found so save it for later
3058: if ($file_version > $version) {
3059: $version = $file_version;
3060: }
3061: }
3062: }
3063: }
3064: $version ++;
3065: return($version);
3066: }
3067:
3068: sub version_selected_portfile {
3069: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
3070: my ($answer_name,$answer_ver,$answer_ext) =
3071: &file_name_version_ext($file_name);
3072: my $new_answer;
3073: $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
3074: if($env{'form.copy'} eq '-1') {
3075: $new_answer = 'problem getting file';
3076: } else {
3077: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
3078: my $copy_result = &Apache::lonnet::finishuserfileupload(
3079: $stu_name,$domain,'copy',
3080: '/portfolio'.$directory.$new_answer);
3081: }
3082: return ($new_answer);
3083: }
3084:
3085: sub file_name_version_ext {
3086: my ($file)=@_;
3087: my @file_parts = split(/\./, $file);
3088: my ($name,$version,$ext);
3089: if (@file_parts > 1) {
3090: $ext=pop(@file_parts);
3091: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
3092: $version=pop(@file_parts);
3093: }
3094: $name=join('.',@file_parts);
3095: } else {
3096: $name=join('.',@file_parts);
3097: }
3098: return($name,$version,$ext);
3099: }
3100:
3101: #--------------------------------------------------------------------------------------
3102: #
3103: #-------------------------- Next few routines handles grading by section or whole class
3104: #
3105: #--- Javascript to handle grading by section or whole class
3106: sub viewgrades_js {
3107: my ($request) = shift;
3108:
3109: my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
3110: $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
3111: function writePoint(partid,weight,point) {
3112: var radioButton = document.classgrade["RADVAL_"+partid];
3113: var textbox = document.classgrade["TEXTVAL_"+partid];
3114: if (point == "textval") {
3115: point = document.classgrade["TEXTVAL_"+partid].value;
3116: if (isNaN(point) || parseFloat(point) < 0) {
3117: alert("$alertmsg"+parseFloat(point));
3118: var resetbox = false;
3119: for (var i=0; i<radioButton.length; i++) {
3120: if (radioButton[i].checked) {
3121: textbox.value = i;
3122: resetbox = true;
3123: }
3124: }
3125: if (!resetbox) {
3126: textbox.value = "";
3127: }
3128: return;
3129: }
3130: if (parseFloat(point) > parseFloat(weight)) {
3131: var resp = confirm("You entered a value ("+parseFloat(point)+
3132: ") greater than the weight for the part. Accept?");
3133: if (resp == false) {
3134: textbox.value = "";
3135: return;
3136: }
3137: }
3138: for (var i=0; i<radioButton.length; i++) {
3139: radioButton[i].checked=false;
3140: if (parseFloat(point) == i) {
3141: radioButton[i].checked=true;
3142: }
3143: }
3144:
3145: } else {
3146: textbox.value = parseFloat(point);
3147: }
3148: for (i=0;i<document.classgrade.total.value;i++) {
3149: var user = document.classgrade["ctr"+i].value;
3150: user = user.replace(new RegExp(':', 'g'),"_");
3151: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3152: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3153: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3154: if (saveval != "correct") {
3155: scorename.value = point;
3156: if (selname[0].selected != true) {
3157: selname[0].selected = true;
3158: }
3159: }
3160: }
3161: document.classgrade["SELVAL_"+partid][0].selected = true;
3162: }
3163:
3164: function writeRadText(partid,weight) {
3165: var selval = document.classgrade["SELVAL_"+partid];
3166: var radioButton = document.classgrade["RADVAL_"+partid];
3167: var override = document.classgrade["FORCE_"+partid].checked;
3168: var textbox = document.classgrade["TEXTVAL_"+partid];
3169: if (selval[1].selected || selval[2].selected) {
3170: for (var i=0; i<radioButton.length; i++) {
3171: radioButton[i].checked=false;
3172:
3173: }
3174: textbox.value = "";
3175:
3176: for (i=0;i<document.classgrade.total.value;i++) {
3177: var user = document.classgrade["ctr"+i].value;
3178: user = user.replace(new RegExp(':', 'g'),"_");
3179: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3180: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3181: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3182: if ((saveval != "correct") || override) {
3183: scorename.value = "";
3184: if (selval[1].selected) {
3185: selname[1].selected = true;
3186: } else {
3187: selname[2].selected = true;
3188: if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value))
3189: {document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
3190: }
3191: }
3192: }
3193: } else {
3194: for (i=0;i<document.classgrade.total.value;i++) {
3195: var user = document.classgrade["ctr"+i].value;
3196: user = user.replace(new RegExp(':', 'g'),"_");
3197: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3198: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3199: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3200: if ((saveval != "correct") || override) {
3201: scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
3202: selname[0].selected = true;
3203: }
3204: }
3205: }
3206: }
3207:
3208: function changeSelect(partid,user) {
3209: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
3210: var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
3211: var point = textbox.value;
3212: var weight = document.classgrade["weight_"+partid].value;
3213:
3214: if (isNaN(point) || parseFloat(point) < 0) {
3215: alert("$alertmsg"+parseFloat(point));
3216: textbox.value = "";
3217: return;
3218: }
3219: if (parseFloat(point) > parseFloat(weight)) {
3220: var resp = confirm("You entered a value ("+parseFloat(point)+
3221: ") greater than the weight of the part. Accept?");
3222: if (resp == false) {
3223: textbox.value = "";
3224: return;
3225: }
3226: }
3227: selval[0].selected = true;
3228: }
3229:
3230: function changeOneScore(partid,user) {
3231: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
3232: if (selval[1].selected || selval[2].selected) {
3233: document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
3234: if (selval[2].selected) {
3235: document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
3236: }
3237: }
3238: }
3239:
3240: function resetEntry(numpart) {
3241: for (ctpart=0;ctpart<numpart;ctpart++) {
3242: var partid = document.classgrade["partid_"+ctpart].value;
3243: var radioButton = document.classgrade["RADVAL_"+partid];
3244: var textbox = document.classgrade["TEXTVAL_"+partid];
3245: var selval = document.classgrade["SELVAL_"+partid];
3246: for (var i=0; i<radioButton.length; i++) {
3247: radioButton[i].checked=false;
3248:
3249: }
3250: textbox.value = "";
3251: selval[0].selected = true;
3252:
3253: for (i=0;i<document.classgrade.total.value;i++) {
3254: var user = document.classgrade["ctr"+i].value;
3255: user = user.replace(new RegExp(':', 'g'),"_");
3256: var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3257: resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
3258: var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
3259: resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
3260: var saveselval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3261: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3262: if (saveselval == "excused") {
3263: if (selname[1].selected == false) { selname[1].selected = true;}
3264: } else {
3265: if (selname[0].selected == false) {selname[0].selected = true};
3266: }
3267: }
3268: }
3269: }
3270:
3271: VIEWJAVASCRIPT
3272: }
3273:
3274: #--- show scores for a section or whole class w/ option to change/update a score
3275: sub viewgrades {
3276: my ($request,$symb) = @_;
3277: &viewgrades_js($request);
3278:
3279: #need to make sure we have the correct data for later EXT calls,
3280: #thus invalidate the cache
3281: &Apache::lonnet::devalidatecourseresdata(
3282: $env{'course.'.$env{'request.course.id'}.'.num'},
3283: $env{'course.'.$env{'request.course.id'}.'.domain'});
3284: &Apache::lonnet::clear_EXT_cache_status();
3285:
3286: my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
3287:
3288: #view individual student submission form - called using Javascript viewOneStudent
3289: $result.=&jscriptNform($symb);
3290:
3291: #beginning of class grading form
3292: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
3293: $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
3294: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
3295: '<input type="hidden" name="command" value="editgrades" />'."\n".
3296: &build_section_inputs().
3297: '<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
3298:
3299: my ($common_header,$specific_header);
3300: if ($env{'form.section'} eq 'all') {
3301: $common_header = &mt('Assign Common Grade to Class');
3302: $specific_header = &mt('Assign Grade to Specific Students in Class');
3303: } elsif ($env{'form.section'} eq 'none') {
3304: $common_header = &mt('Assign Common Grade to Students in no Section');
3305: $specific_header = &mt('Assign Grade to Specific Students in no Section');
3306: } else {
3307: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3308: $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
3309: $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
3310: }
3311: $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
3312: #radio buttons/text box for assigning points for a section or class.
3313: #handles different parts of a problem
3314: my $res_error;
3315: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
3316: if ($res_error) {
3317: return &navmap_errormsg();
3318: }
3319: my %weight = ();
3320: my $ctsparts = 0;
3321: my %seen = ();
3322: my @part_response_id = &flatten_responseType($responseType);
3323: foreach my $part_response_id (@part_response_id) {
3324: my ($partid,$respid) = @{ $part_response_id };
3325: my $part_resp = join('_',@{ $part_response_id });
3326: next if $seen{$partid};
3327: $seen{$partid}++;
3328: my $handgrade=$$handgrade{$part_resp};
3329: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
3330: $weight{$partid} = $wgt eq '' ? '1' : $wgt;
3331:
3332: my $display_part=&get_display_part($partid,$symb);
3333: my $radio.='<table border="0"><tr>';
3334: my $ctr = 0;
3335: while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
3336: $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
3337: 'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
3338: ','.$ctr.')" />'.$ctr."</label></td>\n";
3339: $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
3340: $ctr++;
3341: }
3342: $radio.='</tr></table>';
3343: my $line = '<input type="text" name="TEXTVAL_'.
3344: $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
3345: $partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
3346: $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
3347: $line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
3348: 'onchange="javascript:writeRadText(\''.$partid.'\','.
3349: $weight{$partid}.')"> '.
3350: '<option selected="selected"> </option>'.
3351: '<option value="excused">'.&mt('excused').'</option>'.
3352: '<option value="reset status">'.&mt('reset status').'</option>'.
3353: '</select></td>'.
3354: '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
3355: $line.='<input type="hidden" name="partid_'.
3356: $ctsparts.'" value="'.$partid.'" />'."\n";
3357: $line.='<input type="hidden" name="weight_'.
3358: $partid.'" value="'.$weight{$partid}.'" />'."\n";
3359:
3360: $result.=
3361: &Apache::loncommon::start_data_table_row()."\n".
3362: '<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>'.
3363: &Apache::loncommon::end_data_table_row()."\n";
3364: $ctsparts++;
3365: }
3366: $result.=&Apache::loncommon::end_data_table()."\n".
3367: '<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
3368: $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
3369: 'onclick="javascript:resetEntry('.$ctsparts.');" />';
3370:
3371: #table listing all the students in a section/class
3372: #header of table
3373: $result.= '<h3>'.$specific_header.'</h3>'.
3374: &Apache::loncommon::start_data_table().
3375: &Apache::loncommon::start_data_table_header_row().
3376: '<th>'.&mt('No.').'</th>'.
3377: '<th>'.&nameUserString('header')."</th>\n";
3378: my $partserror;
3379: my (@parts) = sort(&getpartlist($symb,\$partserror));
3380: if ($partserror) {
3381: return &navmap_errormsg();
3382: }
3383: my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
3384: my @partids = ();
3385: foreach my $part (@parts) {
3386: my $display=&Apache::lonnet::metadata($url,$part.'.display');
3387: my $narrowtext = &mt('Tries');
3388: $display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
3389: if (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
3390: my ($partid) = &split_part_type($part);
3391: push(@partids,$partid);
3392: #
3393: # FIXME: Looks like $display looks at English text
3394: #
3395: my $display_part=&get_display_part($partid,$symb);
3396: if ($display =~ /^Partial Credit Factor/) {
3397: $result.='<th>'.
3398: &mt('Score Part: [_1]<br /> (weight = [_2])',
3399: $display_part,$weight{$partid}).'</th>'."\n";
3400: next;
3401:
3402: } else {
3403: if ($display =~ /Problem Status/) {
3404: my $grade_status_mt = &mt('Grade Status');
3405: $display =~ s{Problem Status}{$grade_status_mt<br />};
3406: }
3407: my $part_mt = &mt('Part:');
3408: $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
3409: }
3410:
3411: $result.='<th>'.$display.'</th>'."\n";
3412: }
3413: $result.=&Apache::loncommon::end_data_table_header_row();
3414:
3415: my %last_resets =
3416: &get_last_resets($symb,$env{'request.course.id'},\@partids);
3417:
3418: #get info for each student
3419: #list all the students - with points and grade status
3420: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
3421: my $ctr = 0;
3422: foreach (sort
3423: {
3424: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
3425: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
3426: }
3427: return $a cmp $b;
3428: } (keys(%$fullname))) {
3429: $ctr++;
3430: $result.=&viewstudentgrade($symb,$env{'request.course.id'},
3431: $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
3432: }
3433: $result.=&Apache::loncommon::end_data_table();
3434: $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
3435: $result.='<input type="button" value="'.&mt('Save').'" '.
3436: 'onclick="javascript:submit();" target="_self" /></form>'."\n";
3437: if (scalar(%$fullname) eq 0) {
3438: my $colspan=3+scalar(@parts);
3439: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3440: my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
3441: $result='<span class="LC_warning">'.
3442: &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
3443: $section_display, $stu_status).
3444: '</span>';
3445: }
3446: return $result;
3447: }
3448:
3449: #--- call by previous routine to display each student
3450: sub viewstudentgrade {
3451: my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
3452: my ($uname,$udom) = split(/:/,$student);
3453: my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
3454: my %aggregates = ();
3455: my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
3456: '<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
3457: "\n".$ctr.' </td><td> '.
3458: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
3459: '\');" target="_self">'.$fullname.'</a> '.
3460: '<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
3461: $student=~s/:/_/; # colon doen't work in javascript for names
3462: foreach my $apart (@$parts) {
3463: my ($part,$type) = &split_part_type($apart);
3464: my $score=$record{"resource.$part.$type"};
3465: $result.='<td align="center">';
3466: my ($aggtries,$totaltries);
3467: unless (exists($aggregates{$part})) {
3468: $totaltries = $record{'resource.'.$part.'.tries'};
3469:
3470: $aggtries = $totaltries;
3471: if ($$last_resets{$part}) {
3472: $aggtries = &get_num_tries(\%record,$$last_resets{$part},
3473: $part);
3474: }
3475: $result.='<input type="hidden" name="'.
3476: 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
3477: $result.='<input type="hidden" name="'.
3478: 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
3479: $aggregates{$part} = 1;
3480: }
3481: if ($type eq 'awarded') {
3482: my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
3483: $result.='<input type="hidden" name="'.
3484: 'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
3485: $result.='<input type="text" name="'.
3486: 'GD_'.$student.'_'.$part.'_awarded" '.
3487: 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
3488: '\')" value="'.$pts.'" size="4" /></td>'."\n";
3489: } elsif ($type eq 'solved') {
3490: my ($status,$foo)=split(/_/,$score,2);
3491: $status = 'nothing' if ($status eq '');
3492: $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
3493: $part.'_solved_s" value="'.$status.'" />'."\n";
3494: $result.=' <select name="'.
3495: 'GD_'.$student.'_'.$part.'_solved" '.
3496: 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
3497: $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>'
3498: : '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
3499: $result.='<option value="reset status">'.&mt('reset status').'</option>';
3500: $result.="</select> </td>\n";
3501: } else {
3502: $result.='<input type="hidden" name="'.
3503: 'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
3504: "\n";
3505: $result.='<input type="text" name="'.
3506: 'GD_'.$student.'_'.$part.'_'.$type.'" '.
3507: 'value="'.$score.'" size="4" /></td>'."\n";
3508: }
3509: }
3510: $result.=&Apache::loncommon::end_data_table_row();
3511: return $result;
3512: }
3513:
3514: #--- change scores for all the students in a section/class
3515: # record does not get update if unchanged
3516: sub editgrades {
3517: my ($request,$symb) = @_;
3518:
3519: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3520: my $title='<h2>'.&mt('Current Grade Status').'</h2>';
3521: $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
3522:
3523: my $result= &Apache::loncommon::start_data_table().
3524: &Apache::loncommon::start_data_table_header_row().
3525: '<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
3526: '<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
3527: my %scoreptr = (
3528: 'correct' =>'correct_by_override',
3529: 'incorrect'=>'incorrect_by_override',
3530: 'excused' =>'excused',
3531: 'ungraded' =>'ungraded_attempted',
3532: 'credited' =>'credit_attempted',
3533: 'nothing' => '',
3534: );
3535: my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
3536:
3537: my (@partid);
3538: my %weight = ();
3539: my %columns = ();
3540: my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
3541:
3542: my $partserror;
3543: my (@parts) = sort(&getpartlist($symb,\$partserror));
3544: if ($partserror) {
3545: return &navmap_errormsg();
3546: }
3547: my $header;
3548: while ($ctr < $env{'form.totalparts'}) {
3549: my $partid = $env{'form.partid_'.$ctr};
3550: push(@partid,$partid);
3551: $weight{$partid} = $env{'form.weight_'.$partid};
3552: $ctr++;
3553: }
3554: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3555: foreach my $partid (@partid) {
3556: $header .= '<th align="center">'.&mt('Old Score').'</th>'.
3557: '<th align="center">'.&mt('New Score').'</th>';
3558: $columns{$partid}=2;
3559: foreach my $stores (@parts) {
3560: my ($part,$type) = &split_part_type($stores);
3561: if ($part !~ m/^\Q$partid\E/) { next;}
3562: if ($type eq 'awarded' || $type eq 'solved') { next; }
3563: my $display=&Apache::lonnet::metadata($url,$stores.'.display');
3564: $display =~ s/\[Part: \Q$part\E\]//;
3565: my $narrowtext = &mt('Tries');
3566: $display =~ s/Number of Attempts/$narrowtext/;
3567: $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
3568: '<th align="center">'.&mt('New').' '.$display.'</th>';
3569: $columns{$partid}+=2;
3570: }
3571: }
3572: foreach my $partid (@partid) {
3573: my $display_part=&get_display_part($partid,$symb);
3574: $result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
3575: &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
3576: '</th>';
3577:
3578: }
3579: $result .= &Apache::loncommon::end_data_table_header_row().
3580: &Apache::loncommon::start_data_table_header_row().
3581: $header.
3582: &Apache::loncommon::end_data_table_header_row();
3583: my @noupdate;
3584: my ($updateCtr,$noupdateCtr) = (1,1);
3585: for ($i=0; $i<$env{'form.total'}; $i++) {
3586: my $line;
3587: my $user = $env{'form.ctr'.$i};
3588: my ($uname,$udom)=split(/:/,$user);
3589: my %newrecord;
3590: my $updateflag = 0;
3591: $line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
3592: my $usec=$classlist->{"$uname:$udom"}[5];
3593: if (!&canmodify($usec)) {
3594: my $numcols=scalar(@partid)*4+2;
3595: push(@noupdate,
3596: $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
3597: &mt('Not allowed to modify student')."</span></td></tr>");
3598: next;
3599: }
3600: my %aggregate = ();
3601: my $aggregateflag = 0;
3602: $user=~s/:/_/; # colon doen't work in javascript for names
3603: foreach (@partid) {
3604: my $old_aw = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
3605: my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
3606: my $old_part = $old_aw eq '' ? '' : $old_part_pcr;
3607: my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
3608: my $awarded = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
3609: my $pcr = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
3610: my $partial = $awarded eq '' ? '' : $pcr;
3611: my $score;
3612: if ($partial eq '') {
3613: $score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
3614: } elsif ($partial > 0) {
3615: $score = 'correct_by_override';
3616: } elsif ($partial == 0) {
3617: $score = 'incorrect_by_override';
3618: }
3619: my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
3620: $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
3621:
3622: $newrecord{'resource.'.$_.'.regrader'}=
3623: "$env{'user.name'}:$env{'user.domain'}";
3624: if ($dropMenu eq 'reset status' &&
3625: $old_score ne '') { # ignore if no previous attempts => nothing to reset
3626: $newrecord{'resource.'.$_.'.tries'} = '';
3627: $newrecord{'resource.'.$_.'.solved'} = '';
3628: $newrecord{'resource.'.$_.'.award'} = '';
3629: $newrecord{'resource.'.$_.'.awarded'} = '';
3630: $updateflag = 1;
3631: if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
3632: my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
3633: my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
3634: my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
3635: &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
3636: $aggregateflag = 1;
3637: }
3638: } elsif (!($old_part eq $partial && $old_score eq $score)) {
3639: $updateflag = 1;
3640: $newrecord{'resource.'.$_.'.awarded'} = $partial if $partial ne '';
3641: $newrecord{'resource.'.$_.'.solved'} = $score;
3642: $rec_update++;
3643: }
3644:
3645: $line .= '<td align="center">'.$old_aw.' </td>'.
3646: '<td align="center">'.$awarded.
3647: ($score eq 'excused' ? $score : '').' </td>';
3648:
3649:
3650: my $partid=$_;
3651: foreach my $stores (@parts) {
3652: my ($part,$type) = &split_part_type($stores);
3653: if ($part !~ m/^\Q$partid\E/) { next;}
3654: if ($type eq 'awarded' || $type eq 'solved') { next; }
3655: my $old_aw = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
3656: my $awarded = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
3657: if ($awarded ne '' && $awarded ne $old_aw) {
3658: $newrecord{'resource.'.$part.'.'.$type}= $awarded;
3659: $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
3660: $updateflag=1;
3661: }
3662: $line .= '<td align="center">'.$old_aw.' </td>'.
3663: '<td align="center">'.$awarded.' </td>';
3664: }
3665: }
3666: $line.="\n";
3667:
3668: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3669: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3670:
3671: if ($updateflag) {
3672: $count++;
3673: &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
3674: $udom,$uname);
3675:
3676: if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
3677: $cnum,$udom,$uname)) {
3678: # need to figure out if should be in queue.
3679: my %record =
3680: &Apache::lonnet::restore($symb,$env{'request.course.id'},
3681: $udom,$uname);
3682: my $all_graded = 1;
3683: my $none_graded = 1;
3684: foreach my $part (@parts) {
3685: if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
3686: $all_graded = 0;
3687: } else {
3688: $none_graded = 0;
3689: }
3690: }
3691:
3692: if ($all_graded || $none_graded) {
3693: &Apache::bridgetask::remove_from_queue('gradingqueue',
3694: $symb,$cdom,$cnum,
3695: $udom,$uname);
3696: }
3697: }
3698:
3699: $result.=&Apache::loncommon::start_data_table_row().
3700: '<td align="right"> '.$updateCtr.' </td>'.$line.
3701: &Apache::loncommon::end_data_table_row();
3702: $updateCtr++;
3703: } else {
3704: push(@noupdate,
3705: '<td align="right"> '.$noupdateCtr.' </td>'.$line);
3706: $noupdateCtr++;
3707: }
3708: if ($aggregateflag) {
3709: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
3710: $cdom,$cnum);
3711: }
3712: }
3713: if (@noupdate) {
3714: # my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
3715: my $numcols=scalar(@partid)*4+2;
3716: $result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
3717: '<td align="center" colspan="'.$numcols.'">'.
3718: &mt('No Changes Occurred For the Students Below').
3719: '</td>'.
3720: &Apache::loncommon::end_data_table_row();
3721: foreach my $line (@noupdate) {
3722: $result.=
3723: &Apache::loncommon::start_data_table_row().
3724: $line.
3725: &Apache::loncommon::end_data_table_row();
3726: }
3727: }
3728: $result .= &Apache::loncommon::end_data_table();
3729: my $msg = '<p><b>'.
3730: &mt('Number of records updated = [_1] for [quant,_2,student].',
3731: $rec_update,$count).'</b><br />'.
3732: '<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
3733: '</b></p>';
3734: return $title.$msg.$result;
3735: }
3736:
3737: sub split_part_type {
3738: my ($partstr) = @_;
3739: my ($temp,@allparts)=split(/_/,$partstr);
3740: my $type=pop(@allparts);
3741: my $part=join('_',@allparts);
3742: return ($part,$type);
3743: }
3744:
3745: #------------- end of section for handling grading by section/class ---------
3746: #
3747: #----------------------------------------------------------------------------
3748:
3749:
3750: #----------------------------------------------------------------------------
3751: #
3752: #-------------------------- Next few routines handles grading by csv upload
3753: #
3754: #--- Javascript to handle csv upload
3755: sub csvupload_javascript_reverse_associate {
3756: my $error1=&mt('You need to specify the username or the student/employee ID');
3757: my $error2=&mt('You need to specify at least one grading field');
3758: return(<<ENDPICK);
3759: function verify(vf) {
3760: var foundsomething=0;
3761: var founduname=0;
3762: var foundID=0;
3763: for (i=0;i<=vf.nfields.value;i++) {
3764: tw=eval('vf.f'+i+'.selectedIndex');
3765: if (i==0 && tw!=0) { foundID=1; }
3766: if (i==1 && tw!=0) { founduname=1; }
3767: if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
3768: }
3769: if (founduname==0 && foundID==0) {
3770: alert('$error1');
3771: return;
3772: }
3773: if (foundsomething==0) {
3774: alert('$error2');
3775: return;
3776: }
3777: vf.submit();
3778: }
3779: function flip(vf,tf) {
3780: var nw=eval('vf.f'+tf+'.selectedIndex');
3781: var i;
3782: for (i=0;i<=vf.nfields.value;i++) {
3783: //can not pick the same destination field for both name and domain
3784: if (((i ==0)||(i ==1)) &&
3785: ((tf==0)||(tf==1)) &&
3786: (i!=tf) &&
3787: (eval('vf.f'+i+'.selectedIndex')==nw)) {
3788: eval('vf.f'+i+'.selectedIndex=0;')
3789: }
3790: }
3791: }
3792: ENDPICK
3793: }
3794:
3795: sub csvupload_javascript_forward_associate {
3796: my $error1=&mt('You need to specify the username or the student/employee ID');
3797: my $error2=&mt('You need to specify at least one grading field');
3798: return(<<ENDPICK);
3799: function verify(vf) {
3800: var foundsomething=0;
3801: var founduname=0;
3802: var foundID=0;
3803: for (i=0;i<=vf.nfields.value;i++) {
3804: tw=eval('vf.f'+i+'.selectedIndex');
3805: if (tw==1) { foundID=1; }
3806: if (tw==2) { founduname=1; }
3807: if (tw>3) { foundsomething=1; }
3808: }
3809: if (founduname==0 && foundID==0) {
3810: alert('$error1');
3811: return;
3812: }
3813: if (foundsomething==0) {
3814: alert('$error2');
3815: return;
3816: }
3817: vf.submit();
3818: }
3819: function flip(vf,tf) {
3820: var nw=eval('vf.f'+tf+'.selectedIndex');
3821: var i;
3822: //can not pick the same destination field twice
3823: for (i=0;i<=vf.nfields.value;i++) {
3824: if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
3825: eval('vf.f'+i+'.selectedIndex=0;')
3826: }
3827: }
3828: }
3829: ENDPICK
3830: }
3831:
3832: sub csvuploadmap_header {
3833: my ($request,$symb,$datatoken,$distotal)= @_;
3834: my $javascript;
3835: if ($env{'form.upfile_associate'} eq 'reverse') {
3836: $javascript=&csvupload_javascript_reverse_associate();
3837: } else {
3838: $javascript=&csvupload_javascript_forward_associate();
3839: }
3840:
3841: $symb = &Apache::lonenc::check_encrypt($symb);
3842: $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
3843: &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
3844: &mt('Associate entries from the uploaded file with as many fields as you can.'));
3845: my $reverse=&mt("Reverse Association");
3846: $request->print(<<ENDPICK);
3847: <br />
3848: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
3849: <input type="hidden" name="associate" value="" />
3850: <input type="hidden" name="phase" value="three" />
3851: <input type="hidden" name="datatoken" value="$datatoken" />
3852: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
3853: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
3854: <input type="hidden" name="upfile_associate"
3855: value="$env{'form.upfile_associate'}" />
3856: <input type="hidden" name="symb" value="$symb" />
3857: <input type="hidden" name="command" value="csvuploadoptions" />
3858: <hr />
3859: ENDPICK
3860: $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
3861: return '';
3862:
3863: }
3864:
3865: sub csvupload_fields {
3866: my ($symb,$errorref) = @_;
3867: my (@parts) = &getpartlist($symb,$errorref);
3868: if (ref($errorref)) {
3869: if ($$errorref) {
3870: return;
3871: }
3872: }
3873:
3874: my @fields=(['ID','Student/Employee ID'],
3875: ['username','Student Username'],
3876: ['domain','Student Domain']);
3877: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3878: foreach my $part (sort(@parts)) {
3879: my @datum;
3880: my $display=&Apache::lonnet::metadata($url,$part.'.display');
3881: my $name=$part;
3882: if (!$display) { $display = $name; }
3883: @datum=($name,$display);
3884: if ($name=~/^stores_(.*)_awarded/) {
3885: push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
3886: }
3887: push(@fields,\@datum);
3888: }
3889: return (@fields);
3890: }
3891:
3892: sub csvuploadmap_footer {
3893: my ($request,$i,$keyfields) =@_;
3894: $request->print(<<ENDPICK);
3895: </table>
3896: <input type="hidden" name="nfields" value="$i" />
3897: <input type="hidden" name="keyfields" value="$keyfields" />
3898: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
3899: </form>
3900: ENDPICK
3901: }
3902:
3903: sub checkforfile_js {
3904: my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
3905: my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
3906: function checkUpload(formname) {
3907: if (formname.upfile.value == "") {
3908: alert("$alertmsg");
3909: return false;
3910: }
3911: formname.submit();
3912: }
3913: CSVFORMJS
3914: return $result;
3915: }
3916:
3917: sub upcsvScores_form {
3918: my ($request,$symb) = @_;
3919: if (!$symb) {return '';}
3920: my $result=&checkforfile_js();
3921: $result.=&Apache::loncommon::start_data_table().
3922: &Apache::loncommon::start_data_table_header_row().
3923: '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
3924: &Apache::loncommon::end_data_table_header_row().
3925: &Apache::loncommon::start_data_table_row().'<td>';
3926: my $upload=&mt("Upload Scores");
3927: my $upfile_select=&Apache::loncommon::upfile_select_html();
3928: my $ignore=&mt('Ignore First Line');
3929: $symb = &Apache::lonenc::check_encrypt($symb);
3930: $result.=<<ENDUPFORM;
3931: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3932: <input type="hidden" name="symb" value="$symb" />
3933: <input type="hidden" name="command" value="csvuploadmap" />
3934: $upfile_select
3935: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
3936: </form>
3937: ENDUPFORM
3938: $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
3939: &mt("How do I create a CSV file from a spreadsheet")).
3940: '</td>'.
3941: &Apache::loncommon::end_data_table_row().
3942: &Apache::loncommon::end_data_table();
3943: return $result;
3944: }
3945:
3946:
3947: sub csvuploadmap {
3948: my ($request,$symb)= @_;
3949: if (!$symb) {return '';}
3950:
3951: my $datatoken;
3952: if (!$env{'form.datatoken'}) {
3953: $datatoken=&Apache::loncommon::upfile_store($request);
3954: } else {
3955: $datatoken=$env{'form.datatoken'};
3956: &Apache::loncommon::load_tmp_file($request);
3957: }
3958: my @records=&Apache::loncommon::upfile_record_sep();
3959: &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
3960: my ($i,$keyfields);
3961: if (@records) {
3962: my $fieldserror;
3963: my @fields=&csvupload_fields($symb,\$fieldserror);
3964: if ($fieldserror) {
3965: $request->print(&navmap_errormsg());
3966: return;
3967: }
3968: if ($env{'form.upfile_associate'} eq 'reverse') {
3969: &Apache::loncommon::csv_print_samples($request,\@records);
3970: $i=&Apache::loncommon::csv_print_select_table($request,\@records,
3971: \@fields);
3972: foreach (@fields) { $keyfields.=$_->[0].','; }
3973: chop($keyfields);
3974: } else {
3975: unshift(@fields,['none','']);
3976: $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
3977: \@fields);
3978: foreach my $rec (@records) {
3979: my %temp = &Apache::loncommon::record_sep($rec);
3980: if (%temp) {
3981: $keyfields=join(',',sort(keys(%temp)));
3982: last;
3983: }
3984: }
3985: }
3986: }
3987: &csvuploadmap_footer($request,$i,$keyfields);
3988:
3989: return '';
3990: }
3991:
3992: sub csvuploadoptions {
3993: my ($request,$symb)= @_;
3994: my $overwrite=&mt('Overwrite any existing score');
3995: $request->print(<<ENDPICK);
3996: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3997: <input type="hidden" name="command" value="csvuploadassign" />
3998: <p>
3999: <label>
4000: <input type="checkbox" name="overwite_scores" checked="checked" />
4001: $overwrite
4002: </label>
4003: </p>
4004: ENDPICK
4005: my %fields=&get_fields();
4006: if (!defined($fields{'domain'})) {
4007: my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
4008: $request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
4009: }
4010: foreach my $key (sort(keys(%env))) {
4011: if ($key !~ /^form\.(.*)$/) { next; }
4012: my $cleankey=$1;
4013: if ($cleankey eq 'command') { next; }
4014: $request->print('<input type="hidden" name="'.$cleankey.
4015: '" value="'.$env{$key}.'" />'."\n");
4016: }
4017: # FIXME do a check for any duplicated user ids...
4018: # FIXME do a check for any invalid user ids?...
4019: $request->print('<input type="submit" value="Assign Grades" /><br />
4020: <hr /></form>'."\n");
4021: return '';
4022: }
4023:
4024: sub get_fields {
4025: my %fields;
4026: my @keyfields = split(/\,/,$env{'form.keyfields'});
4027: for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
4028: if ($env{'form.upfile_associate'} eq 'reverse') {
4029: if ($env{'form.f'.$i} ne 'none') {
4030: $fields{$keyfields[$i]}=$env{'form.f'.$i};
4031: }
4032: } else {
4033: if ($env{'form.f'.$i} ne 'none') {
4034: $fields{$env{'form.f'.$i}}=$keyfields[$i];
4035: }
4036: }
4037: }
4038: return %fields;
4039: }
4040:
4041: sub csvuploadassign {
4042: my ($request,$symb)= @_;
4043: if (!$symb) {return '';}
4044: my $error_msg = '';
4045: &Apache::loncommon::load_tmp_file($request);
4046: my @gradedata = &Apache::loncommon::upfile_record_sep();
4047: my %fields=&get_fields();
4048: my $courseid=$env{'request.course.id'};
4049: my ($classlist) = &getclasslist('all',0);
4050: my @notallowed;
4051: my @skipped;
4052: my $countdone=0;
4053: foreach my $grade (@gradedata) {
4054: my %entries=&Apache::loncommon::record_sep($grade);
4055: my $domain;
4056: if ($entries{$fields{'domain'}}) {
4057: $domain=$entries{$fields{'domain'}};
4058: } else {
4059: $domain=$env{'form.default_domain'};
4060: }
4061: $domain=~s/\s//g;
4062: my $username=$entries{$fields{'username'}};
4063: $username=~s/\s//g;
4064: if (!$username) {
4065: my $id=$entries{$fields{'ID'}};
4066: $id=~s/\s//g;
4067: my %ids=&Apache::lonnet::idget($domain,$id);
4068: $username=$ids{$id};
4069: }
4070: if (!exists($$classlist{"$username:$domain"})) {
4071: my $id=$entries{$fields{'ID'}};
4072: $id=~s/\s//g;
4073: if ($id) {
4074: push(@skipped,"$id:$domain");
4075: } else {
4076: push(@skipped,"$username:$domain");
4077: }
4078: next;
4079: }
4080: my $usec=$classlist->{"$username:$domain"}[5];
4081: if (!&canmodify($usec)) {
4082: push(@notallowed,"$username:$domain");
4083: next;
4084: }
4085: my %points;
4086: my %grades;
4087: foreach my $dest (keys(%fields)) {
4088: if ($dest eq 'ID' || $dest eq 'username' ||
4089: $dest eq 'domain') { next; }
4090: if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
4091: if ($dest=~/stores_(.*)_points/) {
4092: my $part=$1;
4093: my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
4094: $symb,$domain,$username);
4095: if ($wgt) {
4096: $entries{$fields{$dest}}=~s/\s//g;
4097: my $pcr=$entries{$fields{$dest}} / $wgt;
4098: my $award=($pcr == 0) ? 'incorrect_by_override'
4099: : 'correct_by_override';
4100: if ($pcr>1) {
4101: push(@skipped,&mt("[_1]: point value larger than weight","$username:$domain"));
4102: }
4103: $grades{"resource.$part.awarded"}=$pcr;
4104: $grades{"resource.$part.solved"}=$award;
4105: $points{$part}=1;
4106: } else {
4107: $error_msg = "<br />" .
4108: &mt("Some point values were assigned"
4109: ." for problems with a weight "
4110: ."of zero. These values were "
4111: ."ignored.");
4112: }
4113: } else {
4114: if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
4115: if ($dest=~/stores_(.*)_solved/) { if ($points{$1}) {next;} }
4116: my $store_key=$dest;
4117: $store_key=~s/^stores/resource/;
4118: $store_key=~s/_/\./g;
4119: $grades{$store_key}=$entries{$fields{$dest}};
4120: }
4121: }
4122: if (! %grades) {
4123: push(@skipped,&mt("[_1]: no data to save","$username:$domain"));
4124: } else {
4125: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
4126: my $result=&Apache::lonnet::cstore(\%grades,$symb,
4127: $env{'request.course.id'},
4128: $domain,$username);
4129: if ($result eq 'ok') {
4130: # Successfully stored
4131: $request->print('.');
4132: # Remove from grading queue
4133: &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
4134: $env{'course.'.$env{'request.course.id'}.'.domain'},
4135: $env{'course.'.$env{'request.course.id'}.'.num'},
4136: $domain,$username);
4137: $countdone++;
4138: } else {
4139: $request->print("<p><span class=\"LC_error\">".
4140: &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
4141: "$username:$domain",$result)."</span></p>");
4142: }
4143: $request->rflush();
4144: }
4145: }
4146: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
4147: if (@skipped) {
4148: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
4149: $request->print(join(', ',@skipped));
4150: }
4151: if (@notallowed) {
4152: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
4153: $request->print(join(', ',@notallowed));
4154: }
4155: $request->print("<br />\n");
4156: return $error_msg;
4157: }
4158: #------------- end of section for handling csv file upload ---------
4159: #
4160: #-------------------------------------------------------------------
4161: #
4162: #-------------- Next few routines handle grading by page/sequence
4163: #
4164: #--- Select a page/sequence and a student to grade
4165: sub pickStudentPage {
4166: my ($request,$symb) = @_;
4167:
4168: my $alertmsg = &mt('Please select the student you wish to grade.');
4169: $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
4170:
4171: function checkPickOne(formname) {
4172: if (radioSelection(formname.student) == null) {
4173: alert("$alertmsg");
4174: return;
4175: }
4176: ptr = pullDownSelection(formname.selectpage);
4177: formname.page.value = formname["page"+ptr].value;
4178: formname.title.value = formname["title"+ptr].value;
4179: formname.submit();
4180: }
4181:
4182: LISTJAVASCRIPT
4183: &commonJSfunctions($request);
4184:
4185: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4186: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4187: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4188:
4189: my $result='<h3><span class="LC_info"> '.
4190: &mt('Manual Grading by Page or Sequence').'</span></h3>';
4191:
4192: $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
4193: my $map_error;
4194: my ($titles,$symbx) = &getSymbMap($map_error);
4195: if ($map_error) {
4196: $request->print(&navmap_errormsg());
4197: return;
4198: }
4199: my ($curpage) =&Apache::lonnet::decode_symb($symb);
4200: # my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb);
4201: # my $type=($curpage =~ /\.(page|sequence)/);
4202: my $select = '<select name="selectpage">'."\n";
4203: my $ctr=0;
4204: foreach (@$titles) {
4205: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4206: $select.='<option value="'.$ctr.'" '.
4207: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
4208: '>'.$showtitle.'</option>'."\n";
4209: $ctr++;
4210: }
4211: $select.= '</select>';
4212: $result.=' <b>'.&mt('Problems from').':</b> '.$select."<br />\n";
4213:
4214: $ctr=0;
4215: foreach (@$titles) {
4216: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4217: $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
4218: $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
4219: $ctr++;
4220: }
4221: $result.='<input type="hidden" name="page" />'."\n".
4222: '<input type="hidden" name="title" />'."\n";
4223:
4224: my $options =
4225: '<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
4226: '<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
4227: $result.=' <b>'.&mt('View Problem Text').': </b>'.$options;
4228:
4229: $options =
4230: '<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
4231: '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
4232: '<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
4233: $result.=' <b>'.&mt('Submissions').': </b>'.$options;
4234:
4235: $result.=&build_section_inputs();
4236: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
4237: $result.='<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
4238: '<input type="hidden" name="command" value="displayPage" />'."\n".
4239: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."<br />\n";
4240:
4241: $result.=' <b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
4242:
4243: $result.=' <input type="button" '.
4244: 'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' →" /><br />'."\n";
4245:
4246: $request->print($result);
4247:
4248: my $studentTable.=' <b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
4249: &Apache::loncommon::start_data_table().
4250: &Apache::loncommon::start_data_table_header_row().
4251: '<th align="right"> '.&mt('No.').'</th>'.
4252: '<th>'.&nameUserString('header').'</th>'.
4253: '<th align="right"> '.&mt('No.').'</th>'.
4254: '<th>'.&nameUserString('header').'</th>'.
4255: &Apache::loncommon::end_data_table_header_row();
4256:
4257: my (undef,undef,$fullname) = &getclasslist($getsec,'1');
4258: my $ptr = 1;
4259: foreach my $student (sort
4260: {
4261: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
4262: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
4263: }
4264: return $a cmp $b;
4265: } (keys(%$fullname))) {
4266: my ($uname,$udom) = split(/:/,$student);
4267: $studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
4268: : '</td>');
4269: $studentTable.='<td align="right">'.$ptr.' </td>';
4270: $studentTable.='<td> <label><input type="radio" name="student" value="'.$student.'" /> '
4271: .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
4272: $studentTable.=
4273: ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row()
4274: : '');
4275: $ptr++;
4276: }
4277: if ($ptr%2 == 0) {
4278: $studentTable.='</td><td> </td><td> </td>'.
4279: &Apache::loncommon::end_data_table_row();
4280: }
4281: $studentTable.=&Apache::loncommon::end_data_table()."\n";
4282: $studentTable.='<input type="button" '.
4283: 'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' →" /></form>'."\n";
4284:
4285: $request->print($studentTable);
4286:
4287: return '';
4288: }
4289:
4290: sub getSymbMap {
4291: my ($map_error) = @_;
4292: my $navmap = Apache::lonnavmaps::navmap->new();
4293: unless (ref($navmap)) {
4294: if (ref($map_error)) {
4295: $$map_error = 'navmap';
4296: }
4297: return;
4298: }
4299: my %symbx = ();
4300: my @titles = ();
4301: my $minder = 0;
4302:
4303: # Gather every sequence that has problems.
4304: my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
4305: 1,0,1);
4306: for my $sequence ($navmap->getById('0.0'), @sequences) {
4307: if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
4308: my $title = $minder.'.'.
4309: &HTML::Entities::encode($sequence->compTitle(),'"\'&');
4310: push(@titles, $title); # minder in case two titles are identical
4311: $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
4312: $minder++;
4313: }
4314: }
4315: return \@titles,\%symbx;
4316: }
4317:
4318: #
4319: #--- Displays a page/sequence w/wo problems, w/wo submissions
4320: sub displayPage {
4321: my ($request,$symb) = @_;
4322: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4323: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4324: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4325: my $pageTitle = $env{'form.page'};
4326: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
4327: my ($uname,$udom) = split(/:/,$env{'form.student'});
4328: my $usec=$classlist->{$env{'form.student'}}[5];
4329:
4330: #need to make sure we have the correct data for later EXT calls,
4331: #thus invalidate the cache
4332: &Apache::lonnet::devalidatecourseresdata(
4333: $env{'course.'.$env{'request.course.id'}.'.num'},
4334: $env{'course.'.$env{'request.course.id'}.'.domain'});
4335: &Apache::lonnet::clear_EXT_cache_status();
4336:
4337: if (!&canview($usec)) {
4338: $request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
4339: return;
4340: }
4341: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
4342: $result.='<h3> '.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
4343: '</h3>'."\n";
4344: $env{'form.CODE'} = uc($env{'form.CODE'});
4345: if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
4346: $result.='<h3> '.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
4347: } else {
4348: delete($env{'form.CODE'});
4349: }
4350: &sub_page_js($request);
4351: $request->print($result);
4352:
4353: my $navmap = Apache::lonnavmaps::navmap->new();
4354: unless (ref($navmap)) {
4355: $request->print(&navmap_errormsg());
4356: return;
4357: }
4358: my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
4359: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
4360: if (!$map) {
4361: $request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
4362: return;
4363: }
4364: my $iterator = $navmap->getIterator($map->map_start(),
4365: $map->map_finish());
4366:
4367: my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
4368: '<input type="hidden" name="command" value="gradeByPage" />'."\n".
4369: '<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
4370: '<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
4371: '<input type="hidden" name="page" value="'.$pageTitle.'" />'."\n".
4372: '<input type="hidden" name="title" value="'.$env{'form.title'}.'" />'."\n".
4373: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
4374: '<input type="hidden" name="overRideScore" value="no" />'."\n";
4375:
4376: if (defined($env{'form.CODE'})) {
4377: $studentTable.=
4378: '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
4379: }
4380: my $checkIcon = '<img alt="'.&mt('Check Mark').
4381: '" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
4382:
4383: $studentTable.=' <span class="LC_info">'.
4384: &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
4385: '</span>'."\n".
4386: &Apache::loncommon::start_data_table().
4387: &Apache::loncommon::start_data_table_header_row().
4388: '<th align="center"> Prob. </th>'.
4389: '<th> '.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
4390: &Apache::loncommon::end_data_table_header_row();
4391:
4392: &Apache::lonxml::clear_problem_counter();
4393: my ($depth,$question,$prob) = (1,1,1);
4394: $iterator->next(); # skip the first BEGIN_MAP
4395: my $curRes = $iterator->next(); # for "current resource"
4396: while ($depth > 0) {
4397: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
4398: if($curRes == $iterator->END_MAP) { $depth--; }
4399:
4400: if (ref($curRes) && $curRes->is_problem()) {
4401: my $parts = $curRes->parts();
4402: my $title = $curRes->compTitle();
4403: my $symbx = $curRes->symb();
4404: $studentTable.=
4405: &Apache::loncommon::start_data_table_row().
4406: '<td align="center" valign="top" >'.$prob.
4407: (scalar(@{$parts}) == 1 ? ''
4408: : '<br />('.&mt('[_1]parts)',
4409: scalar(@{$parts}).' ')
4410: ).
4411: '</td>';
4412: $studentTable.='<td valign="top">';
4413: my %form = ('CODE' => $env{'form.CODE'},);
4414: if ($env{'form.vProb'} eq 'yes' ) {
4415: $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
4416: undef,'both',\%form);
4417: } else {
4418: my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
4419: $companswer =~ s|<form(.*?)>||g;
4420: $companswer =~ s|</form>||g;
4421: # while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
4422: # $companswer =~ s/$1/ /ms;
4423: # $request->print('match='.$1."<br />\n");
4424: # }
4425: # $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
4426: $studentTable.=' <b>'.$title.'</b> <br /> <b>'.&mt('Correct answer').':</b><br />'.$companswer;
4427: }
4428:
4429: my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
4430:
4431: if ($env{'form.lastSub'} eq 'datesub') {
4432: if ($record{'version'} eq '') {
4433: $studentTable.='<br /> <span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
4434: } else {
4435: my %responseType = ();
4436: foreach my $partid (@{$parts}) {
4437: my @responseIds =$curRes->responseIds($partid);
4438: my @responseType =$curRes->responseType($partid);
4439: my %responseIds;
4440: for (my $i=0;$i<=$#responseIds;$i++) {
4441: $responseIds{$responseIds[$i]}=$responseType[$i];
4442: }
4443: $responseType{$partid} = \%responseIds;
4444: }
4445: $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
4446:
4447: }
4448: } elsif ($env{'form.lastSub'} eq 'all') {
4449: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
4450: $studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
4451: $env{'request.course.id'},
4452: '','.submission');
4453:
4454: }
4455: if (&canmodify($usec)) {
4456: $studentTable.=&gradeBox_start();
4457: foreach my $partid (@{$parts}) {
4458: $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
4459: $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
4460: $question++;
4461: }
4462: $studentTable.=&gradeBox_end();
4463: $prob++;
4464: }
4465: $studentTable.='</td></tr>';
4466:
4467: }
4468: $curRes = $iterator->next();
4469: }
4470:
4471: $studentTable.=
4472: '</table>'."\n".
4473: '<input type="button" value="'.&mt('Save').'" '.
4474: 'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
4475: '</form>'."\n";
4476: $request->print($studentTable);
4477:
4478: return '';
4479: }
4480:
4481: sub displaySubByDates {
4482: my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
4483: my $isCODE=0;
4484: my $isTask = ($symb =~/\.task$/);
4485: if (exists($record->{'resource.CODE'})) { $isCODE=1; }
4486: my $studentTable=&Apache::loncommon::start_data_table().
4487: &Apache::loncommon::start_data_table_header_row().
4488: '<th>'.&mt('Date/Time').'</th>'.
4489: ($isCODE?'<th>'.&mt('CODE').'</th>':'').
4490: '<th>'.&mt('Submission').'</th>'.
4491: '<th>'.&mt('Status').'</th>'.
4492: &Apache::loncommon::end_data_table_header_row();
4493: my ($version);
4494: my %mark;
4495: my %orders;
4496: $mark{'correct_by_student'} = $checkIcon;
4497: if (!exists($$record{'1:timestamp'})) {
4498: return '<br /> <span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
4499: }
4500:
4501: my $interaction;
4502: my $no_increment = 1;
4503: my %lastrndseed;
4504: for ($version=1;$version<=$$record{'version'};$version++) {
4505: my $timestamp =
4506: &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
4507: if (exists($$record{$version.':resource.0.version'})) {
4508: $interaction = $$record{$version.':resource.0.version'};
4509: }
4510:
4511: my $where = ($isTask ? "$version:resource.$interaction"
4512: : "$version:resource");
4513: $studentTable.=&Apache::loncommon::start_data_table_row().
4514: '<td>'.$timestamp.'</td>';
4515: if ($isCODE) {
4516: $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
4517: }
4518: my @versionKeys = split(/\:/,$$record{$version.':keys'});
4519: my @displaySub = ();
4520: foreach my $partid (@{$parts}) {
4521: my ($hidden,$type);
4522: $type = $$record{$version.':resource.'.$partid.'.type'};
4523: if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
4524: $hidden = 1;
4525: }
4526: my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
4527: : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
4528:
4529: # next if ($$record{"$version:resource.$partid.solved"} eq '');
4530: my $display_part=&get_display_part($partid,$symb);
4531: foreach my $matchKey (@matchKey) {
4532: if (exists($$record{$version.':'.$matchKey}) &&
4533: $$record{$version.':'.$matchKey} ne '') {
4534:
4535: my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
4536: : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
4537: $displaySub[0].='<span class="LC_nobreak"';
4538: $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
4539: .' <span class="LC_internal_info">'
4540: .'('.&mt('Response ID: [_1]',$responseId).')'
4541: .'</span>'
4542: .' <b>';
4543: if ($hidden) {
4544: $displaySub[0].= &mt('Anonymous Survey').'</b>';
4545: } else {
4546: my ($trial,$rndseed,$newvariation);
4547: if ($type eq 'randomizetry') {
4548: $trial = $$record{"$where.$partid.tries"};
4549: $rndseed = $$record{"$where.$partid.rndseed"};
4550: }
4551: if ($$record{"$where.$partid.tries"} eq '') {
4552: $displaySub[0].=&mt('Trial not counted');
4553: } else {
4554: $displaySub[0].=&mt('Trial: [_1]',
4555: $$record{"$where.$partid.tries"});
4556: if ($rndseed || $lastrndseed{$partid}) {
4557: if ($rndseed ne $lastrndseed{$partid}) {
4558: $newvariation = ' ('.&mt('New variation this try').')';
4559: }
4560: }
4561: $lastrndseed{$partid} = $rndseed;
4562: }
4563: my $responseType=($isTask ? 'Task'
4564: : $responseType->{$partid}->{$responseId});
4565: if (!exists($orders{$partid})) { $orders{$partid}={}; }
4566: if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
4567: $orders{$partid}->{$responseId}=
4568: &get_order($partid,$responseId,$symb,$uname,$udom,
4569: $no_increment,$type,$trial,$rndseed);
4570: }
4571: $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
4572: $displaySub[0].=' '.
4573: &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
4574: }
4575: }
4576: }
4577: if (exists($$record{"$where.$partid.checkedin"})) {
4578: $displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
4579: $$record{"$where.$partid.checkedin"},
4580: $$record{"$where.$partid.checkedin.slot"}).
4581: '<br />';
4582: }
4583: if (exists $$record{"$where.$partid.award"}) {
4584: $displaySub[1].='<b>'.&mt('Part:').'</b> '.$display_part.' '.
4585: lc($$record{"$where.$partid.award"}).' '.
4586: $mark{$$record{"$where.$partid.solved"}}.
4587: '<br />';
4588: }
4589: if (exists $$record{"$where.$partid.regrader"}) {
4590: $displaySub[2].=$$record{"$where.$partid.regrader"}.
4591: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
4592: } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
4593: $displaySub[2].=
4594: $$record{"$version:resource.$partid.regrader"}.
4595: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
4596: }
4597: }
4598: # needed because old essay regrader has not parts info
4599: if (exists $$record{"$version:resource.regrader"}) {
4600: $displaySub[2].=$$record{"$version:resource.regrader"};
4601: }
4602: $studentTable.='<td>'.$displaySub[0].' </td><td>'.$displaySub[1];
4603: if ($displaySub[2]) {
4604: $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
4605: }
4606: $studentTable.=' </td>'.
4607: &Apache::loncommon::end_data_table_row();
4608: }
4609: $studentTable.=&Apache::loncommon::end_data_table();
4610: return $studentTable;
4611: }
4612:
4613: sub updateGradeByPage {
4614: my ($request,$symb) = @_;
4615:
4616: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4617: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4618: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4619: my $pageTitle = $env{'form.page'};
4620: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
4621: my ($uname,$udom) = split(/:/,$env{'form.student'});
4622: my $usec=$classlist->{$env{'form.student'}}[5];
4623: if (!&canmodify($usec)) {
4624: $request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
4625: return;
4626: }
4627: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
4628: $result.='<h3> '.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
4629: '</h3>'."\n";
4630:
4631: $request->print($result);
4632:
4633:
4634: my $navmap = Apache::lonnavmaps::navmap->new();
4635: unless (ref($navmap)) {
4636: $request->print(&navmap_errormsg());
4637: return;
4638: }
4639: my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
4640: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
4641: if (!$map) {
4642: $request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
4643: return;
4644: }
4645: my $iterator = $navmap->getIterator($map->map_start(),
4646: $map->map_finish());
4647:
4648: my $studentTable=
4649: &Apache::loncommon::start_data_table().
4650: &Apache::loncommon::start_data_table_header_row().
4651: '<th align="center"> '.&mt('Prob.').' </th>'.
4652: '<th> '.&mt('Title').' </th>'.
4653: '<th> '.&mt('Previous Score').' </th>'.
4654: '<th> '.&mt('New Score').' </th>'.
4655: &Apache::loncommon::end_data_table_header_row();
4656:
4657: $iterator->next(); # skip the first BEGIN_MAP
4658: my $curRes = $iterator->next(); # for "current resource"
4659: my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
4660: while ($depth > 0) {
4661: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
4662: if($curRes == $iterator->END_MAP) { $depth--; }
4663:
4664: if (ref($curRes) && $curRes->is_problem()) {
4665: my $parts = $curRes->parts();
4666: my $title = $curRes->compTitle();
4667: my $symbx = $curRes->symb();
4668: $studentTable.=
4669: &Apache::loncommon::start_data_table_row().
4670: '<td align="center" valign="top" >'.$prob.
4671: (scalar(@{$parts}) == 1 ? ''
4672: : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
4673: .')').'</td>';
4674: $studentTable.='<td valign="top"> <b>'.$title.'</b> </td>';
4675:
4676: my %newrecord=();
4677: my @displayPts=();
4678: my %aggregate = ();
4679: my $aggregateflag = 0;
4680: foreach my $partid (@{$parts}) {
4681: my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
4682: my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
4683:
4684: my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ?
4685: $env{'form.WGT'.$question.'_'.$partid} : 1;
4686: my $partial = $newpts/$wgt;
4687: my $score;
4688: if ($partial > 0) {
4689: $score = 'correct_by_override';
4690: } elsif ($newpts ne '') { #empty is taken as 0
4691: $score = 'incorrect_by_override';
4692: }
4693: my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
4694: if ($dropMenu eq 'excused') {
4695: $partial = '';
4696: $score = 'excused';
4697: } elsif ($dropMenu eq 'reset status'
4698: && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
4699: $newrecord{'resource.'.$partid.'.tries'} = 0;
4700: $newrecord{'resource.'.$partid.'.solved'} = '';
4701: $newrecord{'resource.'.$partid.'.award'} = '';
4702: $newrecord{'resource.'.$partid.'.awarded'} = 0;
4703: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
4704: $changeflag++;
4705: $newpts = '';
4706:
4707: my $aggtries = $env{'form.aggtries'.$question.'_'.$partid};
4708: my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
4709: my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
4710: if ($aggtries > 0) {
4711: &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
4712: $aggregateflag = 1;
4713: }
4714: }
4715: my $display_part=&get_display_part($partid,$curRes->symb());
4716: my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
4717: $displayPts[0].=' <b>'.&mt('Part').':</b> '.$display_part.' = '.
4718: (($oldstatus eq 'excused') ? 'excused' : $oldpts).
4719: ' <br />';
4720: $displayPts[1].=' <b>'.&mt('Part').':</b> '.$display_part.' = '.
4721: (($score eq 'excused') ? 'excused' : $newpts).
4722: ' <br />';
4723: $question++;
4724: next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
4725:
4726: $newrecord{'resource.'.$partid.'.awarded'} = $partial if $partial ne '';
4727: $newrecord{'resource.'.$partid.'.solved'} = $score if $score ne '';
4728: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
4729: if (scalar(keys(%newrecord)) > 0);
4730:
4731: $changeflag++;
4732: }
4733: if (scalar(keys(%newrecord)) > 0) {
4734: my %record =
4735: &Apache::lonnet::restore($symbx,$env{'request.course.id'},
4736: $udom,$uname);
4737:
4738: if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
4739: $newrecord{'resource.CODE'} = $env{'form.CODE'};
4740: } elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
4741: $newrecord{'resource.CODE'} = '';
4742: }
4743: &Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
4744: $udom,$uname);
4745: %record = &Apache::lonnet::restore($symbx,
4746: $env{'request.course.id'},
4747: $udom,$uname);
4748: &check_and_remove_from_queue($parts,\%record,undef,$symbx,
4749: $cdom,$cnum,$udom,$uname);
4750: }
4751:
4752: if ($aggregateflag) {
4753: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
4754: $env{'course.'.$env{'request.course.id'}.'.domain'},
4755: $env{'course.'.$env{'request.course.id'}.'.num'});
4756: }
4757:
4758: $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
4759: '<td valign="top">'.$displayPts[1].'</td>'.
4760: &Apache::loncommon::end_data_table_row();
4761:
4762: $prob++;
4763: }
4764: $curRes = $iterator->next();
4765: }
4766:
4767: $studentTable.=&Apache::loncommon::end_data_table();
4768: my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
4769: &mt('The scores were changed for [quant,_1,problem].',
4770: $changeflag));
4771: $request->print($grademsg.$studentTable);
4772:
4773: return '';
4774: }
4775:
4776: #-------- end of section for handling grading by page/sequence ---------
4777: #
4778: #-------------------------------------------------------------------
4779:
4780: #-------------------- Bubblesheet (Scantron) Grading -------------------
4781: #
4782: #------ start of section for handling grading by page/sequence ---------
4783:
4784: =pod
4785:
4786: =head1 Bubble sheet grading routines
4787:
4788: For this documentation:
4789:
4790: 'scanline' refers to the full line of characters
4791: from the file that we are parsing that represents one entire sheet
4792:
4793: 'bubble line' refers to the data
4794: representing the line of bubbles that are on the physical bubble sheet
4795:
4796:
4797: The overall process is that a scanned in bubble sheet data is uploaded
4798: into a course. When a user wants to grade, they select a
4799: sequence/folder of resources, a file of bubble sheet info, and pick
4800: one of the predefined configurations for what each scanline looks
4801: like.
4802:
4803: Next each scanline is checked for any errors of either 'missing
4804: bubbles' (it's an error because it may have been mis-scanned
4805: because too light bubbling), 'double bubble' (each bubble line should
4806: have no more that one letter picked), invalid or duplicated CODE,
4807: invalid student/employee ID
4808:
4809: If the CODE option is used that determines the randomization of the
4810: homework problems, either way the student/employee ID is looked up into a
4811: username:domain.
4812:
4813: During the validation phase the instructor can choose to skip scanlines.
4814:
4815: After the validation phase, there are now 3 bubble sheet files
4816:
4817: scantron_original_filename (unmodified original file)
4818: scantron_corrected_filename (file where the corrected information has replaced the original information)
4819: scantron_skipped_filename (contains the exact text of scanlines that where skipped)
4820:
4821: Also there is a separate hash nohist_scantrondata that contains extra
4822: correction information that isn't representable in the bubble sheet
4823: file (see &scantron_getfile() for more information)
4824:
4825: After all scanlines are either valid, marked as valid or skipped, then
4826: foreach line foreach problem in the picked sequence, an ssi request is
4827: made that simulates a user submitting their selected letter(s) against
4828: the homework problem.
4829:
4830: =over 4
4831:
4832:
4833:
4834: =item defaultFormData
4835:
4836: Returns html hidden inputs used to hold context/default values.
4837:
4838: Arguments:
4839: $symb - $symb of the current resource
4840:
4841: =cut
4842:
4843: sub defaultFormData {
4844: my ($symb)=@_;
4845: return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
4846: }
4847:
4848:
4849: =pod
4850:
4851: =item getSequenceDropDown
4852:
4853: Return html dropdown of possible sequences to grade
4854:
4855: Arguments:
4856: $symb - $symb of the current resource
4857: $map_error - ref to scalar which will container error if
4858: $navmap object is unavailable in &getSymbMap().
4859:
4860: =cut
4861:
4862: sub getSequenceDropDown {
4863: my ($symb,$map_error)=@_;
4864: my $result='<select name="selectpage">'."\n";
4865: my ($titles,$symbx) = &getSymbMap($map_error);
4866: if (ref($map_error)) {
4867: return if ($$map_error);
4868: }
4869: my ($curpage)=&Apache::lonnet::decode_symb($symb);
4870: my $ctr=0;
4871: foreach (@$titles) {
4872: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4873: $result.='<option value="'.$$symbx{$_}.'" '.
4874: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
4875: '>'.$showtitle.'</option>'."\n";
4876: $ctr++;
4877: }
4878: $result.= '</select>';
4879: return $result;
4880: }
4881:
4882: my %bubble_lines_per_response; # no. bubble lines for each response.
4883: # key is zero-based index - 0, 1, 2 ...
4884:
4885: my %first_bubble_line; # First bubble line no. for each bubble.
4886:
4887: my %subdivided_bubble_lines; # no. bubble lines for optionresponse,
4888: # matchresponse or rankresponse, where
4889: # an individual response can have multiple
4890: # lines
4891:
4892: my %responsetype_per_response; # responsetype for each response
4893:
4894: # Save and restore the bubble lines array to the form env.
4895:
4896:
4897: sub save_bubble_lines {
4898: foreach my $line (keys(%bubble_lines_per_response)) {
4899: $env{"form.scantron.bubblelines.$line"} = $bubble_lines_per_response{$line};
4900: $env{"form.scantron.first_bubble_line.$line"} =
4901: $first_bubble_line{$line};
4902: $env{"form.scantron.sub_bubblelines.$line"} =
4903: $subdivided_bubble_lines{$line};
4904: $env{"form.scantron.responsetype.$line"} =
4905: $responsetype_per_response{$line};
4906: }
4907: }
4908:
4909:
4910: sub restore_bubble_lines {
4911: my $line = 0;
4912: %bubble_lines_per_response = ();
4913: while ($env{"form.scantron.bubblelines.$line"}) {
4914: my $value = $env{"form.scantron.bubblelines.$line"};
4915: $bubble_lines_per_response{$line} = $value;
4916: $first_bubble_line{$line} =
4917: $env{"form.scantron.first_bubble_line.$line"};
4918: $subdivided_bubble_lines{$line} =
4919: $env{"form.scantron.sub_bubblelines.$line"};
4920: $responsetype_per_response{$line} =
4921: $env{"form.scantron.responsetype.$line"};
4922: $line++;
4923: }
4924: }
4925:
4926: # Given the parsed scanline, get the response for
4927: # 'answer' number n:
4928:
4929: sub get_response_bubbles {
4930: my ($parsed_line, $response) = @_;
4931:
4932: my $bubble_line = $first_bubble_line{$response-1} +1;
4933: my $bubble_lines= $bubble_lines_per_response{$response-1};
4934:
4935: my $selected = "";
4936:
4937: for (my $bline = 0; $bline < $bubble_lines; $bline++) {
4938: $selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
4939: $bubble_line++;
4940: }
4941: return $selected;
4942: }
4943:
4944: =pod
4945:
4946: =item scantron_filenames
4947:
4948: Returns a list of the scantron files in the current course
4949:
4950: =cut
4951:
4952: sub scantron_filenames {
4953: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4954: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
4955: my $getpropath = 1;
4956: my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
4957: $getpropath);
4958: my @possiblenames;
4959: foreach my $filename (sort(@files)) {
4960: ($filename)=split(/&/,$filename);
4961: if ($filename!~/^scantron_orig_/) { next ; }
4962: $filename=~s/^scantron_orig_//;
4963: push(@possiblenames,$filename);
4964: }
4965: return @possiblenames;
4966: }
4967:
4968: =pod
4969:
4970: =item scantron_uploads
4971:
4972: Returns html drop-down list of scantron files in current course.
4973:
4974: Arguments:
4975: $file2grade - filename to set as selected in the dropdown
4976:
4977: =cut
4978:
4979: sub scantron_uploads {
4980: my ($file2grade) = @_;
4981: my $result= '<select name="scantron_selectfile">';
4982: $result.="<option></option>";
4983: foreach my $filename (sort(&scantron_filenames())) {
4984: $result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
4985: }
4986: $result.="</select>";
4987: return $result;
4988: }
4989:
4990: =pod
4991:
4992: =item scantron_scantab
4993:
4994: Returns html drop down of the scantron formats in the scantronformat.tab
4995: file.
4996:
4997: =cut
4998:
4999: sub scantron_scantab {
5000: my $result='<select name="scantron_format">'."\n";
5001: $result.='<option></option>'."\n";
5002: my @lines = &get_scantronformat_file();
5003: if (@lines > 0) {
5004: foreach my $line (@lines) {
5005: next if (($line =~ /^\#/) || ($line eq ''));
5006: my ($name,$descrip)=split(/:/,$line);
5007: $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
5008: }
5009: }
5010: $result.='</select>'."\n";
5011: return $result;
5012: }
5013:
5014: =pod
5015:
5016: =item get_scantronformat_file
5017:
5018: Returns an array containing lines from the scantron format file for
5019: the domain of the course.
5020:
5021: If a url for a custom.tab file is listed in domain's configuration.db,
5022: lines are from this file.
5023:
5024: Otherwise, if a default.tab has been published in RES space by the
5025: domainconfig user, lines are from this file.
5026:
5027: Otherwise, fall back to getting lines from the legacy file on the
5028: local server: /home/httpd/lonTabs/default_scantronformat.tab
5029:
5030: =cut
5031:
5032: sub get_scantronformat_file {
5033: my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
5034: my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
5035: my $gottab = 0;
5036: my @lines;
5037: if (ref($domconfig{'scantron'}) eq 'HASH') {
5038: if ($domconfig{'scantron'}{'scantronformat'} ne '') {
5039: my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
5040: if ($formatfile ne '-1') {
5041: @lines = split("\n",$formatfile,-1);
5042: $gottab = 1;
5043: }
5044: }
5045: }
5046: if (!$gottab) {
5047: my $confname = $cdom.'-domainconfig';
5048: my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
5049: my $formatfile = &Apache::lonnet::getfile($default);
5050: if ($formatfile ne '-1') {
5051: @lines = split("\n",$formatfile,-1);
5052: $gottab = 1;
5053: }
5054: }
5055: if (!$gottab) {
5056: my @domains = &Apache::lonnet::current_machine_domains();
5057: if (grep(/^\Q$cdom\E$/,@domains)) {
5058: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
5059: @lines = <$fh>;
5060: close($fh);
5061: } else {
5062: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
5063: @lines = <$fh>;
5064: close($fh);
5065: }
5066: }
5067: return @lines;
5068: }
5069:
5070: =pod
5071:
5072: =item scantron_CODElist
5073:
5074: Returns html drop down of the saved CODE lists from current course,
5075: generated from earlier printings.
5076:
5077: =cut
5078:
5079: sub scantron_CODElist {
5080: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5081: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5082: my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
5083: my $namechoice='<option></option>';
5084: foreach my $name (sort {uc($a) cmp uc($b)} @names) {
5085: if ($name =~ /^error: 2 /) { next; }
5086: if ($name =~ /^type\0/) { next; }
5087: $namechoice.='<option value="'.$name.'">'.$name.'</option>';
5088: }
5089: $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
5090: return $namechoice;
5091: }
5092:
5093: =pod
5094:
5095: =item scantron_CODEunique
5096:
5097: Returns the html for "Each CODE to be used once" radio.
5098:
5099: =cut
5100:
5101: sub scantron_CODEunique {
5102: my $result='<span class="LC_nobreak">
5103: <label><input type="radio" name="scantron_CODEunique"
5104: value="yes" checked="checked" />'.&mt('Yes').' </label>
5105: </span>
5106: <span class="LC_nobreak">
5107: <label><input type="radio" name="scantron_CODEunique"
5108: value="no" />'.&mt('No').' </label>
5109: </span>';
5110: return $result;
5111: }
5112:
5113: =pod
5114:
5115: =item scantron_selectphase
5116:
5117: Generates the initial screen to start the bubble sheet process.
5118: Allows for - starting a grading run.
5119: - downloading existing scan data (original, corrected
5120: or skipped info)
5121:
5122: - uploading new scan data
5123:
5124: Arguments:
5125: $r - The Apache request object
5126: $file2grade - name of the file that contain the scanned data to score
5127:
5128: =cut
5129:
5130: sub scantron_selectphase {
5131: my ($r,$file2grade,$symb) = @_;
5132: if (!$symb) {return '';}
5133: my $map_error;
5134: my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
5135: if ($map_error) {
5136: $r->print('<br />'.&navmap_errormsg().'<br />');
5137: return;
5138: }
5139: my $default_form_data=&defaultFormData($symb);
5140: my $file_selector=&scantron_uploads($file2grade);
5141: my $format_selector=&scantron_scantab();
5142: my $CODE_selector=&scantron_CODElist();
5143: my $CODE_unique=&scantron_CODEunique();
5144: my $result;
5145:
5146: $ssi_error = 0;
5147:
5148: if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
5149: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
5150:
5151: # Chunk of form to prompt for a scantron file upload.
5152:
5153: $r->print('
5154: <br />
5155: '.&Apache::loncommon::start_data_table('LC_scantron_action').'
5156: '.&Apache::loncommon::start_data_table_header_row().'
5157: <th>
5158: '.&mt('Specify a bubblesheet data file to upload.').'
5159: </th>
5160: '.&Apache::loncommon::end_data_table_header_row().'
5161: '.&Apache::loncommon::start_data_table_row().'
5162: <td>
5163: ');
5164: my $default_form_data=&defaultFormData($symb);
5165: my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
5166: my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
5167: $r->print(&Apache::lonhtmlcommon::scripttag('
5168: function checkUpload(formname) {
5169: if (formname.upfile.value == "") {
5170: alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
5171: return false;
5172: }
5173: formname.submit();
5174: }'));
5175: $r->print('
5176: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
5177: '.$default_form_data.'
5178: <input name="courseid" type="hidden" value="'.$cnum.'" />
5179: <input name="domainid" type="hidden" value="'.$cdom.'" />
5180: <input name="command" value="scantronupload_save" type="hidden" />
5181: '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
5182: <br />
5183: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
5184: </form>
5185: ');
5186:
5187: $r->print('
5188: </td>
5189: '.&Apache::loncommon::end_data_table_row().'
5190: '.&Apache::loncommon::end_data_table().'
5191: ');
5192: }
5193:
5194: # Chunk of form to prompt for a file to grade and how:
5195:
5196: $result.= '
5197: <br />
5198: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
5199: <input type="hidden" name="command" value="scantron_warning" />
5200: '.$default_form_data.'
5201: '.&Apache::loncommon::start_data_table('LC_scantron_action').'
5202: '.&Apache::loncommon::start_data_table_header_row().'
5203: <th colspan="2">
5204: '.&mt('Specify file and which Folder/Sequence to grade').'
5205: </th>
5206: '.&Apache::loncommon::end_data_table_header_row().'
5207: '.&Apache::loncommon::start_data_table_row().'
5208: <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
5209: '.&Apache::loncommon::end_data_table_row().'
5210: '.&Apache::loncommon::start_data_table_row().'
5211: <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
5212: '.&Apache::loncommon::end_data_table_row().'
5213: '.&Apache::loncommon::start_data_table_row().'
5214: <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
5215: '.&Apache::loncommon::end_data_table_row().'
5216: '.&Apache::loncommon::start_data_table_row().'
5217: <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
5218: '.&Apache::loncommon::end_data_table_row().'
5219: '.&Apache::loncommon::start_data_table_row().'
5220: <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
5221: '.&Apache::loncommon::end_data_table_row().'
5222: '.&Apache::loncommon::start_data_table_row().'
5223: <td> '.&mt('Options:').' </td>
5224: <td>
5225: <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
5226: <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
5227: <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
5228: </td>
5229: '.&Apache::loncommon::end_data_table_row().'
5230: '.&Apache::loncommon::start_data_table_row().'
5231: <td colspan="2">
5232: <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
5233: </td>
5234: '.&Apache::loncommon::end_data_table_row().'
5235: '.&Apache::loncommon::end_data_table().'
5236: </form>
5237: ';
5238:
5239: $r->print($result);
5240:
5241:
5242:
5243: # Chunk of the form that prompts to view a scoring office file,
5244: # corrected file, skipped records in a file.
5245:
5246: $r->print('
5247: <br />
5248: <form action="/adm/grades" name="scantron_download">
5249: '.$default_form_data.'
5250: <input type="hidden" name="command" value="scantron_download" />
5251: '.&Apache::loncommon::start_data_table('LC_scantron_action').'
5252: '.&Apache::loncommon::start_data_table_header_row().'
5253: <th>
5254: '.&mt('Download a scoring office file').'
5255: </th>
5256: '.&Apache::loncommon::end_data_table_header_row().'
5257: '.&Apache::loncommon::start_data_table_row().'
5258: <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).'
5259: <br />
5260: <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
5261: '.&Apache::loncommon::end_data_table_row().'
5262: '.&Apache::loncommon::end_data_table().'
5263: </form>
5264: <br />
5265: ');
5266:
5267: &Apache::lonpickcode::code_list($r,2);
5268:
5269: $r->print('<br /><form method="post" name="checkscantron">'.
5270: $default_form_data."\n".
5271: &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
5272: &Apache::loncommon::start_data_table_header_row()."\n".
5273: '<th colspan="2">
5274: '.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
5275: '</th>'."\n".
5276: &Apache::loncommon::end_data_table_header_row()."\n".
5277: &Apache::loncommon::start_data_table_row()."\n".
5278: '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
5279: '<td> '.$sequence_selector.' </td>'.
5280: &Apache::loncommon::end_data_table_row()."\n".
5281: &Apache::loncommon::start_data_table_row()."\n".
5282: '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
5283: '<td> '.$file_selector.' </td>'."\n".
5284: &Apache::loncommon::end_data_table_row()."\n".
5285: &Apache::loncommon::start_data_table_row()."\n".
5286: '<td> '.&mt('Format of data file:').' </td>'."\n".
5287: '<td> '.$format_selector.' </td>'."\n".
5288: &Apache::loncommon::end_data_table_row()."\n".
5289: &Apache::loncommon::start_data_table_row()."\n".
5290: '<td> '.&mt('Options').' </td>'."\n".
5291: '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
5292: &Apache::loncommon::end_data_table_row()."\n".
5293: &Apache::loncommon::start_data_table_row()."\n".
5294: '<td colspan="2">'."\n".
5295: '<input type="hidden" name="command" value="checksubmissions" />'."\n".
5296: '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
5297: '</td>'."\n".
5298: &Apache::loncommon::end_data_table_row()."\n".
5299: &Apache::loncommon::end_data_table()."\n".
5300: '</form><br />');
5301: return;
5302: }
5303:
5304: =pod
5305:
5306: =item get_scantron_config
5307:
5308: Parse and return the scantron configuration line selected as a
5309: hash of configuration file fields.
5310:
5311: Arguments:
5312: which - the name of the configuration to parse from the file.
5313:
5314:
5315: Returns:
5316: If the named configuration is not in the file, an empty
5317: hash is returned.
5318: a hash with the fields
5319: name - internal name for the this configuration setup
5320: description - text to display to operator that describes this config
5321: CODElocation - if 0 or the string 'none'
5322: - no CODE exists for this config
5323: if -1 || the string 'letter'
5324: - a CODE exists for this config and is
5325: a string of letters
5326: Unsupported value (but planned for future support)
5327: if a positive integer
5328: - The CODE exists as the first n items from
5329: the question section of the form
5330: if the string 'number'
5331: - The CODE exists for this config and is
5332: a string of numbers
5333: CODEstart - (only matter if a CODE exists) column in the line where
5334: the CODE starts
5335: CODElength - length of the CODE
5336: IDstart - column where the student/employee ID starts
5337: IDlength - length of the student/employee ID info
5338: Qstart - column where the information from the bubbled
5339: 'questions' start
5340: Qlength - number of columns comprising a single bubble line from
5341: the sheet. (usually either 1 or 10)
5342: Qon - either a single character representing the character used
5343: to signal a bubble was chosen in the positional setup, or
5344: the string 'letter' if the letter of the chosen bubble is
5345: in the final, or 'number' if a number representing the
5346: chosen bubble is in the file (1->A 0->J)
5347: Qoff - the character used to represent that a bubble was
5348: left blank
5349: PaperID - if the scanning process generates a unique number for each
5350: sheet scanned the column that this ID number starts in
5351: PaperIDlength - number of columns that comprise the unique ID number
5352: for the sheet of paper
5353: FirstName - column that the first name starts in
5354: FirstNameLength - number of columns that the first name spans
5355:
5356: LastName - column that the last name starts in
5357: LastNameLength - number of columns that the last name spans
5358: BubblesPerRow - number of bubbles available in each row used to
5359: bubble an answer. (If not specified, 10 assumed).
5360: =cut
5361:
5362: sub get_scantron_config {
5363: my ($which) = @_;
5364: my @lines = &get_scantronformat_file();
5365: my %config;
5366: #FIXME probably should move to XML it has already gotten a bit much now
5367: foreach my $line (@lines) {
5368: my ($name,$descrip)=split(/:/,$line);
5369: if ($name ne $which ) { next; }
5370: chomp($line);
5371: my @config=split(/:/,$line);
5372: $config{'name'}=$config[0];
5373: $config{'description'}=$config[1];
5374: $config{'CODElocation'}=$config[2];
5375: $config{'CODEstart'}=$config[3];
5376: $config{'CODElength'}=$config[4];
5377: $config{'IDstart'}=$config[5];
5378: $config{'IDlength'}=$config[6];
5379: $config{'Qstart'}=$config[7];
5380: $config{'Qlength'}=$config[8];
5381: $config{'Qoff'}=$config[9];
5382: $config{'Qon'}=$config[10];
5383: $config{'PaperID'}=$config[11];
5384: $config{'PaperIDlength'}=$config[12];
5385: $config{'FirstName'}=$config[13];
5386: $config{'FirstNamelength'}=$config[14];
5387: $config{'LastName'}=$config[15];
5388: $config{'LastNamelength'}=$config[16];
5389: $config{'BubblesPerRow'}=$config[17];
5390: last;
5391: }
5392: return %config;
5393: }
5394:
5395: =pod
5396:
5397: =item username_to_idmap
5398:
5399: creates a hash keyed by student/employee ID with values of the corresponding
5400: student username:domain.
5401:
5402: Arguments:
5403:
5404: $classlist - reference to the class list hash. This is a hash
5405: keyed by student name:domain whose elements are references
5406: to arrays containing various chunks of information
5407: about the student. (See loncoursedata for more info).
5408:
5409: Returns
5410: %idmap - the constructed hash
5411:
5412: =cut
5413:
5414: sub username_to_idmap {
5415: my ($classlist)= @_;
5416: my %idmap;
5417: foreach my $student (keys(%$classlist)) {
5418: $idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
5419: $student;
5420: }
5421: return %idmap;
5422: }
5423:
5424: =pod
5425:
5426: =item scantron_fixup_scanline
5427:
5428: Process a requested correction to a scanline.
5429:
5430: Arguments:
5431: $scantron_config - hash from &get_scantron_config()
5432: $scan_data - hash of correction information
5433: (see &scantron_getfile())
5434: $line - existing scanline
5435: $whichline - line number of the passed in scanline
5436: $field - type of change to process
5437: (either
5438: 'ID' -> correct the student/employee ID
5439: 'CODE' -> correct the CODE
5440: 'answer' -> fixup the submitted answers)
5441:
5442: $args - hash of additional info,
5443: - 'ID'
5444: 'newid' -> studentID to use in replacement
5445: of existing one
5446: - 'CODE'
5447: 'CODE_ignore_dup' - set to true if duplicates
5448: should be ignored.
5449: 'CODE' - is new code or 'use_unfound'
5450: if the existing unfound code should
5451: be used as is
5452: - 'answer'
5453: 'response' - new answer or 'none' if blank
5454: 'question' - the bubble line to change
5455: 'questionnum' - the question identifier,
5456: may include subquestion.
5457:
5458: Returns:
5459: $line - the modified scanline
5460:
5461: Side effects:
5462: $scan_data - may be updated
5463:
5464: =cut
5465:
5466:
5467: sub scantron_fixup_scanline {
5468: my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
5469: if ($field eq 'ID') {
5470: if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
5471: return ($line,1,'New value too large');
5472: }
5473: if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
5474: $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
5475: $args->{'newid'});
5476: }
5477: substr($line,$$scantron_config{'IDstart'}-1,
5478: $$scantron_config{'IDlength'})=$args->{'newid'};
5479: if ($args->{'newid'}=~/^\s*$/) {
5480: &scan_data($scan_data,"$whichline.user",
5481: $args->{'username'}.':'.$args->{'domain'});
5482: }
5483: } elsif ($field eq 'CODE') {
5484: if ($args->{'CODE_ignore_dup'}) {
5485: &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
5486: }
5487: &scan_data($scan_data,"$whichline.useCODE",'1');
5488: if ($args->{'CODE'} ne 'use_unfound') {
5489: if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
5490: return ($line,1,'New CODE value too large');
5491: }
5492: if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
5493: $args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
5494: }
5495: substr($line,$$scantron_config{'CODEstart'}-1,
5496: $$scantron_config{'CODElength'})=$args->{'CODE'};
5497: }
5498: } elsif ($field eq 'answer') {
5499: my $length=$scantron_config->{'Qlength'};
5500: my $off=$scantron_config->{'Qoff'};
5501: my $on=$scantron_config->{'Qon'};
5502: my $answer=${off}x$length;
5503: if ($args->{'response'} eq 'none') {
5504: &scan_data($scan_data,
5505: "$whichline.no_bubble.".$args->{'questionnum'},'1');
5506: } else {
5507: if ($on eq 'letter') {
5508: my @alphabet=('A'..'Z');
5509: $answer=$alphabet[$args->{'response'}];
5510: } elsif ($on eq 'number') {
5511: $answer=$args->{'response'}+1;
5512: if ($answer == 10) { $answer = '0'; }
5513: } else {
5514: substr($answer,$args->{'response'},1)=$on;
5515: }
5516: &scan_data($scan_data,
5517: "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
5518: }
5519: my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
5520: substr($line,$where-1,$length)=$answer;
5521: }
5522: return $line;
5523: }
5524:
5525: =pod
5526:
5527: =item scan_data
5528:
5529: Edit or look up an item in the scan_data hash.
5530:
5531: Arguments:
5532: $scan_data - The hash (see scantron_getfile)
5533: $key - shorthand of the key to edit (actual key is
5534: scantronfilename_key).
5535: $data - New value of the hash entry.
5536: $delete - If true, the entry is removed from the hash.
5537:
5538: Returns:
5539: The new value of the hash table field (undefined if deleted).
5540:
5541: =cut
5542:
5543:
5544: sub scan_data {
5545: my ($scan_data,$key,$value,$delete)=@_;
5546: my $filename=$env{'form.scantron_selectfile'};
5547: if (defined($value)) {
5548: $scan_data->{$filename.'_'.$key} = $value;
5549: }
5550: if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
5551: return $scan_data->{$filename.'_'.$key};
5552: }
5553:
5554: # ----- These first few routines are general use routines.----
5555:
5556: # Return the number of occurences of a pattern in a string.
5557:
5558: sub occurence_count {
5559: my ($string, $pattern) = @_;
5560:
5561: my @matches = ($string =~ /$pattern/g);
5562:
5563: return scalar(@matches);
5564: }
5565:
5566:
5567: # Take a string known to have digits and convert all the
5568: # digits into letters in the range J,A..I.
5569:
5570: sub digits_to_letters {
5571: my ($input) = @_;
5572:
5573: my @alphabet = ('J', 'A'..'I');
5574:
5575: my @input = split(//, $input);
5576: my $output ='';
5577: for (my $i = 0; $i < scalar(@input); $i++) {
5578: if ($input[$i] =~ /\d/) {
5579: $output .= $alphabet[$input[$i]];
5580: } else {
5581: $output .= $input[$i];
5582: }
5583: }
5584: return $output;
5585: }
5586:
5587: =pod
5588:
5589: =item scantron_parse_scanline
5590:
5591: Decodes a scanline from the selected scantron file
5592:
5593: Arguments:
5594: line - The text of the scantron file line to process
5595: whichline - Line number
5596: scantron_config - Hash describing the format of the scantron lines.
5597: scan_data - Hash of extra information about the scanline
5598: (see scantron_getfile for more information)
5599: just_header - True if should not process question answers but only
5600: the stuff to the left of the answers.
5601: Returns:
5602: Hash containing the result of parsing the scanline
5603:
5604: Keys are all proceeded by the string 'scantron.'
5605:
5606: CODE - the CODE in use for this scanline
5607: useCODE - 1 if the CODE is invalid but it usage has been forced
5608: by the operator
5609: CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
5610: CODEs were selected, but the usage has been
5611: forced by the operator
5612: ID - student/employee ID
5613: PaperID - if used, the ID number printed on the sheet when the
5614: paper was scanned
5615: FirstName - first name from the sheet
5616: LastName - last name from the sheet
5617:
5618: if just_header was not true these key may also exist
5619:
5620: missingerror - a list of bubble ranges that are considered to be answers
5621: to a single question that don't have any bubbles filled in.
5622: Of the form questionnumber:firstbubblenumber:count.
5623: doubleerror - a list of bubble ranges that are considered to be answers
5624: to a single question that have more than one bubble filled in.
5625: Of the form questionnumber::firstbubblenumber:count
5626:
5627: In the above, count is the number of bubble responses in the
5628: input line needed to represent the possible answers to the question.
5629: e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
5630: per line would have count = 2.
5631:
5632: maxquest - the number of the last bubble line that was parsed
5633:
5634: (<number> starts at 1)
5635: <number>.answer - zero or more letters representing the selected
5636: letters from the scanline for the bubble line
5637: <number>.
5638: if blank there was either no bubble or there where
5639: multiple bubbles, (consult the keys missingerror and
5640: doubleerror if this is an error condition)
5641:
5642: =cut
5643:
5644: sub scantron_parse_scanline {
5645: my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
5646:
5647: my %record;
5648: my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
5649: my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos); # Answers
5650: my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # earlier stuff
5651: if (!($$scantron_config{'CODElocation'} eq 0 ||
5652: $$scantron_config{'CODElocation'} eq 'none')) {
5653: if ($$scantron_config{'CODElocation'} < 0 ||
5654: $$scantron_config{'CODElocation'} eq 'letter' ||
5655: $$scantron_config{'CODElocation'} eq 'number') {
5656: $record{'scantron.CODE'}=substr($data,
5657: $$scantron_config{'CODEstart'}-1,
5658: $$scantron_config{'CODElength'});
5659: if (&scan_data($scan_data,"$whichline.useCODE")) {
5660: $record{'scantron.useCODE'}=1;
5661: }
5662: if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
5663: $record{'scantron.CODE_ignore_dup'}=1;
5664: }
5665: } else {
5666: #FIXME interpret first N questions
5667: }
5668: }
5669: $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
5670: $$scantron_config{'IDlength'});
5671: $record{'scantron.PaperID'}=
5672: substr($data,$$scantron_config{'PaperID'}-1,
5673: $$scantron_config{'PaperIDlength'});
5674: $record{'scantron.FirstName'}=
5675: substr($data,$$scantron_config{'FirstName'}-1,
5676: $$scantron_config{'FirstNamelength'});
5677: $record{'scantron.LastName'}=
5678: substr($data,$$scantron_config{'LastName'}-1,
5679: $$scantron_config{'LastNamelength'});
5680: if ($just_header) { return \%record; }
5681:
5682: my @alphabet=('A'..'Z');
5683: my $questnum=0;
5684: my $ansnum =1; # Multiple 'answer lines'/question.
5685:
5686: chomp($questions); # Get rid of any trailing \n.
5687: $questions =~ s/\r$//; # Get rid of trailing \r too (MAC or Win uploads).
5688: while (length($questions)) {
5689: my $answers_needed = $bubble_lines_per_response{$questnum};
5690: my $answer_length = ($$scantron_config{'Qlength'} * $answers_needed)
5691: || 1;
5692: $questnum++;
5693: my $quest_id = $questnum;
5694: my $currentquest = substr($questions,0,$answer_length);
5695: $questions = substr($questions,$answer_length);
5696: if (length($currentquest) < $answer_length) { next; }
5697:
5698: if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
5699: my $subquestnum = 1;
5700: my $subquestions = $currentquest;
5701: my @subanswers_needed =
5702: split(/,/,$subdivided_bubble_lines{$questnum-1});
5703: foreach my $subans (@subanswers_needed) {
5704: my $subans_length =
5705: ($$scantron_config{'Qlength'} * $subans) || 1;
5706: my $currsubquest = substr($subquestions,0,$subans_length);
5707: $subquestions = substr($subquestions,$subans_length);
5708: $quest_id = "$questnum.$subquestnum";
5709: if (($$scantron_config{'Qon'} eq 'letter') ||
5710: ($$scantron_config{'Qon'} eq 'number')) {
5711: $ansnum = &scantron_validator_lettnum($ansnum,
5712: $questnum,$quest_id,$subans,$currsubquest,$whichline,
5713: \@alphabet,\%record,$scantron_config,$scan_data);
5714: } else {
5715: $ansnum = &scantron_validator_positional($ansnum,
5716: $questnum,$quest_id,$subans,$currsubquest,$whichline, \@alphabet,\%record,$scantron_config,$scan_data);
5717: }
5718: $subquestnum ++;
5719: }
5720: } else {
5721: if (($$scantron_config{'Qon'} eq 'letter') ||
5722: ($$scantron_config{'Qon'} eq 'number')) {
5723: $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
5724: $quest_id,$answers_needed,$currentquest,$whichline,
5725: \@alphabet,\%record,$scantron_config,$scan_data);
5726: } else {
5727: $ansnum = &scantron_validator_positional($ansnum,$questnum,
5728: $quest_id,$answers_needed,$currentquest,$whichline,
5729: \@alphabet,\%record,$scantron_config,$scan_data);
5730: }
5731: }
5732: }
5733: $record{'scantron.maxquest'}=$questnum;
5734: return \%record;
5735: }
5736:
5737: sub scantron_validator_lettnum {
5738: my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
5739: $alphabet,$record,$scantron_config,$scan_data) = @_;
5740:
5741: # Qon 'letter' implies for each slot in currquest we have:
5742: # ? or * for doubles, a letter in A-Z for a bubble, and
5743: # about anything else (esp. a value of Qoff) for missing
5744: # bubbles.
5745: #
5746: # Qon 'number' implies each slot gives a digit that indexes the
5747: # bubbles filled, or Qoff, or a non-number for unbubbled lines,
5748: # and * or ? for double bubbles on a single line.
5749: #
5750:
5751: my $matchon;
5752: if ($$scantron_config{'Qon'} eq 'letter') {
5753: $matchon = '[A-Z]';
5754: } elsif ($$scantron_config{'Qon'} eq 'number') {
5755: $matchon = '\d';
5756: }
5757: my $occurrences = 0;
5758: if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
5759: ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
5760: ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
5761: ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
5762: ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
5763: ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
5764: my @singlelines = split('',$currquest);
5765: foreach my $entry (@singlelines) {
5766: $occurrences = &occurence_count($entry,$matchon);
5767: if ($occurrences > 1) {
5768: last;
5769: }
5770: }
5771: } else {
5772: $occurrences = &occurence_count($currquest,$matchon);
5773: }
5774: if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
5775: push(@{$record->{'scantron.doubleerror'}},$quest_id);
5776: for (my $ans=0; $ans<$answers_needed; $ans++) {
5777: my $bubble = substr($currquest,$ans,1);
5778: if ($bubble =~ /$matchon/ ) {
5779: if ($$scantron_config{'Qon'} eq 'number') {
5780: if ($bubble == 0) {
5781: $bubble = 10;
5782: }
5783: $record->{"scantron.$ansnum.answer"} =
5784: $alphabet->[$bubble-1];
5785: } else {
5786: $record->{"scantron.$ansnum.answer"} = $bubble;
5787: }
5788: } else {
5789: $record->{"scantron.$ansnum.answer"}='';
5790: }
5791: $ansnum++;
5792: }
5793: } elsif (!defined($currquest)
5794: || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
5795: || (&occurence_count($currquest,$matchon) == 0)) {
5796: for (my $ans=0; $ans<$answers_needed; $ans++ ) {
5797: $record->{"scantron.$ansnum.answer"}='';
5798: $ansnum++;
5799: }
5800: if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
5801: push(@{$record->{'scantron.missingerror'}},$quest_id);
5802: }
5803: } else {
5804: if ($$scantron_config{'Qon'} eq 'number') {
5805: $currquest = &digits_to_letters($currquest);
5806: }
5807: for (my $ans=0; $ans<$answers_needed; $ans++) {
5808: my $bubble = substr($currquest,$ans,1);
5809: $record->{"scantron.$ansnum.answer"} = $bubble;
5810: $ansnum++;
5811: }
5812: }
5813: return $ansnum;
5814: }
5815:
5816: sub scantron_validator_positional {
5817: my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
5818: $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
5819:
5820: # Otherwise there's a positional notation;
5821: # each bubble line requires Qlength items, and there are filled in
5822: # bubbles for each case where there 'Qon' characters.
5823: #
5824:
5825: my @array=split($$scantron_config{'Qon'},$currquest,-1);
5826:
5827: # If the split only gives us one element.. the full length of the
5828: # answer string, no bubbles are filled in:
5829:
5830: if ($answers_needed eq '') {
5831: return;
5832: }
5833:
5834: if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
5835: for (my $ans=0; $ans<$answers_needed; $ans++ ) {
5836: $record->{"scantron.$ansnum.answer"}='';
5837: $ansnum++;
5838: }
5839: if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
5840: push(@{$record->{"scantron.missingerror"}},$quest_id);
5841: }
5842: } elsif (scalar(@array) == 2) {
5843: my $location = length($array[0]);
5844: my $line_num = int($location / $$scantron_config{'Qlength'});
5845: my $bubble = $alphabet->[$location % $$scantron_config{'Qlength'}];
5846: for (my $ans=0; $ans<$answers_needed; $ans++) {
5847: if ($ans eq $line_num) {
5848: $record->{"scantron.$ansnum.answer"} = $bubble;
5849: } else {
5850: $record->{"scantron.$ansnum.answer"} = ' ';
5851: }
5852: $ansnum++;
5853: }
5854: } else {
5855: # If there's more than one instance of a bubble character
5856: # That's a double bubble; with positional notation we can
5857: # record all the bubbles filled in as well as the
5858: # fact this response consists of multiple bubbles.
5859: #
5860: if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
5861: ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
5862: ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
5863: ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
5864: ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
5865: ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
5866: my $doubleerror = 0;
5867: while (($currquest >= $$scantron_config{'Qlength'}) &&
5868: (!$doubleerror)) {
5869: my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
5870: $currquest = substr($currquest,$$scantron_config{'Qlength'});
5871: my @currarray = split($$scantron_config{'Qon'},$currline,-1);
5872: if (length(@currarray) > 2) {
5873: $doubleerror = 1;
5874: }
5875: }
5876: if ($doubleerror) {
5877: push(@{$record->{'scantron.doubleerror'}},$quest_id);
5878: }
5879: } else {
5880: push(@{$record->{'scantron.doubleerror'}},$quest_id);
5881: }
5882: my $item = $ansnum;
5883: for (my $ans=0; $ans<$answers_needed; $ans++) {
5884: $record->{"scantron.$item.answer"} = '';
5885: $item ++;
5886: }
5887:
5888: my @ans=@array;
5889: my $i=0;
5890: my $increment = 0;
5891: while ($#ans) {
5892: $i+=length($ans[0]) + $increment;
5893: my $line = int($i/$$scantron_config{'Qlength'} + $ansnum);
5894: my $bubble = $i%$$scantron_config{'Qlength'};
5895: $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
5896: shift(@ans);
5897: $increment = 1;
5898: }
5899: $ansnum += $answers_needed;
5900: }
5901: return $ansnum;
5902: }
5903:
5904: =pod
5905:
5906: =item scantron_add_delay
5907:
5908: Adds an error message that occurred during the grading phase to a
5909: queue of messages to be shown after grading pass is complete
5910:
5911: Arguments:
5912: $delayqueue - arrary ref of hash ref of error messages
5913: $scanline - the scanline that caused the error
5914: $errormesage - the error message
5915: $errorcode - a numeric code for the error
5916:
5917: Side Effects:
5918: updates the $delayqueue to have a new hash ref of the error
5919:
5920: =cut
5921:
5922: sub scantron_add_delay {
5923: my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
5924: push(@$delayqueue,
5925: {'line' => $scanline, 'emsg' => $errormessage,
5926: 'ecode' => $errorcode }
5927: );
5928: }
5929:
5930: =pod
5931:
5932: =item scantron_find_student
5933:
5934: Finds the username for the current scanline
5935:
5936: Arguments:
5937: $scantron_record - hash result from scantron_parse_scanline
5938: $scan_data - hash of correction information
5939: (see &scantron_getfile() form more information)
5940: $idmap - hash from &username_to_idmap()
5941: $line - number of current scanline
5942:
5943: Returns:
5944: Either 'username:domain' or undef if unknown
5945:
5946: =cut
5947:
5948: sub scantron_find_student {
5949: my ($scantron_record,$scan_data,$idmap,$line)=@_;
5950: my $scanID=$$scantron_record{'scantron.ID'};
5951: if ($scanID =~ /^\s*$/) {
5952: return &scan_data($scan_data,"$line.user");
5953: }
5954: foreach my $id (keys(%$idmap)) {
5955: if (lc($id) eq lc($scanID)) {
5956: return $$idmap{$id};
5957: }
5958: }
5959: return undef;
5960: }
5961:
5962: =pod
5963:
5964: =item scantron_filter
5965:
5966: Filter sub for lonnavmaps, filters out hidden resources if ignore
5967: hidden resources was selected
5968:
5969: =cut
5970:
5971: sub scantron_filter {
5972: my ($curres)=@_;
5973:
5974: if (ref($curres) && $curres->is_problem()) {
5975: # if the user has asked to not have either hidden
5976: # or 'randomout' controlled resources to be graded
5977: # don't include them
5978: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
5979: && $curres->randomout) {
5980: return 0;
5981: }
5982: return 1;
5983: }
5984: return 0;
5985: }
5986:
5987: =pod
5988:
5989: =item scantron_process_corrections
5990:
5991: Gets correction information out of submitted form data and corrects
5992: the scanline
5993:
5994: =cut
5995:
5996: sub scantron_process_corrections {
5997: my ($r) = @_;
5998: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
5999: my ($scanlines,$scan_data)=&scantron_getfile();
6000: my $classlist=&Apache::loncoursedata::get_classlist();
6001: my $which=$env{'form.scantron_line'};
6002: my $line=&scantron_get_line($scanlines,$scan_data,$which);
6003: my ($skip,$err,$errmsg);
6004: if ($env{'form.scantron_skip_record'}) {
6005: $skip=1;
6006: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
6007: my $newstudent=$env{'form.scantron_username'}.':'.
6008: $env{'form.scantron_domain'};
6009: my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
6010: ($line,$err,$errmsg)=
6011: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
6012: 'ID',{'newid'=>$newid,
6013: 'username'=>$env{'form.scantron_username'},
6014: 'domain'=>$env{'form.scantron_domain'}});
6015: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
6016: my $resolution=$env{'form.scantron_CODE_resolution'};
6017: my $newCODE;
6018: my %args;
6019: if ($resolution eq 'use_unfound') {
6020: $newCODE='use_unfound';
6021: } elsif ($resolution eq 'use_found') {
6022: $newCODE=$env{'form.scantron_CODE_selectedvalue'};
6023: } elsif ($resolution eq 'use_typed') {
6024: $newCODE=$env{'form.scantron_CODE_newvalue'};
6025: } elsif ($resolution =~ /^use_closest_(\d+)/) {
6026: $newCODE=$env{"form.scantron_CODE_closest_$1"};
6027: }
6028: if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
6029: $args{'CODE_ignore_dup'}=1;
6030: }
6031: $args{'CODE'}=$newCODE;
6032: ($line,$err,$errmsg)=
6033: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
6034: 'CODE',\%args);
6035: } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
6036: foreach my $question (split(',',$env{'form.scantron_questions'})) {
6037: ($line,$err,$errmsg)=
6038: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
6039: $which,'answer',
6040: { 'question'=>$question,
6041: 'response'=>$env{"form.scantron_correct_Q_$question"},
6042: 'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
6043: if ($err) { last; }
6044: }
6045: }
6046: if ($err) {
6047: $r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
6048: } else {
6049: &scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
6050: &scantron_putfile($scanlines,$scan_data);
6051: }
6052: }
6053:
6054: =pod
6055:
6056: =item reset_skipping_status
6057:
6058: Forgets the current set of remember skipped scanlines (and thus
6059: reverts back to considering all lines in the
6060: scantron_skipped_<filename> file)
6061:
6062: =cut
6063:
6064: sub reset_skipping_status {
6065: my ($scanlines,$scan_data)=&scantron_getfile();
6066: &scan_data($scan_data,'remember_skipping',undef,1);
6067: &scantron_putfile(undef,$scan_data);
6068: }
6069:
6070: =pod
6071:
6072: =item start_skipping
6073:
6074: Marks a scanline to be skipped.
6075:
6076: =cut
6077:
6078: sub start_skipping {
6079: my ($scan_data,$i)=@_;
6080: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
6081: if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
6082: $remembered{$i}=2;
6083: } else {
6084: $remembered{$i}=1;
6085: }
6086: &scan_data($scan_data,'remember_skipping',join(':',%remembered));
6087: }
6088:
6089: =pod
6090:
6091: =item should_be_skipped
6092:
6093: Checks whether a scanline should be skipped.
6094:
6095: =cut
6096:
6097: sub should_be_skipped {
6098: my ($scanlines,$scan_data,$i)=@_;
6099: if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
6100: # not redoing old skips
6101: if ($scanlines->{'skipped'}[$i]) { return 1; }
6102: return 0;
6103: }
6104: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
6105:
6106: if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
6107: return 0;
6108: }
6109: return 1;
6110: }
6111:
6112: =pod
6113:
6114: =item remember_current_skipped
6115:
6116: Discovers what scanlines are in the scantron_skipped_<filename>
6117: file and remembers them into scan_data for later use.
6118:
6119: =cut
6120:
6121: sub remember_current_skipped {
6122: my ($scanlines,$scan_data)=&scantron_getfile();
6123: my %to_remember;
6124: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6125: if ($scanlines->{'skipped'}[$i]) {
6126: $to_remember{$i}=1;
6127: }
6128: }
6129:
6130: &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
6131: &scantron_putfile(undef,$scan_data);
6132: }
6133:
6134: =pod
6135:
6136: =item check_for_error
6137:
6138: Checks if there was an error when attempting to remove a specific
6139: scantron_.. bubble sheet data file. Prints out an error if
6140: something went wrong.
6141:
6142: =cut
6143:
6144: sub check_for_error {
6145: my ($r,$result)=@_;
6146: if ($result ne 'ok' && $result ne 'not_found' ) {
6147: $r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
6148: }
6149: }
6150:
6151: =pod
6152:
6153: =item scantron_warning_screen
6154:
6155: Interstitial screen to make sure the operator has selected the
6156: correct options before we start the validation phase.
6157:
6158: =cut
6159:
6160: sub scantron_warning_screen {
6161: my ($button_text)=@_;
6162: my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
6163: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6164: my $CODElist;
6165: if ($scantron_config{'CODElocation'} &&
6166: $scantron_config{'CODEstart'} &&
6167: $scantron_config{'CODElength'}) {
6168: $CODElist=$env{'form.scantron_CODElist'};
6169: if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
6170: $CODElist=
6171: '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
6172: $env{'form.scantron_CODElist'}.'</tt></td></tr>';
6173: }
6174: return ('
6175: <p>
6176: <span class="LC_warning">
6177: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
6178: </p>
6179: <table>
6180: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
6181: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
6182: '.$CODElist.'
6183: </table>
6184: <br />
6185: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
6186: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
6187:
6188: <br />
6189: ');
6190: }
6191:
6192: =pod
6193:
6194: =item scantron_do_warning
6195:
6196: Check if the operator has picked something for all required
6197: fields. Error out if something is missing.
6198:
6199: =cut
6200:
6201: sub scantron_do_warning {
6202: my ($r,$symb)=@_;
6203: if (!$symb) {return '';}
6204: my $default_form_data=&defaultFormData($symb);
6205: $r->print(&scantron_form_start().$default_form_data);
6206: if ( $env{'form.selectpage'} eq '' ||
6207: $env{'form.scantron_selectfile'} eq '' ||
6208: $env{'form.scantron_format'} eq '' ) {
6209: $r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
6210: if ( $env{'form.selectpage'} eq '') {
6211: $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
6212: }
6213: if ( $env{'form.scantron_selectfile'} eq '') {
6214: $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
6215: }
6216: if ( $env{'form.scantron_format'} eq '') {
6217: $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
6218: }
6219: } else {
6220: my $warning=&scantron_warning_screen('Grading: Validate Records');
6221: $r->print('
6222: '.$warning.'
6223: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
6224: <input type="hidden" name="command" value="scantron_validate" />
6225: ');
6226: }
6227: $r->print("</form><br />");
6228: return '';
6229: }
6230:
6231: =pod
6232:
6233: =item scantron_form_start
6234:
6235: html hidden input for remembering all selected grading options
6236:
6237: =cut
6238:
6239: sub scantron_form_start {
6240: my ($max_bubble)=@_;
6241: my $result= <<SCANTRONFORM;
6242: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
6243: <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
6244: <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
6245: <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
6246: <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
6247: <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
6248: <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
6249: <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
6250: <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
6251: <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
6252: SCANTRONFORM
6253:
6254: my $line = 0;
6255: while (defined($env{"form.scantron.bubblelines.$line"})) {
6256: my $chunk =
6257: '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
6258: $chunk .=
6259: '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
6260: $chunk .=
6261: '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
6262: $chunk .=
6263: '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
6264: $result .= $chunk;
6265: $line++;
6266: }
6267: return $result;
6268: }
6269:
6270: =pod
6271:
6272: =item scantron_validate_file
6273:
6274: Dispatch routine for doing validation of a bubble sheet data file.
6275:
6276: Also processes any necessary information resets that need to
6277: occur before validation begins (ignore previous corrections,
6278: restarting the skipped records processing)
6279:
6280: =cut
6281:
6282: sub scantron_validate_file {
6283: my ($r,$symb) = @_;
6284: if (!$symb) {return '';}
6285: my $default_form_data=&defaultFormData($symb);
6286:
6287: # do the detection of only doing skipped records first befroe we delete
6288: # them when doing the corrections reset
6289: if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
6290: &reset_skipping_status();
6291: }
6292: if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
6293: &remember_current_skipped();
6294: $env{'form.scantron_options_redo'}='redo_skipped_ready';
6295: }
6296:
6297: if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
6298: &check_for_error($r,&scantron_remove_file('corrected'));
6299: &check_for_error($r,&scantron_remove_file('skipped'));
6300: &check_for_error($r,&scantron_remove_scan_data());
6301: $env{'form.scantron_options_ignore'}='done';
6302: }
6303:
6304: if ($env{'form.scantron_corrections'}) {
6305: &scantron_process_corrections($r);
6306: }
6307: $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
6308: #get the student pick code ready
6309: $r->print(&Apache::loncommon::studentbrowser_javascript());
6310: my $nav_error;
6311: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6312: my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
6313: if ($nav_error) {
6314: $r->print(&navmap_errormsg());
6315: return '';
6316: }
6317: my $result=&scantron_form_start($max_bubble).$default_form_data;
6318: $r->print($result);
6319:
6320: my @validate_phases=( 'sequence',
6321: 'ID',
6322: 'CODE',
6323: 'doublebubble',
6324: 'missingbubbles');
6325: if (!$env{'form.validatepass'}) {
6326: $env{'form.validatepass'} = 0;
6327: }
6328: my $currentphase=$env{'form.validatepass'};
6329:
6330:
6331: my $stop=0;
6332: while (!$stop && $currentphase < scalar(@validate_phases)) {
6333: $r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
6334: $r->rflush();
6335: my $which="scantron_validate_".$validate_phases[$currentphase];
6336: {
6337: no strict 'refs';
6338: ($stop,$currentphase)=&$which($r,$currentphase);
6339: }
6340: }
6341: if (!$stop) {
6342: my $warning=&scantron_warning_screen('Start Grading');
6343: $r->print(&mt('Validation process complete.').'<br />'.
6344: $warning.
6345: &mt('Perform verification for each student after storage of submissions?').
6346: ' <span class="LC_nobreak"><label>'.
6347: '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
6348: (' 'x3).'<label>'.
6349: '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
6350: '</label></span><br />'.
6351: &mt('Grading will take longer if you use verification.').'<br />'.
6352: &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
6353: '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
6354: '<input type="hidden" name="command" value="scantron_process" />'."\n");
6355: } else {
6356: $r->print('<input type="hidden" name="command" value="scantron_validate" />');
6357: $r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
6358: }
6359: if ($stop) {
6360: if ($validate_phases[$currentphase] eq 'sequence') {
6361: $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' → " />');
6362: $r->print(' '.&mt('this error').' <br />');
6363:
6364: $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
6365: } else {
6366: if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
6367: $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' →" onclick="javascript:verify_bubble_radio(this.form)" />');
6368: } else {
6369: $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' →" />');
6370: }
6371: $r->print(' '.&mt('using corrected info').' <br />');
6372: $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
6373: $r->print(" ".&mt("this scanline saving it for later."));
6374: }
6375: }
6376: $r->print(" </form><br />");
6377: return '';
6378: }
6379:
6380:
6381: =pod
6382:
6383: =item scantron_remove_file
6384:
6385: Removes the requested bubble sheet data file, makes sure that
6386: scantron_original_<filename> is never removed
6387:
6388:
6389: =cut
6390:
6391: sub scantron_remove_file {
6392: my ($which)=@_;
6393: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6394: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6395: my $file='scantron_';
6396: if ($which eq 'corrected' || $which eq 'skipped') {
6397: $file.=$which.'_';
6398: } else {
6399: return 'refused';
6400: }
6401: $file.=$env{'form.scantron_selectfile'};
6402: return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
6403: }
6404:
6405:
6406: =pod
6407:
6408: =item scantron_remove_scan_data
6409:
6410: Removes all scan_data correction for the requested bubble sheet
6411: data file. (In the case that both the are doing skipped records we need
6412: to remember the old skipped lines for the time being so that element
6413: persists for a while.)
6414:
6415: =cut
6416:
6417: sub scantron_remove_scan_data {
6418: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6419: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6420: my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
6421: my @todelete;
6422: my $filename=$env{'form.scantron_selectfile'};
6423: foreach my $key (@keys) {
6424: if ($key=~/^\Q$filename\E_/) {
6425: if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
6426: $key=~/remember_skipping/) {
6427: next;
6428: }
6429: push(@todelete,$key);
6430: }
6431: }
6432: my $result;
6433: if (@todelete) {
6434: $result = &Apache::lonnet::del('nohist_scantrondata',
6435: \@todelete,$cdom,$cname);
6436: } else {
6437: $result = 'ok';
6438: }
6439: return $result;
6440: }
6441:
6442:
6443: =pod
6444:
6445: =item scantron_getfile
6446:
6447: Fetches the requested bubble sheet data file (all 3 versions), and
6448: the scan_data hash
6449:
6450: Arguments:
6451: None
6452:
6453: Returns:
6454: 2 hash references
6455:
6456: - first one has
6457: orig -
6458: corrected -
6459: skipped - each of which points to an array ref of the specified
6460: file broken up into individual lines
6461: count - number of scanlines
6462:
6463: - second is the scan_data hash possible keys are
6464: ($number refers to scanline numbered $number and thus the key affects
6465: only that scanline
6466: $bubline refers to the specific bubble line element and the aspects
6467: refers to that specific bubble line element)
6468:
6469: $number.user - username:domain to use
6470: $number.CODE_ignore_dup
6471: - ignore the duplicate CODE error
6472: $number.useCODE
6473: - use the CODE in the scanline as is
6474: $number.no_bubble.$bubline
6475: - it is valid that there is no bubbled in bubble
6476: at $number $bubline
6477: remember_skipping
6478: - a frozen hash containing keys of $number and values
6479: of either
6480: 1 - we are on a 'do skipped records pass' and plan
6481: on processing this line
6482: 2 - we are on a 'do skipped records pass' and this
6483: scanline has been marked to skip yet again
6484:
6485: =cut
6486:
6487: sub scantron_getfile {
6488: #FIXME really would prefer a scantron directory
6489: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6490: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6491: my $lines;
6492: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
6493: 'scantron_orig_'.$env{'form.scantron_selectfile'});
6494: my %scanlines;
6495: $scanlines{'orig'}=[(split("\n",$lines,-1))];
6496: my $temp=$scanlines{'orig'};
6497: $scanlines{'count'}=$#$temp;
6498:
6499: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
6500: 'scantron_corrected_'.$env{'form.scantron_selectfile'});
6501: if ($lines eq '-1') {
6502: $scanlines{'corrected'}=[];
6503: } else {
6504: $scanlines{'corrected'}=[(split("\n",$lines,-1))];
6505: }
6506: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
6507: 'scantron_skipped_'.$env{'form.scantron_selectfile'});
6508: if ($lines eq '-1') {
6509: $scanlines{'skipped'}=[];
6510: } else {
6511: $scanlines{'skipped'}=[(split("\n",$lines,-1))];
6512: }
6513: my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
6514: if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
6515: my %scan_data = @tmp;
6516: return (\%scanlines,\%scan_data);
6517: }
6518:
6519: =pod
6520:
6521: =item lonnet_putfile
6522:
6523: Wrapper routine to call &Apache::lonnet::finishuserfileupload
6524:
6525: Arguments:
6526: $contents - data to store
6527: $filename - filename to store $contents into
6528:
6529: Returns:
6530: result value from &Apache::lonnet::finishuserfileupload
6531:
6532: =cut
6533:
6534: sub lonnet_putfile {
6535: my ($contents,$filename)=@_;
6536: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
6537: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6538: $env{'form.sillywaytopassafilearound'}=$contents;
6539: &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
6540:
6541: }
6542:
6543: =pod
6544:
6545: =item scantron_putfile
6546:
6547: Stores the current version of the bubble sheet data files, and the
6548: scan_data hash. (Does not modify the original version only the
6549: corrected and skipped versions.
6550:
6551: Arguments:
6552: $scanlines - hash ref that looks like the first return value from
6553: &scantron_getfile()
6554: $scan_data - hash ref that looks like the second return value from
6555: &scantron_getfile()
6556:
6557: =cut
6558:
6559: sub scantron_putfile {
6560: my ($scanlines,$scan_data) = @_;
6561: #FIXME really would prefer a scantron directory
6562: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6563: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6564: if ($scanlines) {
6565: my $prefix='scantron_';
6566: # no need to update orig, shouldn't change
6567: # &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
6568: # $env{'form.scantron_selectfile'});
6569: &lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
6570: $prefix.'corrected_'.
6571: $env{'form.scantron_selectfile'});
6572: &lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
6573: $prefix.'skipped_'.
6574: $env{'form.scantron_selectfile'});
6575: }
6576: &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
6577: }
6578:
6579: =pod
6580:
6581: =item scantron_get_line
6582:
6583: Returns the correct version of the scanline
6584:
6585: Arguments:
6586: $scanlines - hash ref that looks like the first return value from
6587: &scantron_getfile()
6588: $scan_data - hash ref that looks like the second return value from
6589: &scantron_getfile()
6590: $i - number of the requested line (starts at 0)
6591:
6592: Returns:
6593: A scanline, (either the original or the corrected one if it
6594: exists), or undef if the requested scanline should be
6595: skipped. (Either because it's an skipped scanline, or it's an
6596: unskipped scanline and we are not doing a 'do skipped scanlines'
6597: pass.
6598:
6599: =cut
6600:
6601: sub scantron_get_line {
6602: my ($scanlines,$scan_data,$i)=@_;
6603: if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
6604: #if ($scanlines->{'skipped'}[$i]) { return undef; }
6605: if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
6606: return $scanlines->{'orig'}[$i];
6607: }
6608:
6609: =pod
6610:
6611: =item scantron_todo_count
6612:
6613: Counts the number of scanlines that need processing.
6614:
6615: Arguments:
6616: $scanlines - hash ref that looks like the first return value from
6617: &scantron_getfile()
6618: $scan_data - hash ref that looks like the second return value from
6619: &scantron_getfile()
6620:
6621: Returns:
6622: $count - number of scanlines to process
6623:
6624: =cut
6625:
6626: sub get_todo_count {
6627: my ($scanlines,$scan_data)=@_;
6628: my $count=0;
6629: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6630: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6631: if ($line=~/^[\s\cz]*$/) { next; }
6632: $count++;
6633: }
6634: return $count;
6635: }
6636:
6637: =pod
6638:
6639: =item scantron_put_line
6640:
6641: Updates the 'corrected' or 'skipped' versions of the bubble sheet
6642: data file.
6643:
6644: Arguments:
6645: $scanlines - hash ref that looks like the first return value from
6646: &scantron_getfile()
6647: $scan_data - hash ref that looks like the second return value from
6648: &scantron_getfile()
6649: $i - line number to update
6650: $newline - contents of the updated scanline
6651: $skip - if true make the line for skipping and update the
6652: 'skipped' file
6653:
6654: =cut
6655:
6656: sub scantron_put_line {
6657: my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
6658: if ($skip) {
6659: $scanlines->{'skipped'}[$i]=$newline;
6660: &start_skipping($scan_data,$i);
6661: return;
6662: }
6663: $scanlines->{'corrected'}[$i]=$newline;
6664: }
6665:
6666: =pod
6667:
6668: =item scantron_clear_skip
6669:
6670: Remove a line from the 'skipped' file
6671:
6672: Arguments:
6673: $scanlines - hash ref that looks like the first return value from
6674: &scantron_getfile()
6675: $scan_data - hash ref that looks like the second return value from
6676: &scantron_getfile()
6677: $i - line number to update
6678:
6679: =cut
6680:
6681: sub scantron_clear_skip {
6682: my ($scanlines,$scan_data,$i)=@_;
6683: if (exists($scanlines->{'skipped'}[$i])) {
6684: undef($scanlines->{'skipped'}[$i]);
6685: return 1;
6686: }
6687: return 0;
6688: }
6689:
6690: =pod
6691:
6692: =item scantron_filter_not_exam
6693:
6694: Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
6695: filter out resources that are not marked as 'exam' mode
6696:
6697: =cut
6698:
6699: sub scantron_filter_not_exam {
6700: my ($curres)=@_;
6701:
6702: if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
6703: # if the user has asked to not have either hidden
6704: # or 'randomout' controlled resources to be graded
6705: # don't include them
6706: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
6707: && $curres->randomout) {
6708: return 0;
6709: }
6710: return 1;
6711: }
6712: return 0;
6713: }
6714:
6715: =pod
6716:
6717: =item scantron_validate_sequence
6718:
6719: Validates the selected sequence, checking for resource that are
6720: not set to exam mode.
6721:
6722: =cut
6723:
6724: sub scantron_validate_sequence {
6725: my ($r,$currentphase) = @_;
6726:
6727: my $navmap=Apache::lonnavmaps::navmap->new();
6728: unless (ref($navmap)) {
6729: $r->print(&navmap_errormsg());
6730: return (1,$currentphase);
6731: }
6732: my (undef,undef,$sequence)=
6733: &Apache::lonnet::decode_symb($env{'form.selectpage'});
6734:
6735: my $map=$navmap->getResourceByUrl($sequence);
6736:
6737: $r->print('<input type="hidden" name="validate_sequence_exam"
6738: value="ignore" />');
6739: if ($env{'form.validate_sequence_exam'} ne 'ignore') {
6740: my @resources=
6741: $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
6742: if (@resources) {
6743: $r->print("<p>".&mt('Some resources in the sequence currently are not set to exam mode. Grading these resources currently may not work correctly.')."</p>");
6744: return (1,$currentphase);
6745: }
6746: }
6747:
6748: return (0,$currentphase+1);
6749: }
6750:
6751:
6752:
6753: sub scantron_validate_ID {
6754: my ($r,$currentphase) = @_;
6755:
6756: #get student info
6757: my $classlist=&Apache::loncoursedata::get_classlist();
6758: my %idmap=&username_to_idmap($classlist);
6759:
6760: #get scantron line setup
6761: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6762: my ($scanlines,$scan_data)=&scantron_getfile();
6763:
6764: my $nav_error;
6765: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
6766: if ($nav_error) {
6767: $r->print(&navmap_errormsg());
6768: return(1,$currentphase);
6769: }
6770:
6771: my %found=('ids'=>{},'usernames'=>{});
6772: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6773: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6774: if ($line=~/^[\s\cz]*$/) { next; }
6775: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6776: $scan_data);
6777: my $id=$$scan_record{'scantron.ID'};
6778: my $found;
6779: foreach my $checkid (keys(%idmap)) {
6780: if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
6781: }
6782: if ($found) {
6783: my $username=$idmap{$found};
6784: if ($found{'ids'}{$found}) {
6785: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6786: $line,'duplicateID',$found);
6787: return(1,$currentphase);
6788: } elsif ($found{'usernames'}{$username}) {
6789: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6790: $line,'duplicateID',$username);
6791: return(1,$currentphase);
6792: }
6793: #FIXME store away line we previously saw the ID on to use above
6794: $found{'ids'}{$found}++;
6795: $found{'usernames'}{$username}++;
6796: } else {
6797: if ($id =~ /^\s*$/) {
6798: my $username=&scan_data($scan_data,"$i.user");
6799: if (defined($username) && $found{'usernames'}{$username}) {
6800: &scantron_get_correction($r,$i,$scan_record,
6801: \%scantron_config,
6802: $line,'duplicateID',$username);
6803: return(1,$currentphase);
6804: } elsif (!defined($username)) {
6805: &scantron_get_correction($r,$i,$scan_record,
6806: \%scantron_config,
6807: $line,'incorrectID');
6808: return(1,$currentphase);
6809: }
6810: $found{'usernames'}{$username}++;
6811: } else {
6812: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6813: $line,'incorrectID');
6814: return(1,$currentphase);
6815: }
6816: }
6817: }
6818:
6819: return (0,$currentphase+1);
6820: }
6821:
6822:
6823: sub scantron_get_correction {
6824: my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
6825: #FIXME in the case of a duplicated ID the previous line, probably need
6826: #to show both the current line and the previous one and allow skipping
6827: #the previous one or the current one
6828:
6829: if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
6830: $r->print("<p>".&mt("<b>An error was detected ($error)</b>".
6831: " for PaperID <tt>[_1]</tt>",
6832: $$scan_record{'scantron.PaperID'})."</p> \n");
6833: } else {
6834: $r->print("<p>".&mt("<b>An error was detected ($error)</b>".
6835: " in scanline [_1] <pre>[_2]</pre>",
6836: $i,$line)."</p> \n");
6837: }
6838: my $message="<p>".&mt("The ID on the form is <tt>[_1]</tt><br />".
6839: "The name on the paper is [_2],[_3]",
6840: $$scan_record{'scantron.ID'},
6841: $$scan_record{'scantron.LastName'},
6842: $$scan_record{'scantron.FirstName'})."</p>";
6843:
6844: $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
6845: $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
6846: # Array populated for doublebubble or
6847: my @lines_to_correct; # missingbubble errors to build javascript
6848: # to validate radio button checking
6849:
6850: if ($error =~ /ID$/) {
6851: if ($error eq 'incorrectID') {
6852: $r->print("<p>".&mt("The encoded ID is not in the classlist").
6853: "</p>\n");
6854: } elsif ($error eq 'duplicateID') {
6855: $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
6856: }
6857: $r->print($message);
6858: $r->print("<p>".&mt("How should I handle this?")." <br /> \n");
6859: $r->print("\n<ul><li> ");
6860: #FIXME it would be nice if this sent back the user ID and
6861: #could do partial userID matches
6862: $r->print(&Apache::loncommon::selectstudent_link('scantronupload',
6863: 'scantron_username','scantron_domain'));
6864: $r->print(": <input type='text' name='scantron_username' value='' />");
6865: $r->print("\n@".
6866: &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
6867:
6868: $r->print('</li>');
6869: } elsif ($error =~ /CODE$/) {
6870: if ($error eq 'incorrectCODE') {
6871: $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
6872: } elsif ($error eq 'duplicateCODE') {
6873: $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");
6874: }
6875: $r->print("<p>".&mt("The CODE on the form is <tt>'[_1]'</tt>",
6876: $$scan_record{'scantron.CODE'})."<br />\n");
6877: $r->print($message);
6878: $r->print("<p>".&mt("How should I handle this?")." <br /> \n");
6879: $r->print("\n<br /> ");
6880: my $i=0;
6881: if ($error eq 'incorrectCODE'
6882: && $$scan_record{'scantron.CODE'}=~/\S/ ) {
6883: my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
6884: if ($closest > 0) {
6885: foreach my $testcode (@{$closest}) {
6886: my $checked='';
6887: if (!$i) { $checked=' checked="checked"'; }
6888: $r->print("
6889: <label>
6890: <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
6891: ".&mt("Use the similar CODE [_1] instead.",
6892: "<b><tt>".$testcode."</tt></b>")."
6893: </label>
6894: <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
6895: $r->print("\n<br />");
6896: $i++;
6897: }
6898: }
6899: }
6900: if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
6901: my $checked; if (!$i) { $checked=' checked="checked"'; }
6902: $r->print("
6903: <label>
6904: <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
6905: ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
6906: "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
6907: </label>");
6908: $r->print("\n<br />");
6909: }
6910:
6911: $r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
6912: function change_radio(field) {
6913: var slct=document.scantronupload.scantron_CODE_resolution;
6914: var i;
6915: for (i=0;i<slct.length;i++) {
6916: if (slct[i].value==field) { slct[i].checked=true; }
6917: }
6918: }
6919: ENDSCRIPT
6920: my $href="/adm/pickcode?".
6921: "form=".&escape("scantronupload").
6922: "&scantron_format=".&escape($env{'form.scantron_format'}).
6923: "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
6924: "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
6925: "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
6926: if ($env{'form.scantron_CODElist'} =~ /\S/) {
6927: $r->print("
6928: <label>
6929: <input type='radio' name='scantron_CODE_resolution' value='use_found' />
6930: ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
6931: "<a target='_blank' href='$href'>","</a>")."
6932: </label>
6933: ".&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\')" />'));
6934: $r->print("\n<br />");
6935: }
6936: $r->print("
6937: <label>
6938: <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
6939: ".&mt("Use [_1] as the CODE.",
6940: "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
6941: $r->print("\n<br /><br />");
6942: } elsif ($error eq 'doublebubble') {
6943: $r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
6944:
6945: # The form field scantron_questions is acutally a list of line numbers.
6946: # represented by this form so:
6947:
6948: my $line_list = &questions_to_line_list($arg);
6949:
6950: $r->print('<input type="hidden" name="scantron_questions" value="'.
6951: $line_list.'" />');
6952: $r->print($message);
6953: $r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
6954: foreach my $question (@{$arg}) {
6955: my @linenums = &prompt_for_corrections($r,$question,$scan_config,
6956: $scan_record, $error);
6957: push(@lines_to_correct,@linenums);
6958: }
6959: $r->print(&verify_bubbles_checked(@lines_to_correct));
6960: } elsif ($error eq 'missingbubble') {
6961: $r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
6962: $r->print($message);
6963: $r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
6964: $r->print(&mt("Some questions have no scanned bubbles.")."\n");
6965:
6966: # The form field scantron_questions is actually a list of line numbers not
6967: # a list of question numbers. Therefore:
6968: #
6969:
6970: my $line_list = &questions_to_line_list($arg);
6971:
6972: $r->print('<input type="hidden" name="scantron_questions" value="'.
6973: $line_list.'" />');
6974: foreach my $question (@{$arg}) {
6975: my @linenums = &prompt_for_corrections($r,$question,$scan_config,
6976: $scan_record, $error);
6977: push(@lines_to_correct,@linenums);
6978: }
6979: $r->print(&verify_bubbles_checked(@lines_to_correct));
6980: } else {
6981: $r->print("\n<ul>");
6982: }
6983: $r->print("\n</li></ul>");
6984: }
6985:
6986: sub verify_bubbles_checked {
6987: my (@ansnums) = @_;
6988: my $ansnumstr = join('","',@ansnums);
6989: my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
6990: my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
6991: function verify_bubble_radio(form) {
6992: var ansnumArray = new Array ("$ansnumstr");
6993: var need_bubble_count = 0;
6994: for (var i=0; i<ansnumArray.length; i++) {
6995: if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
6996: var bubble_picked = 0;
6997: for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
6998: if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
6999: bubble_picked = 1;
7000: }
7001: }
7002: if (bubble_picked == 0) {
7003: need_bubble_count ++;
7004: }
7005: }
7006: }
7007: if (need_bubble_count) {
7008: alert("$warning");
7009: return;
7010: }
7011: form.submit();
7012: }
7013: ENDSCRIPT
7014: return $output;
7015: }
7016:
7017: =pod
7018:
7019: =item questions_to_line_list
7020:
7021: Converts a list of questions into a string of comma separated
7022: line numbers in the answer sheet used by the questions. This is
7023: used to fill in the scantron_questions form field.
7024:
7025: Arguments:
7026: questions - Reference to an array of questions.
7027:
7028: =cut
7029:
7030:
7031: sub questions_to_line_list {
7032: my ($questions) = @_;
7033: my @lines;
7034:
7035: foreach my $item (@{$questions}) {
7036: my $question = $item;
7037: my ($first,$count,$last);
7038: if ($item =~ /^(\d+)\.(\d+)$/) {
7039: $question = $1;
7040: my $subquestion = $2;
7041: $first = $first_bubble_line{$question-1} + 1;
7042: my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
7043: my $subcount = 1;
7044: while ($subcount<$subquestion) {
7045: $first += $subans[$subcount-1];
7046: $subcount ++;
7047: }
7048: $count = $subans[$subquestion-1];
7049: } else {
7050: $first = $first_bubble_line{$question-1} + 1;
7051: $count = $bubble_lines_per_response{$question-1};
7052: }
7053: $last = $first+$count-1;
7054: push(@lines, ($first..$last));
7055: }
7056: return join(',', @lines);
7057: }
7058:
7059: =pod
7060:
7061: =item prompt_for_corrections
7062:
7063: Prompts for a potentially multiline correction to the
7064: user's bubbling (factors out common code from scantron_get_correction
7065: for multi and missing bubble cases).
7066:
7067: Arguments:
7068: $r - Apache request object.
7069: $question - The question number to prompt for.
7070: $scan_config - The scantron file configuration hash.
7071: $scan_record - Reference to the hash that has the the parsed scanlines.
7072: $error - Type of error
7073:
7074: Implicit inputs:
7075: %bubble_lines_per_response - Starting line numbers for each question.
7076: Numbered from 0 (but question numbers are from
7077: 1.
7078: %first_bubble_line - Starting bubble line for each question.
7079: %subdivided_bubble_lines - optionresponse, matchresponse and rankresponse
7080: type problems render as separate sub-questions,
7081: in exam mode. This hash contains a
7082: comma-separated list of the lines per
7083: sub-question.
7084: %responsetype_per_response - essayresponse, formularesponse,
7085: stringresponse, imageresponse, reactionresponse,
7086: and organicresponse type problem parts can have
7087: multiple lines per response if the weight
7088: assigned exceeds 10. In this case, only
7089: one bubble per line is permitted, but more
7090: than one line might contain bubbles, e.g.
7091: bubbling of: line 1 - J, line 2 - J,
7092: line 3 - B would assign 22 points.
7093:
7094: =cut
7095:
7096: sub prompt_for_corrections {
7097: my ($r, $question, $scan_config, $scan_record, $error) = @_;
7098: my ($current_line,$lines);
7099: my @linenums;
7100: my $questionnum = $question;
7101: if ($question =~ /^(\d+)\.(\d+)$/) {
7102: $question = $1;
7103: $current_line = $first_bubble_line{$question-1} + 1 ;
7104: my $subquestion = $2;
7105: my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
7106: my $subcount = 1;
7107: while ($subcount<$subquestion) {
7108: $current_line += $subans[$subcount-1];
7109: $subcount ++;
7110: }
7111: $lines = $subans[$subquestion-1];
7112: } else {
7113: $current_line = $first_bubble_line{$question-1} + 1 ;
7114: $lines = $bubble_lines_per_response{$question-1};
7115: }
7116: if ($lines > 1) {
7117: $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
7118: if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
7119: ($responsetype_per_response{$question-1} eq 'formularesponse') ||
7120: ($responsetype_per_response{$question-1} eq 'stringresponse') ||
7121: ($responsetype_per_response{$question-1} eq 'imageresponse') ||
7122: ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
7123: ($responsetype_per_response{$question-1} eq 'organicresponse')) {
7124: $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 />');
7125: } else {
7126: $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
7127: }
7128: }
7129: for (my $i =0; $i < $lines; $i++) {
7130: my $selected = $$scan_record{"scantron.$current_line.answer"};
7131: &scantron_bubble_selector($r,$scan_config,$current_line,
7132: $questionnum,$error,split('', $selected));
7133: push(@linenums,$current_line);
7134: $current_line++;
7135: }
7136: if ($lines > 1) {
7137: $r->print("<hr /><br />");
7138: }
7139: return @linenums;
7140: }
7141:
7142: =pod
7143:
7144: =item scantron_bubble_selector
7145:
7146: Generates the html radiobuttons to correct a single bubble line
7147: possibly showing the existing the selected bubbles if known
7148:
7149: Arguments:
7150: $r - Apache request object
7151: $scan_config - hash from &get_scantron_config()
7152: $line - Number of the line being displayed.
7153: $questionnum - Question number (may include subquestion)
7154: $error - Type of error.
7155: @selected - Array of bubbles picked on this line.
7156:
7157: =cut
7158:
7159: sub scantron_bubble_selector {
7160: my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
7161: my $max=$$scan_config{'Qlength'};
7162:
7163: my $scmode=$$scan_config{'Qon'};
7164: if ($scmode eq 'number' || $scmode eq 'letter') {
7165: if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
7166: ($$scan_config{'BubblesPerRow'} > 0)) {
7167: $max=$$scan_config{'BubblesPerRow'};
7168: if (($scmode eq 'number') && ($max > 10)) {
7169: $max = 10;
7170: } elsif (($scmode eq 'letter') && $max > 26) {
7171: $max = 26;
7172: }
7173: } else {
7174: $max = 10;
7175: }
7176: }
7177:
7178: my @alphabet=('A'..'Z');
7179: $r->print(&Apache::loncommon::start_data_table().
7180: &Apache::loncommon::start_data_table_row());
7181: $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
7182: for (my $i=0;$i<$max+1;$i++) {
7183: $r->print("\n".'<td align="center">');
7184: if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
7185: else { $r->print(' '); }
7186: $r->print('</td>');
7187: }
7188: $r->print(&Apache::loncommon::end_data_table_row().
7189: &Apache::loncommon::start_data_table_row());
7190: for (my $i=0;$i<$max;$i++) {
7191: $r->print("\n".
7192: '<td><label><input type="radio" name="scantron_correct_Q_'.
7193: $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
7194: }
7195: my $nobub_checked = ' ';
7196: if ($error eq 'missingbubble') {
7197: $nobub_checked = ' checked = "checked" ';
7198: }
7199: $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
7200: $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
7201: '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
7202: $line.'" value="'.$questionnum.'" /></td>');
7203: $r->print(&Apache::loncommon::end_data_table_row().
7204: &Apache::loncommon::end_data_table());
7205: }
7206:
7207: =pod
7208:
7209: =item num_matches
7210:
7211: Counts the number of characters that are the same between the two arguments.
7212:
7213: Arguments:
7214: $orig - CODE from the scanline
7215: $code - CODE to match against
7216:
7217: Returns:
7218: $count - integer count of the number of same characters between the
7219: two arguments
7220:
7221: =cut
7222:
7223: sub num_matches {
7224: my ($orig,$code) = @_;
7225: my @code=split(//,$code);
7226: my @orig=split(//,$orig);
7227: my $same=0;
7228: for (my $i=0;$i<scalar(@code);$i++) {
7229: if ($code[$i] eq $orig[$i]) { $same++; }
7230: }
7231: return $same;
7232: }
7233:
7234: =pod
7235:
7236: =item scantron_get_closely_matching_CODEs
7237:
7238: Cycles through all CODEs and finds the set that has the greatest
7239: number of same characters as the provided CODE
7240:
7241: Arguments:
7242: $allcodes - hash ref returned by &get_codes()
7243: $CODE - CODE from the current scanline
7244:
7245: Returns:
7246: 2 element list
7247: - first elements is number of how closely matching the best fit is
7248: (5 means best set has 5 matching characters)
7249: - second element is an arrary ref containing the set of valid CODEs
7250: that best fit the passed in CODE
7251:
7252: =cut
7253:
7254: sub scantron_get_closely_matching_CODEs {
7255: my ($allcodes,$CODE)=@_;
7256: my @CODEs;
7257: foreach my $testcode (sort(keys(%{$allcodes}))) {
7258: push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
7259: }
7260:
7261: return ($#CODEs,$CODEs[-1]);
7262: }
7263:
7264: =pod
7265:
7266: =item get_codes
7267:
7268: Builds a hash which has keys of all of the valid CODEs from the selected
7269: set of remembered CODEs.
7270:
7271: Arguments:
7272: $old_name - name of the set of remembered CODEs
7273: $cdom - domain of the course
7274: $cnum - internal course name
7275:
7276: Returns:
7277: %allcodes - keys are the valid CODEs, values are all 1
7278:
7279: =cut
7280:
7281: sub get_codes {
7282: my ($old_name, $cdom, $cnum) = @_;
7283: if (!$old_name) {
7284: $old_name=$env{'form.scantron_CODElist'};
7285: }
7286: if (!$cdom) {
7287: $cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
7288: }
7289: if (!$cnum) {
7290: $cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
7291: }
7292: my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
7293: $cdom,$cnum);
7294: my %allcodes;
7295: if ($result{"type\0$old_name"} eq 'number') {
7296: %allcodes=map {($_,1)} split(',',$result{$old_name});
7297: } else {
7298: %allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
7299: }
7300: return %allcodes;
7301: }
7302:
7303: =pod
7304:
7305: =item scantron_validate_CODE
7306:
7307: Validates all scanlines in the selected file to not have any
7308: invalid or underspecified CODEs and that none of the codes are
7309: duplicated if this was requested.
7310:
7311: =cut
7312:
7313: sub scantron_validate_CODE {
7314: my ($r,$currentphase) = @_;
7315: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7316: if ($scantron_config{'CODElocation'} &&
7317: $scantron_config{'CODEstart'} &&
7318: $scantron_config{'CODElength'}) {
7319: if (!defined($env{'form.scantron_CODElist'})) {
7320: &FIXME_blow_up()
7321: }
7322: } else {
7323: return (0,$currentphase+1);
7324: }
7325:
7326: my %usedCODEs;
7327:
7328: my %allcodes=&get_codes();
7329:
7330: my $nav_error;
7331: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
7332: if ($nav_error) {
7333: $r->print(&navmap_errormsg());
7334: return(1,$currentphase);
7335: }
7336:
7337: my ($scanlines,$scan_data)=&scantron_getfile();
7338: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7339: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7340: if ($line=~/^[\s\cz]*$/) { next; }
7341: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7342: $scan_data);
7343: my $CODE=$$scan_record{'scantron.CODE'};
7344: my $error=0;
7345: if (!&Apache::lonnet::validCODE($CODE)) {
7346: &scantron_get_correction($r,$i,$scan_record,
7347: \%scantron_config,
7348: $line,'incorrectCODE',\%allcodes);
7349: return(1,$currentphase);
7350: }
7351: if (%allcodes && !exists($allcodes{$CODE})
7352: && !$$scan_record{'scantron.useCODE'}) {
7353: &scantron_get_correction($r,$i,$scan_record,
7354: \%scantron_config,
7355: $line,'incorrectCODE',\%allcodes);
7356: return(1,$currentphase);
7357: }
7358: if (exists($usedCODEs{$CODE})
7359: && $env{'form.scantron_CODEunique'} eq 'yes'
7360: && !$$scan_record{'scantron.CODE_ignore_dup'}) {
7361: &scantron_get_correction($r,$i,$scan_record,
7362: \%scantron_config,
7363: $line,'duplicateCODE',$usedCODEs{$CODE});
7364: return(1,$currentphase);
7365: }
7366: push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
7367: }
7368: return (0,$currentphase+1);
7369: }
7370:
7371: =pod
7372:
7373: =item scantron_validate_doublebubble
7374:
7375: Validates all scanlines in the selected file to not have any
7376: bubble lines with multiple bubbles marked.
7377:
7378: =cut
7379:
7380: sub scantron_validate_doublebubble {
7381: my ($r,$currentphase) = @_;
7382: #get student info
7383: my $classlist=&Apache::loncoursedata::get_classlist();
7384: my %idmap=&username_to_idmap($classlist);
7385:
7386: #get scantron line setup
7387: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7388: my ($scanlines,$scan_data)=&scantron_getfile();
7389: my $nav_error;
7390: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
7391: if ($nav_error) {
7392: $r->print(&navmap_errormsg());
7393: return(1,$currentphase);
7394: }
7395:
7396: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7397: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7398: if ($line=~/^[\s\cz]*$/) { next; }
7399: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7400: $scan_data);
7401: if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
7402: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
7403: 'doublebubble',
7404: $$scan_record{'scantron.doubleerror'});
7405: return (1,$currentphase);
7406: }
7407: return (0,$currentphase+1);
7408: }
7409:
7410:
7411: sub scantron_get_maxbubble {
7412: my ($nav_error,$scantron_config) = @_;
7413: if (defined($env{'form.scantron_maxbubble'}) &&
7414: $env{'form.scantron_maxbubble'}) {
7415: &restore_bubble_lines();
7416: return $env{'form.scantron_maxbubble'};
7417: }
7418:
7419: my (undef, undef, $sequence) =
7420: &Apache::lonnet::decode_symb($env{'form.selectpage'});
7421:
7422: my $navmap=Apache::lonnavmaps::navmap->new();
7423: unless (ref($navmap)) {
7424: if (ref($nav_error)) {
7425: $$nav_error = 1;
7426: }
7427: return;
7428: }
7429: my $map=$navmap->getResourceByUrl($sequence);
7430: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
7431: my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
7432:
7433: &Apache::lonxml::clear_problem_counter();
7434:
7435: my $uname = $env{'user.name'};
7436: my $udom = $env{'user.domain'};
7437: my $cid = $env{'request.course.id'};
7438: my $total_lines = 0;
7439: %bubble_lines_per_response = ();
7440: %first_bubble_line = ();
7441: %subdivided_bubble_lines = ();
7442: %responsetype_per_response = ();
7443:
7444: my $response_number = 0;
7445: my $bubble_line = 0;
7446: foreach my $resource (@resources) {
7447: my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom,undef,$bubbles_per_row);
7448: if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
7449: foreach my $part_id (@{$parts}) {
7450: my $lines;
7451:
7452: # TODO - make this a persistent hash not an array.
7453:
7454: # optionresponse, matchresponse and rankresponse type items
7455: # render as separate sub-questions in exam mode.
7456: if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
7457: ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
7458: ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
7459: my ($numbub,$numshown);
7460: if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
7461: if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
7462: $numbub = scalar(@{$analysis->{$part_id.'.options'}});
7463: }
7464: } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
7465: if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
7466: $numbub = scalar(@{$analysis->{$part_id.'.items'}});
7467: }
7468: } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
7469: if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
7470: $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
7471: }
7472: }
7473: if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
7474: $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
7475: }
7476: my $bubbles_per_row =
7477: &bubblesheet_bubbles_per_row($scantron_config);
7478: my $inner_bubble_lines = int($numbub/$bubbles_per_row);
7479: if (($numbub % $bubbles_per_row) != 0) {
7480: $inner_bubble_lines++;
7481: }
7482: for (my $i=0; $i<$numshown; $i++) {
7483: $subdivided_bubble_lines{$response_number} .=
7484: $inner_bubble_lines.',';
7485: }
7486: $subdivided_bubble_lines{$response_number} =~ s/,$//;
7487: $lines = $numshown * $inner_bubble_lines;
7488: } else {
7489: $lines = $analysis->{"$part_id.bubble_lines"};
7490: }
7491:
7492: $first_bubble_line{$response_number} = $bubble_line;
7493: $bubble_lines_per_response{$response_number} = $lines;
7494: $responsetype_per_response{$response_number} =
7495: $analysis->{$part_id.'.type'};
7496: $response_number++;
7497:
7498: $bubble_line += $lines;
7499: $total_lines += $lines;
7500: }
7501: }
7502: }
7503: &Apache::lonnet::delenv('scantron.');
7504:
7505: &save_bubble_lines();
7506: $env{'form.scantron_maxbubble'} =
7507: $total_lines;
7508: return $env{'form.scantron_maxbubble'};
7509: }
7510:
7511: sub bubblesheet_bubbles_per_row {
7512: my ($scantron_config) = @_;
7513: my $bubbles_per_row;
7514: if (ref($scantron_config) eq 'HASH') {
7515: $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
7516: }
7517: if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
7518: $bubbles_per_row = 10;
7519: }
7520: return $bubbles_per_row;
7521: }
7522:
7523: sub scantron_validate_missingbubbles {
7524: my ($r,$currentphase) = @_;
7525: #get student info
7526: my $classlist=&Apache::loncoursedata::get_classlist();
7527: my %idmap=&username_to_idmap($classlist);
7528:
7529: #get scantron line setup
7530: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7531: my ($scanlines,$scan_data)=&scantron_getfile();
7532: my $nav_error;
7533: my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
7534: if ($nav_error) {
7535: return(1,$currentphase);
7536: }
7537: if (!$max_bubble) { $max_bubble=2**31; }
7538: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7539: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7540: if ($line=~/^[\s\cz]*$/) { next; }
7541: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7542: $scan_data);
7543: if (!defined($$scan_record{'scantron.missingerror'})) { next; }
7544: my @to_correct;
7545:
7546: # Probably here's where the error is...
7547:
7548: foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
7549: my $lastbubble;
7550: if ($missing =~ /^(\d+)\.(\d+)$/) {
7551: my $question = $1;
7552: my $subquestion = $2;
7553: if (!defined($first_bubble_line{$question -1})) { next; }
7554: my $first = $first_bubble_line{$question-1};
7555: my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
7556: my $subcount = 1;
7557: while ($subcount<$subquestion) {
7558: $first += $subans[$subcount-1];
7559: $subcount ++;
7560: }
7561: my $count = $subans[$subquestion-1];
7562: $lastbubble = $first + $count;
7563: } else {
7564: if (!defined($first_bubble_line{$missing - 1})) { next; }
7565: $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
7566: }
7567: if ($lastbubble > $max_bubble) { next; }
7568: push(@to_correct,$missing);
7569: }
7570: if (@to_correct) {
7571: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
7572: $line,'missingbubble',\@to_correct);
7573: return (1,$currentphase);
7574: }
7575:
7576: }
7577: return (0,$currentphase+1);
7578: }
7579:
7580:
7581: sub scantron_process_students {
7582: my ($r,$symb) = @_;
7583:
7584: my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
7585: if (!$symb) {
7586: return '';
7587: }
7588: my $default_form_data=&defaultFormData($symb);
7589:
7590: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7591: my $bubbles_per_row =
7592: &bubblesheet_bubbles_per_row(\%scantron_config);
7593: my ($scanlines,$scan_data)=&scantron_getfile();
7594: my $classlist=&Apache::loncoursedata::get_classlist();
7595: my %idmap=&username_to_idmap($classlist);
7596: my $navmap=Apache::lonnavmaps::navmap->new();
7597: unless (ref($navmap)) {
7598: $r->print(&navmap_errormsg());
7599: return '';
7600: }
7601: my $map=$navmap->getResourceByUrl($sequence);
7602: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
7603: my (%grader_partids_by_symb,%grader_randomlists_by_symb);
7604: &graders_resources_pass(\@resources,\%grader_partids_by_symb,
7605: \%grader_randomlists_by_symb,$bubbles_per_row);
7606: my $resource_error;
7607: foreach my $resource (@resources) {
7608: my $ressymb;
7609: if (ref($resource)) {
7610: $ressymb = $resource->symb();
7611: } else {
7612: $resource_error = 1;
7613: last;
7614: }
7615: my ($analysis,$parts) =
7616: &scantron_partids_tograde($resource,$env{'request.course.id'},
7617: $env{'user.name'},$env{'user.domain'},1,$bubbles_per_row);
7618: $grader_partids_by_symb{$ressymb} = $parts;
7619: if (ref($analysis) eq 'HASH') {
7620: if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
7621: $grader_randomlists_by_symb{$ressymb} =
7622: $analysis->{'parts_withrandomlist'};
7623: }
7624: }
7625: }
7626: if ($resource_error) {
7627: $r->print(&navmap_errormsg());
7628: return '';
7629: }
7630:
7631: my ($uname,$udom);
7632: my $result= <<SCANTRONFORM;
7633: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
7634: <input type="hidden" name="command" value="scantron_configphase" />
7635: $default_form_data
7636: SCANTRONFORM
7637: $r->print($result);
7638:
7639: my @delayqueue;
7640: my (%completedstudents,%scandata);
7641:
7642: my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
7643: my $count=&get_todo_count($scanlines,$scan_data);
7644: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
7645: 'Bubblesheet Progress',$count,
7646: 'inline',undef,'scantronupload');
7647: &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
7648: 'Processing first student');
7649: $r->print('<br />');
7650: my $start=&Time::HiRes::time();
7651: my $i=-1;
7652: my $started;
7653:
7654: my $nav_error;
7655: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
7656: if ($nav_error) {
7657: $r->print(&navmap_errormsg());
7658: return '';
7659: }
7660:
7661: # If an ssi failed in scantron_get_maxbubble, put an error message out to
7662: # the user and return.
7663:
7664: if ($ssi_error) {
7665: $r->print("</form>");
7666: &ssi_print_error($r);
7667: &Apache::lonnet::remove_lock($lock);
7668: return ''; # Dunno why the other returns return '' rather than just returning.
7669: }
7670:
7671: my %lettdig = &letter_to_digits();
7672: my $numletts = scalar(keys(%lettdig));
7673:
7674: while ($i<$scanlines->{'count'}) {
7675: ($uname,$udom)=('','');
7676: $i++;
7677: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7678: if ($line=~/^[\s\cz]*$/) { next; }
7679: if ($started) {
7680: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
7681: 'last student');
7682: }
7683: $started=1;
7684: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7685: $scan_data);
7686: unless ($uname=&scantron_find_student($scan_record,$scan_data,
7687: \%idmap,$i)) {
7688: &scantron_add_delay(\@delayqueue,$line,
7689: 'Unable to find a student that matches',1);
7690: next;
7691: }
7692: if (exists $completedstudents{$uname}) {
7693: &scantron_add_delay(\@delayqueue,$line,
7694: 'Student '.$uname.' has multiple sheets',2);
7695: next;
7696: }
7697: ($uname,$udom)=split(/:/,$uname);
7698:
7699: my (%partids_by_symb,$res_error);
7700: foreach my $resource (@resources) {
7701: my $ressymb;
7702: if (ref($resource)) {
7703: $ressymb = $resource->symb();
7704: } else {
7705: $res_error = 1;
7706: last;
7707: }
7708: if ((exists($grader_randomlists_by_symb{$ressymb})) ||
7709: (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
7710: my ($analysis,$parts) =
7711: &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom,undef,$bubbles_per_row);
7712: $partids_by_symb{$ressymb} = $parts;
7713: } else {
7714: $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
7715: }
7716: }
7717:
7718: if ($res_error) {
7719: &scantron_add_delay(\@delayqueue,$line,
7720: 'An error occurred while grading student '.$uname,2);
7721: next;
7722: }
7723:
7724: &Apache::lonxml::clear_problem_counter();
7725: &Apache::lonnet::appenv($scan_record);
7726:
7727: if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
7728: &scantron_putfile($scanlines,$scan_data);
7729: }
7730:
7731: my $scancode;
7732: if ((exists($scan_record->{'scantron.CODE'})) &&
7733: (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
7734: $scancode = $scan_record->{'scantron.CODE'};
7735: } else {
7736: $scancode = '';
7737: }
7738:
7739: if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
7740: \@resources,\%partids_by_symb,
7741: $bubbles_per_row) eq 'ssi_error') {
7742: $ssi_error = 0; # So end of handler error message does not trigger.
7743: $r->print("</form>");
7744: &ssi_print_error($r);
7745: &Apache::lonnet::remove_lock($lock);
7746: return ''; # Why return ''? Beats me.
7747: }
7748:
7749: $completedstudents{$uname}={'line'=>$line};
7750: if ($env{'form.verifyrecord'}) {
7751: my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
7752: my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
7753: chomp($studentdata);
7754: $studentdata =~ s/\r$//;
7755: my $studentrecord = '';
7756: my $counter = -1;
7757: foreach my $resource (@resources) {
7758: my $ressymb = $resource->symb();
7759: ($counter,my $recording) =
7760: &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
7761: $counter,$studentdata,$partids_by_symb{$ressymb},
7762: \%scantron_config,\%lettdig,$numletts);
7763: $studentrecord .= $recording;
7764: }
7765: if ($studentrecord ne $studentdata) {
7766: &Apache::lonxml::clear_problem_counter();
7767: if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
7768: \@resources,\%partids_by_symb,
7769: $bubbles_per_row) eq 'ssi_error') {
7770: $ssi_error = 0; # So end of handler error message does not trigger.
7771: $r->print("</form>");
7772: &ssi_print_error($r);
7773: &Apache::lonnet::remove_lock($lock);
7774: delete($completedstudents{$uname});
7775: return '';
7776: }
7777: $counter = -1;
7778: $studentrecord = '';
7779: foreach my $resource (@resources) {
7780: my $ressymb = $resource->symb();
7781: ($counter,my $recording) =
7782: &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
7783: $counter,$studentdata,$partids_by_symb{$ressymb},
7784: \%scantron_config,\%lettdig,$numletts);
7785: $studentrecord .= $recording;
7786: }
7787: if ($studentrecord ne $studentdata) {
7788: $r->print('<p><span class="LC_error">');
7789: if ($scancode eq '') {
7790: $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
7791: $uname.':'.$udom,$scan_record->{'scantron.ID'}));
7792: } else {
7793: $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
7794: $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
7795: }
7796: $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
7797: &Apache::loncommon::start_data_table_header_row()."\n".
7798: '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
7799: &Apache::loncommon::end_data_table_header_row()."\n".
7800: &Apache::loncommon::start_data_table_row().
7801: '<td>'.&mt('Bubble Sheet').'</td>'.
7802: '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
7803: &Apache::loncommon::end_data_table_row().
7804: &Apache::loncommon::start_data_table_row().
7805: '<td>Stored submissions</td>'.
7806: '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
7807: &Apache::loncommon::end_data_table_row().
7808: &Apache::loncommon::end_data_table().'</p>');
7809: } else {
7810: $r->print('<br /><span class="LC_warning">'.
7811: &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 />'.
7812: &mt("As a consequence, this user's submission history records two tries.").
7813: '</span><br />');
7814: }
7815: }
7816: }
7817: if (&Apache::loncommon::connection_aborted($r)) { last; }
7818: } continue {
7819: &Apache::lonxml::clear_problem_counter();
7820: &Apache::lonnet::delenv('scantron.');
7821: }
7822: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
7823: &Apache::lonnet::remove_lock($lock);
7824: # my $lasttime = &Time::HiRes::time()-$start;
7825: # $r->print("<p>took $lasttime</p>");
7826:
7827: $r->print("</form>");
7828: return '';
7829: }
7830:
7831: sub graders_resources_pass {
7832: my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
7833: $bubbles_per_row) = @_;
7834: if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) &&
7835: (ref($grader_randomlists_by_symb) eq 'HASH')) {
7836: foreach my $resource (@{$resources}) {
7837: my $ressymb = $resource->symb();
7838: my ($analysis,$parts) =
7839: &scantron_partids_tograde($resource,$env{'request.course.id'},
7840: $env{'user.name'},$env{'user.domain'},1,$bubbles_per_row);
7841: $grader_partids_by_symb->{$ressymb} = $parts;
7842: if (ref($analysis) eq 'HASH') {
7843: if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
7844: $grader_randomlists_by_symb->{$ressymb} =
7845: $analysis->{'parts_withrandomlist'};
7846: }
7847: }
7848: }
7849: }
7850: return;
7851: }
7852:
7853: sub grade_student_bubbles {
7854: my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row) = @_;
7855: # Walk folder as student here to get resources in order student sees.
7856: if (ref($resources) eq 'ARRAY') {
7857: my $count = 0;
7858: foreach my $resource (@{$resources}) {
7859: my $ressymb = $resource->symb();
7860: my %form = ('submitted' => 'scantron',
7861: 'grade_target' => 'grade',
7862: 'grade_username' => $uname,
7863: 'grade_domain' => $udom,
7864: 'grade_courseid' => $env{'request.course.id'},
7865: 'grade_symb' => $ressymb,
7866: 'CODE' => $scancode
7867: );
7868: if ($bubbles_per_row ne '') {
7869: $form{'bubbles_per_row'} = $bubbles_per_row;
7870: }
7871: if (ref($parts) eq 'HASH') {
7872: if (ref($parts->{$ressymb}) eq 'ARRAY') {
7873: foreach my $part (@{$parts->{$ressymb}}) {
7874: $form{'scantron_questnum_start.'.$part} =
7875: 1+$env{'form.scantron.first_bubble_line.'.$count};
7876: $count++;
7877: }
7878: }
7879: }
7880: my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
7881: return 'ssi_error' if ($ssi_error);
7882: last if (&Apache::loncommon::connection_aborted($r));
7883: }
7884: }
7885: return;
7886: }
7887:
7888: sub scantron_upload_scantron_data {
7889: my ($r,$symb)=@_;
7890: my $dom = $env{'request.role.domain'};
7891: my $domdesc = &Apache::lonnet::domain($dom,'description');
7892: $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
7893: my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
7894: 'domainid',
7895: 'coursename',$dom);
7896: my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
7897: (' 'x2).&mt('(shows course personnel)');
7898: my $default_form_data=&defaultFormData($symb);
7899: my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
7900: 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.");
7901: $r->print(&Apache::lonhtmlcommon::scripttag('
7902: function checkUpload(formname) {
7903: if (formname.upfile.value == "") {
7904: alert("'.$nofile_alert.'");
7905: return false;
7906: }
7907: if (formname.courseid.value == "") {
7908: alert("'.$nocourseid_alert.'");
7909: return false;
7910: }
7911: formname.submit();
7912: }
7913:
7914: function ToSyllabus() {
7915: var cdom = '."'$dom'".';
7916: var cnum = document.rules.courseid.value;
7917: if (cdom == "" || cdom == null) {
7918: return;
7919: }
7920: if (cnum == "" || cnum == null) {
7921: return;
7922: }
7923: syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
7924: "height=350,width=350,scrollbars=yes,menubar=no");
7925: return;
7926: }
7927:
7928: '));
7929: $r->print('
7930: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
7931:
7932: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
7933: '.$default_form_data.
7934: &Apache::lonhtmlcommon::start_pick_box().
7935: &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
7936: '<input name="courseid" type="text" size="30" />'.$select_link.
7937: &Apache::lonhtmlcommon::row_closure().
7938: &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
7939: '<input name="coursename" type="text" size="30" />'.$syllabuslink.
7940: &Apache::lonhtmlcommon::row_closure().
7941: &Apache::lonhtmlcommon::row_title(&mt('Domain')).
7942: '<input name="domainid" type="hidden" />'.$domdesc.
7943: &Apache::lonhtmlcommon::row_closure().
7944: &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
7945: '<input type="file" name="upfile" size="50" />'.
7946: &Apache::lonhtmlcommon::row_closure(1).
7947: &Apache::lonhtmlcommon::end_pick_box().'<br />
7948:
7949: <input name="command" value="scantronupload_save" type="hidden" />
7950: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
7951: </form>
7952: ');
7953: return '';
7954: }
7955:
7956:
7957: sub scantron_upload_scantron_data_save {
7958: my($r,$symb)=@_;
7959: my $doanotherupload=
7960: '<br /><form action="/adm/grades" method="post">'."\n".
7961: '<input type="hidden" name="command" value="scantronupload" />'."\n".
7962: '<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
7963: '</form>'."\n";
7964: if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
7965: !&Apache::lonnet::allowed('usc',
7966: $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
7967: $r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
7968: unless ($symb) {
7969: $r->print($doanotherupload);
7970: }
7971: return '';
7972: }
7973: my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
7974: my $uploadedfile;
7975: $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
7976: if (length($env{'form.upfile'}) < 2) {
7977: $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>'));
7978: } else {
7979: my $result =
7980: &Apache::lonnet::userfileupload('upfile','','scantron','','','',
7981: $env{'form.courseid'},$env{'form.domainid'});
7982: if ($result =~ m{^/uploaded/}) {
7983: $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
7984: '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
7985: '<span class="LC_filename">'.$result.'</span>'));
7986: ($uploadedfile) = ($result =~ m{/([^/]+)$});
7987: $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
7988: $env{'form.courseid'},$uploadedfile));
7989: } else {
7990: $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
7991: '<span class="LC_error">','</span>',$result,
7992: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
7993: }
7994: }
7995: if ($symb) {
7996: $r->print(&scantron_selectphase($r,$uploadedfile,$symb));
7997: } else {
7998: $r->print($doanotherupload);
7999: }
8000: return '';
8001: }
8002:
8003: sub validate_uploaded_scantron_file {
8004: my ($cdom,$cname,$fname) = @_;
8005: my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
8006: my @lines;
8007: if ($scanlines ne '-1') {
8008: @lines=split("\n",$scanlines,-1);
8009: }
8010: my $output;
8011: if (@lines) {
8012: my (%counts,$max_match_format);
8013: my ($max_match_count,$max_match_pct) = (0,0);
8014: my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
8015: my %idmap = &username_to_idmap($classlist);
8016: foreach my $key (keys(%idmap)) {
8017: my $lckey = lc($key);
8018: $idmap{$lckey} = $idmap{$key};
8019: }
8020: my %unique_formats;
8021: my @formatlines = &get_scantronformat_file();
8022: foreach my $line (@formatlines) {
8023: chomp($line);
8024: my @config = split(/:/,$line);
8025: my $idstart = $config[5];
8026: my $idlength = $config[6];
8027: if (($idstart ne '') && ($idlength > 0)) {
8028: if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
8029: push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]);
8030: } else {
8031: $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
8032: }
8033: }
8034: }
8035: foreach my $key (keys(%unique_formats)) {
8036: my ($idstart,$idlength) = split(':',$key);
8037: %{$counts{$key}} = (
8038: 'found' => 0,
8039: 'total' => 0,
8040: );
8041: foreach my $line (@lines) {
8042: next if ($line =~ /^#/);
8043: next if ($line =~ /^[\s\cz]*$/);
8044: my $id = substr($line,$idstart-1,$idlength);
8045: $id = lc($id);
8046: if (exists($idmap{$id})) {
8047: $counts{$key}{'found'} ++;
8048: }
8049: $counts{$key}{'total'} ++;
8050: }
8051: if ($counts{$key}{'total'}) {
8052: my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
8053: if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
8054: $max_match_pct = $percent_match;
8055: $max_match_format = $key;
8056: $max_match_count = $counts{$key}{'total'};
8057: }
8058: }
8059: }
8060: if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
8061: my $format_descs;
8062: my $numwithformat = @{$unique_formats{$max_match_format}};
8063: for (my $i=0; $i<$numwithformat; $i++) {
8064: my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
8065: if ($i<$numwithformat-2) {
8066: $format_descs .= '"<i>'.$desc.'</i>", ';
8067: } elsif ($i==$numwithformat-2) {
8068: $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
8069: } elsif ($i==$numwithformat-1) {
8070: $format_descs .= '"<i>'.$desc.'</i>"';
8071: }
8072: }
8073: my $showpct = sprintf("%.0f",$max_match_pct).'%';
8074: $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).
8075: '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
8076: '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
8077: '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
8078: '<i>'.$cdom.'</i>').'</li>'.
8079: '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
8080: '<li>'.&mt('The course roster is not up to date').'</li>'.
8081: '</ul>';
8082: }
8083: } else {
8084: $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
8085: }
8086: return $output;
8087: }
8088:
8089: sub valid_file {
8090: my ($requested_file)=@_;
8091: foreach my $filename (sort(&scantron_filenames())) {
8092: if ($requested_file eq $filename) { return 1; }
8093: }
8094: return 0;
8095: }
8096:
8097: sub scantron_download_scantron_data {
8098: my ($r,$symb)=@_;
8099: my $default_form_data=&defaultFormData($symb);
8100: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
8101: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
8102: my $file=$env{'form.scantron_selectfile'};
8103: if (! &valid_file($file)) {
8104: $r->print('
8105: <p>
8106: '.&mt('The requested file name was invalid.').'
8107: </p>
8108: ');
8109: return;
8110: }
8111: my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
8112: my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
8113: my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
8114: &Apache::lonnet::allowuploaded('/adm/grades',$orig);
8115: &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
8116: &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
8117: $r->print('
8118: <p>
8119: '.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
8120: '<a href="'.$orig.'">','</a>').'
8121: </p>
8122: <p>
8123: '.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
8124: '<a href="'.$corrected.'">','</a>').'
8125: </p>
8126: <p>
8127: '.&mt('[_1]Skipped[_2], a file of records that were skipped.',
8128: '<a href="'.$skipped.'">','</a>').'
8129: </p>
8130: ');
8131: return '';
8132: }
8133:
8134: sub checkscantron_results {
8135: my ($r,$symb) = @_;
8136: if (!$symb) {return '';}
8137: my $cid = $env{'request.course.id'};
8138: my %lettdig = &letter_to_digits();
8139: my $numletts = scalar(keys(%lettdig));
8140: my $cnum = $env{'course.'.$cid.'.num'};
8141: my $cdom = $env{'course.'.$cid.'.domain'};
8142: my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
8143: my %record;
8144: my %scantron_config =
8145: &Apache::grades::get_scantron_config($env{'form.scantron_format'});
8146: my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
8147: my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
8148: my $classlist=&Apache::loncoursedata::get_classlist();
8149: my %idmap=&Apache::grades::username_to_idmap($classlist);
8150: my $navmap=Apache::lonnavmaps::navmap->new();
8151: unless (ref($navmap)) {
8152: $r->print(&navmap_errormsg());
8153: return '';
8154: }
8155: my $map=$navmap->getResourceByUrl($sequence);
8156: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
8157: my (%grader_partids_by_symb,%grader_randomlists_by_symb);
8158: &graders_resources_pass(\@resources,\%grader_partids_by_symb, \%grader_randomlists_by_symb);
8159:
8160: my ($uname,$udom);
8161: my (%scandata,%lastname,%bylast);
8162: $r->print('
8163: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
8164:
8165: my @delayqueue;
8166: my %completedstudents;
8167:
8168: my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
8169: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
8170: 'Progress of Bubblesheet Data/Submission Records Comparison',$count,
8171: 'inline',undef,'checkscantron');
8172: my ($username,$domain,$started);
8173: my $nav_error;
8174: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
8175: if ($nav_error) {
8176: $r->print(&navmap_errormsg());
8177: return '';
8178: }
8179:
8180: &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
8181: 'Processing first student');
8182: my $start=&Time::HiRes::time();
8183: my $i=-1;
8184:
8185: while ($i<$scanlines->{'count'}) {
8186: ($username,$domain,$uname)=('','','');
8187: $i++;
8188: my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
8189: if ($line=~/^[\s\cz]*$/) { next; }
8190: if ($started) {
8191: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
8192: 'last student');
8193: }
8194: $started=1;
8195: my $scan_record=
8196: &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
8197: $scan_data);
8198: unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
8199: \%idmap,$i)) {
8200: &Apache::grades::scantron_add_delay(\@delayqueue,$line,
8201: 'Unable to find a student that matches',1);
8202: next;
8203: }
8204: if (exists $completedstudents{$uname}) {
8205: &Apache::grades::scantron_add_delay(\@delayqueue,$line,
8206: 'Student '.$uname.' has multiple sheets',2);
8207: next;
8208: }
8209: my $pid = $scan_record->{'scantron.ID'};
8210: $lastname{$pid} = $scan_record->{'scantron.LastName'};
8211: push(@{$bylast{$lastname{$pid}}},$pid);
8212: my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
8213: $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
8214: chomp($scandata{$pid});
8215: $scandata{$pid} =~ s/\r$//;
8216: ($username,$domain)=split(/:/,$uname);
8217: my $counter = -1;
8218: foreach my $resource (@resources) {
8219: my $parts;
8220: my $ressymb = $resource->symb();
8221: if ((exists($grader_randomlists_by_symb{$ressymb})) ||
8222: (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
8223: (my $analysis,$parts) =
8224: &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain,undef,$bubbles_per_row);
8225: } else {
8226: $parts = $grader_partids_by_symb{$ressymb};
8227: }
8228: ($counter,my $recording) =
8229: &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
8230: $scandata{$pid},$parts,
8231: \%scantron_config,\%lettdig,$numletts);
8232: $record{$pid} .= $recording;
8233: }
8234: }
8235: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
8236: $r->print('<br />');
8237: my ($okstudents,$badstudents,$numstudents,$passed,$failed);
8238: $passed = 0;
8239: $failed = 0;
8240: $numstudents = 0;
8241: foreach my $last (sort(keys(%bylast))) {
8242: if (ref($bylast{$last}) eq 'ARRAY') {
8243: foreach my $pid (sort(@{$bylast{$last}})) {
8244: my $showscandata = $scandata{$pid};
8245: my $showrecord = $record{$pid};
8246: $showscandata =~ s/\s/ /g;
8247: $showrecord =~ s/\s/ /g;
8248: if ($scandata{$pid} eq $record{$pid}) {
8249: my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
8250: $okstudents .= '<tr class="'.$css_class.'">'.
8251: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
8252: '</tr>'."\n".
8253: '<tr class="'.$css_class.'">'."\n".
8254: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
8255: $passed ++;
8256: } else {
8257: my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
8258: $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".
8259: '</tr>'."\n".
8260: '<tr class="'.$css_class.'">'."\n".
8261: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
8262: '</tr>'."\n";
8263: $failed ++;
8264: }
8265: $numstudents ++;
8266: }
8267: }
8268: }
8269: $r->print(
8270: '<p>'
8271: .&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).',
8272: '<b>',
8273: $numstudents,
8274: '</b>',
8275: $env{'form.scantron_maxbubble'})
8276: .'</p>'
8277: );
8278: $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>');
8279: if ($passed) {
8280: $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
8281: $r->print(&Apache::loncommon::start_data_table()."\n".
8282: &Apache::loncommon::start_data_table_header_row()."\n".
8283: '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
8284: &Apache::loncommon::end_data_table_header_row()."\n".
8285: $okstudents."\n".
8286: &Apache::loncommon::end_data_table().'<br />');
8287: }
8288: if ($failed) {
8289: $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
8290: $r->print(&Apache::loncommon::start_data_table()."\n".
8291: &Apache::loncommon::start_data_table_header_row()."\n".
8292: '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
8293: &Apache::loncommon::end_data_table_header_row()."\n".
8294: $badstudents."\n".
8295: &Apache::loncommon::end_data_table()).'<br />'.
8296: &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.');
8297: }
8298: $r->print('</form><br />');
8299: return;
8300: }
8301:
8302: sub verify_scantron_grading {
8303: my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
8304: $scantron_config,$lettdig,$numletts) = @_;
8305: my ($record,%expected,%startpos);
8306: return ($counter,$record) if (!ref($resource));
8307: return ($counter,$record) if (!$resource->is_problem());
8308: my $symb = $resource->symb();
8309: return ($counter,$record) if (ref($partids) ne 'ARRAY');
8310: foreach my $part_id (@{$partids}) {
8311: $counter ++;
8312: $expected{$part_id} = 0;
8313: if ($env{"form.scantron.sub_bubblelines.$counter"}) {
8314: my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
8315: foreach my $item (@sub_lines) {
8316: $expected{$part_id} += $item;
8317: }
8318: } else {
8319: $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
8320: }
8321: $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
8322: }
8323: if ($symb) {
8324: my %recorded;
8325: my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
8326: if ($returnhash{'version'}) {
8327: my %lasthash=();
8328: my $version;
8329: for ($version=1;$version<=$returnhash{'version'};$version++) {
8330: foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
8331: $lasthash{$key}=$returnhash{$version.':'.$key};
8332: }
8333: }
8334: foreach my $key (keys(%lasthash)) {
8335: if ($key =~ /\.scantron$/) {
8336: my $value = &unescape($lasthash{$key});
8337: my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
8338: if ($value eq '') {
8339: for (my $i=0; $i<$expected{$part_id}; $i++) {
8340: for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
8341: $recorded{$part_id} .= $scantron_config->{'Qoff'};
8342: }
8343: }
8344: } else {
8345: my @tocheck;
8346: my @items = split(//,$value);
8347: if (($scantron_config->{'Qon'} eq 'letter') ||
8348: ($scantron_config->{'Qon'} eq 'number')) {
8349: if (@items < $expected{$part_id}) {
8350: my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
8351: my @singles = split(//,$fragment);
8352: foreach my $pos (@singles) {
8353: if ($pos eq ' ') {
8354: push(@tocheck,$pos);
8355: } else {
8356: my $next = shift(@items);
8357: push(@tocheck,$next);
8358: }
8359: }
8360: } else {
8361: @tocheck = @items;
8362: }
8363: foreach my $letter (@tocheck) {
8364: if ($scantron_config->{'Qon'} eq 'letter') {
8365: if ($letter !~ /^[A-J]$/) {
8366: $letter = $scantron_config->{'Qoff'};
8367: }
8368: $recorded{$part_id} .= $letter;
8369: } elsif ($scantron_config->{'Qon'} eq 'number') {
8370: my $digit;
8371: if ($letter !~ /^[A-J]$/) {
8372: $digit = $scantron_config->{'Qoff'};
8373: } else {
8374: $digit = $lettdig->{$letter};
8375: }
8376: $recorded{$part_id} .= $digit;
8377: }
8378: }
8379: } else {
8380: @tocheck = @items;
8381: for (my $i=0; $i<$expected{$part_id}; $i++) {
8382: my $curr_sub = shift(@tocheck);
8383: my $digit;
8384: if ($curr_sub =~ /^[A-J]$/) {
8385: $digit = $lettdig->{$curr_sub}-1;
8386: }
8387: if ($curr_sub eq 'J') {
8388: $digit += scalar($numletts);
8389: }
8390: for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
8391: if ($j == $digit) {
8392: $recorded{$part_id} .= $scantron_config->{'Qon'};
8393: } else {
8394: $recorded{$part_id} .= $scantron_config->{'Qoff'};
8395: }
8396: }
8397: }
8398: }
8399: }
8400: }
8401: }
8402: }
8403: foreach my $part_id (@{$partids}) {
8404: if ($recorded{$part_id} eq '') {
8405: for (my $i=0; $i<$expected{$part_id}; $i++) {
8406: for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
8407: $recorded{$part_id} .= $scantron_config->{'Qoff'};
8408: }
8409: }
8410: }
8411: $record .= $recorded{$part_id};
8412: }
8413: }
8414: return ($counter,$record);
8415: }
8416:
8417: sub letter_to_digits {
8418: my %lettdig = (
8419: A => 1,
8420: B => 2,
8421: C => 3,
8422: D => 4,
8423: E => 5,
8424: F => 6,
8425: G => 7,
8426: H => 8,
8427: I => 9,
8428: J => 0,
8429: );
8430: return %lettdig;
8431: }
8432:
8433:
8434: #-------- end of section for handling grading scantron forms -------
8435: #
8436: #-------------------------------------------------------------------
8437:
8438: #-------------------------- Menu interface -------------------------
8439: #
8440: #--- Href with symb and command ---
8441:
8442: sub href_symb_cmd {
8443: my ($symb,$cmd)=@_;
8444: return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&command='.$cmd;
8445: }
8446:
8447: sub grading_menu {
8448: my ($request,$symb) = @_;
8449: if (!$symb) {return '';}
8450:
8451: my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
8452: 'command'=>'individual');
8453:
8454: my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
8455:
8456: $fields{'command'}='ungraded';
8457: my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
8458:
8459: $fields{'command'}='table';
8460: my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
8461:
8462: $fields{'command'}='all_for_one';
8463: my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
8464:
8465: $fields{'command'}='downloadfilesselect';
8466: my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
8467:
8468: $fields{'command'} = 'csvform';
8469: my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
8470:
8471: $fields{'command'} = 'processclicker';
8472: my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
8473:
8474: $fields{'command'} = 'scantron_selectphase';
8475: my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
8476:
8477: $fields{'command'} = 'initialverifyreceipt';
8478: my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
8479:
8480: my @menu = ({ categorytitle=>'Hand Grading',
8481: items =>[
8482: { linktext => 'Select individual students to grade',
8483: url => $url1a,
8484: permission => 'F',
8485: icon => 'grade_students.png',
8486: linktitle => 'Grade current resource for a selection of students.'
8487: },
8488: { linktext => 'Grade ungraded submissions.',
8489: url => $url1b,
8490: permission => 'F',
8491: icon => 'ungrade_sub.png',
8492: linktitle => 'Grade all submissions that have not been graded yet.'
8493: },
8494:
8495: { linktext => 'Grading table',
8496: url => $url1c,
8497: permission => 'F',
8498: icon => 'grading_table.png',
8499: linktitle => 'Grade current resource for all students.'
8500: },
8501: { linktext => 'Grade page/folder for one student',
8502: url => $url1d,
8503: permission => 'F',
8504: icon => 'grade_PageFolder.png',
8505: linktitle => 'Grade all resources in current page/sequence/folder for one student.'
8506: },
8507: { linktext => 'Download submissions',
8508: url => $url1e,
8509: permission => 'F',
8510: icon => 'download_sub.png',
8511: linktitle => 'Download all students submissions.'
8512: }]},
8513: { categorytitle=>'Automated Grading',
8514: items =>[
8515:
8516: { linktext => 'Upload Scores',
8517: url => $url2,
8518: permission => 'F',
8519: icon => 'uploadscores.png',
8520: linktitle => 'Specify a file containing the class scores for current resource.'
8521: },
8522: { linktext => 'Process Clicker',
8523: url => $url3,
8524: permission => 'F',
8525: icon => 'addClickerInfoFile.png',
8526: linktitle => 'Specify a file containing the clicker information for this resource.'
8527: },
8528: { linktext => 'Grade/Manage/Review Bubblesheets',
8529: url => $url4,
8530: permission => 'F',
8531: icon => 'bubblesheet.png',
8532: linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
8533: },
8534: { linktext => 'Verify Receipt Number',
8535: url => $url5,
8536: permission => 'F',
8537: icon => 'receipt_number.png',
8538: linktitle => 'Verify a system-generated receipt number for correct problem solution.'
8539: }
8540:
8541: ]
8542: });
8543:
8544: # Create the menu
8545: my $Str;
8546: $Str .= '<form method="post" action="" name="gradingMenu">';
8547: $Str .= '<input type="hidden" name="command" value="" />'.
8548: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
8549:
8550: $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
8551: return $Str;
8552: }
8553:
8554:
8555: sub ungraded {
8556: my ($request)=@_;
8557: &submit_options($request);
8558: }
8559:
8560: sub submit_options_sequence {
8561: my ($request,$symb) = @_;
8562: if (!$symb) {return '';}
8563: &commonJSfunctions($request);
8564: my $result;
8565:
8566: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
8567: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
8568: $result.=&selectfield(0).
8569: '<input type="hidden" name="command" value="pickStudentPage" />
8570: <div>
8571: <input type="submit" value="'.&mt('Next').' →" />
8572: </div>
8573: </div>
8574: </form>';
8575: return $result;
8576: }
8577:
8578: sub submit_options_table {
8579: my ($request,$symb) = @_;
8580: if (!$symb) {return '';}
8581: &commonJSfunctions($request);
8582: my $result;
8583:
8584: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
8585: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
8586:
8587: $result.=&selectfield(0).
8588: '<input type="hidden" name="command" value="viewgrades" />
8589: <div>
8590: <input type="submit" value="'.&mt('Next').' →" />
8591: </div>
8592: </div>
8593: </form>';
8594: return $result;
8595: }
8596:
8597: sub submit_options_download {
8598: my ($request,$symb) = @_;
8599: if (!$symb) {return '';}
8600:
8601: &commonJSfunctions($request);
8602:
8603: my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
8604: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
8605: $result.='
8606: <h2>
8607: '.&mt('Select Students for Which to Download Submissions').'
8608: </h2>'.&selectfield(1).'
8609: <input type="hidden" name="command" value="downloadfileslink" />
8610: <input type="submit" value="'.&mt('Next').' →" />
8611: </div>
8612: </div>
8613:
8614:
8615: </form>';
8616: return $result;
8617: }
8618:
8619: #--- Displays the submissions first page -------
8620: sub submit_options {
8621: my ($request,$symb) = @_;
8622: if (!$symb) {return '';}
8623:
8624: &commonJSfunctions($request);
8625: my $result;
8626:
8627: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
8628: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
8629: $result.=&selectfield(1).'
8630: <input type="hidden" name="command" value="submission" />
8631: <input type="submit" value="'.&mt('Next').' →" />
8632: </div>
8633: </div>
8634:
8635:
8636: </form>';
8637: return $result;
8638: }
8639:
8640: sub selectfield {
8641: my ($full)=@_;
8642: my %options =
8643: (&Apache::lonlocal::texthash(
8644: 'yes' => 'with submissions',
8645: 'queued' => 'in grading queue',
8646: 'graded' => 'with ungraded submissions',
8647: 'incorrect' => 'with incorrect submissions',
8648: 'all' => 'with any status'),
8649: 'select_form_order' => ['yes','queued','graded','incorrect','all']);
8650: my $result='<div class="LC_columnSection">
8651:
8652: <fieldset>
8653: <legend>
8654: '.&mt('Sections').'
8655: </legend>
8656: '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
8657: </fieldset>
8658:
8659: <fieldset>
8660: <legend>
8661: '.&mt('Groups').'
8662: </legend>
8663: '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
8664: </fieldset>
8665:
8666: <fieldset>
8667: <legend>
8668: '.&mt('Access Status').'
8669: </legend>
8670: '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
8671: </fieldset>';
8672: if ($full) {
8673: $result.='
8674: <fieldset>
8675: <legend>
8676: '.&mt('Submission Status').'
8677: </legend>'.
8678: &Apache::loncommon::select_form('all','submitonly',\%options).
8679: '</fieldset>';
8680: }
8681: $result.='</div><br />';
8682: return $result;
8683: }
8684:
8685: sub reset_perm {
8686: undef(%perm);
8687: }
8688:
8689: sub init_perm {
8690: &reset_perm();
8691: foreach my $test_perm ('vgr','mgr','opa') {
8692:
8693: my $scope = $env{'request.course.id'};
8694: if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
8695:
8696: $scope .= '/'.$env{'request.course.sec'};
8697: if ( $perm{$test_perm}=
8698: &Apache::lonnet::allowed($test_perm,$scope)) {
8699: $perm{$test_perm.'_section'}=$env{'request.course.sec'};
8700: } else {
8701: delete($perm{$test_perm});
8702: }
8703: }
8704: }
8705: }
8706:
8707: sub gather_clicker_ids {
8708: my %clicker_ids;
8709:
8710: my $classlist = &Apache::loncoursedata::get_classlist();
8711:
8712: # Set up a couple variables.
8713: my $username_idx = &Apache::loncoursedata::CL_SNAME();
8714: my $domain_idx = &Apache::loncoursedata::CL_SDOM();
8715: my $status_idx = &Apache::loncoursedata::CL_STATUS();
8716:
8717: foreach my $student (keys(%$classlist)) {
8718: if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
8719: my $username = $classlist->{$student}->[$username_idx];
8720: my $domain = $classlist->{$student}->[$domain_idx];
8721: my $clickers =
8722: (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
8723: foreach my $id (split(/\,/,$clickers)) {
8724: $id=~s/^[\#0]+//;
8725: $id=~s/[\-\:]//g;
8726: if (exists($clicker_ids{$id})) {
8727: $clicker_ids{$id}.=','.$username.':'.$domain;
8728: } else {
8729: $clicker_ids{$id}=$username.':'.$domain;
8730: }
8731: }
8732: }
8733: return %clicker_ids;
8734: }
8735:
8736: sub gather_adv_clicker_ids {
8737: my %clicker_ids;
8738: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
8739: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
8740: my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
8741: foreach my $element (sort(keys(%coursepersonnel))) {
8742: foreach my $person (split(/\,/,$coursepersonnel{$element})) {
8743: my ($puname,$pudom)=split(/\:/,$person);
8744: my $clickers =
8745: (&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
8746: foreach my $id (split(/\,/,$clickers)) {
8747: $id=~s/^[\#0]+//;
8748: $id=~s/[\-\:]//g;
8749: if (exists($clicker_ids{$id})) {
8750: $clicker_ids{$id}.=','.$puname.':'.$pudom;
8751: } else {
8752: $clicker_ids{$id}=$puname.':'.$pudom;
8753: }
8754: }
8755: }
8756: }
8757: return %clicker_ids;
8758: }
8759:
8760: sub clicker_grading_parameters {
8761: return ('gradingmechanism' => 'scalar',
8762: 'upfiletype' => 'scalar',
8763: 'specificid' => 'scalar',
8764: 'pcorrect' => 'scalar',
8765: 'pincorrect' => 'scalar');
8766: }
8767:
8768: sub process_clicker {
8769: my ($r,$symb)=@_;
8770: if (!$symb) {return '';}
8771: my $result=&checkforfile_js();
8772: $result.=&Apache::loncommon::start_data_table().
8773: &Apache::loncommon::start_data_table_header_row().
8774: '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
8775: &Apache::loncommon::end_data_table_header_row().
8776: &Apache::loncommon::start_data_table_row()."<td>\n";
8777: # Attempt to restore parameters from last session, set defaults if not present
8778: my %Saveable_Parameters=&clicker_grading_parameters();
8779: &Apache::loncommon::restore_course_settings('grades_clicker',
8780: \%Saveable_Parameters);
8781: if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
8782: if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
8783: if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
8784: if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
8785:
8786: my %checked;
8787: foreach my $gradingmechanism ('attendance','personnel','specific','given') {
8788: if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
8789: $checked{$gradingmechanism}=' checked="checked"';
8790: }
8791: }
8792:
8793: my $upload=&mt("Evaluate File");
8794: my $type=&mt("Type");
8795: my $attendance=&mt("Award points just for participation");
8796: my $personnel=&mt("Correctness determined from response by course personnel");
8797: my $specific=&mt("Correctness determined from response with clicker ID(s)");
8798: my $given=&mt("Correctness determined from given list of answers").' '.
8799: '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
8800: my $pcorrect=&mt("Percentage points for correct solution");
8801: my $pincorrect=&mt("Percentage points for incorrect solution");
8802: my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
8803: {'iclicker' => 'i>clicker',
8804: 'interwrite' => 'interwrite PRS'});
8805: $symb = &Apache::lonenc::check_encrypt($symb);
8806: $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
8807: function sanitycheck() {
8808: // Accept only integer percentages
8809: document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
8810: document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
8811: // Find out grading choice
8812: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
8813: if (document.forms.gradesupload.gradingmechanism[i].checked) {
8814: gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
8815: }
8816: }
8817: // By default, new choice equals user selection
8818: newgradingchoice=gradingchoice;
8819: // Not good to give more points for false answers than correct ones
8820: if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
8821: document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
8822: }
8823: // If new choice is attendance only, and old choice was correctness-based, restore defaults
8824: if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
8825: document.forms.gradesupload.pcorrect.value=100;
8826: document.forms.gradesupload.pincorrect.value=100;
8827: }
8828: // If the values are different, cannot be attendance only
8829: if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
8830: (gradingchoice=='attendance')) {
8831: newgradingchoice='personnel';
8832: }
8833: // Change grading choice to new one
8834: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
8835: if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
8836: document.forms.gradesupload.gradingmechanism[i].checked=true;
8837: } else {
8838: document.forms.gradesupload.gradingmechanism[i].checked=false;
8839: }
8840: }
8841: // Remember the old state
8842: document.forms.gradesupload.waschecked.value=newgradingchoice;
8843: }
8844: ENDUPFORM
8845: $result.= <<ENDUPFORM;
8846: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
8847: <input type="hidden" name="symb" value="$symb" />
8848: <input type="hidden" name="command" value="processclickerfile" />
8849: <input type="file" name="upfile" size="50" />
8850: <br /><label>$type: $selectform</label>
8851: ENDUPFORM
8852: $result.='</td>'.&Apache::loncommon::end_data_table_row().
8853: &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
8854: <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
8855: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
8856: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
8857: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
8858: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
8859: <br />
8860: <input type="text" name="givenanswer" size="50" />
8861: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
8862: ENDGRADINGFORM
8863: $result.='</td>'.&Apache::loncommon::end_data_table_row().
8864: &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
8865: <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
8866: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
8867: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
8868: </form>'
8869: ENDPERCFORM
8870: $result.='</td>'.
8871: &Apache::loncommon::end_data_table_row().
8872: &Apache::loncommon::end_data_table();
8873: return $result;
8874: }
8875:
8876: sub process_clicker_file {
8877: my ($r,$symb)=@_;
8878: if (!$symb) {return '';}
8879:
8880: my %Saveable_Parameters=&clicker_grading_parameters();
8881: &Apache::loncommon::store_course_settings('grades_clicker',
8882: \%Saveable_Parameters);
8883: my $result='';
8884: if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
8885: $result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
8886: return $result;
8887: }
8888: if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
8889: $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
8890: return $result;
8891: }
8892: my $foundgiven=0;
8893: if ($env{'form.gradingmechanism'} eq 'given') {
8894: $env{'form.givenanswer'}=~s/^\s*//gs;
8895: $env{'form.givenanswer'}=~s/\s*$//gs;
8896: $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
8897: $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
8898: my @answers=split(/\,/,$env{'form.givenanswer'});
8899: $foundgiven=$#answers+1;
8900: }
8901: my %clicker_ids=&gather_clicker_ids();
8902: my %correct_ids;
8903: if ($env{'form.gradingmechanism'} eq 'personnel') {
8904: %correct_ids=&gather_adv_clicker_ids();
8905: }
8906: if ($env{'form.gradingmechanism'} eq 'specific') {
8907: foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
8908: $correct_id=~tr/a-z/A-Z/;
8909: $correct_id=~s/\s//gs;
8910: $correct_id=~s/^[\#0]+//;
8911: $correct_id=~s/[\-\:]//g;
8912: if ($correct_id) {
8913: $correct_ids{$correct_id}='specified';
8914: }
8915: }
8916: }
8917: if ($env{'form.gradingmechanism'} eq 'attendance') {
8918: $result.=&mt('Score based on attendance only');
8919: } elsif ($env{'form.gradingmechanism'} eq 'given') {
8920: $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
8921: } else {
8922: my $number=0;
8923: $result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
8924: foreach my $id (sort(keys(%correct_ids))) {
8925: $result.='<br /><tt>'.$id.'</tt> - ';
8926: if ($correct_ids{$id} eq 'specified') {
8927: $result.=&mt('specified');
8928: } else {
8929: my ($uname,$udom)=split(/\:/,$correct_ids{$id});
8930: $result.=&Apache::loncommon::plainname($uname,$udom);
8931: }
8932: $number++;
8933: }
8934: $result.="</p>\n";
8935: if ($number==0) {
8936: $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
8937: return $result;
8938: }
8939: }
8940: if (length($env{'form.upfile'}) < 2) {
8941: $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
8942: '<span class="LC_error">',
8943: '</span>',
8944: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
8945: return $result;
8946: }
8947:
8948: # Were able to get all the info needed, now analyze the file
8949:
8950: $result.=&Apache::loncommon::studentbrowser_javascript();
8951: $symb = &Apache::lonenc::check_encrypt($symb);
8952: $result.=&Apache::loncommon::start_data_table().
8953: &Apache::loncommon::start_data_table_header_row().
8954: '<th>'.&mt('Evaluate clicker file').'</th>'.
8955: &Apache::loncommon::end_data_table_header_row().
8956: &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
8957: <td>
8958: <form method="post" action="/adm/grades" name="clickeranalysis">
8959: <input type="hidden" name="symb" value="$symb" />
8960: <input type="hidden" name="command" value="assignclickergrades" />
8961: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
8962: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
8963: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
8964: ENDHEADER
8965: if ($env{'form.gradingmechanism'} eq 'given') {
8966: $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
8967: }
8968: my %responses;
8969: my @questiontitles;
8970: my $errormsg='';
8971: my $number=0;
8972: if ($env{'form.upfiletype'} eq 'iclicker') {
8973: ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
8974: }
8975: if ($env{'form.upfiletype'} eq 'interwrite') {
8976: ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
8977: }
8978: $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
8979: '<input type="hidden" name="number" value="'.$number.'" />'.
8980: &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
8981: $env{'form.pcorrect'},$env{'form.pincorrect'}).
8982: '<br />';
8983: if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
8984: $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
8985: return $result;
8986: }
8987: # Remember Question Titles
8988: # FIXME: Possibly need delimiter other than ":"
8989: for (my $i=0;$i<$number;$i++) {
8990: $result.='<input type="hidden" name="question:'.$i.'" value="'.
8991: &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
8992: }
8993: my $correct_count=0;
8994: my $student_count=0;
8995: my $unknown_count=0;
8996: # Match answers with usernames
8997: # FIXME: Possibly need delimiter other than ":"
8998: foreach my $id (keys(%responses)) {
8999: if ($correct_ids{$id}) {
9000: $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
9001: $correct_count++;
9002: } elsif ($clicker_ids{$id}) {
9003: if ($clicker_ids{$id}=~/\,/) {
9004: # More than one user with the same clicker!
9005: $result.="</td>".&Apache::loncommon::end_data_table_row().
9006: &Apache::loncommon::start_data_table_row()."<td>".
9007: &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
9008: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
9009: "<select name='multi".$id."'>";
9010: foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
9011: $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
9012: }
9013: $result.='</select>';
9014: $unknown_count++;
9015: } else {
9016: # Good: found one and only one user with the right clicker
9017: $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
9018: $student_count++;
9019: }
9020: } else {
9021: $result.="</td>".&Apache::loncommon::end_data_table_row().
9022: &Apache::loncommon::start_data_table_row()."<td>".
9023: &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
9024: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
9025: "\n".&mt("Username").": <input type='text' name='uname".$id."' /> ".
9026: "\n".&mt("Domain").": ".
9027: &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).' '.
9028: &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
9029: $unknown_count++;
9030: }
9031: }
9032: $result.='<hr />'.
9033: &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
9034: if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
9035: if ($correct_count==0) {
9036: $errormsg.="Found no correct answers answers for grading!";
9037: } elsif ($correct_count>1) {
9038: $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
9039: }
9040: }
9041: if ($number<1) {
9042: $errormsg.="Found no questions.";
9043: }
9044: if ($errormsg) {
9045: $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
9046: } else {
9047: $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
9048: }
9049: $result.='</form></td>'.
9050: &Apache::loncommon::end_data_table_row().
9051: &Apache::loncommon::end_data_table();
9052: return $result;
9053: }
9054:
9055: sub iclicker_eval {
9056: my ($questiontitles,$responses)=@_;
9057: my $number=0;
9058: my $errormsg='';
9059: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
9060: my %components=&Apache::loncommon::record_sep($line);
9061: my @entries=map {$components{$_}} (sort(keys(%components)));
9062: if ($entries[0] eq 'Question') {
9063: for (my $i=3;$i<$#entries;$i+=6) {
9064: $$questiontitles[$number]=$entries[$i];
9065: $number++;
9066: }
9067: }
9068: if ($entries[0]=~/^\#/) {
9069: my $id=$entries[0];
9070: my @idresponses;
9071: $id=~s/^[\#0]+//;
9072: for (my $i=0;$i<$number;$i++) {
9073: my $idx=3+$i*6;
9074: $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
9075: push(@idresponses,$entries[$idx]);
9076: }
9077: $$responses{$id}=join(',',@idresponses);
9078: }
9079: }
9080: return ($errormsg,$number);
9081: }
9082:
9083: sub interwrite_eval {
9084: my ($questiontitles,$responses)=@_;
9085: my $number=0;
9086: my $errormsg='';
9087: my $skipline=1;
9088: my $questionnumber=0;
9089: my %idresponses=();
9090: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
9091: my %components=&Apache::loncommon::record_sep($line);
9092: my @entries=map {$components{$_}} (sort(keys(%components)));
9093: if ($entries[1] eq 'Time') { $skipline=0; next; }
9094: if ($entries[1] eq 'Response') { $skipline=1; }
9095: next if $skipline;
9096: if ($entries[0]!=$questionnumber) {
9097: $questionnumber=$entries[0];
9098: $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
9099: $number++;
9100: }
9101: my $id=$entries[4];
9102: $id=~s/^[\#0]+//;
9103: $id=~s/^v\d*\://i;
9104: $id=~s/[\-\:]//g;
9105: $idresponses{$id}[$number]=$entries[6];
9106: }
9107: foreach my $id (keys(%idresponses)) {
9108: $$responses{$id}=join(',',@{$idresponses{$id}});
9109: $$responses{$id}=~s/^\s*\,//;
9110: }
9111: return ($errormsg,$number);
9112: }
9113:
9114: sub assign_clicker_grades {
9115: my ($r,$symb)=@_;
9116: if (!$symb) {return '';}
9117: # See which part we are saving to
9118: my $res_error;
9119: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
9120: if ($res_error) {
9121: return &navmap_errormsg();
9122: }
9123: # FIXME: This should probably look for the first handgradeable part
9124: my $part=$$partlist[0];
9125: # Start screen output
9126: my $result=&Apache::loncommon::start_data_table().
9127: &Apache::loncommon::start_data_table_header_row().
9128: '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
9129: &Apache::loncommon::end_data_table_header_row().
9130: &Apache::loncommon::start_data_table_row().'<td>';
9131: # Get correct result
9132: # FIXME: Possibly need delimiter other than ":"
9133: my @correct=();
9134: my $gradingmechanism=$env{'form.gradingmechanism'};
9135: my $number=$env{'form.number'};
9136: if ($gradingmechanism ne 'attendance') {
9137: foreach my $key (keys(%env)) {
9138: if ($key=~/^form\.correct\:/) {
9139: my @input=split(/\,/,$env{$key});
9140: for (my $i=0;$i<=$#input;$i++) {
9141: if (($correct[$i]) && ($input[$i]) &&
9142: ($correct[$i] ne $input[$i])) {
9143: $result.='<br /><span class="LC_warning">'.
9144: &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
9145: $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
9146: } elsif (($input[$i]) || ($input[$i] eq '0')) {
9147: $correct[$i]=$input[$i];
9148: }
9149: }
9150: }
9151: }
9152: for (my $i=0;$i<$number;$i++) {
9153: if ((!$correct[$i]) && ($correct[$i] ne '0')) {
9154: $result.='<br /><span class="LC_error">'.
9155: &mt('No correct result given for question "[_1]"!',
9156: $env{'form.question:'.$i}).'</span>';
9157: }
9158: }
9159: $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
9160: }
9161: # Start grading
9162: my $pcorrect=$env{'form.pcorrect'};
9163: my $pincorrect=$env{'form.pincorrect'};
9164: my $storecount=0;
9165: my %users=();
9166: foreach my $key (keys(%env)) {
9167: my $user='';
9168: if ($key=~/^form\.student\:(.*)$/) {
9169: $user=$1;
9170: }
9171: if ($key=~/^form\.unknown\:(.*)$/) {
9172: my $id=$1;
9173: if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
9174: $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
9175: } elsif ($env{'form.multi'.$id}) {
9176: $user=$env{'form.multi'.$id};
9177: }
9178: }
9179: if ($user) {
9180: if ($users{$user}) {
9181: $result.='<br /><span class="LC_warning">'.
9182: &mt("More than one entry found for <tt>[_1]</tt>!",$user).
9183: '</span><br />';
9184: }
9185: $users{$user}=1;
9186: my @answer=split(/\,/,$env{$key});
9187: my $sum=0;
9188: my $realnumber=$number;
9189: for (my $i=0;$i<$number;$i++) {
9190: if ($correct[$i] eq '-') {
9191: $realnumber--;
9192: } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
9193: if ($gradingmechanism eq 'attendance') {
9194: $sum+=$pcorrect;
9195: } elsif ($correct[$i] eq '*') {
9196: $sum+=$pcorrect;
9197: } else {
9198: # We actually grade if correct or not
9199: my $increment=$pincorrect;
9200: # Special case: numerical answer "0"
9201: if ($correct[$i] eq '0') {
9202: if ($answer[$i]=~/^[0\.]+$/) {
9203: $increment=$pcorrect;
9204: }
9205: # General numerical answer, both evaluate to something non-zero
9206: } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
9207: if (1.0*$correct[$i]==1.0*$answer[$i]) {
9208: $increment=$pcorrect;
9209: }
9210: # Must be just alphanumeric
9211: } elsif ($answer[$i] eq $correct[$i]) {
9212: $increment=$pcorrect;
9213: }
9214: $sum+=$increment;
9215: }
9216: }
9217: }
9218: my $ave=$sum/(100*$realnumber);
9219: # Store
9220: my ($username,$domain)=split(/\:/,$user);
9221: my %grades=();
9222: $grades{"resource.$part.solved"}='correct_by_override';
9223: $grades{"resource.$part.awarded"}=$ave;
9224: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
9225: my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
9226: $env{'request.course.id'},
9227: $domain,$username);
9228: if ($returncode ne 'ok') {
9229: $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
9230: } else {
9231: $storecount++;
9232: }
9233: }
9234: }
9235: # We are done
9236: $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
9237: '</td>'.
9238: &Apache::loncommon::end_data_table_row().
9239: &Apache::loncommon::end_data_table();
9240: return $result;
9241: }
9242:
9243: sub navmap_errormsg {
9244: return '<div class="LC_error">'.
9245: &mt('An error occurred retrieving information about resources in the course.').'<br />'.
9246: &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>').
9247: '</div>';
9248: }
9249:
9250: sub startpage {
9251: my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag) = @_;
9252: unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
9253: $r->print(&Apache::loncommon::start_page('Grading',undef,
9254: {'bread_crumbs' => $crumbs}));
9255: &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
9256: unless ($nodisplayflag) {
9257: $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag));
9258: }
9259: }
9260:
9261: sub select_problem {
9262: my ($r)=@_;
9263: $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
9264: $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
9265: $r->print('<input type="hidden" name="command" value="gradingmenu" />');
9266: $r->print('<input type="submit" value="'.&mt('Next').' →" /></form>');
9267: }
9268:
9269: sub handler {
9270: my $request=$_[0];
9271: &reset_caches();
9272: if ($request->header_only) {
9273: &Apache::loncommon::content_type($request,'text/html');
9274: $request->send_http_header;
9275: return OK;
9276: }
9277: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
9278:
9279: &init_perm();
9280: if (!$env{'request.course.id'}) {
9281: # Not in a course.
9282: $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
9283: return HTTP_NOT_ACCEPTABLE;
9284: } elsif (!%perm) {
9285: $request->internal_redirect('/adm/quickgrades');
9286: }
9287: &Apache::loncommon::content_type($request,'text/html');
9288: $request->send_http_header;
9289:
9290:
9291: # see what command we need to execute
9292:
9293: my @commands=&Apache::loncommon::get_env_multiple('form.command');
9294: my $command=$commands[0];
9295:
9296: if ($#commands > 0) {
9297: &Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
9298: }
9299:
9300: # see what the symb is
9301:
9302: my $symb=$env{'form.symb'};
9303: unless ($symb) {
9304: (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
9305: $symb=&Apache::lonnet::symbread($url);
9306: }
9307: &Apache::lonenc::check_decrypt(\$symb);
9308:
9309: $ssi_error = 0;
9310: if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
9311: #
9312: # Not called from a resource, but inside a course
9313: #
9314: &startpage($request,undef,[],1,1);
9315: &select_problem($request);
9316: } else {
9317: if ($command eq 'submission' && $perm{'vgr'}) {
9318: &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}]);
9319: ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
9320: } elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
9321: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
9322: {href=>'',text=>'Select student'}],1,1);
9323: &pickStudentPage($request,$symb);
9324: } elsif ($command eq 'displayPage' && $perm{'vgr'}) {
9325: &startpage($request,$symb,
9326: [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
9327: {href=>'',text=>'Select student'},
9328: {href=>'',text=>'Grade student'}],1,1);
9329: &displayPage($request,$symb);
9330: } elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
9331: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
9332: {href=>'',text=>'Select student'},
9333: {href=>'',text=>'Grade student'},
9334: {href=>'',text=>'Store grades'}],1,1);
9335: &updateGradeByPage($request,$symb);
9336: } elsif ($command eq 'processGroup' && $perm{'vgr'}) {
9337: &startpage($request,$symb,[{href=>'',text=>'...'},
9338: {href=>'',text=>'Modify grades'}]);
9339: &processGroup($request,$symb);
9340: } elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
9341: &startpage($request,$symb);
9342: $request->print(&grading_menu($request,$symb));
9343: } elsif ($command eq 'individual' && $perm{'vgr'}) {
9344: &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
9345: $request->print(&submit_options($request,$symb));
9346: } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
9347: &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
9348: $request->print(&listStudents($request,$symb,'graded'));
9349: } elsif ($command eq 'table' && $perm{'vgr'}) {
9350: &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
9351: $request->print(&submit_options_table($request,$symb));
9352: } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
9353: &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
9354: $request->print(&submit_options_sequence($request,$symb));
9355: } elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
9356: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
9357: $request->print(&viewgrades($request,$symb));
9358: } elsif ($command eq 'handgrade' && $perm{'mgr'}) {
9359: &startpage($request,$symb,[{href=>'',text=>'...'},
9360: {href=>'',text=>'Store grades'}]);
9361: $request->print(&processHandGrade($request,$symb));
9362: } elsif ($command eq 'editgrades' && $perm{'mgr'}) {
9363: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
9364: {href=>&href_symb_cmd($symb,'viewgrades').'&group=all§ion=all&Status=Active',
9365: text=>"Modify grades"},
9366: {href=>'', text=>"Store grades"}]);
9367: $request->print(&editgrades($request,$symb));
9368: } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
9369: &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
9370: $request->print(&initialverifyreceipt($request,$symb));
9371: } elsif ($command eq 'verify' && $perm{'vgr'}) {
9372: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
9373: {href=>'',text=>'Verification Result'}]);
9374: $request->print(&verifyreceipt($request,$symb));
9375: } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
9376: &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
9377: $request->print(&process_clicker($request,$symb));
9378: } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
9379: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
9380: {href=>'', text=>'Process clicker file'}]);
9381: $request->print(&process_clicker_file($request,$symb));
9382: } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
9383: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
9384: {href=>'', text=>'Process clicker file'},
9385: {href=>'', text=>'Store grades'}]);
9386: $request->print(&assign_clicker_grades($request,$symb));
9387: } elsif ($command eq 'csvform' && $perm{'mgr'}) {
9388: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
9389: $request->print(&upcsvScores_form($request,$symb));
9390: } elsif ($command eq 'csvupload' && $perm{'mgr'}) {
9391: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
9392: $request->print(&csvupload($request,$symb));
9393: } elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
9394: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
9395: $request->print(&csvuploadmap($request,$symb));
9396: } elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
9397: if ($env{'form.associate'} ne 'Reverse Association') {
9398: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
9399: $request->print(&csvuploadoptions($request,$symb));
9400: } else {
9401: if ( $env{'form.upfile_associate'} ne 'reverse' ) {
9402: $env{'form.upfile_associate'} = 'reverse';
9403: } else {
9404: $env{'form.upfile_associate'} = 'forward';
9405: }
9406: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
9407: $request->print(&csvuploadmap($request,$symb));
9408: }
9409: } elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
9410: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
9411: $request->print(&csvuploadassign($request,$symb));
9412: } elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
9413: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9414: $request->print(&scantron_selectphase($request,undef,$symb));
9415: } elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
9416: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9417: $request->print(&scantron_do_warning($request,$symb));
9418: } elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
9419: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9420: $request->print(&scantron_validate_file($request,$symb));
9421: } elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
9422: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9423: $request->print(&scantron_process_students($request,$symb));
9424: } elsif ($command eq 'scantronupload' &&
9425: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
9426: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
9427: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9428: $request->print(&scantron_upload_scantron_data($request,$symb));
9429: } elsif ($command eq 'scantronupload_save' &&
9430: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
9431: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
9432: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9433: $request->print(&scantron_upload_scantron_data_save($request,$symb));
9434: } elsif ($command eq 'scantron_download' &&
9435: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
9436: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9437: $request->print(&scantron_download_scantron_data($request,$symb));
9438: } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
9439: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9440: $request->print(&checkscantron_results($request,$symb));
9441: } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
9442: &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
9443: $request->print(&submit_options_download($request,$symb));
9444: } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
9445: &startpage($request,$symb,
9446: [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
9447: {href=>'', text=>'Download submissions'}]);
9448: &submit_download_link($request,$symb);
9449: } elsif ($command) {
9450: &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
9451: $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
9452: }
9453: }
9454: if ($ssi_error) {
9455: &ssi_print_error($request);
9456: }
9457: &Apache::lonquickgrades::endGradeScreen($request);
9458: $request->print(&Apache::loncommon::end_page());
9459: &reset_caches();
9460: return OK;
9461: }
9462:
9463: 1;
9464:
9465: __END__;
9466:
9467:
9468: =head1 NAME
9469:
9470: Apache::grades
9471:
9472: =head1 SYNOPSIS
9473:
9474: Handles the viewing of grades.
9475:
9476: This is part of the LearningOnline Network with CAPA project
9477: described at http://www.lon-capa.org.
9478:
9479: =head1 OVERVIEW
9480:
9481: Do an ssi with retries:
9482: While I'd love to factor out this with the vesrion in lonprintout,
9483: 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
9484: I'm not quite ready to invent (e.g. an ssi_with_retry object).
9485:
9486: At least the logic that drives this has been pulled out into loncommon.
9487:
9488:
9489:
9490: ssi_with_retries - Does the server side include of a resource.
9491: if the ssi call returns an error we'll retry it up to
9492: the number of times requested by the caller.
9493: If we still have a proble, no text is appended to the
9494: output and we set some global variables.
9495: to indicate to the caller an SSI error occurred.
9496: All of this is supposed to deal with the issues described
9497: in LonCAPA BZ 5631 see:
9498: http://bugs.lon-capa.org/show_bug.cgi?id=5631
9499: by informing the user that this happened.
9500:
9501: Parameters:
9502: resource - The resource to include. This is passed directly, without
9503: interpretation to lonnet::ssi.
9504: form - The form hash parameters that guide the interpretation of the resource
9505:
9506: retries - Number of retries allowed before giving up completely.
9507: Returns:
9508: On success, returns the rendered resource identified by the resource parameter.
9509: Side Effects:
9510: The following global variables can be set:
9511: ssi_error - If an unrecoverable error occurred this becomes true.
9512: It is up to the caller to initialize this to false
9513: if desired.
9514: ssi_error_resource - If an unrecoverable error occurred, this is the value
9515: of the resource that could not be rendered by the ssi
9516: call.
9517: ssi_error_message - The error string fetched from the ssi response
9518: in the event of an error.
9519:
9520:
9521: =head1 HANDLER SUBROUTINE
9522:
9523: ssi_with_retries()
9524:
9525: =head1 SUBROUTINES
9526:
9527: =over
9528:
9529: =item scantron_get_correction() :
9530:
9531: Builds the interface screen to interact with the operator to fix a
9532: specific error condition in a specific scanline
9533:
9534: Arguments:
9535: $r - Apache request object
9536: $i - number of the current scanline
9537: $scan_record - hash ref as returned from &scantron_parse_scanline()
9538: $scan_config - hash ref as returned from &get_scantron_config()
9539: $line - full contents of the current scanline
9540: $error - error condition, valid values are
9541: 'incorrectCODE', 'duplicateCODE',
9542: 'doublebubble', 'missingbubble',
9543: 'duplicateID', 'incorrectID'
9544: $arg - extra information needed
9545: For errors:
9546: - duplicateID - paper number that this studentID was seen before on
9547: - duplicateCODE - array ref of the paper numbers this CODE was
9548: seen on before
9549: - incorrectCODE - current incorrect CODE
9550: - doublebubble - array ref of the bubble lines that have double
9551: bubble errors
9552: - missingbubble - array ref of the bubble lines that have missing
9553: bubble errors
9554:
9555: =item scantron_get_maxbubble() :
9556:
9557: Arguments:
9558: $nav_error - Reference to scalar which is a flag to indicate a
9559: failure to retrieve a navmap object.
9560: if $nav_error is set to 1 by scantron_get_maxbubble(), the
9561: calling routine should trap the error condition and display the warning
9562: found in &navmap_errormsg().
9563:
9564: $scantron_config - Reference to bubblesheet format configuration hash.
9565:
9566: Returns the maximum number of bubble lines that are expected to
9567: occur. Does this by walking the selected sequence rendering the
9568: resource and then checking &Apache::lonxml::get_problem_counter()
9569: for what the current value of the problem counter is.
9570:
9571: Caches the results to $env{'form.scantron_maxbubble'},
9572: $env{'form.scantron.bubble_lines.n'},
9573: $env{'form.scantron.first_bubble_line.n'} and
9574: $env{"form.scantron.sub_bubblelines.n"}
9575: which are the total number of bubble, lines, the number of bubble
9576: lines for response n and number of the first bubble line for response n,
9577: and a comma separated list of numbers of bubble lines for sub-questions
9578: (for optionresponse, matchresponse, and rankresponse items), for response n.
9579:
9580:
9581: =item scantron_validate_missingbubbles() :
9582:
9583: Validates all scanlines in the selected file to not have any
9584: answers that don't have bubbles that have not been verified
9585: to be bubble free.
9586:
9587: =item scantron_process_students() :
9588:
9589: Routine that does the actual grading of the bubble sheet information.
9590:
9591: The parsed scanline hash is added to %env
9592:
9593: Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
9594: foreach resource , with the form data of
9595:
9596: 'submitted' =>'scantron'
9597: 'grade_target' =>'grade',
9598: 'grade_username'=> username of student
9599: 'grade_domain' => domain of student
9600: 'grade_courseid'=> of course
9601: 'grade_symb' => symb of resource to grade
9602:
9603: This triggers a grading pass. The problem grading code takes care
9604: of converting the bubbled letter information (now in %env) into a
9605: valid submission.
9606:
9607: =item scantron_upload_scantron_data() :
9608:
9609: Creates the screen for adding a new bubble sheet data file to a course.
9610:
9611: =item scantron_upload_scantron_data_save() :
9612:
9613: Adds a provided bubble information data file to the course if user
9614: has the correct privileges to do so.
9615:
9616: =item valid_file() :
9617:
9618: Validates that the requested bubble data file exists in the course.
9619:
9620: =item scantron_download_scantron_data() :
9621:
9622: Shows a list of the three internal files (original, corrected,
9623: skipped) for a specific bubble sheet data file that exists in the
9624: course.
9625:
9626: =item scantron_validate_ID() :
9627:
9628: Validates all scanlines in the selected file to not have any
9629: invalid or underspecified student/employee IDs
9630:
9631: =item navmap_errormsg() :
9632:
9633: Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
9634: Should be called whenever the request to instantiate a navmap object fails.
9635:
9636: =back
9637:
9638: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>