File:
[LON-CAPA] /
loncom /
homework /
grades.pm
Revision
1.716:
download - view:
text,
annotated -
select for diffs
Thu Jan 30 18:04:36 2014 UTC (10 years, 6 months ago) by
bisitz
Branches:
MAIN
CVS tags:
HEAD
Bug #5409:
- Also respect customresponse (multiple input fields possible, too)
- Display of answer after "Submitted Answer:" on grades screen
(Co-op with Stefan Droeschler and Marcel Kruse)
1: # The LearningOnline Network with CAPA
2: # The LON-CAPA Grading handler
3: #
4: # $Id: grades.pm,v 1.716 2014/01/30 18:04:36 bisitz Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28:
29:
30:
31: package Apache::grades;
32: use strict;
33: use Apache::style;
34: use Apache::lonxml;
35: use Apache::lonnet;
36: use Apache::loncommon;
37: use Apache::lonhtmlcommon;
38: use Apache::lonnavmaps;
39: use Apache::lonhomework;
40: use Apache::lonpickcode;
41: use Apache::loncoursedata;
42: use Apache::lonmsg();
43: use Apache::Constants qw(:common :http);
44: use Apache::lonlocal;
45: use Apache::lonenc;
46: use Apache::lonstathelpers;
47: use Apache::lonquickgrades;
48: use Apache::bridgetask();
49: use String::Similarity;
50: use LONCAPA;
51:
52: use POSIX qw(floor);
53:
54:
55:
56: my %perm=();
57: my %old_essays=();
58:
59: # These variables are used to recover from ssi errors
60:
61: my $ssi_retries = 5;
62: my $ssi_error;
63: my $ssi_error_resource;
64: my $ssi_error_message;
65:
66:
67: sub ssi_with_retries {
68: my ($resource, $retries, %form) = @_;
69: my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
70: if ($response->is_error) {
71: $ssi_error = 1;
72: $ssi_error_resource = $resource;
73: $ssi_error_message = $response->code . " " . $response->message;
74: }
75:
76: return $content;
77:
78: }
79: #
80: # Prodcuces an ssi retry failure error message to the user:
81: #
82:
83: sub ssi_print_error {
84: my ($r) = @_;
85: my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
86: $r->print('
87: <br />
88: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
89: <p>
90: '.&mt('Unable to retrieve a resource from a server:').'<br />
91: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
92: '.&mt('Error:').' '.$ssi_error_message.'
93: </p>
94: <p>'.
95: &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 />'.
96: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
97: '</p>');
98: return;
99: }
100:
101: #
102: # --- Retrieve the parts from the metadata file.---
103: # Returns an array of everything that the resources stores away
104: #
105:
106: sub getpartlist {
107: my ($symb,$errorref) = @_;
108:
109: my $navmap = Apache::lonnavmaps::navmap->new();
110: unless (ref($navmap)) {
111: if (ref($errorref)) {
112: $$errorref = 'navmap';
113: return;
114: }
115: }
116: my $res = $navmap->getBySymb($symb);
117: my $partlist = $res->parts();
118: my $url = $res->src();
119: my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
120:
121: my @stores;
122: foreach my $part (@{ $partlist }) {
123: foreach my $key (@metakeys) {
124: if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
125: }
126: }
127: return @stores;
128: }
129:
130: #--- Format fullname, username:domain if different for display
131: #--- Use anywhere where the student names are listed
132: sub nameUserString {
133: my ($type,$fullname,$uname,$udom) = @_;
134: if ($type eq 'header') {
135: return '<b> '.&mt('Fullname').' </b><span class="LC_internal_info">('.&mt('Username').')</span>';
136: } else {
137: return ' '.$fullname.'<span class="LC_internal_info"> ('.$uname.
138: ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
139: }
140: }
141:
142: #--- Get the partlist and the response type for a given problem. ---
143: #--- Indicate if a response type is coded handgraded or not. ---
144: #--- Sets response_error pointer to "1" if navmaps object broken ---
145: sub response_type {
146: my ($symb,$response_error) = @_;
147:
148: my $navmap = Apache::lonnavmaps::navmap->new();
149: unless (ref($navmap)) {
150: if (ref($response_error)) {
151: $$response_error = 1;
152: }
153: return;
154: }
155: my $res = $navmap->getBySymb($symb);
156: unless (ref($res)) {
157: $$response_error = 1;
158: return;
159: }
160: my $partlist = $res->parts();
161: my %vPart =
162: map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
163: my (%response_types,%handgrade);
164: foreach my $part (@{ $partlist }) {
165: next if (%vPart && !exists($vPart{$part}));
166:
167: my @types = $res->responseType($part);
168: my @ids = $res->responseIds($part);
169: for (my $i=0; $i < scalar(@ids); $i++) {
170: $response_types{$part}{$ids[$i]} = $types[$i];
171: $handgrade{$part.'_'.$ids[$i]} =
172: &Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
173: '.handgrade',$symb);
174: }
175: }
176: return ($partlist,\%handgrade,\%response_types);
177: }
178:
179: sub flatten_responseType {
180: my ($responseType) = @_;
181: my @part_response_id =
182: map {
183: my $part = $_;
184: map {
185: [$part,$_]
186: } sort(keys(%{ $responseType->{$part} }));
187: } sort(keys(%$responseType));
188: return @part_response_id;
189: }
190:
191: sub get_display_part {
192: my ($partID,$symb)=@_;
193: my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
194: if (defined($display) and $display ne '') {
195: $display.= ' (<span class="LC_internal_info">'
196: .&mt('Part ID: [_1]',$partID).'</span>)';
197: } else {
198: $display=$partID;
199: }
200: return $display;
201: }
202:
203: sub reset_caches {
204: &reset_analyze_cache();
205: &reset_perm();
206: &reset_old_essays();
207: }
208:
209: {
210: my %analyze_cache;
211: my %analyze_cache_formkeys;
212:
213: sub reset_analyze_cache {
214: undef(%analyze_cache);
215: undef(%analyze_cache_formkeys);
216: }
217:
218: sub get_analyze {
219: my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
220: my $key = "$symb\0$uname\0$udom";
221: if ($type eq 'randomizetry') {
222: if ($trial ne '') {
223: $key .= "\0".$trial;
224: }
225: }
226: if (exists($analyze_cache{$key})) {
227: my $getupdate = 0;
228: if (ref($add_to_hash) eq 'HASH') {
229: foreach my $item (keys(%{$add_to_hash})) {
230: if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
231: if (!exists($analyze_cache_formkeys{$key}{$item})) {
232: $getupdate = 1;
233: last;
234: }
235: } else {
236: $getupdate = 1;
237: }
238: }
239: }
240: if (!$getupdate) {
241: return $analyze_cache{$key};
242: }
243: }
244:
245: my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
246: $url=&Apache::lonnet::clutter($url);
247: my %form = ('grade_target' => 'analyze',
248: 'grade_domain' => $udom,
249: 'grade_symb' => $symb,
250: 'grade_courseid' => $env{'request.course.id'},
251: 'grade_username' => $uname,
252: 'grade_noincrement' => $no_increment);
253: if ($bubbles_per_row ne '') {
254: $form{'bubbles_per_row'} = $bubbles_per_row;
255: }
256: if ($type eq 'randomizetry') {
257: $form{'grade_questiontype'} = $type;
258: if ($rndseed ne '') {
259: $form{'grade_rndseed'} = $rndseed;
260: }
261: }
262: if (ref($add_to_hash)) {
263: %form = (%form,%{$add_to_hash});
264: }
265: my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
266: (undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
267: my %analyze=&Apache::lonnet::str2hash($subresult);
268: if (ref($add_to_hash) eq 'HASH') {
269: $analyze_cache_formkeys{$key} = $add_to_hash;
270: } else {
271: $analyze_cache_formkeys{$key} = {};
272: }
273: return $analyze_cache{$key} = \%analyze;
274: }
275:
276: sub get_order {
277: my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
278: my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
279: return $analyze->{"$partid.$respid.shown"};
280: }
281:
282: sub get_radiobutton_correct_foil {
283: my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
284: my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
285: my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
286: if (ref($foils) eq 'ARRAY') {
287: foreach my $foil (@{$foils}) {
288: if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
289: return $foil;
290: }
291: }
292: }
293: }
294:
295: sub scantron_partids_tograde {
296: my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row) = @_;
297: my (%analysis,@parts);
298: if (ref($resource)) {
299: my $symb = $resource->symb();
300: my $add_to_form;
301: if ($check_for_randomlist) {
302: $add_to_form = { 'check_parts_withrandomlist' => 1,};
303: }
304: my $analyze =
305: &get_analyze($symb,$uname,$udom,undef,$add_to_form,
306: undef,undef,undef,$bubbles_per_row);
307: if (ref($analyze) eq 'HASH') {
308: %analysis = %{$analyze};
309: }
310: if (ref($analysis{'parts'}) eq 'ARRAY') {
311: foreach my $part (@{$analysis{'parts'}}) {
312: my ($id,$respid) = split(/\./,$part);
313: if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
314: push(@parts,$part);
315: }
316: }
317: }
318: }
319: return (\%analysis,\@parts);
320: }
321:
322: }
323:
324: #--- Clean response type for display
325: #--- Currently filters option/rank/radiobutton/match/essay/Task
326: # response types only.
327: sub cleanRecord {
328: my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
329: $uname,$udom,$type,$trial,$rndseed) = @_;
330: my $grayFont = '<span class="LC_internal_info">';
331: if ($response =~ /^(option|rank)$/) {
332: my %answer=&Apache::lonnet::str2hash($answer);
333: my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
334: my ($toprow,$bottomrow);
335: foreach my $foil (@$order) {
336: if ($grading{$foil} == 1) {
337: $toprow.='<td><b>'.$answer{$foil}.' </b></td>';
338: } else {
339: $toprow.='<td><i>'.$answer{$foil}.' </i></td>';
340: }
341: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
342: }
343: return '<blockquote><table border="1">'.
344: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
345: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
346: $bottomrow.'</tr></table></blockquote>';
347: } elsif ($response eq 'match') {
348: my %answer=&Apache::lonnet::str2hash($answer);
349: my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
350: my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
351: my ($toprow,$middlerow,$bottomrow);
352: foreach my $foil (@$order) {
353: my $item=shift(@items);
354: if ($grading{$foil} == 1) {
355: $toprow.='<td><b>'.$item.' </b></td>';
356: $middlerow.='<td><b>'.$grayFont.$answer{$foil}.' </span></b></td>';
357: } else {
358: $toprow.='<td><i>'.$item.' </i></td>';
359: $middlerow.='<td><i>'.$grayFont.$answer{$foil}.' </span></i></td>';
360: }
361: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
362: }
363: return '<blockquote><table border="1">'.
364: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
365: '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
366: $middlerow.'</tr>'.
367: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
368: $bottomrow.'</tr></table></blockquote>';
369: } elsif ($response eq 'radiobutton') {
370: my %answer=&Apache::lonnet::str2hash($answer);
371: my ($toprow,$bottomrow);
372: my $correct =
373: &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
374: foreach my $foil (@$order) {
375: if (exists($answer{$foil})) {
376: if ($foil eq $correct) {
377: $toprow.='<td><b>'.&mt('true').'</b></td>';
378: } else {
379: $toprow.='<td><i>'.&mt('true').'</i></td>';
380: }
381: } else {
382: $toprow.='<td>'.&mt('false').'</td>';
383: }
384: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
385: }
386: return '<blockquote><table border="1">'.
387: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
388: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
389: $bottomrow.'</tr></table></blockquote>';
390: } elsif ($response eq 'essay') {
391: if (! exists ($env{'form.'.$symb})) {
392: my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
393: $env{'course.'.$env{'request.course.id'}.'.domain'},
394: $env{'course.'.$env{'request.course.id'}.'.num'});
395:
396: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
397: $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
398: $env{'form.kwclr'} = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
399: $env{'form.kwsize'} = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
400: $env{'form.kwstyle'} = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
401: $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
402: }
403: $answer =~ s-\n-<br />-g;
404: return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
405: } elsif ( $response eq 'organic') {
406: my $result='Smile representation: "<tt>'.$answer.'</tt>"';
407: my $jme=$record->{$version."resource.$partid.$respid.molecule"};
408: $result.=&Apache::chemresponse::jme_img($jme,$answer,400);
409: return $result;
410: } elsif ( $response eq 'Task') {
411: if ( $answer eq 'SUBMITTED') {
412: my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
413: my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
414: return $result;
415: } elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
416: my @matches = grep(/^\Q$version\E.*?\.instance$/,
417: keys(%{$record}));
418: return join('<br />',($version,@matches));
419:
420:
421: } else {
422: my $result =
423: '<p>'
424: .&mt('Overall result: [_1]',
425: $record->{$version."resource.$respid.$partid.status"})
426: .'</p>';
427:
428: $result .= '<ul>';
429: my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
430: keys(%{$record}));
431: foreach my $grade (sort(@grade)) {
432: my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
433: $result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
434: $dim, $record->{$grade}).
435: '</li>';
436: }
437: $result.='</ul>';
438: return $result;
439: }
440: } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
441: # Respect multiple input fields, see Bug #5409
442: $answer =
443: &Apache::loncommon::format_previous_attempt_value('submission',
444: $answer);
445: }
446: return $answer;
447: }
448:
449: #-- A couple of common js functions
450: sub commonJSfunctions {
451: my $request = shift;
452: $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
453: function radioSelection(radioButton) {
454: var selection=null;
455: if (radioButton.length > 1) {
456: for (var i=0; i<radioButton.length; i++) {
457: if (radioButton[i].checked) {
458: return radioButton[i].value;
459: }
460: }
461: } else {
462: if (radioButton.checked) return radioButton.value;
463: }
464: return selection;
465: }
466:
467: function pullDownSelection(selectOne) {
468: var selection="";
469: if (selectOne.length > 1) {
470: for (var i=0; i<selectOne.length; i++) {
471: if (selectOne[i].selected) {
472: return selectOne[i].value;
473: }
474: }
475: } else {
476: // only one value it must be the selected one
477: return selectOne.value;
478: }
479: }
480: COMMONJSFUNCTIONS
481: }
482:
483: #--- Dumps the class list with usernames,list of sections,
484: #--- section, ids and fullnames for each user.
485: sub getclasslist {
486: my ($getsec,$filterlist,$getgroup) = @_;
487: my @getsec;
488: my @getgroup;
489: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
490: if (!ref($getsec)) {
491: if ($getsec ne '' && $getsec ne 'all') {
492: @getsec=($getsec);
493: }
494: } else {
495: @getsec=@{$getsec};
496: }
497: if (grep(/^all$/,@getsec)) { undef(@getsec); }
498: if (!ref($getgroup)) {
499: if ($getgroup ne '' && $getgroup ne 'all') {
500: @getgroup=($getgroup);
501: }
502: } else {
503: @getgroup=@{$getgroup};
504: }
505: if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
506:
507: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
508: # Bail out if we were unable to get the classlist
509: return if (! defined($classlist));
510: &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
511: #
512: my %sections;
513: my %fullnames;
514: foreach my $student (keys(%$classlist)) {
515: my $end =
516: $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
517: my $start =
518: $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
519: my $id =
520: $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
521: my $section =
522: $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
523: my $fullname =
524: $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
525: my $status =
526: $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
527: my $group =
528: $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
529: # filter students according to status selected
530: if ($filterlist && (!($stu_status =~ /Any/))) {
531: if (!($stu_status =~ $status)) {
532: delete($classlist->{$student});
533: next;
534: }
535: }
536: # filter students according to groups selected
537: my @stu_groups = split(/,/,$group);
538: if (@getgroup) {
539: my $exclude = 1;
540: foreach my $grp (@getgroup) {
541: foreach my $stu_group (@stu_groups) {
542: if ($stu_group eq $grp) {
543: $exclude = 0;
544: }
545: }
546: if (($grp eq 'none') && !$group) {
547: $exclude = 0;
548: }
549: }
550: if ($exclude) {
551: delete($classlist->{$student});
552: }
553: }
554: $section = ($section ne '' ? $section : 'none');
555: if (&canview($section)) {
556: if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
557: $sections{$section}++;
558: if ($classlist->{$student}) {
559: $fullnames{$student}=$fullname;
560: }
561: } else {
562: delete($classlist->{$student});
563: }
564: } else {
565: delete($classlist->{$student});
566: }
567: }
568: my %seen = ();
569: my @sections = sort(keys(%sections));
570: return ($classlist,\@sections,\%fullnames);
571: }
572:
573: sub canmodify {
574: my ($sec)=@_;
575: if ($perm{'mgr'}) {
576: if (!defined($perm{'mgr_section'})) {
577: # can modify whole class
578: return 1;
579: } else {
580: if ($sec eq $perm{'mgr_section'}) {
581: #can modify the requested section
582: return 1;
583: } else {
584: # can't modify the request section
585: return 0;
586: }
587: }
588: }
589: #can't modify
590: return 0;
591: }
592:
593: sub canview {
594: my ($sec)=@_;
595: if ($perm{'vgr'}) {
596: if (!defined($perm{'vgr_section'})) {
597: # can modify whole class
598: return 1;
599: } else {
600: if ($sec eq $perm{'vgr_section'}) {
601: #can modify the requested section
602: return 1;
603: } else {
604: # can't modify the request section
605: return 0;
606: }
607: }
608: }
609: #can't modify
610: return 0;
611: }
612:
613: #--- Retrieve the grade status of a student for all the parts
614: sub student_gradeStatus {
615: my ($symb,$udom,$uname,$partlist) = @_;
616: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
617: my %partstatus = ();
618: foreach (@$partlist) {
619: my ($status,undef) = split(/_/,$record{"resource.$_.solved"},2);
620: $status = 'nothing' if ($status eq '');
621: $partstatus{$_} = $status;
622: my $subkey = "resource.$_.submitted_by";
623: $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
624: }
625: return %partstatus;
626: }
627:
628: # hidden form and javascript that calls the form
629: # Use by verifyscript and viewgrades
630: # Shows a student's view of problem and submission
631: sub jscriptNform {
632: my ($symb) = @_;
633: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
634: my $jscript= &Apache::lonhtmlcommon::scripttag(
635: ' function viewOneStudent(user,domain) {'."\n".
636: ' document.onestudent.student.value = user;'."\n".
637: ' document.onestudent.userdom.value = domain;'."\n".
638: ' document.onestudent.submit();'."\n".
639: ' }'."\n".
640: "\n");
641: $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
642: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
643: '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
644: '<input type="hidden" name="command" value="submission" />'."\n".
645: '<input type="hidden" name="student" value="" />'."\n".
646: '<input type="hidden" name="userdom" value="" />'."\n".
647: '</form>'."\n";
648: return $jscript;
649: }
650:
651:
652:
653: # Given the score (as a number [0-1] and the weight) what is the final
654: # point value? This function will round to the nearest tenth, third,
655: # or quarter if one of those is within the tolerance of .00001.
656: sub compute_points {
657: my ($score, $weight) = @_;
658:
659: my $tolerance = .00001;
660: my $points = $score * $weight;
661:
662: # Check for nearness to 1/x.
663: my $check_for_nearness = sub {
664: my ($factor) = @_;
665: my $num = ($points * $factor) + $tolerance;
666: my $floored_num = floor($num);
667: if ($num - $floored_num < 2 * $tolerance * $factor) {
668: return $floored_num / $factor;
669: }
670: return $points;
671: };
672:
673: $points = $check_for_nearness->(10);
674: $points = $check_for_nearness->(3);
675: $points = $check_for_nearness->(4);
676:
677: return $points;
678: }
679:
680: #------------------ End of general use routines --------------------
681:
682: #
683: # Find most similar essay
684: #
685:
686: sub most_similar {
687: my ($uname,$udom,$symb,$uessay)=@_;
688:
689: unless ($symb) { return ''; }
690:
691: unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
692:
693: # ignore spaces and punctuation
694:
695: $uessay=~s/\W+/ /gs;
696:
697: # ignore empty submissions (occuring when only files are sent)
698:
699: unless ($uessay=~/\w+/s) { return ''; }
700:
701: # these will be returned. Do not care if not at least 50 percent similar
702: my $limit=0.6;
703: my $sname='';
704: my $sdom='';
705: my $scrsid='';
706: my $sessay='';
707: # go through all essays ...
708: foreach my $tkey (keys(%{$old_essays{$symb}})) {
709: my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
710: # ... except the same student
711: next if (($tname eq $uname) && ($tdom eq $udom));
712: my $tessay=$old_essays{$symb}{$tkey};
713: $tessay=~s/\W+/ /gs;
714: # String similarity gives up if not even limit
715: my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
716: # Found one
717: if ($tsimilar>$limit) {
718: $limit=$tsimilar;
719: $sname=$tname;
720: $sdom=$tdom;
721: $scrsid=$tcrsid;
722: $sessay=$old_essays{$symb}{$tkey};
723: }
724: }
725: if ($limit>0.6) {
726: return ($sname,$sdom,$scrsid,$sessay,$limit);
727: } else {
728: return ('','','','',0);
729: }
730: }
731:
732: #-------------------------------------------------------------------
733:
734: #------------------------------------ Receipt Verification Routines
735: #
736:
737: sub initialverifyreceipt {
738: my ($request,$symb) = @_;
739: &commonJSfunctions($request);
740: return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
741: &Apache::lonnet::recprefix($env{'request.course.id'}).
742: '-<input type="text" name="receipt" size="4" />'.
743: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
744: '<input type="hidden" name="command" value="verify" />'.
745: "</form>\n";
746: }
747:
748: #--- Check whether a receipt number is valid.---
749: sub verifyreceipt {
750: my ($request,$symb) = @_;
751:
752: my $courseid = $env{'request.course.id'};
753: my $receipt = &Apache::lonnet::recprefix($courseid).'-'.
754: $env{'form.receipt'};
755: $receipt =~ s/[^\-\d]//g;
756:
757: my $title.=
758: '<h3><span class="LC_info">'.
759: &mt('Verifying Receipt Number [_1]',$receipt).
760: '</span></h3>'."\n";
761:
762: my ($string,$contents,$matches) = ('','',0);
763: my (undef,undef,$fullname) = &getclasslist('all','0');
764:
765: my $receiptparts=0;
766: if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
767: $env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
768: my $parts=['0'];
769: if ($receiptparts) {
770: my $res_error;
771: ($parts)=&response_type($symb,\$res_error);
772: if ($res_error) {
773: return &navmap_errormsg();
774: }
775: }
776:
777: my $header =
778: &Apache::loncommon::start_data_table().
779: &Apache::loncommon::start_data_table_header_row().
780: '<th> '.&mt('Fullname').' </th>'."\n".
781: '<th> '.&mt('Username').' </th>'."\n".
782: '<th> '.&mt('Domain').' </th>';
783: if ($receiptparts) {
784: $header.='<th> '.&mt('Problem Part').' </th>';
785: }
786: $header.=
787: &Apache::loncommon::end_data_table_header_row();
788:
789: foreach (sort
790: {
791: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
792: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
793: }
794: return $a cmp $b;
795: } (keys(%$fullname))) {
796: my ($uname,$udom)=split(/\:/);
797: foreach my $part (@$parts) {
798: if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
799: $contents.=
800: &Apache::loncommon::start_data_table_row().
801: '<td> '."\n".
802: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
803: '\');" target="_self">'.$$fullname{$_}.'</a> </td>'."\n".
804: '<td> '.$uname.' </td>'.
805: '<td> '.$udom.' </td>';
806: if ($receiptparts) {
807: $contents.='<td> '.$part.' </td>';
808: }
809: $contents.=
810: &Apache::loncommon::end_data_table_row()."\n";
811:
812: $matches++;
813: }
814: }
815: }
816: if ($matches == 0) {
817: $string = $title
818: .'<p class="LC_warning">'
819: .&mt('No match found for the above receipt number.')
820: .'</p>';
821: } else {
822: $string = &jscriptNform($symb).$title.
823: '<p>'.
824: &mt('The above receipt number matches the following [quant,_1,student].',$matches).
825: '</p>'.
826: $header.
827: $contents.
828: &Apache::loncommon::end_data_table()."\n";
829: }
830: return $string;
831: }
832:
833: #--- This is called by a number of programs.
834: #--- Called from the Grading Menu - View/Grade an individual student
835: #--- Also called directly when one clicks on the subm button
836: # on the problem page.
837: sub listStudents {
838: my ($request,$symb,$submitonly) = @_;
839:
840: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
841: my $cnum = $env{"course.$env{'request.course.id'}.num"};
842: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
843: my $getgroup = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
844: unless ($submitonly) {
845: $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
846: }
847:
848: my $result='';
849: my $res_error;
850: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
851:
852: my %lt = &Apache::lonlocal::texthash (
853: 'multiple' => 'Please select a student or group of students before clicking on the Next button.',
854: 'single' => 'Please select the student before clicking on the Next button.',
855: );
856: $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
857: function checkSelect(checkBox) {
858: var ctr=0;
859: var sense="";
860: if (checkBox.length > 1) {
861: for (var i=0; i<checkBox.length; i++) {
862: if (checkBox[i].checked) {
863: ctr++;
864: }
865: }
866: sense = '$lt{'multiple'}';
867: } else {
868: if (checkBox.checked) {
869: ctr = 1;
870: }
871: sense = '$lt{'single'}';
872: }
873: if (ctr == 0) {
874: alert(sense);
875: return false;
876: }
877: document.gradesub.submit();
878: }
879:
880: function reLoadList(formname) {
881: if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
882: formname.command.value = 'submission';
883: formname.submit();
884: }
885: LISTJAVASCRIPT
886:
887: &commonJSfunctions($request);
888: $request->print($result);
889:
890: my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
891: "\n";
892:
893: $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
894: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
895: .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
896: .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
897: .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
898: .&Apache::lonhtmlcommon::row_closure();
899: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
900: .'<label><input type="radio" name="vAns" value="no" /> '.&mt('no').' </label>'."\n"
901: .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
902: .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
903: .&Apache::lonhtmlcommon::row_closure();
904:
905: my $submission_options;
906: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
907: my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
908: $env{'form.Status'} = $saveStatus;
909: $submission_options.=
910: '<span class="LC_nobreak">'.
911: '<label><input type="radio" name="lastSub" value="lastonly" /> '.
912: &mt('last submission').' </label></span>'."\n".
913: '<span class="LC_nobreak">'.
914: '<label><input type="radio" name="lastSub" value="last" /> '.
915: &mt('last submission with details').' </label></span>'."\n".
916: '<span class="LC_nobreak">'.
917: '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
918: &mt('all submissions').'</label></span>'."\n".
919: '<span class="LC_nobreak">'.
920: '<label><input type="radio" name="lastSub" value="all" /> '.
921: &mt('all submissions with details').'</label></span>';
922: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
923: .$submission_options
924: .&Apache::lonhtmlcommon::row_closure();
925:
926: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
927: .'<select name="increment">'
928: .'<option value="1">'.&mt('Whole Points').'</option>'
929: .'<option value=".5">'.&mt('Half Points').'</option>'
930: .'<option value=".25">'.&mt('Quarter Points').'</option>'
931: .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
932: .'</select>'
933: .&Apache::lonhtmlcommon::row_closure();
934:
935: $gradeTable .=
936: &build_section_inputs().
937: '<input type="hidden" name="submitonly" value="'.$submitonly.'" />'."\n".
938: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
939: '<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
940:
941: if (exists($env{'form.Status'})) {
942: $gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
943: } else {
944: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
945: .&Apache::lonhtmlcommon::StatusOptions(
946: $saveStatus,undef,1,'javascript:reLoadList(this.form);')
947: .&Apache::lonhtmlcommon::row_closure();
948: }
949:
950: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
951: .'<input type="checkbox" name="checkPlag" checked="checked" />'
952: .&Apache::lonhtmlcommon::row_closure(1)
953: .&Apache::lonhtmlcommon::end_pick_box();
954:
955: $gradeTable .= '<p>'
956: .&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"
957: .'<input type="hidden" name="command" value="processGroup" />'
958: .'</p>';
959:
960: # checkall buttons
961: $gradeTable.=&check_script('gradesub', 'stuinfo');
962: $gradeTable.='<input type="button" '."\n".
963: 'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
964: 'value="'.&mt('Next').' →" /> <br />'."\n";
965: $gradeTable.=&check_buttons();
966: my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
967: $gradeTable.= &Apache::loncommon::start_data_table().
968: &Apache::loncommon::start_data_table_header_row();
969: my $loop = 0;
970: while ($loop < 2) {
971: $gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
972: '<th>'.&nameUserString('header').' '.&mt('Section/Group').'</th>';
973: if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
974: foreach my $part (sort(@$partlist)) {
975: my $display_part=
976: &get_display_part((split(/_/,$part))[0],$symb);
977: $gradeTable.=
978: '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
979: }
980: } elsif ($submitonly eq 'queued') {
981: $gradeTable.='<th>'.&mt('Queue Status').' </th>';
982: }
983: $loop++;
984: # $gradeTable.='<td></td>' if ($loop%2 ==1);
985: }
986: $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
987:
988: my $ctr = 0;
989: foreach my $student (sort
990: {
991: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
992: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
993: }
994: return $a cmp $b;
995: }
996: (keys(%$fullname))) {
997: my ($uname,$udom) = split(/:/,$student);
998:
999: my %status = ();
1000:
1001: if ($submitonly eq 'queued') {
1002: my %queue_status =
1003: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
1004: $udom,$uname);
1005: next if (!defined($queue_status{'gradingqueue'}));
1006: $status{'gradingqueue'} = $queue_status{'gradingqueue'};
1007: }
1008:
1009: if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1010: (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1011: my $submitted = 0;
1012: my $graded = 0;
1013: my $incorrect = 0;
1014: foreach (keys(%status)) {
1015: $submitted = 1 if ($status{$_} ne 'nothing');
1016: $graded = 1 if ($status{$_} =~ /^ungraded/);
1017: $incorrect = 1 if ($status{$_} =~ /^incorrect/);
1018:
1019: my ($foo,$partid,$foo1) = split(/\./,$_);
1020: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1021: $submitted = 0;
1022: my ($part)=split(/\./,$partid);
1023: $gradeTable.='<input type="hidden" name="'.
1024: $student.':'.$part.':submitted_by" value="'.
1025: $status{'resource.'.$partid.'.submitted_by'}.'" />';
1026: }
1027: }
1028:
1029: next if (!$submitted && ($submitonly eq 'yes' ||
1030: $submitonly eq 'incorrect' ||
1031: $submitonly eq 'graded'));
1032: next if (!$graded && ($submitonly eq 'graded'));
1033: next if (!$incorrect && $submitonly eq 'incorrect');
1034: }
1035:
1036: $ctr++;
1037: my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1038: my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1039: if ( $perm{'vgr'} eq 'F' ) {
1040: if ($ctr%2 ==1) {
1041: $gradeTable.= &Apache::loncommon::start_data_table_row();
1042: }
1043: $gradeTable.='<td align="right">'.$ctr.' </td>'.
1044: '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1045: $student.':'.$$fullname{$student}.':::SECTION'.$section.
1046: ') " /> </label></td>'."\n".'<td>'.
1047: &nameUserString(undef,$$fullname{$student},$uname,$udom).
1048: ' '.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1049:
1050: if ($submitonly ne 'all') {
1051: foreach (sort(keys(%status))) {
1052: next if ($_ =~ /^resource.*?submitted_by$/);
1053: $gradeTable.='<td align="center"> '.&mt($status{$_}).' </td>'."\n";
1054: }
1055: }
1056: # $gradeTable.='<td></td>' if ($ctr%2 ==1);
1057: if ($ctr%2 ==0) {
1058: $gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
1059: }
1060: }
1061: }
1062: if ($ctr%2 ==1) {
1063: $gradeTable.='<td> </td><td> </td><td> </td>';
1064: if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1065: foreach (@$partlist) {
1066: $gradeTable.='<td> </td>';
1067: }
1068: } elsif ($submitonly eq 'queued') {
1069: $gradeTable.='<td> </td>';
1070: }
1071: $gradeTable.=&Apache::loncommon::end_data_table_row();
1072: }
1073:
1074: $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1075: '<input type="button" '.
1076: 'onclick="javascript:checkSelect(this.form.stuinfo);" '.
1077: 'value="'.&mt('Next').' →" /></form>'."\n";
1078: if ($ctr == 0) {
1079: my $num_students=(scalar(keys(%$fullname)));
1080: if ($num_students eq 0) {
1081: $gradeTable='<br /> <span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1082: } else {
1083: my $submissions='submissions';
1084: if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
1085: if ($submitonly eq 'graded' ) { $submissions = 'ungraded submissions'; }
1086: if ($submitonly eq 'queued' ) { $submissions = 'queued submissions'; }
1087: $gradeTable='<br /> <span class="LC_warning">'.
1088: &mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
1089: $num_students).
1090: '</span><br />';
1091: }
1092: } elsif ($ctr == 1) {
1093: $gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1094: }
1095: $request->print($gradeTable);
1096: return '';
1097: }
1098:
1099: #---- Called from the listStudents routine
1100:
1101: sub check_script {
1102: my ($form, $type)=@_;
1103: my $chkallscript= &Apache::lonhtmlcommon::scripttag('
1104: function checkall() {
1105: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1106: ele = document.forms.'.$form.'.elements[i];
1107: if (ele.name == "'.$type.'") {
1108: document.forms.'.$form.'.elements[i].checked=true;
1109: }
1110: }
1111: }
1112:
1113: function checksec() {
1114: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1115: ele = document.forms.'.$form.'.elements[i];
1116: string = document.forms.'.$form.'.chksec.value;
1117: if
1118: (ele.value.indexOf(":::SECTION"+string)>0) {
1119: document.forms.'.$form.'.elements[i].checked=true;
1120: }
1121: }
1122: }
1123:
1124:
1125: function uncheckall() {
1126: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1127: ele = document.forms.'.$form.'.elements[i];
1128: if (ele.name == "'.$type.'") {
1129: document.forms.'.$form.'.elements[i].checked=false;
1130: }
1131: }
1132: }
1133:
1134: '."\n");
1135: return $chkallscript;
1136: }
1137:
1138: sub check_buttons {
1139: my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
1140: $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" /> ';
1141: $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1142: $buttons.='<input type="text" size="5" name="chksec" /> ';
1143: return $buttons;
1144: }
1145:
1146: # Displays the submissions for one student or a group of students
1147: sub processGroup {
1148: my ($request,$symb) = @_;
1149: my $ctr = 0;
1150: my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1151: my $total = scalar(@stuchecked)-1;
1152:
1153: foreach my $student (@stuchecked) {
1154: my ($uname,$udom,$fullname) = split(/:/,$student);
1155: $env{'form.student'} = $uname;
1156: $env{'form.userdom'} = $udom;
1157: $env{'form.fullname'} = $fullname;
1158: &submission($request,$ctr,$total,$symb);
1159: $ctr++;
1160: }
1161: return '';
1162: }
1163:
1164: #------------------------------------------------------------------------------------
1165: #
1166: #-------------------------- Next few routines handles grading by student, essentially
1167: # handles essay response type problem/part
1168: #
1169: #--- Javascript to handle the submission page functionality ---
1170: sub sub_page_js {
1171: my $request = shift;
1172: my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1173: $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1174: function updateRadio(formname,id,weight) {
1175: var gradeBox = formname["GD_BOX"+id];
1176: var radioButton = formname["RADVAL"+id];
1177: var oldpts = formname["oldpts"+id].value;
1178: var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1179: gradeBox.value = pts;
1180: var resetbox = false;
1181: if (isNaN(pts) || pts < 0) {
1182: alert("$alertmsg"+pts);
1183: for (var i=0; i<radioButton.length; i++) {
1184: if (radioButton[i].checked) {
1185: gradeBox.value = i;
1186: resetbox = true;
1187: }
1188: }
1189: if (!resetbox) {
1190: formtextbox.value = "";
1191: }
1192: return;
1193: }
1194:
1195: if (pts > weight) {
1196: var resp = confirm("You entered a value ("+pts+
1197: ") greater than the weight for the part. Accept?");
1198: if (resp == false) {
1199: gradeBox.value = oldpts;
1200: return;
1201: }
1202: }
1203:
1204: for (var i=0; i<radioButton.length; i++) {
1205: radioButton[i].checked=false;
1206: if (pts == i && pts != "") {
1207: radioButton[i].checked=true;
1208: }
1209: }
1210: updateSelect(formname,id);
1211: formname["stores"+id].value = "0";
1212: }
1213:
1214: function writeBox(formname,id,pts) {
1215: var gradeBox = formname["GD_BOX"+id];
1216: if (checkSolved(formname,id) == 'update') {
1217: gradeBox.value = pts;
1218: } else {
1219: var oldpts = formname["oldpts"+id].value;
1220: gradeBox.value = oldpts;
1221: var radioButton = formname["RADVAL"+id];
1222: for (var i=0; i<radioButton.length; i++) {
1223: radioButton[i].checked=false;
1224: if (i == oldpts) {
1225: radioButton[i].checked=true;
1226: }
1227: }
1228: }
1229: formname["stores"+id].value = "0";
1230: updateSelect(formname,id);
1231: return;
1232: }
1233:
1234: function clearRadBox(formname,id) {
1235: if (checkSolved(formname,id) == 'noupdate') {
1236: updateSelect(formname,id);
1237: return;
1238: }
1239: gradeSelect = formname["GD_SEL"+id];
1240: for (var i=0; i<gradeSelect.length; i++) {
1241: if (gradeSelect[i].selected) {
1242: var selectx=i;
1243: }
1244: }
1245: var stores = formname["stores"+id];
1246: if (selectx == stores.value) { return };
1247: var gradeBox = formname["GD_BOX"+id];
1248: gradeBox.value = "";
1249: var radioButton = formname["RADVAL"+id];
1250: for (var i=0; i<radioButton.length; i++) {
1251: radioButton[i].checked=false;
1252: }
1253: stores.value = selectx;
1254: }
1255:
1256: function checkSolved(formname,id) {
1257: if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1258: var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
1259: if (!reply) {return "noupdate";}
1260: formname.overRideScore.value = 'yes';
1261: }
1262: return "update";
1263: }
1264:
1265: function updateSelect(formname,id) {
1266: formname["GD_SEL"+id][0].selected = true;
1267: return;
1268: }
1269:
1270: //=========== Check that a point is assigned for all the parts ============
1271: function checksubmit(formname,val,total,parttot) {
1272: formname.gradeOpt.value = val;
1273: if (val == "Save & Next") {
1274: for (i=0;i<=total;i++) {
1275: for (j=0;j<parttot;j++) {
1276: var partid = formname["partid"+i+"_"+j].value;
1277: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1278: var points = formname["GD_BOX"+i+"_"+partid].value;
1279: if (points == "") {
1280: var name = formname["name"+i].value;
1281: var studentID = (name != '' ? name : formname["unamedom"+i].value);
1282: var resp = confirm("You did not assign a score for "+studentID+
1283: ", part "+partid+". Continue?");
1284: if (resp == false) {
1285: formname["GD_BOX"+i+"_"+partid].focus();
1286: return false;
1287: }
1288: }
1289: }
1290:
1291: }
1292: }
1293:
1294: }
1295: formname.submit();
1296: }
1297:
1298: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
1299: function checkSubmitPage(formname,total) {
1300: noscore = new Array(100);
1301: var ptr = 0;
1302: for (i=1;i<total;i++) {
1303: var partid = formname["q_"+i].value;
1304: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1305: var points = formname["GD_BOX"+i+"_"+partid].value;
1306: var status = formname["solved"+i+"_"+partid].value;
1307: if (points == "" && status != "correct_by_student") {
1308: noscore[ptr] = i;
1309: ptr++;
1310: }
1311: }
1312: }
1313: if (ptr != 0) {
1314: var sense = ptr == 1 ? ": " : "s: ";
1315: var prolist = "";
1316: if (ptr == 1) {
1317: prolist = noscore[0];
1318: } else {
1319: var i = 0;
1320: while (i < ptr-1) {
1321: prolist += noscore[i]+", ";
1322: i++;
1323: }
1324: prolist += "and "+noscore[i];
1325: }
1326: var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
1327: if (resp == false) {
1328: return false;
1329: }
1330: }
1331:
1332: formname.submit();
1333: }
1334: SUBJAVASCRIPT
1335: }
1336:
1337: #--- javascript for essay type problem --
1338: sub sub_page_kw_js {
1339: my $request = shift;
1340: my $iconpath = $request->dir_config('lonIconsURL');
1341: &commonJSfunctions($request);
1342:
1343: my $inner_js_msg_central= (<<INNERJS);
1344: <script type="text/javascript">
1345: function checkInput() {
1346: opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
1347: var nmsg = opener.document.SCORE.savemsgN.value;
1348: var usrctr = document.msgcenter.usrctr.value;
1349: var newval = opener.document.SCORE["newmsg"+usrctr];
1350: newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
1351:
1352: var msgchk = "";
1353: if (document.msgcenter.subchk.checked) {
1354: msgchk = "msgsub,";
1355: }
1356: var includemsg = 0;
1357: for (var i=1; i<=nmsg; i++) {
1358: var opnmsg = opener.document.SCORE["savemsg"+i];
1359: var frmmsg = document.msgcenter["msg"+i];
1360: opnmsg.value = opener.checkEntities(frmmsg.value);
1361: var showflg = opener.document.SCORE["shownOnce"+i];
1362: showflg.value = "1";
1363: var chkbox = document.msgcenter["msgn"+i];
1364: if (chkbox.checked) {
1365: msgchk += "savemsg"+i+",";
1366: includemsg = 1;
1367: }
1368: }
1369: if (document.msgcenter.newmsgchk.checked) {
1370: msgchk += "newmsg"+usrctr;
1371: includemsg = 1;
1372: }
1373: imgformname = opener.document.SCORE["mailicon"+usrctr];
1374: imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
1375: var includemsg = opener.document.SCORE["includemsg"+usrctr];
1376: includemsg.value = msgchk;
1377:
1378: self.close()
1379:
1380: }
1381: </script>
1382: INNERJS
1383:
1384: my $inner_js_highlight_central= (<<INNERJS);
1385: <script type="text/javascript">
1386: function updateChoice(flag) {
1387: opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
1388: opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
1389: opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
1390: opener.document.SCORE.refresh.value = "on";
1391: if (opener.document.SCORE.keywords.value!=""){
1392: opener.document.SCORE.submit();
1393: }
1394: self.close()
1395: }
1396: </script>
1397: INNERJS
1398:
1399: my $start_page_msg_central =
1400: &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
1401: {'js_ready' => 1,
1402: 'only_body' => 1,
1403: 'bgcolor' =>'#FFFFFF',});
1404: my $end_page_msg_central =
1405: &Apache::loncommon::end_page({'js_ready' => 1});
1406:
1407:
1408: my $start_page_highlight_central =
1409: &Apache::loncommon::start_page('Highlight Central',
1410: $inner_js_highlight_central,
1411: {'js_ready' => 1,
1412: 'only_body' => 1,
1413: 'bgcolor' =>'#FFFFFF',});
1414: my $end_page_highlight_central =
1415: &Apache::loncommon::end_page({'js_ready' => 1});
1416:
1417: my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1418: $docopen=~s/^document\.//;
1419: my %lt = &Apache::lonlocal::texthash(
1420: keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
1421: plse => 'Please select a word or group of words from document and then click this link.',
1422: adds => 'Add selection to keyword list? Edit if desired.',
1423: comp => 'Compose Message for: ',
1424: incl => 'Include',
1425: type => 'Type',
1426: subj => 'Subject',
1427: mesa => 'Message',
1428: new => 'New',
1429: save => 'Save',
1430: canc => 'Cancel',
1431: kehi => 'Keyword Highlight Options',
1432: txtc => 'Text Color',
1433: font => 'Font Size',
1434: fnst => 'Font Style',
1435: );
1436: $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1437:
1438: //===================== Show list of keywords ====================
1439: function keywords(formname) {
1440: var nret = prompt("$lt{'keyw'}",formname.keywords.value);
1441: if (nret==null) return;
1442: formname.keywords.value = nret;
1443:
1444: if (formname.keywords.value != "") {
1445: formname.refresh.value = "on";
1446: formname.submit();
1447: }
1448: return;
1449: }
1450:
1451: //===================== Script to view submitted by ==================
1452: function viewSubmitter(submitter) {
1453: document.SCORE.refresh.value = "on";
1454: document.SCORE.NCT.value = "1";
1455: document.SCORE.unamedom0.value = submitter;
1456: document.SCORE.submit();
1457: return;
1458: }
1459:
1460: //===================== Script to add keyword(s) ==================
1461: function getSel() {
1462: if (document.getSelection) txt = document.getSelection();
1463: else if (document.selection) txt = document.selection.createRange().text;
1464: else return;
1465: var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
1466: if (cleantxt=="") {
1467: alert("$lt{'plse'}");
1468: return;
1469: }
1470: var nret = prompt("$lt{'adds'}",cleantxt);
1471: if (nret==null) return;
1472: document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1473: if (document.SCORE.keywords.value != "") {
1474: document.SCORE.refresh.value = "on";
1475: document.SCORE.submit();
1476: }
1477: return;
1478: }
1479:
1480: //====================== Script for composing message ==============
1481: // preload images
1482: img1 = new Image();
1483: img1.src = "$iconpath/mailbkgrd.gif";
1484: img2 = new Image();
1485: img2.src = "$iconpath/mailto.gif";
1486:
1487: function msgCenter(msgform,usrctr,fullname) {
1488: var Nmsg = msgform.savemsgN.value;
1489: savedMsgHeader(Nmsg,usrctr,fullname);
1490: var subject = msgform.msgsub.value;
1491: var msgchk = document.SCORE["includemsg"+usrctr].value;
1492: re = /msgsub/;
1493: var shwsel = "";
1494: if (re.test(msgchk)) { shwsel = "checked" }
1495: subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
1496: displaySubject(checkEntities(subject),shwsel);
1497: for (var i=1; i<=Nmsg; i++) {
1498: var testmsg = "savemsg"+i+",";
1499: re = new RegExp(testmsg,"g");
1500: shwsel = "";
1501: if (re.test(msgchk)) { shwsel = "checked" }
1502: var message = document.SCORE["savemsg"+i].value;
1503: message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1504: displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
1505: //any < is already converted to <, etc. However, only once!!
1506: }
1507: newmsg = document.SCORE["newmsg"+usrctr].value;
1508: shwsel = "";
1509: re = /newmsg/;
1510: if (re.test(msgchk)) { shwsel = "checked" }
1511: newMsg(newmsg,shwsel);
1512: msgTail();
1513: return;
1514: }
1515:
1516: function checkEntities(strx) {
1517: if (strx.length == 0) return strx;
1518: var orgStr = ["&", "<", ">", '"'];
1519: var newStr = ["&", "<", ">", """];
1520: var counter = 0;
1521: while (counter < 4) {
1522: strx = strReplace(strx,orgStr[counter],newStr[counter]);
1523: counter++;
1524: }
1525: return strx;
1526: }
1527:
1528: function strReplace(strx, orgStr, newStr) {
1529: return strx.split(orgStr).join(newStr);
1530: }
1531:
1532: function savedMsgHeader(Nmsg,usrctr,fullname) {
1533: var height = 70*Nmsg+250;
1534: if (height > 600) {
1535: height = 600;
1536: }
1537: var xpos = (screen.width-600)/2;
1538: xpos = (xpos < 0) ? '0' : xpos;
1539: var ypos = (screen.height-height)/2-30;
1540: ypos = (ypos < 0) ? '0' : ypos;
1541:
1542: pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1543: pWin.focus();
1544: pDoc = pWin.document;
1545: pDoc.$docopen;
1546: pDoc.write('$start_page_msg_central');
1547:
1548: pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
1549: pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1550: pDoc.write("<h1> $lt{'comp'}\"+fullname+\"<\\/h1>");
1551:
1552: pDoc.write('<table style="border:1px solid black;"><tr>');
1553: pDoc.write("<td><b>$lt{'incl'}<\\/b><\\/td><td><b>$lt{'type'}<\\/b><\\/td><td><b>$lt{'mesa'}<\\/td><\\/tr>");
1554: }
1555: function displaySubject(msg,shwsel) {
1556: pDoc = pWin.document;
1557: pDoc.write("<tr>");
1558: pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1559: pDoc.write("<td>$lt{'subj'}<\\/td>");
1560: pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1561: }
1562:
1563: function displaySavedMsg(ctr,msg,shwsel) {
1564: pDoc = pWin.document;
1565: pDoc.write("<tr>");
1566: pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1567: pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
1568: pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1569: }
1570:
1571: function newMsg(newmsg,shwsel) {
1572: pDoc = pWin.document;
1573: pDoc.write("<tr>");
1574: pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1575: pDoc.write("<td align=\\"center\\">$lt{'new'}<\\/td>");
1576: pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1577: }
1578:
1579: function msgTail() {
1580: pDoc = pWin.document;
1581: //pDoc.write("<\\/table>");
1582: pDoc.write("<\\/td><\\/tr><\\/table> ");
1583: pDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:checkInput()\\"> ");
1584: pDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1585: pDoc.write("<\\/form>");
1586: pDoc.write('$end_page_msg_central');
1587: pDoc.close();
1588: }
1589:
1590: //====================== Script for keyword highlight options ==============
1591: function kwhighlight() {
1592: var kwclr = document.SCORE.kwclr.value;
1593: var kwsize = document.SCORE.kwsize.value;
1594: var kwstyle = document.SCORE.kwstyle.value;
1595: var redsel = "";
1596: var grnsel = "";
1597: var blusel = "";
1598: if (kwclr=="red") {var redsel="checked"};
1599: if (kwclr=="green") {var grnsel="checked"};
1600: if (kwclr=="blue") {var blusel="checked"};
1601: var sznsel = "";
1602: var sz1sel = "";
1603: var sz2sel = "";
1604: if (kwsize=="0") {var sznsel="checked"};
1605: if (kwsize=="+1") {var sz1sel="checked"};
1606: if (kwsize=="+2") {var sz2sel="checked"};
1607: var synsel = "";
1608: var syisel = "";
1609: var sybsel = "";
1610: if (kwstyle=="") {var synsel="checked"};
1611: if (kwstyle=="<i>") {var syisel="checked"};
1612: if (kwstyle=="<b>") {var sybsel="checked"};
1613: highlightCentral();
1614: highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
1615: highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
1616: highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
1617: highlightend();
1618: return;
1619: }
1620:
1621: function highlightCentral() {
1622: // if (window.hwdWin) window.hwdWin.close();
1623: var xpos = (screen.width-400)/2;
1624: xpos = (xpos < 0) ? '0' : xpos;
1625: var ypos = (screen.height-330)/2-30;
1626: ypos = (ypos < 0) ? '0' : ypos;
1627:
1628: hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1629: hwdWin.focus();
1630: var hDoc = hwdWin.document;
1631: hDoc.$docopen;
1632: hDoc.write('$start_page_highlight_central');
1633: hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1634: hDoc.write("<h3><span class=\\"LC_info\\"> $lt{'kehi'}<\\/span><\\/h3><br /><br />");
1635:
1636: hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
1637: hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1638: hDoc.write("<td><b>$lt{'txtc'}<\\/b><\\/td><td><b>$lt{'font'}<\\/b><\\/td><td><b>$lt{'fnst'}<\\/td><\\/tr>");
1639: }
1640:
1641: function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) {
1642: var hDoc = hwdWin.document;
1643: hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1644: hDoc.write("<td align=\\"left\\">");
1645: hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+"> "+clrtxt+"<\\/td>");
1646: hDoc.write("<td align=\\"left\\">");
1647: hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+"> "+sztxt+"<\\/td>");
1648: hDoc.write("<td align=\\"left\\">");
1649: hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+"> "+sytxt+"<\\/td>");
1650: hDoc.write("<\\/tr>");
1651: }
1652:
1653: function highlightend() {
1654: var hDoc = hwdWin.document;
1655: hDoc.write("<\\/table>");
1656: hDoc.write("<\\/td><\\/tr><\\/table> ");
1657: hDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\"> ");
1658: hDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1659: hDoc.write("<\\/form>");
1660: hDoc.write('$end_page_highlight_central');
1661: hDoc.close();
1662: }
1663:
1664: SUBJAVASCRIPT
1665: }
1666:
1667: sub get_increment {
1668: my $increment = $env{'form.increment'};
1669: if ($increment != 1 && $increment != .5 && $increment != .25 &&
1670: $increment != .1) {
1671: $increment = 1;
1672: }
1673: return $increment;
1674: }
1675:
1676: sub gradeBox_start {
1677: return (
1678: &Apache::loncommon::start_data_table()
1679: .&Apache::loncommon::start_data_table_header_row()
1680: .'<th>'.&mt('Part').'</th>'
1681: .'<th>'.&mt('Points').'</th>'
1682: .'<th> </th>'
1683: .'<th>'.&mt('Assign Grade').'</th>'
1684: .'<th>'.&mt('Weight').'</th>'
1685: .'<th>'.&mt('Grade Status').'</th>'
1686: .&Apache::loncommon::end_data_table_header_row()
1687: );
1688: }
1689:
1690: sub gradeBox_end {
1691: return (
1692: &Apache::loncommon::end_data_table()
1693: );
1694: }
1695: #--- displays the grading box, used in essay type problem and grading by page/sequence
1696: sub gradeBox {
1697: my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1698: my $checkIcon = '<img alt="'.&mt('Check Mark').
1699: '" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1700: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1701: my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)')
1702: : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1703: $wgt = ($wgt > 0 ? $wgt : '1');
1704: my $score = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1705: '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1706: my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1707: my $display_part= &get_display_part($partid,$symb);
1708: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
1709: [$partid]);
1710: my $aggtries = $$record{'resource.'.$partid.'.tries'};
1711: if ($last_resets{$partid}) {
1712: $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
1713: }
1714: my $result=&Apache::loncommon::start_data_table_row();
1715: my $ctr = 0;
1716: my $thisweight = 0;
1717: my $increment = &get_increment();
1718:
1719: my $radio.='<table border="0"><tr>'."\n"; # display radio buttons in a nice table 10 across
1720: while ($thisweight<=$wgt) {
1721: $radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1722: 'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1723: $thisweight.')" value="'.$thisweight.'" '.
1724: ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1725: $radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1726: $thisweight += $increment;
1727: $ctr++;
1728: }
1729: $radio.='</tr></table>';
1730:
1731: my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1732: ($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1733: 'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1734: $wgt.')" /></td>'."\n";
1735: $line.='<td>/'.$wgt.' '.$wgtmsg.
1736: ($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? ' '.$checkIcon : '').
1737: ' </td>'."\n";
1738: $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1739: 'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1740: if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1741: $line.='<option></option>'.
1742: '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1743: } else {
1744: $line.='<option selected="selected"></option>'.
1745: '<option value="excused" >'.&mt('excused').'</option>';
1746: }
1747: $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
1748:
1749:
1750: $result .=
1751: '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
1752: $result.=&Apache::loncommon::end_data_table_row();
1753: $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
1754: $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
1755: '<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
1756: '<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1757: $$record{'resource.'.$partid.'.solved'}.'" />'."\n".
1758: '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
1759: $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
1760: '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
1761: $aggtries.'" />'."\n";
1762: my $res_error;
1763: $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1764: $result.='</td>'.&Apache::loncommon::end_data_table_row();
1765: if ($res_error) {
1766: return &navmap_errormsg();
1767: }
1768: return $result;
1769: }
1770:
1771: sub handback_box {
1772: my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
1773: my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
1774: my (@respids);
1775: my @part_response_id = &flatten_responseType($responseType);
1776: foreach my $part_response_id (@part_response_id) {
1777: my ($part,$resp) = @{ $part_response_id };
1778: if ($part eq $partid) {
1779: push(@respids,$resp);
1780: }
1781: }
1782: my $result;
1783: foreach my $respid (@respids) {
1784: my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
1785: my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
1786: next if (!@$files);
1787: my $file_counter = 0;
1788: foreach my $file (@$files) {
1789: if ($file =~ /\/portfolio\//) {
1790: $file_counter++;
1791: my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1792: my ($name,$version,$ext) = &file_name_version_ext($file_disp);
1793: $file_disp = "$name.$ext";
1794: $file = $file_path.$file_disp;
1795: $result.=&mt('Return commented version of [_1] to student.',
1796: '<span class="LC_filename">'.$file_disp.'</span>');
1797: $result.='<input type="file" name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1798: $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1799: }
1800: }
1801: if ($file_counter) {
1802: $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
1803: '<span class="LC_info">'.
1804: '('.&mt('File(s) will be uploaded when you click on Save & Next below.',$file_counter).')</span><br /><br />';
1805: }
1806: }
1807: return $result;
1808: }
1809:
1810: sub show_problem {
1811: my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1812: my $rendered;
1813: my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1814: &Apache::lonxml::remember_problem_counter();
1815: if ($mode eq 'both' or $mode eq 'text') {
1816: $rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1817: $env{'request.course.id'},
1818: undef,\%form);
1819: }
1820: if ($removeform) {
1821: $rendered=~s|<form(.*?)>||g;
1822: $rendered=~s|</form>||g;
1823: $rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1824: }
1825: my $companswer;
1826: if ($mode eq 'both' or $mode eq 'answer') {
1827: &Apache::lonxml::restore_problem_counter();
1828: $companswer=
1829: &Apache::loncommon::get_student_answers($symb,$uname,$udom,
1830: $env{'request.course.id'},
1831: %form);
1832: }
1833: if ($removeform) {
1834: $companswer=~s|<form(.*?)>||g;
1835: $companswer=~s|</form>||g;
1836: $companswer=~s|name="submit"|name="would_have_been_submit"|g;
1837: }
1838: my $renderheading = &mt('View of the problem');
1839: my $answerheading = &mt('Correct answer');
1840: if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1841: my $stu_fullname = $env{'form.fullname'};
1842: if ($stu_fullname eq '') {
1843: $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
1844: }
1845: my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
1846: if ($forwhom ne '') {
1847: $renderheading = &mt('View of the problem for[_1]',$forwhom);
1848: $answerheading = &mt('Correct answer for[_1]',$forwhom);
1849: }
1850: }
1851: $rendered=
1852: '<div class="LC_Box">'
1853: .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1854: .$rendered
1855: .'</div>';
1856: $companswer=
1857: '<div class="LC_Box">'
1858: .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1859: .$companswer
1860: .'</div>';
1861: my $result;
1862: if ($mode eq 'both') {
1863: $result=$rendered.$companswer;
1864: } elsif ($mode eq 'text') {
1865: $result=$rendered;
1866: } elsif ($mode eq 'answer') {
1867: $result=$companswer;
1868: }
1869: return $result;
1870: }
1871:
1872: sub files_exist {
1873: my ($r, $symb) = @_;
1874: my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1875:
1876: foreach my $student (@students) {
1877: my ($uname,$udom,$fullname) = split(/:/,$student);
1878: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
1879: $udom,$uname);
1880: my ($string,$timestamp)= &get_last_submission(\%record);
1881: foreach my $submission (@$string) {
1882: my ($partid,$respid) =
1883: ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1884: my $files=&get_submitted_files($udom,$uname,$partid,$respid,
1885: \%record);
1886: return 1 if (@$files);
1887: }
1888: }
1889: return 0;
1890: }
1891:
1892: sub download_all_link {
1893: my ($r,$symb) = @_;
1894: unless (&files_exist($r, $symb)) {
1895: $r->print(&mt('There are currently no submitted documents.'));
1896: return;
1897: }
1898:
1899: my $all_students =
1900: join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
1901:
1902: my $parts =
1903: join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
1904:
1905: my $identifier = &Apache::loncommon::get_cgi_id();
1906: &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
1907: 'cgi.'.$identifier.'.symb' => $symb,
1908: 'cgi.'.$identifier.'.parts' => $parts,});
1909: $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
1910: &mt('Download All Submitted Documents').'</a>');
1911: return;
1912: }
1913:
1914: sub submit_download_link {
1915: my ($request,$symb) = @_;
1916: if (!$symb) { return ''; }
1917: #FIXME: Figure out which type of problem this is and provide appropriate download
1918: &download_all_link($request,$symb);
1919: }
1920:
1921: sub build_section_inputs {
1922: my $section_inputs;
1923: if ($env{'form.section'} eq '') {
1924: $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
1925: } else {
1926: my @sections = &Apache::loncommon::get_env_multiple('form.section');
1927: foreach my $section (@sections) {
1928: $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
1929: }
1930: }
1931: return $section_inputs;
1932: }
1933:
1934: # --------------------------- show submissions of a student, option to grade
1935: sub submission {
1936: my ($request,$counter,$total,$symb) = @_;
1937: my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
1938: $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
1939: my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
1940: $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1941:
1942: my $probtitle=&Apache::lonnet::gettitle($symb);
1943: if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1944:
1945: if (!&canview($usec)) {
1946: $request->print(
1947: '<span class="LC_warning">'.
1948: &mt('Unable to view requested student.').
1949: ' '.&mt('([_1] in section [_2] in course id [_3])',
1950: $uname.':'.$udom,$usec,$env{'request.course.id'}).
1951: '</span>');
1952: return;
1953: }
1954:
1955: if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
1956: if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
1957: if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
1958: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1959: my $checkIcon = '<img alt="'.&mt('Check Mark').
1960: '" src="'.$request->dir_config('lonIconsURL').
1961: '/check.gif" height="16" border="0" />';
1962:
1963: # header info
1964: if ($counter == 0) {
1965: &sub_page_js($request);
1966: &sub_page_kw_js($request);
1967:
1968: # option to display problem, only once else it cause problems
1969: # with the form later since the problem has a form.
1970: if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1971: my $mode;
1972: if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1973: $mode='both';
1974: } elsif ($env{'form.vProb'} eq 'yes') {
1975: $mode='text';
1976: } elsif ($env{'form.vAns'} eq 'yes') {
1977: $mode='answer';
1978: }
1979: &Apache::lonxml::clear_problem_counter();
1980: $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1981: }
1982:
1983: # kwclr is the only variable that is guaranteed not to be blank
1984: # if this subroutine has been called once.
1985: my %keyhash = ();
1986: # if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1987: if (1) {
1988: %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1989: $env{'course.'.$env{'request.course.id'}.'.domain'},
1990: $env{'course.'.$env{'request.course.id'}.'.num'});
1991:
1992: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1993: $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
1994: $env{'form.kwclr'} = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
1995: $env{'form.kwsize'} = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
1996: $env{'form.kwstyle'} = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
1997: $env{'form.msgsub'} = $keyhash{$symb.'_subject'} ne '' ?
1998: $keyhash{$symb.'_subject'} : $probtitle;
1999: $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
2000: }
2001: my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
2002: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
2003: $request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
2004: '<input type="hidden" name="command" value="handgrade" />'."\n".
2005: '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
2006: '<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
2007: '<input type="hidden" name="refresh" value="off" />'."\n".
2008: '<input type="hidden" name="studentNo" value="" />'."\n".
2009: '<input type="hidden" name="gradeOpt" value="" />'."\n".
2010: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
2011: '<input type="hidden" name="vProb" value="'.$env{'form.vProb'}.'" />'."\n".
2012: '<input type="hidden" name="vAns" value="'.$env{'form.vAns'}.'" />'."\n".
2013: '<input type="hidden" name="lastSub" value="'.$env{'form.lastSub'}.'" />'."\n".
2014: &build_section_inputs().
2015: '<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
2016: '<input type="hidden" name="NCT"'.
2017: ' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
2018: # if ($env{'form.handgrade'} eq 'yes') {
2019: if (1) {
2020: $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
2021: '<input type="hidden" name="kwclr" value="'.$env{'form.kwclr'}.'" />'."\n".
2022: '<input type="hidden" name="kwsize" value="'.$env{'form.kwsize'}.'" />'."\n".
2023: '<input type="hidden" name="kwstyle" value="'.$env{'form.kwstyle'}.'" />'."\n".
2024: '<input type="hidden" name="msgsub" value="'.$env{'form.msgsub'}.'" />'."\n".
2025: '<input type="hidden" name="shownSub" value="0" />'."\n".
2026: '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
2027: foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
2028: $request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
2029: }
2030: }
2031:
2032: my ($cts,$prnmsg) = (1,'');
2033: while ($cts <= $env{'form.savemsgN'}) {
2034: $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
2035: (!exists($keyhash{$symb.'_savemsg'.$cts}) ?
2036: &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
2037: &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
2038: '" />'."\n".
2039: '<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
2040: $cts++;
2041: }
2042: $request->print($prnmsg);
2043:
2044: # if ($env{'form.handgrade'} eq 'yes') {
2045: if (1) {
2046:
2047: my %lt = &Apache::lonlocal::texthash(
2048: keyw => 'Keyword Options',
2049: list => 'List',
2050: past => 'Paste Selection to List',
2051: high => 'Highlight Attribute',
2052: );
2053: #
2054: # Print out the keyword options line
2055: #
2056: $request->print(<<KEYWORDS);
2057: <br /><b>$lt{'keyw'}:</b>
2058: <a href="javascript:keywords(document.SCORE);" target="_self">$lt{'list'}</a>
2059: <a href="#" onmousedown="javascript:getSel(); return false"
2060: class="page">$lt{'past'}</a>
2061: <a href="javascript:kwhighlight();" target="_self">$lt{'high'}</a><br /><br />
2062: KEYWORDS
2063: #
2064: # Load the other essays for similarity check
2065: #
2066: my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
2067: my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
2068: $apath=&escape($apath);
2069: $apath=~s/\W/\_/gs;
2070: &init_old_essays($symb,$apath,$adom,$aname);
2071: }
2072: }
2073:
2074: # This is where output for one specific student would start
2075: my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
2076: $request->print(
2077: "\n\n"
2078: .'<div class="LC_grade_show_user'.$add_class.'">'
2079: .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
2080: ."\n"
2081: );
2082:
2083: # Show additional functions if allowed
2084: if ($perm{'vgr'}) {
2085: $request->print(
2086: &Apache::loncommon::track_student_link(
2087: 'View recent activity',
2088: $uname,$udom,'check')
2089: .' '
2090: );
2091: }
2092: if ($perm{'opa'}) {
2093: $request->print(
2094: &Apache::loncommon::pprmlink(
2095: &mt('Set/Change parameters'),
2096: $uname,$udom,$symb,'check'));
2097: }
2098:
2099: # Show Problem
2100: if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
2101: my $mode;
2102: if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
2103: $mode='both';
2104: } elsif ($env{'form.vProb'} eq 'all' ) {
2105: $mode='text';
2106: } elsif ($env{'form.vAns'} eq 'all') {
2107: $mode='answer';
2108: }
2109: &Apache::lonxml::clear_problem_counter();
2110: $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
2111: }
2112:
2113: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
2114: my $res_error;
2115: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
2116: if ($res_error) {
2117: $request->print(&navmap_errormsg());
2118: return;
2119: }
2120:
2121: # Display student info
2122: $request->print(($counter == 0 ? '' : '<br />'));
2123:
2124: my $result='<div class="LC_Box">'
2125: .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
2126: $result.='<input type="hidden" name="name'.$counter.
2127: '" value="'.$env{'form.fullname'}.'" />'."\n";
2128: # if ($env{'form.handgrade'} eq 'no') {
2129: if (1) {
2130: $result.='<p class="LC_info">'
2131: .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
2132: ."</p>\n";
2133: }
2134:
2135: # If any part of the problem is an essay-response (handgraded), then check for collaborators
2136: my $fullname;
2137: my $col_fullnames = [];
2138: # if ($env{'form.handgrade'} eq 'yes') {
2139: if (1) {
2140: (my $sub_result,$fullname,$col_fullnames)=
2141: &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
2142: $counter);
2143: $result.=$sub_result;
2144: }
2145: $request->print($result."\n");
2146:
2147: # print student answer/submission
2148: # Options are (1) Handgraded submission only
2149: # (2) Last submission, includes submission that is not handgraded
2150: # (for multi-response type part)
2151: # (3) Last submission plus the parts info
2152: # (4) The whole record for this student
2153:
2154: my ($string,$timestamp)= &get_last_submission(\%record);
2155:
2156: my $lastsubonly;
2157:
2158: if ($$timestamp eq '') {
2159: $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>';
2160: } else {
2161: $lastsubonly =
2162: '<div class="LC_grade_submissions_body">'
2163: .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
2164:
2165: my %seenparts;
2166: my @part_response_id = &flatten_responseType($responseType);
2167: foreach my $part (@part_response_id) {
2168: next if ($env{'form.lastSub'} eq 'hdgrade'
2169: && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
2170:
2171: my ($partid,$respid) = @{ $part };
2172: my $display_part=&get_display_part($partid,$symb);
2173: if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
2174: if (exists($seenparts{$partid})) { next; }
2175: $seenparts{$partid}=1;
2176: $request->print(
2177: '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
2178: ' <b>'.&mt('Collaborative submission by: [_1]',
2179: '<a href="javascript:viewSubmitter(\''.
2180: $env{"form.$uname:$udom:$partid:submitted_by"}.
2181: '\');" target="_self">'.
2182: $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
2183: '<br />');
2184: next;
2185: }
2186: my $responsetype = $responseType->{$partid}->{$respid};
2187: if (!exists($record{"resource.$partid.$respid.submission"})) {
2188: $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
2189: '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
2190: ' <span class="LC_internal_info">'.
2191: '('.&mt('Response ID: [_1]',$respid).')'.
2192: '</span> '.
2193: '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
2194: next;
2195: }
2196: foreach my $submission (@$string) {
2197: my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
2198: if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
2199: my ($ressub,$hide,$subval) = split(/:/,$submission,3);
2200: # Similarity check
2201: my $similar='';
2202: my ($type,$trial,$rndseed);
2203: if ($hide eq 'rand') {
2204: $type = 'randomizetry';
2205: $trial = $record{"resource.$partid.tries"};
2206: $rndseed = $record{"resource.$partid.rndseed"};
2207: }
2208: if ($env{'form.checkPlag'}) {
2209: my ($oname,$odom,$ocrsid,$oessay,$osim)=
2210: &most_similar($uname,$udom,$symb,$subval);
2211: if ($osim) {
2212: $osim=int($osim*100.0);
2213: my %old_course_desc =
2214: &Apache::lonnet::coursedescription($ocrsid,
2215: {'one_time' => 1});
2216:
2217: if ($hide eq 'anon') {
2218: $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
2219: &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
2220: } else {
2221: $similar="<hr /><h3><span class=\"LC_warning\">".
2222: &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
2223: $osim,
2224: &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
2225: $old_course_desc{'description'},
2226: $old_course_desc{'num'},
2227: $old_course_desc{'domain'}).
2228: '</span></h3><blockquote><i>'.
2229: &keywords_highlight($oessay).
2230: '</i></blockquote><hr />';
2231: }
2232: }
2233: }
2234: my $order=&get_order($partid,$respid,$symb,$uname,$udom,
2235: undef,$type,$trial,$rndseed);
2236: if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' &&
2237: $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
2238: my $display_part=&get_display_part($partid,$symb);
2239: $lastsubonly.='<div class="LC_grade_submission_part">'.
2240: '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
2241: ' <span class="LC_internal_info">'.
2242: '('.&mt('Response ID: [_1]',$respid).')'.
2243: '</span> ';
2244: my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
2245:
2246: if (@$files) {
2247: if ($hide eq 'anon') {
2248: $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
2249: } else {
2250: $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
2251: .'<br /><span class="LC_warning">';
2252: if(@$files == 1) {
2253: $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
2254: } else {
2255: $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
2256: }
2257: $lastsubonly .= '</span>';
2258: foreach my $file (@$files) {
2259: &Apache::lonnet::allowuploaded('/adm/grades',$file);
2260: $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
2261: }
2262: }
2263: $lastsubonly.='<br />';
2264: }
2265: if ($hide eq 'anon') {
2266: $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>';
2267: } else {
2268: $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>'.
2269: &cleanRecord($subval,$responsetype,$symb,$partid,
2270: $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
2271: }
2272: if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
2273: $lastsubonly.='</div>';
2274: }
2275: }
2276: }
2277: $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
2278: }
2279: $request->print($lastsubonly);
2280: if ($env{'form.lastSub'} eq 'datesub') {
2281: my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
2282: $request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
2283: }
2284: if ($env{'form.lastSub'} =~ /^(last|all)$/) {
2285: $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
2286: $env{'request.course.id'},
2287: $last,'.submission',
2288: 'Apache::grades::keywords_highlight'));
2289: }
2290: $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
2291: .$udom.'" />'."\n");
2292: # return if view submission with no grading option
2293: if (!&canmodify($usec)) {
2294: $request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
2295: return;
2296: } else {
2297: $request->print('</div>'."\n");
2298: }
2299:
2300: # essay grading message center
2301: # if ($env{'form.handgrade'} eq 'yes') {
2302: if (1) {
2303: my $result='<div class="LC_grade_message_center">';
2304:
2305: $result.='<div class="LC_grade_message_center_header">'.
2306: &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
2307: my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
2308: my $msgfor = $givenn.' '.$lastname;
2309: if (scalar(@$col_fullnames) > 0) {
2310: my $lastone = pop(@$col_fullnames);
2311: $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
2312: }
2313: $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
2314: $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
2315: '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
2316: $result.=' <a href="javascript:msgCenter(document.SCORE,'.$counter.
2317: ',\''.$msgfor.'\');" target="_self">'.
2318: &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
2319: &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
2320: ' <img src="'.$request->dir_config('lonIconsURL').
2321: '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
2322: '<br /> ('.
2323: &mt('Message will be sent when you click on Save & Next below.').")\n";
2324: $result.='</div></div>';
2325: $request->print($result);
2326: }
2327:
2328: my %seen = ();
2329: my @partlist;
2330: my @gradePartRespid;
2331: my @part_response_id = &flatten_responseType($responseType);
2332: $request->print(
2333: '<div class="LC_Box">'
2334: .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
2335: );
2336: $request->print(&gradeBox_start());
2337: foreach my $part_response_id (@part_response_id) {
2338: my ($partid,$respid) = @{ $part_response_id };
2339: my $part_resp = join('_',@{ $part_response_id });
2340: next if ($seen{$partid} > 0);
2341: $seen{$partid}++;
2342: next if ($$handgrade{$part_resp} ne 'yes'
2343: && $env{'form.lastSub'} eq 'hdgrade');
2344: push(@partlist,$partid);
2345: push(@gradePartRespid,$partid.'.'.$respid);
2346: $request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
2347: }
2348: $request->print(&gradeBox_end()); # </div>
2349: $request->print('</div>');
2350:
2351: $request->print('<div class="LC_grade_info_links">');
2352: $request->print('</div>');
2353:
2354: $result='<input type="hidden" name="partlist'.$counter.
2355: '" value="'.(join ":",@partlist).'" />'."\n";
2356: $result.='<input type="hidden" name="gradePartRespid'.
2357: '" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
2358: my $ctr = 0;
2359: while ($ctr < scalar(@partlist)) {
2360: $result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
2361: $partlist[$ctr].'" />'."\n";
2362: $ctr++;
2363: }
2364: $request->print($result.''."\n");
2365:
2366: # Done with printing info for one student
2367:
2368: $request->print('</div>');#LC_grade_show_user
2369:
2370:
2371: # print end of form
2372: if ($counter == $total) {
2373: my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
2374: $endform.='<input type="button" value="'.&mt('Save & Next').'" '.
2375: 'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
2376: $total.','.scalar(@partlist).');" target="_self" /> '."\n";
2377: my $ntstu ='<select name="NTSTU">'.
2378: '<option>1</option><option>2</option>'.
2379: '<option>3</option><option>5</option>'.
2380: '<option>7</option><option>10</option></select>'."\n";
2381: my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
2382: $ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
2383: $endform.=&mt('[_1]student(s)',$ntstu);
2384: $endform.=' <input type="button" value="'.&mt('Previous').'" '.
2385: 'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> '."\n".
2386: '<input type="button" value="'.&mt('Next').'" '.
2387: 'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> ';
2388: $endform.='<span class="LC_warning">'.
2389: &mt('(Next and Previous (student) do not save the scores.)').
2390: '</span>'."\n" ;
2391: $endform.="<input type='hidden' value='".&get_increment().
2392: "' name='increment' />";
2393: $endform.='</td></tr></table></form>';
2394: $request->print($endform);
2395: }
2396: return '';
2397: }
2398:
2399: sub check_collaborators {
2400: my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
2401: my ($result,@col_fullnames);
2402: my ($classlist,undef,$fullname) = &getclasslist('all','0');
2403: foreach my $part (keys(%$handgrade)) {
2404: my $ncol = &Apache::lonnet::EXT('resource.'.$part.
2405: '.maxcollaborators',
2406: $symb,$udom,$uname);
2407: next if ($ncol <= 0);
2408: $part =~ s/\_/\./g;
2409: next if ($record->{'resource.'.$part.'.collaborators'} eq '');
2410: my (@good_collaborators, @bad_collaborators);
2411: foreach my $possible_collaborator
2412: (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) {
2413: $possible_collaborator =~ s/[\$\^\(\)]//g;
2414: next if ($possible_collaborator eq '');
2415: my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
2416: $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
2417: next if ($co_name eq $uname && $co_dom eq $udom);
2418: # Doing this grep allows 'fuzzy' specification
2419: my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i,
2420: keys(%$classlist));
2421: if (! scalar(@matches)) {
2422: push(@bad_collaborators, $possible_collaborator);
2423: } else {
2424: push(@good_collaborators, @matches);
2425: }
2426: }
2427: if (scalar(@good_collaborators) != 0) {
2428: $result.='<br />'.&mt('Collaborators:').'<ol>';
2429: foreach my $name (@good_collaborators) {
2430: my ($lastname,$givenn) = split(/,/,$$fullname{$name});
2431: push(@col_fullnames, $givenn.' '.$lastname);
2432: $result.='<li>'.$fullname->{$name}.'</li>';
2433: }
2434: $result.='</ol><br />'."\n";
2435: my ($part)=split(/\./,$part);
2436: $result.='<input type="hidden" name="collaborator'.$counter.
2437: '" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
2438: "\n";
2439: }
2440: if (scalar(@bad_collaborators) > 0) {
2441: $result.='<div class="LC_warning">';
2442: $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
2443: $result .= '</div>';
2444: }
2445: if (scalar(@bad_collaborators > $ncol)) {
2446: $result .= '<div class="LC_warning">';
2447: $result .= &mt('This student has submitted too many '.
2448: 'collaborators. Maximum is [_1].',$ncol);
2449: $result .= '</div>';
2450: }
2451: }
2452: return ($result,$fullname,\@col_fullnames);
2453: }
2454:
2455: #--- Retrieve the last submission for all the parts
2456: sub get_last_submission {
2457: my ($returnhash)=@_;
2458: my (@string,$timestamp,%lasthidden);
2459: if ($$returnhash{'version'}) {
2460: my %lasthash=();
2461: my ($version);
2462: for ($version=1;$version<=$$returnhash{'version'};$version++) {
2463: foreach my $key (sort(split(/\:/,
2464: $$returnhash{$version.':keys'}))) {
2465: $lasthash{$key}=$$returnhash{$version.':'.$key};
2466: $timestamp =
2467: &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
2468: }
2469: }
2470: my (%typeparts,%randombytry);
2471: my $showsurv =
2472: &Apache::lonnet::allowed('vas',$env{'request.course.id'});
2473: foreach my $key (sort(keys(%lasthash))) {
2474: if ($key =~ /\.type$/) {
2475: if (($lasthash{$key} eq 'anonsurvey') ||
2476: ($lasthash{$key} eq 'anonsurveycred') ||
2477: ($lasthash{$key} eq 'randomizetry')) {
2478: my ($ign,@parts) = split(/\./,$key);
2479: pop(@parts);
2480: my $id = join('.',@parts);
2481: if ($lasthash{$key} eq 'randomizetry') {
2482: $randombytry{$ign.'.'.$id} = $lasthash{$key};
2483: } else {
2484: unless ($showsurv) {
2485: $typeparts{$ign.'.'.$id} = $lasthash{$key};
2486: }
2487: }
2488: delete($lasthash{$key});
2489: }
2490: }
2491: }
2492: my @hidden = keys(%typeparts);
2493: my @randomize = keys(%randombytry);
2494: foreach my $key (keys(%lasthash)) {
2495: next if ($key !~ /\.submission$/);
2496: my $hide;
2497: if (@hidden) {
2498: foreach my $id (@hidden) {
2499: if ($key =~ /^\Q$id\E/) {
2500: $hide = 'anon';
2501: last;
2502: }
2503: }
2504: }
2505: unless ($hide) {
2506: if (@randomize) {
2507: foreach my $id (@hidden) {
2508: if ($key =~ /^\Q$id\E/) {
2509: $hide = 'rand';
2510: last;
2511: }
2512: }
2513: }
2514: }
2515: my ($partid,$foo) = split(/submission$/,$key);
2516: my $draft = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
2517: '<span class="LC_warning">Draft Copy</span> ' : '';
2518: #push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
2519: push(@string, join(':', $key, $hide, $draft.(
2520: ref($lasthash{$key}) eq 'ARRAY' ?
2521: join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
2522: }
2523: }
2524: if (!@string) {
2525: $string[0] =
2526: '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
2527: }
2528: return (\@string,\$timestamp);
2529: }
2530:
2531: #--- High light keywords, with style choosen by user.
2532: sub keywords_highlight {
2533: my $string = shift;
2534: my $size = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
2535: my $styleon = $env{'form.kwstyle'} eq '' ? '' : $env{'form.kwstyle'};
2536: (my $styleoff = $styleon) =~ s/\</\<\//;
2537: my @keylist = split(/[,\s+]/,$env{'form.keywords'});
2538: foreach my $keyword (@keylist) {
2539: $string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
2540: }
2541: return $string;
2542: }
2543:
2544: # For Tasks provide a mechanism to display previous version for one specific student
2545:
2546: sub show_previous_task_version {
2547: my ($request,$symb) = @_;
2548: if ($symb eq '') {
2549: $request->print("Unable to handle ambiguous references.");
2550:
2551: return '';
2552: }
2553: my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
2554: my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
2555: if (!&canview($usec)) {
2556: $request->print(
2557: '<span class="LC_warning">'.
2558: &mt('Unable to view previous version for requested student.').
2559: ' '.&mt('([_1] in section [_2] in course id [_3])',
2560: $uname.':'.$udom,$usec,$env{'request.course.id'}).
2561: '</span>');
2562: return;
2563: }
2564: my $mode = 'both';
2565: my $isTask = ($symb =~/\.task$/);
2566: if ($isTask) {
2567: if ($env{'form.previousversion'} =~ /^\d+$/) {
2568: if ($env{'form.fullname'} eq '') {
2569: $env{'form.fullname'} =
2570: &Apache::loncommon::plainname($uname,$udom,'lastname');
2571: }
2572: my $probtitle=&Apache::lonnet::gettitle($symb);
2573: $request->print("\n\n".
2574: '<div class="LC_grade_show_user">'.
2575: '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
2576: '</h2>'."\n");
2577: &Apache::lonxml::clear_problem_counter();
2578: $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
2579: {'previousversion' => $env{'form.previousversion'} }));
2580: $request->print("\n</div>");
2581: }
2582: }
2583: return;
2584: }
2585:
2586: sub choose_task_version_form {
2587: my ($symb,$uname,$udom,$nomenu) = @_;
2588: my $isTask = ($symb =~/\.task$/);
2589: my ($current,$version,$result,$js,$displayed,$rowtitle);
2590: if ($isTask) {
2591: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
2592: $udom,$uname);
2593: if (($record{'resource.0.version'} eq '') ||
2594: ($record{'resource.0.version'} < 2)) {
2595: return ($record{'resource.0.version'},
2596: $record{'resource.0.version'},$result,$js);
2597: } else {
2598: $current = $record{'resource.0.version'};
2599: }
2600: if ($env{'form.previousversion'}) {
2601: $displayed = $env{'form.previousversion'};
2602: $rowtitle = &mt('Choose another version:')
2603: } else {
2604: $displayed = $current;
2605: $rowtitle = &mt('Show earlier version:');
2606: }
2607: $result = '<div class="LC_left_float">';
2608: my $list;
2609: my $numversions = 0;
2610: for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
2611: if ($i == $current) {
2612: if (!$env{'form.previousversion'} || $nomenu) {
2613: next;
2614: } else {
2615: $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
2616: $numversions ++;
2617: }
2618: } elsif (defined($record{'resource.'.$i.'.0.status'})) {
2619: unless ($i == $env{'form.previousversion'}) {
2620: $numversions ++;
2621: }
2622: $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
2623: }
2624: }
2625: if ($numversions) {
2626: $symb = &HTML::Entities::encode($symb,'<>"&');
2627: $result .=
2628: '<form name="getprev" method="post" action=""'.
2629: ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
2630: &Apache::loncommon::start_data_table().
2631: &Apache::loncommon::start_data_table_row().
2632: '<th align="left">'.$rowtitle.'</th>'.
2633: '<td><select name="version">'.
2634: '<option>'.&mt('Select').'</option>'.
2635: $list.
2636: '</select></td>'.
2637: &Apache::loncommon::end_data_table_row();
2638: unless ($nomenu) {
2639: $result .= &Apache::loncommon::start_data_table_row().
2640: '<th align="left">'.&mt('Open in new window').'</th>'.
2641: '<td><span class="LC_nobreak">'.
2642: '<label><input type="radio" name="prevwin" value="1" />'.
2643: &mt('Yes').'</label>'.
2644: '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
2645: '</span></td>'.
2646: &Apache::loncommon::end_data_table_row();
2647: }
2648: $result .=
2649: &Apache::loncommon::start_data_table_row().
2650: '<th align="left"> </th>'.
2651: '<td>'.
2652: '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
2653: '</td>'.
2654: &Apache::loncommon::end_data_table_row().
2655: &Apache::loncommon::end_data_table().
2656: '</form>';
2657: $js = &previous_display_javascript($nomenu,$current);
2658: } elsif ($displayed && $nomenu) {
2659: $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
2660: } else {
2661: $result .= &mt('No previous versions to show for this student');
2662: }
2663: $result .= '</div>';
2664: }
2665: return ($current,$displayed,$result,$js);
2666: }
2667:
2668: sub previous_display_javascript {
2669: my ($nomenu,$current) = @_;
2670: my $js = <<"JSONE";
2671: <script type="text/javascript">
2672: // <![CDATA[
2673: function previousVersion(uname,udom,symb) {
2674: var current = '$current';
2675: var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
2676: var prevstr = new RegExp("^\\\\d+\$");
2677: if (!prevstr.test(version)) {
2678: return false;
2679: }
2680: var url = '';
2681: if (version == current) {
2682: url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
2683: } else {
2684: url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
2685: }
2686: JSONE
2687: if ($nomenu) {
2688: $js .= <<"JSTWO";
2689: document.location.href = url;
2690: JSTWO
2691: } else {
2692: $js .= <<"JSTHREE";
2693: var newwin = 0;
2694: for (var i=0; i<document.getprev.prevwin.length; i++) {
2695: if (document.getprev.prevwin[i].checked == true) {
2696: newwin = document.getprev.prevwin[i].value;
2697: }
2698: }
2699: if (newwin == 1) {
2700: var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
2701: url = url+'&inhibitmenu=yes';
2702: if (typeof(previousWin) == 'undefined' || previousWin.closed) {
2703: previousWin = window.open(url,'',options,1);
2704: } else {
2705: previousWin.location.href = url;
2706: }
2707: previousWin.focus();
2708: return false;
2709: } else {
2710: document.location.href = url;
2711: return false;
2712: }
2713: JSTHREE
2714: }
2715: $js .= <<"ENDJS";
2716: return false;
2717: }
2718: // ]]>
2719: </script>
2720: ENDJS
2721:
2722: }
2723:
2724: #--- Called from submission routine
2725: sub processHandGrade {
2726: my ($request,$symb) = @_;
2727: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
2728: my $button = $env{'form.gradeOpt'};
2729: my $ngrade = $env{'form.NCT'};
2730: my $ntstu = $env{'form.NTSTU'};
2731: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2732: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2733:
2734: if ($button eq 'Save & Next') {
2735: my $ctr = 0;
2736: while ($ctr < $ngrade) {
2737: my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
2738: my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
2739: if ($errorflag eq 'no_score') {
2740: $ctr++;
2741: next;
2742: }
2743: if ($errorflag eq 'not_allowed') {
2744: $request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
2745: $ctr++;
2746: next;
2747: }
2748: my $includemsg = $env{'form.includemsg'.$ctr};
2749: my ($subject,$message,$msgstatus) = ('','','');
2750: my $restitle = &Apache::lonnet::gettitle($symb);
2751: my ($feedurl,$showsymb) =
2752: &get_feedurl_and_symb($symb,$uname,$udom);
2753: my $messagetail;
2754: if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
2755: $subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
2756: unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
2757: $subject.=' ['.$restitle.']';
2758: my (@msgnum) = split(/,/,$includemsg);
2759: foreach (@msgnum) {
2760: $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
2761: }
2762: $message =&Apache::lonfeedback::clear_out_html($message);
2763: if ($env{'form.withgrades'.$ctr}) {
2764: $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
2765: $messagetail = " for <a href=\"".
2766: $feedurl."?symb=$showsymb\">$restitle</a>";
2767: }
2768: $msgstatus =
2769: &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
2770: $message.$messagetail,
2771: undef,$feedurl,undef,
2772: undef,undef,$showsymb,
2773: $restitle);
2774: $request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
2775: $msgstatus.'<br />');
2776: }
2777: if ($env{'form.collaborator'.$ctr}) {
2778: my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
2779: foreach my $collabstr (@collabstrs) {
2780: my ($part,@collaborators) = split(/:/,$collabstr);
2781: foreach my $collaborator (@collaborators) {
2782: my ($errorflag,$pts,$wgt) =
2783: &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
2784: $env{'form.unamedom'.$ctr},$part);
2785: if ($errorflag eq 'not_allowed') {
2786: $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
2787: next;
2788: } elsif ($message ne '') {
2789: my ($baseurl,$showsymb) =
2790: &get_feedurl_and_symb($symb,$collaborator,
2791: $udom);
2792: if ($env{'form.withgrades'.$ctr}) {
2793: $messagetail = " for <a href=\"".
2794: $baseurl."?symb=$showsymb\">$restitle</a>";
2795: }
2796: $msgstatus =
2797: &Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
2798: }
2799: }
2800: }
2801: }
2802: $ctr++;
2803: }
2804: }
2805:
2806: # if ($env{'form.handgrade'} eq 'yes') {
2807: if (1) {
2808: # Keywords sorted in alphabatical order
2809: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
2810: my %keyhash = ();
2811: $env{'form.keywords'} =~ s/,\s{0,}|\s+/ /g;
2812: $env{'form.keywords'} =~ s/^\s+|\s+$//;
2813: my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
2814: $env{'form.keywords'} = join(' ',@keywords);
2815: $keyhash{$symb.'_keywords'} = $env{'form.keywords'};
2816: $keyhash{$symb.'_subject'} = $env{'form.msgsub'};
2817: $keyhash{$loginuser.'_kwclr'} = $env{'form.kwclr'};
2818: $keyhash{$loginuser.'_kwsize'} = $env{'form.kwsize'};
2819: $keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
2820:
2821: # message center - Order of message gets changed. Blank line is eliminated.
2822: # New messages are saved in env for the next student.
2823: # All messages are saved in nohist_handgrade.db
2824: my ($ctr,$idx) = (1,1);
2825: while ($ctr <= $env{'form.savemsgN'}) {
2826: if ($env{'form.savemsg'.$ctr} ne '') {
2827: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
2828: $idx++;
2829: }
2830: $ctr++;
2831: }
2832: $ctr = 0;
2833: while ($ctr < $ngrade) {
2834: if ($env{'form.newmsg'.$ctr} ne '') {
2835: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2836: $env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2837: $idx++;
2838: }
2839: $ctr++;
2840: }
2841: $env{'form.savemsgN'} = --$idx;
2842: $keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
2843: my $putresult = &Apache::lonnet::put
2844: ('nohist_handgrade',\%keyhash,$cdom,$cnum);
2845: }
2846: # Called by Save & Refresh from Highlight Attribute Window
2847: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
2848: if ($env{'form.refresh'} eq 'on') {
2849: my ($ctr,$total) = (0,0);
2850: while ($ctr < $ngrade) {
2851: $total++ if $env{'form.unamedom'.$ctr} ne '';
2852: $ctr++;
2853: }
2854: $env{'form.NTSTU'}=$ngrade;
2855: $ctr = 0;
2856: while ($ctr < $total) {
2857: my $processUser = $env{'form.unamedom'.$ctr};
2858: ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
2859: $env{'form.fullname'} = $$fullname{$processUser};
2860: &submission($request,$ctr,$total-1,$symb);
2861: $ctr++;
2862: }
2863: return '';
2864: }
2865:
2866: # Get the next/previous one or group of students
2867: my $firststu = $env{'form.unamedom0'};
2868: my $laststu = $env{'form.unamedom'.($ngrade-1)};
2869: my $ctr = 2;
2870: while ($laststu eq '') {
2871: $laststu = $env{'form.unamedom'.($ngrade-$ctr)};
2872: $ctr++;
2873: $laststu = $firststu if ($ctr > $ngrade);
2874: }
2875:
2876: my (@parsedlist,@nextlist);
2877: my ($nextflg) = 0;
2878: foreach my $item (sort
2879: {
2880: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
2881: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
2882: }
2883: return $a cmp $b;
2884: } (keys(%$fullname))) {
2885: # FIXME: this is fishy, looks like the button label
2886: if ($nextflg == 1 && $button =~ /Next$/) {
2887: push(@parsedlist,$item);
2888: }
2889: $nextflg = 1 if ($item eq $laststu);
2890: if ($button eq 'Previous') {
2891: last if ($item eq $firststu);
2892: push(@parsedlist,$item);
2893: }
2894: }
2895: $ctr = 0;
2896: # FIXME: this is fishy, looks like the button label
2897: @parsedlist = reverse @parsedlist if ($button eq 'Previous');
2898: my $res_error;
2899: my ($partlist) = &response_type($symb,\$res_error);
2900: if ($res_error) {
2901: $request->print(&navmap_errormsg());
2902: return;
2903: }
2904: foreach my $student (@parsedlist) {
2905: my $submitonly=$env{'form.submitonly'};
2906: my ($uname,$udom) = split(/:/,$student);
2907:
2908: if ($submitonly eq 'queued') {
2909: my %queue_status =
2910: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
2911: $udom,$uname);
2912: next if (!defined($queue_status{'gradingqueue'}));
2913: }
2914:
2915: if ($submitonly =~ /^(yes|graded|incorrect)$/) {
2916: # my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
2917: my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
2918: my $submitted = 0;
2919: my $ungraded = 0;
2920: my $incorrect = 0;
2921: foreach my $item (keys(%status)) {
2922: $submitted = 1 if ($status{$item} ne 'nothing');
2923: $ungraded = 1 if ($status{$item} =~ /^ungraded/);
2924: $incorrect = 1 if ($status{$item} =~ /^incorrect/);
2925: my ($foo,$partid,$foo1) = split(/\./,$item);
2926: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
2927: $submitted = 0;
2928: }
2929: }
2930: next if (!$submitted && ($submitonly eq 'yes' ||
2931: $submitonly eq 'incorrect' ||
2932: $submitonly eq 'graded'));
2933: next if (!$ungraded && ($submitonly eq 'graded'));
2934: next if (!$incorrect && $submitonly eq 'incorrect');
2935: }
2936: push(@nextlist,$student) if ($ctr < $ntstu);
2937: last if ($ctr == $ntstu);
2938: $ctr++;
2939: }
2940:
2941: $ctr = 0;
2942: my $total = scalar(@nextlist)-1;
2943:
2944: foreach (sort(@nextlist)) {
2945: my ($uname,$udom,$submitter) = split(/:/);
2946: $env{'form.student'} = $uname;
2947: $env{'form.userdom'} = $udom;
2948: $env{'form.fullname'} = $$fullname{$_};
2949: &submission($request,$ctr,$total,$symb);
2950: $ctr++;
2951: }
2952: if ($total < 0) {
2953: my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
2954: $request->print($the_end);
2955: }
2956: return '';
2957: }
2958:
2959: #---- Save the score and award for each student, if changed
2960: sub saveHandGrade {
2961: my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
2962: my @version_parts;
2963: my $usec = &Apache::lonnet::getsection($domain,$stuname,
2964: $env{'request.course.id'});
2965: if (!&canmodify($usec)) { return('not_allowed'); }
2966: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
2967: my @parts_graded;
2968: my %newrecord = ();
2969: my ($pts,$wgt) = ('','');
2970: my %aggregate = ();
2971: my $aggregateflag = 0;
2972: my @parts = split(/:/,$env{'form.partlist'.$newflg});
2973: foreach my $new_part (@parts) {
2974: #collaborator ($submi may vary for different parts
2975: if ($submitter && $new_part ne $part) { next; }
2976: my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
2977: if ($dropMenu eq 'excused') {
2978: if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
2979: $newrecord{'resource.'.$new_part.'.solved'} = 'excused';
2980: if (exists($record{'resource.'.$new_part.'.awarded'})) {
2981: $newrecord{'resource.'.$new_part.'.awarded'} = '';
2982: }
2983: $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
2984: }
2985: } elsif ($dropMenu eq 'reset status'
2986: && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
2987: foreach my $key (keys(%record)) {
2988: if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
2989: }
2990: $newrecord{'resource.'.$new_part.'.regrader'}=
2991: "$env{'user.name'}:$env{'user.domain'}";
2992: my $totaltries = $record{'resource.'.$part.'.tries'};
2993:
2994: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
2995: [$new_part]);
2996: my $aggtries =$totaltries;
2997: if ($last_resets{$new_part}) {
2998: $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
2999: $new_part);
3000: }
3001:
3002: my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
3003: if ($aggtries > 0) {
3004: &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
3005: $aggregateflag = 1;
3006: }
3007: } elsif ($dropMenu eq '') {
3008: $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ?
3009: $env{'form.GD_BOX'.$newflg.'_'.$new_part} :
3010: $env{'form.RADVAL'.$newflg.'_'.$new_part});
3011: if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
3012: next;
3013: }
3014: $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 :
3015: $env{'form.WGT'.$newflg.'_'.$new_part};
3016: my $partial= $pts/$wgt;
3017: if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
3018: #do not update score for part if not changed.
3019: &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
3020: next;
3021: } else {
3022: push(@parts_graded,$new_part);
3023: }
3024: if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
3025: $newrecord{'resource.'.$new_part.'.awarded'} = $partial;
3026: }
3027: my $reckey = 'resource.'.$new_part.'.solved';
3028: if ($partial == 0) {
3029: if ($record{$reckey} ne 'incorrect_by_override') {
3030: $newrecord{$reckey} = 'incorrect_by_override';
3031: }
3032: } else {
3033: if ($record{$reckey} ne 'correct_by_override') {
3034: $newrecord{$reckey} = 'correct_by_override';
3035: }
3036: }
3037: if ($submitter &&
3038: ($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
3039: $newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
3040: }
3041: $newrecord{'resource.'.$new_part.'.regrader'}=
3042: "$env{'user.name'}:$env{'user.domain'}";
3043: }
3044: # unless problem has been graded, set flag to version the submitted files
3045: unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/ ||
3046: $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
3047: $dropMenu eq 'reset status')
3048: {
3049: push(@version_parts,$new_part);
3050: }
3051: }
3052: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3053: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3054:
3055: if (%newrecord) {
3056: if (@version_parts) {
3057: my @changed_keys = &version_portfiles(\%record, \@parts_graded,
3058: $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
3059: @newrecord{@changed_keys} = @record{@changed_keys};
3060: foreach my $new_part (@version_parts) {
3061: &handback_files($request,$symb,$stuname,$domain,$newflg,
3062: $new_part,\%newrecord);
3063: }
3064: }
3065: &Apache::lonnet::cstore(\%newrecord,$symb,
3066: $env{'request.course.id'},$domain,$stuname);
3067: &check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
3068: $cdom,$cnum,$domain,$stuname);
3069: }
3070: if ($aggregateflag) {
3071: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
3072: $cdom,$cnum);
3073: }
3074: return ('',$pts,$wgt);
3075: }
3076:
3077: sub check_and_remove_from_queue {
3078: my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
3079: my @ungraded_parts;
3080: foreach my $part (@{$parts}) {
3081: if ( $record->{ 'resource.'.$part.'.awarded'} eq ''
3082: && $record->{ 'resource.'.$part.'.solved' } ne 'excused'
3083: && $newrecord->{'resource.'.$part.'.awarded'} eq ''
3084: && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
3085: ) {
3086: push(@ungraded_parts, $part);
3087: }
3088: }
3089: if ( !@ungraded_parts ) {
3090: &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
3091: $cnum,$domain,$stuname);
3092: }
3093: }
3094:
3095: sub handback_files {
3096: my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
3097: my $portfolio_root = '/userfiles/portfolio';
3098: my $res_error;
3099: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
3100: if ($res_error) {
3101: $request->print('<br />'.&navmap_errormsg().'<br />');
3102: return;
3103: }
3104: my @handedback;
3105: my $file_msg;
3106: my @part_response_id = &flatten_responseType($responseType);
3107: foreach my $part_response_id (@part_response_id) {
3108: my ($part_id,$resp_id) = @{ $part_response_id };
3109: my $part_resp = join('_',@{ $part_response_id });
3110: if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
3111: for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
3112: # if multiple files are uploaded names will be 'returndoc2','returndoc3'
3113: if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
3114: my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
3115: my ($directory,$answer_file) =
3116: ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
3117: my ($answer_name,$answer_ver,$answer_ext) =
3118: &file_name_version_ext($answer_file);
3119: my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
3120: my $getpropath = 1;
3121: my ($dir_list,$listerror) =
3122: &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
3123: $domain,$stuname,$getpropath);
3124: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
3125: # fix filename
3126: my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
3127: my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
3128: $newflg.'_'.$part_resp.'_returndoc'.$counter,
3129: $save_file_name);
3130: if ($result !~ m|^/uploaded/|) {
3131: $request->print('<br /><span class="LC_error">'.
3132: &mt('An error occurred ([_1]) while trying to upload [_2].',
3133: $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
3134: '</span>');
3135: } else {
3136: # mark the file as read only
3137: push(@handedback,$save_file_name);
3138: if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
3139: $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
3140: }
3141: $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
3142: $file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
3143: }
3144: $request->print('<br />'.&mt('[_1] will be the uploaded filename [_2]','<span class="LC_info">'.$fname.'</span>','<span class="LC_filename">'.$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter}.'</span>'));
3145: }
3146: }
3147: }
3148: }
3149: if (@handedback > 0) {
3150: $request->print('<br />');
3151: my @what = ($symb,$env{'request.course.id'},'handback');
3152: &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
3153: my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});
3154: my ($subject,$message);
3155: if (scalar(@handedback) == 1) {
3156: $subject = &mt_user($user_lh,'File Handed Back by Instructor');
3157: $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
3158: } else {
3159: $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
3160: $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
3161: }
3162: $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
3163: $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
3164: &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
3165: my ($feedurl,$showsymb) =
3166: &get_feedurl_and_symb($symb,$domain,$stuname);
3167: my $restitle = &Apache::lonnet::gettitle($symb);
3168: $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
3169: my $msgstatus =
3170: &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
3171: $message,undef,$feedurl,undef,undef,undef,$showsymb,
3172: $restitle);
3173: if ($msgstatus) {
3174: $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
3175: }
3176: }
3177: return;
3178: }
3179:
3180: sub get_feedurl_and_symb {
3181: my ($symb,$uname,$udom) = @_;
3182: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3183: $url = &Apache::lonnet::clutter($url);
3184: my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
3185: $symb,$udom,$uname);
3186: if ($encrypturl =~ /^yes$/i) {
3187: &Apache::lonenc::encrypted(\$url,1);
3188: &Apache::lonenc::encrypted(\$symb,1);
3189: }
3190: return ($url,$symb);
3191: }
3192:
3193: sub get_submitted_files {
3194: my ($udom,$uname,$partid,$respid,$record) = @_;
3195: my @files;
3196: if ($$record{"resource.$partid.$respid.portfiles"}) {
3197: my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
3198: foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
3199: push(@files,$file_url.$file);
3200: }
3201: }
3202: if ($$record{"resource.$partid.$respid.uploadedurl"}) {
3203: push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
3204: }
3205: return (\@files);
3206: }
3207:
3208: # ----------- Provides number of tries since last reset.
3209: sub get_num_tries {
3210: my ($record,$last_reset,$part) = @_;
3211: my $timestamp = '';
3212: my $num_tries = 0;
3213: if ($$record{'version'}) {
3214: for (my $version=$$record{'version'};$version>=1;$version--) {
3215: if (exists($$record{$version.':resource.'.$part.'.solved'})) {
3216: $timestamp = $$record{$version.':timestamp'};
3217: if ($timestamp > $last_reset) {
3218: $num_tries ++;
3219: } else {
3220: last;
3221: }
3222: }
3223: }
3224: }
3225: return $num_tries;
3226: }
3227:
3228: # ----------- Determine decrements required in aggregate totals
3229: sub decrement_aggs {
3230: my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
3231: my %decrement = (
3232: attempts => 0,
3233: users => 0,
3234: correct => 0
3235: );
3236: $decrement{'attempts'} = $aggtries;
3237: if ($solvedstatus =~ /^correct/) {
3238: $decrement{'correct'} = 1;
3239: }
3240: if ($aggtries == $totaltries) {
3241: $decrement{'users'} = 1;
3242: }
3243: foreach my $type (keys(%decrement)) {
3244: $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
3245: }
3246: return;
3247: }
3248:
3249: # ----------- Determine timestamps for last reset of aggregate totals for parts
3250: sub get_last_resets {
3251: my ($symb,$courseid,$partids) =@_;
3252: my %last_resets;
3253: my $cdom = $env{'course.'.$courseid.'.domain'};
3254: my $cname = $env{'course.'.$courseid.'.num'};
3255: my @keys;
3256: foreach my $part (@{$partids}) {
3257: push(@keys,"$symb\0$part\0resettime");
3258: }
3259: my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
3260: $cdom,$cname);
3261: foreach my $part (@{$partids}) {
3262: $last_resets{$part}=$results{"$symb\0$part\0resettime"};
3263: }
3264: return %last_resets;
3265: }
3266:
3267: # ----------- Handles creating versions for portfolio files as answers
3268: sub version_portfiles {
3269: my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
3270: my $version_parts = join('|',@$v_flag);
3271: my @returned_keys;
3272: my $parts = join('|', @$parts_graded);
3273: my $portfolio_root = '/userfiles/portfolio';
3274: foreach my $key (keys(%$record)) {
3275: my $new_portfiles;
3276: if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
3277: my @versioned_portfiles;
3278: my @portfiles = split(/\s*,\s*/,$$record{$key});
3279: foreach my $file (@portfiles) {
3280: &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
3281: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
3282: my ($answer_name,$answer_ver,$answer_ext) =
3283: &file_name_version_ext($answer_file);
3284: my $getpropath = 1;
3285: my ($dir_list,$listerror) =
3286: &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
3287: $stu_name,$getpropath);
3288: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
3289: my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
3290: if ($new_answer ne 'problem getting file') {
3291: push(@versioned_portfiles, $directory.$new_answer);
3292: &Apache::lonnet::mark_as_readonly($domain,$stu_name,
3293: [$directory.$new_answer],
3294: [$symb,$env{'request.course.id'},'graded']);
3295: }
3296: }
3297: $$record{$key} = join(',',@versioned_portfiles);
3298: push(@returned_keys,$key);
3299: }
3300: }
3301: return (@returned_keys);
3302: }
3303:
3304: sub get_next_version {
3305: my ($answer_name, $answer_ext, $dir_list) = @_;
3306: my $version;
3307: if (ref($dir_list) eq 'ARRAY') {
3308: foreach my $row (@{$dir_list}) {
3309: my ($file) = split(/\&/,$row,2);
3310: my ($file_name,$file_version,$file_ext) =
3311: &file_name_version_ext($file);
3312: if (($file_name eq $answer_name) &&
3313: ($file_ext eq $answer_ext)) {
3314: # gets here if filename and extension match,
3315: # regardless of version
3316: if ($file_version ne '') {
3317: # a versioned file is found so save it for later
3318: if ($file_version > $version) {
3319: $version = $file_version;
3320: }
3321: }
3322: }
3323: }
3324: }
3325: $version ++;
3326: return($version);
3327: }
3328:
3329: sub version_selected_portfile {
3330: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
3331: my ($answer_name,$answer_ver,$answer_ext) =
3332: &file_name_version_ext($file_name);
3333: my $new_answer;
3334: $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
3335: if($env{'form.copy'} eq '-1') {
3336: $new_answer = 'problem getting file';
3337: } else {
3338: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
3339: my $copy_result = &Apache::lonnet::finishuserfileupload(
3340: $stu_name,$domain,'copy',
3341: '/portfolio'.$directory.$new_answer);
3342: }
3343: return ($new_answer);
3344: }
3345:
3346: sub file_name_version_ext {
3347: my ($file)=@_;
3348: my @file_parts = split(/\./, $file);
3349: my ($name,$version,$ext);
3350: if (@file_parts > 1) {
3351: $ext=pop(@file_parts);
3352: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
3353: $version=pop(@file_parts);
3354: }
3355: $name=join('.',@file_parts);
3356: } else {
3357: $name=join('.',@file_parts);
3358: }
3359: return($name,$version,$ext);
3360: }
3361:
3362: #--------------------------------------------------------------------------------------
3363: #
3364: #-------------------------- Next few routines handles grading by section or whole class
3365: #
3366: #--- Javascript to handle grading by section or whole class
3367: sub viewgrades_js {
3368: my ($request) = shift;
3369:
3370: my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
3371: $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
3372: function writePoint(partid,weight,point) {
3373: var radioButton = document.classgrade["RADVAL_"+partid];
3374: var textbox = document.classgrade["TEXTVAL_"+partid];
3375: if (point == "textval") {
3376: point = document.classgrade["TEXTVAL_"+partid].value;
3377: if (isNaN(point) || parseFloat(point) < 0) {
3378: alert("$alertmsg"+parseFloat(point));
3379: var resetbox = false;
3380: for (var i=0; i<radioButton.length; i++) {
3381: if (radioButton[i].checked) {
3382: textbox.value = i;
3383: resetbox = true;
3384: }
3385: }
3386: if (!resetbox) {
3387: textbox.value = "";
3388: }
3389: return;
3390: }
3391: if (parseFloat(point) > parseFloat(weight)) {
3392: var resp = confirm("You entered a value ("+parseFloat(point)+
3393: ") greater than the weight for the part. Accept?");
3394: if (resp == false) {
3395: textbox.value = "";
3396: return;
3397: }
3398: }
3399: for (var i=0; i<radioButton.length; i++) {
3400: radioButton[i].checked=false;
3401: if (parseFloat(point) == i) {
3402: radioButton[i].checked=true;
3403: }
3404: }
3405:
3406: } else {
3407: textbox.value = parseFloat(point);
3408: }
3409: for (i=0;i<document.classgrade.total.value;i++) {
3410: var user = document.classgrade["ctr"+i].value;
3411: user = user.replace(new RegExp(':', 'g'),"_");
3412: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3413: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3414: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3415: if (saveval != "correct") {
3416: scorename.value = point;
3417: if (selname[0].selected != true) {
3418: selname[0].selected = true;
3419: }
3420: }
3421: }
3422: document.classgrade["SELVAL_"+partid][0].selected = true;
3423: }
3424:
3425: function writeRadText(partid,weight) {
3426: var selval = document.classgrade["SELVAL_"+partid];
3427: var radioButton = document.classgrade["RADVAL_"+partid];
3428: var override = document.classgrade["FORCE_"+partid].checked;
3429: var textbox = document.classgrade["TEXTVAL_"+partid];
3430: if (selval[1].selected || selval[2].selected) {
3431: for (var i=0; i<radioButton.length; i++) {
3432: radioButton[i].checked=false;
3433:
3434: }
3435: textbox.value = "";
3436:
3437: for (i=0;i<document.classgrade.total.value;i++) {
3438: var user = document.classgrade["ctr"+i].value;
3439: user = user.replace(new RegExp(':', 'g'),"_");
3440: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3441: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3442: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3443: if ((saveval != "correct") || override) {
3444: scorename.value = "";
3445: if (selval[1].selected) {
3446: selname[1].selected = true;
3447: } else {
3448: selname[2].selected = true;
3449: if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value))
3450: {document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
3451: }
3452: }
3453: }
3454: } else {
3455: for (i=0;i<document.classgrade.total.value;i++) {
3456: var user = document.classgrade["ctr"+i].value;
3457: user = user.replace(new RegExp(':', 'g'),"_");
3458: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3459: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3460: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3461: if ((saveval != "correct") || override) {
3462: scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
3463: selname[0].selected = true;
3464: }
3465: }
3466: }
3467: }
3468:
3469: function changeSelect(partid,user) {
3470: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
3471: var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
3472: var point = textbox.value;
3473: var weight = document.classgrade["weight_"+partid].value;
3474:
3475: if (isNaN(point) || parseFloat(point) < 0) {
3476: alert("$alertmsg"+parseFloat(point));
3477: textbox.value = "";
3478: return;
3479: }
3480: if (parseFloat(point) > parseFloat(weight)) {
3481: var resp = confirm("You entered a value ("+parseFloat(point)+
3482: ") greater than the weight of the part. Accept?");
3483: if (resp == false) {
3484: textbox.value = "";
3485: return;
3486: }
3487: }
3488: selval[0].selected = true;
3489: }
3490:
3491: function changeOneScore(partid,user) {
3492: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
3493: if (selval[1].selected || selval[2].selected) {
3494: document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
3495: if (selval[2].selected) {
3496: document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
3497: }
3498: }
3499: }
3500:
3501: function resetEntry(numpart) {
3502: for (ctpart=0;ctpart<numpart;ctpart++) {
3503: var partid = document.classgrade["partid_"+ctpart].value;
3504: var radioButton = document.classgrade["RADVAL_"+partid];
3505: var textbox = document.classgrade["TEXTVAL_"+partid];
3506: var selval = document.classgrade["SELVAL_"+partid];
3507: for (var i=0; i<radioButton.length; i++) {
3508: radioButton[i].checked=false;
3509:
3510: }
3511: textbox.value = "";
3512: selval[0].selected = true;
3513:
3514: for (i=0;i<document.classgrade.total.value;i++) {
3515: var user = document.classgrade["ctr"+i].value;
3516: user = user.replace(new RegExp(':', 'g'),"_");
3517: var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3518: resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
3519: var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
3520: resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
3521: var saveselval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3522: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3523: if (saveselval == "excused") {
3524: if (selname[1].selected == false) { selname[1].selected = true;}
3525: } else {
3526: if (selname[0].selected == false) {selname[0].selected = true};
3527: }
3528: }
3529: }
3530: }
3531:
3532: VIEWJAVASCRIPT
3533: }
3534:
3535: #--- show scores for a section or whole class w/ option to change/update a score
3536: sub viewgrades {
3537: my ($request,$symb) = @_;
3538: &viewgrades_js($request);
3539:
3540: #need to make sure we have the correct data for later EXT calls,
3541: #thus invalidate the cache
3542: &Apache::lonnet::devalidatecourseresdata(
3543: $env{'course.'.$env{'request.course.id'}.'.num'},
3544: $env{'course.'.$env{'request.course.id'}.'.domain'});
3545: &Apache::lonnet::clear_EXT_cache_status();
3546:
3547: my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
3548:
3549: #view individual student submission form - called using Javascript viewOneStudent
3550: $result.=&jscriptNform($symb);
3551:
3552: #beginning of class grading form
3553: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
3554: $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
3555: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
3556: '<input type="hidden" name="command" value="editgrades" />'."\n".
3557: &build_section_inputs().
3558: '<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
3559:
3560: my ($common_header,$specific_header);
3561: if ($env{'form.section'} eq 'all') {
3562: $common_header = &mt('Assign Common Grade to Class');
3563: $specific_header = &mt('Assign Grade to Specific Students in Class');
3564: } elsif ($env{'form.section'} eq 'none') {
3565: $common_header = &mt('Assign Common Grade to Students in no Section');
3566: $specific_header = &mt('Assign Grade to Specific Students in no Section');
3567: } else {
3568: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3569: $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
3570: $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
3571: }
3572: $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
3573: #radio buttons/text box for assigning points for a section or class.
3574: #handles different parts of a problem
3575: my $res_error;
3576: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
3577: if ($res_error) {
3578: return &navmap_errormsg();
3579: }
3580: my %weight = ();
3581: my $ctsparts = 0;
3582: my %seen = ();
3583: my @part_response_id = &flatten_responseType($responseType);
3584: foreach my $part_response_id (@part_response_id) {
3585: my ($partid,$respid) = @{ $part_response_id };
3586: my $part_resp = join('_',@{ $part_response_id });
3587: next if $seen{$partid};
3588: $seen{$partid}++;
3589: my $handgrade=$$handgrade{$part_resp};
3590: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
3591: $weight{$partid} = $wgt eq '' ? '1' : $wgt;
3592:
3593: my $display_part=&get_display_part($partid,$symb);
3594: my $radio.='<table border="0"><tr>';
3595: my $ctr = 0;
3596: while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
3597: $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
3598: 'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
3599: ','.$ctr.')" />'.$ctr."</label></td>\n";
3600: $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
3601: $ctr++;
3602: }
3603: $radio.='</tr></table>';
3604: my $line = '<input type="text" name="TEXTVAL_'.
3605: $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
3606: $partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
3607: $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
3608: $line.= '<td><b>'.&mt('Grade Status').':</b>'.
3609: '<select name="SELVAL_'.$partid.'" '.
3610: 'onchange="javascript:writeRadText(\''.$partid.'\','.
3611: $weight{$partid}.')"> '.
3612: '<option selected="selected"> </option>'.
3613: '<option value="excused">'.&mt('excused').'</option>'.
3614: '<option value="reset status">'.&mt('reset status').'</option>'.
3615: '</select></td>'.
3616: '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
3617: $line.='<input type="hidden" name="partid_'.
3618: $ctsparts.'" value="'.$partid.'" />'."\n";
3619: $line.='<input type="hidden" name="weight_'.
3620: $partid.'" value="'.$weight{$partid}.'" />'."\n";
3621:
3622: $result.=
3623: &Apache::loncommon::start_data_table_row()."\n".
3624: '<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>'.
3625: &Apache::loncommon::end_data_table_row()."\n";
3626: $ctsparts++;
3627: }
3628: $result.=&Apache::loncommon::end_data_table()."\n".
3629: '<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
3630: $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
3631: 'onclick="javascript:resetEntry('.$ctsparts.');" />';
3632:
3633: #table listing all the students in a section/class
3634: #header of table
3635: $result.= '<h3>'.$specific_header.'</h3>'.
3636: &Apache::loncommon::start_data_table().
3637: &Apache::loncommon::start_data_table_header_row().
3638: '<th>'.&mt('No.').'</th>'.
3639: '<th>'.&nameUserString('header')."</th>\n";
3640: my $partserror;
3641: my (@parts) = sort(&getpartlist($symb,\$partserror));
3642: if ($partserror) {
3643: return &navmap_errormsg();
3644: }
3645: my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
3646: my @partids = ();
3647: foreach my $part (@parts) {
3648: my $display=&Apache::lonnet::metadata($url,$part.'.display');
3649: my $narrowtext = &mt('Tries');
3650: $display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
3651: if (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
3652: my ($partid) = &split_part_type($part);
3653: push(@partids,$partid);
3654: #
3655: # FIXME: Looks like $display looks at English text
3656: #
3657: my $display_part=&get_display_part($partid,$symb);
3658: if ($display =~ /^Partial Credit Factor/) {
3659: $result.='<th>'.
3660: &mt('Score Part: [_1][_2](weight = [_3])',
3661: $display_part,'<br />',$weight{$partid}).'</th>'."\n";
3662: next;
3663:
3664: } else {
3665: if ($display =~ /Problem Status/) {
3666: my $grade_status_mt = &mt('Grade Status');
3667: $display =~ s{Problem Status}{$grade_status_mt<br />};
3668: }
3669: my $part_mt = &mt('Part:');
3670: $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
3671: }
3672:
3673: $result.='<th>'.$display.'</th>'."\n";
3674: }
3675: $result.=&Apache::loncommon::end_data_table_header_row();
3676:
3677: my %last_resets =
3678: &get_last_resets($symb,$env{'request.course.id'},\@partids);
3679:
3680: #get info for each student
3681: #list all the students - with points and grade status
3682: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
3683: my $ctr = 0;
3684: foreach (sort
3685: {
3686: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
3687: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
3688: }
3689: return $a cmp $b;
3690: } (keys(%$fullname))) {
3691: $ctr++;
3692: $result.=&viewstudentgrade($symb,$env{'request.course.id'},
3693: $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
3694: }
3695: $result.=&Apache::loncommon::end_data_table();
3696: $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
3697: $result.='<input type="button" value="'.&mt('Save').'" '.
3698: 'onclick="javascript:submit();" target="_self" /></form>'."\n";
3699: if (scalar(%$fullname) eq 0) {
3700: my $colspan=3+scalar(@parts);
3701: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3702: my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
3703: $result='<span class="LC_warning">'.
3704: &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
3705: $section_display, $stu_status).
3706: '</span>';
3707: }
3708: return $result;
3709: }
3710:
3711: #--- call by previous routine to display each student
3712: sub viewstudentgrade {
3713: my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
3714: my ($uname,$udom) = split(/:/,$student);
3715: my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
3716: my %aggregates = ();
3717: my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
3718: '<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
3719: "\n".$ctr.' </td><td> '.
3720: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
3721: '\');" target="_self">'.$fullname.'</a> '.
3722: '<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
3723: $student=~s/:/_/; # colon doen't work in javascript for names
3724: foreach my $apart (@$parts) {
3725: my ($part,$type) = &split_part_type($apart);
3726: my $score=$record{"resource.$part.$type"};
3727: $result.='<td align="center">';
3728: my ($aggtries,$totaltries);
3729: unless (exists($aggregates{$part})) {
3730: $totaltries = $record{'resource.'.$part.'.tries'};
3731:
3732: $aggtries = $totaltries;
3733: if ($$last_resets{$part}) {
3734: $aggtries = &get_num_tries(\%record,$$last_resets{$part},
3735: $part);
3736: }
3737: $result.='<input type="hidden" name="'.
3738: 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
3739: $result.='<input type="hidden" name="'.
3740: 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
3741: $aggregates{$part} = 1;
3742: }
3743: if ($type eq 'awarded') {
3744: my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
3745: $result.='<input type="hidden" name="'.
3746: 'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
3747: $result.='<input type="text" name="'.
3748: 'GD_'.$student.'_'.$part.'_awarded" '.
3749: 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
3750: '\')" value="'.$pts.'" size="4" /></td>'."\n";
3751: } elsif ($type eq 'solved') {
3752: my ($status,$foo)=split(/_/,$score,2);
3753: $status = 'nothing' if ($status eq '');
3754: $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
3755: $part.'_solved_s" value="'.$status.'" />'."\n";
3756: $result.=' <select name="'.
3757: 'GD_'.$student.'_'.$part.'_solved" '.
3758: 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
3759: $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>'
3760: : '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
3761: $result.='<option value="reset status">'.&mt('reset status').'</option>';
3762: $result.="</select> </td>\n";
3763: } else {
3764: $result.='<input type="hidden" name="'.
3765: 'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
3766: "\n";
3767: $result.='<input type="text" name="'.
3768: 'GD_'.$student.'_'.$part.'_'.$type.'" '.
3769: 'value="'.$score.'" size="4" /></td>'."\n";
3770: }
3771: }
3772: $result.=&Apache::loncommon::end_data_table_row();
3773: return $result;
3774: }
3775:
3776: #--- change scores for all the students in a section/class
3777: # record does not get update if unchanged
3778: sub editgrades {
3779: my ($request,$symb) = @_;
3780:
3781: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3782: my $title='<h2>'.&mt('Current Grade Status').'</h2>';
3783: $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
3784:
3785: my $result= &Apache::loncommon::start_data_table().
3786: &Apache::loncommon::start_data_table_header_row().
3787: '<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
3788: '<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
3789: my %scoreptr = (
3790: 'correct' =>'correct_by_override',
3791: 'incorrect'=>'incorrect_by_override',
3792: 'excused' =>'excused',
3793: 'ungraded' =>'ungraded_attempted',
3794: 'credited' =>'credit_attempted',
3795: 'nothing' => '',
3796: );
3797: my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
3798:
3799: my (@partid);
3800: my %weight = ();
3801: my %columns = ();
3802: my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
3803:
3804: my $partserror;
3805: my (@parts) = sort(&getpartlist($symb,\$partserror));
3806: if ($partserror) {
3807: return &navmap_errormsg();
3808: }
3809: my $header;
3810: while ($ctr < $env{'form.totalparts'}) {
3811: my $partid = $env{'form.partid_'.$ctr};
3812: push(@partid,$partid);
3813: $weight{$partid} = $env{'form.weight_'.$partid};
3814: $ctr++;
3815: }
3816: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3817: foreach my $partid (@partid) {
3818: $header .= '<th align="center">'.&mt('Old Score').'</th>'.
3819: '<th align="center">'.&mt('New Score').'</th>';
3820: $columns{$partid}=2;
3821: foreach my $stores (@parts) {
3822: my ($part,$type) = &split_part_type($stores);
3823: if ($part !~ m/^\Q$partid\E/) { next;}
3824: if ($type eq 'awarded' || $type eq 'solved') { next; }
3825: my $display=&Apache::lonnet::metadata($url,$stores.'.display');
3826: $display =~ s/\[Part: \Q$part\E\]//;
3827: my $narrowtext = &mt('Tries');
3828: $display =~ s/Number of Attempts/$narrowtext/;
3829: $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
3830: '<th align="center">'.&mt('New').' '.$display.'</th>';
3831: $columns{$partid}+=2;
3832: }
3833: }
3834: foreach my $partid (@partid) {
3835: my $display_part=&get_display_part($partid,$symb);
3836: $result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
3837: &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
3838: '</th>';
3839:
3840: }
3841: $result .= &Apache::loncommon::end_data_table_header_row().
3842: &Apache::loncommon::start_data_table_header_row().
3843: $header.
3844: &Apache::loncommon::end_data_table_header_row();
3845: my @noupdate;
3846: my ($updateCtr,$noupdateCtr) = (1,1);
3847: for ($i=0; $i<$env{'form.total'}; $i++) {
3848: my $line;
3849: my $user = $env{'form.ctr'.$i};
3850: my ($uname,$udom)=split(/:/,$user);
3851: my %newrecord;
3852: my $updateflag = 0;
3853: $line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
3854: my $usec=$classlist->{"$uname:$udom"}[5];
3855: if (!&canmodify($usec)) {
3856: my $numcols=scalar(@partid)*4+2;
3857: push(@noupdate,
3858: $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
3859: &mt('Not allowed to modify student')."</span></td></tr>");
3860: next;
3861: }
3862: my %aggregate = ();
3863: my $aggregateflag = 0;
3864: $user=~s/:/_/; # colon doen't work in javascript for names
3865: foreach (@partid) {
3866: my $old_aw = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
3867: my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
3868: my $old_part = $old_aw eq '' ? '' : $old_part_pcr;
3869: my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
3870: my $awarded = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
3871: my $pcr = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
3872: my $partial = $awarded eq '' ? '' : $pcr;
3873: my $score;
3874: if ($partial eq '') {
3875: $score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
3876: } elsif ($partial > 0) {
3877: $score = 'correct_by_override';
3878: } elsif ($partial == 0) {
3879: $score = 'incorrect_by_override';
3880: }
3881: my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
3882: $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
3883:
3884: $newrecord{'resource.'.$_.'.regrader'}=
3885: "$env{'user.name'}:$env{'user.domain'}";
3886: if ($dropMenu eq 'reset status' &&
3887: $old_score ne '') { # ignore if no previous attempts => nothing to reset
3888: $newrecord{'resource.'.$_.'.tries'} = '';
3889: $newrecord{'resource.'.$_.'.solved'} = '';
3890: $newrecord{'resource.'.$_.'.award'} = '';
3891: $newrecord{'resource.'.$_.'.awarded'} = '';
3892: $updateflag = 1;
3893: if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
3894: my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
3895: my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
3896: my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
3897: &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
3898: $aggregateflag = 1;
3899: }
3900: } elsif (!($old_part eq $partial && $old_score eq $score)) {
3901: $updateflag = 1;
3902: $newrecord{'resource.'.$_.'.awarded'} = $partial if $partial ne '';
3903: $newrecord{'resource.'.$_.'.solved'} = $score;
3904: $rec_update++;
3905: }
3906:
3907: $line .= '<td align="center">'.$old_aw.' </td>'.
3908: '<td align="center">'.$awarded.
3909: ($score eq 'excused' ? $score : '').' </td>';
3910:
3911:
3912: my $partid=$_;
3913: foreach my $stores (@parts) {
3914: my ($part,$type) = &split_part_type($stores);
3915: if ($part !~ m/^\Q$partid\E/) { next;}
3916: if ($type eq 'awarded' || $type eq 'solved') { next; }
3917: my $old_aw = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
3918: my $awarded = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
3919: if ($awarded ne '' && $awarded ne $old_aw) {
3920: $newrecord{'resource.'.$part.'.'.$type}= $awarded;
3921: $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
3922: $updateflag=1;
3923: }
3924: $line .= '<td align="center">'.$old_aw.' </td>'.
3925: '<td align="center">'.$awarded.' </td>';
3926: }
3927: }
3928: $line.="\n";
3929:
3930: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3931: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3932:
3933: if ($updateflag) {
3934: $count++;
3935: &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
3936: $udom,$uname);
3937:
3938: if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
3939: $cnum,$udom,$uname)) {
3940: # need to figure out if should be in queue.
3941: my %record =
3942: &Apache::lonnet::restore($symb,$env{'request.course.id'},
3943: $udom,$uname);
3944: my $all_graded = 1;
3945: my $none_graded = 1;
3946: foreach my $part (@parts) {
3947: if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
3948: $all_graded = 0;
3949: } else {
3950: $none_graded = 0;
3951: }
3952: }
3953:
3954: if ($all_graded || $none_graded) {
3955: &Apache::bridgetask::remove_from_queue('gradingqueue',
3956: $symb,$cdom,$cnum,
3957: $udom,$uname);
3958: }
3959: }
3960:
3961: $result.=&Apache::loncommon::start_data_table_row().
3962: '<td align="right"> '.$updateCtr.' </td>'.$line.
3963: &Apache::loncommon::end_data_table_row();
3964: $updateCtr++;
3965: } else {
3966: push(@noupdate,
3967: '<td align="right"> '.$noupdateCtr.' </td>'.$line);
3968: $noupdateCtr++;
3969: }
3970: if ($aggregateflag) {
3971: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
3972: $cdom,$cnum);
3973: }
3974: }
3975: if (@noupdate) {
3976: # my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
3977: my $numcols=scalar(@partid)*4+2;
3978: $result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
3979: '<td align="center" colspan="'.$numcols.'">'.
3980: &mt('No Changes Occurred For the Students Below').
3981: '</td>'.
3982: &Apache::loncommon::end_data_table_row();
3983: foreach my $line (@noupdate) {
3984: $result.=
3985: &Apache::loncommon::start_data_table_row().
3986: $line.
3987: &Apache::loncommon::end_data_table_row();
3988: }
3989: }
3990: $result .= &Apache::loncommon::end_data_table();
3991: my $msg = '<p><b>'.
3992: &mt('Number of records updated = [_1] for [quant,_2,student].',
3993: $rec_update,$count).'</b><br />'.
3994: '<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
3995: '</b></p>';
3996: return $title.$msg.$result;
3997: }
3998:
3999: sub split_part_type {
4000: my ($partstr) = @_;
4001: my ($temp,@allparts)=split(/_/,$partstr);
4002: my $type=pop(@allparts);
4003: my $part=join('_',@allparts);
4004: return ($part,$type);
4005: }
4006:
4007: #------------- end of section for handling grading by section/class ---------
4008: #
4009: #----------------------------------------------------------------------------
4010:
4011:
4012: #----------------------------------------------------------------------------
4013: #
4014: #-------------------------- Next few routines handles grading by csv upload
4015: #
4016: #--- Javascript to handle csv upload
4017: sub csvupload_javascript_reverse_associate {
4018: my $error1=&mt('You need to specify the username or the student/employee ID');
4019: my $error2=&mt('You need to specify at least one grading field');
4020: return(<<ENDPICK);
4021: function verify(vf) {
4022: var foundsomething=0;
4023: var founduname=0;
4024: var foundID=0;
4025: for (i=0;i<=vf.nfields.value;i++) {
4026: tw=eval('vf.f'+i+'.selectedIndex');
4027: if (i==0 && tw!=0) { foundID=1; }
4028: if (i==1 && tw!=0) { founduname=1; }
4029: if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
4030: }
4031: if (founduname==0 && foundID==0) {
4032: alert('$error1');
4033: return;
4034: }
4035: if (foundsomething==0) {
4036: alert('$error2');
4037: return;
4038: }
4039: vf.submit();
4040: }
4041: function flip(vf,tf) {
4042: var nw=eval('vf.f'+tf+'.selectedIndex');
4043: var i;
4044: for (i=0;i<=vf.nfields.value;i++) {
4045: //can not pick the same destination field for both name and domain
4046: if (((i ==0)||(i ==1)) &&
4047: ((tf==0)||(tf==1)) &&
4048: (i!=tf) &&
4049: (eval('vf.f'+i+'.selectedIndex')==nw)) {
4050: eval('vf.f'+i+'.selectedIndex=0;')
4051: }
4052: }
4053: }
4054: ENDPICK
4055: }
4056:
4057: sub csvupload_javascript_forward_associate {
4058: my $error1=&mt('You need to specify the username or the student/employee ID');
4059: my $error2=&mt('You need to specify at least one grading field');
4060: return(<<ENDPICK);
4061: function verify(vf) {
4062: var foundsomething=0;
4063: var founduname=0;
4064: var foundID=0;
4065: for (i=0;i<=vf.nfields.value;i++) {
4066: tw=eval('vf.f'+i+'.selectedIndex');
4067: if (tw==1) { foundID=1; }
4068: if (tw==2) { founduname=1; }
4069: if (tw>3) { foundsomething=1; }
4070: }
4071: if (founduname==0 && foundID==0) {
4072: alert('$error1');
4073: return;
4074: }
4075: if (foundsomething==0) {
4076: alert('$error2');
4077: return;
4078: }
4079: vf.submit();
4080: }
4081: function flip(vf,tf) {
4082: var nw=eval('vf.f'+tf+'.selectedIndex');
4083: var i;
4084: //can not pick the same destination field twice
4085: for (i=0;i<=vf.nfields.value;i++) {
4086: if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
4087: eval('vf.f'+i+'.selectedIndex=0;')
4088: }
4089: }
4090: }
4091: ENDPICK
4092: }
4093:
4094: sub csvuploadmap_header {
4095: my ($request,$symb,$datatoken,$distotal)= @_;
4096: my $javascript;
4097: if ($env{'form.upfile_associate'} eq 'reverse') {
4098: $javascript=&csvupload_javascript_reverse_associate();
4099: } else {
4100: $javascript=&csvupload_javascript_forward_associate();
4101: }
4102:
4103: $symb = &Apache::lonenc::check_encrypt($symb);
4104: $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
4105: &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
4106: &mt('Associate entries from the uploaded file with as many fields as you can.'));
4107: my $reverse=&mt("Reverse Association");
4108: $request->print(<<ENDPICK);
4109: <br />
4110: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
4111: <input type="hidden" name="associate" value="" />
4112: <input type="hidden" name="phase" value="three" />
4113: <input type="hidden" name="datatoken" value="$datatoken" />
4114: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
4115: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
4116: <input type="hidden" name="upfile_associate"
4117: value="$env{'form.upfile_associate'}" />
4118: <input type="hidden" name="symb" value="$symb" />
4119: <input type="hidden" name="command" value="csvuploadoptions" />
4120: <hr />
4121: ENDPICK
4122: $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
4123: return '';
4124:
4125: }
4126:
4127: sub csvupload_fields {
4128: my ($symb,$errorref) = @_;
4129: my (@parts) = &getpartlist($symb,$errorref);
4130: if (ref($errorref)) {
4131: if ($$errorref) {
4132: return;
4133: }
4134: }
4135:
4136: my @fields=(['ID','Student/Employee ID'],
4137: ['username','Student Username'],
4138: ['domain','Student Domain']);
4139: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
4140: foreach my $part (sort(@parts)) {
4141: my @datum;
4142: my $display=&Apache::lonnet::metadata($url,$part.'.display');
4143: my $name=$part;
4144: if (!$display) { $display = $name; }
4145: @datum=($name,$display);
4146: if ($name=~/^stores_(.*)_awarded/) {
4147: push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
4148: }
4149: push(@fields,\@datum);
4150: }
4151: return (@fields);
4152: }
4153:
4154: sub csvuploadmap_footer {
4155: my ($request,$i,$keyfields) =@_;
4156: my $buttontext = &mt('Assign Grades');
4157: $request->print(<<ENDPICK);
4158: </table>
4159: <input type="hidden" name="nfields" value="$i" />
4160: <input type="hidden" name="keyfields" value="$keyfields" />
4161: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
4162: </form>
4163: ENDPICK
4164: }
4165:
4166: sub checkforfile_js {
4167: my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
4168: my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
4169: function checkUpload(formname) {
4170: if (formname.upfile.value == "") {
4171: alert("$alertmsg");
4172: return false;
4173: }
4174: formname.submit();
4175: }
4176: CSVFORMJS
4177: return $result;
4178: }
4179:
4180: sub upcsvScores_form {
4181: my ($request,$symb) = @_;
4182: if (!$symb) {return '';}
4183: my $result=&checkforfile_js();
4184: $result.=&Apache::loncommon::start_data_table().
4185: &Apache::loncommon::start_data_table_header_row().
4186: '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
4187: &Apache::loncommon::end_data_table_header_row().
4188: &Apache::loncommon::start_data_table_row().'<td>';
4189: my $upload=&mt("Upload Scores");
4190: my $upfile_select=&Apache::loncommon::upfile_select_html();
4191: my $ignore=&mt('Ignore First Line');
4192: $symb = &Apache::lonenc::check_encrypt($symb);
4193: $result.=<<ENDUPFORM;
4194: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
4195: <input type="hidden" name="symb" value="$symb" />
4196: <input type="hidden" name="command" value="csvuploadmap" />
4197: $upfile_select
4198: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
4199: </form>
4200: ENDUPFORM
4201: $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
4202: &mt("How do I create a CSV file from a spreadsheet")).
4203: '</td>'.
4204: &Apache::loncommon::end_data_table_row().
4205: &Apache::loncommon::end_data_table();
4206: return $result;
4207: }
4208:
4209:
4210: sub csvuploadmap {
4211: my ($request,$symb)= @_;
4212: if (!$symb) {return '';}
4213:
4214: my $datatoken;
4215: if (!$env{'form.datatoken'}) {
4216: $datatoken=&Apache::loncommon::upfile_store($request);
4217: } else {
4218: $datatoken=$env{'form.datatoken'};
4219: &Apache::loncommon::load_tmp_file($request);
4220: }
4221: my @records=&Apache::loncommon::upfile_record_sep();
4222: &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
4223: my ($i,$keyfields);
4224: if (@records) {
4225: my $fieldserror;
4226: my @fields=&csvupload_fields($symb,\$fieldserror);
4227: if ($fieldserror) {
4228: $request->print(&navmap_errormsg());
4229: return;
4230: }
4231: if ($env{'form.upfile_associate'} eq 'reverse') {
4232: &Apache::loncommon::csv_print_samples($request,\@records);
4233: $i=&Apache::loncommon::csv_print_select_table($request,\@records,
4234: \@fields);
4235: foreach (@fields) { $keyfields.=$_->[0].','; }
4236: chop($keyfields);
4237: } else {
4238: unshift(@fields,['none','']);
4239: $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
4240: \@fields);
4241: foreach my $rec (@records) {
4242: my %temp = &Apache::loncommon::record_sep($rec);
4243: if (%temp) {
4244: $keyfields=join(',',sort(keys(%temp)));
4245: last;
4246: }
4247: }
4248: }
4249: }
4250: &csvuploadmap_footer($request,$i,$keyfields);
4251:
4252: return '';
4253: }
4254:
4255: sub csvuploadoptions {
4256: my ($request,$symb)= @_;
4257: my $overwrite=&mt('Overwrite any existing score');
4258: $request->print(<<ENDPICK);
4259: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
4260: <input type="hidden" name="command" value="csvuploadassign" />
4261: <p>
4262: <label>
4263: <input type="checkbox" name="overwite_scores" checked="checked" />
4264: $overwrite
4265: </label>
4266: </p>
4267: ENDPICK
4268: my %fields=&get_fields();
4269: if (!defined($fields{'domain'})) {
4270: my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
4271: $request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
4272: }
4273: foreach my $key (sort(keys(%env))) {
4274: if ($key !~ /^form\.(.*)$/) { next; }
4275: my $cleankey=$1;
4276: if ($cleankey eq 'command') { next; }
4277: $request->print('<input type="hidden" name="'.$cleankey.
4278: '" value="'.$env{$key}.'" />'."\n");
4279: }
4280: # FIXME do a check for any duplicated user ids...
4281: # FIXME do a check for any invalid user ids?...
4282: $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
4283: <hr /></form>'."\n");
4284: return '';
4285: }
4286:
4287: sub get_fields {
4288: my %fields;
4289: my @keyfields = split(/\,/,$env{'form.keyfields'});
4290: for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
4291: if ($env{'form.upfile_associate'} eq 'reverse') {
4292: if ($env{'form.f'.$i} ne 'none') {
4293: $fields{$keyfields[$i]}=$env{'form.f'.$i};
4294: }
4295: } else {
4296: if ($env{'form.f'.$i} ne 'none') {
4297: $fields{$env{'form.f'.$i}}=$keyfields[$i];
4298: }
4299: }
4300: }
4301: return %fields;
4302: }
4303:
4304: sub csvuploadassign {
4305: my ($request,$symb)= @_;
4306: if (!$symb) {return '';}
4307: my $error_msg = '';
4308: &Apache::loncommon::load_tmp_file($request);
4309: my @gradedata = &Apache::loncommon::upfile_record_sep();
4310: my %fields=&get_fields();
4311: my $courseid=$env{'request.course.id'};
4312: my ($classlist) = &getclasslist('all',0);
4313: my @notallowed;
4314: my @skipped;
4315: my @warnings;
4316: my $countdone=0;
4317: foreach my $grade (@gradedata) {
4318: my %entries=&Apache::loncommon::record_sep($grade);
4319: my $domain;
4320: if ($entries{$fields{'domain'}}) {
4321: $domain=$entries{$fields{'domain'}};
4322: } else {
4323: $domain=$env{'form.default_domain'};
4324: }
4325: $domain=~s/\s//g;
4326: my $username=$entries{$fields{'username'}};
4327: $username=~s/\s//g;
4328: if (!$username) {
4329: my $id=$entries{$fields{'ID'}};
4330: $id=~s/\s//g;
4331: my %ids=&Apache::lonnet::idget($domain,$id);
4332: $username=$ids{$id};
4333: }
4334: if (!exists($$classlist{"$username:$domain"})) {
4335: my $id=$entries{$fields{'ID'}};
4336: $id=~s/\s//g;
4337: if ($id) {
4338: push(@skipped,"$id:$domain");
4339: } else {
4340: push(@skipped,"$username:$domain");
4341: }
4342: next;
4343: }
4344: my $usec=$classlist->{"$username:$domain"}[5];
4345: if (!&canmodify($usec)) {
4346: push(@notallowed,"$username:$domain");
4347: next;
4348: }
4349: my %points;
4350: my %grades;
4351: foreach my $dest (keys(%fields)) {
4352: if ($dest eq 'ID' || $dest eq 'username' ||
4353: $dest eq 'domain') { next; }
4354: if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
4355: if ($dest=~/stores_(.*)_points/) {
4356: my $part=$1;
4357: my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
4358: $symb,$domain,$username);
4359: if ($wgt) {
4360: $entries{$fields{$dest}}=~s/\s//g;
4361: my $pcr=$entries{$fields{$dest}} / $wgt;
4362: my $award=($pcr == 0) ? 'incorrect_by_override'
4363: : 'correct_by_override';
4364: if ($pcr>1) {
4365: push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
4366: }
4367: $grades{"resource.$part.awarded"}=$pcr;
4368: $grades{"resource.$part.solved"}=$award;
4369: $points{$part}=1;
4370: } else {
4371: $error_msg = "<br />" .
4372: &mt("Some point values were assigned"
4373: ." for problems with a weight "
4374: ."of zero. These values were "
4375: ."ignored.");
4376: }
4377: } else {
4378: if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
4379: if ($dest=~/stores_(.*)_solved/) { if ($points{$1}) {next;} }
4380: my $store_key=$dest;
4381: $store_key=~s/^stores/resource/;
4382: $store_key=~s/_/\./g;
4383: $grades{$store_key}=$entries{$fields{$dest}};
4384: }
4385: }
4386: if (! %grades) {
4387: push(@skipped,&mt("[_1]: no data to save","$username:$domain"));
4388: } else {
4389: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
4390: my $result=&Apache::lonnet::cstore(\%grades,$symb,
4391: $env{'request.course.id'},
4392: $domain,$username);
4393: if ($result eq 'ok') {
4394: # Successfully stored
4395: $request->print('.');
4396: # Remove from grading queue
4397: &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
4398: $env{'course.'.$env{'request.course.id'}.'.domain'},
4399: $env{'course.'.$env{'request.course.id'}.'.num'},
4400: $domain,$username);
4401: $countdone++;
4402: } else {
4403: $request->print("<p><span class=\"LC_error\">".
4404: &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
4405: "$username:$domain",$result)."</span></p>");
4406: }
4407: $request->rflush();
4408: }
4409: }
4410: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
4411: if (@warnings) {
4412: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
4413: $request->print(join(', ',@warnings));
4414: }
4415: if (@skipped) {
4416: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
4417: $request->print(join(', ',@skipped));
4418: }
4419: if (@notallowed) {
4420: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
4421: $request->print(join(', ',@notallowed));
4422: }
4423: $request->print("<br />\n");
4424: return $error_msg;
4425: }
4426: #------------- end of section for handling csv file upload ---------
4427: #
4428: #-------------------------------------------------------------------
4429: #
4430: #-------------- Next few routines handle grading by page/sequence
4431: #
4432: #--- Select a page/sequence and a student to grade
4433: sub pickStudentPage {
4434: my ($request,$symb) = @_;
4435:
4436: my $alertmsg = &mt('Please select the student you wish to grade.');
4437: $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
4438:
4439: function checkPickOne(formname) {
4440: if (radioSelection(formname.student) == null) {
4441: alert("$alertmsg");
4442: return;
4443: }
4444: ptr = pullDownSelection(formname.selectpage);
4445: formname.page.value = formname["page"+ptr].value;
4446: formname.title.value = formname["title"+ptr].value;
4447: formname.submit();
4448: }
4449:
4450: LISTJAVASCRIPT
4451: &commonJSfunctions($request);
4452:
4453: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4454: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4455: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4456:
4457: my $result='<h3><span class="LC_info"> '.
4458: &mt('Manual Grading by Page or Sequence').'</span></h3>';
4459:
4460: $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
4461: my $map_error;
4462: my ($titles,$symbx) = &getSymbMap($map_error);
4463: if ($map_error) {
4464: $request->print(&navmap_errormsg());
4465: return;
4466: }
4467: my ($curpage) =&Apache::lonnet::decode_symb($symb);
4468: # my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb);
4469: # my $type=($curpage =~ /\.(page|sequence)/);
4470:
4471: # Collection of hidden fields
4472: my $ctr=0;
4473: foreach (@$titles) {
4474: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4475: $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
4476: $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
4477: $ctr++;
4478: }
4479: $result.='<input type="hidden" name="page" />'."\n".
4480: '<input type="hidden" name="title" />'."\n";
4481:
4482: $result.=&build_section_inputs();
4483: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
4484: $result.='<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
4485: '<input type="hidden" name="command" value="displayPage" />'."\n".
4486: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
4487:
4488: # Show grading options
4489: $result.=&Apache::lonhtmlcommon::start_pick_box();
4490: my $select = '<select name="selectpage">'."\n";
4491: $ctr=0;
4492: foreach (@$titles) {
4493: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4494: $select.='<option value="'.$ctr.'"'.
4495: ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
4496: '>'.$showtitle.'</option>'."\n";
4497: $ctr++;
4498: }
4499: $select.= '</select>';
4500:
4501: $result.=
4502: &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
4503: .$select
4504: .&Apache::lonhtmlcommon::row_closure();
4505:
4506: $result.=
4507: &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
4508: .'<label><input type="radio" name="vProb" value="no"'
4509: .' checked="checked" /> '.&mt('no').' </label>'."\n"
4510: .'<label><input type="radio" name="vProb" value="yes" />'
4511: .&mt('yes').'</label>'."\n"
4512: .&Apache::lonhtmlcommon::row_closure();
4513:
4514: $result.=
4515: &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
4516: .'<label><input type="radio" name="lastSub" value="none" /> '
4517: .&mt('none').' </label>'."\n"
4518: .'<label><input type="radio" name="lastSub" value="datesub"'
4519: .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
4520: .'<label><input type="radio" name="lastSub" value="all" /> '
4521: .&mt('all submissions with details').' </label>'
4522: .&Apache::lonhtmlcommon::row_closure();
4523:
4524: $result.=
4525: &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
4526: .'<input type="text" name="CODE" value="" />'
4527: .&Apache::lonhtmlcommon::row_closure(1)
4528: .&Apache::lonhtmlcommon::end_pick_box();
4529:
4530: # Show list of students to select for grading
4531: $result.='<br /><input type="button" '.
4532: 'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' →" /><br />'."\n";
4533:
4534: $request->print($result);
4535:
4536: my $studentTable.=' <b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
4537: &Apache::loncommon::start_data_table().
4538: &Apache::loncommon::start_data_table_header_row().
4539: '<th align="right"> '.&mt('No.').'</th>'.
4540: '<th>'.&nameUserString('header').'</th>'.
4541: '<th align="right"> '.&mt('No.').'</th>'.
4542: '<th>'.&nameUserString('header').'</th>'.
4543: &Apache::loncommon::end_data_table_header_row();
4544:
4545: my (undef,undef,$fullname) = &getclasslist($getsec,'1');
4546: my $ptr = 1;
4547: foreach my $student (sort
4548: {
4549: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
4550: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
4551: }
4552: return $a cmp $b;
4553: } (keys(%$fullname))) {
4554: my ($uname,$udom) = split(/:/,$student);
4555: $studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
4556: : '</td>');
4557: $studentTable.='<td align="right">'.$ptr.' </td>';
4558: $studentTable.='<td> <label><input type="radio" name="student" value="'.$student.'" /> '
4559: .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
4560: $studentTable.=
4561: ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row()
4562: : '');
4563: $ptr++;
4564: }
4565: if ($ptr%2 == 0) {
4566: $studentTable.='</td><td> </td><td> </td>'.
4567: &Apache::loncommon::end_data_table_row();
4568: }
4569: $studentTable.=&Apache::loncommon::end_data_table()."\n";
4570: $studentTable.='<input type="button" '.
4571: 'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' →" /></form>'."\n";
4572:
4573: $request->print($studentTable);
4574:
4575: return '';
4576: }
4577:
4578: sub getSymbMap {
4579: my ($map_error) = @_;
4580: my $navmap = Apache::lonnavmaps::navmap->new();
4581: unless (ref($navmap)) {
4582: if (ref($map_error)) {
4583: $$map_error = 'navmap';
4584: }
4585: return;
4586: }
4587: my %symbx = ();
4588: my @titles = ();
4589: my $minder = 0;
4590:
4591: # Gather every sequence that has problems.
4592: my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
4593: 1,0,1);
4594: for my $sequence ($navmap->getById('0.0'), @sequences) {
4595: if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
4596: my $title = $minder.'.'.
4597: &HTML::Entities::encode($sequence->compTitle(),'"\'&');
4598: push(@titles, $title); # minder in case two titles are identical
4599: $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
4600: $minder++;
4601: }
4602: }
4603: return \@titles,\%symbx;
4604: }
4605:
4606: #
4607: #--- Displays a page/sequence w/wo problems, w/wo submissions
4608: sub displayPage {
4609: my ($request,$symb) = @_;
4610: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4611: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4612: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4613: my $pageTitle = $env{'form.page'};
4614: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
4615: my ($uname,$udom) = split(/:/,$env{'form.student'});
4616: my $usec=$classlist->{$env{'form.student'}}[5];
4617:
4618: #need to make sure we have the correct data for later EXT calls,
4619: #thus invalidate the cache
4620: &Apache::lonnet::devalidatecourseresdata(
4621: $env{'course.'.$env{'request.course.id'}.'.num'},
4622: $env{'course.'.$env{'request.course.id'}.'.domain'});
4623: &Apache::lonnet::clear_EXT_cache_status();
4624:
4625: if (!&canview($usec)) {
4626: $request->print(
4627: '<span class="LC_warning">'.
4628: &mt('Unable to view requested student. ([_1])',
4629: $env{'form.student'}).
4630: '</span>');
4631: return;
4632: }
4633: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
4634: $result.='<h3> '.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
4635: '</h3>'."\n";
4636: $env{'form.CODE'} = uc($env{'form.CODE'});
4637: if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
4638: $result.='<h3> '.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
4639: } else {
4640: delete($env{'form.CODE'});
4641: }
4642: &sub_page_js($request);
4643: $request->print($result);
4644:
4645: my $navmap = Apache::lonnavmaps::navmap->new();
4646: unless (ref($navmap)) {
4647: $request->print(&navmap_errormsg());
4648: return;
4649: }
4650: my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
4651: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
4652: if (!$map) {
4653: $request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
4654: return;
4655: }
4656: my $iterator = $navmap->getIterator($map->map_start(),
4657: $map->map_finish());
4658:
4659: my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
4660: '<input type="hidden" name="command" value="gradeByPage" />'."\n".
4661: '<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
4662: '<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
4663: '<input type="hidden" name="page" value="'.$pageTitle.'" />'."\n".
4664: '<input type="hidden" name="title" value="'.$env{'form.title'}.'" />'."\n".
4665: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
4666: '<input type="hidden" name="overRideScore" value="no" />'."\n";
4667:
4668: if (defined($env{'form.CODE'})) {
4669: $studentTable.=
4670: '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
4671: }
4672: my $checkIcon = '<img alt="'.&mt('Check Mark').
4673: '" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
4674:
4675: $studentTable.=' <span class="LC_info">'.
4676: &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
4677: '</span>'."\n".
4678: &Apache::loncommon::start_data_table().
4679: &Apache::loncommon::start_data_table_header_row().
4680: '<th>'.&mt('Prob.').'</th>'.
4681: '<th> '.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
4682: &Apache::loncommon::end_data_table_header_row();
4683:
4684: &Apache::lonxml::clear_problem_counter();
4685: my ($depth,$question,$prob) = (1,1,1);
4686: $iterator->next(); # skip the first BEGIN_MAP
4687: my $curRes = $iterator->next(); # for "current resource"
4688: while ($depth > 0) {
4689: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
4690: if($curRes == $iterator->END_MAP) { $depth--; }
4691:
4692: if (ref($curRes) && $curRes->is_problem()) {
4693: my $parts = $curRes->parts();
4694: my $title = $curRes->compTitle();
4695: my $symbx = $curRes->symb();
4696: $studentTable.=
4697: &Apache::loncommon::start_data_table_row().
4698: '<td align="center" valign="top" >'.$prob.
4699: (scalar(@{$parts}) == 1 ? ''
4700: : '<br />('.&mt('[_1]parts',
4701: scalar(@{$parts}).' ').')'
4702: ).
4703: '</td>';
4704: $studentTable.='<td valign="top">';
4705: my %form = ('CODE' => $env{'form.CODE'},);
4706: if ($env{'form.vProb'} eq 'yes' ) {
4707: $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
4708: undef,'both',\%form);
4709: } else {
4710: my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
4711: $companswer =~ s|<form(.*?)>||g;
4712: $companswer =~ s|</form>||g;
4713: # while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
4714: # $companswer =~ s/$1/ /ms;
4715: # $request->print('match='.$1."<br />\n");
4716: # }
4717: # $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
4718: $studentTable.=' <b>'.$title.'</b> <br /> <b>'.&mt('Correct answer').':</b><br />'.$companswer;
4719: }
4720:
4721: my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
4722:
4723: if ($env{'form.lastSub'} eq 'datesub') {
4724: if ($record{'version'} eq '') {
4725: $studentTable.='<br /> <span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
4726: } else {
4727: my %responseType = ();
4728: foreach my $partid (@{$parts}) {
4729: my @responseIds =$curRes->responseIds($partid);
4730: my @responseType =$curRes->responseType($partid);
4731: my %responseIds;
4732: for (my $i=0;$i<=$#responseIds;$i++) {
4733: $responseIds{$responseIds[$i]}=$responseType[$i];
4734: }
4735: $responseType{$partid} = \%responseIds;
4736: }
4737: $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
4738:
4739: }
4740: } elsif ($env{'form.lastSub'} eq 'all') {
4741: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
4742: $studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
4743: $env{'request.course.id'},
4744: '','.submission');
4745:
4746: }
4747: if (&canmodify($usec)) {
4748: $studentTable.=&gradeBox_start();
4749: foreach my $partid (@{$parts}) {
4750: $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
4751: $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
4752: $question++;
4753: }
4754: $studentTable.=&gradeBox_end();
4755: $prob++;
4756: }
4757: $studentTable.='</td></tr>';
4758:
4759: }
4760: $curRes = $iterator->next();
4761: }
4762:
4763: $studentTable.=
4764: '</table>'."\n".
4765: '<input type="button" value="'.&mt('Save').'" '.
4766: 'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
4767: '</form>'."\n";
4768: $request->print($studentTable);
4769:
4770: return '';
4771: }
4772:
4773: sub displaySubByDates {
4774: my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
4775: my $isCODE=0;
4776: my $isTask = ($symb =~/\.task$/);
4777: if (exists($record->{'resource.CODE'})) { $isCODE=1; }
4778: my $studentTable=&Apache::loncommon::start_data_table().
4779: &Apache::loncommon::start_data_table_header_row().
4780: '<th>'.&mt('Date/Time').'</th>'.
4781: ($isCODE?'<th>'.&mt('CODE').'</th>':'').
4782: ($isTask?'<th>'.&mt('Version').'</th>':'').
4783: '<th>'.&mt('Submission').'</th>'.
4784: '<th>'.&mt('Status').'</th>'.
4785: &Apache::loncommon::end_data_table_header_row();
4786: my ($version);
4787: my %mark;
4788: my %orders;
4789: $mark{'correct_by_student'} = $checkIcon;
4790: if (!exists($$record{'1:timestamp'})) {
4791: return '<br /> <span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
4792: }
4793:
4794: my $interaction;
4795: my $no_increment = 1;
4796: my %lastrndseed;
4797: for ($version=1;$version<=$$record{'version'};$version++) {
4798: my $timestamp =
4799: &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
4800: if (exists($$record{$version.':resource.0.version'})) {
4801: $interaction = $$record{$version.':resource.0.version'};
4802: }
4803: if ($isTask && $env{'form.previousversion'}) {
4804: next unless ($interaction == $env{'form.previousversion'});
4805: }
4806: my $where = ($isTask ? "$version:resource.$interaction"
4807: : "$version:resource");
4808: $studentTable.=&Apache::loncommon::start_data_table_row().
4809: '<td>'.$timestamp.'</td>';
4810: if ($isCODE) {
4811: $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
4812: }
4813: if ($isTask) {
4814: $studentTable.='<td>'.$interaction.'</td>';
4815: }
4816: my @versionKeys = split(/\:/,$$record{$version.':keys'});
4817: my @displaySub = ();
4818: foreach my $partid (@{$parts}) {
4819: my ($hidden,$type);
4820: $type = $$record{$version.':resource.'.$partid.'.type'};
4821: if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
4822: $hidden = 1;
4823: }
4824: my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
4825: : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
4826:
4827: # next if ($$record{"$version:resource.$partid.solved"} eq '');
4828: my $display_part=&get_display_part($partid,$symb);
4829: foreach my $matchKey (@matchKey) {
4830: if (exists($$record{$version.':'.$matchKey}) &&
4831: $$record{$version.':'.$matchKey} ne '') {
4832:
4833: my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
4834: : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
4835: $displaySub[0].='<span class="LC_nobreak">';
4836: $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
4837: .' <span class="LC_internal_info">'
4838: .'('.&mt('Response ID: [_1]',$responseId).')'
4839: .'</span>'
4840: .' <b>';
4841: if ($hidden) {
4842: $displaySub[0].= &mt('Anonymous Survey').'</b>';
4843: } else {
4844: my ($trial,$rndseed,$newvariation);
4845: if ($type eq 'randomizetry') {
4846: $trial = $$record{"$where.$partid.tries"};
4847: $rndseed = $$record{"$where.$partid.rndseed"};
4848: }
4849: if ($$record{"$where.$partid.tries"} eq '') {
4850: $displaySub[0].=&mt('Trial not counted');
4851: } else {
4852: $displaySub[0].=&mt('Trial: [_1]',
4853: $$record{"$where.$partid.tries"});
4854: if ($rndseed || $lastrndseed{$partid}) {
4855: if ($rndseed ne $lastrndseed{$partid}) {
4856: $newvariation = ' ('.&mt('New variation this try').')';
4857: }
4858: }
4859: $lastrndseed{$partid} = $rndseed;
4860: }
4861: my $responseType=($isTask ? 'Task'
4862: : $responseType->{$partid}->{$responseId});
4863: if (!exists($orders{$partid})) { $orders{$partid}={}; }
4864: if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
4865: $orders{$partid}->{$responseId}=
4866: &get_order($partid,$responseId,$symb,$uname,$udom,
4867: $no_increment,$type,$trial,$rndseed);
4868: }
4869: $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
4870: $displaySub[0].=' '.
4871: &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
4872: }
4873: }
4874: }
4875: if (exists($$record{"$where.$partid.checkedin"})) {
4876: $displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
4877: $$record{"$where.$partid.checkedin"},
4878: $$record{"$where.$partid.checkedin.slot"}).
4879: '<br />';
4880: }
4881: if (exists $$record{"$where.$partid.award"}) {
4882: $displaySub[1].='<b>'.&mt('Part:').'</b> '.$display_part.' '.
4883: lc($$record{"$where.$partid.award"}).' '.
4884: $mark{$$record{"$where.$partid.solved"}}.
4885: '<br />';
4886: }
4887: if (exists $$record{"$where.$partid.regrader"}) {
4888: $displaySub[2].=$$record{"$where.$partid.regrader"}.
4889: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
4890: } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
4891: $displaySub[2].=
4892: $$record{"$version:resource.$partid.regrader"}.
4893: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
4894: }
4895: }
4896: # needed because old essay regrader has not parts info
4897: if (exists $$record{"$version:resource.regrader"}) {
4898: $displaySub[2].=$$record{"$version:resource.regrader"};
4899: }
4900: $studentTable.='<td>'.$displaySub[0].' </td><td>'.$displaySub[1];
4901: if ($displaySub[2]) {
4902: $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
4903: }
4904: $studentTable.=' </td>'.
4905: &Apache::loncommon::end_data_table_row();
4906: }
4907: $studentTable.=&Apache::loncommon::end_data_table();
4908: return $studentTable;
4909: }
4910:
4911: sub updateGradeByPage {
4912: my ($request,$symb) = @_;
4913:
4914: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4915: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4916: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4917: my $pageTitle = $env{'form.page'};
4918: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
4919: my ($uname,$udom) = split(/:/,$env{'form.student'});
4920: my $usec=$classlist->{$env{'form.student'}}[5];
4921: if (!&canmodify($usec)) {
4922: $request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
4923: return;
4924: }
4925: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
4926: $result.='<h3> '.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
4927: '</h3>'."\n";
4928:
4929: $request->print($result);
4930:
4931:
4932: my $navmap = Apache::lonnavmaps::navmap->new();
4933: unless (ref($navmap)) {
4934: $request->print(&navmap_errormsg());
4935: return;
4936: }
4937: my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
4938: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
4939: if (!$map) {
4940: $request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
4941: return;
4942: }
4943: my $iterator = $navmap->getIterator($map->map_start(),
4944: $map->map_finish());
4945:
4946: my $studentTable=
4947: &Apache::loncommon::start_data_table().
4948: &Apache::loncommon::start_data_table_header_row().
4949: '<th align="center"> '.&mt('Prob.').' </th>'.
4950: '<th> '.&mt('Title').' </th>'.
4951: '<th> '.&mt('Previous Score').' </th>'.
4952: '<th> '.&mt('New Score').' </th>'.
4953: &Apache::loncommon::end_data_table_header_row();
4954:
4955: $iterator->next(); # skip the first BEGIN_MAP
4956: my $curRes = $iterator->next(); # for "current resource"
4957: my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
4958: while ($depth > 0) {
4959: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
4960: if($curRes == $iterator->END_MAP) { $depth--; }
4961:
4962: if (ref($curRes) && $curRes->is_problem()) {
4963: my $parts = $curRes->parts();
4964: my $title = $curRes->compTitle();
4965: my $symbx = $curRes->symb();
4966: $studentTable.=
4967: &Apache::loncommon::start_data_table_row().
4968: '<td align="center" valign="top" >'.$prob.
4969: (scalar(@{$parts}) == 1 ? ''
4970: : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
4971: .')').'</td>';
4972: $studentTable.='<td valign="top"> <b>'.$title.'</b> </td>';
4973:
4974: my %newrecord=();
4975: my @displayPts=();
4976: my %aggregate = ();
4977: my $aggregateflag = 0;
4978: foreach my $partid (@{$parts}) {
4979: my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
4980: my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
4981:
4982: my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ?
4983: $env{'form.WGT'.$question.'_'.$partid} : 1;
4984: my $partial = $newpts/$wgt;
4985: my $score;
4986: if ($partial > 0) {
4987: $score = 'correct_by_override';
4988: } elsif ($newpts ne '') { #empty is taken as 0
4989: $score = 'incorrect_by_override';
4990: }
4991: my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
4992: if ($dropMenu eq 'excused') {
4993: $partial = '';
4994: $score = 'excused';
4995: } elsif ($dropMenu eq 'reset status'
4996: && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
4997: $newrecord{'resource.'.$partid.'.tries'} = 0;
4998: $newrecord{'resource.'.$partid.'.solved'} = '';
4999: $newrecord{'resource.'.$partid.'.award'} = '';
5000: $newrecord{'resource.'.$partid.'.awarded'} = 0;
5001: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
5002: $changeflag++;
5003: $newpts = '';
5004:
5005: my $aggtries = $env{'form.aggtries'.$question.'_'.$partid};
5006: my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
5007: my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
5008: if ($aggtries > 0) {
5009: &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
5010: $aggregateflag = 1;
5011: }
5012: }
5013: my $display_part=&get_display_part($partid,$curRes->symb());
5014: my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
5015: $displayPts[0].=' <b>'.&mt('Part').':</b> '.$display_part.' = '.
5016: (($oldstatus eq 'excused') ? 'excused' : $oldpts).
5017: ' <br />';
5018: $displayPts[1].=' <b>'.&mt('Part').':</b> '.$display_part.' = '.
5019: (($score eq 'excused') ? 'excused' : $newpts).
5020: ' <br />';
5021: $question++;
5022: next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
5023:
5024: $newrecord{'resource.'.$partid.'.awarded'} = $partial if $partial ne '';
5025: $newrecord{'resource.'.$partid.'.solved'} = $score if $score ne '';
5026: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
5027: if (scalar(keys(%newrecord)) > 0);
5028:
5029: $changeflag++;
5030: }
5031: if (scalar(keys(%newrecord)) > 0) {
5032: my %record =
5033: &Apache::lonnet::restore($symbx,$env{'request.course.id'},
5034: $udom,$uname);
5035:
5036: if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
5037: $newrecord{'resource.CODE'} = $env{'form.CODE'};
5038: } elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
5039: $newrecord{'resource.CODE'} = '';
5040: }
5041: &Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
5042: $udom,$uname);
5043: %record = &Apache::lonnet::restore($symbx,
5044: $env{'request.course.id'},
5045: $udom,$uname);
5046: &check_and_remove_from_queue($parts,\%record,undef,$symbx,
5047: $cdom,$cnum,$udom,$uname);
5048: }
5049:
5050: if ($aggregateflag) {
5051: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
5052: $env{'course.'.$env{'request.course.id'}.'.domain'},
5053: $env{'course.'.$env{'request.course.id'}.'.num'});
5054: }
5055:
5056: $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
5057: '<td valign="top">'.$displayPts[1].'</td>'.
5058: &Apache::loncommon::end_data_table_row();
5059:
5060: $prob++;
5061: }
5062: $curRes = $iterator->next();
5063: }
5064:
5065: $studentTable.=&Apache::loncommon::end_data_table();
5066: my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
5067: &mt('The scores were changed for [quant,_1,problem].',
5068: $changeflag));
5069: $request->print($grademsg.$studentTable);
5070:
5071: return '';
5072: }
5073:
5074: #-------- end of section for handling grading by page/sequence ---------
5075: #
5076: #-------------------------------------------------------------------
5077:
5078: #-------------------- Bubblesheet (Scantron) Grading -------------------
5079: #
5080: #------ start of section for handling grading by page/sequence ---------
5081:
5082: =pod
5083:
5084: =head1 Bubble sheet grading routines
5085:
5086: For this documentation:
5087:
5088: 'scanline' refers to the full line of characters
5089: from the file that we are parsing that represents one entire sheet
5090:
5091: 'bubble line' refers to the data
5092: representing the line of bubbles that are on the physical bubblesheet
5093:
5094:
5095: The overall process is that a scanned in bubblesheet data is uploaded
5096: into a course. When a user wants to grade, they select a
5097: sequence/folder of resources, a file of bubblesheet info, and pick
5098: one of the predefined configurations for what each scanline looks
5099: like.
5100:
5101: Next each scanline is checked for any errors of either 'missing
5102: bubbles' (it's an error because it may have been mis-scanned
5103: because too light bubbling), 'double bubble' (each bubble line should
5104: have no more than one letter picked), invalid or duplicated CODE,
5105: invalid student/employee ID
5106:
5107: If the CODE option is used that determines the randomization of the
5108: homework problems, either way the student/employee ID is looked up into a
5109: username:domain.
5110:
5111: During the validation phase the instructor can choose to skip scanlines.
5112:
5113: After the validation phase, there are now 3 bubblesheet files
5114:
5115: scantron_original_filename (unmodified original file)
5116: scantron_corrected_filename (file where the corrected information has replaced the original information)
5117: scantron_skipped_filename (contains the exact text of scanlines that where skipped)
5118:
5119: Also there is a separate hash nohist_scantrondata that contains extra
5120: correction information that isn't representable in the bubblesheet
5121: file (see &scantron_getfile() for more information)
5122:
5123: After all scanlines are either valid, marked as valid or skipped, then
5124: foreach line foreach problem in the picked sequence, an ssi request is
5125: made that simulates a user submitting their selected letter(s) against
5126: the homework problem.
5127:
5128: =over 4
5129:
5130:
5131:
5132: =item defaultFormData
5133:
5134: Returns html hidden inputs used to hold context/default values.
5135:
5136: Arguments:
5137: $symb - $symb of the current resource
5138:
5139: =cut
5140:
5141: sub defaultFormData {
5142: my ($symb)=@_;
5143: return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
5144: }
5145:
5146:
5147: =pod
5148:
5149: =item getSequenceDropDown
5150:
5151: Return html dropdown of possible sequences to grade
5152:
5153: Arguments:
5154: $symb - $symb of the current resource
5155: $map_error - ref to scalar which will container error if
5156: $navmap object is unavailable in &getSymbMap().
5157:
5158: =cut
5159:
5160: sub getSequenceDropDown {
5161: my ($symb,$map_error)=@_;
5162: my $result='<select name="selectpage">'."\n";
5163: my ($titles,$symbx) = &getSymbMap($map_error);
5164: if (ref($map_error)) {
5165: return if ($$map_error);
5166: }
5167: my ($curpage)=&Apache::lonnet::decode_symb($symb);
5168: my $ctr=0;
5169: foreach (@$titles) {
5170: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
5171: $result.='<option value="'.$$symbx{$_}.'" '.
5172: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
5173: '>'.$showtitle.'</option>'."\n";
5174: $ctr++;
5175: }
5176: $result.= '</select>';
5177: return $result;
5178: }
5179:
5180: my %bubble_lines_per_response; # no. bubble lines for each response.
5181: # key is zero-based index - 0, 1, 2 ...
5182:
5183: my %first_bubble_line; # First bubble line no. for each bubble.
5184:
5185: my %subdivided_bubble_lines; # no. bubble lines for optionresponse,
5186: # matchresponse or rankresponse, where
5187: # an individual response can have multiple
5188: # lines
5189:
5190: my %responsetype_per_response; # responsetype for each response
5191:
5192: my %masterseq_id_responsenum; # src_id (e.g., 12.3_0.11 etc.) for each
5193: # numbered response. Needed when randomorder
5194: # or randompick are in use. Key is ID, value
5195: # is response number.
5196:
5197: # Save and restore the bubble lines array to the form env.
5198:
5199:
5200: sub save_bubble_lines {
5201: foreach my $line (keys(%bubble_lines_per_response)) {
5202: $env{"form.scantron.bubblelines.$line"} = $bubble_lines_per_response{$line};
5203: $env{"form.scantron.first_bubble_line.$line"} =
5204: $first_bubble_line{$line};
5205: $env{"form.scantron.sub_bubblelines.$line"} =
5206: $subdivided_bubble_lines{$line};
5207: $env{"form.scantron.responsetype.$line"} =
5208: $responsetype_per_response{$line};
5209: }
5210: foreach my $resid (keys(%masterseq_id_responsenum)) {
5211: my $line = $masterseq_id_responsenum{$resid};
5212: $env{"form.scantron.residpart.$line"} = $resid;
5213: }
5214: }
5215:
5216:
5217: sub restore_bubble_lines {
5218: my $line = 0;
5219: %bubble_lines_per_response = ();
5220: %masterseq_id_responsenum = ();
5221: while ($env{"form.scantron.bubblelines.$line"}) {
5222: my $value = $env{"form.scantron.bubblelines.$line"};
5223: $bubble_lines_per_response{$line} = $value;
5224: $first_bubble_line{$line} =
5225: $env{"form.scantron.first_bubble_line.$line"};
5226: $subdivided_bubble_lines{$line} =
5227: $env{"form.scantron.sub_bubblelines.$line"};
5228: $responsetype_per_response{$line} =
5229: $env{"form.scantron.responsetype.$line"};
5230: my $id = $env{"form.scantron.residpart.$line"};
5231: $masterseq_id_responsenum{$id} = $line;
5232: $line++;
5233: }
5234: }
5235:
5236: =pod
5237:
5238: =item scantron_filenames
5239:
5240: Returns a list of the scantron files in the current course
5241:
5242: =cut
5243:
5244: sub scantron_filenames {
5245: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5246: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5247: my $getpropath = 1;
5248: my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
5249: $cname,$getpropath);
5250: my @possiblenames;
5251: if (ref($dirlist) eq 'ARRAY') {
5252: foreach my $filename (sort(@{$dirlist})) {
5253: ($filename)=split(/&/,$filename);
5254: if ($filename!~/^scantron_orig_/) { next ; }
5255: $filename=~s/^scantron_orig_//;
5256: push(@possiblenames,$filename);
5257: }
5258: }
5259: return @possiblenames;
5260: }
5261:
5262: =pod
5263:
5264: =item scantron_uploads
5265:
5266: Returns html drop-down list of scantron files in current course.
5267:
5268: Arguments:
5269: $file2grade - filename to set as selected in the dropdown
5270:
5271: =cut
5272:
5273: sub scantron_uploads {
5274: my ($file2grade) = @_;
5275: my $result= '<select name="scantron_selectfile">';
5276: $result.="<option></option>";
5277: foreach my $filename (sort(&scantron_filenames())) {
5278: $result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
5279: }
5280: $result.="</select>";
5281: return $result;
5282: }
5283:
5284: =pod
5285:
5286: =item scantron_scantab
5287:
5288: Returns html drop down of the scantron formats in the scantronformat.tab
5289: file.
5290:
5291: =cut
5292:
5293: sub scantron_scantab {
5294: my $result='<select name="scantron_format">'."\n";
5295: $result.='<option></option>'."\n";
5296: my @lines = &get_scantronformat_file();
5297: if (@lines > 0) {
5298: foreach my $line (@lines) {
5299: next if (($line =~ /^\#/) || ($line eq ''));
5300: my ($name,$descrip)=split(/:/,$line);
5301: $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
5302: }
5303: }
5304: $result.='</select>'."\n";
5305: return $result;
5306: }
5307:
5308: =pod
5309:
5310: =item get_scantronformat_file
5311:
5312: Returns an array containing lines from the scantron format file for
5313: the domain of the course.
5314:
5315: If a url for a custom.tab file is listed in domain's configuration.db,
5316: lines are from this file.
5317:
5318: Otherwise, if a default.tab has been published in RES space by the
5319: domainconfig user, lines are from this file.
5320:
5321: Otherwise, fall back to getting lines from the legacy file on the
5322: local server: /home/httpd/lonTabs/default_scantronformat.tab
5323:
5324: =cut
5325:
5326: sub get_scantronformat_file {
5327: my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
5328: my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
5329: my $gottab = 0;
5330: my @lines;
5331: if (ref($domconfig{'scantron'}) eq 'HASH') {
5332: if ($domconfig{'scantron'}{'scantronformat'} ne '') {
5333: my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
5334: if ($formatfile ne '-1') {
5335: @lines = split("\n",$formatfile,-1);
5336: $gottab = 1;
5337: }
5338: }
5339: }
5340: if (!$gottab) {
5341: my $confname = $cdom.'-domainconfig';
5342: my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
5343: my $formatfile = &Apache::lonnet::getfile($default);
5344: if ($formatfile ne '-1') {
5345: @lines = split("\n",$formatfile,-1);
5346: $gottab = 1;
5347: }
5348: }
5349: if (!$gottab) {
5350: my @domains = &Apache::lonnet::current_machine_domains();
5351: if (grep(/^\Q$cdom\E$/,@domains)) {
5352: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
5353: @lines = <$fh>;
5354: close($fh);
5355: } else {
5356: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
5357: @lines = <$fh>;
5358: close($fh);
5359: }
5360: }
5361: return @lines;
5362: }
5363:
5364: =pod
5365:
5366: =item scantron_CODElist
5367:
5368: Returns html drop down of the saved CODE lists from current course,
5369: generated from earlier printings.
5370:
5371: =cut
5372:
5373: sub scantron_CODElist {
5374: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5375: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5376: my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
5377: my $namechoice='<option></option>';
5378: foreach my $name (sort {uc($a) cmp uc($b)} @names) {
5379: if ($name =~ /^error: 2 /) { next; }
5380: if ($name =~ /^type\0/) { next; }
5381: $namechoice.='<option value="'.$name.'">'.$name.'</option>';
5382: }
5383: $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
5384: return $namechoice;
5385: }
5386:
5387: =pod
5388:
5389: =item scantron_CODEunique
5390:
5391: Returns the html for "Each CODE to be used once" radio.
5392:
5393: =cut
5394:
5395: sub scantron_CODEunique {
5396: my $result='<span class="LC_nobreak">
5397: <label><input type="radio" name="scantron_CODEunique"
5398: value="yes" checked="checked" />'.&mt('Yes').' </label>
5399: </span>
5400: <span class="LC_nobreak">
5401: <label><input type="radio" name="scantron_CODEunique"
5402: value="no" />'.&mt('No').' </label>
5403: </span>';
5404: return $result;
5405: }
5406:
5407: =pod
5408:
5409: =item scantron_selectphase
5410:
5411: Generates the initial screen to start the bubblesheet process.
5412: Allows for - starting a grading run.
5413: - downloading existing scan data (original, corrected
5414: or skipped info)
5415:
5416: - uploading new scan data
5417:
5418: Arguments:
5419: $r - The Apache request object
5420: $file2grade - name of the file that contain the scanned data to score
5421:
5422: =cut
5423:
5424: sub scantron_selectphase {
5425: my ($r,$file2grade,$symb) = @_;
5426: if (!$symb) {return '';}
5427: my $map_error;
5428: my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
5429: if ($map_error) {
5430: $r->print('<br />'.&navmap_errormsg().'<br />');
5431: return;
5432: }
5433: my $default_form_data=&defaultFormData($symb);
5434: my $file_selector=&scantron_uploads($file2grade);
5435: my $format_selector=&scantron_scantab();
5436: my $CODE_selector=&scantron_CODElist();
5437: my $CODE_unique=&scantron_CODEunique();
5438: my $result;
5439:
5440: $ssi_error = 0;
5441:
5442: if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
5443: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
5444:
5445: # Chunk of form to prompt for a scantron file upload.
5446:
5447: $r->print('
5448: <br />
5449: '.&Apache::loncommon::start_data_table('LC_scantron_action').'
5450: '.&Apache::loncommon::start_data_table_header_row().'
5451: <th>
5452: '.&mt('Specify a bubblesheet data file to upload.').'
5453: </th>
5454: '.&Apache::loncommon::end_data_table_header_row().'
5455: '.&Apache::loncommon::start_data_table_row().'
5456: <td>
5457: ');
5458: my $default_form_data=&defaultFormData($symb);
5459: my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
5460: my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
5461: $r->print(&Apache::lonhtmlcommon::scripttag('
5462: function checkUpload(formname) {
5463: if (formname.upfile.value == "") {
5464: alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
5465: return false;
5466: }
5467: formname.submit();
5468: }'));
5469: $r->print('
5470: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
5471: '.$default_form_data.'
5472: <input name="courseid" type="hidden" value="'.$cnum.'" />
5473: <input name="domainid" type="hidden" value="'.$cdom.'" />
5474: <input name="command" value="scantronupload_save" type="hidden" />
5475: '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
5476: <br />
5477: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
5478: </form>
5479: ');
5480:
5481: $r->print('
5482: </td>
5483: '.&Apache::loncommon::end_data_table_row().'
5484: '.&Apache::loncommon::end_data_table().'
5485: ');
5486: }
5487:
5488: # Chunk of form to prompt for a file to grade and how:
5489:
5490: $result.= '
5491: <br />
5492: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
5493: <input type="hidden" name="command" value="scantron_warning" />
5494: '.$default_form_data.'
5495: '.&Apache::loncommon::start_data_table('LC_scantron_action').'
5496: '.&Apache::loncommon::start_data_table_header_row().'
5497: <th colspan="2">
5498: '.&mt('Specify file and which Folder/Sequence to grade').'
5499: </th>
5500: '.&Apache::loncommon::end_data_table_header_row().'
5501: '.&Apache::loncommon::start_data_table_row().'
5502: <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
5503: '.&Apache::loncommon::end_data_table_row().'
5504: '.&Apache::loncommon::start_data_table_row().'
5505: <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
5506: '.&Apache::loncommon::end_data_table_row().'
5507: '.&Apache::loncommon::start_data_table_row().'
5508: <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
5509: '.&Apache::loncommon::end_data_table_row().'
5510: '.&Apache::loncommon::start_data_table_row().'
5511: <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
5512: '.&Apache::loncommon::end_data_table_row().'
5513: '.&Apache::loncommon::start_data_table_row().'
5514: <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
5515: '.&Apache::loncommon::end_data_table_row().'
5516: '.&Apache::loncommon::start_data_table_row().'
5517: <td> '.&mt('Options:').' </td>
5518: <td>
5519: <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
5520: <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
5521: <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
5522: </td>
5523: '.&Apache::loncommon::end_data_table_row().'
5524: '.&Apache::loncommon::start_data_table_row().'
5525: <td colspan="2">
5526: <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
5527: </td>
5528: '.&Apache::loncommon::end_data_table_row().'
5529: '.&Apache::loncommon::end_data_table().'
5530: </form>
5531: ';
5532:
5533: $r->print($result);
5534:
5535:
5536:
5537: # Chunk of the form that prompts to view a scoring office file,
5538: # corrected file, skipped records in a file.
5539:
5540: $r->print('
5541: <br />
5542: <form action="/adm/grades" name="scantron_download">
5543: '.$default_form_data.'
5544: <input type="hidden" name="command" value="scantron_download" />
5545: '.&Apache::loncommon::start_data_table('LC_scantron_action').'
5546: '.&Apache::loncommon::start_data_table_header_row().'
5547: <th>
5548: '.&mt('Download a scoring office file').'
5549: </th>
5550: '.&Apache::loncommon::end_data_table_header_row().'
5551: '.&Apache::loncommon::start_data_table_row().'
5552: <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).'
5553: <br />
5554: <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
5555: '.&Apache::loncommon::end_data_table_row().'
5556: '.&Apache::loncommon::end_data_table().'
5557: </form>
5558: <br />
5559: ');
5560:
5561: &Apache::lonpickcode::code_list($r,2);
5562:
5563: $r->print('<br /><form method="post" name="checkscantron" action="">'.
5564: $default_form_data."\n".
5565: &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
5566: &Apache::loncommon::start_data_table_header_row()."\n".
5567: '<th colspan="2">
5568: '.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
5569: '</th>'."\n".
5570: &Apache::loncommon::end_data_table_header_row()."\n".
5571: &Apache::loncommon::start_data_table_row()."\n".
5572: '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
5573: '<td> '.$sequence_selector.' </td>'.
5574: &Apache::loncommon::end_data_table_row()."\n".
5575: &Apache::loncommon::start_data_table_row()."\n".
5576: '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
5577: '<td> '.$file_selector.' </td>'."\n".
5578: &Apache::loncommon::end_data_table_row()."\n".
5579: &Apache::loncommon::start_data_table_row()."\n".
5580: '<td> '.&mt('Format of data file:').' </td>'."\n".
5581: '<td> '.$format_selector.' </td>'."\n".
5582: &Apache::loncommon::end_data_table_row()."\n".
5583: &Apache::loncommon::start_data_table_row()."\n".
5584: '<td> '.&mt('Options').' </td>'."\n".
5585: '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
5586: &Apache::loncommon::end_data_table_row()."\n".
5587: &Apache::loncommon::start_data_table_row()."\n".
5588: '<td colspan="2">'."\n".
5589: '<input type="hidden" name="command" value="checksubmissions" />'."\n".
5590: '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
5591: '</td>'."\n".
5592: &Apache::loncommon::end_data_table_row()."\n".
5593: &Apache::loncommon::end_data_table()."\n".
5594: '</form><br />');
5595: return;
5596: }
5597:
5598: =pod
5599:
5600: =item get_scantron_config
5601:
5602: Parse and return the bubblesheet configuration line selected as a
5603: hash of configuration file fields.
5604:
5605: Arguments:
5606: which - the name of the configuration to parse from the file.
5607:
5608:
5609: Returns:
5610: If the named configuration is not in the file, an empty
5611: hash is returned.
5612: a hash with the fields
5613: name - internal name for the this configuration setup
5614: description - text to display to operator that describes this config
5615: CODElocation - if 0 or the string 'none'
5616: - no CODE exists for this config
5617: if -1 || the string 'letter'
5618: - a CODE exists for this config and is
5619: a string of letters
5620: Unsupported value (but planned for future support)
5621: if a positive integer
5622: - The CODE exists as the first n items from
5623: the question section of the form
5624: if the string 'number'
5625: - The CODE exists for this config and is
5626: a string of numbers
5627: CODEstart - (only matter if a CODE exists) column in the line where
5628: the CODE starts
5629: CODElength - length of the CODE
5630: IDstart - column where the student/employee ID starts
5631: IDlength - length of the student/employee ID info
5632: Qstart - column where the information from the bubbled
5633: 'questions' start
5634: Qlength - number of columns comprising a single bubble line from
5635: the sheet. (usually either 1 or 10)
5636: Qon - either a single character representing the character used
5637: to signal a bubble was chosen in the positional setup, or
5638: the string 'letter' if the letter of the chosen bubble is
5639: in the final, or 'number' if a number representing the
5640: chosen bubble is in the file (1->A 0->J)
5641: Qoff - the character used to represent that a bubble was
5642: left blank
5643: PaperID - if the scanning process generates a unique number for each
5644: sheet scanned the column that this ID number starts in
5645: PaperIDlength - number of columns that comprise the unique ID number
5646: for the sheet of paper
5647: FirstName - column that the first name starts in
5648: FirstNameLength - number of columns that the first name spans
5649:
5650: LastName - column that the last name starts in
5651: LastNameLength - number of columns that the last name spans
5652: BubblesPerRow - number of bubbles available in each row used to
5653: bubble an answer. (If not specified, 10 assumed).
5654:
5655: =cut
5656:
5657: sub get_scantron_config {
5658: my ($which) = @_;
5659: my @lines = &get_scantronformat_file();
5660: my %config;
5661: #FIXME probably should move to XML it has already gotten a bit much now
5662: foreach my $line (@lines) {
5663: my ($name,$descrip)=split(/:/,$line);
5664: if ($name ne $which ) { next; }
5665: chomp($line);
5666: my @config=split(/:/,$line);
5667: $config{'name'}=$config[0];
5668: $config{'description'}=$config[1];
5669: $config{'CODElocation'}=$config[2];
5670: $config{'CODEstart'}=$config[3];
5671: $config{'CODElength'}=$config[4];
5672: $config{'IDstart'}=$config[5];
5673: $config{'IDlength'}=$config[6];
5674: $config{'Qstart'}=$config[7];
5675: $config{'Qlength'}=$config[8];
5676: $config{'Qoff'}=$config[9];
5677: $config{'Qon'}=$config[10];
5678: $config{'PaperID'}=$config[11];
5679: $config{'PaperIDlength'}=$config[12];
5680: $config{'FirstName'}=$config[13];
5681: $config{'FirstNamelength'}=$config[14];
5682: $config{'LastName'}=$config[15];
5683: $config{'LastNamelength'}=$config[16];
5684: $config{'BubblesPerRow'}=$config[17];
5685: last;
5686: }
5687: return %config;
5688: }
5689:
5690: =pod
5691:
5692: =item username_to_idmap
5693:
5694: creates a hash keyed by student/employee ID with values of the corresponding
5695: student username:domain.
5696:
5697: Arguments:
5698:
5699: $classlist - reference to the class list hash. This is a hash
5700: keyed by student name:domain whose elements are references
5701: to arrays containing various chunks of information
5702: about the student. (See loncoursedata for more info).
5703:
5704: Returns
5705: %idmap - the constructed hash
5706:
5707: =cut
5708:
5709: sub username_to_idmap {
5710: my ($classlist)= @_;
5711: my %idmap;
5712: foreach my $student (keys(%$classlist)) {
5713: $idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
5714: $student;
5715: }
5716: return %idmap;
5717: }
5718:
5719: =pod
5720:
5721: =item scantron_fixup_scanline
5722:
5723: Process a requested correction to a scanline.
5724:
5725: Arguments:
5726: $scantron_config - hash from &get_scantron_config()
5727: $scan_data - hash of correction information
5728: (see &scantron_getfile())
5729: $line - existing scanline
5730: $whichline - line number of the passed in scanline
5731: $field - type of change to process
5732: (either
5733: 'ID' -> correct the student/employee ID
5734: 'CODE' -> correct the CODE
5735: 'answer' -> fixup the submitted answers)
5736:
5737: $args - hash of additional info,
5738: - 'ID'
5739: 'newid' -> studentID to use in replacement
5740: of existing one
5741: - 'CODE'
5742: 'CODE_ignore_dup' - set to true if duplicates
5743: should be ignored.
5744: 'CODE' - is new code or 'use_unfound'
5745: if the existing unfound code should
5746: be used as is
5747: - 'answer'
5748: 'response' - new answer or 'none' if blank
5749: 'question' - the bubble line to change
5750: 'questionnum' - the question identifier,
5751: may include subquestion.
5752:
5753: Returns:
5754: $line - the modified scanline
5755:
5756: Side effects:
5757: $scan_data - may be updated
5758:
5759: =cut
5760:
5761:
5762: sub scantron_fixup_scanline {
5763: my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
5764: if ($field eq 'ID') {
5765: if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
5766: return ($line,1,'New value too large');
5767: }
5768: if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
5769: $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
5770: $args->{'newid'});
5771: }
5772: substr($line,$$scantron_config{'IDstart'}-1,
5773: $$scantron_config{'IDlength'})=$args->{'newid'};
5774: if ($args->{'newid'}=~/^\s*$/) {
5775: &scan_data($scan_data,"$whichline.user",
5776: $args->{'username'}.':'.$args->{'domain'});
5777: }
5778: } elsif ($field eq 'CODE') {
5779: if ($args->{'CODE_ignore_dup'}) {
5780: &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
5781: }
5782: &scan_data($scan_data,"$whichline.useCODE",'1');
5783: if ($args->{'CODE'} ne 'use_unfound') {
5784: if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
5785: return ($line,1,'New CODE value too large');
5786: }
5787: if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
5788: $args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
5789: }
5790: substr($line,$$scantron_config{'CODEstart'}-1,
5791: $$scantron_config{'CODElength'})=$args->{'CODE'};
5792: }
5793: } elsif ($field eq 'answer') {
5794: my $length=$scantron_config->{'Qlength'};
5795: my $off=$scantron_config->{'Qoff'};
5796: my $on=$scantron_config->{'Qon'};
5797: my $answer=${off}x$length;
5798: if ($args->{'response'} eq 'none') {
5799: &scan_data($scan_data,
5800: "$whichline.no_bubble.".$args->{'questionnum'},'1');
5801: } else {
5802: if ($on eq 'letter') {
5803: my @alphabet=('A'..'Z');
5804: $answer=$alphabet[$args->{'response'}];
5805: } elsif ($on eq 'number') {
5806: $answer=$args->{'response'}+1;
5807: if ($answer == 10) { $answer = '0'; }
5808: } else {
5809: substr($answer,$args->{'response'},1)=$on;
5810: }
5811: &scan_data($scan_data,
5812: "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
5813: }
5814: my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
5815: substr($line,$where-1,$length)=$answer;
5816: }
5817: return $line;
5818: }
5819:
5820: =pod
5821:
5822: =item scan_data
5823:
5824: Edit or look up an item in the scan_data hash.
5825:
5826: Arguments:
5827: $scan_data - The hash (see scantron_getfile)
5828: $key - shorthand of the key to edit (actual key is
5829: scantronfilename_key).
5830: $data - New value of the hash entry.
5831: $delete - If true, the entry is removed from the hash.
5832:
5833: Returns:
5834: The new value of the hash table field (undefined if deleted).
5835:
5836: =cut
5837:
5838:
5839: sub scan_data {
5840: my ($scan_data,$key,$value,$delete)=@_;
5841: my $filename=$env{'form.scantron_selectfile'};
5842: if (defined($value)) {
5843: $scan_data->{$filename.'_'.$key} = $value;
5844: }
5845: if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
5846: return $scan_data->{$filename.'_'.$key};
5847: }
5848:
5849: # ----- These first few routines are general use routines.----
5850:
5851: # Return the number of occurences of a pattern in a string.
5852:
5853: sub occurence_count {
5854: my ($string, $pattern) = @_;
5855:
5856: my @matches = ($string =~ /$pattern/g);
5857:
5858: return scalar(@matches);
5859: }
5860:
5861:
5862: # Take a string known to have digits and convert all the
5863: # digits into letters in the range J,A..I.
5864:
5865: sub digits_to_letters {
5866: my ($input) = @_;
5867:
5868: my @alphabet = ('J', 'A'..'I');
5869:
5870: my @input = split(//, $input);
5871: my $output ='';
5872: for (my $i = 0; $i < scalar(@input); $i++) {
5873: if ($input[$i] =~ /\d/) {
5874: $output .= $alphabet[$input[$i]];
5875: } else {
5876: $output .= $input[$i];
5877: }
5878: }
5879: return $output;
5880: }
5881:
5882: =pod
5883:
5884: =item scantron_parse_scanline
5885:
5886: Decodes a scanline from the selected bubblesheet file
5887:
5888: Arguments:
5889: line - The text of the bubblesheet file line to process
5890: whichline - Line number
5891: scantron_config - Hash describing the format of the bubblesheet lines.
5892: scan_data - Hash of extra information about the scanline
5893: (see scantron_getfile for more information)
5894: just_header - True if should not process question answers but only
5895: the stuff to the left of the answers.
5896: randomorder - True if randomorder in use
5897: randompick - True if randompick in use
5898: sequence - Exam folder URL
5899: master_seq - Ref to array containing symbs in exam folder
5900: symb_to_resource - Ref to hash of symbs for resources in exam folder
5901: (corresponding values are resource objects)
5902: partids_by_symb - Ref to hash of symb -> array ref of partIDs
5903: orderedforcode - Ref to hash of arrays. keys are CODEs and values
5904: are refs to an array of resource objects, ordered
5905: according to order used for CODE, when randomorder
5906: and or randompick are in use.
5907: respnumlookup - Ref to hash mapping question numbers in bubble lines
5908: for current line to question number used for same question
5909: in "Master Sequence" (as seen by Course Coordinator).
5910: startline - Ref to hash where key is question number (0 is first)
5911: and value is number of first bubble line for current
5912: student or code-based randompick and/or randomorder.
5913: totalref - Ref of scalar used to score total number of bubble
5914: lines needed for responses in a scan line (used when
5915: randompick in use.
5916:
5917: Returns:
5918: Hash containing the result of parsing the scanline
5919:
5920: Keys are all proceeded by the string 'scantron.'
5921:
5922: CODE - the CODE in use for this scanline
5923: useCODE - 1 if the CODE is invalid but it usage has been forced
5924: by the operator
5925: CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
5926: CODEs were selected, but the usage has been
5927: forced by the operator
5928: ID - student/employee ID
5929: PaperID - if used, the ID number printed on the sheet when the
5930: paper was scanned
5931: FirstName - first name from the sheet
5932: LastName - last name from the sheet
5933:
5934: if just_header was not true these key may also exist
5935:
5936: missingerror - a list of bubble ranges that are considered to be answers
5937: to a single question that don't have any bubbles filled in.
5938: Of the form questionnumber:firstbubblenumber:count.
5939: doubleerror - a list of bubble ranges that are considered to be answers
5940: to a single question that have more than one bubble filled in.
5941: Of the form questionnumber::firstbubblenumber:count
5942:
5943: In the above, count is the number of bubble responses in the
5944: input line needed to represent the possible answers to the question.
5945: e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
5946: per line would have count = 2.
5947:
5948: maxquest - the number of the last bubble line that was parsed
5949:
5950: (<number> starts at 1)
5951: <number>.answer - zero or more letters representing the selected
5952: letters from the scanline for the bubble line
5953: <number>.
5954: if blank there was either no bubble or there where
5955: multiple bubbles, (consult the keys missingerror and
5956: doubleerror if this is an error condition)
5957:
5958: =cut
5959:
5960: sub scantron_parse_scanline {
5961: my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
5962: $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
5963: $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
5964:
5965: my %record;
5966: my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
5967: if (!($$scantron_config{'CODElocation'} eq 0 ||
5968: $$scantron_config{'CODElocation'} eq 'none')) {
5969: if ($$scantron_config{'CODElocation'} < 0 ||
5970: $$scantron_config{'CODElocation'} eq 'letter' ||
5971: $$scantron_config{'CODElocation'} eq 'number') {
5972: $record{'scantron.CODE'}=substr($data,
5973: $$scantron_config{'CODEstart'}-1,
5974: $$scantron_config{'CODElength'});
5975: if (&scan_data($scan_data,"$whichline.useCODE")) {
5976: $record{'scantron.useCODE'}=1;
5977: }
5978: if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
5979: $record{'scantron.CODE_ignore_dup'}=1;
5980: }
5981: } else {
5982: #FIXME interpret first N questions
5983: }
5984: }
5985: $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
5986: $$scantron_config{'IDlength'});
5987: $record{'scantron.PaperID'}=
5988: substr($data,$$scantron_config{'PaperID'}-1,
5989: $$scantron_config{'PaperIDlength'});
5990: $record{'scantron.FirstName'}=
5991: substr($data,$$scantron_config{'FirstName'}-1,
5992: $$scantron_config{'FirstNamelength'});
5993: $record{'scantron.LastName'}=
5994: substr($data,$$scantron_config{'LastName'}-1,
5995: $$scantron_config{'LastNamelength'});
5996: if ($just_header) { return \%record; }
5997:
5998: my @alphabet=('A'..'Z');
5999: my $questnum=0;
6000: my $ansnum =1; # Multiple 'answer lines'/question.
6001:
6002: my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
6003: if ($randompick || $randomorder) {
6004: my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
6005: $master_seq,$symb_to_resource,
6006: $partids_by_symb,$orderedforcode,
6007: $respnumlookup,$startline);
6008: if ($total) {
6009: $lastpos = $total*$$scantron_config{'Qlength'};
6010: }
6011: if (ref($totalref)) {
6012: $$totalref = $total;
6013: }
6014: }
6015: my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos); # Answers
6016: chomp($questions); # Get rid of any trailing \n.
6017: $questions =~ s/\r$//; # Get rid of trailing \r too (MAC or Win uploads).
6018: while (length($questions)) {
6019: my $answers_needed;
6020: if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
6021: $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
6022: } else {
6023: $answers_needed = $bubble_lines_per_response{$questnum};
6024: }
6025: my $answer_length = ($$scantron_config{'Qlength'} * $answers_needed)
6026: || 1;
6027: $questnum++;
6028: my $quest_id = $questnum;
6029: my $currentquest = substr($questions,0,$answer_length);
6030: $questions = substr($questions,$answer_length);
6031: if (length($currentquest) < $answer_length) { next; }
6032:
6033: my $subdivided;
6034: if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
6035: $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
6036: } else {
6037: $subdivided = $subdivided_bubble_lines{$questnum-1};
6038: }
6039: if ($subdivided =~ /,/) {
6040: my $subquestnum = 1;
6041: my $subquestions = $currentquest;
6042: my @subanswers_needed = split(/,/,$subdivided);
6043: foreach my $subans (@subanswers_needed) {
6044: my $subans_length =
6045: ($$scantron_config{'Qlength'} * $subans) || 1;
6046: my $currsubquest = substr($subquestions,0,$subans_length);
6047: $subquestions = substr($subquestions,$subans_length);
6048: $quest_id = "$questnum.$subquestnum";
6049: if (($$scantron_config{'Qon'} eq 'letter') ||
6050: ($$scantron_config{'Qon'} eq 'number')) {
6051: $ansnum = &scantron_validator_lettnum($ansnum,
6052: $questnum,$quest_id,$subans,$currsubquest,$whichline,
6053: \@alphabet,\%record,$scantron_config,$scan_data,
6054: $randomorder,$randompick,$respnumlookup);
6055: } else {
6056: $ansnum = &scantron_validator_positional($ansnum,
6057: $questnum,$quest_id,$subans,$currsubquest,$whichline,
6058: \@alphabet,\%record,$scantron_config,$scan_data,
6059: $randomorder,$randompick,$respnumlookup);
6060: }
6061: $subquestnum ++;
6062: }
6063: } else {
6064: if (($$scantron_config{'Qon'} eq 'letter') ||
6065: ($$scantron_config{'Qon'} eq 'number')) {
6066: $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
6067: $quest_id,$answers_needed,$currentquest,$whichline,
6068: \@alphabet,\%record,$scantron_config,$scan_data,
6069: $randomorder,$randompick,$respnumlookup);
6070: } else {
6071: $ansnum = &scantron_validator_positional($ansnum,$questnum,
6072: $quest_id,$answers_needed,$currentquest,$whichline,
6073: \@alphabet,\%record,$scantron_config,$scan_data,
6074: $randomorder,$randompick,$respnumlookup);
6075: }
6076: }
6077: }
6078: $record{'scantron.maxquest'}=$questnum;
6079: return \%record;
6080: }
6081:
6082: sub get_master_seq {
6083: my ($resources,$master_seq,$symb_to_resource) = @_;
6084: return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') &&
6085: (ref($symb_to_resource) eq 'HASH'));
6086: my $resource_error;
6087: foreach my $resource (@{$resources}) {
6088: my $ressymb;
6089: if (ref($resource)) {
6090: $ressymb = $resource->symb();
6091: push(@{$master_seq},$ressymb);
6092: $symb_to_resource->{$ressymb} = $resource;
6093: } else {
6094: $resource_error = 1;
6095: last;
6096: }
6097: }
6098: return $resource_error;
6099: }
6100:
6101: sub get_respnum_lookups {
6102: my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
6103: $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
6104: return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
6105: (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
6106: (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
6107: (ref($startline) eq 'HASH'));
6108: my ($user,$scancode);
6109: if ((exists($record->{'scantron.CODE'})) &&
6110: (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
6111: $scancode = $record->{'scantron.CODE'};
6112: } else {
6113: $user = &scantron_find_student($record,$scan_data,$idmap,$line);
6114: }
6115: my @mapresources =
6116: &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
6117: $orderedforcode);
6118: my $total = 0;
6119: my $count = 0;
6120: foreach my $resource (@mapresources) {
6121: my $id = $resource->id();
6122: my $symb = $resource->symb();
6123: if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
6124: foreach my $partid (@{$partids_by_symb->{$symb}}) {
6125: my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
6126: if ($respnum ne '') {
6127: $respnumlookup->{$count} = $respnum;
6128: $startline->{$count} = $total;
6129: $total += $bubble_lines_per_response{$respnum};
6130: $count ++;
6131: }
6132: }
6133: }
6134: }
6135: return $total;
6136: }
6137:
6138: sub scantron_validator_lettnum {
6139: my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
6140: $alphabet,$record,$scantron_config,$scan_data,$randomorder,
6141: $randompick,$respnumlookup) = @_;
6142:
6143: # Qon 'letter' implies for each slot in currquest we have:
6144: # ? or * for doubles, a letter in A-Z for a bubble, and
6145: # about anything else (esp. a value of Qoff) for missing
6146: # bubbles.
6147: #
6148: # Qon 'number' implies each slot gives a digit that indexes the
6149: # bubbles filled, or Qoff, or a non-number for unbubbled lines,
6150: # and * or ? for double bubbles on a single line.
6151: #
6152:
6153: my $matchon;
6154: if ($$scantron_config{'Qon'} eq 'letter') {
6155: $matchon = '[A-Z]';
6156: } elsif ($$scantron_config{'Qon'} eq 'number') {
6157: $matchon = '\d';
6158: }
6159: my $occurrences = 0;
6160: my $responsenum = $questnum-1;
6161: if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
6162: $responsenum = $respnumlookup->{$questnum-1}
6163: }
6164: if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
6165: ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
6166: ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
6167: ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
6168: ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
6169: ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
6170: my @singlelines = split('',$currquest);
6171: foreach my $entry (@singlelines) {
6172: $occurrences = &occurence_count($entry,$matchon);
6173: if ($occurrences > 1) {
6174: last;
6175: }
6176: }
6177: } else {
6178: $occurrences = &occurence_count($currquest,$matchon);
6179: }
6180: if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
6181: push(@{$record->{'scantron.doubleerror'}},$quest_id);
6182: for (my $ans=0; $ans<$answers_needed; $ans++) {
6183: my $bubble = substr($currquest,$ans,1);
6184: if ($bubble =~ /$matchon/ ) {
6185: if ($$scantron_config{'Qon'} eq 'number') {
6186: if ($bubble == 0) {
6187: $bubble = 10;
6188: }
6189: $record->{"scantron.$ansnum.answer"} =
6190: $alphabet->[$bubble-1];
6191: } else {
6192: $record->{"scantron.$ansnum.answer"} = $bubble;
6193: }
6194: } else {
6195: $record->{"scantron.$ansnum.answer"}='';
6196: }
6197: $ansnum++;
6198: }
6199: } elsif (!defined($currquest)
6200: || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
6201: || (&occurence_count($currquest,$matchon) == 0)) {
6202: for (my $ans=0; $ans<$answers_needed; $ans++ ) {
6203: $record->{"scantron.$ansnum.answer"}='';
6204: $ansnum++;
6205: }
6206: if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
6207: push(@{$record->{'scantron.missingerror'}},$quest_id);
6208: }
6209: } else {
6210: if ($$scantron_config{'Qon'} eq 'number') {
6211: $currquest = &digits_to_letters($currquest);
6212: }
6213: for (my $ans=0; $ans<$answers_needed; $ans++) {
6214: my $bubble = substr($currquest,$ans,1);
6215: $record->{"scantron.$ansnum.answer"} = $bubble;
6216: $ansnum++;
6217: }
6218: }
6219: return $ansnum;
6220: }
6221:
6222: sub scantron_validator_positional {
6223: my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
6224: $whichline,$alphabet,$record,$scantron_config,$scan_data,
6225: $randomorder,$randompick,$respnumlookup) = @_;
6226:
6227: # Otherwise there's a positional notation;
6228: # each bubble line requires Qlength items, and there are filled in
6229: # bubbles for each case where there 'Qon' characters.
6230: #
6231:
6232: my @array=split($$scantron_config{'Qon'},$currquest,-1);
6233:
6234: # If the split only gives us one element.. the full length of the
6235: # answer string, no bubbles are filled in:
6236:
6237: if ($answers_needed eq '') {
6238: return;
6239: }
6240:
6241: if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
6242: for (my $ans=0; $ans<$answers_needed; $ans++ ) {
6243: $record->{"scantron.$ansnum.answer"}='';
6244: $ansnum++;
6245: }
6246: if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
6247: push(@{$record->{"scantron.missingerror"}},$quest_id);
6248: }
6249: } elsif (scalar(@array) == 2) {
6250: my $location = length($array[0]);
6251: my $line_num = int($location / $$scantron_config{'Qlength'});
6252: my $bubble = $alphabet->[$location % $$scantron_config{'Qlength'}];
6253: for (my $ans=0; $ans<$answers_needed; $ans++) {
6254: if ($ans eq $line_num) {
6255: $record->{"scantron.$ansnum.answer"} = $bubble;
6256: } else {
6257: $record->{"scantron.$ansnum.answer"} = ' ';
6258: }
6259: $ansnum++;
6260: }
6261: } else {
6262: # If there's more than one instance of a bubble character
6263: # That's a double bubble; with positional notation we can
6264: # record all the bubbles filled in as well as the
6265: # fact this response consists of multiple bubbles.
6266: #
6267: my $responsenum = $questnum-1;
6268: if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
6269: $responsenum = $respnumlookup->{$questnum-1}
6270: }
6271: if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
6272: ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
6273: ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
6274: ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
6275: ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
6276: ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
6277: my $doubleerror = 0;
6278: while (($currquest >= $$scantron_config{'Qlength'}) &&
6279: (!$doubleerror)) {
6280: my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
6281: $currquest = substr($currquest,$$scantron_config{'Qlength'});
6282: my @currarray = split($$scantron_config{'Qon'},$currline,-1);
6283: if (length(@currarray) > 2) {
6284: $doubleerror = 1;
6285: }
6286: }
6287: if ($doubleerror) {
6288: push(@{$record->{'scantron.doubleerror'}},$quest_id);
6289: }
6290: } else {
6291: push(@{$record->{'scantron.doubleerror'}},$quest_id);
6292: }
6293: my $item = $ansnum;
6294: for (my $ans=0; $ans<$answers_needed; $ans++) {
6295: $record->{"scantron.$item.answer"} = '';
6296: $item ++;
6297: }
6298:
6299: my @ans=@array;
6300: my $i=0;
6301: my $increment = 0;
6302: while ($#ans) {
6303: $i+=length($ans[0]) + $increment;
6304: my $line = int($i/$$scantron_config{'Qlength'} + $ansnum);
6305: my $bubble = $i%$$scantron_config{'Qlength'};
6306: $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
6307: shift(@ans);
6308: $increment = 1;
6309: }
6310: $ansnum += $answers_needed;
6311: }
6312: return $ansnum;
6313: }
6314:
6315: =pod
6316:
6317: =item scantron_add_delay
6318:
6319: Adds an error message that occurred during the grading phase to a
6320: queue of messages to be shown after grading pass is complete
6321:
6322: Arguments:
6323: $delayqueue - arrary ref of hash ref of error messages
6324: $scanline - the scanline that caused the error
6325: $errormesage - the error message
6326: $errorcode - a numeric code for the error
6327:
6328: Side Effects:
6329: updates the $delayqueue to have a new hash ref of the error
6330:
6331: =cut
6332:
6333: sub scantron_add_delay {
6334: my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
6335: push(@$delayqueue,
6336: {'line' => $scanline, 'emsg' => $errormessage,
6337: 'ecode' => $errorcode }
6338: );
6339: }
6340:
6341: =pod
6342:
6343: =item scantron_find_student
6344:
6345: Finds the username for the current scanline
6346:
6347: Arguments:
6348: $scantron_record - hash result from scantron_parse_scanline
6349: $scan_data - hash of correction information
6350: (see &scantron_getfile() form more information)
6351: $idmap - hash from &username_to_idmap()
6352: $line - number of current scanline
6353:
6354: Returns:
6355: Either 'username:domain' or undef if unknown
6356:
6357: =cut
6358:
6359: sub scantron_find_student {
6360: my ($scantron_record,$scan_data,$idmap,$line)=@_;
6361: my $scanID=$$scantron_record{'scantron.ID'};
6362: if ($scanID =~ /^\s*$/) {
6363: return &scan_data($scan_data,"$line.user");
6364: }
6365: foreach my $id (keys(%$idmap)) {
6366: if (lc($id) eq lc($scanID)) {
6367: return $$idmap{$id};
6368: }
6369: }
6370: return undef;
6371: }
6372:
6373: =pod
6374:
6375: =item scantron_filter
6376:
6377: Filter sub for lonnavmaps, filters out hidden resources if ignore
6378: hidden resources was selected
6379:
6380: =cut
6381:
6382: sub scantron_filter {
6383: my ($curres)=@_;
6384:
6385: if (ref($curres) && $curres->is_problem()) {
6386: # if the user has asked to not have either hidden
6387: # or 'randomout' controlled resources to be graded
6388: # don't include them
6389: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
6390: && $curres->randomout) {
6391: return 0;
6392: }
6393: return 1;
6394: }
6395: return 0;
6396: }
6397:
6398: =pod
6399:
6400: =item scantron_process_corrections
6401:
6402: Gets correction information out of submitted form data and corrects
6403: the scanline
6404:
6405: =cut
6406:
6407: sub scantron_process_corrections {
6408: my ($r) = @_;
6409: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6410: my ($scanlines,$scan_data)=&scantron_getfile();
6411: my $classlist=&Apache::loncoursedata::get_classlist();
6412: my $which=$env{'form.scantron_line'};
6413: my $line=&scantron_get_line($scanlines,$scan_data,$which);
6414: my ($skip,$err,$errmsg);
6415: if ($env{'form.scantron_skip_record'}) {
6416: $skip=1;
6417: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
6418: my $newstudent=$env{'form.scantron_username'}.':'.
6419: $env{'form.scantron_domain'};
6420: my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
6421: ($line,$err,$errmsg)=
6422: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
6423: 'ID',{'newid'=>$newid,
6424: 'username'=>$env{'form.scantron_username'},
6425: 'domain'=>$env{'form.scantron_domain'}});
6426: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
6427: my $resolution=$env{'form.scantron_CODE_resolution'};
6428: my $newCODE;
6429: my %args;
6430: if ($resolution eq 'use_unfound') {
6431: $newCODE='use_unfound';
6432: } elsif ($resolution eq 'use_found') {
6433: $newCODE=$env{'form.scantron_CODE_selectedvalue'};
6434: } elsif ($resolution eq 'use_typed') {
6435: $newCODE=$env{'form.scantron_CODE_newvalue'};
6436: } elsif ($resolution =~ /^use_closest_(\d+)/) {
6437: $newCODE=$env{"form.scantron_CODE_closest_$1"};
6438: }
6439: if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
6440: $args{'CODE_ignore_dup'}=1;
6441: }
6442: $args{'CODE'}=$newCODE;
6443: ($line,$err,$errmsg)=
6444: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
6445: 'CODE',\%args);
6446: } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
6447: foreach my $question (split(',',$env{'form.scantron_questions'})) {
6448: ($line,$err,$errmsg)=
6449: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
6450: $which,'answer',
6451: { 'question'=>$question,
6452: 'response'=>$env{"form.scantron_correct_Q_$question"},
6453: 'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
6454: if ($err) { last; }
6455: }
6456: }
6457: if ($err) {
6458: $r->print(
6459: '<p class="LC_error">'
6460: .&mt('Unable to accept last correction, an error occurred: [_1]',
6461: $errmsg)
6462: .'</p>');
6463: } else {
6464: &scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
6465: &scantron_putfile($scanlines,$scan_data);
6466: }
6467: }
6468:
6469: =pod
6470:
6471: =item reset_skipping_status
6472:
6473: Forgets the current set of remember skipped scanlines (and thus
6474: reverts back to considering all lines in the
6475: scantron_skipped_<filename> file)
6476:
6477: =cut
6478:
6479: sub reset_skipping_status {
6480: my ($scanlines,$scan_data)=&scantron_getfile();
6481: &scan_data($scan_data,'remember_skipping',undef,1);
6482: &scantron_putfile(undef,$scan_data);
6483: }
6484:
6485: =pod
6486:
6487: =item start_skipping
6488:
6489: Marks a scanline to be skipped.
6490:
6491: =cut
6492:
6493: sub start_skipping {
6494: my ($scan_data,$i)=@_;
6495: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
6496: if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
6497: $remembered{$i}=2;
6498: } else {
6499: $remembered{$i}=1;
6500: }
6501: &scan_data($scan_data,'remember_skipping',join(':',%remembered));
6502: }
6503:
6504: =pod
6505:
6506: =item should_be_skipped
6507:
6508: Checks whether a scanline should be skipped.
6509:
6510: =cut
6511:
6512: sub should_be_skipped {
6513: my ($scanlines,$scan_data,$i)=@_;
6514: if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
6515: # not redoing old skips
6516: if ($scanlines->{'skipped'}[$i]) { return 1; }
6517: return 0;
6518: }
6519: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
6520:
6521: if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
6522: return 0;
6523: }
6524: return 1;
6525: }
6526:
6527: =pod
6528:
6529: =item remember_current_skipped
6530:
6531: Discovers what scanlines are in the scantron_skipped_<filename>
6532: file and remembers them into scan_data for later use.
6533:
6534: =cut
6535:
6536: sub remember_current_skipped {
6537: my ($scanlines,$scan_data)=&scantron_getfile();
6538: my %to_remember;
6539: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6540: if ($scanlines->{'skipped'}[$i]) {
6541: $to_remember{$i}=1;
6542: }
6543: }
6544:
6545: &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
6546: &scantron_putfile(undef,$scan_data);
6547: }
6548:
6549: =pod
6550:
6551: =item check_for_error
6552:
6553: Checks if there was an error when attempting to remove a specific
6554: scantron_.. bubblesheet data file. Prints out an error if
6555: something went wrong.
6556:
6557: =cut
6558:
6559: sub check_for_error {
6560: my ($r,$result)=@_;
6561: if ($result ne 'ok' && $result ne 'not_found' ) {
6562: $r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
6563: }
6564: }
6565:
6566: =pod
6567:
6568: =item scantron_warning_screen
6569:
6570: Interstitial screen to make sure the operator has selected the
6571: correct options before we start the validation phase.
6572:
6573: =cut
6574:
6575: sub scantron_warning_screen {
6576: my ($button_text,$symb)=@_;
6577: my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
6578: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6579: my $CODElist;
6580: if ($scantron_config{'CODElocation'} &&
6581: $scantron_config{'CODEstart'} &&
6582: $scantron_config{'CODElength'}) {
6583: $CODElist=$env{'form.scantron_CODElist'};
6584: if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
6585: $CODElist=
6586: '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
6587: $env{'form.scantron_CODElist'}.'</tt></td></tr>';
6588: }
6589: my $lastbubblepoints;
6590: if ($env{'form.scantron_lastbubblepoints'} ne '') {
6591: $lastbubblepoints =
6592: '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
6593: $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
6594: }
6595: return ('
6596: <p>
6597: <span class="LC_warning">
6598: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
6599: </p>
6600: <table>
6601: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
6602: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
6603: '.$CODElist.$lastbubblepoints.'
6604: </table>
6605: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
6606: '.&mt('If something is incorrect, please return to [_1]Grade/Manage/Review Bubblesheets[_2] to start over.','<a href="/adm/grades?symb='.$symb.'&command=scantron_selectphase" class="LC_info">','</a>').'</p>
6607:
6608: <br />
6609: ');
6610: }
6611:
6612: =pod
6613:
6614: =item scantron_do_warning
6615:
6616: Check if the operator has picked something for all required
6617: fields. Error out if something is missing.
6618:
6619: =cut
6620:
6621: sub scantron_do_warning {
6622: my ($r,$symb)=@_;
6623: if (!$symb) {return '';}
6624: my $default_form_data=&defaultFormData($symb);
6625: $r->print(&scantron_form_start().$default_form_data);
6626: if ( $env{'form.selectpage'} eq '' ||
6627: $env{'form.scantron_selectfile'} eq '' ||
6628: $env{'form.scantron_format'} eq '' ) {
6629: $r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
6630: if ( $env{'form.selectpage'} eq '') {
6631: $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
6632: }
6633: if ( $env{'form.scantron_selectfile'} eq '') {
6634: $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
6635: }
6636: if ( $env{'form.scantron_format'} eq '') {
6637: $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
6638: }
6639: } else {
6640: my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
6641: my $bubbledbyhand=&hand_bubble_option();
6642: $r->print('
6643: '.$warning.$bubbledbyhand.'
6644: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
6645: <input type="hidden" name="command" value="scantron_validate" />
6646: ');
6647: }
6648: $r->print("</form><br />");
6649: return '';
6650: }
6651:
6652: =pod
6653:
6654: =item scantron_form_start
6655:
6656: html hidden input for remembering all selected grading options
6657:
6658: =cut
6659:
6660: sub scantron_form_start {
6661: my ($max_bubble)=@_;
6662: my $result= <<SCANTRONFORM;
6663: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
6664: <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
6665: <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
6666: <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
6667: <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
6668: <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
6669: <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
6670: <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
6671: <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
6672: <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
6673: SCANTRONFORM
6674:
6675: my $line = 0;
6676: while (defined($env{"form.scantron.bubblelines.$line"})) {
6677: my $chunk =
6678: '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
6679: $chunk .=
6680: '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
6681: $chunk .=
6682: '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
6683: $chunk .=
6684: '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
6685: $chunk .=
6686: '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
6687: $result .= $chunk;
6688: $line++;
6689: }
6690: return $result;
6691: }
6692:
6693: =pod
6694:
6695: =item scantron_validate_file
6696:
6697: Dispatch routine for doing validation of a bubblesheet data file.
6698:
6699: Also processes any necessary information resets that need to
6700: occur before validation begins (ignore previous corrections,
6701: restarting the skipped records processing)
6702:
6703: =cut
6704:
6705: sub scantron_validate_file {
6706: my ($r,$symb) = @_;
6707: if (!$symb) {return '';}
6708: my $default_form_data=&defaultFormData($symb);
6709:
6710: # do the detection of only doing skipped records first before we delete
6711: # them when doing the corrections reset
6712: if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
6713: &reset_skipping_status();
6714: }
6715: if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
6716: &remember_current_skipped();
6717: $env{'form.scantron_options_redo'}='redo_skipped_ready';
6718: }
6719:
6720: if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
6721: &check_for_error($r,&scantron_remove_file('corrected'));
6722: &check_for_error($r,&scantron_remove_file('skipped'));
6723: &check_for_error($r,&scantron_remove_scan_data());
6724: $env{'form.scantron_options_ignore'}='done';
6725: }
6726:
6727: if ($env{'form.scantron_corrections'}) {
6728: &scantron_process_corrections($r);
6729: }
6730: $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
6731: #get the student pick code ready
6732: $r->print(&Apache::loncommon::studentbrowser_javascript());
6733: my $nav_error;
6734: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6735: my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
6736: if ($nav_error) {
6737: $r->print(&navmap_errormsg());
6738: return '';
6739: }
6740: my $result=&scantron_form_start($max_bubble).$default_form_data;
6741: if ($env{'form.scantron_lastbubblepoints'} ne '') {
6742: $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
6743: }
6744: $r->print($result);
6745:
6746: my @validate_phases=( 'sequence',
6747: 'ID',
6748: 'CODE',
6749: 'doublebubble',
6750: 'missingbubbles');
6751: if (!$env{'form.validatepass'}) {
6752: $env{'form.validatepass'} = 0;
6753: }
6754: my $currentphase=$env{'form.validatepass'};
6755:
6756:
6757: my $stop=0;
6758: while (!$stop && $currentphase < scalar(@validate_phases)) {
6759: $r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
6760: $r->rflush();
6761:
6762: my $which="scantron_validate_".$validate_phases[$currentphase];
6763: {
6764: no strict 'refs';
6765: ($stop,$currentphase)=&$which($r,$currentphase);
6766: }
6767: }
6768: if (!$stop) {
6769: my $warning=&scantron_warning_screen('Start Grading',$symb);
6770: $r->print(&mt('Validation process complete.').'<br />'.
6771: $warning.
6772: &mt('Perform verification for each student after storage of submissions?').
6773: ' <span class="LC_nobreak"><label>'.
6774: '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
6775: (' 'x3).'<label>'.
6776: '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
6777: '</label></span><br />'.
6778: &mt('Grading will take longer if you use verification.').'<br />'.
6779: &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','»').'<br /><br />'.
6780: '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
6781: '<input type="hidden" name="command" value="scantron_process" />'."\n");
6782: } else {
6783: $r->print('<input type="hidden" name="command" value="scantron_validate" />');
6784: $r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
6785: }
6786: if ($stop) {
6787: if ($validate_phases[$currentphase] eq 'sequence') {
6788: $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' → " />');
6789: $r->print(' '.&mt('this error').' <br />');
6790:
6791: $r->print('<p>'.&mt('Or return to [_1]Grade/Manage/Review Bubblesheets[_2] to start over.','<a href="/adm/grades?symb='.$symb.'&command=scantron_selectphase" class="LC_info">','</a>').'</p>');
6792: } else {
6793: if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
6794: $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' →" onclick="javascript:verify_bubble_radio(this.form)" />');
6795: } else {
6796: $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' →" />');
6797: }
6798: $r->print(' '.&mt('using corrected info').' <br />');
6799: $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
6800: $r->print(" ".&mt("this scanline saving it for later."));
6801: }
6802: }
6803: $r->print(" </form><br />");
6804: return '';
6805: }
6806:
6807:
6808: =pod
6809:
6810: =item scantron_remove_file
6811:
6812: Removes the requested bubblesheet data file, makes sure that
6813: scantron_original_<filename> is never removed
6814:
6815:
6816: =cut
6817:
6818: sub scantron_remove_file {
6819: my ($which)=@_;
6820: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6821: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6822: my $file='scantron_';
6823: if ($which eq 'corrected' || $which eq 'skipped') {
6824: $file.=$which.'_';
6825: } else {
6826: return 'refused';
6827: }
6828: $file.=$env{'form.scantron_selectfile'};
6829: return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
6830: }
6831:
6832:
6833: =pod
6834:
6835: =item scantron_remove_scan_data
6836:
6837: Removes all scan_data correction for the requested bubblesheet
6838: data file. (In the case that both the are doing skipped records we need
6839: to remember the old skipped lines for the time being so that element
6840: persists for a while.)
6841:
6842: =cut
6843:
6844: sub scantron_remove_scan_data {
6845: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6846: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6847: my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
6848: my @todelete;
6849: my $filename=$env{'form.scantron_selectfile'};
6850: foreach my $key (@keys) {
6851: if ($key=~/^\Q$filename\E_/) {
6852: if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
6853: $key=~/remember_skipping/) {
6854: next;
6855: }
6856: push(@todelete,$key);
6857: }
6858: }
6859: my $result;
6860: if (@todelete) {
6861: $result = &Apache::lonnet::del('nohist_scantrondata',
6862: \@todelete,$cdom,$cname);
6863: } else {
6864: $result = 'ok';
6865: }
6866: return $result;
6867: }
6868:
6869:
6870: =pod
6871:
6872: =item scantron_getfile
6873:
6874: Fetches the requested bubblesheet data file (all 3 versions), and
6875: the scan_data hash
6876:
6877: Arguments:
6878: None
6879:
6880: Returns:
6881: 2 hash references
6882:
6883: - first one has
6884: orig -
6885: corrected -
6886: skipped - each of which points to an array ref of the specified
6887: file broken up into individual lines
6888: count - number of scanlines
6889:
6890: - second is the scan_data hash possible keys are
6891: ($number refers to scanline numbered $number and thus the key affects
6892: only that scanline
6893: $bubline refers to the specific bubble line element and the aspects
6894: refers to that specific bubble line element)
6895:
6896: $number.user - username:domain to use
6897: $number.CODE_ignore_dup
6898: - ignore the duplicate CODE error
6899: $number.useCODE
6900: - use the CODE in the scanline as is
6901: $number.no_bubble.$bubline
6902: - it is valid that there is no bubbled in bubble
6903: at $number $bubline
6904: remember_skipping
6905: - a frozen hash containing keys of $number and values
6906: of either
6907: 1 - we are on a 'do skipped records pass' and plan
6908: on processing this line
6909: 2 - we are on a 'do skipped records pass' and this
6910: scanline has been marked to skip yet again
6911:
6912: =cut
6913:
6914: sub scantron_getfile {
6915: #FIXME really would prefer a scantron directory
6916: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6917: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6918: my $lines;
6919: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
6920: 'scantron_orig_'.$env{'form.scantron_selectfile'});
6921: my %scanlines;
6922: $scanlines{'orig'}=[(split("\n",$lines,-1))];
6923: my $temp=$scanlines{'orig'};
6924: $scanlines{'count'}=$#$temp;
6925:
6926: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
6927: 'scantron_corrected_'.$env{'form.scantron_selectfile'});
6928: if ($lines eq '-1') {
6929: $scanlines{'corrected'}=[];
6930: } else {
6931: $scanlines{'corrected'}=[(split("\n",$lines,-1))];
6932: }
6933: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
6934: 'scantron_skipped_'.$env{'form.scantron_selectfile'});
6935: if ($lines eq '-1') {
6936: $scanlines{'skipped'}=[];
6937: } else {
6938: $scanlines{'skipped'}=[(split("\n",$lines,-1))];
6939: }
6940: my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
6941: if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
6942: my %scan_data = @tmp;
6943: return (\%scanlines,\%scan_data);
6944: }
6945:
6946: =pod
6947:
6948: =item lonnet_putfile
6949:
6950: Wrapper routine to call &Apache::lonnet::finishuserfileupload
6951:
6952: Arguments:
6953: $contents - data to store
6954: $filename - filename to store $contents into
6955:
6956: Returns:
6957: result value from &Apache::lonnet::finishuserfileupload
6958:
6959: =cut
6960:
6961: sub lonnet_putfile {
6962: my ($contents,$filename)=@_;
6963: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
6964: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6965: $env{'form.sillywaytopassafilearound'}=$contents;
6966: &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
6967:
6968: }
6969:
6970: =pod
6971:
6972: =item scantron_putfile
6973:
6974: Stores the current version of the bubblesheet data files, and the
6975: scan_data hash. (Does not modify the original version only the
6976: corrected and skipped versions.
6977:
6978: Arguments:
6979: $scanlines - hash ref that looks like the first return value from
6980: &scantron_getfile()
6981: $scan_data - hash ref that looks like the second return value from
6982: &scantron_getfile()
6983:
6984: =cut
6985:
6986: sub scantron_putfile {
6987: my ($scanlines,$scan_data) = @_;
6988: #FIXME really would prefer a scantron directory
6989: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6990: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6991: if ($scanlines) {
6992: my $prefix='scantron_';
6993: # no need to update orig, shouldn't change
6994: # &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
6995: # $env{'form.scantron_selectfile'});
6996: &lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
6997: $prefix.'corrected_'.
6998: $env{'form.scantron_selectfile'});
6999: &lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
7000: $prefix.'skipped_'.
7001: $env{'form.scantron_selectfile'});
7002: }
7003: &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
7004: }
7005:
7006: =pod
7007:
7008: =item scantron_get_line
7009:
7010: Returns the correct version of the scanline
7011:
7012: Arguments:
7013: $scanlines - hash ref that looks like the first return value from
7014: &scantron_getfile()
7015: $scan_data - hash ref that looks like the second return value from
7016: &scantron_getfile()
7017: $i - number of the requested line (starts at 0)
7018:
7019: Returns:
7020: A scanline, (either the original or the corrected one if it
7021: exists), or undef if the requested scanline should be
7022: skipped. (Either because it's an skipped scanline, or it's an
7023: unskipped scanline and we are not doing a 'do skipped scanlines'
7024: pass.
7025:
7026: =cut
7027:
7028: sub scantron_get_line {
7029: my ($scanlines,$scan_data,$i)=@_;
7030: if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
7031: #if ($scanlines->{'skipped'}[$i]) { return undef; }
7032: if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
7033: return $scanlines->{'orig'}[$i];
7034: }
7035:
7036: =pod
7037:
7038: =item scantron_todo_count
7039:
7040: Counts the number of scanlines that need processing.
7041:
7042: Arguments:
7043: $scanlines - hash ref that looks like the first return value from
7044: &scantron_getfile()
7045: $scan_data - hash ref that looks like the second return value from
7046: &scantron_getfile()
7047:
7048: Returns:
7049: $count - number of scanlines to process
7050:
7051: =cut
7052:
7053: sub get_todo_count {
7054: my ($scanlines,$scan_data)=@_;
7055: my $count=0;
7056: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7057: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7058: if ($line=~/^[\s\cz]*$/) { next; }
7059: $count++;
7060: }
7061: return $count;
7062: }
7063:
7064: =pod
7065:
7066: =item scantron_put_line
7067:
7068: Updates the 'corrected' or 'skipped' versions of the bubblesheet
7069: data file.
7070:
7071: Arguments:
7072: $scanlines - hash ref that looks like the first return value from
7073: &scantron_getfile()
7074: $scan_data - hash ref that looks like the second return value from
7075: &scantron_getfile()
7076: $i - line number to update
7077: $newline - contents of the updated scanline
7078: $skip - if true make the line for skipping and update the
7079: 'skipped' file
7080:
7081: =cut
7082:
7083: sub scantron_put_line {
7084: my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
7085: if ($skip) {
7086: $scanlines->{'skipped'}[$i]=$newline;
7087: &start_skipping($scan_data,$i);
7088: return;
7089: }
7090: $scanlines->{'corrected'}[$i]=$newline;
7091: }
7092:
7093: =pod
7094:
7095: =item scantron_clear_skip
7096:
7097: Remove a line from the 'skipped' file
7098:
7099: Arguments:
7100: $scanlines - hash ref that looks like the first return value from
7101: &scantron_getfile()
7102: $scan_data - hash ref that looks like the second return value from
7103: &scantron_getfile()
7104: $i - line number to update
7105:
7106: =cut
7107:
7108: sub scantron_clear_skip {
7109: my ($scanlines,$scan_data,$i)=@_;
7110: if (exists($scanlines->{'skipped'}[$i])) {
7111: undef($scanlines->{'skipped'}[$i]);
7112: return 1;
7113: }
7114: return 0;
7115: }
7116:
7117: =pod
7118:
7119: =item scantron_filter_not_exam
7120:
7121: Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
7122: filter out resources that are not marked as 'exam' mode
7123:
7124: =cut
7125:
7126: sub scantron_filter_not_exam {
7127: my ($curres)=@_;
7128:
7129: if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
7130: # if the user has asked to not have either hidden
7131: # or 'randomout' controlled resources to be graded
7132: # don't include them
7133: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
7134: && $curres->randomout) {
7135: return 0;
7136: }
7137: return 1;
7138: }
7139: return 0;
7140: }
7141:
7142: =pod
7143:
7144: =item scantron_validate_sequence
7145:
7146: Validates the selected sequence, checking for resource that are
7147: not set to exam mode.
7148:
7149: =cut
7150:
7151: sub scantron_validate_sequence {
7152: my ($r,$currentphase) = @_;
7153:
7154: my $navmap=Apache::lonnavmaps::navmap->new();
7155: unless (ref($navmap)) {
7156: $r->print(&navmap_errormsg());
7157: return (1,$currentphase);
7158: }
7159: my (undef,undef,$sequence)=
7160: &Apache::lonnet::decode_symb($env{'form.selectpage'});
7161:
7162: my $map=$navmap->getResourceByUrl($sequence);
7163:
7164: $r->print('<input type="hidden" name="validate_sequence_exam"
7165: value="ignore" />');
7166: if ($env{'form.validate_sequence_exam'} ne 'ignore') {
7167: my @resources=
7168: $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
7169: if (@resources) {
7170: $r->print(
7171: '<p class="LC_warning">'
7172: .&mt('Some resources in the sequence currently are not set to'
7173: .' bubblesheet exam mode. Grading these resources currently may not'
7174: .' work correctly.')
7175: .'</p>'
7176: );
7177: return (1,$currentphase);
7178: }
7179: }
7180:
7181: return (0,$currentphase+1);
7182: }
7183:
7184:
7185:
7186: sub scantron_validate_ID {
7187: my ($r,$currentphase) = @_;
7188:
7189: #get student info
7190: my $classlist=&Apache::loncoursedata::get_classlist();
7191: my %idmap=&username_to_idmap($classlist);
7192:
7193: #get scantron line setup
7194: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7195: my ($scanlines,$scan_data)=&scantron_getfile();
7196:
7197: my $nav_error;
7198: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
7199: if ($nav_error) {
7200: $r->print(&navmap_errormsg());
7201: return(1,$currentphase);
7202: }
7203:
7204: my %found=('ids'=>{},'usernames'=>{});
7205: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7206: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7207: if ($line=~/^[\s\cz]*$/) { next; }
7208: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7209: $scan_data);
7210: my $id=$$scan_record{'scantron.ID'};
7211: my $found;
7212: foreach my $checkid (keys(%idmap)) {
7213: if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
7214: }
7215: if ($found) {
7216: my $username=$idmap{$found};
7217: if ($found{'ids'}{$found}) {
7218: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
7219: $line,'duplicateID',$found);
7220: return(1,$currentphase);
7221: } elsif ($found{'usernames'}{$username}) {
7222: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
7223: $line,'duplicateID',$username);
7224: return(1,$currentphase);
7225: }
7226: #FIXME store away line we previously saw the ID on to use above
7227: $found{'ids'}{$found}++;
7228: $found{'usernames'}{$username}++;
7229: } else {
7230: if ($id =~ /^\s*$/) {
7231: my $username=&scan_data($scan_data,"$i.user");
7232: if (defined($username) && $found{'usernames'}{$username}) {
7233: &scantron_get_correction($r,$i,$scan_record,
7234: \%scantron_config,
7235: $line,'duplicateID',$username);
7236: return(1,$currentphase);
7237: } elsif (!defined($username)) {
7238: &scantron_get_correction($r,$i,$scan_record,
7239: \%scantron_config,
7240: $line,'incorrectID');
7241: return(1,$currentphase);
7242: }
7243: $found{'usernames'}{$username}++;
7244: } else {
7245: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
7246: $line,'incorrectID');
7247: return(1,$currentphase);
7248: }
7249: }
7250: }
7251:
7252: return (0,$currentphase+1);
7253: }
7254:
7255:
7256: sub scantron_get_correction {
7257: my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
7258: $randomorder,$randompick,$respnumlookup,$startline)=@_;
7259: #FIXME in the case of a duplicated ID the previous line, probably need
7260: #to show both the current line and the previous one and allow skipping
7261: #the previous one or the current one
7262:
7263: if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
7264: $r->print(
7265: '<p class="LC_warning">'
7266: .&mt('An error was detected ([_1]) for PaperID [_2]',
7267: "<b>$error</b>",
7268: '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
7269: ."</p> \n");
7270: } else {
7271: $r->print(
7272: '<p class="LC_warning">'
7273: .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
7274: "<b>$error</b>", $i, "<pre>$line</pre>")
7275: ."</p> \n");
7276: }
7277: my $message =
7278: '<p>'
7279: .&mt('The ID on the form is [_1]',
7280: "<tt>$$scan_record{'scantron.ID'}</tt>")
7281: .'<br />'
7282: .&mt('The name on the paper is [_1], [_2]',
7283: $$scan_record{'scantron.LastName'},
7284: $$scan_record{'scantron.FirstName'})
7285: .'</p>';
7286:
7287: $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
7288: $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
7289: # Array populated for doublebubble or
7290: my @lines_to_correct; # missingbubble errors to build javascript
7291: # to validate radio button checking
7292:
7293: if ($error =~ /ID$/) {
7294: if ($error eq 'incorrectID') {
7295: $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
7296: "</p>\n");
7297: } elsif ($error eq 'duplicateID') {
7298: $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
7299: }
7300: $r->print($message);
7301: $r->print("<p>".&mt("How should I handle this?")." <br /> \n");
7302: $r->print("\n<ul><li> ");
7303: #FIXME it would be nice if this sent back the user ID and
7304: #could do partial userID matches
7305: $r->print(&Apache::loncommon::selectstudent_link('scantronupload',
7306: 'scantron_username','scantron_domain'));
7307: $r->print(": <input type='text' name='scantron_username' value='' />");
7308: $r->print("\n:\n".
7309: &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
7310:
7311: $r->print('</li>');
7312: } elsif ($error =~ /CODE$/) {
7313: if ($error eq 'incorrectCODE') {
7314: $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
7315: } elsif ($error eq 'duplicateCODE') {
7316: $r->print('<p class="LC_warning">'.&mt("The encoded CODE has also been used by a previous paper [_1], and CODEs are supposed to be unique.",join(', ',@{$arg}))."</p>\n");
7317: }
7318: $r->print("<p>".&mt('The CODE on the form is [_1]',
7319: "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
7320: ."</p>\n");
7321: $r->print($message);
7322: $r->print("<p>".&mt("How should I handle this?")."</p>\n");
7323: $r->print("\n<br /> ");
7324: my $i=0;
7325: if ($error eq 'incorrectCODE'
7326: && $$scan_record{'scantron.CODE'}=~/\S/ ) {
7327: my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
7328: if ($closest > 0) {
7329: foreach my $testcode (@{$closest}) {
7330: my $checked='';
7331: if (!$i) { $checked=' checked="checked"'; }
7332: $r->print("
7333: <label>
7334: <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
7335: ".&mt("Use the similar CODE [_1] instead.",
7336: "<b><tt>".$testcode."</tt></b>")."
7337: </label>
7338: <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
7339: $r->print("\n<br />");
7340: $i++;
7341: }
7342: }
7343: }
7344: if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
7345: my $checked; if (!$i) { $checked=' checked="checked"'; }
7346: $r->print("
7347: <label>
7348: <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
7349: ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
7350: "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
7351: </label>");
7352: $r->print("\n<br />");
7353: }
7354:
7355: $r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
7356: function change_radio(field) {
7357: var slct=document.scantronupload.scantron_CODE_resolution;
7358: var i;
7359: for (i=0;i<slct.length;i++) {
7360: if (slct[i].value==field) { slct[i].checked=true; }
7361: }
7362: }
7363: ENDSCRIPT
7364: my $href="/adm/pickcode?".
7365: "form=".&escape("scantronupload").
7366: "&scantron_format=".&escape($env{'form.scantron_format'}).
7367: "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
7368: "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
7369: "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
7370: if ($env{'form.scantron_CODElist'} =~ /\S/) {
7371: $r->print("
7372: <label>
7373: <input type='radio' name='scantron_CODE_resolution' value='use_found' />
7374: ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
7375: "<a target='_blank' href='$href'>","</a>")."
7376: </label>
7377: ".&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\')" />'));
7378: $r->print("\n<br />");
7379: }
7380: $r->print("
7381: <label>
7382: <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
7383: ".&mt("Use [_1] as the CODE.",
7384: "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
7385: $r->print("\n<br /><br />");
7386: } elsif ($error eq 'doublebubble') {
7387: $r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
7388:
7389: # The form field scantron_questions is acutally a list of line numbers.
7390: # represented by this form so:
7391:
7392: my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
7393: $respnumlookup,$startline);
7394:
7395: $r->print('<input type="hidden" name="scantron_questions" value="'.
7396: $line_list.'" />');
7397: $r->print($message);
7398: $r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
7399: foreach my $question (@{$arg}) {
7400: my @linenums = &prompt_for_corrections($r,$question,$scan_config,
7401: $scan_record, $error,
7402: $randomorder,$randompick,
7403: $respnumlookup,$startline);
7404: push(@lines_to_correct,@linenums);
7405: }
7406: $r->print(&verify_bubbles_checked(@lines_to_correct));
7407: } elsif ($error eq 'missingbubble') {
7408: $r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
7409: $r->print($message);
7410: $r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
7411: $r->print(&mt("Some questions have no scanned bubbles.")."\n");
7412:
7413: # The form field scantron_questions is actually a list of line numbers not
7414: # a list of question numbers. Therefore:
7415: #
7416:
7417: my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
7418: $respnumlookup,$startline);
7419:
7420: $r->print('<input type="hidden" name="scantron_questions" value="'.
7421: $line_list.'" />');
7422: foreach my $question (@{$arg}) {
7423: my @linenums = &prompt_for_corrections($r,$question,$scan_config,
7424: $scan_record, $error,
7425: $randomorder,$randompick,
7426: $respnumlookup,$startline);
7427: push(@lines_to_correct,@linenums);
7428: }
7429: $r->print(&verify_bubbles_checked(@lines_to_correct));
7430: } else {
7431: $r->print("\n<ul>");
7432: }
7433: $r->print("\n</li></ul>");
7434: }
7435:
7436: sub verify_bubbles_checked {
7437: my (@ansnums) = @_;
7438: my $ansnumstr = join('","',@ansnums);
7439: my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
7440: my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
7441: function verify_bubble_radio(form) {
7442: var ansnumArray = new Array ("$ansnumstr");
7443: var need_bubble_count = 0;
7444: for (var i=0; i<ansnumArray.length; i++) {
7445: if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
7446: var bubble_picked = 0;
7447: for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
7448: if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
7449: bubble_picked = 1;
7450: }
7451: }
7452: if (bubble_picked == 0) {
7453: need_bubble_count ++;
7454: }
7455: }
7456: }
7457: if (need_bubble_count) {
7458: alert("$warning");
7459: return;
7460: }
7461: form.submit();
7462: }
7463: ENDSCRIPT
7464: return $output;
7465: }
7466:
7467: =pod
7468:
7469: =item questions_to_line_list
7470:
7471: Converts a list of questions into a string of comma separated
7472: line numbers in the answer sheet used by the questions. This is
7473: used to fill in the scantron_questions form field.
7474:
7475: Arguments:
7476: questions - Reference to an array of questions.
7477: randomorder - True if randomorder in use.
7478: randompick - True if randompick in use.
7479: respnumlookup - Reference to HASH mapping question numbers in bubble lines
7480: for current line to question number used for same question
7481: in "Master Seqence" (as seen by Course Coordinator).
7482: startline - Reference to hash where key is question number (0 is first)
7483: and key is number of first bubble line for current student
7484: or code-based randompick and/or randomorder.
7485:
7486: =cut
7487:
7488:
7489: sub questions_to_line_list {
7490: my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
7491: my @lines;
7492:
7493: foreach my $item (@{$questions}) {
7494: my $question = $item;
7495: my ($first,$count,$last);
7496: if ($item =~ /^(\d+)\.(\d+)$/) {
7497: $question = $1;
7498: my $subquestion = $2;
7499: my $responsenum = $question-1;
7500: if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
7501: $responsenum = $respnumlookup->{$question-1};
7502: if (ref($startline) eq 'HASH') {
7503: $first = $startline->{$question-1} + 1;
7504: }
7505: } else {
7506: $first = $first_bubble_line{$responsenum} + 1;
7507: }
7508: my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
7509: my $subcount = 1;
7510: while ($subcount<$subquestion) {
7511: $first += $subans[$subcount-1];
7512: $subcount ++;
7513: }
7514: $count = $subans[$subquestion-1];
7515: } else {
7516: my $responsenum = $question-1;
7517: if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
7518: $responsenum = $respnumlookup->{$question-1};
7519: if (ref($startline) eq 'HASH') {
7520: $first = $startline->{$question-1} + 1;
7521: }
7522: } else {
7523: $first = $first_bubble_line{$responsenum} + 1;
7524: }
7525: $count = $bubble_lines_per_response{$responsenum};
7526: }
7527: $last = $first+$count-1;
7528: push(@lines, ($first..$last));
7529: }
7530: return join(',', @lines);
7531: }
7532:
7533: =pod
7534:
7535: =item prompt_for_corrections
7536:
7537: Prompts for a potentially multiline correction to the
7538: user's bubbling (factors out common code from scantron_get_correction
7539: for multi and missing bubble cases).
7540:
7541: Arguments:
7542: $r - Apache request object.
7543: $question - The question number to prompt for.
7544: $scan_config - The scantron file configuration hash.
7545: $scan_record - Reference to the hash that has the the parsed scanlines.
7546: $error - Type of error
7547: $randomorder - True if randomorder in use.
7548: $randompick - True if randompick in use.
7549: $respnumlookup - Reference to HASH mapping question numbers in bubble lines
7550: for current line to question number used for same question
7551: in "Master Seqence" (as seen by Course Coordinator).
7552: $startline - Reference to hash where key is question number (0 is first)
7553: and value is number of first bubble line for current student
7554: or code-based randompick and/or randomorder.
7555:
7556:
7557: Implicit inputs:
7558: %bubble_lines_per_response - Starting line numbers for each question.
7559: Numbered from 0 (but question numbers are from
7560: 1.
7561: %first_bubble_line - Starting bubble line for each question.
7562: %subdivided_bubble_lines - optionresponse, matchresponse and rankresponse
7563: type problems render as separate sub-questions,
7564: in exam mode. This hash contains a
7565: comma-separated list of the lines per
7566: sub-question.
7567: %responsetype_per_response - essayresponse, formularesponse,
7568: stringresponse, imageresponse, reactionresponse,
7569: and organicresponse type problem parts can have
7570: multiple lines per response if the weight
7571: assigned exceeds 10. In this case, only
7572: one bubble per line is permitted, but more
7573: than one line might contain bubbles, e.g.
7574: bubbling of: line 1 - J, line 2 - J,
7575: line 3 - B would assign 22 points.
7576:
7577: =cut
7578:
7579: sub prompt_for_corrections {
7580: my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
7581: $randompick, $respnumlookup, $startline) = @_;
7582: my ($current_line,$lines);
7583: my @linenums;
7584: my $questionnum = $question;
7585: my ($first,$responsenum);
7586: if ($question =~ /^(\d+)\.(\d+)$/) {
7587: $question = $1;
7588: my $subquestion = $2;
7589: if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
7590: $responsenum = $respnumlookup->{$question-1};
7591: if (ref($startline) eq 'HASH') {
7592: $first = $startline->{$question-1};
7593: }
7594: } else {
7595: $responsenum = $question-1;
7596: $first = $first_bubble_line{$responsenum};
7597: }
7598: $current_line = $first + 1 ;
7599: my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
7600: my $subcount = 1;
7601: while ($subcount<$subquestion) {
7602: $current_line += $subans[$subcount-1];
7603: $subcount ++;
7604: }
7605: $lines = $subans[$subquestion-1];
7606: } else {
7607: if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
7608: $responsenum = $respnumlookup->{$question-1};
7609: if (ref($startline) eq 'HASH') {
7610: $first = $startline->{$question-1};
7611: }
7612: } else {
7613: $responsenum = $question-1;
7614: $first = $first_bubble_line{$responsenum};
7615: }
7616: $current_line = $first + 1;
7617: $lines = $bubble_lines_per_response{$responsenum};
7618: }
7619: if ($lines > 1) {
7620: $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
7621: if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
7622: ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
7623: ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
7624: ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
7625: ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
7626: ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
7627: $r->print(
7628: &mt("Although this particular question type requires handgrading, the instructions for this question in the bubblesheet exam directed students to leave [quant,_1,line] blank on their bubblesheets.",$lines)
7629: .'<br /><br />'
7630: .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
7631: .'<br />'
7632: .&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.')
7633: .'<br />'
7634: .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
7635: .'<br /><br />'
7636: );
7637: } else {
7638: $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
7639: }
7640: }
7641: for (my $i =0; $i < $lines; $i++) {
7642: my $selected = $$scan_record{"scantron.$current_line.answer"};
7643: &scantron_bubble_selector($r,$scan_config,$current_line,
7644: $questionnum,$error,split('', $selected));
7645: push(@linenums,$current_line);
7646: $current_line++;
7647: }
7648: if ($lines > 1) {
7649: $r->print("<hr /><br />");
7650: }
7651: return @linenums;
7652: }
7653:
7654: =pod
7655:
7656: =item scantron_bubble_selector
7657:
7658: Generates the html radiobuttons to correct a single bubble line
7659: possibly showing the existing the selected bubbles if known
7660:
7661: Arguments:
7662: $r - Apache request object
7663: $scan_config - hash from &get_scantron_config()
7664: $line - Number of the line being displayed.
7665: $questionnum - Question number (may include subquestion)
7666: $error - Type of error.
7667: @selected - Array of bubbles picked on this line.
7668:
7669: =cut
7670:
7671: sub scantron_bubble_selector {
7672: my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
7673: my $max=$$scan_config{'Qlength'};
7674:
7675: my $scmode=$$scan_config{'Qon'};
7676: if ($scmode eq 'number' || $scmode eq 'letter') {
7677: if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
7678: ($$scan_config{'BubblesPerRow'} > 0)) {
7679: $max=$$scan_config{'BubblesPerRow'};
7680: if (($scmode eq 'number') && ($max > 10)) {
7681: $max = 10;
7682: } elsif (($scmode eq 'letter') && $max > 26) {
7683: $max = 26;
7684: }
7685: } else {
7686: $max = 10;
7687: }
7688: }
7689:
7690: my @alphabet=('A'..'Z');
7691: $r->print(&Apache::loncommon::start_data_table().
7692: &Apache::loncommon::start_data_table_row());
7693: $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
7694: for (my $i=0;$i<$max+1;$i++) {
7695: $r->print("\n".'<td align="center">');
7696: if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
7697: else { $r->print(' '); }
7698: $r->print('</td>');
7699: }
7700: $r->print(&Apache::loncommon::end_data_table_row().
7701: &Apache::loncommon::start_data_table_row());
7702: for (my $i=0;$i<$max;$i++) {
7703: $r->print("\n".
7704: '<td><label><input type="radio" name="scantron_correct_Q_'.
7705: $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
7706: }
7707: my $nobub_checked = ' ';
7708: if ($error eq 'missingbubble') {
7709: $nobub_checked = ' checked = "checked" ';
7710: }
7711: $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
7712: $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
7713: '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
7714: $line.'" value="'.$questionnum.'" /></td>');
7715: $r->print(&Apache::loncommon::end_data_table_row().
7716: &Apache::loncommon::end_data_table());
7717: }
7718:
7719: =pod
7720:
7721: =item num_matches
7722:
7723: Counts the number of characters that are the same between the two arguments.
7724:
7725: Arguments:
7726: $orig - CODE from the scanline
7727: $code - CODE to match against
7728:
7729: Returns:
7730: $count - integer count of the number of same characters between the
7731: two arguments
7732:
7733: =cut
7734:
7735: sub num_matches {
7736: my ($orig,$code) = @_;
7737: my @code=split(//,$code);
7738: my @orig=split(//,$orig);
7739: my $same=0;
7740: for (my $i=0;$i<scalar(@code);$i++) {
7741: if ($code[$i] eq $orig[$i]) { $same++; }
7742: }
7743: return $same;
7744: }
7745:
7746: =pod
7747:
7748: =item scantron_get_closely_matching_CODEs
7749:
7750: Cycles through all CODEs and finds the set that has the greatest
7751: number of same characters as the provided CODE
7752:
7753: Arguments:
7754: $allcodes - hash ref returned by &get_codes()
7755: $CODE - CODE from the current scanline
7756:
7757: Returns:
7758: 2 element list
7759: - first elements is number of how closely matching the best fit is
7760: (5 means best set has 5 matching characters)
7761: - second element is an arrary ref containing the set of valid CODEs
7762: that best fit the passed in CODE
7763:
7764: =cut
7765:
7766: sub scantron_get_closely_matching_CODEs {
7767: my ($allcodes,$CODE)=@_;
7768: my @CODEs;
7769: foreach my $testcode (sort(keys(%{$allcodes}))) {
7770: push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
7771: }
7772:
7773: return ($#CODEs,$CODEs[-1]);
7774: }
7775:
7776: =pod
7777:
7778: =item get_codes
7779:
7780: Builds a hash which has keys of all of the valid CODEs from the selected
7781: set of remembered CODEs.
7782:
7783: Arguments:
7784: $old_name - name of the set of remembered CODEs
7785: $cdom - domain of the course
7786: $cnum - internal course name
7787:
7788: Returns:
7789: %allcodes - keys are the valid CODEs, values are all 1
7790:
7791: =cut
7792:
7793: sub get_codes {
7794: my ($old_name, $cdom, $cnum) = @_;
7795: if (!$old_name) {
7796: $old_name=$env{'form.scantron_CODElist'};
7797: }
7798: if (!$cdom) {
7799: $cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
7800: }
7801: if (!$cnum) {
7802: $cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
7803: }
7804: my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
7805: $cdom,$cnum);
7806: my %allcodes;
7807: if ($result{"type\0$old_name"} eq 'number') {
7808: %allcodes=map {($_,1)} split(',',$result{$old_name});
7809: } else {
7810: %allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
7811: }
7812: return %allcodes;
7813: }
7814:
7815: =pod
7816:
7817: =item scantron_validate_CODE
7818:
7819: Validates all scanlines in the selected file to not have any
7820: invalid or underspecified CODEs and that none of the codes are
7821: duplicated if this was requested.
7822:
7823: =cut
7824:
7825: sub scantron_validate_CODE {
7826: my ($r,$currentphase) = @_;
7827: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7828: if ($scantron_config{'CODElocation'} &&
7829: $scantron_config{'CODEstart'} &&
7830: $scantron_config{'CODElength'}) {
7831: if (!defined($env{'form.scantron_CODElist'})) {
7832: &FIXME_blow_up()
7833: }
7834: } else {
7835: return (0,$currentphase+1);
7836: }
7837:
7838: my %usedCODEs;
7839:
7840: my %allcodes=&get_codes();
7841:
7842: my $nav_error;
7843: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
7844: if ($nav_error) {
7845: $r->print(&navmap_errormsg());
7846: return(1,$currentphase);
7847: }
7848:
7849: my ($scanlines,$scan_data)=&scantron_getfile();
7850: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7851: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7852: if ($line=~/^[\s\cz]*$/) { next; }
7853: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7854: $scan_data);
7855: my $CODE=$$scan_record{'scantron.CODE'};
7856: my $error=0;
7857: if (!&Apache::lonnet::validCODE($CODE)) {
7858: &scantron_get_correction($r,$i,$scan_record,
7859: \%scantron_config,
7860: $line,'incorrectCODE',\%allcodes);
7861: return(1,$currentphase);
7862: }
7863: if (%allcodes && !exists($allcodes{$CODE})
7864: && !$$scan_record{'scantron.useCODE'}) {
7865: &scantron_get_correction($r,$i,$scan_record,
7866: \%scantron_config,
7867: $line,'incorrectCODE',\%allcodes);
7868: return(1,$currentphase);
7869: }
7870: if (exists($usedCODEs{$CODE})
7871: && $env{'form.scantron_CODEunique'} eq 'yes'
7872: && !$$scan_record{'scantron.CODE_ignore_dup'}) {
7873: &scantron_get_correction($r,$i,$scan_record,
7874: \%scantron_config,
7875: $line,'duplicateCODE',$usedCODEs{$CODE});
7876: return(1,$currentphase);
7877: }
7878: push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
7879: }
7880: return (0,$currentphase+1);
7881: }
7882:
7883: =pod
7884:
7885: =item scantron_validate_doublebubble
7886:
7887: Validates all scanlines in the selected file to not have any
7888: bubble lines with multiple bubbles marked.
7889:
7890: =cut
7891:
7892: sub scantron_validate_doublebubble {
7893: my ($r,$currentphase) = @_;
7894: #get student info
7895: my $classlist=&Apache::loncoursedata::get_classlist();
7896: my %idmap=&username_to_idmap($classlist);
7897: my (undef,undef,$sequence)=
7898: &Apache::lonnet::decode_symb($env{'form.selectpage'});
7899:
7900: #get scantron line setup
7901: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7902: my ($scanlines,$scan_data)=&scantron_getfile();
7903:
7904: my $navmap = Apache::lonnavmaps::navmap->new();
7905: unless (ref($navmap)) {
7906: $r->print(&navmap_errormsg());
7907: return(1,$currentphase);
7908: }
7909: my $map=$navmap->getResourceByUrl($sequence);
7910: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
7911: my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
7912: %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
7913: my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
7914:
7915: my $nav_error;
7916: if (ref($map)) {
7917: $randomorder = $map->randomorder();
7918: $randompick = $map->randompick();
7919: if ($randomorder || $randompick) {
7920: $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
7921: if ($nav_error) {
7922: $r->print(&navmap_errormsg());
7923: return(1,$currentphase);
7924: }
7925: &graders_resources_pass(\@resources,\%grader_partids_by_symb,
7926: \%grader_randomlists_by_symb,$bubbles_per_row);
7927: }
7928: } else {
7929: $r->print(&navmap_errormsg());
7930: return(1,$currentphase);
7931: }
7932:
7933: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
7934: if ($nav_error) {
7935: $r->print(&navmap_errormsg());
7936: return(1,$currentphase);
7937: }
7938:
7939: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7940: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7941: if ($line=~/^[\s\cz]*$/) { next; }
7942: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7943: $scan_data,undef,\%idmap,$randomorder,
7944: $randompick,$sequence,\@master_seq,
7945: \%symb_to_resource,\%grader_partids_by_symb,
7946: \%orderedforcode,\%respnumlookup,\%startline);
7947: if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
7948: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
7949: 'doublebubble',
7950: $$scan_record{'scantron.doubleerror'},
7951: $randomorder,$randompick,\%respnumlookup,\%startline);
7952: return (1,$currentphase);
7953: }
7954: return (0,$currentphase+1);
7955: }
7956:
7957:
7958: sub scantron_get_maxbubble {
7959: my ($nav_error,$scantron_config) = @_;
7960: if (defined($env{'form.scantron_maxbubble'}) &&
7961: $env{'form.scantron_maxbubble'}) {
7962: &restore_bubble_lines();
7963: return $env{'form.scantron_maxbubble'};
7964: }
7965:
7966: my (undef, undef, $sequence) =
7967: &Apache::lonnet::decode_symb($env{'form.selectpage'});
7968:
7969: my $navmap=Apache::lonnavmaps::navmap->new();
7970: unless (ref($navmap)) {
7971: if (ref($nav_error)) {
7972: $$nav_error = 1;
7973: }
7974: return;
7975: }
7976: my $map=$navmap->getResourceByUrl($sequence);
7977: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
7978: my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
7979:
7980: &Apache::lonxml::clear_problem_counter();
7981:
7982: my $uname = $env{'user.name'};
7983: my $udom = $env{'user.domain'};
7984: my $cid = $env{'request.course.id'};
7985: my $total_lines = 0;
7986: %bubble_lines_per_response = ();
7987: %first_bubble_line = ();
7988: %subdivided_bubble_lines = ();
7989: %responsetype_per_response = ();
7990: %masterseq_id_responsenum = ();
7991:
7992: my $response_number = 0;
7993: my $bubble_line = 0;
7994: foreach my $resource (@resources) {
7995: my $resid = $resource->id();
7996: my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
7997: $udom,undef,$bubbles_per_row);
7998: if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
7999: foreach my $part_id (@{$parts}) {
8000: my $lines;
8001:
8002: # TODO - make this a persistent hash not an array.
8003:
8004: # optionresponse, matchresponse and rankresponse type items
8005: # render as separate sub-questions in exam mode.
8006: if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
8007: ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
8008: ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
8009: my ($numbub,$numshown);
8010: if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
8011: if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
8012: $numbub = scalar(@{$analysis->{$part_id.'.options'}});
8013: }
8014: } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
8015: if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
8016: $numbub = scalar(@{$analysis->{$part_id.'.items'}});
8017: }
8018: } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
8019: if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
8020: $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
8021: }
8022: }
8023: if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
8024: $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
8025: }
8026: my $bubbles_per_row =
8027: &bubblesheet_bubbles_per_row($scantron_config);
8028: my $inner_bubble_lines = int($numbub/$bubbles_per_row);
8029: if (($numbub % $bubbles_per_row) != 0) {
8030: $inner_bubble_lines++;
8031: }
8032: for (my $i=0; $i<$numshown; $i++) {
8033: $subdivided_bubble_lines{$response_number} .=
8034: $inner_bubble_lines.',';
8035: }
8036: $subdivided_bubble_lines{$response_number} =~ s/,$//;
8037: $lines = $numshown * $inner_bubble_lines;
8038: } else {
8039: $lines = $analysis->{"$part_id.bubble_lines"};
8040: }
8041:
8042: $first_bubble_line{$response_number} = $bubble_line;
8043: $bubble_lines_per_response{$response_number} = $lines;
8044: $responsetype_per_response{$response_number} =
8045: $analysis->{$part_id.'.type'};
8046: $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;
8047: $response_number++;
8048:
8049: $bubble_line += $lines;
8050: $total_lines += $lines;
8051: }
8052: }
8053: }
8054: &Apache::lonnet::delenv('scantron.');
8055:
8056: &save_bubble_lines();
8057: $env{'form.scantron_maxbubble'} =
8058: $total_lines;
8059: return $env{'form.scantron_maxbubble'};
8060: }
8061:
8062: sub bubblesheet_bubbles_per_row {
8063: my ($scantron_config) = @_;
8064: my $bubbles_per_row;
8065: if (ref($scantron_config) eq 'HASH') {
8066: $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
8067: }
8068: if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
8069: $bubbles_per_row = 10;
8070: }
8071: return $bubbles_per_row;
8072: }
8073:
8074: sub scantron_validate_missingbubbles {
8075: my ($r,$currentphase) = @_;
8076: #get student info
8077: my $classlist=&Apache::loncoursedata::get_classlist();
8078: my %idmap=&username_to_idmap($classlist);
8079: my (undef,undef,$sequence)=
8080: &Apache::lonnet::decode_symb($env{'form.selectpage'});
8081:
8082: #get scantron line setup
8083: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
8084: my ($scanlines,$scan_data)=&scantron_getfile();
8085:
8086: my $navmap = Apache::lonnavmaps::navmap->new();
8087: unless (ref($navmap)) {
8088: $r->print(&navmap_errormsg());
8089: return(1,$currentphase);
8090: }
8091:
8092: my $map=$navmap->getResourceByUrl($sequence);
8093: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
8094: my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
8095: %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
8096: my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
8097:
8098: my $nav_error;
8099: if (ref($map)) {
8100: $randomorder = $map->randomorder();
8101: $randompick = $map->randompick();
8102: if ($randomorder || $randompick) {
8103: $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
8104: if ($nav_error) {
8105: $r->print(&navmap_errormsg());
8106: return(1,$currentphase);
8107: }
8108: &graders_resources_pass(\@resources,\%grader_partids_by_symb,
8109: \%grader_randomlists_by_symb,$bubbles_per_row);
8110: }
8111: } else {
8112: $r->print(&navmap_errormsg());
8113: return(1,$currentphase);
8114: }
8115:
8116:
8117: my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
8118: if ($nav_error) {
8119: $r->print(&navmap_errormsg());
8120: return(1,$currentphase);
8121: }
8122:
8123: if (!$max_bubble) { $max_bubble=2**31; }
8124: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
8125: my $line=&scantron_get_line($scanlines,$scan_data,$i);
8126: if ($line=~/^[\s\cz]*$/) { next; }
8127: my $scan_record =
8128: &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
8129: $randomorder,$randompick,$sequence,\@master_seq,
8130: \%symb_to_resource,\%grader_partids_by_symb,
8131: \%orderedforcode,\%respnumlookup,\%startline);
8132: if (!defined($$scan_record{'scantron.missingerror'})) { next; }
8133: my @to_correct;
8134:
8135: # Probably here's where the error is...
8136:
8137: foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
8138: my $lastbubble;
8139: if ($missing =~ /^(\d+)\.(\d+)$/) {
8140: my $question = $1;
8141: my $subquestion = $2;
8142: my ($first,$responsenum);
8143: if ($randomorder || $randompick) {
8144: $responsenum = $respnumlookup{$question-1};
8145: $first = $startline{$question-1};
8146: } else {
8147: $responsenum = $question-1;
8148: $first = $first_bubble_line{$responsenum};
8149: }
8150: if (!defined($first)) { next; }
8151: my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
8152: my $subcount = 1;
8153: while ($subcount<$subquestion) {
8154: $first += $subans[$subcount-1];
8155: $subcount ++;
8156: }
8157: my $count = $subans[$subquestion-1];
8158: $lastbubble = $first + $count;
8159: } else {
8160: my ($first,$responsenum);
8161: if ($randomorder || $randompick) {
8162: $responsenum = $respnumlookup{$missing-1};
8163: $first = $startline{$missing-1};
8164: } else {
8165: $responsenum = $missing-1;
8166: $first = $first_bubble_line{$responsenum};
8167: }
8168: if (!defined($first)) { next; }
8169: $lastbubble = $first + $bubble_lines_per_response{$responsenum};
8170: }
8171: if ($lastbubble > $max_bubble) { next; }
8172: push(@to_correct,$missing);
8173: }
8174: if (@to_correct) {
8175: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
8176: $line,'missingbubble',\@to_correct,
8177: $randomorder,$randompick,\%respnumlookup,
8178: \%startline);
8179: return (1,$currentphase);
8180: }
8181:
8182: }
8183: return (0,$currentphase+1);
8184: }
8185:
8186: sub hand_bubble_option {
8187: my (undef, undef, $sequence) =
8188: &Apache::lonnet::decode_symb($env{'form.selectpage'});
8189: return if ($sequence eq '');
8190: my $navmap = Apache::lonnavmaps::navmap->new();
8191: unless (ref($navmap)) {
8192: return;
8193: }
8194: my $needs_hand_bubbles;
8195: my $map=$navmap->getResourceByUrl($sequence);
8196: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
8197: foreach my $res (@resources) {
8198: if (ref($res)) {
8199: if ($res->is_problem()) {
8200: my $partlist = $res->parts();
8201: foreach my $part (@{ $partlist }) {
8202: my @types = $res->responseType($part);
8203: if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
8204: $needs_hand_bubbles = 1;
8205: last;
8206: }
8207: }
8208: }
8209: }
8210: }
8211: if ($needs_hand_bubbles) {
8212: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
8213: my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
8214: return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
8215: &mt('If you have already graded these by bubbling sheets to indicate points awarded, [_1]what point value is assigned to a filled last bubble in each row?','<br />').
8216: '<label><input type="radio" name="scantron_lastbubblepoints" value="'.$bubbles_per_row.'" checked="checked" />'.&mt('[quant,_1,point]',$bubbles_per_row).'</label> '.&mt('or').' '.
8217: '<label><input type="radio" name="scantron_lastbubblepoints" value="0"/>0 points</label></p>';
8218: }
8219: return;
8220: }
8221:
8222: sub scantron_process_students {
8223: my ($r,$symb) = @_;
8224:
8225: my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
8226: if (!$symb) {
8227: return '';
8228: }
8229: my $default_form_data=&defaultFormData($symb);
8230:
8231: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
8232: my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
8233: my ($scanlines,$scan_data)=&scantron_getfile();
8234: my $classlist=&Apache::loncoursedata::get_classlist();
8235: my %idmap=&username_to_idmap($classlist);
8236: my $navmap=Apache::lonnavmaps::navmap->new();
8237: unless (ref($navmap)) {
8238: $r->print(&navmap_errormsg());
8239: return '';
8240: }
8241: my $map=$navmap->getResourceByUrl($sequence);
8242: my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
8243: %grader_randomlists_by_symb);
8244: if (ref($map)) {
8245: $randomorder = $map->randomorder();
8246: $randompick = $map->randompick();
8247: } else {
8248: $r->print(&navmap_errormsg());
8249: return '';
8250: }
8251: my $nav_error;
8252: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
8253: if ($randomorder || $randompick) {
8254: $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
8255: if ($nav_error) {
8256: $r->print(&navmap_errormsg());
8257: return '';
8258: }
8259: }
8260: &graders_resources_pass(\@resources,\%grader_partids_by_symb,
8261: \%grader_randomlists_by_symb,$bubbles_per_row);
8262:
8263: my ($uname,$udom);
8264: my $result= <<SCANTRONFORM;
8265: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
8266: <input type="hidden" name="command" value="scantron_configphase" />
8267: $default_form_data
8268: SCANTRONFORM
8269: $r->print($result);
8270:
8271: my @delayqueue;
8272: my (%completedstudents,%scandata);
8273:
8274: my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
8275: my $count=&get_todo_count($scanlines,$scan_data);
8276: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
8277: &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
8278: $r->print('<br />');
8279: my $start=&Time::HiRes::time();
8280: my $i=-1;
8281: my $started;
8282:
8283: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
8284: if ($nav_error) {
8285: $r->print(&navmap_errormsg());
8286: return '';
8287: }
8288:
8289: # If an ssi failed in scantron_get_maxbubble, put an error message out to
8290: # the user and return.
8291:
8292: if ($ssi_error) {
8293: $r->print("</form>");
8294: &ssi_print_error($r);
8295: &Apache::lonnet::remove_lock($lock);
8296: return ''; # Dunno why the other returns return '' rather than just returning.
8297: }
8298:
8299: my %lettdig = &letter_to_digits();
8300: my $numletts = scalar(keys(%lettdig));
8301: my %orderedforcode;
8302:
8303: while ($i<$scanlines->{'count'}) {
8304: ($uname,$udom)=('','');
8305: $i++;
8306: my $line=&scantron_get_line($scanlines,$scan_data,$i);
8307: if ($line=~/^[\s\cz]*$/) { next; }
8308: if ($started) {
8309: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
8310: }
8311: $started=1;
8312: my %respnumlookup = ();
8313: my %startline = ();
8314: my $total;
8315: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
8316: $scan_data,undef,\%idmap,$randomorder,
8317: $randompick,$sequence,\@master_seq,
8318: \%symb_to_resource,\%grader_partids_by_symb,
8319: \%orderedforcode,\%respnumlookup,\%startline,
8320: \$total);
8321: unless ($uname=&scantron_find_student($scan_record,$scan_data,
8322: \%idmap,$i)) {
8323: &scantron_add_delay(\@delayqueue,$line,
8324: 'Unable to find a student that matches',1);
8325: next;
8326: }
8327: if (exists $completedstudents{$uname}) {
8328: &scantron_add_delay(\@delayqueue,$line,
8329: 'Student '.$uname.' has multiple sheets',2);
8330: next;
8331: }
8332: my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
8333: my $user = $uname.':'.$usec;
8334: ($uname,$udom)=split(/:/,$uname);
8335:
8336: my $scancode;
8337: if ((exists($scan_record->{'scantron.CODE'})) &&
8338: (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
8339: $scancode = $scan_record->{'scantron.CODE'};
8340: } else {
8341: $scancode = '';
8342: }
8343:
8344: my @mapresources = @resources;
8345: if ($randomorder || $randompick) {
8346: @mapresources =
8347: &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
8348: \%orderedforcode);
8349: }
8350: my (%partids_by_symb,$res_error);
8351: foreach my $resource (@mapresources) {
8352: my $ressymb;
8353: if (ref($resource)) {
8354: $ressymb = $resource->symb();
8355: } else {
8356: $res_error = 1;
8357: last;
8358: }
8359: if ((exists($grader_randomlists_by_symb{$ressymb})) ||
8360: (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
8361: my ($analysis,$parts) =
8362: &scantron_partids_tograde($resource,$env{'request.course.id'},
8363: $uname,$udom,undef,$bubbles_per_row);
8364: $partids_by_symb{$ressymb} = $parts;
8365: } else {
8366: $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
8367: }
8368: }
8369:
8370: if ($res_error) {
8371: &scantron_add_delay(\@delayqueue,$line,
8372: 'An error occurred while grading student '.$uname,2);
8373: next;
8374: }
8375:
8376: &Apache::lonxml::clear_problem_counter();
8377: &Apache::lonnet::appenv($scan_record);
8378:
8379: if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
8380: &scantron_putfile($scanlines,$scan_data);
8381: }
8382:
8383: if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
8384: \@mapresources,\%partids_by_symb,
8385: $bubbles_per_row,$randomorder,$randompick,
8386: \%respnumlookup,\%startline)
8387: eq 'ssi_error') {
8388: $ssi_error = 0; # So end of handler error message does not trigger.
8389: $r->print("</form>");
8390: &ssi_print_error($r);
8391: &Apache::lonnet::remove_lock($lock);
8392: return ''; # Why return ''? Beats me.
8393: }
8394:
8395: if (($scancode) && ($randomorder || $randompick)) {
8396: my $parmresult =
8397: &Apache::lonparmset::storeparm_by_symb($symb,
8398: '0_examcode',2,$scancode,
8399: 'string_examcode',$uname,
8400: $udom);
8401: }
8402: $completedstudents{$uname}={'line'=>$line};
8403: if ($env{'form.verifyrecord'}) {
8404: my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
8405: if ($randompick) {
8406: if ($total) {
8407: $lastpos = $total*$scantron_config{'Qlength'};
8408: }
8409: }
8410:
8411: my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
8412: chomp($studentdata);
8413: $studentdata =~ s/\r$//;
8414: my $studentrecord = '';
8415: my $counter = -1;
8416: foreach my $resource (@mapresources) {
8417: my $ressymb = $resource->symb();
8418: ($counter,my $recording) =
8419: &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
8420: $counter,$studentdata,$partids_by_symb{$ressymb},
8421: \%scantron_config,\%lettdig,$numletts,$randomorder,
8422: $randompick,\%respnumlookup,\%startline);
8423: $studentrecord .= $recording;
8424: }
8425: if ($studentrecord ne $studentdata) {
8426: &Apache::lonxml::clear_problem_counter();
8427: if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
8428: \@mapresources,\%partids_by_symb,
8429: $bubbles_per_row,$randomorder,$randompick,
8430: \%respnumlookup,\%startline)
8431: eq 'ssi_error') {
8432: $ssi_error = 0; # So end of handler error message does not trigger.
8433: $r->print("</form>");
8434: &ssi_print_error($r);
8435: &Apache::lonnet::remove_lock($lock);
8436: delete($completedstudents{$uname});
8437: return '';
8438: }
8439: $counter = -1;
8440: $studentrecord = '';
8441: foreach my $resource (@mapresources) {
8442: my $ressymb = $resource->symb();
8443: ($counter,my $recording) =
8444: &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
8445: $counter,$studentdata,$partids_by_symb{$ressymb},
8446: \%scantron_config,\%lettdig,$numletts,
8447: $randomorder,$randompick,\%respnumlookup,
8448: \%startline);
8449: $studentrecord .= $recording;
8450: }
8451: if ($studentrecord ne $studentdata) {
8452: $r->print('<p><span class="LC_warning">');
8453: if ($scancode eq '') {
8454: $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
8455: $uname.':'.$udom,$scan_record->{'scantron.ID'}));
8456: } else {
8457: $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
8458: $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
8459: }
8460: $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
8461: &Apache::loncommon::start_data_table_header_row()."\n".
8462: '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
8463: &Apache::loncommon::end_data_table_header_row()."\n".
8464: &Apache::loncommon::start_data_table_row().
8465: '<td>'.&mt('Bubblesheet').'</td>'.
8466: '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
8467: &Apache::loncommon::end_data_table_row().
8468: &Apache::loncommon::start_data_table_row().
8469: '<td>'.&mt('Stored submissions').'</td>'.
8470: '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
8471: &Apache::loncommon::end_data_table_row().
8472: &Apache::loncommon::end_data_table().'</p>');
8473: } else {
8474: $r->print('<br /><span class="LC_warning">'.
8475: &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 />'.
8476: &mt("As a consequence, this user's submission history records two tries.").
8477: '</span><br />');
8478: }
8479: }
8480: }
8481: if (&Apache::loncommon::connection_aborted($r)) { last; }
8482: } continue {
8483: &Apache::lonxml::clear_problem_counter();
8484: &Apache::lonnet::delenv('scantron.');
8485: }
8486: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
8487: &Apache::lonnet::remove_lock($lock);
8488: # my $lasttime = &Time::HiRes::time()-$start;
8489: # $r->print("<p>took $lasttime</p>");
8490:
8491: $r->print("</form>");
8492: return '';
8493: }
8494:
8495: sub graders_resources_pass {
8496: my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
8497: $bubbles_per_row) = @_;
8498: if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) &&
8499: (ref($grader_randomlists_by_symb) eq 'HASH')) {
8500: foreach my $resource (@{$resources}) {
8501: my $ressymb = $resource->symb();
8502: my ($analysis,$parts) =
8503: &scantron_partids_tograde($resource,$env{'request.course.id'},
8504: $env{'user.name'},$env{'user.domain'},
8505: 1,$bubbles_per_row);
8506: $grader_partids_by_symb->{$ressymb} = $parts;
8507: if (ref($analysis) eq 'HASH') {
8508: if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
8509: $grader_randomlists_by_symb->{$ressymb} =
8510: $analysis->{'parts_withrandomlist'};
8511: }
8512: }
8513: }
8514: }
8515: return;
8516: }
8517:
8518: =pod
8519:
8520: =item users_order
8521:
8522: Returns array of resources in current map, ordered based on either CODE,
8523: if this is a CODEd exam, or based on student's identity if this is a
8524: "NAMEd" exam.
8525:
8526: Should be used when randomorder and/or randompick applied when the
8527: corresponding exam was printed, prior to students completing bubblesheets
8528: for the version of the exam the student received.
8529:
8530: =cut
8531:
8532: sub users_order {
8533: my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
8534: my @mapresources;
8535: unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
8536: return @mapresources;
8537: }
8538: if ($scancode) {
8539: if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
8540: @mapresources = @{$orderedforcode->{$scancode}};
8541: } else {
8542: $env{'form.CODE'} = $scancode;
8543: my $actual_seq =
8544: &Apache::lonprintout::master_seq_to_person_seq($mapurl,
8545: $master_seq,
8546: $user,$scancode,1);
8547: if (ref($actual_seq) eq 'ARRAY') {
8548: @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
8549: if (ref($orderedforcode) eq 'HASH') {
8550: if (@mapresources > 0) {
8551: $orderedforcode->{$scancode} = \@mapresources;
8552: }
8553: }
8554: }
8555: delete($env{'form.CODE'});
8556: }
8557: } else {
8558: my $actual_seq =
8559: &Apache::lonprintout::master_seq_to_person_seq($mapurl,
8560: $master_seq,
8561: $user,undef,1);
8562: if (ref($actual_seq) eq 'ARRAY') {
8563: @mapresources =
8564: map { $symb_to_resource->{$_}; } @{$actual_seq};
8565: }
8566: }
8567: return @mapresources;
8568: }
8569:
8570: sub grade_student_bubbles {
8571: my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
8572: $randomorder,$randompick,$respnumlookup,$startline) = @_;
8573: my $uselookup = 0;
8574: if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
8575: (ref($startline) eq 'HASH')) {
8576: $uselookup = 1;
8577: }
8578:
8579: if (ref($resources) eq 'ARRAY') {
8580: my $count = 0;
8581: foreach my $resource (@{$resources}) {
8582: my $ressymb = $resource->symb();
8583: my %form = ('submitted' => 'scantron',
8584: 'grade_target' => 'grade',
8585: 'grade_username' => $uname,
8586: 'grade_domain' => $udom,
8587: 'grade_courseid' => $env{'request.course.id'},
8588: 'grade_symb' => $ressymb,
8589: 'CODE' => $scancode
8590: );
8591: if ($bubbles_per_row ne '') {
8592: $form{'bubbles_per_row'} = $bubbles_per_row;
8593: }
8594: if ($env{'form.scantron_lastbubblepoints'} ne '') {
8595: $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
8596: }
8597: if (ref($parts) eq 'HASH') {
8598: if (ref($parts->{$ressymb}) eq 'ARRAY') {
8599: foreach my $part (@{$parts->{$ressymb}}) {
8600: if ($uselookup) {
8601: $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
8602: } else {
8603: $form{'scantron_questnum_start.'.$part} =
8604: 1+$env{'form.scantron.first_bubble_line.'.$count};
8605: }
8606: $count++;
8607: }
8608: }
8609: }
8610: my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
8611: return 'ssi_error' if ($ssi_error);
8612: last if (&Apache::loncommon::connection_aborted($r));
8613: }
8614: }
8615: return;
8616: }
8617:
8618: sub scantron_upload_scantron_data {
8619: my ($r,$symb)=@_;
8620: my $dom = $env{'request.role.domain'};
8621: my $domdesc = &Apache::lonnet::domain($dom,'description');
8622: $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
8623: my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
8624: 'domainid',
8625: 'coursename',$dom);
8626: my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
8627: (' 'x2).&mt('(shows course personnel)');
8628: my $default_form_data=&defaultFormData($symb);
8629: my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
8630: 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.");
8631: $r->print(&Apache::lonhtmlcommon::scripttag('
8632: function checkUpload(formname) {
8633: if (formname.upfile.value == "") {
8634: alert("'.$nofile_alert.'");
8635: return false;
8636: }
8637: if (formname.courseid.value == "") {
8638: alert("'.$nocourseid_alert.'");
8639: return false;
8640: }
8641: formname.submit();
8642: }
8643:
8644: function ToSyllabus() {
8645: var cdom = '."'$dom'".';
8646: var cnum = document.rules.courseid.value;
8647: if (cdom == "" || cdom == null) {
8648: return;
8649: }
8650: if (cnum == "" || cnum == null) {
8651: return;
8652: }
8653: syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
8654: "height=350,width=350,scrollbars=yes,menubar=no");
8655: return;
8656: }
8657:
8658: '));
8659: $r->print('
8660: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
8661:
8662: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
8663: '.$default_form_data.
8664: &Apache::lonhtmlcommon::start_pick_box().
8665: &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
8666: '<input name="courseid" type="text" size="30" />'.$select_link.
8667: &Apache::lonhtmlcommon::row_closure().
8668: &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
8669: '<input name="coursename" type="text" size="30" />'.$syllabuslink.
8670: &Apache::lonhtmlcommon::row_closure().
8671: &Apache::lonhtmlcommon::row_title(&mt('Domain')).
8672: '<input name="domainid" type="hidden" />'.$domdesc.
8673: &Apache::lonhtmlcommon::row_closure().
8674: &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
8675: '<input type="file" name="upfile" size="50" />'.
8676: &Apache::lonhtmlcommon::row_closure(1).
8677: &Apache::lonhtmlcommon::end_pick_box().'<br />
8678:
8679: <input name="command" value="scantronupload_save" type="hidden" />
8680: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
8681: </form>
8682: ');
8683: return '';
8684: }
8685:
8686:
8687: sub scantron_upload_scantron_data_save {
8688: my($r,$symb)=@_;
8689: my $doanotherupload=
8690: '<br /><form action="/adm/grades" method="post">'."\n".
8691: '<input type="hidden" name="command" value="scantronupload" />'."\n".
8692: '<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
8693: '</form>'."\n";
8694: if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
8695: !&Apache::lonnet::allowed('usc',
8696: $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
8697: $r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
8698: unless ($symb) {
8699: $r->print($doanotherupload);
8700: }
8701: return '';
8702: }
8703: my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
8704: my $uploadedfile;
8705: $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
8706: if (length($env{'form.upfile'}) < 2) {
8707: $r->print(
8708: &Apache::lonhtmlcommon::confirm_success(
8709: &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
8710: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
8711: } else {
8712: my $result =
8713: &Apache::lonnet::userfileupload('upfile','','scantron','','','',
8714: $env{'form.courseid'},$env{'form.domainid'});
8715: if ($result =~ m{^/uploaded/}) {
8716: $r->print(
8717: &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
8718: &mt('Uploaded [_1] bytes of data into location: [_2]',
8719: (length($env{'form.upfile'})-1),
8720: '<span class="LC_filename">'.$result.'</span>'));
8721: ($uploadedfile) = ($result =~ m{/([^/]+)$});
8722: $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
8723: $env{'form.courseid'},$uploadedfile));
8724: } else {
8725: $r->print(
8726: &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
8727: &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
8728: $result,
8729: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
8730: }
8731: }
8732: if ($symb) {
8733: $r->print(&scantron_selectphase($r,$uploadedfile,$symb));
8734: } else {
8735: $r->print($doanotherupload);
8736: }
8737: return '';
8738: }
8739:
8740: sub validate_uploaded_scantron_file {
8741: my ($cdom,$cname,$fname) = @_;
8742: my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
8743: my @lines;
8744: if ($scanlines ne '-1') {
8745: @lines=split("\n",$scanlines,-1);
8746: }
8747: my $output;
8748: if (@lines) {
8749: my (%counts,$max_match_format);
8750: my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
8751: my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
8752: my %idmap = &username_to_idmap($classlist);
8753: foreach my $key (keys(%idmap)) {
8754: my $lckey = lc($key);
8755: $idmap{$lckey} = $idmap{$key};
8756: }
8757: my %unique_formats;
8758: my @formatlines = &get_scantronformat_file();
8759: foreach my $line (@formatlines) {
8760: chomp($line);
8761: my @config = split(/:/,$line);
8762: my $idstart = $config[5];
8763: my $idlength = $config[6];
8764: if (($idstart ne '') && ($idlength > 0)) {
8765: if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
8766: push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]);
8767: } else {
8768: $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
8769: }
8770: }
8771: }
8772: foreach my $key (keys(%unique_formats)) {
8773: my ($idstart,$idlength) = split(':',$key);
8774: %{$counts{$key}} = (
8775: 'found' => 0,
8776: 'total' => 0,
8777: );
8778: foreach my $line (@lines) {
8779: next if ($line =~ /^#/);
8780: next if ($line =~ /^[\s\cz]*$/);
8781: my $id = substr($line,$idstart-1,$idlength);
8782: $id = lc($id);
8783: if (exists($idmap{$id})) {
8784: $counts{$key}{'found'} ++;
8785: }
8786: $counts{$key}{'total'} ++;
8787: }
8788: if ($counts{$key}{'total'}) {
8789: my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
8790: if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
8791: $max_match_pct = $percent_match;
8792: $max_match_format = $key;
8793: $found_match_count = $counts{$key}{'found'};
8794: $max_match_count = $counts{$key}{'total'};
8795: }
8796: }
8797: }
8798: if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
8799: my $format_descs;
8800: my $numwithformat = @{$unique_formats{$max_match_format}};
8801: for (my $i=0; $i<$numwithformat; $i++) {
8802: my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
8803: if ($i<$numwithformat-2) {
8804: $format_descs .= '"<i>'.$desc.'</i>", ';
8805: } elsif ($i==$numwithformat-2) {
8806: $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
8807: } elsif ($i==$numwithformat-1) {
8808: $format_descs .= '"<i>'.$desc.'</i>"';
8809: }
8810: }
8811: my $showpct = sprintf("%.0f",$max_match_pct).'%';
8812: $output .= '<br />';
8813: if ($found_match_count == $max_match_count) {
8814: # 100% matching entries
8815: $output .= &Apache::lonhtmlcommon::confirm_success(
8816: &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
8817: '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
8818: &mt('Comparison of student IDs in the uploaded file with'.
8819: ' the course roster found matches for [_1] of the [_2] entries'.
8820: ' in the file (for the format defined for [_3]).',
8821: '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
8822: } else {
8823: # Not all entries matching? -> Show warning and additional info
8824: $output .=
8825: &Apache::lonhtmlcommon::confirm_success(
8826: &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
8827: '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
8828: &mt('Not all entries could be matched!'),1).'<br />'.
8829: &mt('Comparison of student IDs in the uploaded file with'.
8830: ' the course roster found matches for [_1] of the [_2] entries'.
8831: ' in the file (for the format defined for [_3]).',
8832: '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
8833: '<p class="LC_info">'.
8834: &mt('A low percentage of matches results from one of the following:').
8835: '</p><ul>'.
8836: '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
8837: '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
8838: '<i>'.$cdom.'</i>').'</li>'.
8839: '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
8840: '<li>'.&mt('The course roster is not up to date.').'</li>'.
8841: '</ul>';
8842: }
8843: }
8844: } else {
8845: $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
8846: }
8847: return $output;
8848: }
8849:
8850: sub valid_file {
8851: my ($requested_file)=@_;
8852: foreach my $filename (sort(&scantron_filenames())) {
8853: if ($requested_file eq $filename) { return 1; }
8854: }
8855: return 0;
8856: }
8857:
8858: sub scantron_download_scantron_data {
8859: my ($r,$symb)=@_;
8860: my $default_form_data=&defaultFormData($symb);
8861: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
8862: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
8863: my $file=$env{'form.scantron_selectfile'};
8864: if (! &valid_file($file)) {
8865: $r->print('
8866: <p>
8867: '.&mt('The requested filename was invalid.').'
8868: </p>
8869: ');
8870: return;
8871: }
8872: my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
8873: my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
8874: my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
8875: &Apache::lonnet::allowuploaded('/adm/grades',$orig);
8876: &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
8877: &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
8878: $r->print('
8879: <p>
8880: '.&mt('[_1]Original[_2] file as uploaded by the bubblesheet office.',
8881: '<a href="'.$orig.'">','</a>').'
8882: </p>
8883: <p>
8884: '.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
8885: '<a href="'.$corrected.'">','</a>').'
8886: </p>
8887: <p>
8888: '.&mt('[_1]Skipped[_2], a file of records that were skipped.',
8889: '<a href="'.$skipped.'">','</a>').'
8890: </p>
8891: ');
8892: return '';
8893: }
8894:
8895: sub checkscantron_results {
8896: my ($r,$symb) = @_;
8897: if (!$symb) {return '';}
8898: my $cid = $env{'request.course.id'};
8899: my %lettdig = &letter_to_digits();
8900: my $numletts = scalar(keys(%lettdig));
8901: my $cnum = $env{'course.'.$cid.'.num'};
8902: my $cdom = $env{'course.'.$cid.'.domain'};
8903: my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
8904: my %record;
8905: my %scantron_config =
8906: &Apache::grades::get_scantron_config($env{'form.scantron_format'});
8907: my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
8908: my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
8909: my $classlist=&Apache::loncoursedata::get_classlist();
8910: my %idmap=&Apache::grades::username_to_idmap($classlist);
8911: my $navmap=Apache::lonnavmaps::navmap->new();
8912: unless (ref($navmap)) {
8913: $r->print(&navmap_errormsg());
8914: return '';
8915: }
8916: my $map=$navmap->getResourceByUrl($sequence);
8917: my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
8918: %grader_randomlists_by_symb,%orderedforcode);
8919: if (ref($map)) {
8920: $randomorder=$map->randomorder();
8921: $randompick=$map->randompick();
8922: }
8923: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
8924: my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
8925: if ($nav_error) {
8926: $r->print(&navmap_errormsg());
8927: return '';
8928: }
8929: &graders_resources_pass(\@resources,\%grader_partids_by_symb,
8930: \%grader_randomlists_by_symb,$bubbles_per_row);
8931: my ($uname,$udom);
8932: my (%scandata,%lastname,%bylast);
8933: $r->print('
8934: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
8935:
8936: my @delayqueue;
8937: my %completedstudents;
8938:
8939: my $count=&get_todo_count($scanlines,$scan_data);
8940: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
8941: my ($username,$domain,$started);
8942: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
8943: if ($nav_error) {
8944: $r->print(&navmap_errormsg());
8945: return '';
8946: }
8947:
8948: &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
8949: my $start=&Time::HiRes::time();
8950: my $i=-1;
8951:
8952: while ($i<$scanlines->{'count'}) {
8953: ($username,$domain,$uname)=('','','');
8954: $i++;
8955: my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
8956: if ($line=~/^[\s\cz]*$/) { next; }
8957: if ($started) {
8958: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
8959: }
8960: $started=1;
8961: my $scan_record=
8962: &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
8963: $scan_data);
8964: unless ($uname=&scantron_find_student($scan_record,$scan_data,
8965: \%idmap,$i)) {
8966: &Apache::grades::scantron_add_delay(\@delayqueue,$line,
8967: 'Unable to find a student that matches',1);
8968: next;
8969: }
8970: if (exists $completedstudents{$uname}) {
8971: &Apache::grades::scantron_add_delay(\@delayqueue,$line,
8972: 'Student '.$uname.' has multiple sheets',2);
8973: next;
8974: }
8975: my $pid = $scan_record->{'scantron.ID'};
8976: $lastname{$pid} = $scan_record->{'scantron.LastName'};
8977: push(@{$bylast{$lastname{$pid}}},$pid);
8978: my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
8979: my $user = $uname.':'.$usec;
8980: ($username,$domain)=split(/:/,$uname);
8981:
8982: my $scancode;
8983: if ((exists($scan_record->{'scantron.CODE'})) &&
8984: (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
8985: $scancode = $scan_record->{'scantron.CODE'};
8986: } else {
8987: $scancode = '';
8988: }
8989:
8990: my @mapresources = @resources;
8991: my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
8992: my %respnumlookup=();
8993: my %startline=();
8994: if ($randomorder || $randompick) {
8995: @mapresources =
8996: &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
8997: \%orderedforcode);
8998: my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
8999: $scan_record,\@master_seq,\%symb_to_resource,
9000: \%grader_partids_by_symb,\%orderedforcode,
9001: \%respnumlookup,\%startline);
9002: if ($randompick && $total) {
9003: $lastpos = $total*$scantron_config{'Qlength'};
9004: }
9005: }
9006: $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
9007: chomp($scandata{$pid});
9008: $scandata{$pid} =~ s/\r$//;
9009:
9010: my $counter = -1;
9011: foreach my $resource (@mapresources) {
9012: my $parts;
9013: my $ressymb = $resource->symb();
9014: if ((exists($grader_randomlists_by_symb{$ressymb})) ||
9015: (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
9016: (my $analysis,$parts) =
9017: &scantron_partids_tograde($resource,$env{'request.course.id'},
9018: $username,$domain,undef,
9019: $bubbles_per_row);
9020: } else {
9021: $parts = $grader_partids_by_symb{$ressymb};
9022: }
9023: ($counter,my $recording) =
9024: &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
9025: $scandata{$pid},$parts,
9026: \%scantron_config,\%lettdig,$numletts,
9027: $randomorder,$randompick,
9028: \%respnumlookup,\%startline);
9029: $record{$pid} .= $recording;
9030: }
9031: }
9032: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
9033: $r->print('<br />');
9034: my ($okstudents,$badstudents,$numstudents,$passed,$failed);
9035: $passed = 0;
9036: $failed = 0;
9037: $numstudents = 0;
9038: foreach my $last (sort(keys(%bylast))) {
9039: if (ref($bylast{$last}) eq 'ARRAY') {
9040: foreach my $pid (sort(@{$bylast{$last}})) {
9041: my $showscandata = $scandata{$pid};
9042: my $showrecord = $record{$pid};
9043: $showscandata =~ s/\s/ /g;
9044: $showrecord =~ s/\s/ /g;
9045: if ($scandata{$pid} eq $record{$pid}) {
9046: my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
9047: $okstudents .= '<tr class="'.$css_class.'">'.
9048: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
9049: '</tr>'."\n".
9050: '<tr class="'.$css_class.'">'."\n".
9051: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
9052: $passed ++;
9053: } else {
9054: my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
9055: $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".
9056: '</tr>'."\n".
9057: '<tr class="'.$css_class.'">'."\n".
9058: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
9059: '</tr>'."\n";
9060: $failed ++;
9061: }
9062: $numstudents ++;
9063: }
9064: }
9065: }
9066: $r->print(
9067: '<p>'
9068: .&mt('Comparison of bubblesheet data (including corrections) with corresponding submission records (most recent submission) for [_1][quant,_2,student][_3] ([quant,_4,bubblesheet line] per student).',
9069: '<b>',
9070: $numstudents,
9071: '</b>',
9072: $env{'form.scantron_maxbubble'})
9073: .'</p>'
9074: );
9075: $r->print('<p>'
9076: .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
9077: .'<br />'
9078: .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
9079: .'</p>'
9080: );
9081: if ($passed) {
9082: $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
9083: $r->print(&Apache::loncommon::start_data_table()."\n".
9084: &Apache::loncommon::start_data_table_header_row()."\n".
9085: '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
9086: &Apache::loncommon::end_data_table_header_row()."\n".
9087: $okstudents."\n".
9088: &Apache::loncommon::end_data_table().'<br />');
9089: }
9090: if ($failed) {
9091: $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
9092: $r->print(&Apache::loncommon::start_data_table()."\n".
9093: &Apache::loncommon::start_data_table_header_row()."\n".
9094: '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
9095: &Apache::loncommon::end_data_table_header_row()."\n".
9096: $badstudents."\n".
9097: &Apache::loncommon::end_data_table()).'<br />'.
9098: &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.');
9099: }
9100: $r->print('</form><br />');
9101: return;
9102: }
9103:
9104: sub verify_scantron_grading {
9105: my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
9106: $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
9107: $respnumlookup,$startline) = @_;
9108: my ($record,%expected,%startpos);
9109: return ($counter,$record) if (!ref($resource));
9110: return ($counter,$record) if (!$resource->is_problem());
9111: my $symb = $resource->symb();
9112: return ($counter,$record) if (ref($partids) ne 'ARRAY');
9113: foreach my $part_id (@{$partids}) {
9114: $counter ++;
9115: $expected{$part_id} = 0;
9116: my $respnum = $counter;
9117: if ($randomorder || $randompick) {
9118: $respnum = $respnumlookup->{$counter};
9119: $startpos{$part_id} = $startline->{$counter} + 1;
9120: } else {
9121: $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
9122: }
9123: if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
9124: my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
9125: foreach my $item (@sub_lines) {
9126: $expected{$part_id} += $item;
9127: }
9128: } else {
9129: $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
9130: }
9131: }
9132: if ($symb) {
9133: my %recorded;
9134: my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
9135: if ($returnhash{'version'}) {
9136: my %lasthash=();
9137: my $version;
9138: for ($version=1;$version<=$returnhash{'version'};$version++) {
9139: foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
9140: $lasthash{$key}=$returnhash{$version.':'.$key};
9141: }
9142: }
9143: foreach my $key (keys(%lasthash)) {
9144: if ($key =~ /\.scantron$/) {
9145: my $value = &unescape($lasthash{$key});
9146: my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
9147: if ($value eq '') {
9148: for (my $i=0; $i<$expected{$part_id}; $i++) {
9149: for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
9150: $recorded{$part_id} .= $scantron_config->{'Qoff'};
9151: }
9152: }
9153: } else {
9154: my @tocheck;
9155: my @items = split(//,$value);
9156: if (($scantron_config->{'Qon'} eq 'letter') ||
9157: ($scantron_config->{'Qon'} eq 'number')) {
9158: if (@items < $expected{$part_id}) {
9159: my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
9160: my @singles = split(//,$fragment);
9161: foreach my $pos (@singles) {
9162: if ($pos eq ' ') {
9163: push(@tocheck,$pos);
9164: } else {
9165: my $next = shift(@items);
9166: push(@tocheck,$next);
9167: }
9168: }
9169: } else {
9170: @tocheck = @items;
9171: }
9172: foreach my $letter (@tocheck) {
9173: if ($scantron_config->{'Qon'} eq 'letter') {
9174: if ($letter !~ /^[A-J]$/) {
9175: $letter = $scantron_config->{'Qoff'};
9176: }
9177: $recorded{$part_id} .= $letter;
9178: } elsif ($scantron_config->{'Qon'} eq 'number') {
9179: my $digit;
9180: if ($letter !~ /^[A-J]$/) {
9181: $digit = $scantron_config->{'Qoff'};
9182: } else {
9183: $digit = $lettdig->{$letter};
9184: }
9185: $recorded{$part_id} .= $digit;
9186: }
9187: }
9188: } else {
9189: @tocheck = @items;
9190: for (my $i=0; $i<$expected{$part_id}; $i++) {
9191: my $curr_sub = shift(@tocheck);
9192: my $digit;
9193: if ($curr_sub =~ /^[A-J]$/) {
9194: $digit = $lettdig->{$curr_sub}-1;
9195: }
9196: if ($curr_sub eq 'J') {
9197: $digit += scalar($numletts);
9198: }
9199: for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
9200: if ($j == $digit) {
9201: $recorded{$part_id} .= $scantron_config->{'Qon'};
9202: } else {
9203: $recorded{$part_id} .= $scantron_config->{'Qoff'};
9204: }
9205: }
9206: }
9207: }
9208: }
9209: }
9210: }
9211: }
9212: foreach my $part_id (@{$partids}) {
9213: if ($recorded{$part_id} eq '') {
9214: for (my $i=0; $i<$expected{$part_id}; $i++) {
9215: for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
9216: $recorded{$part_id} .= $scantron_config->{'Qoff'};
9217: }
9218: }
9219: }
9220: $record .= $recorded{$part_id};
9221: }
9222: }
9223: return ($counter,$record);
9224: }
9225:
9226: sub letter_to_digits {
9227: my %lettdig = (
9228: A => 1,
9229: B => 2,
9230: C => 3,
9231: D => 4,
9232: E => 5,
9233: F => 6,
9234: G => 7,
9235: H => 8,
9236: I => 9,
9237: J => 0,
9238: );
9239: return %lettdig;
9240: }
9241:
9242:
9243: #-------- end of section for handling grading scantron forms -------
9244: #
9245: #-------------------------------------------------------------------
9246:
9247: #-------------------------- Menu interface -------------------------
9248: #
9249: #--- Href with symb and command ---
9250:
9251: sub href_symb_cmd {
9252: my ($symb,$cmd)=@_;
9253: return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&command='.$cmd;
9254: }
9255:
9256: sub grading_menu {
9257: my ($request,$symb) = @_;
9258: if (!$symb) {return '';}
9259:
9260: my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
9261: 'command'=>'individual');
9262:
9263: my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
9264:
9265: $fields{'command'}='ungraded';
9266: my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
9267:
9268: $fields{'command'}='table';
9269: my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
9270:
9271: $fields{'command'}='all_for_one';
9272: my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
9273:
9274: $fields{'command'}='downloadfilesselect';
9275: my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
9276:
9277: $fields{'command'} = 'csvform';
9278: my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
9279:
9280: $fields{'command'} = 'processclicker';
9281: my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
9282:
9283: $fields{'command'} = 'scantron_selectphase';
9284: my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
9285:
9286: $fields{'command'} = 'initialverifyreceipt';
9287: my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
9288:
9289: my @menu = ({ categorytitle=>'Hand Grading',
9290: items =>[
9291: { linktext => 'Select individual students to grade',
9292: url => $url1a,
9293: permission => 'F',
9294: icon => 'grade_students.png',
9295: linktitle => 'Grade current resource for a selection of students.'
9296: },
9297: { linktext => 'Grade ungraded submissions.',
9298: url => $url1b,
9299: permission => 'F',
9300: icon => 'ungrade_sub.png',
9301: linktitle => 'Grade all submissions that have not been graded yet.'
9302: },
9303:
9304: { linktext => 'Grading table',
9305: url => $url1c,
9306: permission => 'F',
9307: icon => 'grading_table.png',
9308: linktitle => 'Grade current resource for all students.'
9309: },
9310: { linktext => 'Grade page/folder for one student',
9311: url => $url1d,
9312: permission => 'F',
9313: icon => 'grade_PageFolder.png',
9314: linktitle => 'Grade all resources in current page/sequence/folder for one student.'
9315: },
9316: { linktext => 'Download submissions',
9317: url => $url1e,
9318: permission => 'F',
9319: icon => 'download_sub.png',
9320: linktitle => 'Download all students submissions.'
9321: }]},
9322: { categorytitle=>'Automated Grading',
9323: items =>[
9324:
9325: { linktext => 'Upload Scores',
9326: url => $url2,
9327: permission => 'F',
9328: icon => 'uploadscores.png',
9329: linktitle => 'Specify a file containing the class scores for current resource.'
9330: },
9331: { linktext => 'Process Clicker',
9332: url => $url3,
9333: permission => 'F',
9334: icon => 'addClickerInfoFile.png',
9335: linktitle => 'Specify a file containing the clicker information for this resource.'
9336: },
9337: { linktext => 'Grade/Manage/Review Bubblesheets',
9338: url => $url4,
9339: permission => 'F',
9340: icon => 'bubblesheet.png',
9341: linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
9342: },
9343: { linktext => 'Verify Receipt Number',
9344: url => $url5,
9345: permission => 'F',
9346: icon => 'receipt_number.png',
9347: linktitle => 'Verify a system-generated receipt number for correct problem solution.'
9348: }
9349:
9350: ]
9351: });
9352:
9353: # Create the menu
9354: my $Str;
9355: $Str .= '<form method="post" action="" name="gradingMenu">';
9356: $Str .= '<input type="hidden" name="command" value="" />'.
9357: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
9358:
9359: $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
9360: return $Str;
9361: }
9362:
9363:
9364: sub ungraded {
9365: my ($request)=@_;
9366: &submit_options($request);
9367: }
9368:
9369: sub submit_options_sequence {
9370: my ($request,$symb) = @_;
9371: if (!$symb) {return '';}
9372: &commonJSfunctions($request);
9373: my $result;
9374:
9375: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
9376: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
9377: $result.=&selectfield(0).
9378: '<input type="hidden" name="command" value="pickStudentPage" />
9379: <div>
9380: <input type="submit" value="'.&mt('Next').' →" />
9381: </div>
9382: </div>
9383: </form>';
9384: return $result;
9385: }
9386:
9387: sub submit_options_table {
9388: my ($request,$symb) = @_;
9389: if (!$symb) {return '';}
9390: &commonJSfunctions($request);
9391: my $result;
9392:
9393: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
9394: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
9395:
9396: $result.=&selectfield(0).
9397: '<input type="hidden" name="command" value="viewgrades" />
9398: <div>
9399: <input type="submit" value="'.&mt('Next').' →" />
9400: </div>
9401: </div>
9402: </form>';
9403: return $result;
9404: }
9405:
9406: sub submit_options_download {
9407: my ($request,$symb) = @_;
9408: if (!$symb) {return '';}
9409:
9410: &commonJSfunctions($request);
9411:
9412: my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
9413: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
9414: $result.='
9415: <h2>
9416: '.&mt('Select Students for Which to Download Submissions').'
9417: </h2>'.&selectfield(1).'
9418: <input type="hidden" name="command" value="downloadfileslink" />
9419: <input type="submit" value="'.&mt('Next').' →" />
9420: </div>
9421: </div>
9422:
9423:
9424: </form>';
9425: return $result;
9426: }
9427:
9428: #--- Displays the submissions first page -------
9429: sub submit_options {
9430: my ($request,$symb) = @_;
9431: if (!$symb) {return '';}
9432:
9433: &commonJSfunctions($request);
9434: my $result;
9435:
9436: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
9437: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
9438: $result.=&selectfield(1).'
9439: <input type="hidden" name="command" value="submission" />
9440: <input type="submit" value="'.&mt('Next').' →" />
9441: </div>
9442: </div>
9443:
9444:
9445: </form>';
9446: return $result;
9447: }
9448:
9449: sub selectfield {
9450: my ($full)=@_;
9451: my %options =
9452: (&Apache::lonlocal::texthash(
9453: 'yes' => 'with submissions',
9454: 'queued' => 'in grading queue',
9455: 'graded' => 'with ungraded submissions',
9456: 'incorrect' => 'with incorrect submissions',
9457: 'all' => 'with any status'),
9458: 'select_form_order' => ['yes','queued','graded','incorrect','all']);
9459: my $result='<div class="LC_columnSection">
9460:
9461: <fieldset>
9462: <legend>
9463: '.&mt('Sections').'
9464: </legend>
9465: '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
9466: </fieldset>
9467:
9468: <fieldset>
9469: <legend>
9470: '.&mt('Groups').'
9471: </legend>
9472: '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
9473: </fieldset>
9474:
9475: <fieldset>
9476: <legend>
9477: '.&mt('Access Status').'
9478: </legend>
9479: '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
9480: </fieldset>';
9481: if ($full) {
9482: $result.='
9483: <fieldset>
9484: <legend>
9485: '.&mt('Submission Status').'
9486: </legend>'.
9487: &Apache::loncommon::select_form('all','submitonly',\%options).
9488: '</fieldset>';
9489: }
9490: $result.='</div><br />';
9491: return $result;
9492: }
9493:
9494: sub reset_perm {
9495: undef(%perm);
9496: }
9497:
9498: sub init_perm {
9499: &reset_perm();
9500: foreach my $test_perm ('vgr','mgr','opa') {
9501:
9502: my $scope = $env{'request.course.id'};
9503: if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
9504:
9505: $scope .= '/'.$env{'request.course.sec'};
9506: if ( $perm{$test_perm}=
9507: &Apache::lonnet::allowed($test_perm,$scope)) {
9508: $perm{$test_perm.'_section'}=$env{'request.course.sec'};
9509: } else {
9510: delete($perm{$test_perm});
9511: }
9512: }
9513: }
9514: }
9515:
9516: sub init_old_essays {
9517: my ($symb,$apath,$adom,$aname) = @_;
9518: if ($symb ne '') {
9519: my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
9520: if (keys(%essays) > 0) {
9521: $old_essays{$symb} = \%essays;
9522: }
9523: }
9524: return;
9525: }
9526:
9527: sub reset_old_essays {
9528: undef(%old_essays);
9529: }
9530:
9531: sub gather_clicker_ids {
9532: my %clicker_ids;
9533:
9534: my $classlist = &Apache::loncoursedata::get_classlist();
9535:
9536: # Set up a couple variables.
9537: my $username_idx = &Apache::loncoursedata::CL_SNAME();
9538: my $domain_idx = &Apache::loncoursedata::CL_SDOM();
9539: my $status_idx = &Apache::loncoursedata::CL_STATUS();
9540:
9541: foreach my $student (keys(%$classlist)) {
9542: if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
9543: my $username = $classlist->{$student}->[$username_idx];
9544: my $domain = $classlist->{$student}->[$domain_idx];
9545: my $clickers =
9546: (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
9547: foreach my $id (split(/\,/,$clickers)) {
9548: $id=~s/^[\#0]+//;
9549: $id=~s/[\-\:]//g;
9550: if (exists($clicker_ids{$id})) {
9551: $clicker_ids{$id}.=','.$username.':'.$domain;
9552: } else {
9553: $clicker_ids{$id}=$username.':'.$domain;
9554: }
9555: }
9556: }
9557: return %clicker_ids;
9558: }
9559:
9560: sub gather_adv_clicker_ids {
9561: my %clicker_ids;
9562: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
9563: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
9564: my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
9565: foreach my $element (sort(keys(%coursepersonnel))) {
9566: foreach my $person (split(/\,/,$coursepersonnel{$element})) {
9567: my ($puname,$pudom)=split(/\:/,$person);
9568: my $clickers =
9569: (&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
9570: foreach my $id (split(/\,/,$clickers)) {
9571: $id=~s/^[\#0]+//;
9572: $id=~s/[\-\:]//g;
9573: if (exists($clicker_ids{$id})) {
9574: $clicker_ids{$id}.=','.$puname.':'.$pudom;
9575: } else {
9576: $clicker_ids{$id}=$puname.':'.$pudom;
9577: }
9578: }
9579: }
9580: }
9581: return %clicker_ids;
9582: }
9583:
9584: sub clicker_grading_parameters {
9585: return ('gradingmechanism' => 'scalar',
9586: 'upfiletype' => 'scalar',
9587: 'specificid' => 'scalar',
9588: 'pcorrect' => 'scalar',
9589: 'pincorrect' => 'scalar');
9590: }
9591:
9592: sub process_clicker {
9593: my ($r,$symb)=@_;
9594: if (!$symb) {return '';}
9595: my $result=&checkforfile_js();
9596: $result.=&Apache::loncommon::start_data_table().
9597: &Apache::loncommon::start_data_table_header_row().
9598: '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
9599: &Apache::loncommon::end_data_table_header_row().
9600: &Apache::loncommon::start_data_table_row()."<td>\n";
9601: # Attempt to restore parameters from last session, set defaults if not present
9602: my %Saveable_Parameters=&clicker_grading_parameters();
9603: &Apache::loncommon::restore_course_settings('grades_clicker',
9604: \%Saveable_Parameters);
9605: if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
9606: if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
9607: if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
9608: if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
9609:
9610: my %checked;
9611: foreach my $gradingmechanism ('attendance','personnel','specific','given') {
9612: if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
9613: $checked{$gradingmechanism}=' checked="checked"';
9614: }
9615: }
9616:
9617: my $upload=&mt("Evaluate File");
9618: my $type=&mt("Type");
9619: my $attendance=&mt("Award points just for participation");
9620: my $personnel=&mt("Correctness determined from response by course personnel");
9621: my $specific=&mt("Correctness determined from response with clicker ID(s)");
9622: my $given=&mt("Correctness determined from given list of answers").' '.
9623: '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
9624: my $pcorrect=&mt("Percentage points for correct solution");
9625: my $pincorrect=&mt("Percentage points for incorrect solution");
9626: my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
9627: {'iclicker' => 'i>clicker',
9628: 'interwrite' => 'interwrite PRS',
9629: 'turning' => 'Turning Technologies'});
9630: $symb = &Apache::lonenc::check_encrypt($symb);
9631: $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
9632: function sanitycheck() {
9633: // Accept only integer percentages
9634: document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
9635: document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
9636: // Find out grading choice
9637: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
9638: if (document.forms.gradesupload.gradingmechanism[i].checked) {
9639: gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
9640: }
9641: }
9642: // By default, new choice equals user selection
9643: newgradingchoice=gradingchoice;
9644: // Not good to give more points for false answers than correct ones
9645: if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
9646: document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
9647: }
9648: // If new choice is attendance only, and old choice was correctness-based, restore defaults
9649: if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
9650: document.forms.gradesupload.pcorrect.value=100;
9651: document.forms.gradesupload.pincorrect.value=100;
9652: }
9653: // If the values are different, cannot be attendance only
9654: if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
9655: (gradingchoice=='attendance')) {
9656: newgradingchoice='personnel';
9657: }
9658: // Change grading choice to new one
9659: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
9660: if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
9661: document.forms.gradesupload.gradingmechanism[i].checked=true;
9662: } else {
9663: document.forms.gradesupload.gradingmechanism[i].checked=false;
9664: }
9665: }
9666: // Remember the old state
9667: document.forms.gradesupload.waschecked.value=newgradingchoice;
9668: }
9669: ENDUPFORM
9670: $result.= <<ENDUPFORM;
9671: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
9672: <input type="hidden" name="symb" value="$symb" />
9673: <input type="hidden" name="command" value="processclickerfile" />
9674: <input type="file" name="upfile" size="50" />
9675: <br /><label>$type: $selectform</label>
9676: ENDUPFORM
9677: $result.='</td>'.&Apache::loncommon::end_data_table_row().
9678: &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
9679: <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
9680: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
9681: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
9682: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
9683: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
9684: <br />
9685: <input type="text" name="givenanswer" size="50" />
9686: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
9687: ENDGRADINGFORM
9688: $result.='</td>'.&Apache::loncommon::end_data_table_row().
9689: &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
9690: <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
9691: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
9692: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
9693: </form>'
9694: ENDPERCFORM
9695: $result.='</td>'.
9696: &Apache::loncommon::end_data_table_row().
9697: &Apache::loncommon::end_data_table();
9698: return $result;
9699: }
9700:
9701: sub process_clicker_file {
9702: my ($r,$symb)=@_;
9703: if (!$symb) {return '';}
9704:
9705: my %Saveable_Parameters=&clicker_grading_parameters();
9706: &Apache::loncommon::store_course_settings('grades_clicker',
9707: \%Saveable_Parameters);
9708: my $result='';
9709: if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
9710: $result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
9711: return $result;
9712: }
9713: if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
9714: $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
9715: return $result;
9716: }
9717: my $foundgiven=0;
9718: if ($env{'form.gradingmechanism'} eq 'given') {
9719: $env{'form.givenanswer'}=~s/^\s*//gs;
9720: $env{'form.givenanswer'}=~s/\s*$//gs;
9721: $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
9722: $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
9723: my @answers=split(/\,/,$env{'form.givenanswer'});
9724: $foundgiven=$#answers+1;
9725: }
9726: my %clicker_ids=&gather_clicker_ids();
9727: my %correct_ids;
9728: if ($env{'form.gradingmechanism'} eq 'personnel') {
9729: %correct_ids=&gather_adv_clicker_ids();
9730: }
9731: if ($env{'form.gradingmechanism'} eq 'specific') {
9732: foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
9733: $correct_id=~tr/a-z/A-Z/;
9734: $correct_id=~s/\s//gs;
9735: $correct_id=~s/^[\#0]+//;
9736: $correct_id=~s/[\-\:]//g;
9737: if ($correct_id) {
9738: $correct_ids{$correct_id}='specified';
9739: }
9740: }
9741: }
9742: if ($env{'form.gradingmechanism'} eq 'attendance') {
9743: $result.=&mt('Score based on attendance only');
9744: } elsif ($env{'form.gradingmechanism'} eq 'given') {
9745: $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
9746: } else {
9747: my $number=0;
9748: $result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
9749: foreach my $id (sort(keys(%correct_ids))) {
9750: $result.='<br /><tt>'.$id.'</tt> - ';
9751: if ($correct_ids{$id} eq 'specified') {
9752: $result.=&mt('specified');
9753: } else {
9754: my ($uname,$udom)=split(/\:/,$correct_ids{$id});
9755: $result.=&Apache::loncommon::plainname($uname,$udom);
9756: }
9757: $number++;
9758: }
9759: $result.="</p>\n";
9760: if ($number==0) {
9761: $result .=
9762: &Apache::lonhtmlcommon::confirm_success(
9763: &mt('No IDs found to determine correct answer'),1);
9764: return $result;
9765: }
9766: }
9767: if (length($env{'form.upfile'}) < 2) {
9768: $result .=
9769: &Apache::lonhtmlcommon::confirm_success(
9770: &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
9771: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
9772: return $result;
9773: }
9774:
9775: # Were able to get all the info needed, now analyze the file
9776:
9777: $result.=&Apache::loncommon::studentbrowser_javascript();
9778: $symb = &Apache::lonenc::check_encrypt($symb);
9779: $result.=&Apache::loncommon::start_data_table().
9780: &Apache::loncommon::start_data_table_header_row().
9781: '<th>'.&mt('Evaluate clicker file').'</th>'.
9782: &Apache::loncommon::end_data_table_header_row().
9783: &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
9784: <td>
9785: <form method="post" action="/adm/grades" name="clickeranalysis">
9786: <input type="hidden" name="symb" value="$symb" />
9787: <input type="hidden" name="command" value="assignclickergrades" />
9788: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
9789: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
9790: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
9791: ENDHEADER
9792: if ($env{'form.gradingmechanism'} eq 'given') {
9793: $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
9794: }
9795: my %responses;
9796: my @questiontitles;
9797: my $errormsg='';
9798: my $number=0;
9799: if ($env{'form.upfiletype'} eq 'iclicker') {
9800: ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
9801: }
9802: if ($env{'form.upfiletype'} eq 'interwrite') {
9803: ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
9804: }
9805: if ($env{'form.upfiletype'} eq 'turning') {
9806: ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
9807: }
9808: $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
9809: '<input type="hidden" name="number" value="'.$number.'" />'.
9810: &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
9811: $env{'form.pcorrect'},$env{'form.pincorrect'}).
9812: '<br />';
9813: if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
9814: $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
9815: return $result;
9816: }
9817: # Remember Question Titles
9818: # FIXME: Possibly need delimiter other than ":"
9819: for (my $i=0;$i<$number;$i++) {
9820: $result.='<input type="hidden" name="question:'.$i.'" value="'.
9821: &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
9822: }
9823: my $correct_count=0;
9824: my $student_count=0;
9825: my $unknown_count=0;
9826: # Match answers with usernames
9827: # FIXME: Possibly need delimiter other than ":"
9828: foreach my $id (keys(%responses)) {
9829: if ($correct_ids{$id}) {
9830: $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
9831: $correct_count++;
9832: } elsif ($clicker_ids{$id}) {
9833: if ($clicker_ids{$id}=~/\,/) {
9834: # More than one user with the same clicker!
9835: $result.="</td>".&Apache::loncommon::end_data_table_row().
9836: &Apache::loncommon::start_data_table_row()."<td>".
9837: &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
9838: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
9839: "<select name='multi".$id."'>";
9840: foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
9841: $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
9842: }
9843: $result.='</select>';
9844: $unknown_count++;
9845: } else {
9846: # Good: found one and only one user with the right clicker
9847: $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
9848: $student_count++;
9849: }
9850: } else {
9851: $result.="</td>".&Apache::loncommon::end_data_table_row().
9852: &Apache::loncommon::start_data_table_row()."<td>".
9853: &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
9854: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
9855: "\n".&mt("Username").": <input type='text' name='uname".$id."' /> ".
9856: "\n".&mt("Domain").": ".
9857: &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).' '.
9858: &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
9859: $unknown_count++;
9860: }
9861: }
9862: $result.='<hr />'.
9863: &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
9864: if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
9865: if ($correct_count==0) {
9866: $errormsg.="Found no correct answers for grading!";
9867: } elsif ($correct_count>1) {
9868: $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
9869: }
9870: }
9871: if ($number<1) {
9872: $errormsg.="Found no questions.";
9873: }
9874: if ($errormsg) {
9875: $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
9876: } else {
9877: $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
9878: }
9879: $result.='</form></td>'.
9880: &Apache::loncommon::end_data_table_row().
9881: &Apache::loncommon::end_data_table();
9882: return $result;
9883: }
9884:
9885: sub iclicker_eval {
9886: my ($questiontitles,$responses)=@_;
9887: my $number=0;
9888: my $errormsg='';
9889: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
9890: my %components=&Apache::loncommon::record_sep($line);
9891: my @entries=map {$components{$_}} (sort(keys(%components)));
9892: if ($entries[0] eq 'Question') {
9893: for (my $i=3;$i<$#entries;$i+=6) {
9894: $$questiontitles[$number]=$entries[$i];
9895: $number++;
9896: }
9897: }
9898: if ($entries[0]=~/^\#/) {
9899: my $id=$entries[0];
9900: my @idresponses;
9901: $id=~s/^[\#0]+//;
9902: for (my $i=0;$i<$number;$i++) {
9903: my $idx=3+$i*6;
9904: $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
9905: push(@idresponses,$entries[$idx]);
9906: }
9907: $$responses{$id}=join(',',@idresponses);
9908: }
9909: }
9910: return ($errormsg,$number);
9911: }
9912:
9913: sub interwrite_eval {
9914: my ($questiontitles,$responses)=@_;
9915: my $number=0;
9916: my $errormsg='';
9917: my $skipline=1;
9918: my $questionnumber=0;
9919: my %idresponses=();
9920: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
9921: my %components=&Apache::loncommon::record_sep($line);
9922: my @entries=map {$components{$_}} (sort(keys(%components)));
9923: if ($entries[1] eq 'Time') { $skipline=0; next; }
9924: if ($entries[1] eq 'Response') { $skipline=1; }
9925: next if $skipline;
9926: if ($entries[0]!=$questionnumber) {
9927: $questionnumber=$entries[0];
9928: $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
9929: $number++;
9930: }
9931: my $id=$entries[4];
9932: $id=~s/^[\#0]+//;
9933: $id=~s/^v\d*\://i;
9934: $id=~s/[\-\:]//g;
9935: $idresponses{$id}[$number]=$entries[6];
9936: }
9937: foreach my $id (keys(%idresponses)) {
9938: $$responses{$id}=join(',',@{$idresponses{$id}});
9939: $$responses{$id}=~s/^\s*\,//;
9940: }
9941: return ($errormsg,$number);
9942: }
9943:
9944: sub turning_eval {
9945: my ($questiontitles,$responses)=@_;
9946: my $number=0;
9947: my $errormsg='';
9948: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
9949: my %components=&Apache::loncommon::record_sep($line);
9950: my @entries=map {$components{$_}} (sort(keys(%components)));
9951: if ($#entries>$number) { $number=$#entries; }
9952: my $id=$entries[0];
9953: my @idresponses;
9954: $id=~s/^[\#0]+//;
9955: unless ($id) { next; }
9956: for (my $idx=1;$idx<=$#entries;$idx++) {
9957: $entries[$idx]=~s/\,/\;/g;
9958: $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
9959: push(@idresponses,$entries[$idx]);
9960: }
9961: $$responses{$id}=join(',',@idresponses);
9962: }
9963: for (my $i=1; $i<=$number; $i++) {
9964: $$questiontitles[$i]=&mt('Question [_1]',$i);
9965: }
9966: return ($errormsg,$number);
9967: }
9968:
9969:
9970: sub assign_clicker_grades {
9971: my ($r,$symb)=@_;
9972: if (!$symb) {return '';}
9973: # See which part we are saving to
9974: my $res_error;
9975: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
9976: if ($res_error) {
9977: return &navmap_errormsg();
9978: }
9979: # FIXME: This should probably look for the first handgradeable part
9980: my $part=$$partlist[0];
9981: # Start screen output
9982: my $result=&Apache::loncommon::start_data_table().
9983: &Apache::loncommon::start_data_table_header_row().
9984: '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
9985: &Apache::loncommon::end_data_table_header_row().
9986: &Apache::loncommon::start_data_table_row().'<td>';
9987: # Get correct result
9988: # FIXME: Possibly need delimiter other than ":"
9989: my @correct=();
9990: my $gradingmechanism=$env{'form.gradingmechanism'};
9991: my $number=$env{'form.number'};
9992: if ($gradingmechanism ne 'attendance') {
9993: foreach my $key (keys(%env)) {
9994: if ($key=~/^form\.correct\:/) {
9995: my @input=split(/\,/,$env{$key});
9996: for (my $i=0;$i<=$#input;$i++) {
9997: if (($correct[$i]) && ($input[$i]) &&
9998: ($correct[$i] ne $input[$i])) {
9999: $result.='<br /><span class="LC_warning">'.
10000: &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
10001: $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
10002: } elsif (($input[$i]) || ($input[$i] eq '0')) {
10003: $correct[$i]=$input[$i];
10004: }
10005: }
10006: }
10007: }
10008: for (my $i=0;$i<$number;$i++) {
10009: if ((!$correct[$i]) && ($correct[$i] ne '0')) {
10010: $result.='<br /><span class="LC_error">'.
10011: &mt('No correct result given for question "[_1]"!',
10012: $env{'form.question:'.$i}).'</span>';
10013: }
10014: }
10015: $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
10016: }
10017: # Start grading
10018: my $pcorrect=$env{'form.pcorrect'};
10019: my $pincorrect=$env{'form.pincorrect'};
10020: my $storecount=0;
10021: my %users=();
10022: foreach my $key (keys(%env)) {
10023: my $user='';
10024: if ($key=~/^form\.student\:(.*)$/) {
10025: $user=$1;
10026: }
10027: if ($key=~/^form\.unknown\:(.*)$/) {
10028: my $id=$1;
10029: if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
10030: $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
10031: } elsif ($env{'form.multi'.$id}) {
10032: $user=$env{'form.multi'.$id};
10033: }
10034: }
10035: if ($user) {
10036: if ($users{$user}) {
10037: $result.='<br /><span class="LC_warning">'.
10038: &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
10039: '</span><br />';
10040: }
10041: $users{$user}=1;
10042: my @answer=split(/\,/,$env{$key});
10043: my $sum=0;
10044: my $realnumber=$number;
10045: for (my $i=0;$i<$number;$i++) {
10046: if ($correct[$i] eq '-') {
10047: $realnumber--;
10048: } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
10049: if ($gradingmechanism eq 'attendance') {
10050: $sum+=$pcorrect;
10051: } elsif ($correct[$i] eq '*') {
10052: $sum+=$pcorrect;
10053: } else {
10054: # We actually grade if correct or not
10055: my $increment=$pincorrect;
10056: # Special case: numerical answer "0"
10057: if ($correct[$i] eq '0') {
10058: if ($answer[$i]=~/^[0\.]+$/) {
10059: $increment=$pcorrect;
10060: }
10061: # General numerical answer, both evaluate to something non-zero
10062: } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
10063: if (1.0*$correct[$i]==1.0*$answer[$i]) {
10064: $increment=$pcorrect;
10065: }
10066: # Must be just alphanumeric
10067: } elsif ($answer[$i] eq $correct[$i]) {
10068: $increment=$pcorrect;
10069: }
10070: $sum+=$increment;
10071: }
10072: }
10073: }
10074: my $ave=$sum/(100*$realnumber);
10075: # Store
10076: my ($username,$domain)=split(/\:/,$user);
10077: my %grades=();
10078: $grades{"resource.$part.solved"}='correct_by_override';
10079: $grades{"resource.$part.awarded"}=$ave;
10080: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
10081: my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
10082: $env{'request.course.id'},
10083: $domain,$username);
10084: if ($returncode ne 'ok') {
10085: $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
10086: } else {
10087: $storecount++;
10088: }
10089: }
10090: }
10091: # We are done
10092: $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
10093: '</td>'.
10094: &Apache::loncommon::end_data_table_row().
10095: &Apache::loncommon::end_data_table();
10096: return $result;
10097: }
10098:
10099: sub navmap_errormsg {
10100: return '<div class="LC_error">'.
10101: &mt('An error occurred retrieving information about resources in the course.').'<br />'.
10102: &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>').
10103: '</div>';
10104: }
10105:
10106: sub startpage {
10107: my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
10108: if ($nomenu) {
10109: $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
10110: } else {
10111: unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
10112: $r->print(&Apache::loncommon::start_page('Grading',$js,
10113: {'bread_crumbs' => $crumbs}));
10114: &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
10115: }
10116: unless ($nodisplayflag) {
10117: $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
10118: }
10119: }
10120:
10121: sub select_problem {
10122: my ($r)=@_;
10123: $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
10124: $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
10125: $r->print('<input type="hidden" name="command" value="gradingmenu" />');
10126: $r->print('<input type="submit" value="'.&mt('Next').' →" /></form>');
10127: }
10128:
10129: sub handler {
10130: my $request=$_[0];
10131: &reset_caches();
10132: if ($request->header_only) {
10133: &Apache::loncommon::content_type($request,'text/html');
10134: $request->send_http_header;
10135: return OK;
10136: }
10137: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
10138:
10139: # see what command we need to execute
10140:
10141: my @commands=&Apache::loncommon::get_env_multiple('form.command');
10142: my $command=$commands[0];
10143:
10144: &init_perm();
10145: if (!$env{'request.course.id'}) {
10146: unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
10147: ($command =~ /^scantronupload/)) {
10148: # Not in a course.
10149: $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
10150: return HTTP_NOT_ACCEPTABLE;
10151: }
10152: } elsif (!%perm) {
10153: $request->internal_redirect('/adm/quickgrades');
10154: return OK;
10155: }
10156: &Apache::loncommon::content_type($request,'text/html');
10157: $request->send_http_header;
10158:
10159: if ($#commands > 0) {
10160: &Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
10161: }
10162:
10163: # see what the symb is
10164:
10165: my $symb=$env{'form.symb'};
10166: unless ($symb) {
10167: (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
10168: $symb=&Apache::lonnet::symbread($url);
10169: }
10170: &Apache::lonenc::check_decrypt(\$symb);
10171:
10172: $ssi_error = 0;
10173: if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
10174: #
10175: # Not called from a resource, but inside a course
10176: #
10177: &startpage($request,undef,[],1,1);
10178: &select_problem($request);
10179: } else {
10180: if ($command eq 'submission' && $perm{'vgr'}) {
10181: my ($stuvcurrent,$stuvdisp,$versionform,$js);
10182: if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
10183: ($stuvcurrent,$stuvdisp,$versionform,$js) =
10184: &choose_task_version_form($symb,$env{'form.student'},
10185: $env{'form.userdom'});
10186: }
10187: &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
10188: if ($versionform) {
10189: $request->print($versionform);
10190: }
10191: $request->print('<br clear="all" />');
10192: ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
10193: } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
10194: my ($stuvcurrent,$stuvdisp,$versionform,$js) =
10195: &choose_task_version_form($symb,$env{'form.student'},
10196: $env{'form.userdom'},
10197: $env{'form.inhibitmenu'});
10198: &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
10199: if ($versionform) {
10200: $request->print($versionform);
10201: }
10202: $request->print('<br clear="all" />');
10203: $request->print(&show_previous_task_version($request,$symb));
10204: } elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
10205: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10206: {href=>'',text=>'Select student'}],1,1);
10207: &pickStudentPage($request,$symb);
10208: } elsif ($command eq 'displayPage' && $perm{'vgr'}) {
10209: &startpage($request,$symb,
10210: [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10211: {href=>'',text=>'Select student'},
10212: {href=>'',text=>'Grade student'}],1,1);
10213: &displayPage($request,$symb);
10214: } elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
10215: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10216: {href=>'',text=>'Select student'},
10217: {href=>'',text=>'Grade student'},
10218: {href=>'',text=>'Store grades'}],1,1);
10219: &updateGradeByPage($request,$symb);
10220: } elsif ($command eq 'processGroup' && $perm{'vgr'}) {
10221: &startpage($request,$symb,[{href=>'',text=>'...'},
10222: {href=>'',text=>'Modify grades'}]);
10223: &processGroup($request,$symb);
10224: } elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
10225: &startpage($request,$symb);
10226: $request->print(&grading_menu($request,$symb));
10227: } elsif ($command eq 'individual' && $perm{'vgr'}) {
10228: &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
10229: $request->print(&submit_options($request,$symb));
10230: } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
10231: &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
10232: $request->print(&listStudents($request,$symb,'graded'));
10233: } elsif ($command eq 'table' && $perm{'vgr'}) {
10234: &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
10235: $request->print(&submit_options_table($request,$symb));
10236: } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
10237: &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
10238: $request->print(&submit_options_sequence($request,$symb));
10239: } elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
10240: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
10241: $request->print(&viewgrades($request,$symb));
10242: } elsif ($command eq 'handgrade' && $perm{'mgr'}) {
10243: &startpage($request,$symb,[{href=>'',text=>'...'},
10244: {href=>'',text=>'Store grades'}]);
10245: $request->print(&processHandGrade($request,$symb));
10246: } elsif ($command eq 'editgrades' && $perm{'mgr'}) {
10247: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
10248: {href=>&href_symb_cmd($symb,'viewgrades').'&group=all§ion=all&Status=Active',
10249: text=>"Modify grades"},
10250: {href=>'', text=>"Store grades"}]);
10251: $request->print(&editgrades($request,$symb));
10252: } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
10253: &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
10254: $request->print(&initialverifyreceipt($request,$symb));
10255: } elsif ($command eq 'verify' && $perm{'vgr'}) {
10256: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
10257: {href=>'',text=>'Verification Result'}]);
10258: $request->print(&verifyreceipt($request,$symb));
10259: } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
10260: &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
10261: $request->print(&process_clicker($request,$symb));
10262: } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
10263: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
10264: {href=>'', text=>'Process clicker file'}]);
10265: $request->print(&process_clicker_file($request,$symb));
10266: } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
10267: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
10268: {href=>'', text=>'Process clicker file'},
10269: {href=>'', text=>'Store grades'}]);
10270: $request->print(&assign_clicker_grades($request,$symb));
10271: } elsif ($command eq 'csvform' && $perm{'mgr'}) {
10272: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10273: $request->print(&upcsvScores_form($request,$symb));
10274: } elsif ($command eq 'csvupload' && $perm{'mgr'}) {
10275: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10276: $request->print(&csvupload($request,$symb));
10277: } elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
10278: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10279: $request->print(&csvuploadmap($request,$symb));
10280: } elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
10281: if ($env{'form.associate'} ne 'Reverse Association') {
10282: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10283: $request->print(&csvuploadoptions($request,$symb));
10284: } else {
10285: if ( $env{'form.upfile_associate'} ne 'reverse' ) {
10286: $env{'form.upfile_associate'} = 'reverse';
10287: } else {
10288: $env{'form.upfile_associate'} = 'forward';
10289: }
10290: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10291: $request->print(&csvuploadmap($request,$symb));
10292: }
10293: } elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
10294: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10295: $request->print(&csvuploadassign($request,$symb));
10296: } elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
10297: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10298: $request->print(&scantron_selectphase($request,undef,$symb));
10299: } elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
10300: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10301: $request->print(&scantron_do_warning($request,$symb));
10302: } elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
10303: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10304: $request->print(&scantron_validate_file($request,$symb));
10305: } elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
10306: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10307: $request->print(&scantron_process_students($request,$symb));
10308: } elsif ($command eq 'scantronupload' &&
10309: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10310: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10311: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10312: $request->print(&scantron_upload_scantron_data($request,$symb));
10313: } elsif ($command eq 'scantronupload_save' &&
10314: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10315: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10316: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10317: $request->print(&scantron_upload_scantron_data_save($request,$symb));
10318: } elsif ($command eq 'scantron_download' &&
10319: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
10320: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10321: $request->print(&scantron_download_scantron_data($request,$symb));
10322: } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
10323: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10324: $request->print(&checkscantron_results($request,$symb));
10325: } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
10326: &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
10327: $request->print(&submit_options_download($request,$symb));
10328: } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
10329: &startpage($request,$symb,
10330: [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
10331: {href=>'', text=>'Download submissions'}]);
10332: &submit_download_link($request,$symb);
10333: } elsif ($command) {
10334: &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
10335: $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
10336: }
10337: }
10338: if ($ssi_error) {
10339: &ssi_print_error($request);
10340: }
10341: if ($env{'form.inhibitmenu'}) {
10342: $request->print(&Apache::loncommon::end_page());
10343: } else {
10344: &Apache::lonquickgrades::endGradeScreen($request);
10345: }
10346: &reset_caches();
10347: return OK;
10348: }
10349:
10350: 1;
10351:
10352: __END__;
10353:
10354:
10355: =head1 NAME
10356:
10357: Apache::grades
10358:
10359: =head1 SYNOPSIS
10360:
10361: Handles the viewing of grades.
10362:
10363: This is part of the LearningOnline Network with CAPA project
10364: described at http://www.lon-capa.org.
10365:
10366: =head1 OVERVIEW
10367:
10368: Do an ssi with retries:
10369: While I'd love to factor out this with the version in lonprintout,
10370: 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
10371: I'm not quite ready to invent (e.g. an ssi_with_retry object).
10372:
10373: At least the logic that drives this has been pulled out into loncommon.
10374:
10375:
10376:
10377: ssi_with_retries - Does the server side include of a resource.
10378: if the ssi call returns an error we'll retry it up to
10379: the number of times requested by the caller.
10380: If we still have a problem, no text is appended to the
10381: output and we set some global variables.
10382: to indicate to the caller an SSI error occurred.
10383: All of this is supposed to deal with the issues described
10384: in LON-CAPA BZ 5631 see:
10385: http://bugs.lon-capa.org/show_bug.cgi?id=5631
10386: by informing the user that this happened.
10387:
10388: Parameters:
10389: resource - The resource to include. This is passed directly, without
10390: interpretation to lonnet::ssi.
10391: form - The form hash parameters that guide the interpretation of the resource
10392:
10393: retries - Number of retries allowed before giving up completely.
10394: Returns:
10395: On success, returns the rendered resource identified by the resource parameter.
10396: Side Effects:
10397: The following global variables can be set:
10398: ssi_error - If an unrecoverable error occurred this becomes true.
10399: It is up to the caller to initialize this to false
10400: if desired.
10401: ssi_error_resource - If an unrecoverable error occurred, this is the value
10402: of the resource that could not be rendered by the ssi
10403: call.
10404: ssi_error_message - The error string fetched from the ssi response
10405: in the event of an error.
10406:
10407:
10408: =head1 HANDLER SUBROUTINE
10409:
10410: ssi_with_retries()
10411:
10412: =head1 SUBROUTINES
10413:
10414: =over
10415:
10416: =head1 Routines to display previous version of a Task for a specific student
10417:
10418: Tasks are graded pass/fail. Students who have yet to pass a particular Task
10419: can receive another opportunity. Access to tasks is slot-based. If a slot
10420: requires a proctor to check-in the student, a new version of the Task will
10421: be created when the student is checked in to the new opportunity.
10422:
10423: If a particular student has tried two or more versions of a particular task,
10424: the submission screen provides a user with vgr privileges (e.g., a Course
10425: Coordinator) the ability to display a previous version worked on by the
10426: student. By default, the current version is displayed. If a previous version
10427: has been selected for display, submission data are only shown that pertain
10428: to that particular version, and the interface to submit grades is not shown.
10429:
10430: =over 4
10431:
10432: =item show_previous_task_version()
10433:
10434: Displays a specified version of a student's Task, as the student sees it.
10435:
10436: Inputs: 2
10437: request - request object
10438: symb - unique symb for current instance of resource
10439:
10440: Output: None.
10441:
10442: Side Effects: calls &show_problem() to print version of Task, with
10443: version contained in form item: $env{'form.previousversion'}
10444:
10445: =item choose_task_version_form()
10446:
10447: Displays a web form used to select which version of a student's view of a
10448: Task should be displayed. Either launches a pop-up window, or replaces
10449: content in existing pop-up, or replaces page in main window.
10450:
10451: Inputs: 4
10452: symb - unique symb for current instance of resource
10453: uname - username of student
10454: udom - domain of student
10455: nomenu - 1 if display is in a pop-up window, and hence no menu
10456: breadcrumbs etc., are displayed
10457:
10458: Output: 4
10459: current - student's current version
10460: displayed - student's version being displayed
10461: result - scalar containing HTML for web form used to switch to
10462: a different version (or a link to close window, if pop-up).
10463: js - javascript for processing selection in versions web form
10464:
10465: Side Effects: None.
10466:
10467: =item previous_display_javascript()
10468:
10469: Inputs: 2
10470: nomenu - 1 if display is in a pop-up window, and hence no menu
10471: breadcrumbs etc., are displayed.
10472: current - student's current version number.
10473:
10474: Output: 1
10475: js - javascript for processing selection in versions web form.
10476:
10477: Side Effects: None.
10478:
10479: =back
10480:
10481: =head1 Routines to process bubblesheet data.
10482:
10483: =over 4
10484:
10485: =item scantron_get_correction() :
10486:
10487: Builds the interface screen to interact with the operator to fix a
10488: specific error condition in a specific scanline
10489:
10490: Arguments:
10491: $r - Apache request object
10492: $i - number of the current scanline
10493: $scan_record - hash ref as returned from &scantron_parse_scanline()
10494: $scan_config - hash ref as returned from &get_scantron_config()
10495: $line - full contents of the current scanline
10496: $error - error condition, valid values are
10497: 'incorrectCODE', 'duplicateCODE',
10498: 'doublebubble', 'missingbubble',
10499: 'duplicateID', 'incorrectID'
10500: $arg - extra information needed
10501: For errors:
10502: - duplicateID - paper number that this studentID was seen before on
10503: - duplicateCODE - array ref of the paper numbers this CODE was
10504: seen on before
10505: - incorrectCODE - current incorrect CODE
10506: - doublebubble - array ref of the bubble lines that have double
10507: bubble errors
10508: - missingbubble - array ref of the bubble lines that have missing
10509: bubble errors
10510:
10511: $randomorder - True if exam folder has randomorder set
10512: $randompick - True if exam folder has randompick set
10513: $respnumlookup - Reference to HASH mapping question numbers in bubble lines
10514: for current line to question number used for same question
10515: in "Master Seqence" (as seen by Course Coordinator).
10516: $startline - Reference to hash where key is question number (0 is first)
10517: and value is number of first bubble line for current student
10518: or code-based randompick and/or randomorder.
10519:
10520:
10521:
10522: =item scantron_get_maxbubble() :
10523:
10524: Arguments:
10525: $nav_error - Reference to scalar which is a flag to indicate a
10526: failure to retrieve a navmap object.
10527: if $nav_error is set to 1 by scantron_get_maxbubble(), the
10528: calling routine should trap the error condition and display the warning
10529: found in &navmap_errormsg().
10530:
10531: $scantron_config - Reference to bubblesheet format configuration hash.
10532:
10533: Returns the maximum number of bubble lines that are expected to
10534: occur. Does this by walking the selected sequence rendering the
10535: resource and then checking &Apache::lonxml::get_problem_counter()
10536: for what the current value of the problem counter is.
10537:
10538: Caches the results to $env{'form.scantron_maxbubble'},
10539: $env{'form.scantron.bubble_lines.n'},
10540: $env{'form.scantron.first_bubble_line.n'} and
10541: $env{"form.scantron.sub_bubblelines.n"}
10542: which are the total number of bubble lines, the number of bubble
10543: lines for response n and number of the first bubble line for response n,
10544: and a comma separated list of numbers of bubble lines for sub-questions
10545: (for optionresponse, matchresponse, and rankresponse items), for response n.
10546:
10547:
10548: =item scantron_validate_missingbubbles() :
10549:
10550: Validates all scanlines in the selected file to not have any
10551: answers that don't have bubbles that have not been verified
10552: to be bubble free.
10553:
10554: =item scantron_process_students() :
10555:
10556: Routine that does the actual grading of the bubblesheet information.
10557:
10558: The parsed scanline hash is added to %env
10559:
10560: Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
10561: foreach resource , with the form data of
10562:
10563: 'submitted' =>'scantron'
10564: 'grade_target' =>'grade',
10565: 'grade_username'=> username of student
10566: 'grade_domain' => domain of student
10567: 'grade_courseid'=> of course
10568: 'grade_symb' => symb of resource to grade
10569:
10570: This triggers a grading pass. The problem grading code takes care
10571: of converting the bubbled letter information (now in %env) into a
10572: valid submission.
10573:
10574: =item scantron_upload_scantron_data() :
10575:
10576: Creates the screen for adding a new bubblesheet data file to a course.
10577:
10578: =item scantron_upload_scantron_data_save() :
10579:
10580: Adds a provided bubble information data file to the course if user
10581: has the correct privileges to do so.
10582:
10583: =item valid_file() :
10584:
10585: Validates that the requested bubble data file exists in the course.
10586:
10587: =item scantron_download_scantron_data() :
10588:
10589: Shows a list of the three internal files (original, corrected,
10590: skipped) for a specific bubblesheet data file that exists in the
10591: course.
10592:
10593: =item scantron_validate_ID() :
10594:
10595: Validates all scanlines in the selected file to not have any
10596: invalid or underspecified student/employee IDs
10597:
10598: =item navmap_errormsg() :
10599:
10600: Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
10601: Should be called whenever the request to instantiate a navmap object fails.
10602:
10603: =back
10604:
10605: =back
10606:
10607: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>