File:
[LON-CAPA] /
loncom /
homework /
grades.pm
Revision
1.640:
download - view:
text,
annotated -
select for diffs
Sat Dec 18 23:09:57 2010 UTC (13 years, 6 months ago) by
raeburn
Branches:
MAIN
CVS tags:
HEAD
- New Question Type - randomizetry
- New Variation displayed after N tries (default N=1).
- Additional args (type,trial,rndseed) for the following:
&get_analyze(), &get_order(), &get_radiobutton_correct_foil(), &cleanRecord()
- 'New variation this try' displayed in grading screen submissions view
if try used different rndseed.
- rndseed used shown in submission record.
1: # The LearningOnline Network with CAPA
2: # The LON-CAPA Grading handler
3: #
4: # $Id: grades.pm,v 1.640 2010/12/18 23:09:57 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);
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)=@_;
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 ($type eq 'randomizetry') {
251: $form{'grade_questiontype'} = $type;
252: if ($rndseed ne '') {
253: $form{'grade_rndseed'} = $rndseed;
254: }
255: }
256: if (ref($add_to_hash)) {
257: %form = (%form,%{$add_to_hash});
258: }
259: my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
260: (undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
261: my %analyze=&Apache::lonnet::str2hash($subresult);
262: if (ref($add_to_hash) eq 'HASH') {
263: $analyze_cache_formkeys{$key} = $add_to_hash;
264: } else {
265: $analyze_cache_formkeys{$key} = {};
266: }
267: return $analyze_cache{$key} = \%analyze;
268: }
269:
270: sub get_order {
271: my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
272: my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
273: return $analyze->{"$partid.$respid.shown"};
274: }
275:
276: sub get_radiobutton_correct_foil {
277: my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
278: my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
279: my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
280: if (ref($foils) eq 'ARRAY') {
281: foreach my $foil (@{$foils}) {
282: if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
283: return $foil;
284: }
285: }
286: }
287: }
288:
289: sub scantron_partids_tograde {
290: my ($resource,$cid,$uname,$udom,$check_for_randomlist) = @_;
291: my (%analysis,@parts);
292: if (ref($resource)) {
293: my $symb = $resource->symb();
294: my $add_to_form;
295: if ($check_for_randomlist) {
296: $add_to_form = { 'check_parts_withrandomlist' => 1,};
297: }
298: my $analyze = &get_analyze($symb,$uname,$udom,undef,$add_to_form);
299: if (ref($analyze) eq 'HASH') {
300: %analysis = %{$analyze};
301: }
302: if (ref($analysis{'parts'}) eq 'ARRAY') {
303: foreach my $part (@{$analysis{'parts'}}) {
304: my ($id,$respid) = split(/\./,$part);
305: if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
306: push(@parts,$part);
307: }
308: }
309: }
310: }
311: return (\%analysis,\@parts);
312: }
313:
314: }
315:
316: #--- Clean response type for display
317: #--- Currently filters option/rank/radiobutton/match/essay/Task
318: # response types only.
319: sub cleanRecord {
320: my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
321: $uname,$udom,$type,$trial,$rndseed) = @_;
322: my $grayFont = '<span class="LC_internal_info">';
323: if ($response =~ /^(option|rank)$/) {
324: my %answer=&Apache::lonnet::str2hash($answer);
325: my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
326: my ($toprow,$bottomrow);
327: foreach my $foil (@$order) {
328: if ($grading{$foil} == 1) {
329: $toprow.='<td><b>'.$answer{$foil}.' </b></td>';
330: } else {
331: $toprow.='<td><i>'.$answer{$foil}.' </i></td>';
332: }
333: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
334: }
335: return '<blockquote><table border="1">'.
336: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
337: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
338: $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
339: } elsif ($response eq 'match') {
340: my %answer=&Apache::lonnet::str2hash($answer);
341: my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
342: my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
343: my ($toprow,$middlerow,$bottomrow);
344: foreach my $foil (@$order) {
345: my $item=shift(@items);
346: if ($grading{$foil} == 1) {
347: $toprow.='<td><b>'.$item.' </b></td>';
348: $middlerow.='<td><b>'.$grayFont.$answer{$foil}.' </span></b></td>';
349: } else {
350: $toprow.='<td><i>'.$item.' </i></td>';
351: $middlerow.='<td><i>'.$grayFont.$answer{$foil}.' </span></i></td>';
352: }
353: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
354: }
355: return '<blockquote><table border="1">'.
356: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
357: '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
358: $middlerow.'</tr>'.
359: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
360: $bottomrow.'</tr>'.'</table></blockquote>';
361: } elsif ($response eq 'radiobutton') {
362: my %answer=&Apache::lonnet::str2hash($answer);
363: my ($toprow,$bottomrow);
364: my $correct =
365: &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
366: foreach my $foil (@$order) {
367: if (exists($answer{$foil})) {
368: if ($foil eq $correct) {
369: $toprow.='<td><b>'.&mt('true').'</b></td>';
370: } else {
371: $toprow.='<td><i>'.&mt('true').'</i></td>';
372: }
373: } else {
374: $toprow.='<td>'.&mt('false').'</td>';
375: }
376: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
377: }
378: return '<blockquote><table border="1">'.
379: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
380: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
381: $bottomrow.'</tr>'.'</table></blockquote>';
382: } elsif ($response eq 'essay') {
383: if (! exists ($env{'form.'.$symb})) {
384: my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
385: $env{'course.'.$env{'request.course.id'}.'.domain'},
386: $env{'course.'.$env{'request.course.id'}.'.num'});
387:
388: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
389: $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
390: $env{'form.kwclr'} = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
391: $env{'form.kwsize'} = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
392: $env{'form.kwstyle'} = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
393: $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
394: }
395: $answer =~ s-\n-<br />-g;
396: return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
397: } elsif ( $response eq 'organic') {
398: my $result='Smile representation: "<tt>'.$answer.'</tt>"';
399: my $jme=$record->{$version."resource.$partid.$respid.molecule"};
400: $result.=&Apache::chemresponse::jme_img($jme,$answer,400);
401: return $result;
402: } elsif ( $response eq 'Task') {
403: if ( $answer eq 'SUBMITTED') {
404: my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
405: my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
406: return $result;
407: } elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
408: my @matches = grep(/^\Q$version\E.*?\.instance$/,
409: keys(%{$record}));
410: return join('<br />',($version,@matches));
411:
412:
413: } else {
414: my $result =
415: '<p>'
416: .&mt('Overall result: [_1]',
417: $record->{$version."resource.$respid.$partid.status"})
418: .'</p>';
419:
420: $result .= '<ul>';
421: my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
422: keys(%{$record}));
423: foreach my $grade (sort(@grade)) {
424: my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
425: $result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
426: $dim, $record->{$grade}).
427: '</li>';
428: }
429: $result.='</ul>';
430: return $result;
431: }
432: } elsif ( $response =~ m/(?:numerical|formula)/) {
433: $answer =
434: &Apache::loncommon::format_previous_attempt_value('submission',
435: $answer);
436: }
437: return $answer;
438: }
439:
440: #-- A couple of common js functions
441: sub commonJSfunctions {
442: my $request = shift;
443: $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
444: function radioSelection(radioButton) {
445: var selection=null;
446: if (radioButton.length > 1) {
447: for (var i=0; i<radioButton.length; i++) {
448: if (radioButton[i].checked) {
449: return radioButton[i].value;
450: }
451: }
452: } else {
453: if (radioButton.checked) return radioButton.value;
454: }
455: return selection;
456: }
457:
458: function pullDownSelection(selectOne) {
459: var selection="";
460: if (selectOne.length > 1) {
461: for (var i=0; i<selectOne.length; i++) {
462: if (selectOne[i].selected) {
463: return selectOne[i].value;
464: }
465: }
466: } else {
467: // only one value it must be the selected one
468: return selectOne.value;
469: }
470: }
471: COMMONJSFUNCTIONS
472: }
473:
474: #--- Dumps the class list with usernames,list of sections,
475: #--- section, ids and fullnames for each user.
476: sub getclasslist {
477: my ($getsec,$filterlist,$getgroup) = @_;
478: my @getsec;
479: my @getgroup;
480: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
481: if (!ref($getsec)) {
482: if ($getsec ne '' && $getsec ne 'all') {
483: @getsec=($getsec);
484: }
485: } else {
486: @getsec=@{$getsec};
487: }
488: if (grep(/^all$/,@getsec)) { undef(@getsec); }
489: if (!ref($getgroup)) {
490: if ($getgroup ne '' && $getgroup ne 'all') {
491: @getgroup=($getgroup);
492: }
493: } else {
494: @getgroup=@{$getgroup};
495: }
496: if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
497:
498: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
499: # Bail out if we were unable to get the classlist
500: return if (! defined($classlist));
501: &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
502: #
503: my %sections;
504: my %fullnames;
505: foreach my $student (keys(%$classlist)) {
506: my $end =
507: $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
508: my $start =
509: $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
510: my $id =
511: $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
512: my $section =
513: $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
514: my $fullname =
515: $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
516: my $status =
517: $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
518: my $group =
519: $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
520: # filter students according to status selected
521: if ($filterlist && (!($stu_status =~ /Any/))) {
522: if (!($stu_status =~ $status)) {
523: delete($classlist->{$student});
524: next;
525: }
526: }
527: # filter students according to groups selected
528: my @stu_groups = split(/,/,$group);
529: if (@getgroup) {
530: my $exclude = 1;
531: foreach my $grp (@getgroup) {
532: foreach my $stu_group (@stu_groups) {
533: if ($stu_group eq $grp) {
534: $exclude = 0;
535: }
536: }
537: if (($grp eq 'none') && !$group) {
538: $exclude = 0;
539: }
540: }
541: if ($exclude) {
542: delete($classlist->{$student});
543: }
544: }
545: $section = ($section ne '' ? $section : 'none');
546: if (&canview($section)) {
547: if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
548: $sections{$section}++;
549: if ($classlist->{$student}) {
550: $fullnames{$student}=$fullname;
551: }
552: } else {
553: delete($classlist->{$student});
554: }
555: } else {
556: delete($classlist->{$student});
557: }
558: }
559: my %seen = ();
560: my @sections = sort(keys(%sections));
561: return ($classlist,\@sections,\%fullnames);
562: }
563:
564: sub canmodify {
565: my ($sec)=@_;
566: if ($perm{'mgr'}) {
567: if (!defined($perm{'mgr_section'})) {
568: # can modify whole class
569: return 1;
570: } else {
571: if ($sec eq $perm{'mgr_section'}) {
572: #can modify the requested section
573: return 1;
574: } else {
575: # can't modify the request section
576: return 0;
577: }
578: }
579: }
580: #can't modify
581: return 0;
582: }
583:
584: sub canview {
585: my ($sec)=@_;
586: if ($perm{'vgr'}) {
587: if (!defined($perm{'vgr_section'})) {
588: # can modify whole class
589: return 1;
590: } else {
591: if ($sec eq $perm{'vgr_section'}) {
592: #can modify the requested section
593: return 1;
594: } else {
595: # can't modify the request section
596: return 0;
597: }
598: }
599: }
600: #can't modify
601: return 0;
602: }
603:
604: #--- Retrieve the grade status of a student for all the parts
605: sub student_gradeStatus {
606: my ($symb,$udom,$uname,$partlist) = @_;
607: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
608: my %partstatus = ();
609: foreach (@$partlist) {
610: my ($status,undef) = split(/_/,$record{"resource.$_.solved"},2);
611: $status = 'nothing' if ($status eq '');
612: $partstatus{$_} = $status;
613: my $subkey = "resource.$_.submitted_by";
614: $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
615: }
616: return %partstatus;
617: }
618:
619: # hidden form and javascript that calls the form
620: # Use by verifyscript and viewgrades
621: # Shows a student's view of problem and submission
622: sub jscriptNform {
623: my ($symb) = @_;
624: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
625: my $jscript= &Apache::lonhtmlcommon::scripttag(
626: ' function viewOneStudent(user,domain) {'."\n".
627: ' document.onestudent.student.value = user;'."\n".
628: ' document.onestudent.userdom.value = domain;'."\n".
629: ' document.onestudent.submit();'."\n".
630: ' }'."\n".
631: "\n");
632: $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
633: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
634: '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
635: '<input type="hidden" name="command" value="submission" />'."\n".
636: '<input type="hidden" name="student" value="" />'."\n".
637: '<input type="hidden" name="userdom" value="" />'."\n".
638: '</form>'."\n";
639: return $jscript;
640: }
641:
642:
643:
644: # Given the score (as a number [0-1] and the weight) what is the final
645: # point value? This function will round to the nearest tenth, third,
646: # or quarter if one of those is within the tolerance of .00001.
647: sub compute_points {
648: my ($score, $weight) = @_;
649:
650: my $tolerance = .00001;
651: my $points = $score * $weight;
652:
653: # Check for nearness to 1/x.
654: my $check_for_nearness = sub {
655: my ($factor) = @_;
656: my $num = ($points * $factor) + $tolerance;
657: my $floored_num = floor($num);
658: if ($num - $floored_num < 2 * $tolerance * $factor) {
659: return $floored_num / $factor;
660: }
661: return $points;
662: };
663:
664: $points = $check_for_nearness->(10);
665: $points = $check_for_nearness->(3);
666: $points = $check_for_nearness->(4);
667:
668: return $points;
669: }
670:
671: #------------------ End of general use routines --------------------
672:
673: #
674: # Find most similar essay
675: #
676:
677: sub most_similar {
678: my ($uname,$udom,$uessay,$old_essays)=@_;
679:
680: # ignore spaces and punctuation
681:
682: $uessay=~s/\W+/ /gs;
683:
684: # ignore empty submissions (occuring when only files are sent)
685:
686: unless ($uessay=~/\w+/s) { return ''; }
687:
688: # these will be returned. Do not care if not at least 50 percent similar
689: my $limit=0.6;
690: my $sname='';
691: my $sdom='';
692: my $scrsid='';
693: my $sessay='';
694: # go through all essays ...
695: foreach my $tkey (keys(%$old_essays)) {
696: my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
697: # ... except the same student
698: next if (($tname eq $uname) && ($tdom eq $udom));
699: my $tessay=$old_essays->{$tkey};
700: $tessay=~s/\W+/ /gs;
701: # String similarity gives up if not even limit
702: my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
703: # Found one
704: if ($tsimilar>$limit) {
705: $limit=$tsimilar;
706: $sname=$tname;
707: $sdom=$tdom;
708: $scrsid=$tcrsid;
709: $sessay=$old_essays->{$tkey};
710: }
711: }
712: if ($limit>0.6) {
713: return ($sname,$sdom,$scrsid,$sessay,$limit);
714: } else {
715: return ('','','','',0);
716: }
717: }
718:
719: #-------------------------------------------------------------------
720:
721: #------------------------------------ Receipt Verification Routines
722: #
723:
724: sub initialverifyreceipt {
725: my ($request,$symb) = @_;
726: &commonJSfunctions($request);
727: return '<form name="gradingMenu"><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
728: &Apache::lonnet::recprefix($env{'request.course.id'}).
729: '-<input type="text" name="receipt" size="4" />'.
730: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
731: '<input type="hidden" name="command" value="verify" />'.
732: "</form>\n";
733: }
734:
735: #--- Check whether a receipt number is valid.---
736: sub verifyreceipt {
737: my ($request,$symb) = @_;
738:
739: my $courseid = $env{'request.course.id'};
740: my $receipt = &Apache::lonnet::recprefix($courseid).'-'.
741: $env{'form.receipt'};
742: $receipt =~ s/[^\-\d]//g;
743:
744: my $title.=
745: '<h3><span class="LC_info">'.
746: &mt('Verifying Receipt Number [_1]',$receipt).
747: '</span></h3>'."\n";
748:
749: my ($string,$contents,$matches) = ('','',0);
750: my (undef,undef,$fullname) = &getclasslist('all','0');
751:
752: my $receiptparts=0;
753: if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
754: $env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
755: my $parts=['0'];
756: if ($receiptparts) {
757: my $res_error;
758: ($parts)=&response_type($symb,\$res_error);
759: if ($res_error) {
760: return &navmap_errormsg();
761: }
762: }
763:
764: my $header =
765: &Apache::loncommon::start_data_table().
766: &Apache::loncommon::start_data_table_header_row().
767: '<th> '.&mt('Fullname').' </th>'."\n".
768: '<th> '.&mt('Username').' </th>'."\n".
769: '<th> '.&mt('Domain').' </th>';
770: if ($receiptparts) {
771: $header.='<th> '.&mt('Problem Part').' </th>';
772: }
773: $header.=
774: &Apache::loncommon::end_data_table_header_row();
775:
776: foreach (sort
777: {
778: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
779: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
780: }
781: return $a cmp $b;
782: } (keys(%$fullname))) {
783: my ($uname,$udom)=split(/\:/);
784: foreach my $part (@$parts) {
785: if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
786: $contents.=
787: &Apache::loncommon::start_data_table_row().
788: '<td> '."\n".
789: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
790: '\');" target="_self">'.$$fullname{$_}.'</a> </td>'."\n".
791: '<td> '.$uname.' </td>'.
792: '<td> '.$udom.' </td>';
793: if ($receiptparts) {
794: $contents.='<td> '.$part.' </td>';
795: }
796: $contents.=
797: &Apache::loncommon::end_data_table_row()."\n";
798:
799: $matches++;
800: }
801: }
802: }
803: if ($matches == 0) {
804: $string = $title
805: .'<p class="LC_warning">'
806: .&mt('No match found for the above receipt number.')
807: .'</p>';
808: } else {
809: $string = &jscriptNform($symb).$title.
810: '<p>'.
811: &mt('The above receipt number matches the following [quant,_1,student].',$matches).
812: '</p>'.
813: $header.
814: $contents.
815: &Apache::loncommon::end_data_table()."\n";
816: }
817: return $string;
818: }
819:
820: #--- This is called by a number of programs.
821: #--- Called from the Grading Menu - View/Grade an individual student
822: #--- Also called directly when one clicks on the subm button
823: # on the problem page.
824: sub listStudents {
825: my ($request,$symb,$submitonly) = @_;
826:
827: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
828: my $cnum = $env{"course.$env{'request.course.id'}.num"};
829: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
830: my $getgroup = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
831: unless ($submitonly) {
832: $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
833: }
834:
835: my $result='';
836: my $res_error;
837: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
838:
839: my %lt = &Apache::lonlocal::texthash (
840: 'multiple' => 'Please select a student or group of students before clicking on the Next button.',
841: 'single' => 'Please select the student before clicking on the Next button.',
842: );
843: $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
844: function checkSelect(checkBox) {
845: var ctr=0;
846: var sense="";
847: if (checkBox.length > 1) {
848: for (var i=0; i<checkBox.length; i++) {
849: if (checkBox[i].checked) {
850: ctr++;
851: }
852: }
853: sense = '$lt{'multiple'}';
854: } else {
855: if (checkBox.checked) {
856: ctr = 1;
857: }
858: sense = '$lt{'single'}';
859: }
860: if (ctr == 0) {
861: alert(sense);
862: return false;
863: }
864: document.gradesub.submit();
865: }
866:
867: function reLoadList(formname) {
868: if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
869: formname.command.value = 'submission';
870: formname.submit();
871: }
872: LISTJAVASCRIPT
873:
874: &commonJSfunctions($request);
875: $request->print($result);
876:
877: my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
878: "\n";
879:
880: $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
881: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
882: .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
883: .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
884: .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
885: .&Apache::lonhtmlcommon::row_closure();
886: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
887: .'<label><input type="radio" name="vAns" value="no" /> '.&mt('no').' </label>'."\n"
888: .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
889: .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
890: .&Apache::lonhtmlcommon::row_closure();
891:
892: my $submission_options;
893: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
894: my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
895: $env{'form.Status'} = $saveStatus;
896: $submission_options.=
897: '<span class="LC_nobreak">'.
898: '<label><input type="radio" name="lastSub" value="lastonly" /> '.
899: &mt('last submission only').' </label></span>'."\n".
900: '<span class="LC_nobreak">'.
901: '<label><input type="radio" name="lastSub" value="last" /> '.
902: &mt('last submission & parts info').' </label></span>'."\n".
903: '<span class="LC_nobreak">'.
904: '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
905: &mt('by dates and submissions').'</label></span>'."\n".
906: '<span class="LC_nobreak">'.
907: '<label><input type="radio" name="lastSub" value="all" /> '.
908: &mt('all details').'</label></span>';
909: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
910: .$submission_options
911: .&Apache::lonhtmlcommon::row_closure();
912:
913: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
914: .'<select name="increment">'
915: .'<option value="1">'.&mt('Whole Points').'</option>'
916: .'<option value=".5">'.&mt('Half Points').'</option>'
917: .'<option value=".25">'.&mt('Quarter Points').'</option>'
918: .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
919: .'</select>'
920: .&Apache::lonhtmlcommon::row_closure();
921:
922: $gradeTable .=
923: &build_section_inputs().
924: '<input type="hidden" name="submitonly" value="'.$submitonly.'" />'."\n".
925: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
926: '<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
927:
928: if (exists($env{'form.Status'})) {
929: $gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
930: } else {
931: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
932: .&Apache::lonhtmlcommon::StatusOptions(
933: $saveStatus,undef,1,'javascript:reLoadList(this.form);')
934: .&Apache::lonhtmlcommon::row_closure();
935: }
936:
937: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
938: .'<input type="checkbox" name="checkPlag" checked="checked" />'
939: .&Apache::lonhtmlcommon::row_closure(1)
940: .&Apache::lonhtmlcommon::end_pick_box();
941:
942: $gradeTable .= '<p>'
943: .&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"
944: .'<input type="hidden" name="command" value="processGroup" />'
945: .'</p>';
946:
947: # checkall buttons
948: $gradeTable.=&check_script('gradesub', 'stuinfo');
949: $gradeTable.='<input type="button" '."\n".
950: 'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
951: 'value="'.&mt('Next').' →" /> <br />'."\n";
952: $gradeTable.=&check_buttons();
953: my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
954: $gradeTable.= &Apache::loncommon::start_data_table().
955: &Apache::loncommon::start_data_table_header_row();
956: my $loop = 0;
957: while ($loop < 2) {
958: $gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
959: '<th>'.&nameUserString('header').' '.&mt('Section/Group').'</th>';
960: if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
961: foreach my $part (sort(@$partlist)) {
962: my $display_part=
963: &get_display_part((split(/_/,$part))[0],$symb);
964: $gradeTable.=
965: '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
966: }
967: } elsif ($submitonly eq 'queued') {
968: $gradeTable.='<th>'.&mt('Queue Status').' </th>';
969: }
970: $loop++;
971: # $gradeTable.='<td></td>' if ($loop%2 ==1);
972: }
973: $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
974:
975: my $ctr = 0;
976: foreach my $student (sort
977: {
978: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
979: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
980: }
981: return $a cmp $b;
982: }
983: (keys(%$fullname))) {
984: my ($uname,$udom) = split(/:/,$student);
985:
986: my %status = ();
987:
988: if ($submitonly eq 'queued') {
989: my %queue_status =
990: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
991: $udom,$uname);
992: next if (!defined($queue_status{'gradingqueue'}));
993: $status{'gradingqueue'} = $queue_status{'gradingqueue'};
994: }
995:
996: if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
997: (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
998: my $submitted = 0;
999: my $graded = 0;
1000: my $incorrect = 0;
1001: foreach (keys(%status)) {
1002: $submitted = 1 if ($status{$_} ne 'nothing');
1003: $graded = 1 if ($status{$_} =~ /^ungraded/);
1004: $incorrect = 1 if ($status{$_} =~ /^incorrect/);
1005:
1006: my ($foo,$partid,$foo1) = split(/\./,$_);
1007: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1008: $submitted = 0;
1009: my ($part)=split(/\./,$partid);
1010: $gradeTable.='<input type="hidden" name="'.
1011: $student.':'.$part.':submitted_by" value="'.
1012: $status{'resource.'.$partid.'.submitted_by'}.'" />';
1013: }
1014: }
1015:
1016: next if (!$submitted && ($submitonly eq 'yes' ||
1017: $submitonly eq 'incorrect' ||
1018: $submitonly eq 'graded'));
1019: next if (!$graded && ($submitonly eq 'graded'));
1020: next if (!$incorrect && $submitonly eq 'incorrect');
1021: }
1022:
1023: $ctr++;
1024: my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1025: my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1026: if ( $perm{'vgr'} eq 'F' ) {
1027: if ($ctr%2 ==1) {
1028: $gradeTable.= &Apache::loncommon::start_data_table_row();
1029: }
1030: $gradeTable.='<td align="right">'.$ctr.' </td>'.
1031: '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1032: $student.':'.$$fullname{$student}.':::SECTION'.$section.
1033: ') " /> </label></td>'."\n".'<td>'.
1034: &nameUserString(undef,$$fullname{$student},$uname,$udom).
1035: ' '.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1036:
1037: if ($submitonly ne 'all') {
1038: foreach (sort(keys(%status))) {
1039: next if ($_ =~ /^resource.*?submitted_by$/);
1040: $gradeTable.='<td align="center"> '.&mt($status{$_}).' </td>'."\n";
1041: }
1042: }
1043: # $gradeTable.='<td></td>' if ($ctr%2 ==1);
1044: if ($ctr%2 ==0) {
1045: $gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
1046: }
1047: }
1048: }
1049: if ($ctr%2 ==1) {
1050: $gradeTable.='<td> </td><td> </td><td> </td>';
1051: if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1052: foreach (@$partlist) {
1053: $gradeTable.='<td> </td>';
1054: }
1055: } elsif ($submitonly eq 'queued') {
1056: $gradeTable.='<td> </td>';
1057: }
1058: $gradeTable.=&Apache::loncommon::end_data_table_row();
1059: }
1060:
1061: $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1062: '<input type="button" '.
1063: 'onclick="javascript:checkSelect(this.form.stuinfo);" '.
1064: 'value="'.&mt('Next').' →" /></form>'."\n";
1065: if ($ctr == 0) {
1066: my $num_students=(scalar(keys(%$fullname)));
1067: if ($num_students eq 0) {
1068: $gradeTable='<br /> <span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1069: } else {
1070: my $submissions='submissions';
1071: if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
1072: if ($submitonly eq 'graded' ) { $submissions = 'ungraded submissions'; }
1073: if ($submitonly eq 'queued' ) { $submissions = 'queued submissions'; }
1074: $gradeTable='<br /> <span class="LC_warning">'.
1075: &mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
1076: $num_students).
1077: '</span><br />';
1078: }
1079: } elsif ($ctr == 1) {
1080: $gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1081: }
1082: $request->print($gradeTable);
1083: return '';
1084: }
1085:
1086: #---- Called from the listStudents routine
1087:
1088: sub check_script {
1089: my ($form, $type)=@_;
1090: my $chkallscript= &Apache::lonhtmlcommon::scripttag('
1091: function checkall() {
1092: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1093: ele = document.forms.'.$form.'.elements[i];
1094: if (ele.name == "'.$type.'") {
1095: document.forms.'.$form.'.elements[i].checked=true;
1096: }
1097: }
1098: }
1099:
1100: function checksec() {
1101: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1102: ele = document.forms.'.$form.'.elements[i];
1103: string = document.forms.'.$form.'.chksec.value;
1104: if
1105: (ele.value.indexOf(":::SECTION"+string)>0) {
1106: document.forms.'.$form.'.elements[i].checked=true;
1107: }
1108: }
1109: }
1110:
1111:
1112: function uncheckall() {
1113: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1114: ele = document.forms.'.$form.'.elements[i];
1115: if (ele.name == "'.$type.'") {
1116: document.forms.'.$form.'.elements[i].checked=false;
1117: }
1118: }
1119: }
1120:
1121: '."\n");
1122: return $chkallscript;
1123: }
1124:
1125: sub check_buttons {
1126: my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
1127: $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" /> ';
1128: $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1129: $buttons.='<input type="text" size="5" name="chksec" /> ';
1130: return $buttons;
1131: }
1132:
1133: # Displays the submissions for one student or a group of students
1134: sub processGroup {
1135: my ($request,$symb) = @_;
1136: my $ctr = 0;
1137: my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1138: my $total = scalar(@stuchecked)-1;
1139:
1140: foreach my $student (@stuchecked) {
1141: my ($uname,$udom,$fullname) = split(/:/,$student);
1142: $env{'form.student'} = $uname;
1143: $env{'form.userdom'} = $udom;
1144: $env{'form.fullname'} = $fullname;
1145: &submission($request,$ctr,$total,$symb);
1146: $ctr++;
1147: }
1148: return '';
1149: }
1150:
1151: #------------------------------------------------------------------------------------
1152: #
1153: #-------------------------- Next few routines handles grading by student, essentially
1154: # handles essay response type problem/part
1155: #
1156: #--- Javascript to handle the submission page functionality ---
1157: sub sub_page_js {
1158: my $request = shift;
1159: my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1160: $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1161: function updateRadio(formname,id,weight) {
1162: var gradeBox = formname["GD_BOX"+id];
1163: var radioButton = formname["RADVAL"+id];
1164: var oldpts = formname["oldpts"+id].value;
1165: var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1166: gradeBox.value = pts;
1167: var resetbox = false;
1168: if (isNaN(pts) || pts < 0) {
1169: alert("$alertmsg"+pts);
1170: for (var i=0; i<radioButton.length; i++) {
1171: if (radioButton[i].checked) {
1172: gradeBox.value = i;
1173: resetbox = true;
1174: }
1175: }
1176: if (!resetbox) {
1177: formtextbox.value = "";
1178: }
1179: return;
1180: }
1181:
1182: if (pts > weight) {
1183: var resp = confirm("You entered a value ("+pts+
1184: ") greater than the weight for the part. Accept?");
1185: if (resp == false) {
1186: gradeBox.value = oldpts;
1187: return;
1188: }
1189: }
1190:
1191: for (var i=0; i<radioButton.length; i++) {
1192: radioButton[i].checked=false;
1193: if (pts == i && pts != "") {
1194: radioButton[i].checked=true;
1195: }
1196: }
1197: updateSelect(formname,id);
1198: formname["stores"+id].value = "0";
1199: }
1200:
1201: function writeBox(formname,id,pts) {
1202: var gradeBox = formname["GD_BOX"+id];
1203: if (checkSolved(formname,id) == 'update') {
1204: gradeBox.value = pts;
1205: } else {
1206: var oldpts = formname["oldpts"+id].value;
1207: gradeBox.value = oldpts;
1208: var radioButton = formname["RADVAL"+id];
1209: for (var i=0; i<radioButton.length; i++) {
1210: radioButton[i].checked=false;
1211: if (i == oldpts) {
1212: radioButton[i].checked=true;
1213: }
1214: }
1215: }
1216: formname["stores"+id].value = "0";
1217: updateSelect(formname,id);
1218: return;
1219: }
1220:
1221: function clearRadBox(formname,id) {
1222: if (checkSolved(formname,id) == 'noupdate') {
1223: updateSelect(formname,id);
1224: return;
1225: }
1226: gradeSelect = formname["GD_SEL"+id];
1227: for (var i=0; i<gradeSelect.length; i++) {
1228: if (gradeSelect[i].selected) {
1229: var selectx=i;
1230: }
1231: }
1232: var stores = formname["stores"+id];
1233: if (selectx == stores.value) { return };
1234: var gradeBox = formname["GD_BOX"+id];
1235: gradeBox.value = "";
1236: var radioButton = formname["RADVAL"+id];
1237: for (var i=0; i<radioButton.length; i++) {
1238: radioButton[i].checked=false;
1239: }
1240: stores.value = selectx;
1241: }
1242:
1243: function checkSolved(formname,id) {
1244: if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1245: var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
1246: if (!reply) {return "noupdate";}
1247: formname.overRideScore.value = 'yes';
1248: }
1249: return "update";
1250: }
1251:
1252: function updateSelect(formname,id) {
1253: formname["GD_SEL"+id][0].selected = true;
1254: return;
1255: }
1256:
1257: //=========== Check that a point is assigned for all the parts ============
1258: function checksubmit(formname,val,total,parttot) {
1259: formname.gradeOpt.value = val;
1260: if (val == "Save & Next") {
1261: for (i=0;i<=total;i++) {
1262: for (j=0;j<parttot;j++) {
1263: var partid = formname["partid"+i+"_"+j].value;
1264: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1265: var points = formname["GD_BOX"+i+"_"+partid].value;
1266: if (points == "") {
1267: var name = formname["name"+i].value;
1268: var studentID = (name != '' ? name : formname["unamedom"+i].value);
1269: var resp = confirm("You did not assign a score for "+studentID+
1270: ", part "+partid+". Continue?");
1271: if (resp == false) {
1272: formname["GD_BOX"+i+"_"+partid].focus();
1273: return false;
1274: }
1275: }
1276: }
1277:
1278: }
1279: }
1280:
1281: }
1282: formname.submit();
1283: }
1284:
1285: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
1286: function checkSubmitPage(formname,total) {
1287: noscore = new Array(100);
1288: var ptr = 0;
1289: for (i=1;i<total;i++) {
1290: var partid = formname["q_"+i].value;
1291: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1292: var points = formname["GD_BOX"+i+"_"+partid].value;
1293: var status = formname["solved"+i+"_"+partid].value;
1294: if (points == "" && status != "correct_by_student") {
1295: noscore[ptr] = i;
1296: ptr++;
1297: }
1298: }
1299: }
1300: if (ptr != 0) {
1301: var sense = ptr == 1 ? ": " : "s: ";
1302: var prolist = "";
1303: if (ptr == 1) {
1304: prolist = noscore[0];
1305: } else {
1306: var i = 0;
1307: while (i < ptr-1) {
1308: prolist += noscore[i]+", ";
1309: i++;
1310: }
1311: prolist += "and "+noscore[i];
1312: }
1313: var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
1314: if (resp == false) {
1315: return false;
1316: }
1317: }
1318:
1319: formname.submit();
1320: }
1321: SUBJAVASCRIPT
1322: }
1323:
1324: #--- javascript for essay type problem --
1325: sub sub_page_kw_js {
1326: my $request = shift;
1327: my $iconpath = $request->dir_config('lonIconsURL');
1328: &commonJSfunctions($request);
1329:
1330: my $inner_js_msg_central= (<<INNERJS);
1331: <script type="text/javascript">
1332: function checkInput() {
1333: opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
1334: var nmsg = opener.document.SCORE.savemsgN.value;
1335: var usrctr = document.msgcenter.usrctr.value;
1336: var newval = opener.document.SCORE["newmsg"+usrctr];
1337: newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
1338:
1339: var msgchk = "";
1340: if (document.msgcenter.subchk.checked) {
1341: msgchk = "msgsub,";
1342: }
1343: var includemsg = 0;
1344: for (var i=1; i<=nmsg; i++) {
1345: var opnmsg = opener.document.SCORE["savemsg"+i];
1346: var frmmsg = document.msgcenter["msg"+i];
1347: opnmsg.value = opener.checkEntities(frmmsg.value);
1348: var showflg = opener.document.SCORE["shownOnce"+i];
1349: showflg.value = "1";
1350: var chkbox = document.msgcenter["msgn"+i];
1351: if (chkbox.checked) {
1352: msgchk += "savemsg"+i+",";
1353: includemsg = 1;
1354: }
1355: }
1356: if (document.msgcenter.newmsgchk.checked) {
1357: msgchk += "newmsg"+usrctr;
1358: includemsg = 1;
1359: }
1360: imgformname = opener.document.SCORE["mailicon"+usrctr];
1361: imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
1362: var includemsg = opener.document.SCORE["includemsg"+usrctr];
1363: includemsg.value = msgchk;
1364:
1365: self.close()
1366:
1367: }
1368: </script>
1369: INNERJS
1370:
1371: my $inner_js_highlight_central= (<<INNERJS);
1372: <script type="text/javascript">
1373: function updateChoice(flag) {
1374: opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
1375: opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
1376: opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
1377: opener.document.SCORE.refresh.value = "on";
1378: if (opener.document.SCORE.keywords.value!=""){
1379: opener.document.SCORE.submit();
1380: }
1381: self.close()
1382: }
1383: </script>
1384: INNERJS
1385:
1386: my $start_page_msg_central =
1387: &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
1388: {'js_ready' => 1,
1389: 'only_body' => 1,
1390: 'bgcolor' =>'#FFFFFF',});
1391: my $end_page_msg_central =
1392: &Apache::loncommon::end_page({'js_ready' => 1});
1393:
1394:
1395: my $start_page_highlight_central =
1396: &Apache::loncommon::start_page('Highlight Central',
1397: $inner_js_highlight_central,
1398: {'js_ready' => 1,
1399: 'only_body' => 1,
1400: 'bgcolor' =>'#FFFFFF',});
1401: my $end_page_highlight_central =
1402: &Apache::loncommon::end_page({'js_ready' => 1});
1403:
1404: my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1405: $docopen=~s/^document\.//;
1406: my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
1407: $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1408:
1409: //===================== Show list of keywords ====================
1410: function keywords(formname) {
1411: var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1412: if (nret==null) return;
1413: formname.keywords.value = nret;
1414:
1415: if (formname.keywords.value != "") {
1416: formname.refresh.value = "on";
1417: formname.submit();
1418: }
1419: return;
1420: }
1421:
1422: //===================== Script to view submitted by ==================
1423: function viewSubmitter(submitter) {
1424: document.SCORE.refresh.value = "on";
1425: document.SCORE.NCT.value = "1";
1426: document.SCORE.unamedom0.value = submitter;
1427: document.SCORE.submit();
1428: return;
1429: }
1430:
1431: //===================== Script to add keyword(s) ==================
1432: function getSel() {
1433: if (document.getSelection) txt = document.getSelection();
1434: else if (document.selection) txt = document.selection.createRange().text;
1435: else return;
1436: var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
1437: if (cleantxt=="") {
1438: alert("$alertmsg");
1439: return;
1440: }
1441: var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
1442: if (nret==null) return;
1443: document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1444: if (document.SCORE.keywords.value != "") {
1445: document.SCORE.refresh.value = "on";
1446: document.SCORE.submit();
1447: }
1448: return;
1449: }
1450:
1451: //====================== Script for composing message ==============
1452: // preload images
1453: img1 = new Image();
1454: img1.src = "$iconpath/mailbkgrd.gif";
1455: img2 = new Image();
1456: img2.src = "$iconpath/mailto.gif";
1457:
1458: function msgCenter(msgform,usrctr,fullname) {
1459: var Nmsg = msgform.savemsgN.value;
1460: savedMsgHeader(Nmsg,usrctr,fullname);
1461: var subject = msgform.msgsub.value;
1462: var msgchk = document.SCORE["includemsg"+usrctr].value;
1463: re = /msgsub/;
1464: var shwsel = "";
1465: if (re.test(msgchk)) { shwsel = "checked" }
1466: subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
1467: displaySubject(checkEntities(subject),shwsel);
1468: for (var i=1; i<=Nmsg; i++) {
1469: var testmsg = "savemsg"+i+",";
1470: re = new RegExp(testmsg,"g");
1471: shwsel = "";
1472: if (re.test(msgchk)) { shwsel = "checked" }
1473: var message = document.SCORE["savemsg"+i].value;
1474: message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1475: displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
1476: //any < is already converted to <, etc. However, only once!!
1477: }
1478: newmsg = document.SCORE["newmsg"+usrctr].value;
1479: shwsel = "";
1480: re = /newmsg/;
1481: if (re.test(msgchk)) { shwsel = "checked" }
1482: newMsg(newmsg,shwsel);
1483: msgTail();
1484: return;
1485: }
1486:
1487: function checkEntities(strx) {
1488: if (strx.length == 0) return strx;
1489: var orgStr = ["&", "<", ">", '"'];
1490: var newStr = ["&", "<", ">", """];
1491: var counter = 0;
1492: while (counter < 4) {
1493: strx = strReplace(strx,orgStr[counter],newStr[counter]);
1494: counter++;
1495: }
1496: return strx;
1497: }
1498:
1499: function strReplace(strx, orgStr, newStr) {
1500: return strx.split(orgStr).join(newStr);
1501: }
1502:
1503: function savedMsgHeader(Nmsg,usrctr,fullname) {
1504: var height = 70*Nmsg+250;
1505: var scrollbar = "no";
1506: if (height > 600) {
1507: height = 600;
1508: scrollbar = "yes";
1509: }
1510: var xpos = (screen.width-600)/2;
1511: xpos = (xpos < 0) ? '0' : xpos;
1512: var ypos = (screen.height-height)/2-30;
1513: ypos = (ypos < 0) ? '0' : ypos;
1514:
1515: pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1516: pWin.focus();
1517: pDoc = pWin.document;
1518: pDoc.$docopen;
1519: pDoc.write('$start_page_msg_central');
1520:
1521: pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
1522: pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1523: pDoc.write("<h3><span class=\\"LC_info\\"> Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
1524:
1525: pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
1526: pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1527: pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
1528: }
1529: function displaySubject(msg,shwsel) {
1530: pDoc = pWin.document;
1531: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1532: pDoc.write("<td>Subject<\\/td>");
1533: pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1534: pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1535: }
1536:
1537: function displaySavedMsg(ctr,msg,shwsel) {
1538: pDoc = pWin.document;
1539: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1540: pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
1541: pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1542: pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1543: }
1544:
1545: function newMsg(newmsg,shwsel) {
1546: pDoc = pWin.document;
1547: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1548: pDoc.write("<td align=\\"center\\">New<\\/td>");
1549: pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1550: pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1551: }
1552:
1553: function msgTail() {
1554: pDoc = pWin.document;
1555: pDoc.write("<\\/table>");
1556: pDoc.write("<\\/td><\\/tr><\\/table> ");
1557: pDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:checkInput()\\"> ");
1558: pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
1559: pDoc.write("<\\/form>");
1560: pDoc.write('$end_page_msg_central');
1561: pDoc.close();
1562: }
1563:
1564: //====================== Script for keyword highlight options ==============
1565: function kwhighlight() {
1566: var kwclr = document.SCORE.kwclr.value;
1567: var kwsize = document.SCORE.kwsize.value;
1568: var kwstyle = document.SCORE.kwstyle.value;
1569: var redsel = "";
1570: var grnsel = "";
1571: var blusel = "";
1572: if (kwclr=="red") {var redsel="checked"};
1573: if (kwclr=="green") {var grnsel="checked"};
1574: if (kwclr=="blue") {var blusel="checked"};
1575: var sznsel = "";
1576: var sz1sel = "";
1577: var sz2sel = "";
1578: if (kwsize=="0") {var sznsel="checked"};
1579: if (kwsize=="+1") {var sz1sel="checked"};
1580: if (kwsize=="+2") {var sz2sel="checked"};
1581: var synsel = "";
1582: var syisel = "";
1583: var sybsel = "";
1584: if (kwstyle=="") {var synsel="checked"};
1585: if (kwstyle=="<i>") {var syisel="checked"};
1586: if (kwstyle=="<b>") {var sybsel="checked"};
1587: highlightCentral();
1588: highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
1589: highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
1590: highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
1591: highlightend();
1592: return;
1593: }
1594:
1595: function highlightCentral() {
1596: // if (window.hwdWin) window.hwdWin.close();
1597: var xpos = (screen.width-400)/2;
1598: xpos = (xpos < 0) ? '0' : xpos;
1599: var ypos = (screen.height-330)/2-30;
1600: ypos = (ypos < 0) ? '0' : ypos;
1601:
1602: hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1603: hwdWin.focus();
1604: var hDoc = hwdWin.document;
1605: hDoc.$docopen;
1606: hDoc.write('$start_page_highlight_central');
1607: hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1608: hDoc.write("<h3><span class=\\"LC_info\\"> Keyword Highlight Options<\\/span><\\/h3><br /><br />");
1609:
1610: hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
1611: hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1612: hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
1613: }
1614:
1615: function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) {
1616: var hDoc = hwdWin.document;
1617: hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1618: hDoc.write("<td align=\\"left\\">");
1619: hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+"> "+clrtxt+"<\\/td>");
1620: hDoc.write("<td align=\\"left\\">");
1621: hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+"> "+sztxt+"<\\/td>");
1622: hDoc.write("<td align=\\"left\\">");
1623: hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+"> "+sytxt+"<\\/td>");
1624: hDoc.write("<\\/tr>");
1625: }
1626:
1627: function highlightend() {
1628: var hDoc = hwdWin.document;
1629: hDoc.write("<\\/table>");
1630: hDoc.write("<\\/td><\\/tr><\\/table> ");
1631: hDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:updateChoice(1)\\"> ");
1632: hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
1633: hDoc.write("<\\/form>");
1634: hDoc.write('$end_page_highlight_central');
1635: hDoc.close();
1636: }
1637:
1638: SUBJAVASCRIPT
1639: }
1640:
1641: sub get_increment {
1642: my $increment = $env{'form.increment'};
1643: if ($increment != 1 && $increment != .5 && $increment != .25 &&
1644: $increment != .1) {
1645: $increment = 1;
1646: }
1647: return $increment;
1648: }
1649:
1650: sub gradeBox_start {
1651: return (
1652: &Apache::loncommon::start_data_table()
1653: .&Apache::loncommon::start_data_table_header_row()
1654: .'<th>'.&mt('Part').'</th>'
1655: .'<th>'.&mt('Points').'</th>'
1656: .'<th> </th>'
1657: .'<th>'.&mt('Assign Grade').'</th>'
1658: .'<th>'.&mt('Weight').'</th>'
1659: .'<th>'.&mt('Grade Status').'</th>'
1660: .&Apache::loncommon::end_data_table_header_row()
1661: );
1662: }
1663:
1664: sub gradeBox_end {
1665: return (
1666: &Apache::loncommon::end_data_table()
1667: );
1668: }
1669: #--- displays the grading box, used in essay type problem and grading by page/sequence
1670: sub gradeBox {
1671: my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1672: my $checkIcon = '<img alt="'.&mt('Check Mark').
1673: '" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1674: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1675: my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)')
1676: : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1677: $wgt = ($wgt > 0 ? $wgt : '1');
1678: my $score = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1679: '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1680: my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1681: my $display_part= &get_display_part($partid,$symb);
1682: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
1683: [$partid]);
1684: my $aggtries = $$record{'resource.'.$partid.'.tries'};
1685: if ($last_resets{$partid}) {
1686: $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
1687: }
1688: $result.=&Apache::loncommon::start_data_table_row();
1689: my $ctr = 0;
1690: my $thisweight = 0;
1691: my $increment = &get_increment();
1692:
1693: my $radio.='<table border="0"><tr>'."\n"; # display radio buttons in a nice table 10 across
1694: while ($thisweight<=$wgt) {
1695: $radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1696: 'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1697: $thisweight.')" value="'.$thisweight.'" '.
1698: ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1699: $radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1700: $thisweight += $increment;
1701: $ctr++;
1702: }
1703: $radio.='</tr></table>';
1704:
1705: my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1706: ($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1707: 'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1708: $wgt.')" /></td>'."\n";
1709: $line.='<td>/'.$wgt.' '.$wgtmsg.
1710: ($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? ' '.$checkIcon : '').
1711: ' </td>'."\n";
1712: $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1713: 'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1714: if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1715: $line.='<option></option>'.
1716: '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1717: } else {
1718: $line.='<option selected="selected"></option>'.
1719: '<option value="excused" >'.&mt('excused').'</option>';
1720: }
1721: $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
1722:
1723:
1724: $result .=
1725: '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
1726: $result.=&Apache::loncommon::end_data_table_row();
1727: $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
1728: '<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
1729: '<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1730: $$record{'resource.'.$partid.'.solved'}.'" />'."\n".
1731: '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
1732: $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
1733: '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
1734: $aggtries.'" />'."\n";
1735: my $res_error;
1736: $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1737: if ($res_error) {
1738: return &navmap_errormsg();
1739: }
1740: return $result;
1741: }
1742:
1743: sub handback_box {
1744: my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
1745: my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
1746: my (@respids);
1747: my @part_response_id = &flatten_responseType($responseType);
1748: foreach my $part_response_id (@part_response_id) {
1749: my ($part,$resp) = @{ $part_response_id };
1750: if ($part eq $partid) {
1751: push(@respids,$resp);
1752: }
1753: }
1754: my $result;
1755: foreach my $respid (@respids) {
1756: my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
1757: my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
1758: next if (!@$files);
1759: my $file_counter = 1;
1760: foreach my $file (@$files) {
1761: if ($file =~ /\/portfolio\//) {
1762: my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1763: my ($name,$version,$ext) = &file_name_version_ext($file_disp);
1764: $file_disp = "$name.$ext";
1765: $file = $file_path.$file_disp;
1766: $result.=&mt('Return commented version of [_1] to student.',
1767: '<span class="LC_filename">'.$file_disp.'</span>');
1768: $result.='<input type="file" name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1769: $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1770: $result.='('.&mt('File will be uploaded when you click on Save & Next below.').')<br />';
1771: $file_counter++;
1772: }
1773: }
1774: }
1775: return $result;
1776: }
1777:
1778: sub show_problem {
1779: my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1780: my $rendered;
1781: my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1782: &Apache::lonxml::remember_problem_counter();
1783: if ($mode eq 'both' or $mode eq 'text') {
1784: $rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1785: $env{'request.course.id'},
1786: undef,\%form);
1787: }
1788: if ($removeform) {
1789: $rendered=~s|<form(.*?)>||g;
1790: $rendered=~s|</form>||g;
1791: $rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1792: }
1793: my $companswer;
1794: if ($mode eq 'both' or $mode eq 'answer') {
1795: &Apache::lonxml::restore_problem_counter();
1796: $companswer=
1797: &Apache::loncommon::get_student_answers($symb,$uname,$udom,
1798: $env{'request.course.id'},
1799: %form);
1800: }
1801: if ($removeform) {
1802: $companswer=~s|<form(.*?)>||g;
1803: $companswer=~s|</form>||g;
1804: $companswer=~s|name="submit"|name="would_have_been_submit"|g;
1805: }
1806: $rendered=
1807: '<div class="LC_Box">'
1808: .'<h3 class="LC_hcell">'.&mt('View of the problem').'</h3>'
1809: .$rendered
1810: .'</div>';
1811: $companswer=
1812: '<div class="LC_Box">'
1813: .'<h3 class="LC_hcell">'.&mt('Correct answer').'</h3>'
1814: .$companswer
1815: .'</div>';
1816: my $result;
1817: if ($mode eq 'both') {
1818: $result=$rendered.$companswer;
1819: } elsif ($mode eq 'text') {
1820: $result=$rendered;
1821: } elsif ($mode eq 'answer') {
1822: $result=$companswer;
1823: }
1824: return $result;
1825: }
1826:
1827: sub files_exist {
1828: my ($r, $symb) = @_;
1829: my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1830:
1831: foreach my $student (@students) {
1832: my ($uname,$udom,$fullname) = split(/:/,$student);
1833: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
1834: $udom,$uname);
1835: my ($string,$timestamp)= &get_last_submission(\%record);
1836: foreach my $submission (@$string) {
1837: my ($partid,$respid) =
1838: ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1839: my $files=&get_submitted_files($udom,$uname,$partid,$respid,
1840: \%record);
1841: return 1 if (@$files);
1842: }
1843: }
1844: return 0;
1845: }
1846:
1847: sub download_all_link {
1848: my ($r,$symb) = @_;
1849: unless (&files_exist($r, $symb)) {
1850: $r->print(&mt('There are currently no submitted documents.'));
1851: return;
1852: }
1853:
1854: my $all_students =
1855: join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
1856:
1857: my $parts =
1858: join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
1859:
1860: my $identifier = &Apache::loncommon::get_cgi_id();
1861: &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
1862: 'cgi.'.$identifier.'.symb' => $symb,
1863: 'cgi.'.$identifier.'.parts' => $parts,});
1864: $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
1865: &mt('Download All Submitted Documents').'</a>');
1866: return;
1867: }
1868:
1869: sub submit_download_link {
1870: my ($request,$symb) = @_;
1871: if (!$symb) { return ''; }
1872: #FIXME: Figure out which type of problem this is and provide appropriate download
1873: &download_all_link($request,$symb);
1874: }
1875:
1876: sub build_section_inputs {
1877: my $section_inputs;
1878: if ($env{'form.section'} eq '') {
1879: $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
1880: } else {
1881: my @sections = &Apache::loncommon::get_env_multiple('form.section');
1882: foreach my $section (@sections) {
1883: $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
1884: }
1885: }
1886: return $section_inputs;
1887: }
1888:
1889: # --------------------------- show submissions of a student, option to grade
1890: sub submission {
1891: my ($request,$counter,$total,$symb) = @_;
1892: my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
1893: $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
1894: my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
1895: $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1896:
1897: my $probtitle=&Apache::lonnet::gettitle($symb);
1898: if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1899:
1900: if (!&canview($usec)) {
1901: $request->print('<span class="LC_warning">Unable to view requested student.('.
1902: $uname.':'.$udom.' in section '.$usec.' in course id '.
1903: $env{'request.course.id'}.')</span>');
1904: return;
1905: }
1906:
1907: if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
1908: if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
1909: if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
1910: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1911: my $checkIcon = '<img alt="'.&mt('Check Mark').
1912: '" src="'.$request->dir_config('lonIconsURL').
1913: '/check.gif" height="16" border="0" />';
1914:
1915: my %old_essays;
1916: # header info
1917: if ($counter == 0) {
1918: &sub_page_js($request);
1919: &sub_page_kw_js($request);
1920:
1921: # option to display problem, only once else it cause problems
1922: # with the form later since the problem has a form.
1923: if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1924: my $mode;
1925: if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1926: $mode='both';
1927: } elsif ($env{'form.vProb'} eq 'yes') {
1928: $mode='text';
1929: } elsif ($env{'form.vAns'} eq 'yes') {
1930: $mode='answer';
1931: }
1932: &Apache::lonxml::clear_problem_counter();
1933: $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1934: }
1935:
1936: # kwclr is the only variable that is guaranteed to be non blank
1937: # if this subroutine has been called once.
1938: my %keyhash = ();
1939: # if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1940: if (1) {
1941: %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1942: $env{'course.'.$env{'request.course.id'}.'.domain'},
1943: $env{'course.'.$env{'request.course.id'}.'.num'});
1944:
1945: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1946: $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
1947: $env{'form.kwclr'} = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
1948: $env{'form.kwsize'} = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
1949: $env{'form.kwstyle'} = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
1950: $env{'form.msgsub'} = $keyhash{$symb.'_subject'} ne '' ?
1951: $keyhash{$symb.'_subject'} : $probtitle;
1952: $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1953: }
1954: my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1955: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1956: $request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1957: '<input type="hidden" name="command" value="handgrade" />'."\n".
1958: '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
1959: '<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1960: '<input type="hidden" name="refresh" value="off" />'."\n".
1961: '<input type="hidden" name="studentNo" value="" />'."\n".
1962: '<input type="hidden" name="gradeOpt" value="" />'."\n".
1963: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1964: '<input type="hidden" name="vProb" value="'.$env{'form.vProb'}.'" />'."\n".
1965: '<input type="hidden" name="vAns" value="'.$env{'form.vAns'}.'" />'."\n".
1966: '<input type="hidden" name="lastSub" value="'.$env{'form.lastSub'}.'" />'."\n".
1967: &build_section_inputs().
1968: '<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1969: '<input type="hidden" name="NCT"'.
1970: ' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1971: # if ($env{'form.handgrade'} eq 'yes') {
1972: if (1) {
1973: $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
1974: '<input type="hidden" name="kwclr" value="'.$env{'form.kwclr'}.'" />'."\n".
1975: '<input type="hidden" name="kwsize" value="'.$env{'form.kwsize'}.'" />'."\n".
1976: '<input type="hidden" name="kwstyle" value="'.$env{'form.kwstyle'}.'" />'."\n".
1977: '<input type="hidden" name="msgsub" value="'.$env{'form.msgsub'}.'" />'."\n".
1978: '<input type="hidden" name="shownSub" value="0" />'."\n".
1979: '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1980: foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
1981: $request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
1982: }
1983: }
1984:
1985: my ($cts,$prnmsg) = (1,'');
1986: while ($cts <= $env{'form.savemsgN'}) {
1987: $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1988: (!exists($keyhash{$symb.'_savemsg'.$cts}) ?
1989: &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1990: &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1991: '" />'."\n".
1992: '<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1993: $cts++;
1994: }
1995: $request->print($prnmsg);
1996:
1997: # if ($env{'form.handgrade'} eq 'yes') {
1998: if (1) {
1999: #
2000: # Print out the keyword options line
2001: #
2002: $request->print(<<KEYWORDS);
2003: <b>Keyword Options:</b>
2004: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>
2005: <a href="#" onmousedown="javascript:getSel(); return false"
2006: CLASS="page">Paste Selection to List</a>
2007: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
2008: KEYWORDS
2009: #
2010: # Load the other essays for similarity check
2011: #
2012: my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
2013: my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
2014: $apath=&escape($apath);
2015: $apath=~s/\W/\_/gs;
2016: %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
2017: }
2018: }
2019:
2020: # This is where output for one specific student would start
2021: my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
2022: $request->print(
2023: "\n\n"
2024: .'<div class="LC_grade_show_user'.$add_class.'">'
2025: .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
2026: ."\n"
2027: );
2028:
2029: # Show additional functions if allowed
2030: if ($perm{'vgr'}) {
2031: $request->print(
2032: &Apache::loncommon::track_student_link(
2033: &mt('View recent activity'),
2034: $uname,$udom,'check')
2035: .' '
2036: );
2037: }
2038: if ($perm{'opa'}) {
2039: $request->print(
2040: &Apache::loncommon::pprmlink(
2041: &mt('Set/Change parameters'),
2042: $uname,$udom,$symb,'check'));
2043: }
2044:
2045: # Show Problem
2046: if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
2047: my $mode;
2048: if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
2049: $mode='both';
2050: } elsif ($env{'form.vProb'} eq 'all' ) {
2051: $mode='text';
2052: } elsif ($env{'form.vAns'} eq 'all') {
2053: $mode='answer';
2054: }
2055: &Apache::lonxml::clear_problem_counter();
2056: $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
2057: }
2058:
2059: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
2060: my $res_error;
2061: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
2062: if ($res_error) {
2063: $request->print(&navmap_errormsg());
2064: return;
2065: }
2066:
2067: # Display student info
2068: $request->print(($counter == 0 ? '' : '<br />'));
2069:
2070: my $result='<div class="LC_Box">'
2071: .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
2072: $result.='<input type="hidden" name="name'.$counter.
2073: '" value="'.$env{'form.fullname'}.'" />'."\n";
2074: # if ($env{'form.handgrade'} eq 'no') {
2075: if (1) {
2076: $result.='<p class="LC_info">'
2077: .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
2078: ."</p>\n";
2079: }
2080:
2081: # If any part of the problem is an essay-response (handgraded), then check for collaborators
2082: my $fullname;
2083: my $col_fullnames = [];
2084: # if ($env{'form.handgrade'} eq 'yes') {
2085: if (1) {
2086: (my $sub_result,$fullname,$col_fullnames)=
2087: &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
2088: $counter);
2089: $result.=$sub_result;
2090: }
2091: $request->print($result."\n");
2092:
2093: # print student answer/submission
2094: # Options are (1) Handgraded submission only
2095: # (2) Last submission, includes submission that is not handgraded
2096: # (for multi-response type part)
2097: # (3) Last submission plus the parts info
2098: # (4) The whole record for this student
2099: if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
2100: my ($string,$timestamp)= &get_last_submission(\%record);
2101:
2102: my $lastsubonly;
2103:
2104: if ($$timestamp eq '') {
2105: $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>';
2106: } else {
2107: $lastsubonly =
2108: '<div class="LC_grade_submissions_body">'
2109: .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
2110:
2111: my %seenparts;
2112: my @part_response_id = &flatten_responseType($responseType);
2113: foreach my $part (@part_response_id) {
2114: next if ($env{'form.lastSub'} eq 'hdgrade'
2115: && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
2116:
2117: my ($partid,$respid) = @{ $part };
2118: my $display_part=&get_display_part($partid,$symb);
2119: if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
2120: if (exists($seenparts{$partid})) { next; }
2121: $seenparts{$partid}=1;
2122: my $submitby='<b>Part:</b> '.$display_part.
2123: ' <b>Collaborative submission by:</b> '.
2124: '<a href="javascript:viewSubmitter(\''.
2125: $env{"form.$uname:$udom:$partid:submitted_by"}.
2126: '\');" target="_self">'.
2127: $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
2128: $request->print($submitby);
2129: next;
2130: }
2131: my $responsetype = $responseType->{$partid}->{$respid};
2132: if (!exists($record{"resource.$partid.$respid.submission"})) {
2133: $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
2134: '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
2135: ' <span class="LC_internal_info">'.
2136: '('.&mt('Response ID: [_1]',$respid).')'.
2137: '</span> '.
2138: '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
2139: next;
2140: }
2141: foreach my $submission (@$string) {
2142: my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
2143: if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
2144: my ($ressub,$hide,$subval) = split(/:/,$submission,3);
2145: # Similarity check
2146: my $similar='';
2147: my ($type,$trial,$rndseed);
2148: if ($hide eq 'rand') {
2149: $type = 'randomizetry';
2150: $trial = $record{"resource.$partid.tries"};
2151: $rndseed = $record{"resource.$partid.rndseed"};
2152: }
2153: if($env{'form.checkPlag'}){
2154: my ($oname,$odom,$ocrsid,$oessay,$osim)=
2155: &most_similar($uname,$udom,$subval,\%old_essays);
2156: if ($osim) {
2157: $osim=int($osim*100.0);
2158: my %old_course_desc =
2159: &Apache::lonnet::coursedescription($ocrsid,
2160: {'one_time' => 1});
2161:
2162: if ($hide eq 'anon') {
2163: $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
2164: &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
2165: } else {
2166: $similar="<hr /><h3><span class=\"LC_warning\">".
2167: &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
2168: $osim,
2169: &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
2170: $old_course_desc{'description'},
2171: $old_course_desc{'num'},
2172: $old_course_desc{'domain'}).
2173: '</span></h3><blockquote><i>'.
2174: &keywords_highlight($oessay).
2175: '</i></blockquote><hr />';
2176: }
2177: }
2178: }
2179: my $order=&get_order($partid,$respid,$symb,$uname,$udom,
2180: undef,$type,$trial,$rndseed);
2181: if ($env{'form.lastSub'} eq 'lastonly' ||
2182: ($env{'form.lastSub'} eq 'hdgrade' &&
2183: $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
2184: my $display_part=&get_display_part($partid,$symb);
2185: $lastsubonly.='<div class="LC_grade_submission_part">'.
2186: '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
2187: ' <span class="LC_internal_info">'.
2188: '('.&mt('Response ID: [_1]',$respid).')'.
2189: '</span> ';
2190: my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
2191: if (@$files) {
2192: if ($hide eq 'anon') {
2193: $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
2194: } else {
2195: $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
2196: foreach my $file (@$files) {
2197: &Apache::lonnet::allowuploaded('/adm/grades',$file);
2198: $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
2199: }
2200: }
2201: $lastsubonly.='<br />';
2202: }
2203: if ($hide eq 'anon') {
2204: $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>';
2205: } else {
2206: $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
2207: &cleanRecord($subval,$responsetype,$symb,$partid,
2208: $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
2209: }
2210: if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
2211: $lastsubonly.='</div>';
2212: }
2213: }
2214: }
2215: $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
2216: }
2217: $request->print($lastsubonly);
2218: } elsif ($env{'form.lastSub'} eq 'datesub') {
2219: my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
2220: $request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
2221: } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
2222: $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
2223: $env{'request.course.id'},
2224: $last,'.submission',
2225: 'Apache::grades::keywords_highlight'));
2226: }
2227: $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
2228: .$udom.'" />'."\n");
2229: # return if view submission with no grading option
2230: if (!&canmodify($usec)) {
2231: $request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
2232: return;
2233: } else {
2234: $request->print('</div>'."\n");
2235: }
2236:
2237: # essay grading message center
2238: # if ($env{'form.handgrade'} eq 'yes') {
2239: if (1) {
2240: my $result='<div class="LC_grade_message_center">';
2241:
2242: $result.='<div class="LC_grade_message_center_header">'.
2243: &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
2244: my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
2245: my $msgfor = $givenn.' '.$lastname;
2246: if (scalar(@$col_fullnames) > 0) {
2247: my $lastone = pop(@$col_fullnames);
2248: $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
2249: }
2250: $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
2251: $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
2252: '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
2253: $result.=' <a href="javascript:msgCenter(document.SCORE,'.$counter.
2254: ',\''.$msgfor.'\');" target="_self">'.
2255: &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
2256: &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
2257: '<img src="'.$request->dir_config('lonIconsURL').
2258: '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
2259: '<br /> ('.
2260: &mt('Message will be sent when you click on Save & Next below.').")\n";
2261: $result.='</div></div>';
2262: $request->print($result);
2263: }
2264:
2265: my %seen = ();
2266: my @partlist;
2267: my @gradePartRespid;
2268: my @part_response_id = &flatten_responseType($responseType);
2269: $request->print(
2270: '<div class="LC_Box">'
2271: .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
2272: );
2273: $request->print(&gradeBox_start());
2274: foreach my $part_response_id (@part_response_id) {
2275: my ($partid,$respid) = @{ $part_response_id };
2276: my $part_resp = join('_',@{ $part_response_id });
2277: next if ($seen{$partid} > 0);
2278: $seen{$partid}++;
2279: next if ($$handgrade{$part_resp} ne 'yes'
2280: && $env{'form.lastSub'} eq 'hdgrade');
2281: push(@partlist,$partid);
2282: push(@gradePartRespid,$partid.'.'.$respid);
2283: $request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
2284: }
2285: $request->print(&gradeBox_end()); # </div>
2286: $request->print('</div>');
2287:
2288: $request->print('<div class="LC_grade_info_links">');
2289: $request->print('</div>');
2290:
2291: $result='<input type="hidden" name="partlist'.$counter.
2292: '" value="'.(join ":",@partlist).'" />'."\n";
2293: $result.='<input type="hidden" name="gradePartRespid'.
2294: '" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
2295: my $ctr = 0;
2296: while ($ctr < scalar(@partlist)) {
2297: $result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
2298: $partlist[$ctr].'" />'."\n";
2299: $ctr++;
2300: }
2301: $request->print($result.''."\n");
2302:
2303: # Done with printing info for one student
2304:
2305: $request->print('</div>');#LC_grade_show_user
2306:
2307:
2308: # print end of form
2309: if ($counter == $total) {
2310: my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
2311: $endform.='<input type="button" value="'.&mt('Save & Next').'" '.
2312: 'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
2313: $total.','.scalar(@partlist).');" target="_self" /> '."\n";
2314: my $ntstu ='<select name="NTSTU">'.
2315: '<option>1</option><option>2</option>'.
2316: '<option>3</option><option>5</option>'.
2317: '<option>7</option><option>10</option></select>'."\n";
2318: my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
2319: $ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
2320: $endform.=&mt('[_1]student(s)',$ntstu);
2321: $endform.=' <input type="button" value="'.&mt('Previous').'" '.
2322: 'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> '."\n".
2323: '<input type="button" value="'.&mt('Next').'" '.
2324: 'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> ';
2325: $endform.='<span class="LC_warning">'.
2326: &mt('(Next and Previous (student) do not save the scores.)').
2327: '</span>'."\n" ;
2328: $endform.="<input type='hidden' value='".&get_increment().
2329: "' name='increment' />";
2330: $endform.='</td></tr></table></form>';
2331: $request->print($endform);
2332: }
2333: return '';
2334: }
2335:
2336: sub check_collaborators {
2337: my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
2338: my ($result,@col_fullnames);
2339: my ($classlist,undef,$fullname) = &getclasslist('all','0');
2340: foreach my $part (keys(%$handgrade)) {
2341: my $ncol = &Apache::lonnet::EXT('resource.'.$part.
2342: '.maxcollaborators',
2343: $symb,$udom,$uname);
2344: next if ($ncol <= 0);
2345: $part =~ s/\_/\./g;
2346: next if ($record->{'resource.'.$part.'.collaborators'} eq '');
2347: my (@good_collaborators, @bad_collaborators);
2348: foreach my $possible_collaborator
2349: (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) {
2350: $possible_collaborator =~ s/[\$\^\(\)]//g;
2351: next if ($possible_collaborator eq '');
2352: my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
2353: $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
2354: next if ($co_name eq $uname && $co_dom eq $udom);
2355: # Doing this grep allows 'fuzzy' specification
2356: my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i,
2357: keys(%$classlist));
2358: if (! scalar(@matches)) {
2359: push(@bad_collaborators, $possible_collaborator);
2360: } else {
2361: push(@good_collaborators, @matches);
2362: }
2363: }
2364: if (scalar(@good_collaborators) != 0) {
2365: $result.='<br />'.&mt('Collaborators:').'<ol>';
2366: foreach my $name (@good_collaborators) {
2367: my ($lastname,$givenn) = split(/,/,$$fullname{$name});
2368: push(@col_fullnames, $givenn.' '.$lastname);
2369: $result.='<li>'.$fullname->{$name}.'</li>';
2370: }
2371: $result.='</ol><br />'."\n";
2372: my ($part)=split(/\./,$part);
2373: $result.='<input type="hidden" name="collaborator'.$counter.
2374: '" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
2375: "\n";
2376: }
2377: if (scalar(@bad_collaborators) > 0) {
2378: $result.='<div class="LC_warning">';
2379: $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
2380: $result .= '</div>';
2381: }
2382: if (scalar(@bad_collaborators > $ncol)) {
2383: $result .= '<div class="LC_warning">';
2384: $result .= &mt('This student has submitted too many '.
2385: 'collaborators. Maximum is [_1].',$ncol);
2386: $result .= '</div>';
2387: }
2388: }
2389: return ($result,$fullname,\@col_fullnames);
2390: }
2391:
2392: #--- Retrieve the last submission for all the parts
2393: sub get_last_submission {
2394: my ($returnhash)=@_;
2395: my (@string,$timestamp,%lasthidden);
2396: if ($$returnhash{'version'}) {
2397: my %lasthash=();
2398: my ($version);
2399: for ($version=1;$version<=$$returnhash{'version'};$version++) {
2400: foreach my $key (sort(split(/\:/,
2401: $$returnhash{$version.':keys'}))) {
2402: $lasthash{$key}=$$returnhash{$version.':'.$key};
2403: $timestamp =
2404: &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
2405: }
2406: }
2407: my (%typeparts,%randombytry);
2408: my $showsurv =
2409: &Apache::lonnet::allowed('vas',$env{'request.course.id'});
2410: foreach my $key (sort(keys(%lasthash))) {
2411: if ($key =~ /\.type$/) {
2412: if (($lasthash{$key} eq 'anonsurvey') ||
2413: ($lasthash{$key} eq 'anonsurveycred') ||
2414: ($lasthash{$key} eq 'randomizetry')) {
2415: my ($ign,@parts) = split(/\./,$key);
2416: pop(@parts);
2417: if ($lasthash{$key} eq 'randomizetry') {
2418: my $id = join(',',@parts);
2419: $randombytry{$ign.'.'.$id} = $lasthash{$key};
2420: } else {
2421: unless ($showsurv) {
2422: my $id = join(',',@parts);
2423: $typeparts{$ign.'.'.$id} = $lasthash{$key};
2424: }
2425: }
2426: delete($lasthash{$key});
2427: }
2428: }
2429: }
2430: my @hidden = keys(%typeparts);
2431: my @randomize = keys(%randombytry);
2432: foreach my $key (keys(%lasthash)) {
2433: next if ($key !~ /\.submission$/);
2434: my $hide;
2435: if (@hidden) {
2436: foreach my $id (@hidden) {
2437: if ($key =~ /^\Q$id\E/) {
2438: $hide = 'anon';
2439: last;
2440: }
2441: }
2442: }
2443: unless ($hide) {
2444: if (@randomize) {
2445: foreach my $id (@hidden) {
2446: if ($key =~ /^\Q$id\E/) {
2447: $hide = 'rand';
2448: last;
2449: }
2450: }
2451: }
2452: }
2453: my ($partid,$foo) = split(/submission$/,$key);
2454: my $draft = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
2455: '<span class="LC_warning">Draft Copy</span> ' : '';
2456: push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
2457: }
2458: }
2459: if (!@string) {
2460: $string[0] =
2461: '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
2462: }
2463: return (\@string,\$timestamp);
2464: }
2465:
2466: #--- High light keywords, with style choosen by user.
2467: sub keywords_highlight {
2468: my $string = shift;
2469: my $size = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
2470: my $styleon = $env{'form.kwstyle'} eq '' ? '' : $env{'form.kwstyle'};
2471: (my $styleoff = $styleon) =~ s/\</\<\//;
2472: my @keylist = split(/[,\s+]/,$env{'form.keywords'});
2473: foreach my $keyword (@keylist) {
2474: $string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
2475: }
2476: return $string;
2477: }
2478:
2479: #--- Called from submission routine
2480: sub processHandGrade {
2481: my ($request,$symb) = @_;
2482: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
2483: my $button = $env{'form.gradeOpt'};
2484: my $ngrade = $env{'form.NCT'};
2485: my $ntstu = $env{'form.NTSTU'};
2486: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2487: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2488:
2489: if ($button eq 'Save & Next') {
2490: my $ctr = 0;
2491: while ($ctr < $ngrade) {
2492: my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
2493: my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
2494: if ($errorflag eq 'no_score') {
2495: $ctr++;
2496: next;
2497: }
2498: if ($errorflag eq 'not_allowed') {
2499: $request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
2500: $ctr++;
2501: next;
2502: }
2503: my $includemsg = $env{'form.includemsg'.$ctr};
2504: my ($subject,$message,$msgstatus) = ('','','');
2505: my $restitle = &Apache::lonnet::gettitle($symb);
2506: my ($feedurl,$showsymb) =
2507: &get_feedurl_and_symb($symb,$uname,$udom);
2508: my $messagetail;
2509: if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
2510: $subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
2511: unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
2512: $subject.=' ['.$restitle.']';
2513: my (@msgnum) = split(/,/,$includemsg);
2514: foreach (@msgnum) {
2515: $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
2516: }
2517: $message =&Apache::lonfeedback::clear_out_html($message);
2518: if ($env{'form.withgrades'.$ctr}) {
2519: $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
2520: $messagetail = " for <a href=\"".
2521: $feedurl."?symb=$showsymb\">$restitle</a>";
2522: }
2523: $msgstatus =
2524: &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
2525: $message.$messagetail,
2526: undef,$feedurl,undef,
2527: undef,undef,$showsymb,
2528: $restitle);
2529: $request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
2530: $msgstatus);
2531: }
2532: if ($env{'form.collaborator'.$ctr}) {
2533: my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
2534: foreach my $collabstr (@collabstrs) {
2535: my ($part,@collaborators) = split(/:/,$collabstr);
2536: foreach my $collaborator (@collaborators) {
2537: my ($errorflag,$pts,$wgt) =
2538: &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
2539: $env{'form.unamedom'.$ctr},$part);
2540: if ($errorflag eq 'not_allowed') {
2541: $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
2542: next;
2543: } elsif ($message ne '') {
2544: my ($baseurl,$showsymb) =
2545: &get_feedurl_and_symb($symb,$collaborator,
2546: $udom);
2547: if ($env{'form.withgrades'.$ctr}) {
2548: $messagetail = " for <a href=\"".
2549: $baseurl."?symb=$showsymb\">$restitle</a>";
2550: }
2551: $msgstatus =
2552: &Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
2553: }
2554: }
2555: }
2556: }
2557: $ctr++;
2558: }
2559: }
2560:
2561: # if ($env{'form.handgrade'} eq 'yes') {
2562: if (1) {
2563: # Keywords sorted in alphabatical order
2564: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
2565: my %keyhash = ();
2566: $env{'form.keywords'} =~ s/,\s{0,}|\s+/ /g;
2567: $env{'form.keywords'} =~ s/^\s+|\s+$//;
2568: my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
2569: $env{'form.keywords'} = join(' ',@keywords);
2570: $keyhash{$symb.'_keywords'} = $env{'form.keywords'};
2571: $keyhash{$symb.'_subject'} = $env{'form.msgsub'};
2572: $keyhash{$loginuser.'_kwclr'} = $env{'form.kwclr'};
2573: $keyhash{$loginuser.'_kwsize'} = $env{'form.kwsize'};
2574: $keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
2575:
2576: # message center - Order of message gets changed. Blank line is eliminated.
2577: # New messages are saved in env for the next student.
2578: # All messages are saved in nohist_handgrade.db
2579: my ($ctr,$idx) = (1,1);
2580: while ($ctr <= $env{'form.savemsgN'}) {
2581: if ($env{'form.savemsg'.$ctr} ne '') {
2582: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
2583: $idx++;
2584: }
2585: $ctr++;
2586: }
2587: $ctr = 0;
2588: while ($ctr < $ngrade) {
2589: if ($env{'form.newmsg'.$ctr} ne '') {
2590: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2591: $env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2592: $idx++;
2593: }
2594: $ctr++;
2595: }
2596: $env{'form.savemsgN'} = --$idx;
2597: $keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
2598: my $putresult = &Apache::lonnet::put
2599: ('nohist_handgrade',\%keyhash,$cdom,$cnum);
2600: }
2601: # Called by Save & Refresh from Highlight Attribute Window
2602: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
2603: if ($env{'form.refresh'} eq 'on') {
2604: my ($ctr,$total) = (0,0);
2605: while ($ctr < $ngrade) {
2606: $total++ if $env{'form.unamedom'.$ctr} ne '';
2607: $ctr++;
2608: }
2609: $env{'form.NTSTU'}=$ngrade;
2610: $ctr = 0;
2611: while ($ctr < $total) {
2612: my $processUser = $env{'form.unamedom'.$ctr};
2613: ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
2614: $env{'form.fullname'} = $$fullname{$processUser};
2615: &submission($request,$ctr,$total-1,$symb);
2616: $ctr++;
2617: }
2618: return '';
2619: }
2620:
2621: # Get the next/previous one or group of students
2622: my $firststu = $env{'form.unamedom0'};
2623: my $laststu = $env{'form.unamedom'.($ngrade-1)};
2624: my $ctr = 2;
2625: while ($laststu eq '') {
2626: $laststu = $env{'form.unamedom'.($ngrade-$ctr)};
2627: $ctr++;
2628: $laststu = $firststu if ($ctr > $ngrade);
2629: }
2630:
2631: my (@parsedlist,@nextlist);
2632: my ($nextflg) = 0;
2633: foreach my $item (sort
2634: {
2635: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
2636: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
2637: }
2638: return $a cmp $b;
2639: } (keys(%$fullname))) {
2640: # FIXME: this is fishy, looks like the button label
2641: if ($nextflg == 1 && $button =~ /Next$/) {
2642: push(@parsedlist,$item);
2643: }
2644: $nextflg = 1 if ($item eq $laststu);
2645: if ($button eq 'Previous') {
2646: last if ($item eq $firststu);
2647: push(@parsedlist,$item);
2648: }
2649: }
2650: $ctr = 0;
2651: # FIXME: this is fishy, looks like the button label
2652: @parsedlist = reverse @parsedlist if ($button eq 'Previous');
2653: my $res_error;
2654: my ($partlist) = &response_type($symb,\$res_error);
2655: if ($res_error) {
2656: $request->print(&navmap_errormsg());
2657: return;
2658: }
2659: foreach my $student (@parsedlist) {
2660: my $submitonly=$env{'form.submitonly'};
2661: my ($uname,$udom) = split(/:/,$student);
2662:
2663: if ($submitonly eq 'queued') {
2664: my %queue_status =
2665: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
2666: $udom,$uname);
2667: next if (!defined($queue_status{'gradingqueue'}));
2668: }
2669:
2670: if ($submitonly =~ /^(yes|graded|incorrect)$/) {
2671: # my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
2672: my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
2673: my $submitted = 0;
2674: my $ungraded = 0;
2675: my $incorrect = 0;
2676: foreach my $item (keys(%status)) {
2677: $submitted = 1 if ($status{$item} ne 'nothing');
2678: $ungraded = 1 if ($status{$item} =~ /^ungraded/);
2679: $incorrect = 1 if ($status{$item} =~ /^incorrect/);
2680: my ($foo,$partid,$foo1) = split(/\./,$item);
2681: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
2682: $submitted = 0;
2683: }
2684: }
2685: next if (!$submitted && ($submitonly eq 'yes' ||
2686: $submitonly eq 'incorrect' ||
2687: $submitonly eq 'graded'));
2688: next if (!$ungraded && ($submitonly eq 'graded'));
2689: next if (!$incorrect && $submitonly eq 'incorrect');
2690: }
2691: push(@nextlist,$student) if ($ctr < $ntstu);
2692: last if ($ctr == $ntstu);
2693: $ctr++;
2694: }
2695:
2696: $ctr = 0;
2697: my $total = scalar(@nextlist)-1;
2698:
2699: foreach (sort(@nextlist)) {
2700: my ($uname,$udom,$submitter) = split(/:/);
2701: $env{'form.student'} = $uname;
2702: $env{'form.userdom'} = $udom;
2703: $env{'form.fullname'} = $$fullname{$_};
2704: &submission($request,$ctr,$total,$symb);
2705: $ctr++;
2706: }
2707: if ($total < 0) {
2708: my $the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
2709: $request->print($the_end);
2710: }
2711: return '';
2712: }
2713:
2714: #---- Save the score and award for each student, if changed
2715: sub saveHandGrade {
2716: my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
2717: my @version_parts;
2718: my $usec = &Apache::lonnet::getsection($domain,$stuname,
2719: $env{'request.course.id'});
2720: if (!&canmodify($usec)) { return('not_allowed'); }
2721: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
2722: my @parts_graded;
2723: my %newrecord = ();
2724: my ($pts,$wgt) = ('','');
2725: my %aggregate = ();
2726: my $aggregateflag = 0;
2727: my @parts = split(/:/,$env{'form.partlist'.$newflg});
2728: foreach my $new_part (@parts) {
2729: #collaborator ($submi may vary for different parts
2730: if ($submitter && $new_part ne $part) { next; }
2731: my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
2732: if ($dropMenu eq 'excused') {
2733: if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
2734: $newrecord{'resource.'.$new_part.'.solved'} = 'excused';
2735: if (exists($record{'resource.'.$new_part.'.awarded'})) {
2736: $newrecord{'resource.'.$new_part.'.awarded'} = '';
2737: }
2738: $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
2739: }
2740: } elsif ($dropMenu eq 'reset status'
2741: && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
2742: foreach my $key (keys(%record)) {
2743: if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
2744: }
2745: $newrecord{'resource.'.$new_part.'.regrader'}=
2746: "$env{'user.name'}:$env{'user.domain'}";
2747: my $totaltries = $record{'resource.'.$part.'.tries'};
2748:
2749: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
2750: [$new_part]);
2751: my $aggtries =$totaltries;
2752: if ($last_resets{$new_part}) {
2753: $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
2754: $new_part);
2755: }
2756:
2757: my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
2758: if ($aggtries > 0) {
2759: &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
2760: $aggregateflag = 1;
2761: }
2762: } elsif ($dropMenu eq '') {
2763: $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ?
2764: $env{'form.GD_BOX'.$newflg.'_'.$new_part} :
2765: $env{'form.RADVAL'.$newflg.'_'.$new_part});
2766: if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
2767: next;
2768: }
2769: $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 :
2770: $env{'form.WGT'.$newflg.'_'.$new_part};
2771: my $partial= $pts/$wgt;
2772: if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
2773: #do not update score for part if not changed.
2774: &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
2775: next;
2776: } else {
2777: push(@parts_graded,$new_part);
2778: }
2779: if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
2780: $newrecord{'resource.'.$new_part.'.awarded'} = $partial;
2781: }
2782: my $reckey = 'resource.'.$new_part.'.solved';
2783: if ($partial == 0) {
2784: if ($record{$reckey} ne 'incorrect_by_override') {
2785: $newrecord{$reckey} = 'incorrect_by_override';
2786: }
2787: } else {
2788: if ($record{$reckey} ne 'correct_by_override') {
2789: $newrecord{$reckey} = 'correct_by_override';
2790: }
2791: }
2792: if ($submitter &&
2793: ($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
2794: $newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
2795: }
2796: $newrecord{'resource.'.$new_part.'.regrader'}=
2797: "$env{'user.name'}:$env{'user.domain'}";
2798: }
2799: # unless problem has been graded, set flag to version the submitted files
2800: unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/ ||
2801: $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
2802: $dropMenu eq 'reset status')
2803: {
2804: push(@version_parts,$new_part);
2805: }
2806: }
2807: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2808: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2809:
2810: if (%newrecord) {
2811: if (@version_parts) {
2812: my @changed_keys = &version_portfiles(\%record, \@parts_graded,
2813: $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
2814: @newrecord{@changed_keys} = @record{@changed_keys};
2815: foreach my $new_part (@version_parts) {
2816: &handback_files($request,$symb,$stuname,$domain,$newflg,
2817: $new_part,\%newrecord);
2818: }
2819: }
2820: &Apache::lonnet::cstore(\%newrecord,$symb,
2821: $env{'request.course.id'},$domain,$stuname);
2822: &check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
2823: $cdom,$cnum,$domain,$stuname);
2824: }
2825: if ($aggregateflag) {
2826: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
2827: $cdom,$cnum);
2828: }
2829: return ('',$pts,$wgt);
2830: }
2831:
2832: sub check_and_remove_from_queue {
2833: my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
2834: my @ungraded_parts;
2835: foreach my $part (@{$parts}) {
2836: if ( $record->{ 'resource.'.$part.'.awarded'} eq ''
2837: && $record->{ 'resource.'.$part.'.solved' } ne 'excused'
2838: && $newrecord->{'resource.'.$part.'.awarded'} eq ''
2839: && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
2840: ) {
2841: push(@ungraded_parts, $part);
2842: }
2843: }
2844: if ( !@ungraded_parts ) {
2845: &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
2846: $cnum,$domain,$stuname);
2847: }
2848: }
2849:
2850: sub handback_files {
2851: my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
2852: my $portfolio_root = '/userfiles/portfolio';
2853: my $res_error;
2854: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
2855: if ($res_error) {
2856: $request->print('<br />'.&navmap_errormsg().'<br />');
2857: return;
2858: }
2859: my @part_response_id = &flatten_responseType($responseType);
2860: foreach my $part_response_id (@part_response_id) {
2861: my ($part_id,$resp_id) = @{ $part_response_id };
2862: my $part_resp = join('_',@{ $part_response_id });
2863: if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
2864: # if multiple files are uploaded names will be 'returndoc2','returndoc3'
2865: my $file_counter = 1;
2866: my $file_msg;
2867: while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
2868: my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
2869: my ($directory,$answer_file) =
2870: ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
2871: my ($answer_name,$answer_ver,$answer_ext) =
2872: &file_name_version_ext($answer_file);
2873: my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
2874: my $getpropath = 1;
2875: my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
2876: my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
2877: # fix file name
2878: my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
2879: my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
2880: $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
2881: $save_file_name);
2882: if ($result !~ m|^/uploaded/|) {
2883: $request->print('<br /><span class="LC_error">'.
2884: &mt('An error occurred ([_1]) while trying to upload [_2].',
2885: $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
2886: '</span>');
2887: } else {
2888: # mark the file as read only
2889: my @files = ($save_file_name);
2890: my @what = ($symb,$env{'request.course.id'},'handback');
2891: &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
2892: if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
2893: $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
2894: }
2895: $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
2896: $file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
2897:
2898: }
2899: $request->print("<br />".$fname." will be the uploaded file name");
2900: $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
2901: $file_counter++;
2902: }
2903: my $subject = "File Handed Back by Instructor ";
2904: my $message = "A file has been returned that was originally submitted in reponse to: <br />";
2905: $message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
2906: $message .= ' The returned file(s) are named: '. $file_msg;
2907: $message .= " and can be found in your portfolio space.";
2908: my ($feedurl,$showsymb) =
2909: &get_feedurl_and_symb($symb,$domain,$stuname);
2910: my $restitle = &Apache::lonnet::gettitle($symb);
2911: my $msgstatus =
2912: &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
2913: ' (File Returned) ['.$restitle.']',$message,undef,
2914: $feedurl,undef,undef,undef,$showsymb,$restitle);
2915: }
2916: }
2917: return;
2918: }
2919:
2920: sub get_feedurl_and_symb {
2921: my ($symb,$uname,$udom) = @_;
2922: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
2923: $url = &Apache::lonnet::clutter($url);
2924: my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
2925: $symb,$udom,$uname);
2926: if ($encrypturl =~ /^yes$/i) {
2927: &Apache::lonenc::encrypted(\$url,1);
2928: &Apache::lonenc::encrypted(\$symb,1);
2929: }
2930: return ($url,$symb);
2931: }
2932:
2933: sub get_submitted_files {
2934: my ($udom,$uname,$partid,$respid,$record) = @_;
2935: my @files;
2936: if ($$record{"resource.$partid.$respid.portfiles"}) {
2937: my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
2938: foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
2939: push(@files,$file_url.$file);
2940: }
2941: }
2942: if ($$record{"resource.$partid.$respid.uploadedurl"}) {
2943: push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
2944: }
2945: return (\@files);
2946: }
2947:
2948: # ----------- Provides number of tries since last reset.
2949: sub get_num_tries {
2950: my ($record,$last_reset,$part) = @_;
2951: my $timestamp = '';
2952: my $num_tries = 0;
2953: if ($$record{'version'}) {
2954: for (my $version=$$record{'version'};$version>=1;$version--) {
2955: if (exists($$record{$version.':resource.'.$part.'.solved'})) {
2956: $timestamp = $$record{$version.':timestamp'};
2957: if ($timestamp > $last_reset) {
2958: $num_tries ++;
2959: } else {
2960: last;
2961: }
2962: }
2963: }
2964: }
2965: return $num_tries;
2966: }
2967:
2968: # ----------- Determine decrements required in aggregate totals
2969: sub decrement_aggs {
2970: my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
2971: my %decrement = (
2972: attempts => 0,
2973: users => 0,
2974: correct => 0
2975: );
2976: $decrement{'attempts'} = $aggtries;
2977: if ($solvedstatus =~ /^correct/) {
2978: $decrement{'correct'} = 1;
2979: }
2980: if ($aggtries == $totaltries) {
2981: $decrement{'users'} = 1;
2982: }
2983: foreach my $type (keys(%decrement)) {
2984: $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
2985: }
2986: return;
2987: }
2988:
2989: # ----------- Determine timestamps for last reset of aggregate totals for parts
2990: sub get_last_resets {
2991: my ($symb,$courseid,$partids) =@_;
2992: my %last_resets;
2993: my $cdom = $env{'course.'.$courseid.'.domain'};
2994: my $cname = $env{'course.'.$courseid.'.num'};
2995: my @keys;
2996: foreach my $part (@{$partids}) {
2997: push(@keys,"$symb\0$part\0resettime");
2998: }
2999: my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
3000: $cdom,$cname);
3001: foreach my $part (@{$partids}) {
3002: $last_resets{$part}=$results{"$symb\0$part\0resettime"};
3003: }
3004: return %last_resets;
3005: }
3006:
3007: # ----------- Handles creating versions for portfolio files as answers
3008: sub version_portfiles {
3009: my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
3010: my $version_parts = join('|',@$v_flag);
3011: my @returned_keys;
3012: my $parts = join('|', @$parts_graded);
3013: my $portfolio_root = '/userfiles/portfolio';
3014: foreach my $key (keys(%$record)) {
3015: my $new_portfiles;
3016: if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
3017: my @versioned_portfiles;
3018: my @portfiles = split(/\s*,\s*/,$$record{$key});
3019: foreach my $file (@portfiles) {
3020: &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
3021: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
3022: my ($answer_name,$answer_ver,$answer_ext) =
3023: &file_name_version_ext($answer_file);
3024: my $getpropath = 1;
3025: my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
3026: my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
3027: my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
3028: if ($new_answer ne 'problem getting file') {
3029: push(@versioned_portfiles, $directory.$new_answer);
3030: &Apache::lonnet::mark_as_readonly($domain,$stu_name,
3031: [$directory.$new_answer],
3032: [$symb,$env{'request.course.id'},'graded']);
3033: }
3034: }
3035: $$record{$key} = join(',',@versioned_portfiles);
3036: push(@returned_keys,$key);
3037: }
3038: }
3039: return (@returned_keys);
3040: }
3041:
3042: sub get_next_version {
3043: my ($answer_name, $answer_ext, $dir_list) = @_;
3044: my $version;
3045: foreach my $row (@$dir_list) {
3046: my ($file) = split(/\&/,$row,2);
3047: my ($file_name,$file_version,$file_ext) =
3048: &file_name_version_ext($file);
3049: if (($file_name eq $answer_name) &&
3050: ($file_ext eq $answer_ext)) {
3051: # gets here if filename and extension match, regardless of version
3052: if ($file_version ne '') {
3053: # a versioned file is found so save it for later
3054: if ($file_version > $version) {
3055: $version = $file_version;
3056: }
3057: }
3058: }
3059: }
3060: $version ++;
3061: return($version);
3062: }
3063:
3064: sub version_selected_portfile {
3065: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
3066: my ($answer_name,$answer_ver,$answer_ext) =
3067: &file_name_version_ext($file_name);
3068: my $new_answer;
3069: $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
3070: if($env{'form.copy'} eq '-1') {
3071: $new_answer = 'problem getting file';
3072: } else {
3073: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
3074: my $copy_result = &Apache::lonnet::finishuserfileupload(
3075: $stu_name,$domain,'copy',
3076: '/portfolio'.$directory.$new_answer);
3077: }
3078: return ($new_answer);
3079: }
3080:
3081: sub file_name_version_ext {
3082: my ($file)=@_;
3083: my @file_parts = split(/\./, $file);
3084: my ($name,$version,$ext);
3085: if (@file_parts > 1) {
3086: $ext=pop(@file_parts);
3087: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
3088: $version=pop(@file_parts);
3089: }
3090: $name=join('.',@file_parts);
3091: } else {
3092: $name=join('.',@file_parts);
3093: }
3094: return($name,$version,$ext);
3095: }
3096:
3097: #--------------------------------------------------------------------------------------
3098: #
3099: #-------------------------- Next few routines handles grading by section or whole class
3100: #
3101: #--- Javascript to handle grading by section or whole class
3102: sub viewgrades_js {
3103: my ($request) = shift;
3104:
3105: my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
3106: $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
3107: function writePoint(partid,weight,point) {
3108: var radioButton = document.classgrade["RADVAL_"+partid];
3109: var textbox = document.classgrade["TEXTVAL_"+partid];
3110: if (point == "textval") {
3111: point = document.classgrade["TEXTVAL_"+partid].value;
3112: if (isNaN(point) || parseFloat(point) < 0) {
3113: alert("$alertmsg"+parseFloat(point));
3114: var resetbox = false;
3115: for (var i=0; i<radioButton.length; i++) {
3116: if (radioButton[i].checked) {
3117: textbox.value = i;
3118: resetbox = true;
3119: }
3120: }
3121: if (!resetbox) {
3122: textbox.value = "";
3123: }
3124: return;
3125: }
3126: if (parseFloat(point) > parseFloat(weight)) {
3127: var resp = confirm("You entered a value ("+parseFloat(point)+
3128: ") greater than the weight for the part. Accept?");
3129: if (resp == false) {
3130: textbox.value = "";
3131: return;
3132: }
3133: }
3134: for (var i=0; i<radioButton.length; i++) {
3135: radioButton[i].checked=false;
3136: if (parseFloat(point) == i) {
3137: radioButton[i].checked=true;
3138: }
3139: }
3140:
3141: } else {
3142: textbox.value = parseFloat(point);
3143: }
3144: for (i=0;i<document.classgrade.total.value;i++) {
3145: var user = document.classgrade["ctr"+i].value;
3146: user = user.replace(new RegExp(':', 'g'),"_");
3147: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3148: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3149: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3150: if (saveval != "correct") {
3151: scorename.value = point;
3152: if (selname[0].selected != true) {
3153: selname[0].selected = true;
3154: }
3155: }
3156: }
3157: document.classgrade["SELVAL_"+partid][0].selected = true;
3158: }
3159:
3160: function writeRadText(partid,weight) {
3161: var selval = document.classgrade["SELVAL_"+partid];
3162: var radioButton = document.classgrade["RADVAL_"+partid];
3163: var override = document.classgrade["FORCE_"+partid].checked;
3164: var textbox = document.classgrade["TEXTVAL_"+partid];
3165: if (selval[1].selected || selval[2].selected) {
3166: for (var i=0; i<radioButton.length; i++) {
3167: radioButton[i].checked=false;
3168:
3169: }
3170: textbox.value = "";
3171:
3172: for (i=0;i<document.classgrade.total.value;i++) {
3173: var user = document.classgrade["ctr"+i].value;
3174: user = user.replace(new RegExp(':', 'g'),"_");
3175: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3176: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3177: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3178: if ((saveval != "correct") || override) {
3179: scorename.value = "";
3180: if (selval[1].selected) {
3181: selname[1].selected = true;
3182: } else {
3183: selname[2].selected = true;
3184: if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value))
3185: {document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
3186: }
3187: }
3188: }
3189: } else {
3190: for (i=0;i<document.classgrade.total.value;i++) {
3191: var user = document.classgrade["ctr"+i].value;
3192: user = user.replace(new RegExp(':', 'g'),"_");
3193: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3194: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3195: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3196: if ((saveval != "correct") || override) {
3197: scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
3198: selname[0].selected = true;
3199: }
3200: }
3201: }
3202: }
3203:
3204: function changeSelect(partid,user) {
3205: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
3206: var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
3207: var point = textbox.value;
3208: var weight = document.classgrade["weight_"+partid].value;
3209:
3210: if (isNaN(point) || parseFloat(point) < 0) {
3211: alert("$alertmsg"+parseFloat(point));
3212: textbox.value = "";
3213: return;
3214: }
3215: if (parseFloat(point) > parseFloat(weight)) {
3216: var resp = confirm("You entered a value ("+parseFloat(point)+
3217: ") greater than the weight of the part. Accept?");
3218: if (resp == false) {
3219: textbox.value = "";
3220: return;
3221: }
3222: }
3223: selval[0].selected = true;
3224: }
3225:
3226: function changeOneScore(partid,user) {
3227: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
3228: if (selval[1].selected || selval[2].selected) {
3229: document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
3230: if (selval[2].selected) {
3231: document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
3232: }
3233: }
3234: }
3235:
3236: function resetEntry(numpart) {
3237: for (ctpart=0;ctpart<numpart;ctpart++) {
3238: var partid = document.classgrade["partid_"+ctpart].value;
3239: var radioButton = document.classgrade["RADVAL_"+partid];
3240: var textbox = document.classgrade["TEXTVAL_"+partid];
3241: var selval = document.classgrade["SELVAL_"+partid];
3242: for (var i=0; i<radioButton.length; i++) {
3243: radioButton[i].checked=false;
3244:
3245: }
3246: textbox.value = "";
3247: selval[0].selected = true;
3248:
3249: for (i=0;i<document.classgrade.total.value;i++) {
3250: var user = document.classgrade["ctr"+i].value;
3251: user = user.replace(new RegExp(':', 'g'),"_");
3252: var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3253: resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
3254: var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
3255: resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
3256: var saveselval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3257: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3258: if (saveselval == "excused") {
3259: if (selname[1].selected == false) { selname[1].selected = true;}
3260: } else {
3261: if (selname[0].selected == false) {selname[0].selected = true};
3262: }
3263: }
3264: }
3265: }
3266:
3267: VIEWJAVASCRIPT
3268: }
3269:
3270: #--- show scores for a section or whole class w/ option to change/update a score
3271: sub viewgrades {
3272: my ($request,$symb) = @_;
3273: &viewgrades_js($request);
3274:
3275: #need to make sure we have the correct data for later EXT calls,
3276: #thus invalidate the cache
3277: &Apache::lonnet::devalidatecourseresdata(
3278: $env{'course.'.$env{'request.course.id'}.'.num'},
3279: $env{'course.'.$env{'request.course.id'}.'.domain'});
3280: &Apache::lonnet::clear_EXT_cache_status();
3281:
3282: my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
3283:
3284: #view individual student submission form - called using Javascript viewOneStudent
3285: $result.=&jscriptNform($symb);
3286:
3287: #beginning of class grading form
3288: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
3289: $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
3290: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
3291: '<input type="hidden" name="command" value="editgrades" />'."\n".
3292: &build_section_inputs().
3293: '<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
3294:
3295: my ($common_header,$specific_header);
3296: if ($env{'form.section'} eq 'all') {
3297: $common_header = &mt('Assign Common Grade to Class');
3298: $specific_header = &mt('Assign Grade to Specific Students in Class');
3299: } elsif ($env{'form.section'} eq 'none') {
3300: $common_header = &mt('Assign Common Grade to Students in no Section');
3301: $specific_header = &mt('Assign Grade to Specific Students in no Section');
3302: } else {
3303: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3304: $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
3305: $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
3306: }
3307: $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
3308: #radio buttons/text box for assigning points for a section or class.
3309: #handles different parts of a problem
3310: my $res_error;
3311: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
3312: if ($res_error) {
3313: return &navmap_errormsg();
3314: }
3315: my %weight = ();
3316: my $ctsparts = 0;
3317: my %seen = ();
3318: my @part_response_id = &flatten_responseType($responseType);
3319: foreach my $part_response_id (@part_response_id) {
3320: my ($partid,$respid) = @{ $part_response_id };
3321: my $part_resp = join('_',@{ $part_response_id });
3322: next if $seen{$partid};
3323: $seen{$partid}++;
3324: my $handgrade=$$handgrade{$part_resp};
3325: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
3326: $weight{$partid} = $wgt eq '' ? '1' : $wgt;
3327:
3328: my $display_part=&get_display_part($partid,$symb);
3329: my $radio.='<table border="0"><tr>';
3330: my $ctr = 0;
3331: while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
3332: $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
3333: 'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
3334: ','.$ctr.')" />'.$ctr."</label></td>\n";
3335: $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
3336: $ctr++;
3337: }
3338: $radio.='</tr></table>';
3339: my $line = '<input type="text" name="TEXTVAL_'.
3340: $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
3341: $partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
3342: $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
3343: $line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
3344: 'onchange="javascript:writeRadText(\''.$partid.'\','.
3345: $weight{$partid}.')"> '.
3346: '<option selected="selected"> </option>'.
3347: '<option value="excused">'.&mt('excused').'</option>'.
3348: '<option value="reset status">'.&mt('reset status').'</option>'.
3349: '</select></td>'.
3350: '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
3351: $line.='<input type="hidden" name="partid_'.
3352: $ctsparts.'" value="'.$partid.'" />'."\n";
3353: $line.='<input type="hidden" name="weight_'.
3354: $partid.'" value="'.$weight{$partid}.'" />'."\n";
3355:
3356: $result.=
3357: &Apache::loncommon::start_data_table_row()."\n".
3358: '<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>'.
3359: &Apache::loncommon::end_data_table_row()."\n";
3360: $ctsparts++;
3361: }
3362: $result.=&Apache::loncommon::end_data_table()."\n".
3363: '<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
3364: $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
3365: 'onclick="javascript:resetEntry('.$ctsparts.');" />';
3366:
3367: #table listing all the students in a section/class
3368: #header of table
3369: $result.= '<h3>'.$specific_header.'</h3>'.
3370: &Apache::loncommon::start_data_table().
3371: &Apache::loncommon::start_data_table_header_row().
3372: '<th>'.&mt('No.').'</th>'.
3373: '<th>'.&nameUserString('header')."</th>\n";
3374: my $partserror;
3375: my (@parts) = sort(&getpartlist($symb,\$partserror));
3376: if ($partserror) {
3377: return &navmap_errormsg();
3378: }
3379: my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
3380: my @partids = ();
3381: foreach my $part (@parts) {
3382: my $display=&Apache::lonnet::metadata($url,$part.'.display');
3383: my $narrowtext = &mt('Tries');
3384: $display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
3385: if (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
3386: my ($partid) = &split_part_type($part);
3387: push(@partids,$partid);
3388: #
3389: # FIXME: Looks like $display looks at English text
3390: #
3391: my $display_part=&get_display_part($partid,$symb);
3392: if ($display =~ /^Partial Credit Factor/) {
3393: $result.='<th>'.
3394: &mt('Score Part: [_1]<br /> (weight = [_2])',
3395: $display_part,$weight{$partid}).'</th>'."\n";
3396: next;
3397:
3398: } else {
3399: if ($display =~ /Problem Status/) {
3400: my $grade_status_mt = &mt('Grade Status');
3401: $display =~ s{Problem Status}{$grade_status_mt<br />};
3402: }
3403: my $part_mt = &mt('Part:');
3404: $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
3405: }
3406:
3407: $result.='<th>'.$display.'</th>'."\n";
3408: }
3409: $result.=&Apache::loncommon::end_data_table_header_row();
3410:
3411: my %last_resets =
3412: &get_last_resets($symb,$env{'request.course.id'},\@partids);
3413:
3414: #get info for each student
3415: #list all the students - with points and grade status
3416: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
3417: my $ctr = 0;
3418: foreach (sort
3419: {
3420: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
3421: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
3422: }
3423: return $a cmp $b;
3424: } (keys(%$fullname))) {
3425: $ctr++;
3426: $result.=&viewstudentgrade($symb,$env{'request.course.id'},
3427: $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
3428: }
3429: $result.=&Apache::loncommon::end_data_table();
3430: $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
3431: $result.='<input type="button" value="'.&mt('Save').'" '.
3432: 'onclick="javascript:submit();" target="_self" /></form>'."\n";
3433: if (scalar(%$fullname) eq 0) {
3434: my $colspan=3+scalar(@parts);
3435: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3436: my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
3437: $result='<span class="LC_warning">'.
3438: &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
3439: $section_display, $stu_status).
3440: '</span>';
3441: }
3442: return $result;
3443: }
3444:
3445: #--- call by previous routine to display each student
3446: sub viewstudentgrade {
3447: my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
3448: my ($uname,$udom) = split(/:/,$student);
3449: my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
3450: my %aggregates = ();
3451: my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
3452: '<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
3453: "\n".$ctr.' </td><td> '.
3454: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
3455: '\');" target="_self">'.$fullname.'</a> '.
3456: '<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
3457: $student=~s/:/_/; # colon doen't work in javascript for names
3458: foreach my $apart (@$parts) {
3459: my ($part,$type) = &split_part_type($apart);
3460: my $score=$record{"resource.$part.$type"};
3461: $result.='<td align="center">';
3462: my ($aggtries,$totaltries);
3463: unless (exists($aggregates{$part})) {
3464: $totaltries = $record{'resource.'.$part.'.tries'};
3465:
3466: $aggtries = $totaltries;
3467: if ($$last_resets{$part}) {
3468: $aggtries = &get_num_tries(\%record,$$last_resets{$part},
3469: $part);
3470: }
3471: $result.='<input type="hidden" name="'.
3472: 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
3473: $result.='<input type="hidden" name="'.
3474: 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
3475: $aggregates{$part} = 1;
3476: }
3477: if ($type eq 'awarded') {
3478: my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
3479: $result.='<input type="hidden" name="'.
3480: 'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
3481: $result.='<input type="text" name="'.
3482: 'GD_'.$student.'_'.$part.'_awarded" '.
3483: 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
3484: '\')" value="'.$pts.'" size="4" /></td>'."\n";
3485: } elsif ($type eq 'solved') {
3486: my ($status,$foo)=split(/_/,$score,2);
3487: $status = 'nothing' if ($status eq '');
3488: $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
3489: $part.'_solved_s" value="'.$status.'" />'."\n";
3490: $result.=' <select name="'.
3491: 'GD_'.$student.'_'.$part.'_solved" '.
3492: 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
3493: $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>'
3494: : '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
3495: $result.='<option value="reset status">'.&mt('reset status').'</option>';
3496: $result.="</select> </td>\n";
3497: } else {
3498: $result.='<input type="hidden" name="'.
3499: 'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
3500: "\n";
3501: $result.='<input type="text" name="'.
3502: 'GD_'.$student.'_'.$part.'_'.$type.'" '.
3503: 'value="'.$score.'" size="4" /></td>'."\n";
3504: }
3505: }
3506: $result.=&Apache::loncommon::end_data_table_row();
3507: return $result;
3508: }
3509:
3510: #--- change scores for all the students in a section/class
3511: # record does not get update if unchanged
3512: sub editgrades {
3513: my ($request,$symb) = @_;
3514:
3515: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3516: my $title='<h2>'.&mt('Current Grade Status').'</h2>';
3517: $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
3518:
3519: my $result= &Apache::loncommon::start_data_table().
3520: &Apache::loncommon::start_data_table_header_row().
3521: '<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
3522: '<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
3523: my %scoreptr = (
3524: 'correct' =>'correct_by_override',
3525: 'incorrect'=>'incorrect_by_override',
3526: 'excused' =>'excused',
3527: 'ungraded' =>'ungraded_attempted',
3528: 'credited' =>'credit_attempted',
3529: 'nothing' => '',
3530: );
3531: my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
3532:
3533: my (@partid);
3534: my %weight = ();
3535: my %columns = ();
3536: my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
3537:
3538: my $partserror;
3539: my (@parts) = sort(&getpartlist($symb,\$partserror));
3540: if ($partserror) {
3541: return &navmap_errormsg();
3542: }
3543: my $header;
3544: while ($ctr < $env{'form.totalparts'}) {
3545: my $partid = $env{'form.partid_'.$ctr};
3546: push(@partid,$partid);
3547: $weight{$partid} = $env{'form.weight_'.$partid};
3548: $ctr++;
3549: }
3550: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3551: foreach my $partid (@partid) {
3552: $header .= '<th align="center">'.&mt('Old Score').'</th>'.
3553: '<th align="center">'.&mt('New Score').'</th>';
3554: $columns{$partid}=2;
3555: foreach my $stores (@parts) {
3556: my ($part,$type) = &split_part_type($stores);
3557: if ($part !~ m/^\Q$partid\E/) { next;}
3558: if ($type eq 'awarded' || $type eq 'solved') { next; }
3559: my $display=&Apache::lonnet::metadata($url,$stores.'.display');
3560: $display =~ s/\[Part: \Q$part\E\]//;
3561: my $narrowtext = &mt('Tries');
3562: $display =~ s/Number of Attempts/$narrowtext/;
3563: $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
3564: '<th align="center">'.&mt('New').' '.$display.'</th>';
3565: $columns{$partid}+=2;
3566: }
3567: }
3568: foreach my $partid (@partid) {
3569: my $display_part=&get_display_part($partid,$symb);
3570: $result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
3571: &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
3572: '</th>';
3573:
3574: }
3575: $result .= &Apache::loncommon::end_data_table_header_row().
3576: &Apache::loncommon::start_data_table_header_row().
3577: $header.
3578: &Apache::loncommon::end_data_table_header_row();
3579: my @noupdate;
3580: my ($updateCtr,$noupdateCtr) = (1,1);
3581: for ($i=0; $i<$env{'form.total'}; $i++) {
3582: my $line;
3583: my $user = $env{'form.ctr'.$i};
3584: my ($uname,$udom)=split(/:/,$user);
3585: my %newrecord;
3586: my $updateflag = 0;
3587: $line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
3588: my $usec=$classlist->{"$uname:$udom"}[5];
3589: if (!&canmodify($usec)) {
3590: my $numcols=scalar(@partid)*4+2;
3591: push(@noupdate,
3592: $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
3593: &mt('Not allowed to modify student')."</span></td></tr>");
3594: next;
3595: }
3596: my %aggregate = ();
3597: my $aggregateflag = 0;
3598: $user=~s/:/_/; # colon doen't work in javascript for names
3599: foreach (@partid) {
3600: my $old_aw = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
3601: my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
3602: my $old_part = $old_aw eq '' ? '' : $old_part_pcr;
3603: my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
3604: my $awarded = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
3605: my $pcr = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
3606: my $partial = $awarded eq '' ? '' : $pcr;
3607: my $score;
3608: if ($partial eq '') {
3609: $score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
3610: } elsif ($partial > 0) {
3611: $score = 'correct_by_override';
3612: } elsif ($partial == 0) {
3613: $score = 'incorrect_by_override';
3614: }
3615: my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
3616: $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
3617:
3618: $newrecord{'resource.'.$_.'.regrader'}=
3619: "$env{'user.name'}:$env{'user.domain'}";
3620: if ($dropMenu eq 'reset status' &&
3621: $old_score ne '') { # ignore if no previous attempts => nothing to reset
3622: $newrecord{'resource.'.$_.'.tries'} = '';
3623: $newrecord{'resource.'.$_.'.solved'} = '';
3624: $newrecord{'resource.'.$_.'.award'} = '';
3625: $newrecord{'resource.'.$_.'.awarded'} = '';
3626: $updateflag = 1;
3627: if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
3628: my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
3629: my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
3630: my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
3631: &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
3632: $aggregateflag = 1;
3633: }
3634: } elsif (!($old_part eq $partial && $old_score eq $score)) {
3635: $updateflag = 1;
3636: $newrecord{'resource.'.$_.'.awarded'} = $partial if $partial ne '';
3637: $newrecord{'resource.'.$_.'.solved'} = $score;
3638: $rec_update++;
3639: }
3640:
3641: $line .= '<td align="center">'.$old_aw.' </td>'.
3642: '<td align="center">'.$awarded.
3643: ($score eq 'excused' ? $score : '').' </td>';
3644:
3645:
3646: my $partid=$_;
3647: foreach my $stores (@parts) {
3648: my ($part,$type) = &split_part_type($stores);
3649: if ($part !~ m/^\Q$partid\E/) { next;}
3650: if ($type eq 'awarded' || $type eq 'solved') { next; }
3651: my $old_aw = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
3652: my $awarded = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
3653: if ($awarded ne '' && $awarded ne $old_aw) {
3654: $newrecord{'resource.'.$part.'.'.$type}= $awarded;
3655: $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
3656: $updateflag=1;
3657: }
3658: $line .= '<td align="center">'.$old_aw.' </td>'.
3659: '<td align="center">'.$awarded.' </td>';
3660: }
3661: }
3662: $line.="\n";
3663:
3664: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3665: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3666:
3667: if ($updateflag) {
3668: $count++;
3669: &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
3670: $udom,$uname);
3671:
3672: if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
3673: $cnum,$udom,$uname)) {
3674: # need to figure out if should be in queue.
3675: my %record =
3676: &Apache::lonnet::restore($symb,$env{'request.course.id'},
3677: $udom,$uname);
3678: my $all_graded = 1;
3679: my $none_graded = 1;
3680: foreach my $part (@parts) {
3681: if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
3682: $all_graded = 0;
3683: } else {
3684: $none_graded = 0;
3685: }
3686: }
3687:
3688: if ($all_graded || $none_graded) {
3689: &Apache::bridgetask::remove_from_queue('gradingqueue',
3690: $symb,$cdom,$cnum,
3691: $udom,$uname);
3692: }
3693: }
3694:
3695: $result.=&Apache::loncommon::start_data_table_row().
3696: '<td align="right"> '.$updateCtr.' </td>'.$line.
3697: &Apache::loncommon::end_data_table_row();
3698: $updateCtr++;
3699: } else {
3700: push(@noupdate,
3701: '<td align="right"> '.$noupdateCtr.' </td>'.$line);
3702: $noupdateCtr++;
3703: }
3704: if ($aggregateflag) {
3705: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
3706: $cdom,$cnum);
3707: }
3708: }
3709: if (@noupdate) {
3710: # my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
3711: my $numcols=scalar(@partid)*4+2;
3712: $result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
3713: '<td align="center" colspan="'.$numcols.'">'.
3714: &mt('No Changes Occurred For the Students Below').
3715: '</td>'.
3716: &Apache::loncommon::end_data_table_row();
3717: foreach my $line (@noupdate) {
3718: $result.=
3719: &Apache::loncommon::start_data_table_row().
3720: $line.
3721: &Apache::loncommon::end_data_table_row();
3722: }
3723: }
3724: $result .= &Apache::loncommon::end_data_table();
3725: my $msg = '<p><b>'.
3726: &mt('Number of records updated = [_1] for [quant,_2,student].',
3727: $rec_update,$count).'</b><br />'.
3728: '<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
3729: '</b></p>';
3730: return $title.$msg.$result;
3731: }
3732:
3733: sub split_part_type {
3734: my ($partstr) = @_;
3735: my ($temp,@allparts)=split(/_/,$partstr);
3736: my $type=pop(@allparts);
3737: my $part=join('_',@allparts);
3738: return ($part,$type);
3739: }
3740:
3741: #------------- end of section for handling grading by section/class ---------
3742: #
3743: #----------------------------------------------------------------------------
3744:
3745:
3746: #----------------------------------------------------------------------------
3747: #
3748: #-------------------------- Next few routines handles grading by csv upload
3749: #
3750: #--- Javascript to handle csv upload
3751: sub csvupload_javascript_reverse_associate {
3752: my $error1=&mt('You need to specify the username or the student/employee ID');
3753: my $error2=&mt('You need to specify at least one grading field');
3754: return(<<ENDPICK);
3755: function verify(vf) {
3756: var foundsomething=0;
3757: var founduname=0;
3758: var foundID=0;
3759: for (i=0;i<=vf.nfields.value;i++) {
3760: tw=eval('vf.f'+i+'.selectedIndex');
3761: if (i==0 && tw!=0) { foundID=1; }
3762: if (i==1 && tw!=0) { founduname=1; }
3763: if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
3764: }
3765: if (founduname==0 && foundID==0) {
3766: alert('$error1');
3767: return;
3768: }
3769: if (foundsomething==0) {
3770: alert('$error2');
3771: return;
3772: }
3773: vf.submit();
3774: }
3775: function flip(vf,tf) {
3776: var nw=eval('vf.f'+tf+'.selectedIndex');
3777: var i;
3778: for (i=0;i<=vf.nfields.value;i++) {
3779: //can not pick the same destination field for both name and domain
3780: if (((i ==0)||(i ==1)) &&
3781: ((tf==0)||(tf==1)) &&
3782: (i!=tf) &&
3783: (eval('vf.f'+i+'.selectedIndex')==nw)) {
3784: eval('vf.f'+i+'.selectedIndex=0;')
3785: }
3786: }
3787: }
3788: ENDPICK
3789: }
3790:
3791: sub csvupload_javascript_forward_associate {
3792: my $error1=&mt('You need to specify the username or the student/employee ID');
3793: my $error2=&mt('You need to specify at least one grading field');
3794: return(<<ENDPICK);
3795: function verify(vf) {
3796: var foundsomething=0;
3797: var founduname=0;
3798: var foundID=0;
3799: for (i=0;i<=vf.nfields.value;i++) {
3800: tw=eval('vf.f'+i+'.selectedIndex');
3801: if (tw==1) { foundID=1; }
3802: if (tw==2) { founduname=1; }
3803: if (tw>3) { foundsomething=1; }
3804: }
3805: if (founduname==0 && foundID==0) {
3806: alert('$error1');
3807: return;
3808: }
3809: if (foundsomething==0) {
3810: alert('$error2');
3811: return;
3812: }
3813: vf.submit();
3814: }
3815: function flip(vf,tf) {
3816: var nw=eval('vf.f'+tf+'.selectedIndex');
3817: var i;
3818: //can not pick the same destination field twice
3819: for (i=0;i<=vf.nfields.value;i++) {
3820: if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
3821: eval('vf.f'+i+'.selectedIndex=0;')
3822: }
3823: }
3824: }
3825: ENDPICK
3826: }
3827:
3828: sub csvuploadmap_header {
3829: my ($request,$symb,$datatoken,$distotal)= @_;
3830: my $javascript;
3831: if ($env{'form.upfile_associate'} eq 'reverse') {
3832: $javascript=&csvupload_javascript_reverse_associate();
3833: } else {
3834: $javascript=&csvupload_javascript_forward_associate();
3835: }
3836:
3837: $symb = &Apache::lonenc::check_encrypt($symb);
3838: $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
3839: &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
3840: &mt('Associate entries from the uploaded file with as many fields as you can.'));
3841: my $reverse=&mt("Reverse Association");
3842: $request->print(<<ENDPICK);
3843: <br />
3844: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
3845: <input type="hidden" name="associate" value="" />
3846: <input type="hidden" name="phase" value="three" />
3847: <input type="hidden" name="datatoken" value="$datatoken" />
3848: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
3849: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
3850: <input type="hidden" name="upfile_associate"
3851: value="$env{'form.upfile_associate'}" />
3852: <input type="hidden" name="symb" value="$symb" />
3853: <input type="hidden" name="command" value="csvuploadoptions" />
3854: <hr />
3855: ENDPICK
3856: $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
3857: return '';
3858:
3859: }
3860:
3861: sub csvupload_fields {
3862: my ($symb,$errorref) = @_;
3863: my (@parts) = &getpartlist($symb,$errorref);
3864: if (ref($errorref)) {
3865: if ($$errorref) {
3866: return;
3867: }
3868: }
3869:
3870: my @fields=(['ID','Student/Employee ID'],
3871: ['username','Student Username'],
3872: ['domain','Student Domain']);
3873: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3874: foreach my $part (sort(@parts)) {
3875: my @datum;
3876: my $display=&Apache::lonnet::metadata($url,$part.'.display');
3877: my $name=$part;
3878: if (!$display) { $display = $name; }
3879: @datum=($name,$display);
3880: if ($name=~/^stores_(.*)_awarded/) {
3881: push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
3882: }
3883: push(@fields,\@datum);
3884: }
3885: return (@fields);
3886: }
3887:
3888: sub csvuploadmap_footer {
3889: my ($request,$i,$keyfields) =@_;
3890: $request->print(<<ENDPICK);
3891: </table>
3892: <input type="hidden" name="nfields" value="$i" />
3893: <input type="hidden" name="keyfields" value="$keyfields" />
3894: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
3895: </form>
3896: ENDPICK
3897: }
3898:
3899: sub checkforfile_js {
3900: my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
3901: my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
3902: function checkUpload(formname) {
3903: if (formname.upfile.value == "") {
3904: alert("$alertmsg");
3905: return false;
3906: }
3907: formname.submit();
3908: }
3909: CSVFORMJS
3910: return $result;
3911: }
3912:
3913: sub upcsvScores_form {
3914: my ($request,$symb) = @_;
3915: if (!$symb) {return '';}
3916: my $result=&checkforfile_js();
3917: $result.=&Apache::loncommon::start_data_table().
3918: &Apache::loncommon::start_data_table_header_row().
3919: '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
3920: &Apache::loncommon::end_data_table_header_row().
3921: &Apache::loncommon::start_data_table_row().'<td>';
3922: my $upload=&mt("Upload Scores");
3923: my $upfile_select=&Apache::loncommon::upfile_select_html();
3924: my $ignore=&mt('Ignore First Line');
3925: $symb = &Apache::lonenc::check_encrypt($symb);
3926: $result.=<<ENDUPFORM;
3927: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3928: <input type="hidden" name="symb" value="$symb" />
3929: <input type="hidden" name="command" value="csvuploadmap" />
3930: $upfile_select
3931: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
3932: </form>
3933: ENDUPFORM
3934: $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
3935: &mt("How do I create a CSV file from a spreadsheet")).
3936: '</td>'.
3937: &Apache::loncommon::end_data_table_row().
3938: &Apache::loncommon::end_data_table();
3939: return $result;
3940: }
3941:
3942:
3943: sub csvuploadmap {
3944: my ($request,$symb)= @_;
3945: if (!$symb) {return '';}
3946:
3947: my $datatoken;
3948: if (!$env{'form.datatoken'}) {
3949: $datatoken=&Apache::loncommon::upfile_store($request);
3950: } else {
3951: $datatoken=$env{'form.datatoken'};
3952: &Apache::loncommon::load_tmp_file($request);
3953: }
3954: my @records=&Apache::loncommon::upfile_record_sep();
3955: &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
3956: my ($i,$keyfields);
3957: if (@records) {
3958: my $fieldserror;
3959: my @fields=&csvupload_fields($symb,\$fieldserror);
3960: if ($fieldserror) {
3961: $request->print(&navmap_errormsg());
3962: return;
3963: }
3964: if ($env{'form.upfile_associate'} eq 'reverse') {
3965: &Apache::loncommon::csv_print_samples($request,\@records);
3966: $i=&Apache::loncommon::csv_print_select_table($request,\@records,
3967: \@fields);
3968: foreach (@fields) { $keyfields.=$_->[0].','; }
3969: chop($keyfields);
3970: } else {
3971: unshift(@fields,['none','']);
3972: $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
3973: \@fields);
3974: foreach my $rec (@records) {
3975: my %temp = &Apache::loncommon::record_sep($rec);
3976: if (%temp) {
3977: $keyfields=join(',',sort(keys(%temp)));
3978: last;
3979: }
3980: }
3981: }
3982: }
3983: &csvuploadmap_footer($request,$i,$keyfields);
3984:
3985: return '';
3986: }
3987:
3988: sub csvuploadoptions {
3989: my ($request,$symb)= @_;
3990: my $overwrite=&mt('Overwrite any existing score');
3991: $request->print(<<ENDPICK);
3992: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3993: <input type="hidden" name="command" value="csvuploadassign" />
3994: <p>
3995: <label>
3996: <input type="checkbox" name="overwite_scores" checked="checked" />
3997: $overwrite
3998: </label>
3999: </p>
4000: ENDPICK
4001: my %fields=&get_fields();
4002: if (!defined($fields{'domain'})) {
4003: my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
4004: $request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
4005: }
4006: foreach my $key (sort(keys(%env))) {
4007: if ($key !~ /^form\.(.*)$/) { next; }
4008: my $cleankey=$1;
4009: if ($cleankey eq 'command') { next; }
4010: $request->print('<input type="hidden" name="'.$cleankey.
4011: '" value="'.$env{$key}.'" />'."\n");
4012: }
4013: # FIXME do a check for any duplicated user ids...
4014: # FIXME do a check for any invalid user ids?...
4015: $request->print('<input type="submit" value="Assign Grades" /><br />
4016: <hr /></form>'."\n");
4017: return '';
4018: }
4019:
4020: sub get_fields {
4021: my %fields;
4022: my @keyfields = split(/\,/,$env{'form.keyfields'});
4023: for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
4024: if ($env{'form.upfile_associate'} eq 'reverse') {
4025: if ($env{'form.f'.$i} ne 'none') {
4026: $fields{$keyfields[$i]}=$env{'form.f'.$i};
4027: }
4028: } else {
4029: if ($env{'form.f'.$i} ne 'none') {
4030: $fields{$env{'form.f'.$i}}=$keyfields[$i];
4031: }
4032: }
4033: }
4034: return %fields;
4035: }
4036:
4037: sub csvuploadassign {
4038: my ($request,$symb)= @_;
4039: if (!$symb) {return '';}
4040: my $error_msg = '';
4041: &Apache::loncommon::load_tmp_file($request);
4042: my @gradedata = &Apache::loncommon::upfile_record_sep();
4043: my %fields=&get_fields();
4044: my $courseid=$env{'request.course.id'};
4045: my ($classlist) = &getclasslist('all',0);
4046: my @notallowed;
4047: my @skipped;
4048: my $countdone=0;
4049: foreach my $grade (@gradedata) {
4050: my %entries=&Apache::loncommon::record_sep($grade);
4051: my $domain;
4052: if ($entries{$fields{'domain'}}) {
4053: $domain=$entries{$fields{'domain'}};
4054: } else {
4055: $domain=$env{'form.default_domain'};
4056: }
4057: $domain=~s/\s//g;
4058: my $username=$entries{$fields{'username'}};
4059: $username=~s/\s//g;
4060: if (!$username) {
4061: my $id=$entries{$fields{'ID'}};
4062: $id=~s/\s//g;
4063: my %ids=&Apache::lonnet::idget($domain,$id);
4064: $username=$ids{$id};
4065: }
4066: if (!exists($$classlist{"$username:$domain"})) {
4067: my $id=$entries{$fields{'ID'}};
4068: $id=~s/\s//g;
4069: if ($id) {
4070: push(@skipped,"$id:$domain");
4071: } else {
4072: push(@skipped,"$username:$domain");
4073: }
4074: next;
4075: }
4076: my $usec=$classlist->{"$username:$domain"}[5];
4077: if (!&canmodify($usec)) {
4078: push(@notallowed,"$username:$domain");
4079: next;
4080: }
4081: my %points;
4082: my %grades;
4083: foreach my $dest (keys(%fields)) {
4084: if ($dest eq 'ID' || $dest eq 'username' ||
4085: $dest eq 'domain') { next; }
4086: if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
4087: if ($dest=~/stores_(.*)_points/) {
4088: my $part=$1;
4089: my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
4090: $symb,$domain,$username);
4091: if ($wgt) {
4092: $entries{$fields{$dest}}=~s/\s//g;
4093: my $pcr=$entries{$fields{$dest}} / $wgt;
4094: my $award=($pcr == 0) ? 'incorrect_by_override'
4095: : 'correct_by_override';
4096: if ($pcr>1) {
4097: push(@skipped,&mt("[_1]: point value larger than weight","$username:$domain"));
4098: }
4099: $grades{"resource.$part.awarded"}=$pcr;
4100: $grades{"resource.$part.solved"}=$award;
4101: $points{$part}=1;
4102: } else {
4103: $error_msg = "<br />" .
4104: &mt("Some point values were assigned"
4105: ." for problems with a weight "
4106: ."of zero. These values were "
4107: ."ignored.");
4108: }
4109: } else {
4110: if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
4111: if ($dest=~/stores_(.*)_solved/) { if ($points{$1}) {next;} }
4112: my $store_key=$dest;
4113: $store_key=~s/^stores/resource/;
4114: $store_key=~s/_/\./g;
4115: $grades{$store_key}=$entries{$fields{$dest}};
4116: }
4117: }
4118: if (! %grades) {
4119: push(@skipped,&mt("[_1]: no data to save","$username:$domain"));
4120: } else {
4121: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
4122: my $result=&Apache::lonnet::cstore(\%grades,$symb,
4123: $env{'request.course.id'},
4124: $domain,$username);
4125: if ($result eq 'ok') {
4126: # Successfully stored
4127: $request->print('.');
4128: # Remove from grading queue
4129: &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
4130: $env{'course.'.$env{'request.course.id'}.'.domain'},
4131: $env{'course.'.$env{'request.course.id'}.'.num'},
4132: $domain,$username);
4133: $countdone++;
4134: } else {
4135: $request->print("<p><span class=\"LC_error\">".
4136: &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
4137: "$username:$domain",$result)."</span></p>");
4138: }
4139: $request->rflush();
4140: }
4141: }
4142: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
4143: if (@skipped) {
4144: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
4145: $request->print(join(', ',@skipped));
4146: }
4147: if (@notallowed) {
4148: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
4149: $request->print(join(', ',@notallowed));
4150: }
4151: $request->print("<br />\n");
4152: return $error_msg;
4153: }
4154: #------------- end of section for handling csv file upload ---------
4155: #
4156: #-------------------------------------------------------------------
4157: #
4158: #-------------- Next few routines handle grading by page/sequence
4159: #
4160: #--- Select a page/sequence and a student to grade
4161: sub pickStudentPage {
4162: my ($request,$symb) = @_;
4163:
4164: my $alertmsg = &mt('Please select the student you wish to grade.');
4165: $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
4166:
4167: function checkPickOne(formname) {
4168: if (radioSelection(formname.student) == null) {
4169: alert("$alertmsg");
4170: return;
4171: }
4172: ptr = pullDownSelection(formname.selectpage);
4173: formname.page.value = formname["page"+ptr].value;
4174: formname.title.value = formname["title"+ptr].value;
4175: formname.submit();
4176: }
4177:
4178: LISTJAVASCRIPT
4179: &commonJSfunctions($request);
4180:
4181: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4182: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4183: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4184:
4185: my $result='<h3><span class="LC_info"> '.
4186: &mt('Manual Grading by Page or Sequence').'</span></h3>';
4187:
4188: $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
4189: my $map_error;
4190: my ($titles,$symbx) = &getSymbMap($map_error);
4191: if ($map_error) {
4192: $request->print(&navmap_errormsg());
4193: return;
4194: }
4195: my ($curpage) =&Apache::lonnet::decode_symb($symb);
4196: # my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb);
4197: # my $type=($curpage =~ /\.(page|sequence)/);
4198: my $select = '<select name="selectpage">'."\n";
4199: my $ctr=0;
4200: foreach (@$titles) {
4201: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4202: $select.='<option value="'.$ctr.'" '.
4203: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
4204: '>'.$showtitle.'</option>'."\n";
4205: $ctr++;
4206: }
4207: $select.= '</select>';
4208: $result.=' <b>'.&mt('Problems from').':</b> '.$select."<br />\n";
4209:
4210: $ctr=0;
4211: foreach (@$titles) {
4212: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4213: $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
4214: $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
4215: $ctr++;
4216: }
4217: $result.='<input type="hidden" name="page" />'."\n".
4218: '<input type="hidden" name="title" />'."\n";
4219:
4220: my $options =
4221: '<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
4222: '<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
4223: $result.=' <b>'.&mt('View Problem Text').': </b>'.$options;
4224:
4225: $options =
4226: '<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
4227: '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
4228: '<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
4229: $result.=' <b>'.&mt('Submissions').': </b>'.$options;
4230:
4231: $result.=&build_section_inputs();
4232: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
4233: $result.='<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
4234: '<input type="hidden" name="command" value="displayPage" />'."\n".
4235: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."<br />\n";
4236:
4237: $result.=' <b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
4238:
4239: $result.=' <input type="button" '.
4240: 'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' →" /><br />'."\n";
4241:
4242: $request->print($result);
4243:
4244: my $studentTable.=' <b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
4245: &Apache::loncommon::start_data_table().
4246: &Apache::loncommon::start_data_table_header_row().
4247: '<th align="right"> '.&mt('No.').'</th>'.
4248: '<th>'.&nameUserString('header').'</th>'.
4249: '<th align="right"> '.&mt('No.').'</th>'.
4250: '<th>'.&nameUserString('header').'</th>'.
4251: &Apache::loncommon::end_data_table_header_row();
4252:
4253: my (undef,undef,$fullname) = &getclasslist($getsec,'1');
4254: my $ptr = 1;
4255: foreach my $student (sort
4256: {
4257: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
4258: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
4259: }
4260: return $a cmp $b;
4261: } (keys(%$fullname))) {
4262: my ($uname,$udom) = split(/:/,$student);
4263: $studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
4264: : '</td>');
4265: $studentTable.='<td align="right">'.$ptr.' </td>';
4266: $studentTable.='<td> <label><input type="radio" name="student" value="'.$student.'" /> '
4267: .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
4268: $studentTable.=
4269: ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row()
4270: : '');
4271: $ptr++;
4272: }
4273: if ($ptr%2 == 0) {
4274: $studentTable.='</td><td> </td><td> </td>'.
4275: &Apache::loncommon::end_data_table_row();
4276: }
4277: $studentTable.=&Apache::loncommon::end_data_table()."\n";
4278: $studentTable.='<input type="button" '.
4279: 'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' →" /></form>'."\n";
4280:
4281: $request->print($studentTable);
4282:
4283: return '';
4284: }
4285:
4286: sub getSymbMap {
4287: my ($map_error) = @_;
4288: my $navmap = Apache::lonnavmaps::navmap->new();
4289: unless (ref($navmap)) {
4290: if (ref($map_error)) {
4291: $$map_error = 'navmap';
4292: }
4293: return;
4294: }
4295: my %symbx = ();
4296: my @titles = ();
4297: my $minder = 0;
4298:
4299: # Gather every sequence that has problems.
4300: my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
4301: 1,0,1);
4302: for my $sequence ($navmap->getById('0.0'), @sequences) {
4303: if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
4304: my $title = $minder.'.'.
4305: &HTML::Entities::encode($sequence->compTitle(),'"\'&');
4306: push(@titles, $title); # minder in case two titles are identical
4307: $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
4308: $minder++;
4309: }
4310: }
4311: return \@titles,\%symbx;
4312: }
4313:
4314: #
4315: #--- Displays a page/sequence w/wo problems, w/wo submissions
4316: sub displayPage {
4317: my ($request,$symb) = @_;
4318: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4319: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4320: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4321: my $pageTitle = $env{'form.page'};
4322: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
4323: my ($uname,$udom) = split(/:/,$env{'form.student'});
4324: my $usec=$classlist->{$env{'form.student'}}[5];
4325:
4326: #need to make sure we have the correct data for later EXT calls,
4327: #thus invalidate the cache
4328: &Apache::lonnet::devalidatecourseresdata(
4329: $env{'course.'.$env{'request.course.id'}.'.num'},
4330: $env{'course.'.$env{'request.course.id'}.'.domain'});
4331: &Apache::lonnet::clear_EXT_cache_status();
4332:
4333: if (!&canview($usec)) {
4334: $request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
4335: return;
4336: }
4337: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
4338: $result.='<h3> '.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
4339: '</h3>'."\n";
4340: $env{'form.CODE'} = uc($env{'form.CODE'});
4341: if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
4342: $result.='<h3> '.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
4343: } else {
4344: delete($env{'form.CODE'});
4345: }
4346: &sub_page_js($request);
4347: $request->print($result);
4348:
4349: my $navmap = Apache::lonnavmaps::navmap->new();
4350: unless (ref($navmap)) {
4351: $request->print(&navmap_errormsg());
4352: return;
4353: }
4354: my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
4355: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
4356: if (!$map) {
4357: $request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
4358: return;
4359: }
4360: my $iterator = $navmap->getIterator($map->map_start(),
4361: $map->map_finish());
4362:
4363: my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
4364: '<input type="hidden" name="command" value="gradeByPage" />'."\n".
4365: '<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
4366: '<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
4367: '<input type="hidden" name="page" value="'.$pageTitle.'" />'."\n".
4368: '<input type="hidden" name="title" value="'.$env{'form.title'}.'" />'."\n".
4369: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
4370: '<input type="hidden" name="overRideScore" value="no" />'."\n";
4371:
4372: if (defined($env{'form.CODE'})) {
4373: $studentTable.=
4374: '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
4375: }
4376: my $checkIcon = '<img alt="'.&mt('Check Mark').
4377: '" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
4378:
4379: $studentTable.=' <span class="LC_info">'.
4380: &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
4381: '</span>'."\n".
4382: &Apache::loncommon::start_data_table().
4383: &Apache::loncommon::start_data_table_header_row().
4384: '<th align="center"> Prob. </th>'.
4385: '<th> '.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
4386: &Apache::loncommon::end_data_table_header_row();
4387:
4388: &Apache::lonxml::clear_problem_counter();
4389: my ($depth,$question,$prob) = (1,1,1);
4390: $iterator->next(); # skip the first BEGIN_MAP
4391: my $curRes = $iterator->next(); # for "current resource"
4392: while ($depth > 0) {
4393: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
4394: if($curRes == $iterator->END_MAP) { $depth--; }
4395:
4396: if (ref($curRes) && $curRes->is_problem()) {
4397: my $parts = $curRes->parts();
4398: my $title = $curRes->compTitle();
4399: my $symbx = $curRes->symb();
4400: $studentTable.=
4401: &Apache::loncommon::start_data_table_row().
4402: '<td align="center" valign="top" >'.$prob.
4403: (scalar(@{$parts}) == 1 ? ''
4404: : '<br />('.&mt('[_1]parts)',
4405: scalar(@{$parts}).' ')
4406: ).
4407: '</td>';
4408: $studentTable.='<td valign="top">';
4409: my %form = ('CODE' => $env{'form.CODE'},);
4410: if ($env{'form.vProb'} eq 'yes' ) {
4411: $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
4412: undef,'both',\%form);
4413: } else {
4414: my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
4415: $companswer =~ s|<form(.*?)>||g;
4416: $companswer =~ s|</form>||g;
4417: # while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
4418: # $companswer =~ s/$1/ /ms;
4419: # $request->print('match='.$1."<br />\n");
4420: # }
4421: # $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
4422: $studentTable.=' <b>'.$title.'</b> <br /> <b>'.&mt('Correct answer').':</b><br />'.$companswer;
4423: }
4424:
4425: my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
4426:
4427: if ($env{'form.lastSub'} eq 'datesub') {
4428: if ($record{'version'} eq '') {
4429: $studentTable.='<br /> <span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
4430: } else {
4431: my %responseType = ();
4432: foreach my $partid (@{$parts}) {
4433: my @responseIds =$curRes->responseIds($partid);
4434: my @responseType =$curRes->responseType($partid);
4435: my %responseIds;
4436: for (my $i=0;$i<=$#responseIds;$i++) {
4437: $responseIds{$responseIds[$i]}=$responseType[$i];
4438: }
4439: $responseType{$partid} = \%responseIds;
4440: }
4441: $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
4442:
4443: }
4444: } elsif ($env{'form.lastSub'} eq 'all') {
4445: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
4446: $studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
4447: $env{'request.course.id'},
4448: '','.submission');
4449:
4450: }
4451: if (&canmodify($usec)) {
4452: $studentTable.=&gradeBox_start();
4453: foreach my $partid (@{$parts}) {
4454: $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
4455: $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
4456: $question++;
4457: }
4458: $studentTable.=&gradeBox_end();
4459: $prob++;
4460: }
4461: $studentTable.='</td></tr>';
4462:
4463: }
4464: $curRes = $iterator->next();
4465: }
4466:
4467: $studentTable.=
4468: '</table>'."\n".
4469: '<input type="button" value="'.&mt('Save').'" '.
4470: 'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
4471: '</form>'."\n";
4472: $request->print($studentTable);
4473:
4474: return '';
4475: }
4476:
4477: sub displaySubByDates {
4478: my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
4479: my $isCODE=0;
4480: my $isTask = ($symb =~/\.task$/);
4481: if (exists($record->{'resource.CODE'})) { $isCODE=1; }
4482: my $studentTable=&Apache::loncommon::start_data_table().
4483: &Apache::loncommon::start_data_table_header_row().
4484: '<th>'.&mt('Date/Time').'</th>'.
4485: ($isCODE?'<th>'.&mt('CODE').'</th>':'').
4486: '<th>'.&mt('Submission').'</th>'.
4487: '<th>'.&mt('Status').'</th>'.
4488: &Apache::loncommon::end_data_table_header_row();
4489: my ($version);
4490: my %mark;
4491: my %orders;
4492: $mark{'correct_by_student'} = $checkIcon;
4493: if (!exists($$record{'1:timestamp'})) {
4494: return '<br /> <span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
4495: }
4496:
4497: my $interaction;
4498: my $no_increment = 1;
4499: my %lastrndseed;
4500: for ($version=1;$version<=$$record{'version'};$version++) {
4501: my $timestamp =
4502: &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
4503: if (exists($$record{$version.':resource.0.version'})) {
4504: $interaction = $$record{$version.':resource.0.version'};
4505: }
4506:
4507: my $where = ($isTask ? "$version:resource.$interaction"
4508: : "$version:resource");
4509: $studentTable.=&Apache::loncommon::start_data_table_row().
4510: '<td>'.$timestamp.'</td>';
4511: if ($isCODE) {
4512: $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
4513: }
4514: my @versionKeys = split(/\:/,$$record{$version.':keys'});
4515: my @displaySub = ();
4516: foreach my $partid (@{$parts}) {
4517: my ($hidden,$type);
4518: $type = $$record{$version.':resource.'.$partid.'.type'};
4519: if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
4520: $hidden = 1;
4521: }
4522: my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
4523: : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
4524:
4525: # next if ($$record{"$version:resource.$partid.solved"} eq '');
4526: my $display_part=&get_display_part($partid,$symb);
4527: foreach my $matchKey (@matchKey) {
4528: if (exists($$record{$version.':'.$matchKey}) &&
4529: $$record{$version.':'.$matchKey} ne '') {
4530:
4531: my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
4532: : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
4533: $displaySub[0].='<span class="LC_nobreak"';
4534: $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
4535: .' <span class="LC_internal_info">'
4536: .'('.&mt('Response ID: [_1]',$responseId).')'
4537: .'</span>'
4538: .' <b>';
4539: if ($hidden) {
4540: $displaySub[0].= &mt('Anonymous Survey').'</b>';
4541: } else {
4542: my ($trial,$rndseed,$newvariation);
4543: if ($type eq 'randomizetry') {
4544: $trial = $$record{"$where.$partid.tries"};
4545: $rndseed = $$record{"$where.$partid.rndseed"};
4546: }
4547: if ($$record{"$where.$partid.tries"} eq '') {
4548: $displaySub[0].=&mt('Trial not counted');
4549: } else {
4550: $displaySub[0].=&mt('Trial: [_1]',
4551: $$record{"$where.$partid.tries"});
4552: if ($rndseed || $lastrndseed{$partid}) {
4553: if ($rndseed ne $lastrndseed{$partid}) {
4554: $newvariation = ' ('.&mt('New variation this try').')';
4555: }
4556: }
4557: $lastrndseed{$partid} = $rndseed;
4558: }
4559: my $responseType=($isTask ? 'Task'
4560: : $responseType->{$partid}->{$responseId});
4561: if (!exists($orders{$partid})) { $orders{$partid}={}; }
4562: if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
4563: $orders{$partid}->{$responseId}=
4564: &get_order($partid,$responseId,$symb,$uname,$udom,
4565: $no_increment,$type,$trial,$rndseed);
4566: }
4567: $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
4568: $displaySub[0].=' '.
4569: &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
4570: }
4571: }
4572: }
4573: if (exists($$record{"$where.$partid.checkedin"})) {
4574: $displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
4575: $$record{"$where.$partid.checkedin"},
4576: $$record{"$where.$partid.checkedin.slot"}).
4577: '<br />';
4578: }
4579: if (exists $$record{"$where.$partid.award"}) {
4580: $displaySub[1].='<b>'.&mt('Part:').'</b> '.$display_part.' '.
4581: lc($$record{"$where.$partid.award"}).' '.
4582: $mark{$$record{"$where.$partid.solved"}}.
4583: '<br />';
4584: }
4585: if (exists $$record{"$where.$partid.regrader"}) {
4586: $displaySub[2].=$$record{"$where.$partid.regrader"}.
4587: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
4588: } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
4589: $displaySub[2].=
4590: $$record{"$version:resource.$partid.regrader"}.
4591: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
4592: }
4593: }
4594: # needed because old essay regrader has not parts info
4595: if (exists $$record{"$version:resource.regrader"}) {
4596: $displaySub[2].=$$record{"$version:resource.regrader"};
4597: }
4598: $studentTable.='<td>'.$displaySub[0].' </td><td>'.$displaySub[1];
4599: if ($displaySub[2]) {
4600: $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
4601: }
4602: $studentTable.=' </td>'.
4603: &Apache::loncommon::end_data_table_row();
4604: }
4605: $studentTable.=&Apache::loncommon::end_data_table();
4606: return $studentTable;
4607: }
4608:
4609: sub updateGradeByPage {
4610: my ($request,$symb) = @_;
4611:
4612: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4613: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4614: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4615: my $pageTitle = $env{'form.page'};
4616: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
4617: my ($uname,$udom) = split(/:/,$env{'form.student'});
4618: my $usec=$classlist->{$env{'form.student'}}[5];
4619: if (!&canmodify($usec)) {
4620: $request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
4621: return;
4622: }
4623: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
4624: $result.='<h3> '.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
4625: '</h3>'."\n";
4626:
4627: $request->print($result);
4628:
4629:
4630: my $navmap = Apache::lonnavmaps::navmap->new();
4631: unless (ref($navmap)) {
4632: $request->print(&navmap_errormsg());
4633: return;
4634: }
4635: my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
4636: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
4637: if (!$map) {
4638: $request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
4639: return;
4640: }
4641: my $iterator = $navmap->getIterator($map->map_start(),
4642: $map->map_finish());
4643:
4644: my $studentTable=
4645: &Apache::loncommon::start_data_table().
4646: &Apache::loncommon::start_data_table_header_row().
4647: '<th align="center"> '.&mt('Prob.').' </th>'.
4648: '<th> '.&mt('Title').' </th>'.
4649: '<th> '.&mt('Previous Score').' </th>'.
4650: '<th> '.&mt('New Score').' </th>'.
4651: &Apache::loncommon::end_data_table_header_row();
4652:
4653: $iterator->next(); # skip the first BEGIN_MAP
4654: my $curRes = $iterator->next(); # for "current resource"
4655: my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
4656: while ($depth > 0) {
4657: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
4658: if($curRes == $iterator->END_MAP) { $depth--; }
4659:
4660: if (ref($curRes) && $curRes->is_problem()) {
4661: my $parts = $curRes->parts();
4662: my $title = $curRes->compTitle();
4663: my $symbx = $curRes->symb();
4664: $studentTable.=
4665: &Apache::loncommon::start_data_table_row().
4666: '<td align="center" valign="top" >'.$prob.
4667: (scalar(@{$parts}) == 1 ? ''
4668: : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
4669: .')').'</td>';
4670: $studentTable.='<td valign="top"> <b>'.$title.'</b> </td>';
4671:
4672: my %newrecord=();
4673: my @displayPts=();
4674: my %aggregate = ();
4675: my $aggregateflag = 0;
4676: foreach my $partid (@{$parts}) {
4677: my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
4678: my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
4679:
4680: my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ?
4681: $env{'form.WGT'.$question.'_'.$partid} : 1;
4682: my $partial = $newpts/$wgt;
4683: my $score;
4684: if ($partial > 0) {
4685: $score = 'correct_by_override';
4686: } elsif ($newpts ne '') { #empty is taken as 0
4687: $score = 'incorrect_by_override';
4688: }
4689: my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
4690: if ($dropMenu eq 'excused') {
4691: $partial = '';
4692: $score = 'excused';
4693: } elsif ($dropMenu eq 'reset status'
4694: && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
4695: $newrecord{'resource.'.$partid.'.tries'} = 0;
4696: $newrecord{'resource.'.$partid.'.solved'} = '';
4697: $newrecord{'resource.'.$partid.'.award'} = '';
4698: $newrecord{'resource.'.$partid.'.awarded'} = 0;
4699: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
4700: $changeflag++;
4701: $newpts = '';
4702:
4703: my $aggtries = $env{'form.aggtries'.$question.'_'.$partid};
4704: my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
4705: my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
4706: if ($aggtries > 0) {
4707: &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
4708: $aggregateflag = 1;
4709: }
4710: }
4711: my $display_part=&get_display_part($partid,$curRes->symb());
4712: my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
4713: $displayPts[0].=' <b>'.&mt('Part').':</b> '.$display_part.' = '.
4714: (($oldstatus eq 'excused') ? 'excused' : $oldpts).
4715: ' <br />';
4716: $displayPts[1].=' <b>'.&mt('Part').':</b> '.$display_part.' = '.
4717: (($score eq 'excused') ? 'excused' : $newpts).
4718: ' <br />';
4719: $question++;
4720: next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
4721:
4722: $newrecord{'resource.'.$partid.'.awarded'} = $partial if $partial ne '';
4723: $newrecord{'resource.'.$partid.'.solved'} = $score if $score ne '';
4724: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
4725: if (scalar(keys(%newrecord)) > 0);
4726:
4727: $changeflag++;
4728: }
4729: if (scalar(keys(%newrecord)) > 0) {
4730: my %record =
4731: &Apache::lonnet::restore($symbx,$env{'request.course.id'},
4732: $udom,$uname);
4733:
4734: if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
4735: $newrecord{'resource.CODE'} = $env{'form.CODE'};
4736: } elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
4737: $newrecord{'resource.CODE'} = '';
4738: }
4739: &Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
4740: $udom,$uname);
4741: %record = &Apache::lonnet::restore($symbx,
4742: $env{'request.course.id'},
4743: $udom,$uname);
4744: &check_and_remove_from_queue($parts,\%record,undef,$symbx,
4745: $cdom,$cnum,$udom,$uname);
4746: }
4747:
4748: if ($aggregateflag) {
4749: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
4750: $env{'course.'.$env{'request.course.id'}.'.domain'},
4751: $env{'course.'.$env{'request.course.id'}.'.num'});
4752: }
4753:
4754: $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
4755: '<td valign="top">'.$displayPts[1].'</td>'.
4756: &Apache::loncommon::end_data_table_row();
4757:
4758: $prob++;
4759: }
4760: $curRes = $iterator->next();
4761: }
4762:
4763: $studentTable.=&Apache::loncommon::end_data_table();
4764: my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
4765: &mt('The scores were changed for [quant,_1,problem].',
4766: $changeflag));
4767: $request->print($grademsg.$studentTable);
4768:
4769: return '';
4770: }
4771:
4772: #-------- end of section for handling grading by page/sequence ---------
4773: #
4774: #-------------------------------------------------------------------
4775:
4776: #-------------------- Bubblesheet (Scantron) Grading -------------------
4777: #
4778: #------ start of section for handling grading by page/sequence ---------
4779:
4780: =pod
4781:
4782: =head1 Bubble sheet grading routines
4783:
4784: For this documentation:
4785:
4786: 'scanline' refers to the full line of characters
4787: from the file that we are parsing that represents one entire sheet
4788:
4789: 'bubble line' refers to the data
4790: representing the line of bubbles that are on the physical bubble sheet
4791:
4792:
4793: The overall process is that a scanned in bubble sheet data is uploaded
4794: into a course. When a user wants to grade, they select a
4795: sequence/folder of resources, a file of bubble sheet info, and pick
4796: one of the predefined configurations for what each scanline looks
4797: like.
4798:
4799: Next each scanline is checked for any errors of either 'missing
4800: bubbles' (it's an error because it may have been mis-scanned
4801: because too light bubbling), 'double bubble' (each bubble line should
4802: have no more that one letter picked), invalid or duplicated CODE,
4803: invalid student/employee ID
4804:
4805: If the CODE option is used that determines the randomization of the
4806: homework problems, either way the student/employee ID is looked up into a
4807: username:domain.
4808:
4809: During the validation phase the instructor can choose to skip scanlines.
4810:
4811: After the validation phase, there are now 3 bubble sheet files
4812:
4813: scantron_original_filename (unmodified original file)
4814: scantron_corrected_filename (file where the corrected information has replaced the original information)
4815: scantron_skipped_filename (contains the exact text of scanlines that where skipped)
4816:
4817: Also there is a separate hash nohist_scantrondata that contains extra
4818: correction information that isn't representable in the bubble sheet
4819: file (see &scantron_getfile() for more information)
4820:
4821: After all scanlines are either valid, marked as valid or skipped, then
4822: foreach line foreach problem in the picked sequence, an ssi request is
4823: made that simulates a user submitting their selected letter(s) against
4824: the homework problem.
4825:
4826: =over 4
4827:
4828:
4829:
4830: =item defaultFormData
4831:
4832: Returns html hidden inputs used to hold context/default values.
4833:
4834: Arguments:
4835: $symb - $symb of the current resource
4836:
4837: =cut
4838:
4839: sub defaultFormData {
4840: my ($symb)=@_;
4841: return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
4842: }
4843:
4844:
4845: =pod
4846:
4847: =item getSequenceDropDown
4848:
4849: Return html dropdown of possible sequences to grade
4850:
4851: Arguments:
4852: $symb - $symb of the current resource
4853: $map_error - ref to scalar which will container error if
4854: $navmap object is unavailable in &getSymbMap().
4855:
4856: =cut
4857:
4858: sub getSequenceDropDown {
4859: my ($symb,$map_error)=@_;
4860: my $result='<select name="selectpage">'."\n";
4861: my ($titles,$symbx) = &getSymbMap($map_error);
4862: if (ref($map_error)) {
4863: return if ($$map_error);
4864: }
4865: my ($curpage)=&Apache::lonnet::decode_symb($symb);
4866: my $ctr=0;
4867: foreach (@$titles) {
4868: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4869: $result.='<option value="'.$$symbx{$_}.'" '.
4870: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
4871: '>'.$showtitle.'</option>'."\n";
4872: $ctr++;
4873: }
4874: $result.= '</select>';
4875: return $result;
4876: }
4877:
4878: my %bubble_lines_per_response; # no. bubble lines for each response.
4879: # key is zero-based index - 0, 1, 2 ...
4880:
4881: my %first_bubble_line; # First bubble line no. for each bubble.
4882:
4883: my %subdivided_bubble_lines; # no. bubble lines for optionresponse,
4884: # matchresponse or rankresponse, where
4885: # an individual response can have multiple
4886: # lines
4887:
4888: my %responsetype_per_response; # responsetype for each response
4889:
4890: # Save and restore the bubble lines array to the form env.
4891:
4892:
4893: sub save_bubble_lines {
4894: foreach my $line (keys(%bubble_lines_per_response)) {
4895: $env{"form.scantron.bubblelines.$line"} = $bubble_lines_per_response{$line};
4896: $env{"form.scantron.first_bubble_line.$line"} =
4897: $first_bubble_line{$line};
4898: $env{"form.scantron.sub_bubblelines.$line"} =
4899: $subdivided_bubble_lines{$line};
4900: $env{"form.scantron.responsetype.$line"} =
4901: $responsetype_per_response{$line};
4902: }
4903: }
4904:
4905:
4906: sub restore_bubble_lines {
4907: my $line = 0;
4908: %bubble_lines_per_response = ();
4909: while ($env{"form.scantron.bubblelines.$line"}) {
4910: my $value = $env{"form.scantron.bubblelines.$line"};
4911: $bubble_lines_per_response{$line} = $value;
4912: $first_bubble_line{$line} =
4913: $env{"form.scantron.first_bubble_line.$line"};
4914: $subdivided_bubble_lines{$line} =
4915: $env{"form.scantron.sub_bubblelines.$line"};
4916: $responsetype_per_response{$line} =
4917: $env{"form.scantron.responsetype.$line"};
4918: $line++;
4919: }
4920: }
4921:
4922: # Given the parsed scanline, get the response for
4923: # 'answer' number n:
4924:
4925: sub get_response_bubbles {
4926: my ($parsed_line, $response) = @_;
4927:
4928: my $bubble_line = $first_bubble_line{$response-1} +1;
4929: my $bubble_lines= $bubble_lines_per_response{$response-1};
4930:
4931: my $selected = "";
4932:
4933: for (my $bline = 0; $bline < $bubble_lines; $bline++) {
4934: $selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
4935: $bubble_line++;
4936: }
4937: return $selected;
4938: }
4939:
4940: =pod
4941:
4942: =item scantron_filenames
4943:
4944: Returns a list of the scantron files in the current course
4945:
4946: =cut
4947:
4948: sub scantron_filenames {
4949: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4950: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
4951: my $getpropath = 1;
4952: my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
4953: $getpropath);
4954: my @possiblenames;
4955: foreach my $filename (sort(@files)) {
4956: ($filename)=split(/&/,$filename);
4957: if ($filename!~/^scantron_orig_/) { next ; }
4958: $filename=~s/^scantron_orig_//;
4959: push(@possiblenames,$filename);
4960: }
4961: return @possiblenames;
4962: }
4963:
4964: =pod
4965:
4966: =item scantron_uploads
4967:
4968: Returns html drop-down list of scantron files in current course.
4969:
4970: Arguments:
4971: $file2grade - filename to set as selected in the dropdown
4972:
4973: =cut
4974:
4975: sub scantron_uploads {
4976: my ($file2grade) = @_;
4977: my $result= '<select name="scantron_selectfile">';
4978: $result.="<option></option>";
4979: foreach my $filename (sort(&scantron_filenames())) {
4980: $result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
4981: }
4982: $result.="</select>";
4983: return $result;
4984: }
4985:
4986: =pod
4987:
4988: =item scantron_scantab
4989:
4990: Returns html drop down of the scantron formats in the scantronformat.tab
4991: file.
4992:
4993: =cut
4994:
4995: sub scantron_scantab {
4996: my $result='<select name="scantron_format">'."\n";
4997: $result.='<option></option>'."\n";
4998: my @lines = &get_scantronformat_file();
4999: if (@lines > 0) {
5000: foreach my $line (@lines) {
5001: next if (($line =~ /^\#/) || ($line eq ''));
5002: my ($name,$descrip)=split(/:/,$line);
5003: $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
5004: }
5005: }
5006: $result.='</select>'."\n";
5007: return $result;
5008: }
5009:
5010: =pod
5011:
5012: =item get_scantronformat_file
5013:
5014: Returns an array containing lines from the scantron format file for
5015: the domain of the course.
5016:
5017: If a url for a custom.tab file is listed in domain's configuration.db,
5018: lines are from this file.
5019:
5020: Otherwise, if a default.tab has been published in RES space by the
5021: domainconfig user, lines are from this file.
5022:
5023: Otherwise, fall back to getting lines from the legacy file on the
5024: local server: /home/httpd/lonTabs/default_scantronformat.tab
5025:
5026: =cut
5027:
5028: sub get_scantronformat_file {
5029: my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
5030: my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
5031: my $gottab = 0;
5032: my @lines;
5033: if (ref($domconfig{'scantron'}) eq 'HASH') {
5034: if ($domconfig{'scantron'}{'scantronformat'} ne '') {
5035: my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
5036: if ($formatfile ne '-1') {
5037: @lines = split("\n",$formatfile,-1);
5038: $gottab = 1;
5039: }
5040: }
5041: }
5042: if (!$gottab) {
5043: my $confname = $cdom.'-domainconfig';
5044: my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
5045: my $formatfile = &Apache::lonnet::getfile($default);
5046: if ($formatfile ne '-1') {
5047: @lines = split("\n",$formatfile,-1);
5048: $gottab = 1;
5049: }
5050: }
5051: if (!$gottab) {
5052: my @domains = &Apache::lonnet::current_machine_domains();
5053: if (grep(/^\Q$cdom\E$/,@domains)) {
5054: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
5055: @lines = <$fh>;
5056: close($fh);
5057: } else {
5058: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
5059: @lines = <$fh>;
5060: close($fh);
5061: }
5062: }
5063: return @lines;
5064: }
5065:
5066: =pod
5067:
5068: =item scantron_CODElist
5069:
5070: Returns html drop down of the saved CODE lists from current course,
5071: generated from earlier printings.
5072:
5073: =cut
5074:
5075: sub scantron_CODElist {
5076: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5077: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5078: my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
5079: my $namechoice='<option></option>';
5080: foreach my $name (sort {uc($a) cmp uc($b)} @names) {
5081: if ($name =~ /^error: 2 /) { next; }
5082: if ($name =~ /^type\0/) { next; }
5083: $namechoice.='<option value="'.$name.'">'.$name.'</option>';
5084: }
5085: $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
5086: return $namechoice;
5087: }
5088:
5089: =pod
5090:
5091: =item scantron_CODEunique
5092:
5093: Returns the html for "Each CODE to be used once" radio.
5094:
5095: =cut
5096:
5097: sub scantron_CODEunique {
5098: my $result='<span class="LC_nobreak">
5099: <label><input type="radio" name="scantron_CODEunique"
5100: value="yes" checked="checked" />'.&mt('Yes').' </label>
5101: </span>
5102: <span class="LC_nobreak">
5103: <label><input type="radio" name="scantron_CODEunique"
5104: value="no" />'.&mt('No').' </label>
5105: </span>';
5106: return $result;
5107: }
5108:
5109: =pod
5110:
5111: =item scantron_selectphase
5112:
5113: Generates the initial screen to start the bubble sheet process.
5114: Allows for - starting a grading run.
5115: - downloading existing scan data (original, corrected
5116: or skipped info)
5117:
5118: - uploading new scan data
5119:
5120: Arguments:
5121: $r - The Apache request object
5122: $file2grade - name of the file that contain the scanned data to score
5123:
5124: =cut
5125:
5126: sub scantron_selectphase {
5127: my ($r,$file2grade,$symb) = @_;
5128: if (!$symb) {return '';}
5129: my $map_error;
5130: my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
5131: if ($map_error) {
5132: $r->print('<br />'.&navmap_errormsg().'<br />');
5133: return;
5134: }
5135: my $default_form_data=&defaultFormData($symb);
5136: my $file_selector=&scantron_uploads($file2grade);
5137: my $format_selector=&scantron_scantab();
5138: my $CODE_selector=&scantron_CODElist();
5139: my $CODE_unique=&scantron_CODEunique();
5140: my $result;
5141:
5142: $ssi_error = 0;
5143:
5144: if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
5145: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
5146:
5147: # Chunk of form to prompt for a scantron file upload.
5148:
5149: $r->print('
5150: <br />
5151: '.&Apache::loncommon::start_data_table('LC_scantron_action').'
5152: '.&Apache::loncommon::start_data_table_header_row().'
5153: <th>
5154: '.&mt('Specify a bubblesheet data file to upload.').'
5155: </th>
5156: '.&Apache::loncommon::end_data_table_header_row().'
5157: '.&Apache::loncommon::start_data_table_row().'
5158: <td>
5159: ');
5160: my $default_form_data=&defaultFormData($symb);
5161: my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
5162: my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
5163: $r->print(&Apache::lonhtmlcommon::scripttag('
5164: function checkUpload(formname) {
5165: if (formname.upfile.value == "") {
5166: alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
5167: return false;
5168: }
5169: formname.submit();
5170: }'));
5171: $r->print('
5172: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
5173: '.$default_form_data.'
5174: <input name="courseid" type="hidden" value="'.$cnum.'" />
5175: <input name="domainid" type="hidden" value="'.$cdom.'" />
5176: <input name="command" value="scantronupload_save" type="hidden" />
5177: '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
5178: <br />
5179: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
5180: </form>
5181: ');
5182:
5183: $r->print('
5184: </td>
5185: '.&Apache::loncommon::end_data_table_row().'
5186: '.&Apache::loncommon::end_data_table().'
5187: ');
5188: }
5189:
5190: # Chunk of form to prompt for a file to grade and how:
5191:
5192: $result.= '
5193: <br />
5194: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
5195: <input type="hidden" name="command" value="scantron_warning" />
5196: '.$default_form_data.'
5197: '.&Apache::loncommon::start_data_table('LC_scantron_action').'
5198: '.&Apache::loncommon::start_data_table_header_row().'
5199: <th colspan="2">
5200: '.&mt('Specify file and which Folder/Sequence to grade').'
5201: </th>
5202: '.&Apache::loncommon::end_data_table_header_row().'
5203: '.&Apache::loncommon::start_data_table_row().'
5204: <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
5205: '.&Apache::loncommon::end_data_table_row().'
5206: '.&Apache::loncommon::start_data_table_row().'
5207: <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
5208: '.&Apache::loncommon::end_data_table_row().'
5209: '.&Apache::loncommon::start_data_table_row().'
5210: <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
5211: '.&Apache::loncommon::end_data_table_row().'
5212: '.&Apache::loncommon::start_data_table_row().'
5213: <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
5214: '.&Apache::loncommon::end_data_table_row().'
5215: '.&Apache::loncommon::start_data_table_row().'
5216: <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
5217: '.&Apache::loncommon::end_data_table_row().'
5218: '.&Apache::loncommon::start_data_table_row().'
5219: <td> '.&mt('Options:').' </td>
5220: <td>
5221: <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
5222: <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
5223: <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
5224: </td>
5225: '.&Apache::loncommon::end_data_table_row().'
5226: '.&Apache::loncommon::start_data_table_row().'
5227: <td colspan="2">
5228: <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
5229: </td>
5230: '.&Apache::loncommon::end_data_table_row().'
5231: '.&Apache::loncommon::end_data_table().'
5232: </form>
5233: ';
5234:
5235: $r->print($result);
5236:
5237:
5238:
5239: # Chunk of the form that prompts to view a scoring office file,
5240: # corrected file, skipped records in a file.
5241:
5242: $r->print('
5243: <br />
5244: <form action="/adm/grades" name="scantron_download">
5245: '.$default_form_data.'
5246: <input type="hidden" name="command" value="scantron_download" />
5247: '.&Apache::loncommon::start_data_table('LC_scantron_action').'
5248: '.&Apache::loncommon::start_data_table_header_row().'
5249: <th>
5250: '.&mt('Download a scoring office file').'
5251: </th>
5252: '.&Apache::loncommon::end_data_table_header_row().'
5253: '.&Apache::loncommon::start_data_table_row().'
5254: <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).'
5255: <br />
5256: <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
5257: '.&Apache::loncommon::end_data_table_row().'
5258: '.&Apache::loncommon::end_data_table().'
5259: </form>
5260: <br />
5261: ');
5262:
5263: &Apache::lonpickcode::code_list($r,2);
5264:
5265: $r->print('<br /><form method="post" name="checkscantron">'.
5266: $default_form_data."\n".
5267: &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
5268: &Apache::loncommon::start_data_table_header_row()."\n".
5269: '<th colspan="2">
5270: '.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
5271: '</th>'."\n".
5272: &Apache::loncommon::end_data_table_header_row()."\n".
5273: &Apache::loncommon::start_data_table_row()."\n".
5274: '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
5275: '<td> '.$sequence_selector.' </td>'.
5276: &Apache::loncommon::end_data_table_row()."\n".
5277: &Apache::loncommon::start_data_table_row()."\n".
5278: '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
5279: '<td> '.$file_selector.' </td>'."\n".
5280: &Apache::loncommon::end_data_table_row()."\n".
5281: &Apache::loncommon::start_data_table_row()."\n".
5282: '<td> '.&mt('Format of data file:').' </td>'."\n".
5283: '<td> '.$format_selector.' </td>'."\n".
5284: &Apache::loncommon::end_data_table_row()."\n".
5285: &Apache::loncommon::start_data_table_row()."\n".
5286: '<td> '.&mt('Options').' </td>'."\n".
5287: '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
5288: &Apache::loncommon::end_data_table_row()."\n".
5289: &Apache::loncommon::start_data_table_row()."\n".
5290: '<td colspan="2">'."\n".
5291: '<input type="hidden" name="command" value="checksubmissions" />'."\n".
5292: '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
5293: '</td>'."\n".
5294: &Apache::loncommon::end_data_table_row()."\n".
5295: &Apache::loncommon::end_data_table()."\n".
5296: '</form><br />');
5297: return;
5298: }
5299:
5300: =pod
5301:
5302: =item get_scantron_config
5303:
5304: Parse and return the scantron configuration line selected as a
5305: hash of configuration file fields.
5306:
5307: Arguments:
5308: which - the name of the configuration to parse from the file.
5309:
5310:
5311: Returns:
5312: If the named configuration is not in the file, an empty
5313: hash is returned.
5314: a hash with the fields
5315: name - internal name for the this configuration setup
5316: description - text to display to operator that describes this config
5317: CODElocation - if 0 or the string 'none'
5318: - no CODE exists for this config
5319: if -1 || the string 'letter'
5320: - a CODE exists for this config and is
5321: a string of letters
5322: Unsupported value (but planned for future support)
5323: if a positive integer
5324: - The CODE exists as the first n items from
5325: the question section of the form
5326: if the string 'number'
5327: - The CODE exists for this config and is
5328: a string of numbers
5329: CODEstart - (only matter if a CODE exists) column in the line where
5330: the CODE starts
5331: CODElength - length of the CODE
5332: IDstart - column where the student/employee ID starts
5333: IDlength - length of the student/employee ID info
5334: Qstart - column where the information from the bubbled
5335: 'questions' start
5336: Qlength - number of columns comprising a single bubble line from
5337: the sheet. (usually either 1 or 10)
5338: Qon - either a single character representing the character used
5339: to signal a bubble was chosen in the positional setup, or
5340: the string 'letter' if the letter of the chosen bubble is
5341: in the final, or 'number' if a number representing the
5342: chosen bubble is in the file (1->A 0->J)
5343: Qoff - the character used to represent that a bubble was
5344: left blank
5345: PaperID - if the scanning process generates a unique number for each
5346: sheet scanned the column that this ID number starts in
5347: PaperIDlength - number of columns that comprise the unique ID number
5348: for the sheet of paper
5349: FirstName - column that the first name starts in
5350: FirstNameLength - number of columns that the first name spans
5351:
5352: LastName - column that the last name starts in
5353: LastNameLength - number of columns that the last name spans
5354:
5355: =cut
5356:
5357: sub get_scantron_config {
5358: my ($which) = @_;
5359: my @lines = &get_scantronformat_file();
5360: my %config;
5361: #FIXME probably should move to XML it has already gotten a bit much now
5362: foreach my $line (@lines) {
5363: my ($name,$descrip)=split(/:/,$line);
5364: if ($name ne $which ) { next; }
5365: chomp($line);
5366: my @config=split(/:/,$line);
5367: $config{'name'}=$config[0];
5368: $config{'description'}=$config[1];
5369: $config{'CODElocation'}=$config[2];
5370: $config{'CODEstart'}=$config[3];
5371: $config{'CODElength'}=$config[4];
5372: $config{'IDstart'}=$config[5];
5373: $config{'IDlength'}=$config[6];
5374: $config{'Qstart'}=$config[7];
5375: $config{'Qlength'}=$config[8];
5376: $config{'Qoff'}=$config[9];
5377: $config{'Qon'}=$config[10];
5378: $config{'PaperID'}=$config[11];
5379: $config{'PaperIDlength'}=$config[12];
5380: $config{'FirstName'}=$config[13];
5381: $config{'FirstNamelength'}=$config[14];
5382: $config{'LastName'}=$config[15];
5383: $config{'LastNamelength'}=$config[16];
5384: last;
5385: }
5386: return %config;
5387: }
5388:
5389: =pod
5390:
5391: =item username_to_idmap
5392:
5393: creates a hash keyed by student/employee ID with values of the corresponding
5394: student username:domain.
5395:
5396: Arguments:
5397:
5398: $classlist - reference to the class list hash. This is a hash
5399: keyed by student name:domain whose elements are references
5400: to arrays containing various chunks of information
5401: about the student. (See loncoursedata for more info).
5402:
5403: Returns
5404: %idmap - the constructed hash
5405:
5406: =cut
5407:
5408: sub username_to_idmap {
5409: my ($classlist)= @_;
5410: my %idmap;
5411: foreach my $student (keys(%$classlist)) {
5412: $idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
5413: $student;
5414: }
5415: return %idmap;
5416: }
5417:
5418: =pod
5419:
5420: =item scantron_fixup_scanline
5421:
5422: Process a requested correction to a scanline.
5423:
5424: Arguments:
5425: $scantron_config - hash from &get_scantron_config()
5426: $scan_data - hash of correction information
5427: (see &scantron_getfile())
5428: $line - existing scanline
5429: $whichline - line number of the passed in scanline
5430: $field - type of change to process
5431: (either
5432: 'ID' -> correct the student/employee ID
5433: 'CODE' -> correct the CODE
5434: 'answer' -> fixup the submitted answers)
5435:
5436: $args - hash of additional info,
5437: - 'ID'
5438: 'newid' -> studentID to use in replacement
5439: of existing one
5440: - 'CODE'
5441: 'CODE_ignore_dup' - set to true if duplicates
5442: should be ignored.
5443: 'CODE' - is new code or 'use_unfound'
5444: if the existing unfound code should
5445: be used as is
5446: - 'answer'
5447: 'response' - new answer or 'none' if blank
5448: 'question' - the bubble line to change
5449: 'questionnum' - the question identifier,
5450: may include subquestion.
5451:
5452: Returns:
5453: $line - the modified scanline
5454:
5455: Side effects:
5456: $scan_data - may be updated
5457:
5458: =cut
5459:
5460:
5461: sub scantron_fixup_scanline {
5462: my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
5463: if ($field eq 'ID') {
5464: if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
5465: return ($line,1,'New value too large');
5466: }
5467: if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
5468: $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
5469: $args->{'newid'});
5470: }
5471: substr($line,$$scantron_config{'IDstart'}-1,
5472: $$scantron_config{'IDlength'})=$args->{'newid'};
5473: if ($args->{'newid'}=~/^\s*$/) {
5474: &scan_data($scan_data,"$whichline.user",
5475: $args->{'username'}.':'.$args->{'domain'});
5476: }
5477: } elsif ($field eq 'CODE') {
5478: if ($args->{'CODE_ignore_dup'}) {
5479: &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
5480: }
5481: &scan_data($scan_data,"$whichline.useCODE",'1');
5482: if ($args->{'CODE'} ne 'use_unfound') {
5483: if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
5484: return ($line,1,'New CODE value too large');
5485: }
5486: if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
5487: $args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
5488: }
5489: substr($line,$$scantron_config{'CODEstart'}-1,
5490: $$scantron_config{'CODElength'})=$args->{'CODE'};
5491: }
5492: } elsif ($field eq 'answer') {
5493: my $length=$scantron_config->{'Qlength'};
5494: my $off=$scantron_config->{'Qoff'};
5495: my $on=$scantron_config->{'Qon'};
5496: my $answer=${off}x$length;
5497: if ($args->{'response'} eq 'none') {
5498: &scan_data($scan_data,
5499: "$whichline.no_bubble.".$args->{'questionnum'},'1');
5500: } else {
5501: if ($on eq 'letter') {
5502: my @alphabet=('A'..'Z');
5503: $answer=$alphabet[$args->{'response'}];
5504: } elsif ($on eq 'number') {
5505: $answer=$args->{'response'}+1;
5506: if ($answer == 10) { $answer = '0'; }
5507: } else {
5508: substr($answer,$args->{'response'},1)=$on;
5509: }
5510: &scan_data($scan_data,
5511: "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
5512: }
5513: my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
5514: substr($line,$where-1,$length)=$answer;
5515: }
5516: return $line;
5517: }
5518:
5519: =pod
5520:
5521: =item scan_data
5522:
5523: Edit or look up an item in the scan_data hash.
5524:
5525: Arguments:
5526: $scan_data - The hash (see scantron_getfile)
5527: $key - shorthand of the key to edit (actual key is
5528: scantronfilename_key).
5529: $data - New value of the hash entry.
5530: $delete - If true, the entry is removed from the hash.
5531:
5532: Returns:
5533: The new value of the hash table field (undefined if deleted).
5534:
5535: =cut
5536:
5537:
5538: sub scan_data {
5539: my ($scan_data,$key,$value,$delete)=@_;
5540: my $filename=$env{'form.scantron_selectfile'};
5541: if (defined($value)) {
5542: $scan_data->{$filename.'_'.$key} = $value;
5543: }
5544: if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
5545: return $scan_data->{$filename.'_'.$key};
5546: }
5547:
5548: # ----- These first few routines are general use routines.----
5549:
5550: # Return the number of occurences of a pattern in a string.
5551:
5552: sub occurence_count {
5553: my ($string, $pattern) = @_;
5554:
5555: my @matches = ($string =~ /$pattern/g);
5556:
5557: return scalar(@matches);
5558: }
5559:
5560:
5561: # Take a string known to have digits and convert all the
5562: # digits into letters in the range J,A..I.
5563:
5564: sub digits_to_letters {
5565: my ($input) = @_;
5566:
5567: my @alphabet = ('J', 'A'..'I');
5568:
5569: my @input = split(//, $input);
5570: my $output ='';
5571: for (my $i = 0; $i < scalar(@input); $i++) {
5572: if ($input[$i] =~ /\d/) {
5573: $output .= $alphabet[$input[$i]];
5574: } else {
5575: $output .= $input[$i];
5576: }
5577: }
5578: return $output;
5579: }
5580:
5581: =pod
5582:
5583: =item scantron_parse_scanline
5584:
5585: Decodes a scanline from the selected scantron file
5586:
5587: Arguments:
5588: line - The text of the scantron file line to process
5589: whichline - Line number
5590: scantron_config - Hash describing the format of the scantron lines.
5591: scan_data - Hash of extra information about the scanline
5592: (see scantron_getfile for more information)
5593: just_header - True if should not process question answers but only
5594: the stuff to the left of the answers.
5595: Returns:
5596: Hash containing the result of parsing the scanline
5597:
5598: Keys are all proceeded by the string 'scantron.'
5599:
5600: CODE - the CODE in use for this scanline
5601: useCODE - 1 if the CODE is invalid but it usage has been forced
5602: by the operator
5603: CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
5604: CODEs were selected, but the usage has been
5605: forced by the operator
5606: ID - student/employee ID
5607: PaperID - if used, the ID number printed on the sheet when the
5608: paper was scanned
5609: FirstName - first name from the sheet
5610: LastName - last name from the sheet
5611:
5612: if just_header was not true these key may also exist
5613:
5614: missingerror - a list of bubble ranges that are considered to be answers
5615: to a single question that don't have any bubbles filled in.
5616: Of the form questionnumber:firstbubblenumber:count.
5617: doubleerror - a list of bubble ranges that are considered to be answers
5618: to a single question that have more than one bubble filled in.
5619: Of the form questionnumber::firstbubblenumber:count
5620:
5621: In the above, count is the number of bubble responses in the
5622: input line needed to represent the possible answers to the question.
5623: e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
5624: per line would have count = 2.
5625:
5626: maxquest - the number of the last bubble line that was parsed
5627:
5628: (<number> starts at 1)
5629: <number>.answer - zero or more letters representing the selected
5630: letters from the scanline for the bubble line
5631: <number>.
5632: if blank there was either no bubble or there where
5633: multiple bubbles, (consult the keys missingerror and
5634: doubleerror if this is an error condition)
5635:
5636: =cut
5637:
5638: sub scantron_parse_scanline {
5639: my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
5640:
5641: my %record;
5642: my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
5643: my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos); # Answers
5644: my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # earlier stuff
5645: if (!($$scantron_config{'CODElocation'} eq 0 ||
5646: $$scantron_config{'CODElocation'} eq 'none')) {
5647: if ($$scantron_config{'CODElocation'} < 0 ||
5648: $$scantron_config{'CODElocation'} eq 'letter' ||
5649: $$scantron_config{'CODElocation'} eq 'number') {
5650: $record{'scantron.CODE'}=substr($data,
5651: $$scantron_config{'CODEstart'}-1,
5652: $$scantron_config{'CODElength'});
5653: if (&scan_data($scan_data,"$whichline.useCODE")) {
5654: $record{'scantron.useCODE'}=1;
5655: }
5656: if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
5657: $record{'scantron.CODE_ignore_dup'}=1;
5658: }
5659: } else {
5660: #FIXME interpret first N questions
5661: }
5662: }
5663: $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
5664: $$scantron_config{'IDlength'});
5665: $record{'scantron.PaperID'}=
5666: substr($data,$$scantron_config{'PaperID'}-1,
5667: $$scantron_config{'PaperIDlength'});
5668: $record{'scantron.FirstName'}=
5669: substr($data,$$scantron_config{'FirstName'}-1,
5670: $$scantron_config{'FirstNamelength'});
5671: $record{'scantron.LastName'}=
5672: substr($data,$$scantron_config{'LastName'}-1,
5673: $$scantron_config{'LastNamelength'});
5674: if ($just_header) { return \%record; }
5675:
5676: my @alphabet=('A'..'Z');
5677: my $questnum=0;
5678: my $ansnum =1; # Multiple 'answer lines'/question.
5679:
5680: chomp($questions); # Get rid of any trailing \n.
5681: $questions =~ s/\r$//; # Get rid of trailing \r too (MAC or Win uploads).
5682: while (length($questions)) {
5683: my $answers_needed = $bubble_lines_per_response{$questnum};
5684: my $answer_length = ($$scantron_config{'Qlength'} * $answers_needed)
5685: || 1;
5686: $questnum++;
5687: my $quest_id = $questnum;
5688: my $currentquest = substr($questions,0,$answer_length);
5689: $questions = substr($questions,$answer_length);
5690: if (length($currentquest) < $answer_length) { next; }
5691:
5692: if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
5693: my $subquestnum = 1;
5694: my $subquestions = $currentquest;
5695: my @subanswers_needed =
5696: split(/,/,$subdivided_bubble_lines{$questnum-1});
5697: foreach my $subans (@subanswers_needed) {
5698: my $subans_length =
5699: ($$scantron_config{'Qlength'} * $subans) || 1;
5700: my $currsubquest = substr($subquestions,0,$subans_length);
5701: $subquestions = substr($subquestions,$subans_length);
5702: $quest_id = "$questnum.$subquestnum";
5703: if (($$scantron_config{'Qon'} eq 'letter') ||
5704: ($$scantron_config{'Qon'} eq 'number')) {
5705: $ansnum = &scantron_validator_lettnum($ansnum,
5706: $questnum,$quest_id,$subans,$currsubquest,$whichline,
5707: \@alphabet,\%record,$scantron_config,$scan_data);
5708: } else {
5709: $ansnum = &scantron_validator_positional($ansnum,
5710: $questnum,$quest_id,$subans,$currsubquest,$whichline, \@alphabet,\%record,$scantron_config,$scan_data);
5711: }
5712: $subquestnum ++;
5713: }
5714: } else {
5715: if (($$scantron_config{'Qon'} eq 'letter') ||
5716: ($$scantron_config{'Qon'} eq 'number')) {
5717: $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
5718: $quest_id,$answers_needed,$currentquest,$whichline,
5719: \@alphabet,\%record,$scantron_config,$scan_data);
5720: } else {
5721: $ansnum = &scantron_validator_positional($ansnum,$questnum,
5722: $quest_id,$answers_needed,$currentquest,$whichline,
5723: \@alphabet,\%record,$scantron_config,$scan_data);
5724: }
5725: }
5726: }
5727: $record{'scantron.maxquest'}=$questnum;
5728: return \%record;
5729: }
5730:
5731: sub scantron_validator_lettnum {
5732: my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
5733: $alphabet,$record,$scantron_config,$scan_data) = @_;
5734:
5735: # Qon 'letter' implies for each slot in currquest we have:
5736: # ? or * for doubles, a letter in A-Z for a bubble, and
5737: # about anything else (esp. a value of Qoff) for missing
5738: # bubbles.
5739: #
5740: # Qon 'number' implies each slot gives a digit that indexes the
5741: # bubbles filled, or Qoff, or a non-number for unbubbled lines,
5742: # and * or ? for double bubbles on a single line.
5743: #
5744:
5745: my $matchon;
5746: if ($$scantron_config{'Qon'} eq 'letter') {
5747: $matchon = '[A-Z]';
5748: } elsif ($$scantron_config{'Qon'} eq 'number') {
5749: $matchon = '\d';
5750: }
5751: my $occurrences = 0;
5752: if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
5753: ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
5754: ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
5755: ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
5756: ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
5757: ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
5758: my @singlelines = split('',$currquest);
5759: foreach my $entry (@singlelines) {
5760: $occurrences = &occurence_count($entry,$matchon);
5761: if ($occurrences > 1) {
5762: last;
5763: }
5764: }
5765: } else {
5766: $occurrences = &occurence_count($currquest,$matchon);
5767: }
5768: if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
5769: push(@{$record->{'scantron.doubleerror'}},$quest_id);
5770: for (my $ans=0; $ans<$answers_needed; $ans++) {
5771: my $bubble = substr($currquest,$ans,1);
5772: if ($bubble =~ /$matchon/ ) {
5773: if ($$scantron_config{'Qon'} eq 'number') {
5774: if ($bubble == 0) {
5775: $bubble = 10;
5776: }
5777: $record->{"scantron.$ansnum.answer"} =
5778: $alphabet->[$bubble-1];
5779: } else {
5780: $record->{"scantron.$ansnum.answer"} = $bubble;
5781: }
5782: } else {
5783: $record->{"scantron.$ansnum.answer"}='';
5784: }
5785: $ansnum++;
5786: }
5787: } elsif (!defined($currquest)
5788: || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
5789: || (&occurence_count($currquest,$matchon) == 0)) {
5790: for (my $ans=0; $ans<$answers_needed; $ans++ ) {
5791: $record->{"scantron.$ansnum.answer"}='';
5792: $ansnum++;
5793: }
5794: if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
5795: push(@{$record->{'scantron.missingerror'}},$quest_id);
5796: }
5797: } else {
5798: if ($$scantron_config{'Qon'} eq 'number') {
5799: $currquest = &digits_to_letters($currquest);
5800: }
5801: for (my $ans=0; $ans<$answers_needed; $ans++) {
5802: my $bubble = substr($currquest,$ans,1);
5803: $record->{"scantron.$ansnum.answer"} = $bubble;
5804: $ansnum++;
5805: }
5806: }
5807: return $ansnum;
5808: }
5809:
5810: sub scantron_validator_positional {
5811: my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
5812: $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
5813:
5814: # Otherwise there's a positional notation;
5815: # each bubble line requires Qlength items, and there are filled in
5816: # bubbles for each case where there 'Qon' characters.
5817: #
5818:
5819: my @array=split($$scantron_config{'Qon'},$currquest,-1);
5820:
5821: # If the split only gives us one element.. the full length of the
5822: # answer string, no bubbles are filled in:
5823:
5824: if ($answers_needed eq '') {
5825: return;
5826: }
5827:
5828: if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
5829: for (my $ans=0; $ans<$answers_needed; $ans++ ) {
5830: $record->{"scantron.$ansnum.answer"}='';
5831: $ansnum++;
5832: }
5833: if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
5834: push(@{$record->{"scantron.missingerror"}},$quest_id);
5835: }
5836: } elsif (scalar(@array) == 2) {
5837: my $location = length($array[0]);
5838: my $line_num = int($location / $$scantron_config{'Qlength'});
5839: my $bubble = $alphabet->[$location % $$scantron_config{'Qlength'}];
5840: for (my $ans=0; $ans<$answers_needed; $ans++) {
5841: if ($ans eq $line_num) {
5842: $record->{"scantron.$ansnum.answer"} = $bubble;
5843: } else {
5844: $record->{"scantron.$ansnum.answer"} = ' ';
5845: }
5846: $ansnum++;
5847: }
5848: } else {
5849: # If there's more than one instance of a bubble character
5850: # That's a double bubble; with positional notation we can
5851: # record all the bubbles filled in as well as the
5852: # fact this response consists of multiple bubbles.
5853: #
5854: if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
5855: ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
5856: ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
5857: ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
5858: ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
5859: ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
5860: my $doubleerror = 0;
5861: while (($currquest >= $$scantron_config{'Qlength'}) &&
5862: (!$doubleerror)) {
5863: my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
5864: $currquest = substr($currquest,$$scantron_config{'Qlength'});
5865: my @currarray = split($$scantron_config{'Qon'},$currline,-1);
5866: if (length(@currarray) > 2) {
5867: $doubleerror = 1;
5868: }
5869: }
5870: if ($doubleerror) {
5871: push(@{$record->{'scantron.doubleerror'}},$quest_id);
5872: }
5873: } else {
5874: push(@{$record->{'scantron.doubleerror'}},$quest_id);
5875: }
5876: my $item = $ansnum;
5877: for (my $ans=0; $ans<$answers_needed; $ans++) {
5878: $record->{"scantron.$item.answer"} = '';
5879: $item ++;
5880: }
5881:
5882: my @ans=@array;
5883: my $i=0;
5884: my $increment = 0;
5885: while ($#ans) {
5886: $i+=length($ans[0]) + $increment;
5887: my $line = int($i/$$scantron_config{'Qlength'} + $ansnum);
5888: my $bubble = $i%$$scantron_config{'Qlength'};
5889: $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
5890: shift(@ans);
5891: $increment = 1;
5892: }
5893: $ansnum += $answers_needed;
5894: }
5895: return $ansnum;
5896: }
5897:
5898: =pod
5899:
5900: =item scantron_add_delay
5901:
5902: Adds an error message that occurred during the grading phase to a
5903: queue of messages to be shown after grading pass is complete
5904:
5905: Arguments:
5906: $delayqueue - arrary ref of hash ref of error messages
5907: $scanline - the scanline that caused the error
5908: $errormesage - the error message
5909: $errorcode - a numeric code for the error
5910:
5911: Side Effects:
5912: updates the $delayqueue to have a new hash ref of the error
5913:
5914: =cut
5915:
5916: sub scantron_add_delay {
5917: my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
5918: push(@$delayqueue,
5919: {'line' => $scanline, 'emsg' => $errormessage,
5920: 'ecode' => $errorcode }
5921: );
5922: }
5923:
5924: =pod
5925:
5926: =item scantron_find_student
5927:
5928: Finds the username for the current scanline
5929:
5930: Arguments:
5931: $scantron_record - hash result from scantron_parse_scanline
5932: $scan_data - hash of correction information
5933: (see &scantron_getfile() form more information)
5934: $idmap - hash from &username_to_idmap()
5935: $line - number of current scanline
5936:
5937: Returns:
5938: Either 'username:domain' or undef if unknown
5939:
5940: =cut
5941:
5942: sub scantron_find_student {
5943: my ($scantron_record,$scan_data,$idmap,$line)=@_;
5944: my $scanID=$$scantron_record{'scantron.ID'};
5945: if ($scanID =~ /^\s*$/) {
5946: return &scan_data($scan_data,"$line.user");
5947: }
5948: foreach my $id (keys(%$idmap)) {
5949: if (lc($id) eq lc($scanID)) {
5950: return $$idmap{$id};
5951: }
5952: }
5953: return undef;
5954: }
5955:
5956: =pod
5957:
5958: =item scantron_filter
5959:
5960: Filter sub for lonnavmaps, filters out hidden resources if ignore
5961: hidden resources was selected
5962:
5963: =cut
5964:
5965: sub scantron_filter {
5966: my ($curres)=@_;
5967:
5968: if (ref($curres) && $curres->is_problem()) {
5969: # if the user has asked to not have either hidden
5970: # or 'randomout' controlled resources to be graded
5971: # don't include them
5972: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
5973: && $curres->randomout) {
5974: return 0;
5975: }
5976: return 1;
5977: }
5978: return 0;
5979: }
5980:
5981: =pod
5982:
5983: =item scantron_process_corrections
5984:
5985: Gets correction information out of submitted form data and corrects
5986: the scanline
5987:
5988: =cut
5989:
5990: sub scantron_process_corrections {
5991: my ($r) = @_;
5992: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
5993: my ($scanlines,$scan_data)=&scantron_getfile();
5994: my $classlist=&Apache::loncoursedata::get_classlist();
5995: my $which=$env{'form.scantron_line'};
5996: my $line=&scantron_get_line($scanlines,$scan_data,$which);
5997: my ($skip,$err,$errmsg);
5998: if ($env{'form.scantron_skip_record'}) {
5999: $skip=1;
6000: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
6001: my $newstudent=$env{'form.scantron_username'}.':'.
6002: $env{'form.scantron_domain'};
6003: my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
6004: ($line,$err,$errmsg)=
6005: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
6006: 'ID',{'newid'=>$newid,
6007: 'username'=>$env{'form.scantron_username'},
6008: 'domain'=>$env{'form.scantron_domain'}});
6009: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
6010: my $resolution=$env{'form.scantron_CODE_resolution'};
6011: my $newCODE;
6012: my %args;
6013: if ($resolution eq 'use_unfound') {
6014: $newCODE='use_unfound';
6015: } elsif ($resolution eq 'use_found') {
6016: $newCODE=$env{'form.scantron_CODE_selectedvalue'};
6017: } elsif ($resolution eq 'use_typed') {
6018: $newCODE=$env{'form.scantron_CODE_newvalue'};
6019: } elsif ($resolution =~ /^use_closest_(\d+)/) {
6020: $newCODE=$env{"form.scantron_CODE_closest_$1"};
6021: }
6022: if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
6023: $args{'CODE_ignore_dup'}=1;
6024: }
6025: $args{'CODE'}=$newCODE;
6026: ($line,$err,$errmsg)=
6027: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
6028: 'CODE',\%args);
6029: } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
6030: foreach my $question (split(',',$env{'form.scantron_questions'})) {
6031: ($line,$err,$errmsg)=
6032: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
6033: $which,'answer',
6034: { 'question'=>$question,
6035: 'response'=>$env{"form.scantron_correct_Q_$question"},
6036: 'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
6037: if ($err) { last; }
6038: }
6039: }
6040: if ($err) {
6041: $r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
6042: } else {
6043: &scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
6044: &scantron_putfile($scanlines,$scan_data);
6045: }
6046: }
6047:
6048: =pod
6049:
6050: =item reset_skipping_status
6051:
6052: Forgets the current set of remember skipped scanlines (and thus
6053: reverts back to considering all lines in the
6054: scantron_skipped_<filename> file)
6055:
6056: =cut
6057:
6058: sub reset_skipping_status {
6059: my ($scanlines,$scan_data)=&scantron_getfile();
6060: &scan_data($scan_data,'remember_skipping',undef,1);
6061: &scantron_putfile(undef,$scan_data);
6062: }
6063:
6064: =pod
6065:
6066: =item start_skipping
6067:
6068: Marks a scanline to be skipped.
6069:
6070: =cut
6071:
6072: sub start_skipping {
6073: my ($scan_data,$i)=@_;
6074: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
6075: if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
6076: $remembered{$i}=2;
6077: } else {
6078: $remembered{$i}=1;
6079: }
6080: &scan_data($scan_data,'remember_skipping',join(':',%remembered));
6081: }
6082:
6083: =pod
6084:
6085: =item should_be_skipped
6086:
6087: Checks whether a scanline should be skipped.
6088:
6089: =cut
6090:
6091: sub should_be_skipped {
6092: my ($scanlines,$scan_data,$i)=@_;
6093: if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
6094: # not redoing old skips
6095: if ($scanlines->{'skipped'}[$i]) { return 1; }
6096: return 0;
6097: }
6098: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
6099:
6100: if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
6101: return 0;
6102: }
6103: return 1;
6104: }
6105:
6106: =pod
6107:
6108: =item remember_current_skipped
6109:
6110: Discovers what scanlines are in the scantron_skipped_<filename>
6111: file and remembers them into scan_data for later use.
6112:
6113: =cut
6114:
6115: sub remember_current_skipped {
6116: my ($scanlines,$scan_data)=&scantron_getfile();
6117: my %to_remember;
6118: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6119: if ($scanlines->{'skipped'}[$i]) {
6120: $to_remember{$i}=1;
6121: }
6122: }
6123:
6124: &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
6125: &scantron_putfile(undef,$scan_data);
6126: }
6127:
6128: =pod
6129:
6130: =item check_for_error
6131:
6132: Checks if there was an error when attempting to remove a specific
6133: scantron_.. bubble sheet data file. Prints out an error if
6134: something went wrong.
6135:
6136: =cut
6137:
6138: sub check_for_error {
6139: my ($r,$result)=@_;
6140: if ($result ne 'ok' && $result ne 'not_found' ) {
6141: $r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
6142: }
6143: }
6144:
6145: =pod
6146:
6147: =item scantron_warning_screen
6148:
6149: Interstitial screen to make sure the operator has selected the
6150: correct options before we start the validation phase.
6151:
6152: =cut
6153:
6154: sub scantron_warning_screen {
6155: my ($button_text)=@_;
6156: my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
6157: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6158: my $CODElist;
6159: if ($scantron_config{'CODElocation'} &&
6160: $scantron_config{'CODEstart'} &&
6161: $scantron_config{'CODElength'}) {
6162: $CODElist=$env{'form.scantron_CODElist'};
6163: if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
6164: $CODElist=
6165: '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
6166: $env{'form.scantron_CODElist'}.'</tt></td></tr>';
6167: }
6168: return ('
6169: <p>
6170: <span class="LC_warning">
6171: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
6172: </p>
6173: <table>
6174: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
6175: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
6176: '.$CODElist.'
6177: </table>
6178: <br />
6179: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
6180: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
6181:
6182: <br />
6183: ');
6184: }
6185:
6186: =pod
6187:
6188: =item scantron_do_warning
6189:
6190: Check if the operator has picked something for all required
6191: fields. Error out if something is missing.
6192:
6193: =cut
6194:
6195: sub scantron_do_warning {
6196: my ($r,$symb)=@_;
6197: if (!$symb) {return '';}
6198: my $default_form_data=&defaultFormData($symb);
6199: $r->print(&scantron_form_start().$default_form_data);
6200: if ( $env{'form.selectpage'} eq '' ||
6201: $env{'form.scantron_selectfile'} eq '' ||
6202: $env{'form.scantron_format'} eq '' ) {
6203: $r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
6204: if ( $env{'form.selectpage'} eq '') {
6205: $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
6206: }
6207: if ( $env{'form.scantron_selectfile'} eq '') {
6208: $r->print('<p><span class="LC_error">'.&mt('You have not selected a file that contains the student\'s response data.').'</span></p>');
6209: }
6210: if ( $env{'form.scantron_format'} eq '') {
6211: $r->print('<p><span class="LC_error">'.&mt('You have not selected a the format of the student\'s response data.').'</span></p>');
6212: }
6213: } else {
6214: my $warning=&scantron_warning_screen('Grading: Validate Records');
6215: $r->print('
6216: '.$warning.'
6217: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
6218: <input type="hidden" name="command" value="scantron_validate" />
6219: ');
6220: }
6221: $r->print("</form><br />");
6222: return '';
6223: }
6224:
6225: =pod
6226:
6227: =item scantron_form_start
6228:
6229: html hidden input for remembering all selected grading options
6230:
6231: =cut
6232:
6233: sub scantron_form_start {
6234: my ($max_bubble)=@_;
6235: my $result= <<SCANTRONFORM;
6236: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
6237: <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
6238: <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
6239: <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
6240: <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
6241: <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
6242: <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
6243: <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
6244: <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
6245: <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
6246: SCANTRONFORM
6247:
6248: my $line = 0;
6249: while (defined($env{"form.scantron.bubblelines.$line"})) {
6250: my $chunk =
6251: '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
6252: $chunk .=
6253: '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
6254: $chunk .=
6255: '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
6256: $chunk .=
6257: '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
6258: $result .= $chunk;
6259: $line++;
6260: }
6261: return $result;
6262: }
6263:
6264: =pod
6265:
6266: =item scantron_validate_file
6267:
6268: Dispatch routine for doing validation of a bubble sheet data file.
6269:
6270: Also processes any necessary information resets that need to
6271: occur before validation begins (ignore previous corrections,
6272: restarting the skipped records processing)
6273:
6274: =cut
6275:
6276: sub scantron_validate_file {
6277: my ($r,$symb) = @_;
6278: if (!$symb) {return '';}
6279: my $default_form_data=&defaultFormData($symb);
6280:
6281: # do the detection of only doing skipped records first befroe we delete
6282: # them when doing the corrections reset
6283: if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
6284: &reset_skipping_status();
6285: }
6286: if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
6287: &remember_current_skipped();
6288: $env{'form.scantron_options_redo'}='redo_skipped_ready';
6289: }
6290:
6291: if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
6292: &check_for_error($r,&scantron_remove_file('corrected'));
6293: &check_for_error($r,&scantron_remove_file('skipped'));
6294: &check_for_error($r,&scantron_remove_scan_data());
6295: $env{'form.scantron_options_ignore'}='done';
6296: }
6297:
6298: if ($env{'form.scantron_corrections'}) {
6299: &scantron_process_corrections($r);
6300: }
6301: $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
6302: #get the student pick code ready
6303: $r->print(&Apache::loncommon::studentbrowser_javascript());
6304: my $nav_error;
6305: my $max_bubble=&scantron_get_maxbubble(\$nav_error);
6306: if ($nav_error) {
6307: $r->print(&navmap_errormsg());
6308: return '';
6309: }
6310: my $result=&scantron_form_start($max_bubble).$default_form_data;
6311: $r->print($result);
6312:
6313: my @validate_phases=( 'sequence',
6314: 'ID',
6315: 'CODE',
6316: 'doublebubble',
6317: 'missingbubbles');
6318: if (!$env{'form.validatepass'}) {
6319: $env{'form.validatepass'} = 0;
6320: }
6321: my $currentphase=$env{'form.validatepass'};
6322:
6323:
6324: my $stop=0;
6325: while (!$stop && $currentphase < scalar(@validate_phases)) {
6326: $r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
6327: $r->rflush();
6328: my $which="scantron_validate_".$validate_phases[$currentphase];
6329: {
6330: no strict 'refs';
6331: ($stop,$currentphase)=&$which($r,$currentphase);
6332: }
6333: }
6334: if (!$stop) {
6335: my $warning=&scantron_warning_screen('Start Grading');
6336: $r->print(&mt('Validation process complete.').'<br />'.
6337: $warning.
6338: &mt('Perform verification for each student after storage of submissions?').
6339: ' <span class="LC_nobreak"><label>'.
6340: '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
6341: (' 'x3).'<label>'.
6342: '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
6343: '</label></span><br />'.
6344: &mt('Grading will take longer if you use verification.').'<br />'.
6345: &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
6346: '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
6347: '<input type="hidden" name="command" value="scantron_process" />'."\n");
6348: } else {
6349: $r->print('<input type="hidden" name="command" value="scantron_validate" />');
6350: $r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
6351: }
6352: if ($stop) {
6353: if ($validate_phases[$currentphase] eq 'sequence') {
6354: $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' → " />');
6355: $r->print(' '.&mt('this error').' <br />');
6356:
6357: $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
6358: } else {
6359: if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
6360: $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' →" onclick="javascript:verify_bubble_radio(this.form)" />');
6361: } else {
6362: $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' →" />');
6363: }
6364: $r->print(' '.&mt('using corrected info').' <br />');
6365: $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
6366: $r->print(" ".&mt("this scanline saving it for later."));
6367: }
6368: }
6369: $r->print(" </form><br />");
6370: return '';
6371: }
6372:
6373:
6374: =pod
6375:
6376: =item scantron_remove_file
6377:
6378: Removes the requested bubble sheet data file, makes sure that
6379: scantron_original_<filename> is never removed
6380:
6381:
6382: =cut
6383:
6384: sub scantron_remove_file {
6385: my ($which)=@_;
6386: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6387: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6388: my $file='scantron_';
6389: if ($which eq 'corrected' || $which eq 'skipped') {
6390: $file.=$which.'_';
6391: } else {
6392: return 'refused';
6393: }
6394: $file.=$env{'form.scantron_selectfile'};
6395: return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
6396: }
6397:
6398:
6399: =pod
6400:
6401: =item scantron_remove_scan_data
6402:
6403: Removes all scan_data correction for the requested bubble sheet
6404: data file. (In the case that both the are doing skipped records we need
6405: to remember the old skipped lines for the time being so that element
6406: persists for a while.)
6407:
6408: =cut
6409:
6410: sub scantron_remove_scan_data {
6411: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6412: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6413: my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
6414: my @todelete;
6415: my $filename=$env{'form.scantron_selectfile'};
6416: foreach my $key (@keys) {
6417: if ($key=~/^\Q$filename\E_/) {
6418: if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
6419: $key=~/remember_skipping/) {
6420: next;
6421: }
6422: push(@todelete,$key);
6423: }
6424: }
6425: my $result;
6426: if (@todelete) {
6427: $result = &Apache::lonnet::del('nohist_scantrondata',
6428: \@todelete,$cdom,$cname);
6429: } else {
6430: $result = 'ok';
6431: }
6432: return $result;
6433: }
6434:
6435:
6436: =pod
6437:
6438: =item scantron_getfile
6439:
6440: Fetches the requested bubble sheet data file (all 3 versions), and
6441: the scan_data hash
6442:
6443: Arguments:
6444: None
6445:
6446: Returns:
6447: 2 hash references
6448:
6449: - first one has
6450: orig -
6451: corrected -
6452: skipped - each of which points to an array ref of the specified
6453: file broken up into individual lines
6454: count - number of scanlines
6455:
6456: - second is the scan_data hash possible keys are
6457: ($number refers to scanline numbered $number and thus the key affects
6458: only that scanline
6459: $bubline refers to the specific bubble line element and the aspects
6460: refers to that specific bubble line element)
6461:
6462: $number.user - username:domain to use
6463: $number.CODE_ignore_dup
6464: - ignore the duplicate CODE error
6465: $number.useCODE
6466: - use the CODE in the scanline as is
6467: $number.no_bubble.$bubline
6468: - it is valid that there is no bubbled in bubble
6469: at $number $bubline
6470: remember_skipping
6471: - a frozen hash containing keys of $number and values
6472: of either
6473: 1 - we are on a 'do skipped records pass' and plan
6474: on processing this line
6475: 2 - we are on a 'do skipped records pass' and this
6476: scanline has been marked to skip yet again
6477:
6478: =cut
6479:
6480: sub scantron_getfile {
6481: #FIXME really would prefer a scantron directory
6482: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6483: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6484: my $lines;
6485: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
6486: 'scantron_orig_'.$env{'form.scantron_selectfile'});
6487: my %scanlines;
6488: $scanlines{'orig'}=[(split("\n",$lines,-1))];
6489: my $temp=$scanlines{'orig'};
6490: $scanlines{'count'}=$#$temp;
6491:
6492: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
6493: 'scantron_corrected_'.$env{'form.scantron_selectfile'});
6494: if ($lines eq '-1') {
6495: $scanlines{'corrected'}=[];
6496: } else {
6497: $scanlines{'corrected'}=[(split("\n",$lines,-1))];
6498: }
6499: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
6500: 'scantron_skipped_'.$env{'form.scantron_selectfile'});
6501: if ($lines eq '-1') {
6502: $scanlines{'skipped'}=[];
6503: } else {
6504: $scanlines{'skipped'}=[(split("\n",$lines,-1))];
6505: }
6506: my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
6507: if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
6508: my %scan_data = @tmp;
6509: return (\%scanlines,\%scan_data);
6510: }
6511:
6512: =pod
6513:
6514: =item lonnet_putfile
6515:
6516: Wrapper routine to call &Apache::lonnet::finishuserfileupload
6517:
6518: Arguments:
6519: $contents - data to store
6520: $filename - filename to store $contents into
6521:
6522: Returns:
6523: result value from &Apache::lonnet::finishuserfileupload
6524:
6525: =cut
6526:
6527: sub lonnet_putfile {
6528: my ($contents,$filename)=@_;
6529: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
6530: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6531: $env{'form.sillywaytopassafilearound'}=$contents;
6532: &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
6533:
6534: }
6535:
6536: =pod
6537:
6538: =item scantron_putfile
6539:
6540: Stores the current version of the bubble sheet data files, and the
6541: scan_data hash. (Does not modify the original version only the
6542: corrected and skipped versions.
6543:
6544: Arguments:
6545: $scanlines - hash ref that looks like the first return value from
6546: &scantron_getfile()
6547: $scan_data - hash ref that looks like the second return value from
6548: &scantron_getfile()
6549:
6550: =cut
6551:
6552: sub scantron_putfile {
6553: my ($scanlines,$scan_data) = @_;
6554: #FIXME really would prefer a scantron directory
6555: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6556: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6557: if ($scanlines) {
6558: my $prefix='scantron_';
6559: # no need to update orig, shouldn't change
6560: # &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
6561: # $env{'form.scantron_selectfile'});
6562: &lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
6563: $prefix.'corrected_'.
6564: $env{'form.scantron_selectfile'});
6565: &lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
6566: $prefix.'skipped_'.
6567: $env{'form.scantron_selectfile'});
6568: }
6569: &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
6570: }
6571:
6572: =pod
6573:
6574: =item scantron_get_line
6575:
6576: Returns the correct version of the scanline
6577:
6578: Arguments:
6579: $scanlines - hash ref that looks like the first return value from
6580: &scantron_getfile()
6581: $scan_data - hash ref that looks like the second return value from
6582: &scantron_getfile()
6583: $i - number of the requested line (starts at 0)
6584:
6585: Returns:
6586: A scanline, (either the original or the corrected one if it
6587: exists), or undef if the requested scanline should be
6588: skipped. (Either because it's an skipped scanline, or it's an
6589: unskipped scanline and we are not doing a 'do skipped scanlines'
6590: pass.
6591:
6592: =cut
6593:
6594: sub scantron_get_line {
6595: my ($scanlines,$scan_data,$i)=@_;
6596: if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
6597: #if ($scanlines->{'skipped'}[$i]) { return undef; }
6598: if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
6599: return $scanlines->{'orig'}[$i];
6600: }
6601:
6602: =pod
6603:
6604: =item scantron_todo_count
6605:
6606: Counts the number of scanlines that need processing.
6607:
6608: Arguments:
6609: $scanlines - hash ref that looks like the first return value from
6610: &scantron_getfile()
6611: $scan_data - hash ref that looks like the second return value from
6612: &scantron_getfile()
6613:
6614: Returns:
6615: $count - number of scanlines to process
6616:
6617: =cut
6618:
6619: sub get_todo_count {
6620: my ($scanlines,$scan_data)=@_;
6621: my $count=0;
6622: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6623: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6624: if ($line=~/^[\s\cz]*$/) { next; }
6625: $count++;
6626: }
6627: return $count;
6628: }
6629:
6630: =pod
6631:
6632: =item scantron_put_line
6633:
6634: Updates the 'corrected' or 'skipped' versions of the bubble sheet
6635: data file.
6636:
6637: Arguments:
6638: $scanlines - hash ref that looks like the first return value from
6639: &scantron_getfile()
6640: $scan_data - hash ref that looks like the second return value from
6641: &scantron_getfile()
6642: $i - line number to update
6643: $newline - contents of the updated scanline
6644: $skip - if true make the line for skipping and update the
6645: 'skipped' file
6646:
6647: =cut
6648:
6649: sub scantron_put_line {
6650: my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
6651: if ($skip) {
6652: $scanlines->{'skipped'}[$i]=$newline;
6653: &start_skipping($scan_data,$i);
6654: return;
6655: }
6656: $scanlines->{'corrected'}[$i]=$newline;
6657: }
6658:
6659: =pod
6660:
6661: =item scantron_clear_skip
6662:
6663: Remove a line from the 'skipped' file
6664:
6665: Arguments:
6666: $scanlines - hash ref that looks like the first return value from
6667: &scantron_getfile()
6668: $scan_data - hash ref that looks like the second return value from
6669: &scantron_getfile()
6670: $i - line number to update
6671:
6672: =cut
6673:
6674: sub scantron_clear_skip {
6675: my ($scanlines,$scan_data,$i)=@_;
6676: if (exists($scanlines->{'skipped'}[$i])) {
6677: undef($scanlines->{'skipped'}[$i]);
6678: return 1;
6679: }
6680: return 0;
6681: }
6682:
6683: =pod
6684:
6685: =item scantron_filter_not_exam
6686:
6687: Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
6688: filter out resources that are not marked as 'exam' mode
6689:
6690: =cut
6691:
6692: sub scantron_filter_not_exam {
6693: my ($curres)=@_;
6694:
6695: if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
6696: # if the user has asked to not have either hidden
6697: # or 'randomout' controlled resources to be graded
6698: # don't include them
6699: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
6700: && $curres->randomout) {
6701: return 0;
6702: }
6703: return 1;
6704: }
6705: return 0;
6706: }
6707:
6708: =pod
6709:
6710: =item scantron_validate_sequence
6711:
6712: Validates the selected sequence, checking for resource that are
6713: not set to exam mode.
6714:
6715: =cut
6716:
6717: sub scantron_validate_sequence {
6718: my ($r,$currentphase) = @_;
6719:
6720: my $navmap=Apache::lonnavmaps::navmap->new();
6721: unless (ref($navmap)) {
6722: $r->print(&navmap_errormsg());
6723: return (1,$currentphase);
6724: }
6725: my (undef,undef,$sequence)=
6726: &Apache::lonnet::decode_symb($env{'form.selectpage'});
6727:
6728: my $map=$navmap->getResourceByUrl($sequence);
6729:
6730: $r->print('<input type="hidden" name="validate_sequence_exam"
6731: value="ignore" />');
6732: if ($env{'form.validate_sequence_exam'} ne 'ignore') {
6733: my @resources=
6734: $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
6735: if (@resources) {
6736: $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>");
6737: return (1,$currentphase);
6738: }
6739: }
6740:
6741: return (0,$currentphase+1);
6742: }
6743:
6744:
6745:
6746: sub scantron_validate_ID {
6747: my ($r,$currentphase) = @_;
6748:
6749: #get student info
6750: my $classlist=&Apache::loncoursedata::get_classlist();
6751: my %idmap=&username_to_idmap($classlist);
6752:
6753: #get scantron line setup
6754: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6755: my ($scanlines,$scan_data)=&scantron_getfile();
6756:
6757: my $nav_error;
6758: &scantron_get_maxbubble(\$nav_error); # parse needs the bubble_lines.. array.
6759: if ($nav_error) {
6760: $r->print(&navmap_errormsg());
6761: return(1,$currentphase);
6762: }
6763:
6764: my %found=('ids'=>{},'usernames'=>{});
6765: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6766: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6767: if ($line=~/^[\s\cz]*$/) { next; }
6768: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6769: $scan_data);
6770: my $id=$$scan_record{'scantron.ID'};
6771: my $found;
6772: foreach my $checkid (keys(%idmap)) {
6773: if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
6774: }
6775: if ($found) {
6776: my $username=$idmap{$found};
6777: if ($found{'ids'}{$found}) {
6778: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6779: $line,'duplicateID',$found);
6780: return(1,$currentphase);
6781: } elsif ($found{'usernames'}{$username}) {
6782: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6783: $line,'duplicateID',$username);
6784: return(1,$currentphase);
6785: }
6786: #FIXME store away line we previously saw the ID on to use above
6787: $found{'ids'}{$found}++;
6788: $found{'usernames'}{$username}++;
6789: } else {
6790: if ($id =~ /^\s*$/) {
6791: my $username=&scan_data($scan_data,"$i.user");
6792: if (defined($username) && $found{'usernames'}{$username}) {
6793: &scantron_get_correction($r,$i,$scan_record,
6794: \%scantron_config,
6795: $line,'duplicateID',$username);
6796: return(1,$currentphase);
6797: } elsif (!defined($username)) {
6798: &scantron_get_correction($r,$i,$scan_record,
6799: \%scantron_config,
6800: $line,'incorrectID');
6801: return(1,$currentphase);
6802: }
6803: $found{'usernames'}{$username}++;
6804: } else {
6805: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6806: $line,'incorrectID');
6807: return(1,$currentphase);
6808: }
6809: }
6810: }
6811:
6812: return (0,$currentphase+1);
6813: }
6814:
6815:
6816: sub scantron_get_correction {
6817: my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
6818: #FIXME in the case of a duplicated ID the previous line, probably need
6819: #to show both the current line and the previous one and allow skipping
6820: #the previous one or the current one
6821:
6822: if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
6823: $r->print("<p>".&mt("<b>An error was detected ($error)</b>".
6824: " for PaperID <tt>[_1]</tt>",
6825: $$scan_record{'scantron.PaperID'})."</p> \n");
6826: } else {
6827: $r->print("<p>".&mt("<b>An error was detected ($error)</b>".
6828: " in scanline [_1] <pre>[_2]</pre>",
6829: $i,$line)."</p> \n");
6830: }
6831: my $message="<p>".&mt("The ID on the form is <tt>[_1]</tt><br />".
6832: "The name on the paper is [_2],[_3]",
6833: $$scan_record{'scantron.ID'},
6834: $$scan_record{'scantron.LastName'},
6835: $$scan_record{'scantron.FirstName'})."</p>";
6836:
6837: $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
6838: $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
6839: # Array populated for doublebubble or
6840: my @lines_to_correct; # missingbubble errors to build javascript
6841: # to validate radio button checking
6842:
6843: if ($error =~ /ID$/) {
6844: if ($error eq 'incorrectID') {
6845: $r->print("<p>".&mt("The encoded ID is not in the classlist").
6846: "</p>\n");
6847: } elsif ($error eq 'duplicateID') {
6848: $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
6849: }
6850: $r->print($message);
6851: $r->print("<p>".&mt("How should I handle this?")." <br /> \n");
6852: $r->print("\n<ul><li> ");
6853: #FIXME it would be nice if this sent back the user ID and
6854: #could do partial userID matches
6855: $r->print(&Apache::loncommon::selectstudent_link('scantronupload',
6856: 'scantron_username','scantron_domain'));
6857: $r->print(": <input type='text' name='scantron_username' value='' />");
6858: $r->print("\n@".
6859: &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
6860:
6861: $r->print('</li>');
6862: } elsif ($error =~ /CODE$/) {
6863: if ($error eq 'incorrectCODE') {
6864: $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
6865: } elsif ($error eq 'duplicateCODE') {
6866: $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");
6867: }
6868: $r->print("<p>".&mt("The CODE on the form is <tt>'[_1]'</tt>",
6869: $$scan_record{'scantron.CODE'})."<br />\n");
6870: $r->print($message);
6871: $r->print("<p>".&mt("How should I handle this?")." <br /> \n");
6872: $r->print("\n<br /> ");
6873: my $i=0;
6874: if ($error eq 'incorrectCODE'
6875: && $$scan_record{'scantron.CODE'}=~/\S/ ) {
6876: my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
6877: if ($closest > 0) {
6878: foreach my $testcode (@{$closest}) {
6879: my $checked='';
6880: if (!$i) { $checked=' checked="checked"'; }
6881: $r->print("
6882: <label>
6883: <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
6884: ".&mt("Use the similar CODE [_1] instead.",
6885: "<b><tt>".$testcode."</tt></b>")."
6886: </label>
6887: <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
6888: $r->print("\n<br />");
6889: $i++;
6890: }
6891: }
6892: }
6893: if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
6894: my $checked; if (!$i) { $checked=' checked="checked"'; }
6895: $r->print("
6896: <label>
6897: <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
6898: ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
6899: "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
6900: </label>");
6901: $r->print("\n<br />");
6902: }
6903:
6904: $r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
6905: function change_radio(field) {
6906: var slct=document.scantronupload.scantron_CODE_resolution;
6907: var i;
6908: for (i=0;i<slct.length;i++) {
6909: if (slct[i].value==field) { slct[i].checked=true; }
6910: }
6911: }
6912: ENDSCRIPT
6913: my $href="/adm/pickcode?".
6914: "form=".&escape("scantronupload").
6915: "&scantron_format=".&escape($env{'form.scantron_format'}).
6916: "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
6917: "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
6918: "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
6919: if ($env{'form.scantron_CODElist'} =~ /\S/) {
6920: $r->print("
6921: <label>
6922: <input type='radio' name='scantron_CODE_resolution' value='use_found' />
6923: ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
6924: "<a target='_blank' href='$href'>","</a>")."
6925: </label>
6926: ".&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\')" />'));
6927: $r->print("\n<br />");
6928: }
6929: $r->print("
6930: <label>
6931: <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
6932: ".&mt("Use [_1] as the CODE.",
6933: "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
6934: $r->print("\n<br /><br />");
6935: } elsif ($error eq 'doublebubble') {
6936: $r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
6937:
6938: # The form field scantron_questions is acutally a list of line numbers.
6939: # represented by this form so:
6940:
6941: my $line_list = &questions_to_line_list($arg);
6942:
6943: $r->print('<input type="hidden" name="scantron_questions" value="'.
6944: $line_list.'" />');
6945: $r->print($message);
6946: $r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
6947: foreach my $question (@{$arg}) {
6948: my @linenums = &prompt_for_corrections($r,$question,$scan_config,
6949: $scan_record, $error);
6950: push(@lines_to_correct,@linenums);
6951: }
6952: $r->print(&verify_bubbles_checked(@lines_to_correct));
6953: } elsif ($error eq 'missingbubble') {
6954: $r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
6955: $r->print($message);
6956: $r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
6957: $r->print(&mt("Some questions have no scanned bubbles.")."\n");
6958:
6959: # The form field scantron_questions is actually a list of line numbers not
6960: # a list of question numbers. Therefore:
6961: #
6962:
6963: my $line_list = &questions_to_line_list($arg);
6964:
6965: $r->print('<input type="hidden" name="scantron_questions" value="'.
6966: $line_list.'" />');
6967: foreach my $question (@{$arg}) {
6968: my @linenums = &prompt_for_corrections($r,$question,$scan_config,
6969: $scan_record, $error);
6970: push(@lines_to_correct,@linenums);
6971: }
6972: $r->print(&verify_bubbles_checked(@lines_to_correct));
6973: } else {
6974: $r->print("\n<ul>");
6975: }
6976: $r->print("\n</li></ul>");
6977: }
6978:
6979: sub verify_bubbles_checked {
6980: my (@ansnums) = @_;
6981: my $ansnumstr = join('","',@ansnums);
6982: my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
6983: my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
6984: function verify_bubble_radio(form) {
6985: var ansnumArray = new Array ("$ansnumstr");
6986: var need_bubble_count = 0;
6987: for (var i=0; i<ansnumArray.length; i++) {
6988: if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
6989: var bubble_picked = 0;
6990: for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
6991: if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
6992: bubble_picked = 1;
6993: }
6994: }
6995: if (bubble_picked == 0) {
6996: need_bubble_count ++;
6997: }
6998: }
6999: }
7000: if (need_bubble_count) {
7001: alert("$warning");
7002: return;
7003: }
7004: form.submit();
7005: }
7006: ENDSCRIPT
7007: return $output;
7008: }
7009:
7010: =pod
7011:
7012: =item questions_to_line_list
7013:
7014: Converts a list of questions into a string of comma separated
7015: line numbers in the answer sheet used by the questions. This is
7016: used to fill in the scantron_questions form field.
7017:
7018: Arguments:
7019: questions - Reference to an array of questions.
7020:
7021: =cut
7022:
7023:
7024: sub questions_to_line_list {
7025: my ($questions) = @_;
7026: my @lines;
7027:
7028: foreach my $item (@{$questions}) {
7029: my $question = $item;
7030: my ($first,$count,$last);
7031: if ($item =~ /^(\d+)\.(\d+)$/) {
7032: $question = $1;
7033: my $subquestion = $2;
7034: $first = $first_bubble_line{$question-1} + 1;
7035: my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
7036: my $subcount = 1;
7037: while ($subcount<$subquestion) {
7038: $first += $subans[$subcount-1];
7039: $subcount ++;
7040: }
7041: $count = $subans[$subquestion-1];
7042: } else {
7043: $first = $first_bubble_line{$question-1} + 1;
7044: $count = $bubble_lines_per_response{$question-1};
7045: }
7046: $last = $first+$count-1;
7047: push(@lines, ($first..$last));
7048: }
7049: return join(',', @lines);
7050: }
7051:
7052: =pod
7053:
7054: =item prompt_for_corrections
7055:
7056: Prompts for a potentially multiline correction to the
7057: user's bubbling (factors out common code from scantron_get_correction
7058: for multi and missing bubble cases).
7059:
7060: Arguments:
7061: $r - Apache request object.
7062: $question - The question number to prompt for.
7063: $scan_config - The scantron file configuration hash.
7064: $scan_record - Reference to the hash that has the the parsed scanlines.
7065: $error - Type of error
7066:
7067: Implicit inputs:
7068: %bubble_lines_per_response - Starting line numbers for each question.
7069: Numbered from 0 (but question numbers are from
7070: 1.
7071: %first_bubble_line - Starting bubble line for each question.
7072: %subdivided_bubble_lines - optionresponse, matchresponse and rankresponse
7073: type problems render as separate sub-questions,
7074: in exam mode. This hash contains a
7075: comma-separated list of the lines per
7076: sub-question.
7077: %responsetype_per_response - essayresponse, formularesponse,
7078: stringresponse, imageresponse, reactionresponse,
7079: and organicresponse type problem parts can have
7080: multiple lines per response if the weight
7081: assigned exceeds 10. In this case, only
7082: one bubble per line is permitted, but more
7083: than one line might contain bubbles, e.g.
7084: bubbling of: line 1 - J, line 2 - J,
7085: line 3 - B would assign 22 points.
7086:
7087: =cut
7088:
7089: sub prompt_for_corrections {
7090: my ($r, $question, $scan_config, $scan_record, $error) = @_;
7091: my ($current_line,$lines);
7092: my @linenums;
7093: my $questionnum = $question;
7094: if ($question =~ /^(\d+)\.(\d+)$/) {
7095: $question = $1;
7096: $current_line = $first_bubble_line{$question-1} + 1 ;
7097: my $subquestion = $2;
7098: my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
7099: my $subcount = 1;
7100: while ($subcount<$subquestion) {
7101: $current_line += $subans[$subcount-1];
7102: $subcount ++;
7103: }
7104: $lines = $subans[$subquestion-1];
7105: } else {
7106: $current_line = $first_bubble_line{$question-1} + 1 ;
7107: $lines = $bubble_lines_per_response{$question-1};
7108: }
7109: if ($lines > 1) {
7110: $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
7111: if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
7112: ($responsetype_per_response{$question-1} eq 'formularesponse') ||
7113: ($responsetype_per_response{$question-1} eq 'stringresponse') ||
7114: ($responsetype_per_response{$question-1} eq 'imageresponse') ||
7115: ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
7116: ($responsetype_per_response{$question-1} eq 'organicresponse')) {
7117: $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 />');
7118: } else {
7119: $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
7120: }
7121: }
7122: for (my $i =0; $i < $lines; $i++) {
7123: my $selected = $$scan_record{"scantron.$current_line.answer"};
7124: &scantron_bubble_selector($r,$scan_config,$current_line,
7125: $questionnum,$error,split('', $selected));
7126: push(@linenums,$current_line);
7127: $current_line++;
7128: }
7129: if ($lines > 1) {
7130: $r->print("<hr /><br />");
7131: }
7132: return @linenums;
7133: }
7134:
7135: =pod
7136:
7137: =item scantron_bubble_selector
7138:
7139: Generates the html radiobuttons to correct a single bubble line
7140: possibly showing the existing the selected bubbles if known
7141:
7142: Arguments:
7143: $r - Apache request object
7144: $scan_config - hash from &get_scantron_config()
7145: $line - Number of the line being displayed.
7146: $questionnum - Question number (may include subquestion)
7147: $error - Type of error.
7148: @selected - Array of bubbles picked on this line.
7149:
7150: =cut
7151:
7152: sub scantron_bubble_selector {
7153: my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
7154: my $max=$$scan_config{'Qlength'};
7155:
7156: my $scmode=$$scan_config{'Qon'};
7157: if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }
7158:
7159: my @alphabet=('A'..'Z');
7160: $r->print(&Apache::loncommon::start_data_table().
7161: &Apache::loncommon::start_data_table_row());
7162: $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
7163: for (my $i=0;$i<$max+1;$i++) {
7164: $r->print("\n".'<td align="center">');
7165: if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
7166: else { $r->print(' '); }
7167: $r->print('</td>');
7168: }
7169: $r->print(&Apache::loncommon::end_data_table_row().
7170: &Apache::loncommon::start_data_table_row());
7171: for (my $i=0;$i<$max;$i++) {
7172: $r->print("\n".
7173: '<td><label><input type="radio" name="scantron_correct_Q_'.
7174: $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
7175: }
7176: my $nobub_checked = ' ';
7177: if ($error eq 'missingbubble') {
7178: $nobub_checked = ' checked = "checked" ';
7179: }
7180: $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
7181: $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
7182: '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
7183: $line.'" value="'.$questionnum.'" /></td>');
7184: $r->print(&Apache::loncommon::end_data_table_row().
7185: &Apache::loncommon::end_data_table());
7186: }
7187:
7188: =pod
7189:
7190: =item num_matches
7191:
7192: Counts the number of characters that are the same between the two arguments.
7193:
7194: Arguments:
7195: $orig - CODE from the scanline
7196: $code - CODE to match against
7197:
7198: Returns:
7199: $count - integer count of the number of same characters between the
7200: two arguments
7201:
7202: =cut
7203:
7204: sub num_matches {
7205: my ($orig,$code) = @_;
7206: my @code=split(//,$code);
7207: my @orig=split(//,$orig);
7208: my $same=0;
7209: for (my $i=0;$i<scalar(@code);$i++) {
7210: if ($code[$i] eq $orig[$i]) { $same++; }
7211: }
7212: return $same;
7213: }
7214:
7215: =pod
7216:
7217: =item scantron_get_closely_matching_CODEs
7218:
7219: Cycles through all CODEs and finds the set that has the greatest
7220: number of same characters as the provided CODE
7221:
7222: Arguments:
7223: $allcodes - hash ref returned by &get_codes()
7224: $CODE - CODE from the current scanline
7225:
7226: Returns:
7227: 2 element list
7228: - first elements is number of how closely matching the best fit is
7229: (5 means best set has 5 matching characters)
7230: - second element is an arrary ref containing the set of valid CODEs
7231: that best fit the passed in CODE
7232:
7233: =cut
7234:
7235: sub scantron_get_closely_matching_CODEs {
7236: my ($allcodes,$CODE)=@_;
7237: my @CODEs;
7238: foreach my $testcode (sort(keys(%{$allcodes}))) {
7239: push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
7240: }
7241:
7242: return ($#CODEs,$CODEs[-1]);
7243: }
7244:
7245: =pod
7246:
7247: =item get_codes
7248:
7249: Builds a hash which has keys of all of the valid CODEs from the selected
7250: set of remembered CODEs.
7251:
7252: Arguments:
7253: $old_name - name of the set of remembered CODEs
7254: $cdom - domain of the course
7255: $cnum - internal course name
7256:
7257: Returns:
7258: %allcodes - keys are the valid CODEs, values are all 1
7259:
7260: =cut
7261:
7262: sub get_codes {
7263: my ($old_name, $cdom, $cnum) = @_;
7264: if (!$old_name) {
7265: $old_name=$env{'form.scantron_CODElist'};
7266: }
7267: if (!$cdom) {
7268: $cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
7269: }
7270: if (!$cnum) {
7271: $cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
7272: }
7273: my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
7274: $cdom,$cnum);
7275: my %allcodes;
7276: if ($result{"type\0$old_name"} eq 'number') {
7277: %allcodes=map {($_,1)} split(',',$result{$old_name});
7278: } else {
7279: %allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
7280: }
7281: return %allcodes;
7282: }
7283:
7284: =pod
7285:
7286: =item scantron_validate_CODE
7287:
7288: Validates all scanlines in the selected file to not have any
7289: invalid or underspecified CODEs and that none of the codes are
7290: duplicated if this was requested.
7291:
7292: =cut
7293:
7294: sub scantron_validate_CODE {
7295: my ($r,$currentphase) = @_;
7296: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7297: if ($scantron_config{'CODElocation'} &&
7298: $scantron_config{'CODEstart'} &&
7299: $scantron_config{'CODElength'}) {
7300: if (!defined($env{'form.scantron_CODElist'})) {
7301: &FIXME_blow_up()
7302: }
7303: } else {
7304: return (0,$currentphase+1);
7305: }
7306:
7307: my %usedCODEs;
7308:
7309: my %allcodes=&get_codes();
7310:
7311: my $nav_error;
7312: &scantron_get_maxbubble(\$nav_error); # parse needs the lines per response array.
7313: if ($nav_error) {
7314: $r->print(&navmap_errormsg());
7315: return(1,$currentphase);
7316: }
7317:
7318: my ($scanlines,$scan_data)=&scantron_getfile();
7319: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7320: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7321: if ($line=~/^[\s\cz]*$/) { next; }
7322: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7323: $scan_data);
7324: my $CODE=$$scan_record{'scantron.CODE'};
7325: my $error=0;
7326: if (!&Apache::lonnet::validCODE($CODE)) {
7327: &scantron_get_correction($r,$i,$scan_record,
7328: \%scantron_config,
7329: $line,'incorrectCODE',\%allcodes);
7330: return(1,$currentphase);
7331: }
7332: if (%allcodes && !exists($allcodes{$CODE})
7333: && !$$scan_record{'scantron.useCODE'}) {
7334: &scantron_get_correction($r,$i,$scan_record,
7335: \%scantron_config,
7336: $line,'incorrectCODE',\%allcodes);
7337: return(1,$currentphase);
7338: }
7339: if (exists($usedCODEs{$CODE})
7340: && $env{'form.scantron_CODEunique'} eq 'yes'
7341: && !$$scan_record{'scantron.CODE_ignore_dup'}) {
7342: &scantron_get_correction($r,$i,$scan_record,
7343: \%scantron_config,
7344: $line,'duplicateCODE',$usedCODEs{$CODE});
7345: return(1,$currentphase);
7346: }
7347: push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
7348: }
7349: return (0,$currentphase+1);
7350: }
7351:
7352: =pod
7353:
7354: =item scantron_validate_doublebubble
7355:
7356: Validates all scanlines in the selected file to not have any
7357: bubble lines with multiple bubbles marked.
7358:
7359: =cut
7360:
7361: sub scantron_validate_doublebubble {
7362: my ($r,$currentphase) = @_;
7363: #get student info
7364: my $classlist=&Apache::loncoursedata::get_classlist();
7365: my %idmap=&username_to_idmap($classlist);
7366:
7367: #get scantron line setup
7368: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7369: my ($scanlines,$scan_data)=&scantron_getfile();
7370: my $nav_error;
7371: &scantron_get_maxbubble(\$nav_error); # parse needs the bubble line array.
7372: if ($nav_error) {
7373: $r->print(&navmap_errormsg());
7374: return(1,$currentphase);
7375: }
7376:
7377: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7378: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7379: if ($line=~/^[\s\cz]*$/) { next; }
7380: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7381: $scan_data);
7382: if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
7383: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
7384: 'doublebubble',
7385: $$scan_record{'scantron.doubleerror'});
7386: return (1,$currentphase);
7387: }
7388: return (0,$currentphase+1);
7389: }
7390:
7391:
7392: sub scantron_get_maxbubble {
7393: my ($nav_error) = @_;
7394: if (defined($env{'form.scantron_maxbubble'}) &&
7395: $env{'form.scantron_maxbubble'}) {
7396: &restore_bubble_lines();
7397: return $env{'form.scantron_maxbubble'};
7398: }
7399:
7400: my (undef, undef, $sequence) =
7401: &Apache::lonnet::decode_symb($env{'form.selectpage'});
7402:
7403: my $navmap=Apache::lonnavmaps::navmap->new();
7404: unless (ref($navmap)) {
7405: if (ref($nav_error)) {
7406: $$nav_error = 1;
7407: }
7408: return;
7409: }
7410: my $map=$navmap->getResourceByUrl($sequence);
7411: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
7412:
7413: &Apache::lonxml::clear_problem_counter();
7414:
7415: my $uname = $env{'user.name'};
7416: my $udom = $env{'user.domain'};
7417: my $cid = $env{'request.course.id'};
7418: my $total_lines = 0;
7419: %bubble_lines_per_response = ();
7420: %first_bubble_line = ();
7421: %subdivided_bubble_lines = ();
7422: %responsetype_per_response = ();
7423:
7424: my $response_number = 0;
7425: my $bubble_line = 0;
7426: foreach my $resource (@resources) {
7427: my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
7428: if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
7429: foreach my $part_id (@{$parts}) {
7430: my $lines;
7431:
7432: # TODO - make this a persistent hash not an array.
7433:
7434: # optionresponse, matchresponse and rankresponse type items
7435: # render as separate sub-questions in exam mode.
7436: if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
7437: ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
7438: ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
7439: my ($numbub,$numshown);
7440: if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
7441: if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
7442: $numbub = scalar(@{$analysis->{$part_id.'.options'}});
7443: }
7444: } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
7445: if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
7446: $numbub = scalar(@{$analysis->{$part_id.'.items'}});
7447: }
7448: } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
7449: if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
7450: $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
7451: }
7452: }
7453: if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
7454: $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
7455: }
7456: my $bubbles_per_line = 10;
7457: my $inner_bubble_lines = int($numbub/$bubbles_per_line);
7458: if (($numbub % $bubbles_per_line) != 0) {
7459: $inner_bubble_lines++;
7460: }
7461: for (my $i=0; $i<$numshown; $i++) {
7462: $subdivided_bubble_lines{$response_number} .=
7463: $inner_bubble_lines.',';
7464: }
7465: $subdivided_bubble_lines{$response_number} =~ s/,$//;
7466: $lines = $numshown * $inner_bubble_lines;
7467: } else {
7468: $lines = $analysis->{"$part_id.bubble_lines"};
7469: }
7470:
7471: $first_bubble_line{$response_number} = $bubble_line;
7472: $bubble_lines_per_response{$response_number} = $lines;
7473: $responsetype_per_response{$response_number} =
7474: $analysis->{$part_id.'.type'};
7475: $response_number++;
7476:
7477: $bubble_line += $lines;
7478: $total_lines += $lines;
7479: }
7480: }
7481: }
7482: &Apache::lonnet::delenv('scantron.');
7483:
7484: &save_bubble_lines();
7485: $env{'form.scantron_maxbubble'} =
7486: $total_lines;
7487: return $env{'form.scantron_maxbubble'};
7488: }
7489:
7490: sub scantron_validate_missingbubbles {
7491: my ($r,$currentphase) = @_;
7492: #get student info
7493: my $classlist=&Apache::loncoursedata::get_classlist();
7494: my %idmap=&username_to_idmap($classlist);
7495:
7496: #get scantron line setup
7497: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7498: my ($scanlines,$scan_data)=&scantron_getfile();
7499: my $nav_error;
7500: my $max_bubble=&scantron_get_maxbubble(\$nav_error);
7501: if ($nav_error) {
7502: return(1,$currentphase);
7503: }
7504: if (!$max_bubble) { $max_bubble=2**31; }
7505: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7506: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7507: if ($line=~/^[\s\cz]*$/) { next; }
7508: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7509: $scan_data);
7510: if (!defined($$scan_record{'scantron.missingerror'})) { next; }
7511: my @to_correct;
7512:
7513: # Probably here's where the error is...
7514:
7515: foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
7516: my $lastbubble;
7517: if ($missing =~ /^(\d+)\.(\d+)$/) {
7518: my $question = $1;
7519: my $subquestion = $2;
7520: if (!defined($first_bubble_line{$question -1})) { next; }
7521: my $first = $first_bubble_line{$question-1};
7522: my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
7523: my $subcount = 1;
7524: while ($subcount<$subquestion) {
7525: $first += $subans[$subcount-1];
7526: $subcount ++;
7527: }
7528: my $count = $subans[$subquestion-1];
7529: $lastbubble = $first + $count;
7530: } else {
7531: if (!defined($first_bubble_line{$missing - 1})) { next; }
7532: $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
7533: }
7534: if ($lastbubble > $max_bubble) { next; }
7535: push(@to_correct,$missing);
7536: }
7537: if (@to_correct) {
7538: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
7539: $line,'missingbubble',\@to_correct);
7540: return (1,$currentphase);
7541: }
7542:
7543: }
7544: return (0,$currentphase+1);
7545: }
7546:
7547:
7548: sub scantron_process_students {
7549: my ($r,$symb) = @_;
7550:
7551: my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
7552: if (!$symb) {
7553: return '';
7554: }
7555: my $default_form_data=&defaultFormData($symb);
7556:
7557: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7558: my ($scanlines,$scan_data)=&scantron_getfile();
7559: my $classlist=&Apache::loncoursedata::get_classlist();
7560: my %idmap=&username_to_idmap($classlist);
7561: my $navmap=Apache::lonnavmaps::navmap->new();
7562: unless (ref($navmap)) {
7563: $r->print(&navmap_errormsg());
7564: return '';
7565: }
7566: my $map=$navmap->getResourceByUrl($sequence);
7567: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
7568: my (%grader_partids_by_symb,%grader_randomlists_by_symb);
7569: &graders_resources_pass(\@resources,\%grader_partids_by_symb,
7570: \%grader_randomlists_by_symb);
7571: my $resource_error;
7572: foreach my $resource (@resources) {
7573: my $ressymb;
7574: if (ref($resource)) {
7575: $ressymb = $resource->symb();
7576: } else {
7577: $resource_error = 1;
7578: last;
7579: }
7580: my ($analysis,$parts) =
7581: &scantron_partids_tograde($resource,$env{'request.course.id'},
7582: $env{'user.name'},$env{'user.domain'},1);
7583: $grader_partids_by_symb{$ressymb} = $parts;
7584: if (ref($analysis) eq 'HASH') {
7585: if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
7586: $grader_randomlists_by_symb{$ressymb} =
7587: $analysis->{'parts_withrandomlist'};
7588: }
7589: }
7590: }
7591: if ($resource_error) {
7592: $r->print(&navmap_errormsg());
7593: return '';
7594: }
7595:
7596: my ($uname,$udom);
7597: my $result= <<SCANTRONFORM;
7598: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
7599: <input type="hidden" name="command" value="scantron_configphase" />
7600: $default_form_data
7601: SCANTRONFORM
7602: $r->print($result);
7603:
7604: my @delayqueue;
7605: my (%completedstudents,%scandata);
7606:
7607: my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
7608: my $count=&get_todo_count($scanlines,$scan_data);
7609: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
7610: 'Bubblesheet Progress',$count,
7611: 'inline',undef,'scantronupload');
7612: &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
7613: 'Processing first student');
7614: $r->print('<br />');
7615: my $start=&Time::HiRes::time();
7616: my $i=-1;
7617: my $started;
7618:
7619: my $nav_error;
7620: &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
7621: if ($nav_error) {
7622: $r->print(&navmap_errormsg());
7623: return '';
7624: }
7625:
7626: # If an ssi failed in scantron_get_maxbubble, put an error message out to
7627: # the user and return.
7628:
7629: if ($ssi_error) {
7630: $r->print("</form>");
7631: &ssi_print_error($r);
7632: &Apache::lonnet::remove_lock($lock);
7633: return ''; # Dunno why the other returns return '' rather than just returning.
7634: }
7635:
7636: my %lettdig = &letter_to_digits();
7637: my $numletts = scalar(keys(%lettdig));
7638:
7639: while ($i<$scanlines->{'count'}) {
7640: ($uname,$udom)=('','');
7641: $i++;
7642: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7643: if ($line=~/^[\s\cz]*$/) { next; }
7644: if ($started) {
7645: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
7646: 'last student');
7647: }
7648: $started=1;
7649: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7650: $scan_data);
7651: unless ($uname=&scantron_find_student($scan_record,$scan_data,
7652: \%idmap,$i)) {
7653: &scantron_add_delay(\@delayqueue,$line,
7654: 'Unable to find a student that matches',1);
7655: next;
7656: }
7657: if (exists $completedstudents{$uname}) {
7658: &scantron_add_delay(\@delayqueue,$line,
7659: 'Student '.$uname.' has multiple sheets',2);
7660: next;
7661: }
7662: ($uname,$udom)=split(/:/,$uname);
7663:
7664: my (%partids_by_symb,$res_error);
7665: foreach my $resource (@resources) {
7666: my $ressymb;
7667: if (ref($resource)) {
7668: $ressymb = $resource->symb();
7669: } else {
7670: $res_error = 1;
7671: last;
7672: }
7673: if ((exists($grader_randomlists_by_symb{$ressymb})) ||
7674: (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
7675: my ($analysis,$parts) =
7676: &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
7677: $partids_by_symb{$ressymb} = $parts;
7678: } else {
7679: $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
7680: }
7681: }
7682:
7683: if ($res_error) {
7684: &scantron_add_delay(\@delayqueue,$line,
7685: 'An error occurred while grading student '.$uname,2);
7686: next;
7687: }
7688:
7689: &Apache::lonxml::clear_problem_counter();
7690: &Apache::lonnet::appenv($scan_record);
7691:
7692: if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
7693: &scantron_putfile($scanlines,$scan_data);
7694: }
7695:
7696: my $scancode;
7697: if ((exists($scan_record->{'scantron.CODE'})) &&
7698: (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
7699: $scancode = $scan_record->{'scantron.CODE'};
7700: } else {
7701: $scancode = '';
7702: }
7703:
7704: if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
7705: \@resources,\%partids_by_symb) eq 'ssi_error') {
7706: $ssi_error = 0; # So end of handler error message does not trigger.
7707: $r->print("</form>");
7708: &ssi_print_error($r);
7709: &Apache::lonnet::remove_lock($lock);
7710: return ''; # Why return ''? Beats me.
7711: }
7712:
7713: $completedstudents{$uname}={'line'=>$line};
7714: if ($env{'form.verifyrecord'}) {
7715: my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
7716: my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
7717: chomp($studentdata);
7718: $studentdata =~ s/\r$//;
7719: my $studentrecord = '';
7720: my $counter = -1;
7721: foreach my $resource (@resources) {
7722: my $ressymb = $resource->symb();
7723: ($counter,my $recording) =
7724: &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
7725: $counter,$studentdata,$partids_by_symb{$ressymb},
7726: \%scantron_config,\%lettdig,$numletts);
7727: $studentrecord .= $recording;
7728: }
7729: if ($studentrecord ne $studentdata) {
7730: &Apache::lonxml::clear_problem_counter();
7731: if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
7732: \@resources,\%partids_by_symb) eq 'ssi_error') {
7733: $ssi_error = 0; # So end of handler error message does not trigger.
7734: $r->print("</form>");
7735: &ssi_print_error($r);
7736: &Apache::lonnet::remove_lock($lock);
7737: delete($completedstudents{$uname});
7738: return '';
7739: }
7740: $counter = -1;
7741: $studentrecord = '';
7742: foreach my $resource (@resources) {
7743: my $ressymb = $resource->symb();
7744: ($counter,my $recording) =
7745: &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
7746: $counter,$studentdata,$partids_by_symb{$ressymb},
7747: \%scantron_config,\%lettdig,$numletts);
7748: $studentrecord .= $recording;
7749: }
7750: if ($studentrecord ne $studentdata) {
7751: $r->print('<p><span class="LC_error">');
7752: if ($scancode eq '') {
7753: $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
7754: $uname.':'.$udom,$scan_record->{'scantron.ID'}));
7755: } else {
7756: $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
7757: $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
7758: }
7759: $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
7760: &Apache::loncommon::start_data_table_header_row()."\n".
7761: '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
7762: &Apache::loncommon::end_data_table_header_row()."\n".
7763: &Apache::loncommon::start_data_table_row().
7764: '<td>'.&mt('Bubble Sheet').'</td>'.
7765: '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
7766: &Apache::loncommon::end_data_table_row().
7767: &Apache::loncommon::start_data_table_row().
7768: '<td>Stored submissions</td>'.
7769: '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
7770: &Apache::loncommon::end_data_table_row().
7771: &Apache::loncommon::end_data_table().'</p>');
7772: } else {
7773: $r->print('<br /><span class="LC_warning">'.
7774: &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 />'.
7775: &mt("As a consequence, this user's submission history records two tries.").
7776: '</span><br />');
7777: }
7778: }
7779: }
7780: if (&Apache::loncommon::connection_aborted($r)) { last; }
7781: } continue {
7782: &Apache::lonxml::clear_problem_counter();
7783: &Apache::lonnet::delenv('scantron.');
7784: }
7785: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
7786: &Apache::lonnet::remove_lock($lock);
7787: # my $lasttime = &Time::HiRes::time()-$start;
7788: # $r->print("<p>took $lasttime</p>");
7789:
7790: $r->print("</form>");
7791: return '';
7792: }
7793:
7794: sub graders_resources_pass {
7795: my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
7796: if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) &&
7797: (ref($grader_randomlists_by_symb) eq 'HASH')) {
7798: foreach my $resource (@{$resources}) {
7799: my $ressymb = $resource->symb();
7800: my ($analysis,$parts) =
7801: &scantron_partids_tograde($resource,$env{'request.course.id'},
7802: $env{'user.name'},$env{'user.domain'},1);
7803: $grader_partids_by_symb->{$ressymb} = $parts;
7804: if (ref($analysis) eq 'HASH') {
7805: if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
7806: $grader_randomlists_by_symb->{$ressymb} =
7807: $analysis->{'parts_withrandomlist'};
7808: }
7809: }
7810: }
7811: }
7812: return;
7813: }
7814:
7815: sub grade_student_bubbles {
7816: my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
7817: if (ref($resources) eq 'ARRAY') {
7818: my $count = 0;
7819: foreach my $resource (@{$resources}) {
7820: my $ressymb = $resource->symb();
7821: my %form = ('submitted' => 'scantron',
7822: 'grade_target' => 'grade',
7823: 'grade_username' => $uname,
7824: 'grade_domain' => $udom,
7825: 'grade_courseid' => $env{'request.course.id'},
7826: 'grade_symb' => $ressymb,
7827: 'CODE' => $scancode
7828: );
7829: if (ref($parts) eq 'HASH') {
7830: if (ref($parts->{$ressymb}) eq 'ARRAY') {
7831: foreach my $part (@{$parts->{$ressymb}}) {
7832: $form{'scantron_questnum_start.'.$part} =
7833: 1+$env{'form.scantron.first_bubble_line.'.$count};
7834: $count++;
7835: }
7836: }
7837: }
7838: my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
7839: return 'ssi_error' if ($ssi_error);
7840: last if (&Apache::loncommon::connection_aborted($r));
7841: }
7842: }
7843: return;
7844: }
7845:
7846: sub scantron_upload_scantron_data {
7847: my ($r,$symb)=@_;
7848: my $dom = $env{'request.role.domain'};
7849: my $domdesc = &Apache::lonnet::domain($dom,'description');
7850: $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
7851: my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
7852: 'domainid',
7853: 'coursename',$dom);
7854: my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
7855: (' 'x2).&mt('(shows course personnel)');
7856: my $default_form_data=&defaultFormData($symb);
7857: my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
7858: 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.");
7859: $r->print(&Apache::lonhtmlcommon::scripttag('
7860: function checkUpload(formname) {
7861: if (formname.upfile.value == "") {
7862: alert("'.$nofile_alert.'");
7863: return false;
7864: }
7865: if (formname.courseid.value == "") {
7866: alert("'.$nocourseid_alert.'");
7867: return false;
7868: }
7869: formname.submit();
7870: }
7871:
7872: function ToSyllabus() {
7873: var cdom = '."'$dom'".';
7874: var cnum = document.rules.courseid.value;
7875: if (cdom == "" || cdom == null) {
7876: return;
7877: }
7878: if (cnum == "" || cnum == null) {
7879: return;
7880: }
7881: syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
7882: "height=350,width=350,scrollbars=yes,menubar=no");
7883: return;
7884: }
7885:
7886: '));
7887: $r->print('
7888: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
7889:
7890: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
7891: '.$default_form_data.
7892: &Apache::lonhtmlcommon::start_pick_box().
7893: &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
7894: '<input name="courseid" type="text" size="30" />'.$select_link.
7895: &Apache::lonhtmlcommon::row_closure().
7896: &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
7897: '<input name="coursename" type="text" size="30" />'.$syllabuslink.
7898: &Apache::lonhtmlcommon::row_closure().
7899: &Apache::lonhtmlcommon::row_title(&mt('Domain')).
7900: '<input name="domainid" type="hidden" />'.$domdesc.
7901: &Apache::lonhtmlcommon::row_closure().
7902: &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
7903: '<input type="file" name="upfile" size="50" />'.
7904: &Apache::lonhtmlcommon::row_closure(1).
7905: &Apache::lonhtmlcommon::end_pick_box().'<br />
7906:
7907: <input name="command" value="scantronupload_save" type="hidden" />
7908: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
7909: </form>
7910: ');
7911: return '';
7912: }
7913:
7914:
7915: sub scantron_upload_scantron_data_save {
7916: my($r,$symb)=@_;
7917: my $doanotherupload=
7918: '<br /><form action="/adm/grades" method="post">'."\n".
7919: '<input type="hidden" name="command" value="scantronupload" />'."\n".
7920: '<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
7921: '</form>'."\n";
7922: if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
7923: !&Apache::lonnet::allowed('usc',
7924: $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
7925: $r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
7926: unless ($symb) {
7927: $r->print($doanotherupload);
7928: }
7929: return '';
7930: }
7931: my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
7932: my $uploadedfile;
7933: $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
7934: if (length($env{'form.upfile'}) < 2) {
7935: $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>'));
7936: } else {
7937: my $result =
7938: &Apache::lonnet::userfileupload('upfile','','scantron','','','',
7939: $env{'form.courseid'},$env{'form.domainid'});
7940: if ($result =~ m{^/uploaded/}) {
7941: $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
7942: '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
7943: '<span class="LC_filename">'.$result.'</span>'));
7944: ($uploadedfile) = ($result =~ m{/([^/]+)$});
7945: $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
7946: $env{'form.courseid'},$uploadedfile));
7947: } else {
7948: $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
7949: '<span class="LC_error">','</span>',$result,
7950: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
7951: }
7952: }
7953: if ($symb) {
7954: $r->print(&scantron_selectphase($r,$uploadedfile,$symb));
7955: } else {
7956: $r->print($doanotherupload);
7957: }
7958: return '';
7959: }
7960:
7961: sub validate_uploaded_scantron_file {
7962: my ($cdom,$cname,$fname) = @_;
7963: my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
7964: my @lines;
7965: if ($scanlines ne '-1') {
7966: @lines=split("\n",$scanlines,-1);
7967: }
7968: my $output;
7969: if (@lines) {
7970: my (%counts,$max_match_format);
7971: my ($max_match_count,$max_match_pct) = (0,0);
7972: my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
7973: my %idmap = &username_to_idmap($classlist);
7974: foreach my $key (keys(%idmap)) {
7975: my $lckey = lc($key);
7976: $idmap{$lckey} = $idmap{$key};
7977: }
7978: my %unique_formats;
7979: my @formatlines = &get_scantronformat_file();
7980: foreach my $line (@formatlines) {
7981: chomp($line);
7982: my @config = split(/:/,$line);
7983: my $idstart = $config[5];
7984: my $idlength = $config[6];
7985: if (($idstart ne '') && ($idlength > 0)) {
7986: if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
7987: push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]);
7988: } else {
7989: $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
7990: }
7991: }
7992: }
7993: foreach my $key (keys(%unique_formats)) {
7994: my ($idstart,$idlength) = split(':',$key);
7995: %{$counts{$key}} = (
7996: 'found' => 0,
7997: 'total' => 0,
7998: );
7999: foreach my $line (@lines) {
8000: next if ($line =~ /^#/);
8001: next if ($line =~ /^[\s\cz]*$/);
8002: my $id = substr($line,$idstart-1,$idlength);
8003: $id = lc($id);
8004: if (exists($idmap{$id})) {
8005: $counts{$key}{'found'} ++;
8006: }
8007: $counts{$key}{'total'} ++;
8008: }
8009: if ($counts{$key}{'total'}) {
8010: my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
8011: if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
8012: $max_match_pct = $percent_match;
8013: $max_match_format = $key;
8014: $max_match_count = $counts{$key}{'total'};
8015: }
8016: }
8017: }
8018: if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
8019: my $format_descs;
8020: my $numwithformat = @{$unique_formats{$max_match_format}};
8021: for (my $i=0; $i<$numwithformat; $i++) {
8022: my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
8023: if ($i<$numwithformat-2) {
8024: $format_descs .= '"<i>'.$desc.'</i>", ';
8025: } elsif ($i==$numwithformat-2) {
8026: $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
8027: } elsif ($i==$numwithformat-1) {
8028: $format_descs .= '"<i>'.$desc.'</i>"';
8029: }
8030: }
8031: my $showpct = sprintf("%.0f",$max_match_pct).'%';
8032: $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).
8033: '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
8034: '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
8035: '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
8036: '<i>'.$cdom.'</i>').'</li>'.
8037: '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
8038: '<li>'.&mt('The course roster is not up to date').'</li>'.
8039: '</ul>';
8040: }
8041: } else {
8042: $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
8043: }
8044: return $output;
8045: }
8046:
8047: sub valid_file {
8048: my ($requested_file)=@_;
8049: foreach my $filename (sort(&scantron_filenames())) {
8050: if ($requested_file eq $filename) { return 1; }
8051: }
8052: return 0;
8053: }
8054:
8055: sub scantron_download_scantron_data {
8056: my ($r,$symb)=@_;
8057: my $default_form_data=&defaultFormData($symb);
8058: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
8059: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
8060: my $file=$env{'form.scantron_selectfile'};
8061: if (! &valid_file($file)) {
8062: $r->print('
8063: <p>
8064: '.&mt('The requested file name was invalid.').'
8065: </p>
8066: ');
8067: return;
8068: }
8069: my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
8070: my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
8071: my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
8072: &Apache::lonnet::allowuploaded('/adm/grades',$orig);
8073: &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
8074: &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
8075: $r->print('
8076: <p>
8077: '.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
8078: '<a href="'.$orig.'">','</a>').'
8079: </p>
8080: <p>
8081: '.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
8082: '<a href="'.$corrected.'">','</a>').'
8083: </p>
8084: <p>
8085: '.&mt('[_1]Skipped[_2], a file of records that were skipped.',
8086: '<a href="'.$skipped.'">','</a>').'
8087: </p>
8088: ');
8089: return '';
8090: }
8091:
8092: sub checkscantron_results {
8093: my ($r,$symb) = @_;
8094: if (!$symb) {return '';}
8095: my $cid = $env{'request.course.id'};
8096: my %lettdig = &letter_to_digits();
8097: my $numletts = scalar(keys(%lettdig));
8098: my $cnum = $env{'course.'.$cid.'.num'};
8099: my $cdom = $env{'course.'.$cid.'.domain'};
8100: my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
8101: my %record;
8102: my %scantron_config =
8103: &Apache::grades::get_scantron_config($env{'form.scantron_format'});
8104: my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
8105: my $classlist=&Apache::loncoursedata::get_classlist();
8106: my %idmap=&Apache::grades::username_to_idmap($classlist);
8107: my $navmap=Apache::lonnavmaps::navmap->new();
8108: unless (ref($navmap)) {
8109: $r->print(&navmap_errormsg());
8110: return '';
8111: }
8112: my $map=$navmap->getResourceByUrl($sequence);
8113: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
8114: my (%grader_partids_by_symb,%grader_randomlists_by_symb);
8115: &graders_resources_pass(\@resources,\%grader_partids_by_symb, \%grader_randomlists_by_symb);
8116:
8117: my ($uname,$udom);
8118: my (%scandata,%lastname,%bylast);
8119: $r->print('
8120: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
8121:
8122: my @delayqueue;
8123: my %completedstudents;
8124:
8125: my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
8126: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
8127: 'Progress of Bubblesheet Data/Submission Records Comparison',$count,
8128: 'inline',undef,'checkscantron');
8129: my ($username,$domain,$started);
8130: my $nav_error;
8131: &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
8132: if ($nav_error) {
8133: $r->print(&navmap_errormsg());
8134: return '';
8135: }
8136:
8137: &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
8138: 'Processing first student');
8139: my $start=&Time::HiRes::time();
8140: my $i=-1;
8141:
8142: while ($i<$scanlines->{'count'}) {
8143: ($username,$domain,$uname)=('','','');
8144: $i++;
8145: my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
8146: if ($line=~/^[\s\cz]*$/) { next; }
8147: if ($started) {
8148: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
8149: 'last student');
8150: }
8151: $started=1;
8152: my $scan_record=
8153: &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
8154: $scan_data);
8155: unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
8156: \%idmap,$i)) {
8157: &Apache::grades::scantron_add_delay(\@delayqueue,$line,
8158: 'Unable to find a student that matches',1);
8159: next;
8160: }
8161: if (exists $completedstudents{$uname}) {
8162: &Apache::grades::scantron_add_delay(\@delayqueue,$line,
8163: 'Student '.$uname.' has multiple sheets',2);
8164: next;
8165: }
8166: my $pid = $scan_record->{'scantron.ID'};
8167: $lastname{$pid} = $scan_record->{'scantron.LastName'};
8168: push(@{$bylast{$lastname{$pid}}},$pid);
8169: my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
8170: $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
8171: chomp($scandata{$pid});
8172: $scandata{$pid} =~ s/\r$//;
8173: ($username,$domain)=split(/:/,$uname);
8174: my $counter = -1;
8175: foreach my $resource (@resources) {
8176: my $parts;
8177: my $ressymb = $resource->symb();
8178: if ((exists($grader_randomlists_by_symb{$ressymb})) ||
8179: (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
8180: (my $analysis,$parts) =
8181: &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
8182: } else {
8183: $parts = $grader_partids_by_symb{$ressymb};
8184: }
8185: ($counter,my $recording) =
8186: &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
8187: $scandata{$pid},$parts,
8188: \%scantron_config,\%lettdig,$numletts);
8189: $record{$pid} .= $recording;
8190: }
8191: }
8192: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
8193: $r->print('<br />');
8194: my ($okstudents,$badstudents,$numstudents,$passed,$failed);
8195: $passed = 0;
8196: $failed = 0;
8197: $numstudents = 0;
8198: foreach my $last (sort(keys(%bylast))) {
8199: if (ref($bylast{$last}) eq 'ARRAY') {
8200: foreach my $pid (sort(@{$bylast{$last}})) {
8201: my $showscandata = $scandata{$pid};
8202: my $showrecord = $record{$pid};
8203: $showscandata =~ s/\s/ /g;
8204: $showrecord =~ s/\s/ /g;
8205: if ($scandata{$pid} eq $record{$pid}) {
8206: my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
8207: $okstudents .= '<tr class="'.$css_class.'">'.
8208: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
8209: '</tr>'."\n".
8210: '<tr class="'.$css_class.'">'."\n".
8211: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
8212: $passed ++;
8213: } else {
8214: my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
8215: $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".
8216: '</tr>'."\n".
8217: '<tr class="'.$css_class.'">'."\n".
8218: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
8219: '</tr>'."\n";
8220: $failed ++;
8221: }
8222: $numstudents ++;
8223: }
8224: }
8225: }
8226: $r->print('<p>'.&mt('Comparison of bubblesheet data (including corrections) with corresponding submission records (most recent submission) for <b>[quant,_1,student]</b> ([_2] scantron lines/student).',$numstudents,$env{'form.scantron_maxbubble'}).'</p>');
8227: $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>');
8228: if ($passed) {
8229: $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
8230: $r->print(&Apache::loncommon::start_data_table()."\n".
8231: &Apache::loncommon::start_data_table_header_row()."\n".
8232: '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
8233: &Apache::loncommon::end_data_table_header_row()."\n".
8234: $okstudents."\n".
8235: &Apache::loncommon::end_data_table().'<br />');
8236: }
8237: if ($failed) {
8238: $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
8239: $r->print(&Apache::loncommon::start_data_table()."\n".
8240: &Apache::loncommon::start_data_table_header_row()."\n".
8241: '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
8242: &Apache::loncommon::end_data_table_header_row()."\n".
8243: $badstudents."\n".
8244: &Apache::loncommon::end_data_table()).'<br />'.
8245: &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.');
8246: }
8247: $r->print('</form><br />');
8248: return;
8249: }
8250:
8251: sub verify_scantron_grading {
8252: my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
8253: $scantron_config,$lettdig,$numletts) = @_;
8254: my ($record,%expected,%startpos);
8255: return ($counter,$record) if (!ref($resource));
8256: return ($counter,$record) if (!$resource->is_problem());
8257: my $symb = $resource->symb();
8258: return ($counter,$record) if (ref($partids) ne 'ARRAY');
8259: foreach my $part_id (@{$partids}) {
8260: $counter ++;
8261: $expected{$part_id} = 0;
8262: if ($env{"form.scantron.sub_bubblelines.$counter"}) {
8263: my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
8264: foreach my $item (@sub_lines) {
8265: $expected{$part_id} += $item;
8266: }
8267: } else {
8268: $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
8269: }
8270: $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
8271: }
8272: if ($symb) {
8273: my %recorded;
8274: my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
8275: if ($returnhash{'version'}) {
8276: my %lasthash=();
8277: my $version;
8278: for ($version=1;$version<=$returnhash{'version'};$version++) {
8279: foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
8280: $lasthash{$key}=$returnhash{$version.':'.$key};
8281: }
8282: }
8283: foreach my $key (keys(%lasthash)) {
8284: if ($key =~ /\.scantron$/) {
8285: my $value = &unescape($lasthash{$key});
8286: my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
8287: if ($value eq '') {
8288: for (my $i=0; $i<$expected{$part_id}; $i++) {
8289: for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
8290: $recorded{$part_id} .= $scantron_config->{'Qoff'};
8291: }
8292: }
8293: } else {
8294: my @tocheck;
8295: my @items = split(//,$value);
8296: if (($scantron_config->{'Qon'} eq 'letter') ||
8297: ($scantron_config->{'Qon'} eq 'number')) {
8298: if (@items < $expected{$part_id}) {
8299: my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
8300: my @singles = split(//,$fragment);
8301: foreach my $pos (@singles) {
8302: if ($pos eq ' ') {
8303: push(@tocheck,$pos);
8304: } else {
8305: my $next = shift(@items);
8306: push(@tocheck,$next);
8307: }
8308: }
8309: } else {
8310: @tocheck = @items;
8311: }
8312: foreach my $letter (@tocheck) {
8313: if ($scantron_config->{'Qon'} eq 'letter') {
8314: if ($letter !~ /^[A-J]$/) {
8315: $letter = $scantron_config->{'Qoff'};
8316: }
8317: $recorded{$part_id} .= $letter;
8318: } elsif ($scantron_config->{'Qon'} eq 'number') {
8319: my $digit;
8320: if ($letter !~ /^[A-J]$/) {
8321: $digit = $scantron_config->{'Qoff'};
8322: } else {
8323: $digit = $lettdig->{$letter};
8324: }
8325: $recorded{$part_id} .= $digit;
8326: }
8327: }
8328: } else {
8329: @tocheck = @items;
8330: for (my $i=0; $i<$expected{$part_id}; $i++) {
8331: my $curr_sub = shift(@tocheck);
8332: my $digit;
8333: if ($curr_sub =~ /^[A-J]$/) {
8334: $digit = $lettdig->{$curr_sub}-1;
8335: }
8336: if ($curr_sub eq 'J') {
8337: $digit += scalar($numletts);
8338: }
8339: for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
8340: if ($j == $digit) {
8341: $recorded{$part_id} .= $scantron_config->{'Qon'};
8342: } else {
8343: $recorded{$part_id} .= $scantron_config->{'Qoff'};
8344: }
8345: }
8346: }
8347: }
8348: }
8349: }
8350: }
8351: }
8352: foreach my $part_id (@{$partids}) {
8353: if ($recorded{$part_id} eq '') {
8354: for (my $i=0; $i<$expected{$part_id}; $i++) {
8355: for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
8356: $recorded{$part_id} .= $scantron_config->{'Qoff'};
8357: }
8358: }
8359: }
8360: $record .= $recorded{$part_id};
8361: }
8362: }
8363: return ($counter,$record);
8364: }
8365:
8366: sub letter_to_digits {
8367: my %lettdig = (
8368: A => 1,
8369: B => 2,
8370: C => 3,
8371: D => 4,
8372: E => 5,
8373: F => 6,
8374: G => 7,
8375: H => 8,
8376: I => 9,
8377: J => 0,
8378: );
8379: return %lettdig;
8380: }
8381:
8382:
8383: #-------- end of section for handling grading scantron forms -------
8384: #
8385: #-------------------------------------------------------------------
8386:
8387: #-------------------------- Menu interface -------------------------
8388: #
8389: #--- Href with symb and command ---
8390:
8391: sub href_symb_cmd {
8392: my ($symb,$cmd)=@_;
8393: return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&command='.$cmd;
8394: }
8395:
8396: sub grading_menu {
8397: my ($request,$symb) = @_;
8398: if (!$symb) {return '';}
8399:
8400: my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
8401: 'command'=>'individual');
8402:
8403: my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
8404:
8405: $fields{'command'}='ungraded';
8406: my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
8407:
8408: $fields{'command'}='table';
8409: my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
8410:
8411: $fields{'command'}='all_for_one';
8412: my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
8413:
8414: $fields{'command'}='downloadfilesselect';
8415: my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
8416:
8417: $fields{'command'} = 'csvform';
8418: my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
8419:
8420: $fields{'command'} = 'processclicker';
8421: my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
8422:
8423: $fields{'command'} = 'scantron_selectphase';
8424: my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
8425:
8426: $fields{'command'} = 'initialverifyreceipt';
8427: my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
8428:
8429: my @menu = ({ categorytitle=>'Hand Grading',
8430: items =>[
8431: { linktext => 'Select individual students to grade',
8432: url => $url1a,
8433: permission => 'F',
8434: icon => 'grade_students.png',
8435: linktitle => 'Grade current resource for a selection of students.'
8436: },
8437: { linktext => 'Grade ungraded submissions.',
8438: url => $url1b,
8439: permission => 'F',
8440: icon => 'ungrade_sub.png',
8441: linktitle => 'Grade all submissions that have not been graded yet.'
8442: },
8443:
8444: { linktext => 'Grading table',
8445: url => $url1c,
8446: permission => 'F',
8447: icon => 'grading_table.png',
8448: linktitle => 'Grade current resource for all students.'
8449: },
8450: { linktext => 'Grade page/folder for one student',
8451: url => $url1d,
8452: permission => 'F',
8453: icon => 'grade_PageFolder.png',
8454: linktitle => 'Grade all resources in current page/sequence/folder for one student.'
8455: },
8456: { linktext => 'Download submissions',
8457: url => $url1e,
8458: permission => 'F',
8459: icon => 'download_sub.png',
8460: linktitle => 'Download all students submissions.'
8461: }]},
8462: { categorytitle=>'Automated Grading',
8463: items =>[
8464:
8465: { linktext => 'Upload Scores',
8466: url => $url2,
8467: permission => 'F',
8468: icon => 'uploadscores.png',
8469: linktitle => 'Specify a file containing the class scores for current resource.'
8470: },
8471: { linktext => 'Process Clicker',
8472: url => $url3,
8473: permission => 'F',
8474: icon => 'addClickerInfoFile.png',
8475: linktitle => 'Specify a file containing the clicker information for this resource.'
8476: },
8477: { linktext => 'Grade/Manage/Review Bubblesheets',
8478: url => $url4,
8479: permission => 'F',
8480: icon => 'bubblesheet.png',
8481: linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
8482: },
8483: { linktext => 'Verify Receipt Number',
8484: url => $url5,
8485: permission => 'F',
8486: icon => 'receipt_number.png',
8487: linktitle => 'Verify a system-generated receipt number for correct problem solution.'
8488: }
8489:
8490: ]
8491: });
8492:
8493: # Create the menu
8494: my $Str;
8495: $Str .= '<form method="post" action="" name="gradingMenu">';
8496: $Str .= '<input type="hidden" name="command" value="" />'.
8497: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
8498:
8499: $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
8500: return $Str;
8501: }
8502:
8503:
8504: sub ungraded {
8505: my ($request)=@_;
8506: &submit_options($request);
8507: }
8508:
8509: sub submit_options_sequence {
8510: my ($request,$symb) = @_;
8511: if (!$symb) {return '';}
8512: &commonJSfunctions($request);
8513: my $result;
8514:
8515: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
8516: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
8517: $result.=&selectfield(0).
8518: '<input type="hidden" name="command" value="pickStudentPage" />
8519: <div>
8520: <input type="submit" value="'.&mt('Next').' →" />
8521: </div>
8522: </div>
8523: </form>';
8524: return $result;
8525: }
8526:
8527: sub submit_options_table {
8528: my ($request,$symb) = @_;
8529: if (!$symb) {return '';}
8530: &commonJSfunctions($request);
8531: my $result;
8532:
8533: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
8534: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
8535:
8536: $result.=&selectfield(0).
8537: '<input type="hidden" name="command" value="viewgrades" />
8538: <div>
8539: <input type="submit" value="'.&mt('Next').' →" />
8540: </div>
8541: </div>
8542: </form>';
8543: return $result;
8544: }
8545:
8546: sub submit_options_download {
8547: my ($request,$symb) = @_;
8548: if (!$symb) {return '';}
8549:
8550: &commonJSfunctions($request);
8551:
8552: my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
8553: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
8554: $result.='
8555: <h2>
8556: '.&mt('Select Students for Which to Download Submissions').'
8557: </h2>'.&selectfield(1).'
8558: <input type="hidden" name="command" value="downloadfileslink" />
8559: <input type="submit" value="'.&mt('Next').' →" />
8560: </div>
8561: </div>
8562:
8563:
8564: </form>';
8565: return $result;
8566: }
8567:
8568: #--- Displays the submissions first page -------
8569: sub submit_options {
8570: my ($request,$symb) = @_;
8571: if (!$symb) {return '';}
8572:
8573: &commonJSfunctions($request);
8574: my $result;
8575:
8576: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
8577: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
8578: $result.=&selectfield(1).'
8579: <input type="hidden" name="command" value="submission" />
8580: <input type="submit" value="'.&mt('Next').' →" />
8581: </div>
8582: </div>
8583:
8584:
8585: </form>';
8586: return $result;
8587: }
8588:
8589: sub selectfield {
8590: my ($full)=@_;
8591: my %options =
8592: (&Apache::lonlocal::texthash(
8593: 'yes' => 'with submissions',
8594: 'queued' => 'in grading queue',
8595: 'graded' => 'with ungraded submissions',
8596: 'incorrect' => 'with incorrect submissions',
8597: 'all' => 'with any status'),
8598: 'select_form_order' => ['yes','queued','graded','incorrect','all']);
8599: my $result='<div class="LC_columnSection">
8600:
8601: <fieldset>
8602: <legend>
8603: '.&mt('Sections').'
8604: </legend>
8605: '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
8606: </fieldset>
8607:
8608: <fieldset>
8609: <legend>
8610: '.&mt('Groups').'
8611: </legend>
8612: '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
8613: </fieldset>
8614:
8615: <fieldset>
8616: <legend>
8617: '.&mt('Access Status').'
8618: </legend>
8619: '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
8620: </fieldset>';
8621: if ($full) {
8622: $result.='
8623: <fieldset>
8624: <legend>
8625: '.&mt('Submission Status').'
8626: </legend>'.
8627: &Apache::loncommon::select_form('all','submitonly',\%options).
8628: '</fieldset>';
8629: }
8630: $result.='</div><br />';
8631: return $result;
8632: }
8633:
8634: sub reset_perm {
8635: undef(%perm);
8636: }
8637:
8638: sub init_perm {
8639: &reset_perm();
8640: foreach my $test_perm ('vgr','mgr','opa') {
8641:
8642: my $scope = $env{'request.course.id'};
8643: if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
8644:
8645: $scope .= '/'.$env{'request.course.sec'};
8646: if ( $perm{$test_perm}=
8647: &Apache::lonnet::allowed($test_perm,$scope)) {
8648: $perm{$test_perm.'_section'}=$env{'request.course.sec'};
8649: } else {
8650: delete($perm{$test_perm});
8651: }
8652: }
8653: }
8654: }
8655:
8656: sub gather_clicker_ids {
8657: my %clicker_ids;
8658:
8659: my $classlist = &Apache::loncoursedata::get_classlist();
8660:
8661: # Set up a couple variables.
8662: my $username_idx = &Apache::loncoursedata::CL_SNAME();
8663: my $domain_idx = &Apache::loncoursedata::CL_SDOM();
8664: my $status_idx = &Apache::loncoursedata::CL_STATUS();
8665:
8666: foreach my $student (keys(%$classlist)) {
8667: if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
8668: my $username = $classlist->{$student}->[$username_idx];
8669: my $domain = $classlist->{$student}->[$domain_idx];
8670: my $clickers =
8671: (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
8672: foreach my $id (split(/\,/,$clickers)) {
8673: $id=~s/^[\#0]+//;
8674: $id=~s/[\-\:]//g;
8675: if (exists($clicker_ids{$id})) {
8676: $clicker_ids{$id}.=','.$username.':'.$domain;
8677: } else {
8678: $clicker_ids{$id}=$username.':'.$domain;
8679: }
8680: }
8681: }
8682: return %clicker_ids;
8683: }
8684:
8685: sub gather_adv_clicker_ids {
8686: my %clicker_ids;
8687: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
8688: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
8689: my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
8690: foreach my $element (sort(keys(%coursepersonnel))) {
8691: foreach my $person (split(/\,/,$coursepersonnel{$element})) {
8692: my ($puname,$pudom)=split(/\:/,$person);
8693: my $clickers =
8694: (&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
8695: foreach my $id (split(/\,/,$clickers)) {
8696: $id=~s/^[\#0]+//;
8697: $id=~s/[\-\:]//g;
8698: if (exists($clicker_ids{$id})) {
8699: $clicker_ids{$id}.=','.$puname.':'.$pudom;
8700: } else {
8701: $clicker_ids{$id}=$puname.':'.$pudom;
8702: }
8703: }
8704: }
8705: }
8706: return %clicker_ids;
8707: }
8708:
8709: sub clicker_grading_parameters {
8710: return ('gradingmechanism' => 'scalar',
8711: 'upfiletype' => 'scalar',
8712: 'specificid' => 'scalar',
8713: 'pcorrect' => 'scalar',
8714: 'pincorrect' => 'scalar');
8715: }
8716:
8717: sub process_clicker {
8718: my ($r,$symb)=@_;
8719: if (!$symb) {return '';}
8720: my $result=&checkforfile_js();
8721: $result.=&Apache::loncommon::start_data_table().
8722: &Apache::loncommon::start_data_table_header_row().
8723: '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
8724: &Apache::loncommon::end_data_table_header_row().
8725: &Apache::loncommon::start_data_table_row()."<td>\n";
8726: # Attempt to restore parameters from last session, set defaults if not present
8727: my %Saveable_Parameters=&clicker_grading_parameters();
8728: &Apache::loncommon::restore_course_settings('grades_clicker',
8729: \%Saveable_Parameters);
8730: if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
8731: if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
8732: if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
8733: if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
8734:
8735: my %checked;
8736: foreach my $gradingmechanism ('attendance','personnel','specific','given') {
8737: if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
8738: $checked{$gradingmechanism}=' checked="checked"';
8739: }
8740: }
8741:
8742: my $upload=&mt("Evaluate File");
8743: my $type=&mt("Type");
8744: my $attendance=&mt("Award points just for participation");
8745: my $personnel=&mt("Correctness determined from response by course personnel");
8746: my $specific=&mt("Correctness determined from response with clicker ID(s)");
8747: my $given=&mt("Correctness determined from given list of answers").' '.
8748: '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
8749: my $pcorrect=&mt("Percentage points for correct solution");
8750: my $pincorrect=&mt("Percentage points for incorrect solution");
8751: my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
8752: {'iclicker' => 'i>clicker',
8753: 'interwrite' => 'interwrite PRS'});
8754: $symb = &Apache::lonenc::check_encrypt($symb);
8755: $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
8756: function sanitycheck() {
8757: // Accept only integer percentages
8758: document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
8759: document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
8760: // Find out grading choice
8761: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
8762: if (document.forms.gradesupload.gradingmechanism[i].checked) {
8763: gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
8764: }
8765: }
8766: // By default, new choice equals user selection
8767: newgradingchoice=gradingchoice;
8768: // Not good to give more points for false answers than correct ones
8769: if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
8770: document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
8771: }
8772: // If new choice is attendance only, and old choice was correctness-based, restore defaults
8773: if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
8774: document.forms.gradesupload.pcorrect.value=100;
8775: document.forms.gradesupload.pincorrect.value=100;
8776: }
8777: // If the values are different, cannot be attendance only
8778: if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
8779: (gradingchoice=='attendance')) {
8780: newgradingchoice='personnel';
8781: }
8782: // Change grading choice to new one
8783: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
8784: if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
8785: document.forms.gradesupload.gradingmechanism[i].checked=true;
8786: } else {
8787: document.forms.gradesupload.gradingmechanism[i].checked=false;
8788: }
8789: }
8790: // Remember the old state
8791: document.forms.gradesupload.waschecked.value=newgradingchoice;
8792: }
8793: ENDUPFORM
8794: $result.= <<ENDUPFORM;
8795: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
8796: <input type="hidden" name="symb" value="$symb" />
8797: <input type="hidden" name="command" value="processclickerfile" />
8798: <input type="file" name="upfile" size="50" />
8799: <br /><label>$type: $selectform</label>
8800: ENDUPFORM
8801: $result.='</td>'.&Apache::loncommon::end_data_table_row().
8802: &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
8803: <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
8804: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
8805: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
8806: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
8807: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
8808: <br />
8809: <input type="text" name="givenanswer" size="50" />
8810: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
8811: ENDGRADINGFORM
8812: $result.='</td>'.&Apache::loncommon::end_data_table_row().
8813: &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
8814: <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
8815: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
8816: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
8817: </form>'
8818: ENDPERCFORM
8819: $result.='</td>'.
8820: &Apache::loncommon::end_data_table_row().
8821: &Apache::loncommon::end_data_table();
8822: return $result;
8823: }
8824:
8825: sub process_clicker_file {
8826: my ($r,$symb)=@_;
8827: if (!$symb) {return '';}
8828:
8829: my %Saveable_Parameters=&clicker_grading_parameters();
8830: &Apache::loncommon::store_course_settings('grades_clicker',
8831: \%Saveable_Parameters);
8832: my $result='';
8833: if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
8834: $result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
8835: return $result;
8836: }
8837: if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
8838: $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
8839: return $result;
8840: }
8841: my $foundgiven=0;
8842: if ($env{'form.gradingmechanism'} eq 'given') {
8843: $env{'form.givenanswer'}=~s/^\s*//gs;
8844: $env{'form.givenanswer'}=~s/\s*$//gs;
8845: $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
8846: $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
8847: my @answers=split(/\,/,$env{'form.givenanswer'});
8848: $foundgiven=$#answers+1;
8849: }
8850: my %clicker_ids=&gather_clicker_ids();
8851: my %correct_ids;
8852: if ($env{'form.gradingmechanism'} eq 'personnel') {
8853: %correct_ids=&gather_adv_clicker_ids();
8854: }
8855: if ($env{'form.gradingmechanism'} eq 'specific') {
8856: foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
8857: $correct_id=~tr/a-z/A-Z/;
8858: $correct_id=~s/\s//gs;
8859: $correct_id=~s/^[\#0]+//;
8860: $correct_id=~s/[\-\:]//g;
8861: if ($correct_id) {
8862: $correct_ids{$correct_id}='specified';
8863: }
8864: }
8865: }
8866: if ($env{'form.gradingmechanism'} eq 'attendance') {
8867: $result.=&mt('Score based on attendance only');
8868: } elsif ($env{'form.gradingmechanism'} eq 'given') {
8869: $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
8870: } else {
8871: my $number=0;
8872: $result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
8873: foreach my $id (sort(keys(%correct_ids))) {
8874: $result.='<br /><tt>'.$id.'</tt> - ';
8875: if ($correct_ids{$id} eq 'specified') {
8876: $result.=&mt('specified');
8877: } else {
8878: my ($uname,$udom)=split(/\:/,$correct_ids{$id});
8879: $result.=&Apache::loncommon::plainname($uname,$udom);
8880: }
8881: $number++;
8882: }
8883: $result.="</p>\n";
8884: if ($number==0) {
8885: $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
8886: return $result;
8887: }
8888: }
8889: if (length($env{'form.upfile'}) < 2) {
8890: $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
8891: '<span class="LC_error">',
8892: '</span>',
8893: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
8894: return $result;
8895: }
8896:
8897: # Were able to get all the info needed, now analyze the file
8898:
8899: $result.=&Apache::loncommon::studentbrowser_javascript();
8900: $symb = &Apache::lonenc::check_encrypt($symb);
8901: $result.=&Apache::loncommon::start_data_table().
8902: &Apache::loncommon::start_data_table_header_row().
8903: '<th>'.&mt('Evaluate clicker file').'</th>'.
8904: &Apache::loncommon::end_data_table_header_row().
8905: &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
8906: <td>
8907: <form method="post" action="/adm/grades" name="clickeranalysis">
8908: <input type="hidden" name="symb" value="$symb" />
8909: <input type="hidden" name="command" value="assignclickergrades" />
8910: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
8911: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
8912: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
8913: ENDHEADER
8914: if ($env{'form.gradingmechanism'} eq 'given') {
8915: $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
8916: }
8917: my %responses;
8918: my @questiontitles;
8919: my $errormsg='';
8920: my $number=0;
8921: if ($env{'form.upfiletype'} eq 'iclicker') {
8922: ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
8923: }
8924: if ($env{'form.upfiletype'} eq 'interwrite') {
8925: ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
8926: }
8927: $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
8928: '<input type="hidden" name="number" value="'.$number.'" />'.
8929: &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
8930: $env{'form.pcorrect'},$env{'form.pincorrect'}).
8931: '<br />';
8932: if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
8933: $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
8934: return $result;
8935: }
8936: # Remember Question Titles
8937: # FIXME: Possibly need delimiter other than ":"
8938: for (my $i=0;$i<$number;$i++) {
8939: $result.='<input type="hidden" name="question:'.$i.'" value="'.
8940: &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
8941: }
8942: my $correct_count=0;
8943: my $student_count=0;
8944: my $unknown_count=0;
8945: # Match answers with usernames
8946: # FIXME: Possibly need delimiter other than ":"
8947: foreach my $id (keys(%responses)) {
8948: if ($correct_ids{$id}) {
8949: $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
8950: $correct_count++;
8951: } elsif ($clicker_ids{$id}) {
8952: if ($clicker_ids{$id}=~/\,/) {
8953: # More than one user with the same clicker!
8954: $result.="</td>".&Apache::loncommon::end_data_table_row().
8955: &Apache::loncommon::start_data_table_row()."<td>".
8956: &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
8957: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
8958: "<select name='multi".$id."'>";
8959: foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
8960: $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
8961: }
8962: $result.='</select>';
8963: $unknown_count++;
8964: } else {
8965: # Good: found one and only one user with the right clicker
8966: $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
8967: $student_count++;
8968: }
8969: } else {
8970: $result.="</td>".&Apache::loncommon::end_data_table_row().
8971: &Apache::loncommon::start_data_table_row()."<td>".
8972: &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
8973: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
8974: "\n".&mt("Username").": <input type='text' name='uname".$id."' /> ".
8975: "\n".&mt("Domain").": ".
8976: &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).' '.
8977: &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
8978: $unknown_count++;
8979: }
8980: }
8981: $result.='<hr />'.
8982: &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
8983: if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
8984: if ($correct_count==0) {
8985: $errormsg.="Found no correct answers answers for grading!";
8986: } elsif ($correct_count>1) {
8987: $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
8988: }
8989: }
8990: if ($number<1) {
8991: $errormsg.="Found no questions.";
8992: }
8993: if ($errormsg) {
8994: $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
8995: } else {
8996: $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
8997: }
8998: $result.='</form></td>'.
8999: &Apache::loncommon::end_data_table_row().
9000: &Apache::loncommon::end_data_table();
9001: return $result;
9002: }
9003:
9004: sub iclicker_eval {
9005: my ($questiontitles,$responses)=@_;
9006: my $number=0;
9007: my $errormsg='';
9008: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
9009: my %components=&Apache::loncommon::record_sep($line);
9010: my @entries=map {$components{$_}} (sort(keys(%components)));
9011: if ($entries[0] eq 'Question') {
9012: for (my $i=3;$i<$#entries;$i+=6) {
9013: $$questiontitles[$number]=$entries[$i];
9014: $number++;
9015: }
9016: }
9017: if ($entries[0]=~/^\#/) {
9018: my $id=$entries[0];
9019: my @idresponses;
9020: $id=~s/^[\#0]+//;
9021: for (my $i=0;$i<$number;$i++) {
9022: my $idx=3+$i*6;
9023: push(@idresponses,$entries[$idx]);
9024: }
9025: $$responses{$id}=join(',',@idresponses);
9026: }
9027: }
9028: return ($errormsg,$number);
9029: }
9030:
9031: sub interwrite_eval {
9032: my ($questiontitles,$responses)=@_;
9033: my $number=0;
9034: my $errormsg='';
9035: my $skipline=1;
9036: my $questionnumber=0;
9037: my %idresponses=();
9038: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
9039: my %components=&Apache::loncommon::record_sep($line);
9040: my @entries=map {$components{$_}} (sort(keys(%components)));
9041: if ($entries[1] eq 'Time') { $skipline=0; next; }
9042: if ($entries[1] eq 'Response') { $skipline=1; }
9043: next if $skipline;
9044: if ($entries[0]!=$questionnumber) {
9045: $questionnumber=$entries[0];
9046: $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
9047: $number++;
9048: }
9049: my $id=$entries[4];
9050: $id=~s/^[\#0]+//;
9051: $id=~s/^v\d*\://i;
9052: $id=~s/[\-\:]//g;
9053: $idresponses{$id}[$number]=$entries[6];
9054: }
9055: foreach my $id (keys(%idresponses)) {
9056: $$responses{$id}=join(',',@{$idresponses{$id}});
9057: $$responses{$id}=~s/^\s*\,//;
9058: }
9059: return ($errormsg,$number);
9060: }
9061:
9062: sub assign_clicker_grades {
9063: my ($r,$symb)=@_;
9064: if (!$symb) {return '';}
9065: # See which part we are saving to
9066: my $res_error;
9067: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
9068: if ($res_error) {
9069: return &navmap_errormsg();
9070: }
9071: # FIXME: This should probably look for the first handgradeable part
9072: my $part=$$partlist[0];
9073: # Start screen output
9074: my $result=&Apache::loncommon::start_data_table().
9075: &Apache::loncommon::start_data_table_header_row().
9076: '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
9077: &Apache::loncommon::end_data_table_header_row().
9078: &Apache::loncommon::start_data_table_row().'<td>';
9079: # Get correct result
9080: # FIXME: Possibly need delimiter other than ":"
9081: my @correct=();
9082: my $gradingmechanism=$env{'form.gradingmechanism'};
9083: my $number=$env{'form.number'};
9084: if ($gradingmechanism ne 'attendance') {
9085: foreach my $key (keys(%env)) {
9086: if ($key=~/^form\.correct\:/) {
9087: my @input=split(/\,/,$env{$key});
9088: for (my $i=0;$i<=$#input;$i++) {
9089: if (($correct[$i]) && ($input[$i]) &&
9090: ($correct[$i] ne $input[$i])) {
9091: $result.='<br /><span class="LC_warning">'.
9092: &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
9093: $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
9094: } elsif ($input[$i]) {
9095: $correct[$i]=$input[$i];
9096: }
9097: }
9098: }
9099: }
9100: for (my $i=0;$i<$number;$i++) {
9101: if (!$correct[$i]) {
9102: $result.='<br /><span class="LC_error">'.
9103: &mt('No correct result given for question "[_1]"!',
9104: $env{'form.question:'.$i}).'</span>';
9105: }
9106: }
9107: $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
9108: }
9109: # Start grading
9110: my $pcorrect=$env{'form.pcorrect'};
9111: my $pincorrect=$env{'form.pincorrect'};
9112: my $storecount=0;
9113: my %users=();
9114: foreach my $key (keys(%env)) {
9115: my $user='';
9116: if ($key=~/^form\.student\:(.*)$/) {
9117: $user=$1;
9118: }
9119: if ($key=~/^form\.unknown\:(.*)$/) {
9120: my $id=$1;
9121: if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
9122: $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
9123: } elsif ($env{'form.multi'.$id}) {
9124: $user=$env{'form.multi'.$id};
9125: }
9126: }
9127: if ($user) {
9128: if ($users{$user}) {
9129: $result.='<br /><span class="LC_warning">'.
9130: &mt("More than one entry found for <tt>[_1]</tt>!",$user).
9131: '</span><br />';
9132: }
9133: $users{$user}=1;
9134: my @answer=split(/\,/,$env{$key});
9135: my $sum=0;
9136: my $realnumber=$number;
9137: for (my $i=0;$i<$number;$i++) {
9138: if ($correct[$i] eq '-') {
9139: $realnumber--;
9140: } elsif ($answer[$i]) {
9141: if ($gradingmechanism eq 'attendance') {
9142: $sum+=$pcorrect;
9143: } elsif ($correct[$i] eq '*') {
9144: $sum+=$pcorrect;
9145: } else {
9146: if ($answer[$i] eq $correct[$i]) {
9147: $sum+=$pcorrect;
9148: } else {
9149: $sum+=$pincorrect;
9150: }
9151: }
9152: }
9153: }
9154: my $ave=$sum/(100*$realnumber);
9155: # Store
9156: my ($username,$domain)=split(/\:/,$user);
9157: my %grades=();
9158: $grades{"resource.$part.solved"}='correct_by_override';
9159: $grades{"resource.$part.awarded"}=$ave;
9160: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
9161: my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
9162: $env{'request.course.id'},
9163: $domain,$username);
9164: if ($returncode ne 'ok') {
9165: $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
9166: } else {
9167: $storecount++;
9168: }
9169: }
9170: }
9171: # We are done
9172: $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
9173: '</td>'.
9174: &Apache::loncommon::end_data_table_row().
9175: &Apache::loncommon::end_data_table();
9176: return $result;
9177: }
9178:
9179: sub navmap_errormsg {
9180: return '<div class="LC_error">'.
9181: &mt('An error occurred retrieving information about resources in the course.').'<br />'.
9182: &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>').
9183: '</div>';
9184: }
9185:
9186: sub startpage {
9187: my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag) = @_;
9188: unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
9189: $r->print(&Apache::loncommon::start_page('Grading',undef,
9190: {'bread_crumbs' => $crumbs}));
9191: &Apache::lonquickgrades::startGradeScreen($r,'grading');
9192: unless ($nodisplayflag) {
9193: $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag));
9194: }
9195: }
9196:
9197: sub select_problem {
9198: my ($r)=@_;
9199: $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
9200: $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
9201: $r->print('<input type="hidden" name="command" value="gradingmenu" />');
9202: $r->print('<input type="submit" value="'.&mt('Next').' →" /></form>');
9203: }
9204:
9205: sub handler {
9206: my $request=$_[0];
9207: &reset_caches();
9208: if ($env{'browser.mathml'}) {
9209: &Apache::loncommon::content_type($request,'text/xml');
9210: } else {
9211: &Apache::loncommon::content_type($request,'text/html');
9212: }
9213: $request->send_http_header;
9214: return '' if $request->header_only;
9215: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
9216:
9217: # see what command we need to execute
9218:
9219: my @commands=&Apache::loncommon::get_env_multiple('form.command');
9220: my $command=$commands[0];
9221:
9222: if ($#commands > 0) {
9223: &Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
9224: }
9225:
9226: # see what the symb is
9227:
9228: my $symb=$env{'form.symb'};
9229: unless ($symb) {
9230: (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
9231: $symb=&Apache::lonnet::symbread($url);
9232: }
9233: &Apache::lonenc::check_decrypt(\$symb);
9234:
9235: $ssi_error = 0;
9236: if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
9237: #
9238: # Not called from a resource, but inside a course
9239: #
9240: &startpage($request,undef,[],1,1);
9241: &select_problem($request);
9242: } else {
9243: &init_perm();
9244: if ($command eq 'submission' && $perm{'vgr'}) {
9245: &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}]);
9246: ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
9247: } elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
9248: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
9249: {href=>'',text=>'Select student'}],1,1);
9250: &pickStudentPage($request,$symb);
9251: } elsif ($command eq 'displayPage' && $perm{'vgr'}) {
9252: &startpage($request,$symb,
9253: [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
9254: {href=>'',text=>'Select student'},
9255: {href=>'',text=>'Grade student'}],1,1);
9256: &displayPage($request,$symb);
9257: } elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
9258: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
9259: {href=>'',text=>'Select student'},
9260: {href=>'',text=>'Grade student'},
9261: {href=>'',text=>'Store grades'}],1,1);
9262: &updateGradeByPage($request,$symb);
9263: } elsif ($command eq 'processGroup' && $perm{'vgr'}) {
9264: &startpage($request,$symb,[{href=>'',text=>'...'},
9265: {href=>'',text=>'Modify grades'}]);
9266: &processGroup($request,$symb);
9267: } elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
9268: &startpage($request,$symb);
9269: $request->print(&grading_menu($request,$symb));
9270: } elsif ($command eq 'individual' && $perm{'vgr'}) {
9271: &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
9272: $request->print(&submit_options($request,$symb));
9273: } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
9274: &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
9275: $request->print(&listStudents($request,$symb,'graded'));
9276: } elsif ($command eq 'table' && $perm{'vgr'}) {
9277: &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
9278: $request->print(&submit_options_table($request,$symb));
9279: } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
9280: &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
9281: $request->print(&submit_options_sequence($request,$symb));
9282: } elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
9283: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
9284: $request->print(&viewgrades($request,$symb));
9285: } elsif ($command eq 'handgrade' && $perm{'mgr'}) {
9286: &startpage($request,$symb,[{href=>'',text=>'...'},
9287: {href=>'',text=>'Store grades'}]);
9288: $request->print(&processHandGrade($request,$symb));
9289: } elsif ($command eq 'editgrades' && $perm{'mgr'}) {
9290: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
9291: {href=>&href_symb_cmd($symb,'viewgrades').'&group=all§ion=all&Status=Active',
9292: text=>"Modify grades"},
9293: {href=>'', text=>"Store grades"}]);
9294: $request->print(&editgrades($request,$symb));
9295: } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
9296: &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
9297: $request->print(&initialverifyreceipt($request,$symb));
9298: } elsif ($command eq 'verify' && $perm{'vgr'}) {
9299: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
9300: {href=>'',text=>'Verification Result'}]);
9301: $request->print(&verifyreceipt($request,$symb));
9302: } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
9303: &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
9304: $request->print(&process_clicker($request,$symb));
9305: } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
9306: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
9307: {href=>'', text=>'Process clicker file'}]);
9308: $request->print(&process_clicker_file($request,$symb));
9309: } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
9310: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
9311: {href=>'', text=>'Process clicker file'},
9312: {href=>'', text=>'Store grades'}]);
9313: $request->print(&assign_clicker_grades($request,$symb));
9314: } elsif ($command eq 'csvform' && $perm{'mgr'}) {
9315: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
9316: $request->print(&upcsvScores_form($request,$symb));
9317: } elsif ($command eq 'csvupload' && $perm{'mgr'}) {
9318: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
9319: $request->print(&csvupload($request,$symb));
9320: } elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
9321: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
9322: $request->print(&csvuploadmap($request,$symb));
9323: } elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
9324: if ($env{'form.associate'} ne 'Reverse Association') {
9325: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
9326: $request->print(&csvuploadoptions($request,$symb));
9327: } else {
9328: if ( $env{'form.upfile_associate'} ne 'reverse' ) {
9329: $env{'form.upfile_associate'} = 'reverse';
9330: } else {
9331: $env{'form.upfile_associate'} = 'forward';
9332: }
9333: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
9334: $request->print(&csvuploadmap($request,$symb));
9335: }
9336: } elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
9337: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
9338: $request->print(&csvuploadassign($request,$symb));
9339: } elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
9340: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9341: $request->print(&scantron_selectphase($request,undef,$symb));
9342: } elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
9343: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9344: $request->print(&scantron_do_warning($request,$symb));
9345: } elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
9346: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9347: $request->print(&scantron_validate_file($request,$symb));
9348: } elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
9349: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9350: $request->print(&scantron_process_students($request,$symb));
9351: } elsif ($command eq 'scantronupload' &&
9352: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
9353: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
9354: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9355: $request->print(&scantron_upload_scantron_data($request,$symb));
9356: } elsif ($command eq 'scantronupload_save' &&
9357: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
9358: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
9359: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9360: $request->print(&scantron_upload_scantron_data_save($request,$symb));
9361: } elsif ($command eq 'scantron_download' &&
9362: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
9363: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9364: $request->print(&scantron_download_scantron_data($request,$symb));
9365: } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
9366: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9367: $request->print(&checkscantron_results($request,$symb));
9368: } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
9369: &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
9370: $request->print(&submit_options_download($request,$symb));
9371: } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
9372: &startpage($request,$symb,
9373: [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
9374: {href=>'', text=>'Download submissions'}]);
9375: &submit_download_link($request,$symb);
9376: } elsif ($command) {
9377: &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
9378: $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
9379: }
9380: }
9381: if ($ssi_error) {
9382: &ssi_print_error($request);
9383: }
9384: &Apache::lonquickgrades::endGradeScreen($request);
9385: $request->print(&Apache::loncommon::end_page());
9386: &reset_caches();
9387: return '';
9388: }
9389:
9390: 1;
9391:
9392: __END__;
9393:
9394:
9395: =head1 NAME
9396:
9397: Apache::grades
9398:
9399: =head1 SYNOPSIS
9400:
9401: Handles the viewing of grades.
9402:
9403: This is part of the LearningOnline Network with CAPA project
9404: described at http://www.lon-capa.org.
9405:
9406: =head1 OVERVIEW
9407:
9408: Do an ssi with retries:
9409: While I'd love to factor out this with the vesrion in lonprintout,
9410: 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
9411: I'm not quite ready to invent (e.g. an ssi_with_retry object).
9412:
9413: At least the logic that drives this has been pulled out into loncommon.
9414:
9415:
9416:
9417: ssi_with_retries - Does the server side include of a resource.
9418: if the ssi call returns an error we'll retry it up to
9419: the number of times requested by the caller.
9420: If we still have a proble, no text is appended to the
9421: output and we set some global variables.
9422: to indicate to the caller an SSI error occurred.
9423: All of this is supposed to deal with the issues described
9424: in LonCAPA BZ 5631 see:
9425: http://bugs.lon-capa.org/show_bug.cgi?id=5631
9426: by informing the user that this happened.
9427:
9428: Parameters:
9429: resource - The resource to include. This is passed directly, without
9430: interpretation to lonnet::ssi.
9431: form - The form hash parameters that guide the interpretation of the resource
9432:
9433: retries - Number of retries allowed before giving up completely.
9434: Returns:
9435: On success, returns the rendered resource identified by the resource parameter.
9436: Side Effects:
9437: The following global variables can be set:
9438: ssi_error - If an unrecoverable error occurred this becomes true.
9439: It is up to the caller to initialize this to false
9440: if desired.
9441: ssi_error_resource - If an unrecoverable error occurred, this is the value
9442: of the resource that could not be rendered by the ssi
9443: call.
9444: ssi_error_message - The error string fetched from the ssi response
9445: in the event of an error.
9446:
9447:
9448: =head1 HANDLER SUBROUTINE
9449:
9450: ssi_with_retries()
9451:
9452: =head1 SUBROUTINES
9453:
9454: =over
9455:
9456: =item scantron_get_correction() :
9457:
9458: Builds the interface screen to interact with the operator to fix a
9459: specific error condition in a specific scanline
9460:
9461: Arguments:
9462: $r - Apache request object
9463: $i - number of the current scanline
9464: $scan_record - hash ref as returned from &scantron_parse_scanline()
9465: $scan_config - hash ref as returned from &get_scantron_config()
9466: $line - full contents of the current scanline
9467: $error - error condition, valid values are
9468: 'incorrectCODE', 'duplicateCODE',
9469: 'doublebubble', 'missingbubble',
9470: 'duplicateID', 'incorrectID'
9471: $arg - extra information needed
9472: For errors:
9473: - duplicateID - paper number that this studentID was seen before on
9474: - duplicateCODE - array ref of the paper numbers this CODE was
9475: seen on before
9476: - incorrectCODE - current incorrect CODE
9477: - doublebubble - array ref of the bubble lines that have double
9478: bubble errors
9479: - missingbubble - array ref of the bubble lines that have missing
9480: bubble errors
9481:
9482: =item scantron_get_maxbubble() :
9483:
9484: Arguments:
9485: $nav_error - Reference to scalar which is a flag to indicate a
9486: failure to retrieve a navmap object.
9487: if $nav_error is set to 1 by scantron_get_maxbubble(), the
9488: calling routine should trap the error condition and display the warning
9489: found in &navmap_errormsg().
9490:
9491: Returns the maximum number of bubble lines that are expected to
9492: occur. Does this by walking the selected sequence rendering the
9493: resource and then checking &Apache::lonxml::get_problem_counter()
9494: for what the current value of the problem counter is.
9495:
9496: Caches the results to $env{'form.scantron_maxbubble'},
9497: $env{'form.scantron.bubble_lines.n'},
9498: $env{'form.scantron.first_bubble_line.n'} and
9499: $env{"form.scantron.sub_bubblelines.n"}
9500: which are the total number of bubble, lines, the number of bubble
9501: lines for response n and number of the first bubble line for response n,
9502: and a comma separated list of numbers of bubble lines for sub-questions
9503: (for optionresponse, matchresponse, and rankresponse items), for response n.
9504:
9505:
9506: =item scantron_validate_missingbubbles() :
9507:
9508: Validates all scanlines in the selected file to not have any
9509: answers that don't have bubbles that have not been verified
9510: to be bubble free.
9511:
9512: =item scantron_process_students() :
9513:
9514: Routine that does the actual grading of the bubble sheet information.
9515:
9516: The parsed scanline hash is added to %env
9517:
9518: Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
9519: foreach resource , with the form data of
9520:
9521: 'submitted' =>'scantron'
9522: 'grade_target' =>'grade',
9523: 'grade_username'=> username of student
9524: 'grade_domain' => domain of student
9525: 'grade_courseid'=> of course
9526: 'grade_symb' => symb of resource to grade
9527:
9528: This triggers a grading pass. The problem grading code takes care
9529: of converting the bubbled letter information (now in %env) into a
9530: valid submission.
9531:
9532: =item scantron_upload_scantron_data() :
9533:
9534: Creates the screen for adding a new bubble sheet data file to a course.
9535:
9536: =item scantron_upload_scantron_data_save() :
9537:
9538: Adds a provided bubble information data file to the course if user
9539: has the correct privileges to do so.
9540:
9541: =item valid_file() :
9542:
9543: Validates that the requested bubble data file exists in the course.
9544:
9545: =item scantron_download_scantron_data() :
9546:
9547: Shows a list of the three internal files (original, corrected,
9548: skipped) for a specific bubble sheet data file that exists in the
9549: course.
9550:
9551: =item scantron_validate_ID() :
9552:
9553: Validates all scanlines in the selected file to not have any
9554: invalid or underspecified student/employee IDs
9555:
9556: =item navmap_errormsg() :
9557:
9558: Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
9559: Should be called whenever the request to instantiate a navmap object fails.
9560:
9561: =back
9562:
9563: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>