File:
[LON-CAPA] /
loncom /
homework /
grades.pm
Revision
1.574:
download - view:
text,
annotated -
select for diffs
Thu May 14 14:24:07 2009 UTC (15 years, 3 months ago) by
bisitz
Branches:
MAIN
CVS tags:
version_2_9_X,
HEAD
Don't translate separator character between and domain.
Advantages: No need to change the translation files, if...
- different separator character should be used
- different output is wanted, e.g. just username, plainname, both, etc.
- different style should be used for output
(work in progress to make this even more flexible by introducing a global function usernamewrapper)
1: # The LearningOnline Network with CAPA
2: # The LON-CAPA Grading handler
3: #
4: # $Id: grades.pm,v 1.574 2009/05/14 14:24:07 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);
44: use Apache::lonlocal;
45: use Apache::lonenc;
46: use String::Similarity;
47: use LONCAPA;
48:
49: use POSIX qw(floor);
50:
51:
52:
53: my %perm=();
54:
55: # These variables are used to recover from ssi errors
56:
57: my $ssi_retries = 5;
58: my $ssi_error;
59: my $ssi_error_resource;
60: my $ssi_error_message;
61:
62:
63: sub ssi_with_retries {
64: my ($resource, $retries, %form) = @_;
65: my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
66: if ($response->is_error) {
67: $ssi_error = 1;
68: $ssi_error_resource = $resource;
69: $ssi_error_message = $response->code . " " . $response->message;
70: }
71:
72: return $content;
73:
74: }
75: #
76: # Prodcuces an ssi retry failure error message to the user:
77: #
78:
79: sub ssi_print_error {
80: my ($r) = @_;
81: my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
82: $r->print('
83: <br />
84: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
85: <p>
86: '.&mt('Unable to retrieve a resource from a server:').'<br />
87: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
88: '.&mt('Error:').' '.$ssi_error_message.'
89: </p>
90: <p>'.
91: &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 />'.
92: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
93: '</p>');
94: return;
95: }
96:
97: #
98: # --- Retrieve the parts from the metadata file.---
99: sub getpartlist {
100: my ($symb) = @_;
101:
102: my $navmap = Apache::lonnavmaps::navmap->new();
103: my $res = $navmap->getBySymb($symb);
104: my $partlist = $res->parts();
105: my $url = $res->src();
106: my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
107:
108: my @stores;
109: foreach my $part (@{ $partlist }) {
110: foreach my $key (@metakeys) {
111: if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
112: }
113: }
114: return @stores;
115: }
116:
117: # --- Get the symbolic name of a problem and the url
118: sub get_symb {
119: my ($request,$silent) = @_;
120: (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
121: my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
122: if ($symb eq '') {
123: if (!$silent) {
124: $request->print("Unable to handle ambiguous references:$url:.");
125: return ();
126: }
127: }
128: &Apache::lonenc::check_decrypt(\$symb);
129: return ($symb);
130: }
131:
132: #--- Format fullname, username:domain if different for display
133: #--- Use anywhere where the student names are listed
134: sub nameUserString {
135: my ($type,$fullname,$uname,$udom) = @_;
136: if ($type eq 'header') {
137: return '<b> '.&mt('Fullname').' </b><span class="LC_internal_info">('.&mt('Username').')</span>';
138: } else {
139: return ' '.$fullname.'<span class="LC_internal_info"> ('.$uname.
140: ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
141: }
142: }
143:
144: #--- Get the partlist and the response type for a given problem. ---
145: #--- Indicate if a response type is coded handgraded or not. ---
146: sub response_type {
147: my ($symb) = shift;
148:
149: my $navmap = Apache::lonnavmaps::navmap->new();
150: my $res = $navmap->getBySymb($symb);
151: my $partlist = $res->parts();
152: my %vPart =
153: map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
154: my (%response_types,%handgrade);
155: foreach my $part (@{ $partlist }) {
156: next if (%vPart && !exists($vPart{$part}));
157:
158: my @types = $res->responseType($part);
159: my @ids = $res->responseIds($part);
160: for (my $i=0; $i < scalar(@ids); $i++) {
161: $response_types{$part}{$ids[$i]} = $types[$i];
162: $handgrade{$part.'_'.$ids[$i]} =
163: &Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
164: '.handgrade',$symb);
165: }
166: }
167: return ($partlist,\%handgrade,\%response_types);
168: }
169:
170: sub flatten_responseType {
171: my ($responseType) = @_;
172: my @part_response_id =
173: map {
174: my $part = $_;
175: map {
176: [$part,$_]
177: } sort(keys(%{ $responseType->{$part} }));
178: } sort(keys(%$responseType));
179: return @part_response_id;
180: }
181:
182: sub get_display_part {
183: my ($partID,$symb)=@_;
184: my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
185: if (defined($display) and $display ne '') {
186: $display.= " (<span class=\"LC_internal_info\">id $partID</span>)";
187: } else {
188: $display=$partID;
189: }
190: return $display;
191: }
192:
193: #--- Show resource title
194: #--- and parts and response type
195: sub showResourceInfo {
196: my ($symb,$probTitle,$checkboxes) = @_;
197: my $col=3;
198: if ($checkboxes) { $col=4; }
199: my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
200: $result .='<table border="0">';
201: my ($partlist,$handgrade,$responseType) = &response_type($symb);
202: my %resptype = ();
203: my $hdgrade='no';
204: my %partsseen;
205: foreach my $partID (sort(keys(%$responseType))) {
206: foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
207: my $handgrade=$$handgrade{$partID.'_'.$resID};
208: my $responsetype = $responseType->{$partID}->{$resID};
209: $hdgrade = $handgrade if ($handgrade eq 'yes');
210: $result.='<tr>';
211: if ($checkboxes) {
212: if (exists($partsseen{$partID})) {
213: $result.="<td> </td>";
214: } else {
215: $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
216: }
217: $partsseen{$partID}=1;
218: }
219: my $display_part=&get_display_part($partID,$symb);
220: $result.='<td><b>'.&mt('Part').': </b>'.$display_part.
221: ' <span class="LC_internal_info">'.$resID.'</span></td>'.
222: '<td><b>'.&mt('Type').': </b>'.$responsetype.'</td></tr>';
223: # '<td>'.&mt('<b>Handgrade: </b>[_1]',$handgrade).'</td></tr>';
224: }
225: }
226: $result.='</table>'."\n";
227: return $result,$responseType,$hdgrade,$partlist,$handgrade;
228: }
229:
230: sub reset_caches {
231: &reset_analyze_cache();
232: &reset_perm();
233: }
234:
235: {
236: my %analyze_cache;
237: my %analyze_cache_formkeys;
238:
239: sub reset_analyze_cache {
240: undef(%analyze_cache);
241: undef(%analyze_cache_formkeys);
242: }
243:
244: sub get_analyze {
245: my ($symb,$uname,$udom,$no_increment,$add_to_hash)=@_;
246: my $key = "$symb\0$uname\0$udom";
247: if (exists($analyze_cache{$key})) {
248: my $getupdate = 0;
249: if (ref($add_to_hash) eq 'HASH') {
250: foreach my $item (keys(%{$add_to_hash})) {
251: if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
252: if (!exists($analyze_cache_formkeys{$key}{$item})) {
253: $getupdate = 1;
254: last;
255: }
256: } else {
257: $getupdate = 1;
258: }
259: }
260: }
261: if (!$getupdate) {
262: return $analyze_cache{$key};
263: }
264: }
265:
266: my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
267: $url=&Apache::lonnet::clutter($url);
268: my %form = ('grade_target' => 'analyze',
269: 'grade_domain' => $udom,
270: 'grade_symb' => $symb,
271: 'grade_courseid' => $env{'request.course.id'},
272: 'grade_username' => $uname,
273: 'grade_noincrement' => $no_increment);
274: if (ref($add_to_hash)) {
275: %form = (%form,%{$add_to_hash});
276: }
277: my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
278: (undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
279: my %analyze=&Apache::lonnet::str2hash($subresult);
280: if (ref($add_to_hash) eq 'HASH') {
281: $analyze_cache_formkeys{$key} = $add_to_hash;
282: } else {
283: $analyze_cache_formkeys{$key} = {};
284: }
285: return $analyze_cache{$key} = \%analyze;
286: }
287:
288: sub get_order {
289: my ($partid,$respid,$symb,$uname,$udom,$no_increment)=@_;
290: my $analyze = &get_analyze($symb,$uname,$udom,$no_increment);
291: return $analyze->{"$partid.$respid.shown"};
292: }
293:
294: sub get_radiobutton_correct_foil {
295: my ($partid,$respid,$symb,$uname,$udom)=@_;
296: my $analyze = &get_analyze($symb,$uname,$udom);
297: my $foils = &get_order($partid,$respid,$symb,$uname,$udom);
298: if (ref($foils) eq 'ARRAY') {
299: foreach my $foil (@{$foils}) {
300: if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
301: return $foil;
302: }
303: }
304: }
305: }
306:
307: sub scantron_partids_tograde {
308: my ($resource,$cid,$uname,$udom,$check_for_randomlist) = @_;
309: my (%analysis,@parts);
310: if (ref($resource)) {
311: my $symb = $resource->symb();
312: my $add_to_form;
313: if ($check_for_randomlist) {
314: $add_to_form = { 'check_parts_withrandomlist' => 1,};
315: }
316: my $analyze = &get_analyze($symb,$uname,$udom,undef,$add_to_form);
317: if (ref($analyze) eq 'HASH') {
318: %analysis = %{$analyze};
319: }
320: if (ref($analysis{'parts'}) eq 'ARRAY') {
321: foreach my $part (@{$analysis{'parts'}}) {
322: my ($id,$respid) = split(/\./,$part);
323: if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
324: push(@parts,$part);
325: }
326: }
327: }
328: }
329: return (\%analysis,\@parts);
330: }
331:
332: }
333:
334: #--- Clean response type for display
335: #--- Currently filters option/rank/radiobutton/match/essay/Task
336: # response types only.
337: sub cleanRecord {
338: my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
339: $uname,$udom) = @_;
340: my $grayFont = '<span class="LC_internal_info">';
341: if ($response =~ /^(option|rank)$/) {
342: my %answer=&Apache::lonnet::str2hash($answer);
343: my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
344: my ($toprow,$bottomrow);
345: foreach my $foil (@$order) {
346: if ($grading{$foil} == 1) {
347: $toprow.='<td><b>'.$answer{$foil}.' </b></td>';
348: } else {
349: $toprow.='<td><i>'.$answer{$foil}.' </i></td>';
350: }
351: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
352: }
353: return '<blockquote><table border="1">'.
354: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
355: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
356: $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
357: } elsif ($response eq 'match') {
358: my %answer=&Apache::lonnet::str2hash($answer);
359: my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
360: my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
361: my ($toprow,$middlerow,$bottomrow);
362: foreach my $foil (@$order) {
363: my $item=shift(@items);
364: if ($grading{$foil} == 1) {
365: $toprow.='<td><b>'.$item.' </b></td>';
366: $middlerow.='<td><b>'.$grayFont.$answer{$foil}.' </span></b></td>';
367: } else {
368: $toprow.='<td><i>'.$item.' </i></td>';
369: $middlerow.='<td><i>'.$grayFont.$answer{$foil}.' </span></i></td>';
370: }
371: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
372: }
373: return '<blockquote><table border="1">'.
374: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
375: '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
376: $middlerow.'</tr>'.
377: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
378: $bottomrow.'</tr>'.'</table></blockquote>';
379: } elsif ($response eq 'radiobutton') {
380: my %answer=&Apache::lonnet::str2hash($answer);
381: my ($toprow,$bottomrow);
382: my $correct =
383: &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
384: foreach my $foil (@$order) {
385: if (exists($answer{$foil})) {
386: if ($foil eq $correct) {
387: $toprow.='<td><b>'.&mt('true').'</b></td>';
388: } else {
389: $toprow.='<td><i>'.&mt('true').'</i></td>';
390: }
391: } else {
392: $toprow.='<td>'.&mt('false').'</td>';
393: }
394: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
395: }
396: return '<blockquote><table border="1">'.
397: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
398: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
399: $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
400: } elsif ($response eq 'essay') {
401: if (! exists ($env{'form.'.$symb})) {
402: my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
403: $env{'course.'.$env{'request.course.id'}.'.domain'},
404: $env{'course.'.$env{'request.course.id'}.'.num'});
405:
406: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
407: $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
408: $env{'form.kwclr'} = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
409: $env{'form.kwsize'} = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
410: $env{'form.kwstyle'} = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
411: $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
412: }
413: $answer =~ s-\n-<br />-g;
414: return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
415: } elsif ( $response eq 'organic') {
416: my $result='Smile representation: "<tt>'.$answer.'</tt>"';
417: my $jme=$record->{$version."resource.$partid.$respid.molecule"};
418: $result.=&Apache::chemresponse::jme_img($jme,$answer,400);
419: return $result;
420: } elsif ( $response eq 'Task') {
421: if ( $answer eq 'SUBMITTED') {
422: my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
423: my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
424: return $result;
425: } elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
426: my @matches = grep(/^\Q$version\E.*?\.instance$/,
427: keys(%{$record}));
428: return join('<br />',($version,@matches));
429:
430:
431: } else {
432: my $result =
433: '<p>'
434: .&mt('Overall result: [_1]',
435: $record->{$version."resource.$respid.$partid.status"})
436: .'</p>';
437:
438: $result .= '<ul>';
439: my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
440: keys(%{$record}));
441: foreach my $grade (sort(@grade)) {
442: my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
443: $result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
444: $dim, $record->{$grade}).
445: '</li>';
446: }
447: $result.='</ul>';
448: return $result;
449: }
450: } elsif ( $response =~ m/(?:numerical|formula)/) {
451: $answer =
452: &Apache::loncommon::format_previous_attempt_value('submission',
453: $answer);
454: }
455: return $answer;
456: }
457:
458: #-- A couple of common js functions
459: sub commonJSfunctions {
460: my $request = shift;
461: $request->print(<<COMMONJSFUNCTIONS);
462: <script type="text/javascript" language="javascript">
463: function radioSelection(radioButton) {
464: var selection=null;
465: if (radioButton.length > 1) {
466: for (var i=0; i<radioButton.length; i++) {
467: if (radioButton[i].checked) {
468: return radioButton[i].value;
469: }
470: }
471: } else {
472: if (radioButton.checked) return radioButton.value;
473: }
474: return selection;
475: }
476:
477: function pullDownSelection(selectOne) {
478: var selection="";
479: if (selectOne.length > 1) {
480: for (var i=0; i<selectOne.length; i++) {
481: if (selectOne[i].selected) {
482: return selectOne[i].value;
483: }
484: }
485: } else {
486: // only one value it must be the selected one
487: return selectOne.value;
488: }
489: }
490: </script>
491: COMMONJSFUNCTIONS
492: }
493:
494: #--- Dumps the class list with usernames,list of sections,
495: #--- section, ids and fullnames for each user.
496: sub getclasslist {
497: my ($getsec,$filterlist,$getgroup) = @_;
498: my @getsec;
499: my @getgroup;
500: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
501: if (!ref($getsec)) {
502: if ($getsec ne '' && $getsec ne 'all') {
503: @getsec=($getsec);
504: }
505: } else {
506: @getsec=@{$getsec};
507: }
508: if (grep(/^all$/,@getsec)) { undef(@getsec); }
509: if (!ref($getgroup)) {
510: if ($getgroup ne '' && $getgroup ne 'all') {
511: @getgroup=($getgroup);
512: }
513: } else {
514: @getgroup=@{$getgroup};
515: }
516: if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
517:
518: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
519: # Bail out if we were unable to get the classlist
520: return if (! defined($classlist));
521: &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
522: #
523: my %sections;
524: my %fullnames;
525: foreach my $student (keys(%$classlist)) {
526: my $end =
527: $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
528: my $start =
529: $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
530: my $id =
531: $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
532: my $section =
533: $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
534: my $fullname =
535: $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
536: my $status =
537: $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
538: my $group =
539: $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
540: # filter students according to status selected
541: if ($filterlist && (!($stu_status =~ /Any/))) {
542: if (!($stu_status =~ $status)) {
543: delete($classlist->{$student});
544: next;
545: }
546: }
547: # filter students according to groups selected
548: my @stu_groups = split(/,/,$group);
549: if (@getgroup) {
550: my $exclude = 1;
551: foreach my $grp (@getgroup) {
552: foreach my $stu_group (@stu_groups) {
553: if ($stu_group eq $grp) {
554: $exclude = 0;
555: }
556: }
557: if (($grp eq 'none') && !$group) {
558: $exclude = 0;
559: }
560: }
561: if ($exclude) {
562: delete($classlist->{$student});
563: }
564: }
565: $section = ($section ne '' ? $section : 'none');
566: if (&canview($section)) {
567: if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
568: $sections{$section}++;
569: if ($classlist->{$student}) {
570: $fullnames{$student}=$fullname;
571: }
572: } else {
573: delete($classlist->{$student});
574: }
575: } else {
576: delete($classlist->{$student});
577: }
578: }
579: my %seen = ();
580: my @sections = sort(keys(%sections));
581: return ($classlist,\@sections,\%fullnames);
582: }
583:
584: sub canmodify {
585: my ($sec)=@_;
586: if ($perm{'mgr'}) {
587: if (!defined($perm{'mgr_section'})) {
588: # can modify whole class
589: return 1;
590: } else {
591: if ($sec eq $perm{'mgr_section'}) {
592: #can modify the requested section
593: return 1;
594: } else {
595: # can't modify the request section
596: return 0;
597: }
598: }
599: }
600: #can't modify
601: return 0;
602: }
603:
604: sub canview {
605: my ($sec)=@_;
606: if ($perm{'vgr'}) {
607: if (!defined($perm{'vgr_section'})) {
608: # can modify whole class
609: return 1;
610: } else {
611: if ($sec eq $perm{'vgr_section'}) {
612: #can modify the requested section
613: return 1;
614: } else {
615: # can't modify the request section
616: return 0;
617: }
618: }
619: }
620: #can't modify
621: return 0;
622: }
623:
624: #--- Retrieve the grade status of a student for all the parts
625: sub student_gradeStatus {
626: my ($symb,$udom,$uname,$partlist) = @_;
627: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
628: my %partstatus = ();
629: foreach (@$partlist) {
630: my ($status,undef) = split(/_/,$record{"resource.$_.solved"},2);
631: $status = 'nothing' if ($status eq '');
632: $partstatus{$_} = $status;
633: my $subkey = "resource.$_.submitted_by";
634: $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
635: }
636: return %partstatus;
637: }
638:
639: # hidden form and javascript that calls the form
640: # Use by verifyscript and viewgrades
641: # Shows a student's view of problem and submission
642: sub jscriptNform {
643: my ($symb) = @_;
644: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
645: my $jscript='<script type="text/javascript" language="javascript">'."\n".
646: ' function viewOneStudent(user,domain) {'."\n".
647: ' document.onestudent.student.value = user;'."\n".
648: ' document.onestudent.userdom.value = domain;'."\n".
649: ' document.onestudent.submit();'."\n".
650: ' }'."\n".
651: '</script>'."\n";
652: $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
653: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
654: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
655: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
656: '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
657: '<input type="hidden" name="command" value="submission" />'."\n".
658: '<input type="hidden" name="student" value="" />'."\n".
659: '<input type="hidden" name="userdom" value="" />'."\n".
660: '</form>'."\n";
661: return $jscript;
662: }
663:
664:
665:
666: # Given the score (as a number [0-1] and the weight) what is the final
667: # point value? This function will round to the nearest tenth, third,
668: # or quarter if one of those is within the tolerance of .00001.
669: sub compute_points {
670: my ($score, $weight) = @_;
671:
672: my $tolerance = .00001;
673: my $points = $score * $weight;
674:
675: # Check for nearness to 1/x.
676: my $check_for_nearness = sub {
677: my ($factor) = @_;
678: my $num = ($points * $factor) + $tolerance;
679: my $floored_num = floor($num);
680: if ($num - $floored_num < 2 * $tolerance * $factor) {
681: return $floored_num / $factor;
682: }
683: return $points;
684: };
685:
686: $points = $check_for_nearness->(10);
687: $points = $check_for_nearness->(3);
688: $points = $check_for_nearness->(4);
689:
690: return $points;
691: }
692:
693: #------------------ End of general use routines --------------------
694:
695: #
696: # Find most similar essay
697: #
698:
699: sub most_similar {
700: my ($uname,$udom,$uessay,$old_essays)=@_;
701:
702: # ignore spaces and punctuation
703:
704: $uessay=~s/\W+/ /gs;
705:
706: # ignore empty submissions (occuring when only files are sent)
707:
708: unless ($uessay=~/\w+/) { return ''; }
709:
710: # these will be returned. Do not care if not at least 50 percent similar
711: my $limit=0.6;
712: my $sname='';
713: my $sdom='';
714: my $scrsid='';
715: my $sessay='';
716: # go through all essays ...
717: foreach my $tkey (keys(%$old_essays)) {
718: my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
719: # ... except the same student
720: next if (($tname eq $uname) && ($tdom eq $udom));
721: my $tessay=$old_essays->{$tkey};
722: $tessay=~s/\W+/ /gs;
723: # String similarity gives up if not even limit
724: my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
725: # Found one
726: if ($tsimilar>$limit) {
727: $limit=$tsimilar;
728: $sname=$tname;
729: $sdom=$tdom;
730: $scrsid=$tcrsid;
731: $sessay=$old_essays->{$tkey};
732: }
733: }
734: if ($limit>0.6) {
735: return ($sname,$sdom,$scrsid,$sessay,$limit);
736: } else {
737: return ('','','','',0);
738: }
739: }
740:
741: #-------------------------------------------------------------------
742:
743: #------------------------------------ Receipt Verification Routines
744: #
745: #--- Check whether a receipt number is valid.---
746: sub verifyreceipt {
747: my $request = shift;
748:
749: my $courseid = $env{'request.course.id'};
750: my $receipt = &Apache::lonnet::recprefix($courseid).'-'.
751: $env{'form.receipt'};
752: $receipt =~ s/[^\-\d]//g;
753: my ($symb) = &get_symb($request);
754:
755: my $title.=
756: '<h3><span class="LC_info">'.
757: &mt('Verifying Receipt No. [_1]',$receipt).
758: '</span></h3>'."\n".
759: '<h4>'.&mt('<b>Resource: </b>[_1]',$env{'form.probTitle'}).
760: '</h4>'."\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) { ($parts)=&response_type($symb); }
770:
771: my $header =
772: &Apache::loncommon::start_data_table().
773: &Apache::loncommon::start_data_table_header_row().
774: '<th> '.&mt('Fullname').' </th>'."\n".
775: '<th> '.&mt('Username').' </th>'."\n".
776: '<th> '.&mt('Domain').' </th>';
777: if ($receiptparts) {
778: $header.='<th> '.&mt('Problem Part').' </th>';
779: }
780: $header.=
781: &Apache::loncommon::end_data_table_header_row();
782:
783: foreach (sort
784: {
785: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
786: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
787: }
788: return $a cmp $b;
789: } (keys(%$fullname))) {
790: my ($uname,$udom)=split(/\:/);
791: foreach my $part (@$parts) {
792: if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
793: $contents.=
794: &Apache::loncommon::start_data_table_row().
795: '<td> '."\n".
796: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
797: '\');" target="_self">'.$$fullname{$_}.'</a> </td>'."\n".
798: '<td> '.$uname.' </td>'.
799: '<td> '.$udom.' </td>';
800: if ($receiptparts) {
801: $contents.='<td> '.$part.' </td>';
802: }
803: $contents.=
804: &Apache::loncommon::end_data_table_row()."\n";
805:
806: $matches++;
807: }
808: }
809: }
810: if ($matches == 0) {
811: $string = $title.&mt('No match found for the above receipt.');
812: } else {
813: $string = &jscriptNform($symb).$title.
814: '<p>'.
815: &mt('The above receipt matches the following [numerate,_1,student].',$matches).
816: '</p>'.
817: $header.
818: $contents.
819: &Apache::loncommon::end_data_table()."\n";
820: }
821: return $string.&show_grading_menu_form($symb);
822: }
823:
824: #--- This is called by a number of programs.
825: #--- Called from the Grading Menu - View/Grade an individual student
826: #--- Also called directly when one clicks on the subm button
827: # on the problem page.
828: sub listStudents {
829: my ($request) = shift;
830:
831: my ($symb) = &get_symb($request);
832: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
833: my $cnum = $env{"course.$env{'request.course.id'}.num"};
834: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
835: my $getgroup = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
836: my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
837: my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
838: $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ?
839: &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
840:
841: my $result='<h3><span class="LC_info"> '
842: .&mt("$viewgrade Submissions for a Student or a Group of Students")
843: .'</span></h3>';
844:
845: my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
846:
847: my %lt = &Apache::lonlocal::texthash (
848: 'multiple' => 'Please select a student or group of students before clicking on the Next button.',
849: 'single' => 'Please select the student before clicking on the Next button.',
850: );
851: $request->print(<<LISTJAVASCRIPT);
852: <script type="text/javascript" language="javascript">
853: function checkSelect(checkBox) {
854: var ctr=0;
855: var sense="";
856: if (checkBox.length > 1) {
857: for (var i=0; i<checkBox.length; i++) {
858: if (checkBox[i].checked) {
859: ctr++;
860: }
861: }
862: sense = '$lt{'multiple'}';
863: } else {
864: if (checkBox.checked) {
865: ctr = 1;
866: }
867: sense = '$lt{'single'}';
868: }
869: if (ctr == 0) {
870: alert(sense);
871: return false;
872: }
873: document.gradesub.submit();
874: }
875:
876: function reLoadList(formname) {
877: if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
878: formname.command.value = 'submission';
879: formname.submit();
880: }
881: </script>
882: LISTJAVASCRIPT
883:
884: &commonJSfunctions($request);
885: $request->print($result);
886:
887: my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
888: my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
889: my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
890: "\n".$table;
891:
892: $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
893: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
894: .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
895: .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
896: .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
897: .&Apache::lonhtmlcommon::row_closure();
898: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
899: .'<label><input type="radio" name="vAns" value="no" /> '.&mt('no').' </label>'."\n"
900: .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
901: .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
902: .&Apache::lonhtmlcommon::row_closure();
903:
904: my $submission_options;
905: if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
906: $submission_options.=
907: '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
908: }
909: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
910: my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
911: $env{'form.Status'} = $saveStatus;
912: $submission_options.=
913: '<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.&mt('last submission only').' </label>'."\n".
914: '<label><input type="radio" name="lastSub" value="last" /> '.&mt('last submission & parts info').' </label>'."\n".
915: '<label><input type="radio" name="lastSub" value="datesub" /> '.&mt('by dates and submissions').' </label>'."\n".
916: '<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').'</label>';
917: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
918: .$submission_options
919: .&Apache::lonhtmlcommon::row_closure();
920:
921: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
922: .'<select name="increment">'
923: .'<option value="1">'.&mt('Whole Points').'</option>'
924: .'<option value=".5">'.&mt('Half Points').'</option>'
925: .'<option value=".25">'.&mt('Quarter Points').'</option>'
926: .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
927: .'</select>'
928: .&Apache::lonhtmlcommon::row_closure();
929:
930: $gradeTable .=
931: &build_section_inputs().
932: '<input type="hidden" name="submitonly" value="'.$submitonly.'" />'."\n".
933: '<input type="hidden" name="handgrade" value="'.$env{'form.handgrade'}.'" /><br />'."\n".
934: '<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
935: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
936: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
937: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
938: '<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
939:
940: if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
941: $gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
942: } else {
943: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
944: .&Apache::lonhtmlcommon::StatusOptions(
945: $saveStatus,undef,1,'javascript:reLoadList(this.form);')
946: .&Apache::lonhtmlcommon::row_closure();
947: }
948:
949: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
950: .'<input type="checkbox" name="checkPlag" checked="checked" />'
951: .&Apache::lonhtmlcommon::row_closure(1)
952: .&Apache::lonhtmlcommon::end_pick_box();
953:
954: $gradeTable .= '<p>'
955: .&mt('To '.lc($viewgrade)." 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"
956: .'<input type="hidden" name="command" value="processGroup" />'
957: .'</p>';
958:
959: # checkall buttons
960: $gradeTable.=&check_script('gradesub', 'stuinfo');
961: $gradeTable.='<input type="button" '."\n".
962: 'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
963: 'value="'.&mt('Next').' →" /> <br />'."\n";
964: $gradeTable.=&check_buttons();
965: my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
966: $gradeTable.= &Apache::loncommon::start_data_table().
967: &Apache::loncommon::start_data_table_header_row();
968: my $loop = 0;
969: while ($loop < 2) {
970: $gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
971: '<th>'.&nameUserString('header').' '.&mt('Section/Group').'</th>';
972: if ($env{'form.showgrading'} eq 'yes'
973: && $submitonly ne 'queued'
974: && $submitonly ne 'all') {
975: foreach my $part (sort(@$partlist)) {
976: my $display_part=
977: &get_display_part((split(/_/,$part))[0],$symb);
978: $gradeTable.=
979: '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
980: }
981: } elsif ($submitonly eq 'queued') {
982: $gradeTable.='<th>'.&mt('Queue Status').' </th>';
983: }
984: $loop++;
985: # $gradeTable.='<td></td>' if ($loop%2 ==1);
986: }
987: $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
988:
989: my $ctr = 0;
990: foreach my $student (sort
991: {
992: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
993: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
994: }
995: return $a cmp $b;
996: }
997: (keys(%$fullname))) {
998: my ($uname,$udom) = split(/:/,$student);
999:
1000: my %status = ();
1001:
1002: if ($submitonly eq 'queued') {
1003: my %queue_status =
1004: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
1005: $udom,$uname);
1006: next if (!defined($queue_status{'gradingqueue'}));
1007: $status{'gradingqueue'} = $queue_status{'gradingqueue'};
1008: }
1009:
1010: if ($env{'form.showgrading'} eq 'yes'
1011: && $submitonly ne 'queued'
1012: && $submitonly ne 'all') {
1013: (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1014: my $submitted = 0;
1015: my $graded = 0;
1016: my $incorrect = 0;
1017: foreach (keys(%status)) {
1018: $submitted = 1 if ($status{$_} ne 'nothing');
1019: $graded = 1 if ($status{$_} =~ /^ungraded/);
1020: $incorrect = 1 if ($status{$_} =~ /^incorrect/);
1021:
1022: my ($foo,$partid,$foo1) = split(/\./,$_);
1023: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1024: $submitted = 0;
1025: my ($part)=split(/\./,$partid);
1026: $gradeTable.='<input type="hidden" name="'.
1027: $student.':'.$part.':submitted_by" value="'.
1028: $status{'resource.'.$partid.'.submitted_by'}.'" />';
1029: }
1030: }
1031:
1032: next if (!$submitted && ($submitonly eq 'yes' ||
1033: $submitonly eq 'incorrect' ||
1034: $submitonly eq 'graded'));
1035: next if (!$graded && ($submitonly eq 'graded'));
1036: next if (!$incorrect && $submitonly eq 'incorrect');
1037: }
1038:
1039: $ctr++;
1040: my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1041: my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1042: if ( $perm{'vgr'} eq 'F' ) {
1043: if ($ctr%2 ==1) {
1044: $gradeTable.= &Apache::loncommon::start_data_table_row();
1045: }
1046: $gradeTable.='<td align="right">'.$ctr.' </td>'.
1047: '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1048: $student.':'.$$fullname{$student}.':::SECTION'.$section.
1049: ') " /> </label></td>'."\n".'<td>'.
1050: &nameUserString(undef,$$fullname{$student},$uname,$udom).
1051: ' '.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1052:
1053: if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1054: foreach (sort(keys(%status))) {
1055: next if ($_ =~ /^resource.*?submitted_by$/);
1056: $gradeTable.='<td align="center"> '.&mt($status{$_}).' </td>'."\n";
1057: }
1058: }
1059: # $gradeTable.='<td></td>' if ($ctr%2 ==1);
1060: if ($ctr%2 ==0) {
1061: $gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
1062: }
1063: }
1064: }
1065: if ($ctr%2 ==1) {
1066: $gradeTable.='<td> </td><td> </td><td> </td>';
1067: if ($env{'form.showgrading'} eq 'yes'
1068: && $submitonly ne 'queued'
1069: && $submitonly ne 'all') {
1070: foreach (@$partlist) {
1071: $gradeTable.='<td> </td>';
1072: }
1073: } elsif ($submitonly eq 'queued') {
1074: $gradeTable.='<td> </td>';
1075: }
1076: $gradeTable.=&Apache::loncommon::end_data_table_row();
1077: }
1078:
1079: $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1080: '<input type="button" '.
1081: 'onClick="javascript:checkSelect(this.form.stuinfo);" '.
1082: 'value="'.&mt('Next').' →" /></form>'."\n";
1083: if ($ctr == 0) {
1084: my $num_students=(scalar(keys(%$fullname)));
1085: if ($num_students eq 0) {
1086: $gradeTable='<br /> <span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1087: } else {
1088: my $submissions='submissions';
1089: if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
1090: if ($submitonly eq 'graded' ) { $submissions = 'ungraded submissions'; }
1091: if ($submitonly eq 'queued' ) { $submissions = 'queued submissions'; }
1092: $gradeTable='<br /> <span class="LC_warning">'.
1093: &mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
1094: $num_students).
1095: '</span><br />';
1096: }
1097: } elsif ($ctr == 1) {
1098: $gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1099: }
1100: $gradeTable.=&show_grading_menu_form($symb);
1101: $request->print($gradeTable);
1102: return '';
1103: }
1104:
1105: #---- Called from the listStudents routine
1106:
1107: sub check_script {
1108: my ($form, $type)=@_;
1109: my $chkallscript='<script type="text/javascript">
1110: function checkall() {
1111: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1112: ele = document.forms.'.$form.'.elements[i];
1113: if (ele.name == "'.$type.'") {
1114: document.forms.'.$form.'.elements[i].checked=true;
1115: }
1116: }
1117: }
1118:
1119: function checksec() {
1120: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1121: ele = document.forms.'.$form.'.elements[i];
1122: string = document.forms.'.$form.'.chksec.value;
1123: if
1124: (ele.value.indexOf(":::SECTION"+string)>0) {
1125: document.forms.'.$form.'.elements[i].checked=true;
1126: }
1127: }
1128: }
1129:
1130:
1131: function uncheckall() {
1132: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1133: ele = document.forms.'.$form.'.elements[i];
1134: if (ele.name == "'.$type.'") {
1135: document.forms.'.$form.'.elements[i].checked=false;
1136: }
1137: }
1138: }
1139:
1140: </script>'."\n";
1141: return $chkallscript;
1142: }
1143:
1144: sub check_buttons {
1145: my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
1146: $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" /> ';
1147: $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1148: $buttons.='<input type="text" size="5" name="chksec" /> ';
1149: return $buttons;
1150: }
1151:
1152: # Displays the submissions for one student or a group of students
1153: sub processGroup {
1154: my ($request) = shift;
1155: my $ctr = 0;
1156: my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1157: my $total = scalar(@stuchecked)-1;
1158:
1159: foreach my $student (@stuchecked) {
1160: my ($uname,$udom,$fullname) = split(/:/,$student);
1161: $env{'form.student'} = $uname;
1162: $env{'form.userdom'} = $udom;
1163: $env{'form.fullname'} = $fullname;
1164: &submission($request,$ctr,$total);
1165: $ctr++;
1166: }
1167: return '';
1168: }
1169:
1170: #------------------------------------------------------------------------------------
1171: #
1172: #-------------------------- Next few routines handles grading by student, essentially
1173: # handles essay response type problem/part
1174: #
1175: #--- Javascript to handle the submission page functionality ---
1176: sub sub_page_js {
1177: my $request = shift;
1178: my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1179: $request->print(<<SUBJAVASCRIPT);
1180: <script type="text/javascript" language="javascript">
1181: function updateRadio(formname,id,weight) {
1182: var gradeBox = formname["GD_BOX"+id];
1183: var radioButton = formname["RADVAL"+id];
1184: var oldpts = formname["oldpts"+id].value;
1185: var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1186: gradeBox.value = pts;
1187: var resetbox = false;
1188: if (isNaN(pts) || pts < 0) {
1189: alert("$alertmsg"+pts);
1190: for (var i=0; i<radioButton.length; i++) {
1191: if (radioButton[i].checked) {
1192: gradeBox.value = i;
1193: resetbox = true;
1194: }
1195: }
1196: if (!resetbox) {
1197: formtextbox.value = "";
1198: }
1199: return;
1200: }
1201:
1202: if (pts > weight) {
1203: var resp = confirm("You entered a value ("+pts+
1204: ") greater than the weight for the part. Accept?");
1205: if (resp == false) {
1206: gradeBox.value = oldpts;
1207: return;
1208: }
1209: }
1210:
1211: for (var i=0; i<radioButton.length; i++) {
1212: radioButton[i].checked=false;
1213: if (pts == i && pts != "") {
1214: radioButton[i].checked=true;
1215: }
1216: }
1217: updateSelect(formname,id);
1218: formname["stores"+id].value = "0";
1219: }
1220:
1221: function writeBox(formname,id,pts) {
1222: var gradeBox = formname["GD_BOX"+id];
1223: if (checkSolved(formname,id) == 'update') {
1224: gradeBox.value = pts;
1225: } else {
1226: var oldpts = formname["oldpts"+id].value;
1227: gradeBox.value = oldpts;
1228: var radioButton = formname["RADVAL"+id];
1229: for (var i=0; i<radioButton.length; i++) {
1230: radioButton[i].checked=false;
1231: if (i == oldpts) {
1232: radioButton[i].checked=true;
1233: }
1234: }
1235: }
1236: formname["stores"+id].value = "0";
1237: updateSelect(formname,id);
1238: return;
1239: }
1240:
1241: function clearRadBox(formname,id) {
1242: if (checkSolved(formname,id) == 'noupdate') {
1243: updateSelect(formname,id);
1244: return;
1245: }
1246: gradeSelect = formname["GD_SEL"+id];
1247: for (var i=0; i<gradeSelect.length; i++) {
1248: if (gradeSelect[i].selected) {
1249: var selectx=i;
1250: }
1251: }
1252: var stores = formname["stores"+id];
1253: if (selectx == stores.value) { return };
1254: var gradeBox = formname["GD_BOX"+id];
1255: gradeBox.value = "";
1256: var radioButton = formname["RADVAL"+id];
1257: for (var i=0; i<radioButton.length; i++) {
1258: radioButton[i].checked=false;
1259: }
1260: stores.value = selectx;
1261: }
1262:
1263: function checkSolved(formname,id) {
1264: if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1265: var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
1266: if (!reply) {return "noupdate";}
1267: formname.overRideScore.value = 'yes';
1268: }
1269: return "update";
1270: }
1271:
1272: function updateSelect(formname,id) {
1273: formname["GD_SEL"+id][0].selected = true;
1274: return;
1275: }
1276:
1277: //=========== Check that a point is assigned for all the parts ============
1278: function checksubmit(formname,val,total,parttot) {
1279: formname.gradeOpt.value = val;
1280: if (val == "Save & Next") {
1281: for (i=0;i<=total;i++) {
1282: for (j=0;j<parttot;j++) {
1283: var partid = formname["partid"+i+"_"+j].value;
1284: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1285: var points = formname["GD_BOX"+i+"_"+partid].value;
1286: if (points == "") {
1287: var name = formname["name"+i].value;
1288: var studentID = (name != '' ? name : formname["unamedom"+i].value);
1289: var resp = confirm("You did not assign a score for "+studentID+
1290: ", part "+partid+". Continue?");
1291: if (resp == false) {
1292: formname["GD_BOX"+i+"_"+partid].focus();
1293: return false;
1294: }
1295: }
1296: }
1297:
1298: }
1299: }
1300:
1301: }
1302: if (val == "Grade Student") {
1303: formname.showgrading.value = "yes";
1304: if (formname.Status.value == "") {
1305: formname.Status.value = "Active";
1306: }
1307: formname.studentNo.value = total;
1308: }
1309: formname.submit();
1310: }
1311:
1312: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
1313: function checkSubmitPage(formname,total) {
1314: noscore = new Array(100);
1315: var ptr = 0;
1316: for (i=1;i<total;i++) {
1317: var partid = formname["q_"+i].value;
1318: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1319: var points = formname["GD_BOX"+i+"_"+partid].value;
1320: var status = formname["solved"+i+"_"+partid].value;
1321: if (points == "" && status != "correct_by_student") {
1322: noscore[ptr] = i;
1323: ptr++;
1324: }
1325: }
1326: }
1327: if (ptr != 0) {
1328: var sense = ptr == 1 ? ": " : "s: ";
1329: var prolist = "";
1330: if (ptr == 1) {
1331: prolist = noscore[0];
1332: } else {
1333: var i = 0;
1334: while (i < ptr-1) {
1335: prolist += noscore[i]+", ";
1336: i++;
1337: }
1338: prolist += "and "+noscore[i];
1339: }
1340: var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
1341: if (resp == false) {
1342: return false;
1343: }
1344: }
1345:
1346: formname.submit();
1347: }
1348: </script>
1349: SUBJAVASCRIPT
1350: }
1351:
1352: #--- javascript for essay type problem --
1353: sub sub_page_kw_js {
1354: my $request = shift;
1355: my $iconpath = $request->dir_config('lonIconsURL');
1356: &commonJSfunctions($request);
1357:
1358: my $inner_js_msg_central=<<INNERJS;
1359: <script text="text/javascript">
1360: function checkInput() {
1361: opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
1362: var nmsg = opener.document.SCORE.savemsgN.value;
1363: var usrctr = document.msgcenter.usrctr.value;
1364: var newval = opener.document.SCORE["newmsg"+usrctr];
1365: newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
1366:
1367: var msgchk = "";
1368: if (document.msgcenter.subchk.checked) {
1369: msgchk = "msgsub,";
1370: }
1371: var includemsg = 0;
1372: for (var i=1; i<=nmsg; i++) {
1373: var opnmsg = opener.document.SCORE["savemsg"+i];
1374: var frmmsg = document.msgcenter["msg"+i];
1375: opnmsg.value = opener.checkEntities(frmmsg.value);
1376: var showflg = opener.document.SCORE["shownOnce"+i];
1377: showflg.value = "1";
1378: var chkbox = document.msgcenter["msgn"+i];
1379: if (chkbox.checked) {
1380: msgchk += "savemsg"+i+",";
1381: includemsg = 1;
1382: }
1383: }
1384: if (document.msgcenter.newmsgchk.checked) {
1385: msgchk += "newmsg"+usrctr;
1386: includemsg = 1;
1387: }
1388: imgformname = opener.document.SCORE["mailicon"+usrctr];
1389: imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
1390: var includemsg = opener.document.SCORE["includemsg"+usrctr];
1391: includemsg.value = msgchk;
1392:
1393: self.close()
1394:
1395: }
1396: </script>
1397: INNERJS
1398:
1399: my $inner_js_highlight_central=<<INNERJS;
1400: <script type="text/javascript">
1401: function updateChoice(flag) {
1402: opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
1403: opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
1404: opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
1405: opener.document.SCORE.refresh.value = "on";
1406: if (opener.document.SCORE.keywords.value!=""){
1407: opener.document.SCORE.submit();
1408: }
1409: self.close()
1410: }
1411: </script>
1412: INNERJS
1413:
1414: my $start_page_msg_central =
1415: &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
1416: {'js_ready' => 1,
1417: 'only_body' => 1,
1418: 'bgcolor' =>'#FFFFFF',});
1419: my $end_page_msg_central =
1420: &Apache::loncommon::end_page({'js_ready' => 1});
1421:
1422:
1423: my $start_page_highlight_central =
1424: &Apache::loncommon::start_page('Highlight Central',
1425: $inner_js_highlight_central,
1426: {'js_ready' => 1,
1427: 'only_body' => 1,
1428: 'bgcolor' =>'#FFFFFF',});
1429: my $end_page_highlight_central =
1430: &Apache::loncommon::end_page({'js_ready' => 1});
1431:
1432: my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1433: $docopen=~s/^document\.//;
1434: my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
1435: $request->print(<<SUBJAVASCRIPT);
1436: <script type="text/javascript" language="javascript">
1437:
1438: //===================== Show list of keywords ====================
1439: function keywords(formname) {
1440: var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",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("$alertmsg");
1468: return;
1469: }
1470: var nret = prompt("Add selection to keyword list? Edit if desired.",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: var scrollbar = "no";
1535: if (height > 600) {
1536: height = 600;
1537: scrollbar = "yes";
1538: }
1539: var xpos = (screen.width-600)/2;
1540: xpos = (xpos < 0) ? '0' : xpos;
1541: var ypos = (screen.height-height)/2-30;
1542: ypos = (ypos < 0) ? '0' : ypos;
1543:
1544: pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1545: pWin.focus();
1546: pDoc = pWin.document;
1547: pDoc.$docopen;
1548: pDoc.write('$start_page_msg_central');
1549:
1550: pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
1551: pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1552: pDoc.write("<h3><span class=\\"LC_info\\"> Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
1553:
1554: pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
1555: pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1556: pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
1557: }
1558: function displaySubject(msg,shwsel) {
1559: pDoc = pWin.document;
1560: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1561: pDoc.write("<td>Subject<\\/td>");
1562: pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1563: pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1564: }
1565:
1566: function displaySavedMsg(ctr,msg,shwsel) {
1567: pDoc = pWin.document;
1568: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1569: pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
1570: pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1571: pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1572: }
1573:
1574: function newMsg(newmsg,shwsel) {
1575: pDoc = pWin.document;
1576: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1577: pDoc.write("<td align=\\"center\\">New<\\/td>");
1578: pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1579: pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1580: }
1581:
1582: function msgTail() {
1583: pDoc = pWin.document;
1584: pDoc.write("<\\/table>");
1585: pDoc.write("<\\/td><\\/tr><\\/table> ");
1586: pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\"> ");
1587: pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1588: pDoc.write("<\\/form>");
1589: pDoc.write('$end_page_msg_central');
1590: pDoc.close();
1591: }
1592:
1593: //====================== Script for keyword highlight options ==============
1594: function kwhighlight() {
1595: var kwclr = document.SCORE.kwclr.value;
1596: var kwsize = document.SCORE.kwsize.value;
1597: var kwstyle = document.SCORE.kwstyle.value;
1598: var redsel = "";
1599: var grnsel = "";
1600: var blusel = "";
1601: if (kwclr=="red") {var redsel="checked"};
1602: if (kwclr=="green") {var grnsel="checked"};
1603: if (kwclr=="blue") {var blusel="checked"};
1604: var sznsel = "";
1605: var sz1sel = "";
1606: var sz2sel = "";
1607: if (kwsize=="0") {var sznsel="checked"};
1608: if (kwsize=="+1") {var sz1sel="checked"};
1609: if (kwsize=="+2") {var sz2sel="checked"};
1610: var synsel = "";
1611: var syisel = "";
1612: var sybsel = "";
1613: if (kwstyle=="") {var synsel="checked"};
1614: if (kwstyle=="<i>") {var syisel="checked"};
1615: if (kwstyle=="<b>") {var sybsel="checked"};
1616: highlightCentral();
1617: highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
1618: highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
1619: highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
1620: highlightend();
1621: return;
1622: }
1623:
1624: function highlightCentral() {
1625: // if (window.hwdWin) window.hwdWin.close();
1626: var xpos = (screen.width-400)/2;
1627: xpos = (xpos < 0) ? '0' : xpos;
1628: var ypos = (screen.height-330)/2-30;
1629: ypos = (ypos < 0) ? '0' : ypos;
1630:
1631: hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1632: hwdWin.focus();
1633: var hDoc = hwdWin.document;
1634: hDoc.$docopen;
1635: hDoc.write('$start_page_highlight_central');
1636: hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1637: hDoc.write("<h3><span class=\\"LC_info\\"> Keyword Highlight Options<\\/span><\\/h3><br /><br />");
1638:
1639: hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
1640: hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1641: hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
1642: }
1643:
1644: function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) {
1645: var hDoc = hwdWin.document;
1646: hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1647: hDoc.write("<td align=\\"left\\">");
1648: hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+"> "+clrtxt+"<\\/td>");
1649: hDoc.write("<td align=\\"left\\">");
1650: hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+"> "+sztxt+"<\\/td>");
1651: hDoc.write("<td align=\\"left\\">");
1652: hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+"> "+sytxt+"<\\/td>");
1653: hDoc.write("<\\/tr>");
1654: }
1655:
1656: function highlightend() {
1657: var hDoc = hwdWin.document;
1658: hDoc.write("<\\/table>");
1659: hDoc.write("<\\/td><\\/tr><\\/table> ");
1660: hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\"> ");
1661: hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1662: hDoc.write("<\\/form>");
1663: hDoc.write('$end_page_highlight_central');
1664: hDoc.close();
1665: }
1666:
1667: </script>
1668: SUBJAVASCRIPT
1669: }
1670:
1671: sub get_increment {
1672: my $increment = $env{'form.increment'};
1673: if ($increment != 1 && $increment != .5 && $increment != .25 &&
1674: $increment != .1) {
1675: $increment = 1;
1676: }
1677: return $increment;
1678: }
1679:
1680: #--- displays the grading box, used in essay type problem and grading by page/sequence
1681: sub gradeBox {
1682: my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1683: my $checkIcon = '<img alt="'.&mt('Check Mark').
1684: '" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1685: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1686: my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)')
1687: : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1688: $wgt = ($wgt > 0 ? $wgt : '1');
1689: my $score = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1690: '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1691: my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1692: my $display_part= &get_display_part($partid,$symb);
1693: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
1694: [$partid]);
1695: my $aggtries = $$record{'resource.'.$partid.'.tries'};
1696: if ($last_resets{$partid}) {
1697: $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
1698: }
1699: $result.='<table border="0"><tr>';
1700: my $ctr = 0;
1701: my $thisweight = 0;
1702: my $increment = &get_increment();
1703:
1704: my $radio.='<table border="0"><tr>'."\n"; # display radio buttons in a nice table 10 across
1705: while ($thisweight<=$wgt) {
1706: $radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1707: 'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1708: $thisweight.')" value="'.$thisweight.'" '.
1709: ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1710: $radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1711: $thisweight += $increment;
1712: $ctr++;
1713: }
1714: $radio.='</tr></table>';
1715:
1716: my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1717: ($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1718: 'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1719: $wgt.')" /></td>'."\n";
1720: $line.='<td>/'.$wgt.' '.$wgtmsg.
1721: ($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? ' '.$checkIcon : '').
1722: ' </td><td><b>'.&mt('Grade Status').':</b>'."\n";
1723: $line.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
1724: 'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1725: if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1726: $line.='<option></option>'.
1727: '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1728: } else {
1729: $line.='<option selected="selected"></option>'.
1730: '<option value="excused" >'.&mt('excused').'</option>';
1731: }
1732: $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
1733:
1734:
1735: #&mt('<td><b>Part:</b></td><td>[_1]</td><td><b>Points:</b></td><td>[_2]</td><td>or</td><td>[_3]</td>',$display_part,$radio,$line);
1736: $result .=
1737: '<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>'.
1738:
1739: $result.='</tr></table>'."\n";
1740: $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
1741: '<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
1742: '<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1743: $$record{'resource.'.$partid.'.solved'}.'" />'."\n".
1744: '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
1745: $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
1746: '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
1747: $aggtries.'" />'."\n";
1748: $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
1749: return $result;
1750: }
1751:
1752: sub handback_box {
1753: my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
1754: my ($partlist,$handgrade,$responseType) = &response_type($symb);
1755: my (@respids);
1756: my @part_response_id = &flatten_responseType($responseType);
1757: foreach my $part_response_id (@part_response_id) {
1758: my ($part,$resp) = @{ $part_response_id };
1759: if ($part eq $partid) {
1760: push(@respids,$resp);
1761: }
1762: }
1763: my $result;
1764: foreach my $respid (@respids) {
1765: my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
1766: my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
1767: next if (!@$files);
1768: my $file_counter = 1;
1769: foreach my $file (@$files) {
1770: if ($file =~ /\/portfolio\//) {
1771: my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1772: my ($name,$version,$ext) = &file_name_version_ext($file_disp);
1773: $file_disp = "$name.$ext";
1774: $file = $file_path.$file_disp;
1775: $result.=&mt('Return commented version of [_1] to student.',
1776: '<span class="LC_filename">'.$file_disp.'</span>');
1777: $result.='<input type="file" name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1778: $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1779: $result.='('.&mt('File will be uploaded when you click on Save & Next below.').')<br />';
1780: $file_counter++;
1781: }
1782: }
1783: }
1784: return $result;
1785: }
1786:
1787: sub show_problem {
1788: my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1789: my $rendered;
1790: my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1791: &Apache::lonxml::remember_problem_counter();
1792: if ($mode eq 'both' or $mode eq 'text') {
1793: $rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1794: $env{'request.course.id'},
1795: undef,\%form);
1796: }
1797: if ($removeform) {
1798: $rendered=~s|<form(.*?)>||g;
1799: $rendered=~s|</form>||g;
1800: $rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1801: }
1802: my $companswer;
1803: if ($mode eq 'both' or $mode eq 'answer') {
1804: &Apache::lonxml::restore_problem_counter();
1805: $companswer=
1806: &Apache::loncommon::get_student_answers($symb,$uname,$udom,
1807: $env{'request.course.id'},
1808: %form);
1809: }
1810: if ($removeform) {
1811: $companswer=~s|<form(.*?)>||g;
1812: $companswer=~s|</form>||g;
1813: $companswer=~s|name="submit"|name="would_have_been_submit"|g;
1814: }
1815: $rendered=
1816: '<div class="LC_grade_show_problem_header">'.
1817: &mt('View of the problem').
1818: '</div><div class="LC_grade_show_problem_problem">'.
1819: $rendered.
1820: '</div>';
1821: $companswer=
1822: '<div class="LC_grade_show_problem_header">'.
1823: &mt('Correct answer').
1824: '</div><div class="LC_grade_show_problem_problem">'.
1825: $companswer.
1826: '</div>';
1827: my $result;
1828: if ($mode eq 'both') {
1829: $result=$rendered.$companswer;
1830: } elsif ($mode eq 'text') {
1831: $result=$rendered;
1832: } elsif ($mode eq 'answer') {
1833: $result=$companswer;
1834: }
1835: $result='<div class="LC_grade_show_problem">'.$result.'</div>';
1836: return $result;
1837: }
1838:
1839: sub files_exist {
1840: my ($r, $symb) = @_;
1841: my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1842:
1843: foreach my $student (@students) {
1844: my ($uname,$udom,$fullname) = split(/:/,$student);
1845: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
1846: $udom,$uname);
1847: my ($string,$timestamp)= &get_last_submission(\%record);
1848: foreach my $submission (@$string) {
1849: my ($partid,$respid) =
1850: ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1851: my $files=&get_submitted_files($udom,$uname,$partid,$respid,
1852: \%record);
1853: return 1 if (@$files);
1854: }
1855: }
1856: return 0;
1857: }
1858:
1859: sub download_all_link {
1860: my ($r,$symb) = @_;
1861: my $all_students =
1862: join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
1863:
1864: my $parts =
1865: join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
1866:
1867: my $identifier = &Apache::loncommon::get_cgi_id();
1868: &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
1869: 'cgi.'.$identifier.'.symb' => $symb,
1870: 'cgi.'.$identifier.'.parts' => $parts,});
1871: $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
1872: &mt('Download All Submitted Documents').'</a>');
1873: return
1874: }
1875:
1876: sub build_section_inputs {
1877: my $section_inputs;
1878: if ($env{'form.section'} eq '') {
1879: $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
1880: } else {
1881: my @sections = &Apache::loncommon::get_env_multiple('form.section');
1882: foreach my $section (@sections) {
1883: $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
1884: }
1885: }
1886: return $section_inputs;
1887: }
1888:
1889: # --------------------------- show submissions of a student, option to grade
1890: sub submission {
1891: my ($request,$counter,$total) = @_;
1892: my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
1893: $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
1894: my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
1895: $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1896: my $symb = &get_symb($request);
1897: if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1898:
1899: if (!&canview($usec)) {
1900: $request->print('<span class="LC_warning">Unable to view requested student.('.
1901: $uname.':'.$udom.' in section '.$usec.' in course id '.
1902: $env{'request.course.id'}.')</span>');
1903: $request->print(&show_grading_menu_form($symb));
1904: return;
1905: }
1906:
1907: if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
1908: if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
1909: if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
1910: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1911: my $checkIcon = '<img alt="'.&mt('Check Mark').
1912: '" src="'.$request->dir_config('lonIconsURL').
1913: '/check.gif" height="16" border="0" />';
1914:
1915: my %old_essays;
1916: # header info
1917: if ($counter == 0) {
1918: &sub_page_js($request);
1919: &sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
1920: $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ?
1921: &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1922: if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1923: &download_all_link($request, $symb);
1924: }
1925: $request->print('<h3> <span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
1926: '<h4> '.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
1927:
1928: # option to display problem, only once else it cause problems
1929: # with the form later since the problem has a form.
1930: if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1931: my $mode;
1932: if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1933: $mode='both';
1934: } elsif ($env{'form.vProb'} eq 'yes') {
1935: $mode='text';
1936: } elsif ($env{'form.vAns'} eq 'yes') {
1937: $mode='answer';
1938: }
1939: &Apache::lonxml::clear_problem_counter();
1940: $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1941: }
1942:
1943: # kwclr is the only variable that is guaranteed to be non blank
1944: # if this subroutine has been called once.
1945: my %keyhash = ();
1946: if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1947: %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1948: $env{'course.'.$env{'request.course.id'}.'.domain'},
1949: $env{'course.'.$env{'request.course.id'}.'.num'});
1950:
1951: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1952: $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
1953: $env{'form.kwclr'} = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
1954: $env{'form.kwsize'} = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
1955: $env{'form.kwstyle'} = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
1956: $env{'form.msgsub'} = $keyhash{$symb.'_subject'} ne '' ?
1957: $keyhash{$symb.'_subject'} : $env{'form.probTitle'};
1958: $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1959: }
1960: my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1961: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1962: $request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1963: '<input type="hidden" name="command" value="handgrade" />'."\n".
1964: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1965: '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
1966: '<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1967: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
1968: '<input type="hidden" name="refresh" value="off" />'."\n".
1969: '<input type="hidden" name="studentNo" value="" />'."\n".
1970: '<input type="hidden" name="gradeOpt" value="" />'."\n".
1971: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1972: '<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
1973: '<input type="hidden" name="vProb" value="'.$env{'form.vProb'}.'" />'."\n".
1974: '<input type="hidden" name="vAns" value="'.$env{'form.vAns'}.'" />'."\n".
1975: '<input type="hidden" name="lastSub" value="'.$env{'form.lastSub'}.'" />'."\n".
1976: &build_section_inputs().
1977: '<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1978: '<input type="hidden" name="handgrade" value="'.$env{'form.handgrade'}.'" />'."\n".
1979: '<input type="hidden" name="NCT"'.
1980: ' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1981: if ($env{'form.handgrade'} eq 'yes') {
1982: $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
1983: '<input type="hidden" name="kwclr" value="'.$env{'form.kwclr'}.'" />'."\n".
1984: '<input type="hidden" name="kwsize" value="'.$env{'form.kwsize'}.'" />'."\n".
1985: '<input type="hidden" name="kwstyle" value="'.$env{'form.kwstyle'}.'" />'."\n".
1986: '<input type="hidden" name="msgsub" value="'.$env{'form.msgsub'}.'" />'."\n".
1987: '<input type="hidden" name="shownSub" value="0" />'."\n".
1988: '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1989: foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
1990: $request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
1991: }
1992: }
1993:
1994: my ($cts,$prnmsg) = (1,'');
1995: while ($cts <= $env{'form.savemsgN'}) {
1996: $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1997: (!exists($keyhash{$symb.'_savemsg'.$cts}) ?
1998: &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1999: &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
2000: '" />'."\n".
2001: '<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
2002: $cts++;
2003: }
2004: $request->print($prnmsg);
2005:
2006: if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
2007: #
2008: # Print out the keyword options line
2009: #
2010: $request->print(<<KEYWORDS);
2011: <b>Keyword Options:</b>
2012: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>
2013: <a href="#" onMouseDown="javascript:getSel(); return false"
2014: CLASS="page">Paste Selection to List</a>
2015: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
2016: KEYWORDS
2017: #
2018: # Load the other essays for similarity check
2019: #
2020: my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
2021: my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
2022: $apath=&escape($apath);
2023: $apath=~s/\W/\_/gs;
2024: %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
2025: }
2026: }
2027:
2028: # This is where output for one specific student would start
2029: my $add_class = ($counter%2) ? 'LC_grade_show_user_odd_row' : '';
2030: $request->print("\n\n".
2031: '<div class="LC_grade_show_user '.$add_class.'">'.
2032: '<div class="LC_grade_user_name">'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</div>'.
2033: '<div class="LC_grade_show_user_body">'."\n");
2034:
2035: if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
2036: my $mode;
2037: if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
2038: $mode='both';
2039: } elsif ($env{'form.vProb'} eq 'all' ) {
2040: $mode='text';
2041: } elsif ($env{'form.vAns'} eq 'all') {
2042: $mode='answer';
2043: }
2044: &Apache::lonxml::clear_problem_counter();
2045: $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
2046: }
2047:
2048: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
2049: my ($partlist,$handgrade,$responseType) = &response_type($symb);
2050:
2051: # Display student info
2052: $request->print(($counter == 0 ? '' : '<br />'));
2053: my $result='<div class="LC_grade_submissions">';
2054:
2055: $result.='<div class="LC_grade_submissions_header">';
2056: $result.= &mt('Submissions');
2057: $result.='<input type="hidden" name="name'.$counter.
2058: '" value="'.$env{'form.fullname'}.'" />'."\n";
2059: if ($env{'form.handgrade'} eq 'no') {
2060: $result.='<span class="LC_grade_check_note">'.
2061: &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)."</span>\n";
2062:
2063: }
2064:
2065:
2066:
2067: # If any part of the problem is an essay-response (handgraded), then check for collaborators
2068: my $fullname;
2069: my $col_fullnames = [];
2070: if ($env{'form.handgrade'} eq 'yes') {
2071: (my $sub_result,$fullname,$col_fullnames)=
2072: &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
2073: $counter);
2074: $result.=$sub_result;
2075: }
2076: $request->print($result."\n");
2077: $request->print('</div>'."\n");
2078: # print student answer/submission
2079: # Options are (1) Handgaded submission only
2080: # (2) Last submission, includes submission that is not handgraded
2081: # (for multi-response type part)
2082: # (3) Last submission plus the parts info
2083: # (4) The whole record for this student
2084: if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
2085: my ($string,$timestamp)= &get_last_submission(\%record);
2086:
2087: my $lastsubonly;
2088:
2089: if ($$timestamp eq '') {
2090: $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>';
2091: } else {
2092: $lastsubonly = '<div class="LC_grade_submissions_body"> <b>Date Submitted:</b> '.$$timestamp."\n";
2093:
2094: my %seenparts;
2095: my @part_response_id = &flatten_responseType($responseType);
2096: foreach my $part (@part_response_id) {
2097: next if ($env{'form.lastSub'} eq 'hdgrade'
2098: && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
2099:
2100: my ($partid,$respid) = @{ $part };
2101: my $display_part=&get_display_part($partid,$symb);
2102: if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
2103: if (exists($seenparts{$partid})) { next; }
2104: $seenparts{$partid}=1;
2105: my $submitby='<b>Part:</b> '.$display_part.
2106: ' <b>Collaborative submission by:</b> '.
2107: '<a href="javascript:viewSubmitter(\''.
2108: $env{"form.$uname:$udom:$partid:submitted_by"}.
2109: '\');" target="_self">'.
2110: $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
2111: $request->print($submitby);
2112: next;
2113: }
2114: my $responsetype = $responseType->{$partid}->{$respid};
2115: if (!exists($record{"resource.$partid.$respid.submission"})) {
2116: $lastsubonly.="\n".'<div class="LC_grade_submission_part"><b>Part:</b> '.
2117: $display_part.' <span class="LC_internal_info">( ID '.$respid.
2118: ' )</span> '.
2119: '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
2120: next;
2121: }
2122: foreach my $submission (@$string) {
2123: my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
2124: if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
2125: my ($ressub,$subval) = split(/:/,$submission,2);
2126: # Similarity check
2127: my $similar='';
2128: if($env{'form.checkPlag'}){
2129: my ($oname,$odom,$ocrsid,$oessay,$osim)=
2130: &most_similar($uname,$udom,$subval,\%old_essays);
2131: if ($osim) {
2132: $osim=int($osim*100.0);
2133: my %old_course_desc =
2134: &Apache::lonnet::coursedescription($ocrsid,
2135: {'one_time' => 1});
2136:
2137: $similar="<hr /><h3><span class=\"LC_warning\">".
2138: &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
2139: $osim,
2140: &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
2141: $old_course_desc{'description'},
2142: $old_course_desc{'num'},
2143: $old_course_desc{'domain'}).
2144: '</span></h3><blockquote><i>'.
2145: &keywords_highlight($oessay).
2146: '</i></blockquote><hr />';
2147: }
2148: }
2149: my $order=&get_order($partid,$respid,$symb,$uname,$udom);
2150: if ($env{'form.lastSub'} eq 'lastonly' ||
2151: ($env{'form.lastSub'} eq 'hdgrade' &&
2152: $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
2153: my $display_part=&get_display_part($partid,$symb);
2154: $lastsubonly.='<div class="LC_grade_submission_part"><b>Part:</b> '.
2155: $display_part.' <span class="LC_internal_info">( ID '.$respid.
2156: ' )</span> ';
2157: my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
2158: if (@$files) {
2159: $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
2160: my $file_counter = 0;
2161: foreach my $file (@$files) {
2162: $file_counter++;
2163: &Apache::lonnet::allowuploaded('/adm/grades',$file);
2164: $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
2165: }
2166: $lastsubonly.='<br />';
2167: }
2168: $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
2169: &cleanRecord($subval,$responsetype,$symb,$partid,
2170: $respid,\%record,$order,undef,$uname,$udom);
2171: if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
2172: $lastsubonly.='</div>';
2173: }
2174: }
2175: }
2176: $lastsubonly.='</div>'."\n";
2177: }
2178: $request->print($lastsubonly);
2179: } elsif ($env{'form.lastSub'} eq 'datesub') {
2180: my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
2181: $request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
2182: } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
2183: $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
2184: $env{'request.course.id'},
2185: $last,'.submission',
2186: 'Apache::grades::keywords_highlight'));
2187: }
2188:
2189: $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
2190: .$udom.'" />'."\n");
2191: # return if view submission with no grading option
2192: if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
2193: my $toGrade.='<input type="button" value="Grade Student" '.
2194: 'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
2195: .$counter.'\');" target="_self" /> '."\n" if (&canmodify($usec));
2196: $toGrade.='</div>'."\n";
2197: if (($env{'form.command'} eq 'submission') ||
2198: ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
2199: $toGrade.='</form>'.&show_grading_menu_form($symb);
2200: }
2201: $request->print($toGrade);
2202: return;
2203: } else {
2204: $request->print('</div>'."\n");
2205: }
2206:
2207: # essay grading message center
2208: if ($env{'form.handgrade'} eq 'yes') {
2209: my $result='<div class="LC_grade_message_center">';
2210:
2211: $result.='<div class="LC_grade_message_center_header">'.
2212: &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
2213: my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
2214: my $msgfor = $givenn.' '.$lastname;
2215: if (scalar(@$col_fullnames) > 0) {
2216: my $lastone = pop(@$col_fullnames);
2217: $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
2218: }
2219: $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
2220: $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
2221: '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
2222: $result.=' <a href="javascript:msgCenter(document.SCORE,'.$counter.
2223: ',\''.$msgfor.'\');" target="_self">'.
2224: &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
2225: &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
2226: '<img src="'.$request->dir_config('lonIconsURL').
2227: '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
2228: '<br /> ('.
2229: &mt('Message will be sent when you click on Save & Next below.').")\n";
2230: $result.='</div></div>';
2231: $request->print($result);
2232: }
2233:
2234: my %seen = ();
2235: my @partlist;
2236: my @gradePartRespid;
2237: my @part_response_id = &flatten_responseType($responseType);
2238: $request->print('<div class="LC_grade_assign">'.
2239:
2240: '<div class="LC_grade_assign_header">'.
2241: &mt('Assign Grades').'</div>'.
2242: '<div class="LC_grade_assign_body">');
2243: foreach my $part_response_id (@part_response_id) {
2244: my ($partid,$respid) = @{ $part_response_id };
2245: my $part_resp = join('_',@{ $part_response_id });
2246: next if ($seen{$partid} > 0);
2247: $seen{$partid}++;
2248: next if ($$handgrade{$part_resp} ne 'yes'
2249: && $env{'form.lastSub'} eq 'hdgrade');
2250: push(@partlist,$partid);
2251: push(@gradePartRespid,$partid.'.'.$respid);
2252: $request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
2253: }
2254: $request->print('</div></div>');
2255:
2256: $request->print('<div class="LC_grade_info_links">');
2257: if ($perm{'vgr'}) {
2258: $request->print(
2259: &Apache::loncommon::track_student_link(&mt('View recent activity'),
2260: $uname,$udom,'check'));
2261: }
2262: if ($perm{'opa'}) {
2263: $request->print(
2264: &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
2265: $uname,$udom,$symb,'check'));
2266: }
2267: $request->print('</div>');
2268:
2269: $result='<input type="hidden" name="partlist'.$counter.
2270: '" value="'.(join ":",@partlist).'" />'."\n";
2271: $result.='<input type="hidden" name="gradePartRespid'.
2272: '" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
2273: my $ctr = 0;
2274: while ($ctr < scalar(@partlist)) {
2275: $result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
2276: $partlist[$ctr].'" />'."\n";
2277: $ctr++;
2278: }
2279: $request->print($result.''."\n");
2280:
2281: # Done with printing info for one student
2282:
2283: $request->print('</div>');#LC_grade_show_user_body
2284: $request->print('</div>');#LC_grade_show_user
2285:
2286:
2287: # print end of form
2288: if ($counter == $total) {
2289: my $endform='<table border="0"><tr><td>'."\n";
2290: $endform.='<input type="button" value="'.&mt('Save & Next').'" '.
2291: 'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
2292: $total.','.scalar(@partlist).');" target="_self" /> '."\n";
2293: my $ntstu ='<select name="NTSTU">'.
2294: '<option>1</option><option>2</option>'.
2295: '<option>3</option><option>5</option>'.
2296: '<option>7</option><option>10</option></select>'."\n";
2297: my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
2298: $ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
2299: $endform.=&mt('[quant,_1,student]',$ntstu);
2300: $endform.=' <input type="button" value="'.&mt('Previous').'" '.
2301: 'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> '."\n".
2302: '<input type="button" value="'.&mt('Next').'" '.
2303: 'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> ';
2304: $endform.=&mt('(Next and Previous (student) do not save the scores.)')."\n" ;
2305: $endform.="<input type='hidden' value='".&get_increment().
2306: "' name='increment' />";
2307: $endform.='</td></tr></table></form>';
2308: $endform.=&show_grading_menu_form($symb);
2309: $request->print($endform);
2310: }
2311: return '';
2312: }
2313:
2314: sub check_collaborators {
2315: my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
2316: my ($result,@col_fullnames);
2317: my ($classlist,undef,$fullname) = &getclasslist('all','0');
2318: foreach my $part (keys(%$handgrade)) {
2319: my $ncol = &Apache::lonnet::EXT('resource.'.$part.
2320: '.maxcollaborators',
2321: $symb,$udom,$uname);
2322: next if ($ncol <= 0);
2323: $part =~ s/\_/\./g;
2324: next if ($record->{'resource.'.$part.'.collaborators'} eq '');
2325: my (@good_collaborators, @bad_collaborators);
2326: foreach my $possible_collaborator
2327: (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) {
2328: $possible_collaborator =~ s/[\$\^\(\)]//g;
2329: next if ($possible_collaborator eq '');
2330: my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
2331: $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
2332: next if ($co_name eq $uname && $co_dom eq $udom);
2333: # Doing this grep allows 'fuzzy' specification
2334: my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i,
2335: keys(%$classlist));
2336: if (! scalar(@matches)) {
2337: push(@bad_collaborators, $possible_collaborator);
2338: } else {
2339: push(@good_collaborators, @matches);
2340: }
2341: }
2342: if (scalar(@good_collaborators) != 0) {
2343: $result.='<br />'.&mt('Collaborators: ');
2344: foreach my $name (@good_collaborators) {
2345: my ($lastname,$givenn) = split(/,/,$$fullname{$name});
2346: push(@col_fullnames, $givenn.' '.$lastname);
2347: $result.=$fullname->{$name}.' ';
2348: }
2349: $result.='<br />'."\n";
2350: my ($part)=split(/\./,$part);
2351: $result.='<input type="hidden" name="collaborator'.$counter.
2352: '" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
2353: "\n";
2354: }
2355: if (scalar(@bad_collaborators) > 0) {
2356: $result.='<div class="LC_warning">';
2357: $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
2358: $result .= '</div>';
2359: }
2360: if (scalar(@bad_collaborators > $ncol)) {
2361: $result .= '<div class="LC_warning">';
2362: $result .= &mt('This student has submitted too many '.
2363: 'collaborators. Maximum is [_1].',$ncol);
2364: $result .= '</div>';
2365: }
2366: }
2367: return ($result,$fullname,\@col_fullnames);
2368: }
2369:
2370: #--- Retrieve the last submission for all the parts
2371: sub get_last_submission {
2372: my ($returnhash)=@_;
2373: my (@string,$timestamp);
2374: if ($$returnhash{'version'}) {
2375: my %lasthash=();
2376: my ($version);
2377: for ($version=1;$version<=$$returnhash{'version'};$version++) {
2378: foreach my $key (sort(split(/\:/,
2379: $$returnhash{$version.':keys'}))) {
2380: $lasthash{$key}=$$returnhash{$version.':'.$key};
2381: $timestamp =
2382: &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
2383: }
2384: }
2385: foreach my $key (keys(%lasthash)) {
2386: next if ($key !~ /\.submission$/);
2387:
2388: my ($partid,$foo) = split(/submission$/,$key);
2389: my $draft = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
2390: '<span class="LC_warning">Draft Copy</span> ' : '';
2391: push(@string, join(':', $key, $draft.$lasthash{$key}));
2392: }
2393: }
2394: if (!@string) {
2395: $string[0] =
2396: '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
2397: }
2398: return (\@string,\$timestamp);
2399: }
2400:
2401: #--- High light keywords, with style choosen by user.
2402: sub keywords_highlight {
2403: my $string = shift;
2404: my $size = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
2405: my $styleon = $env{'form.kwstyle'} eq '' ? '' : $env{'form.kwstyle'};
2406: (my $styleoff = $styleon) =~ s/\</\<\//;
2407: my @keylist = split(/[,\s+]/,$env{'form.keywords'});
2408: foreach my $keyword (@keylist) {
2409: $string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
2410: }
2411: return $string;
2412: }
2413:
2414: #--- Called from submission routine
2415: sub processHandGrade {
2416: my ($request) = shift;
2417: my $symb = &get_symb($request);
2418: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
2419: my $button = $env{'form.gradeOpt'};
2420: my $ngrade = $env{'form.NCT'};
2421: my $ntstu = $env{'form.NTSTU'};
2422: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2423: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2424:
2425: if ($button eq 'Save & Next') {
2426: my $ctr = 0;
2427: while ($ctr < $ngrade) {
2428: my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
2429: my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
2430: if ($errorflag eq 'no_score') {
2431: $ctr++;
2432: next;
2433: }
2434: if ($errorflag eq 'not_allowed') {
2435: $request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
2436: $ctr++;
2437: next;
2438: }
2439: my $includemsg = $env{'form.includemsg'.$ctr};
2440: my ($subject,$message,$msgstatus) = ('','','');
2441: my $restitle = &Apache::lonnet::gettitle($symb);
2442: my ($feedurl,$showsymb) =
2443: &get_feedurl_and_symb($symb,$uname,$udom);
2444: my $messagetail;
2445: if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
2446: $subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
2447: unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
2448: $subject.=' ['.$restitle.']';
2449: my (@msgnum) = split(/,/,$includemsg);
2450: foreach (@msgnum) {
2451: $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
2452: }
2453: $message =&Apache::lonfeedback::clear_out_html($message);
2454: if ($env{'form.withgrades'.$ctr}) {
2455: $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
2456: $messagetail = " for <a href=\"".
2457: $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
2458: }
2459: $msgstatus =
2460: &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
2461: $message.$messagetail,
2462: undef,$feedurl,undef,
2463: undef,undef,$showsymb,
2464: $restitle);
2465: $request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
2466: $msgstatus);
2467: }
2468: if ($env{'form.collaborator'.$ctr}) {
2469: my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
2470: foreach my $collabstr (@collabstrs) {
2471: my ($part,@collaborators) = split(/:/,$collabstr);
2472: foreach my $collaborator (@collaborators) {
2473: my ($errorflag,$pts,$wgt) =
2474: &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
2475: $env{'form.unamedom'.$ctr},$part);
2476: if ($errorflag eq 'not_allowed') {
2477: $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
2478: next;
2479: } elsif ($message ne '') {
2480: my ($baseurl,$showsymb) =
2481: &get_feedurl_and_symb($symb,$collaborator,
2482: $udom);
2483: if ($env{'form.withgrades'.$ctr}) {
2484: $messagetail = " for <a href=\"".
2485: $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
2486: }
2487: $msgstatus =
2488: &Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
2489: }
2490: }
2491: }
2492: }
2493: $ctr++;
2494: }
2495: }
2496:
2497: if ($env{'form.handgrade'} eq 'yes') {
2498: # Keywords sorted in alphabatical order
2499: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
2500: my %keyhash = ();
2501: $env{'form.keywords'} =~ s/,\s{0,}|\s+/ /g;
2502: $env{'form.keywords'} =~ s/^\s+|\s+$//;
2503: my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
2504: $env{'form.keywords'} = join(' ',@keywords);
2505: $keyhash{$symb.'_keywords'} = $env{'form.keywords'};
2506: $keyhash{$symb.'_subject'} = $env{'form.msgsub'};
2507: $keyhash{$loginuser.'_kwclr'} = $env{'form.kwclr'};
2508: $keyhash{$loginuser.'_kwsize'} = $env{'form.kwsize'};
2509: $keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
2510:
2511: # message center - Order of message gets changed. Blank line is eliminated.
2512: # New messages are saved in env for the next student.
2513: # All messages are saved in nohist_handgrade.db
2514: my ($ctr,$idx) = (1,1);
2515: while ($ctr <= $env{'form.savemsgN'}) {
2516: if ($env{'form.savemsg'.$ctr} ne '') {
2517: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
2518: $idx++;
2519: }
2520: $ctr++;
2521: }
2522: $ctr = 0;
2523: while ($ctr < $ngrade) {
2524: if ($env{'form.newmsg'.$ctr} ne '') {
2525: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2526: $env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2527: $idx++;
2528: }
2529: $ctr++;
2530: }
2531: $env{'form.savemsgN'} = --$idx;
2532: $keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
2533: my $putresult = &Apache::lonnet::put
2534: ('nohist_handgrade',\%keyhash,$cdom,$cnum);
2535: }
2536: # Called by Save & Refresh from Highlight Attribute Window
2537: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
2538: if ($env{'form.refresh'} eq 'on') {
2539: my ($ctr,$total) = (0,0);
2540: while ($ctr < $ngrade) {
2541: $total++ if $env{'form.unamedom'.$ctr} ne '';
2542: $ctr++;
2543: }
2544: $env{'form.NTSTU'}=$ngrade;
2545: $ctr = 0;
2546: while ($ctr < $total) {
2547: my $processUser = $env{'form.unamedom'.$ctr};
2548: ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
2549: $env{'form.fullname'} = $$fullname{$processUser};
2550: &submission($request,$ctr,$total-1);
2551: $ctr++;
2552: }
2553: return '';
2554: }
2555:
2556: # Go directly to grade student - from submission or link from chart page
2557: if ($button eq 'Grade Student') {
2558: (undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
2559: my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
2560: ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
2561: $env{'form.fullname'} = $$fullname{$processUser};
2562: &submission($request,0,0);
2563: return '';
2564: }
2565:
2566: # Get the next/previous one or group of students
2567: my $firststu = $env{'form.unamedom0'};
2568: my $laststu = $env{'form.unamedom'.($ngrade-1)};
2569: my $ctr = 2;
2570: while ($laststu eq '') {
2571: $laststu = $env{'form.unamedom'.($ngrade-$ctr)};
2572: $ctr++;
2573: $laststu = $firststu if ($ctr > $ngrade);
2574: }
2575:
2576: my (@parsedlist,@nextlist);
2577: my ($nextflg) = 0;
2578: foreach my $item (sort
2579: {
2580: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
2581: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
2582: }
2583: return $a cmp $b;
2584: } (keys(%$fullname))) {
2585: if ($nextflg == 1 && $button =~ /Next$/) {
2586: push(@parsedlist,$item);
2587: }
2588: $nextflg = 1 if ($item eq $laststu);
2589: if ($button eq 'Previous') {
2590: last if ($item eq $firststu);
2591: push(@parsedlist,$item);
2592: }
2593: }
2594: $ctr = 0;
2595: @parsedlist = reverse @parsedlist if ($button eq 'Previous');
2596: my ($partlist) = &response_type($symb);
2597: foreach my $student (@parsedlist) {
2598: my $submitonly=$env{'form.submitonly'};
2599: my ($uname,$udom) = split(/:/,$student);
2600:
2601: if ($submitonly eq 'queued') {
2602: my %queue_status =
2603: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
2604: $udom,$uname);
2605: next if (!defined($queue_status{'gradingqueue'}));
2606: }
2607:
2608: if ($submitonly =~ /^(yes|graded|incorrect)$/) {
2609: # my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
2610: my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
2611: my $submitted = 0;
2612: my $ungraded = 0;
2613: my $incorrect = 0;
2614: foreach my $item (keys(%status)) {
2615: $submitted = 1 if ($status{$item} ne 'nothing');
2616: $ungraded = 1 if ($status{$item} =~ /^ungraded/);
2617: $incorrect = 1 if ($status{$item} =~ /^incorrect/);
2618: my ($foo,$partid,$foo1) = split(/\./,$item);
2619: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
2620: $submitted = 0;
2621: }
2622: }
2623: next if (!$submitted && ($submitonly eq 'yes' ||
2624: $submitonly eq 'incorrect' ||
2625: $submitonly eq 'graded'));
2626: next if (!$ungraded && ($submitonly eq 'graded'));
2627: next if (!$incorrect && $submitonly eq 'incorrect');
2628: }
2629: push(@nextlist,$student) if ($ctr < $ntstu);
2630: last if ($ctr == $ntstu);
2631: $ctr++;
2632: }
2633:
2634: $ctr = 0;
2635: my $total = scalar(@nextlist)-1;
2636:
2637: foreach (sort(@nextlist)) {
2638: my ($uname,$udom,$submitter) = split(/:/);
2639: $env{'form.student'} = $uname;
2640: $env{'form.userdom'} = $udom;
2641: $env{'form.fullname'} = $$fullname{$_};
2642: &submission($request,$ctr,$total);
2643: $ctr++;
2644: }
2645: if ($total < 0) {
2646: my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
2647: $the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
2648: $the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
2649: $the_end.=&show_grading_menu_form($symb);
2650: $request->print($the_end);
2651: }
2652: return '';
2653: }
2654:
2655: #---- Save the score and award for each student, if changed
2656: sub saveHandGrade {
2657: my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
2658: my @version_parts;
2659: my $usec = &Apache::lonnet::getsection($domain,$stuname,
2660: $env{'request.course.id'});
2661: if (!&canmodify($usec)) { return('not_allowed'); }
2662: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
2663: my @parts_graded;
2664: my %newrecord = ();
2665: my ($pts,$wgt) = ('','');
2666: my %aggregate = ();
2667: my $aggregateflag = 0;
2668: my @parts = split(/:/,$env{'form.partlist'.$newflg});
2669: foreach my $new_part (@parts) {
2670: #collaborator ($submi may vary for different parts
2671: if ($submitter && $new_part ne $part) { next; }
2672: my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
2673: if ($dropMenu eq 'excused') {
2674: if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
2675: $newrecord{'resource.'.$new_part.'.solved'} = 'excused';
2676: if (exists($record{'resource.'.$new_part.'.awarded'})) {
2677: $newrecord{'resource.'.$new_part.'.awarded'} = '';
2678: }
2679: $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
2680: }
2681: } elsif ($dropMenu eq 'reset status'
2682: && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
2683: foreach my $key (keys(%record)) {
2684: if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
2685: }
2686: $newrecord{'resource.'.$new_part.'.regrader'}=
2687: "$env{'user.name'}:$env{'user.domain'}";
2688: my $totaltries = $record{'resource.'.$part.'.tries'};
2689:
2690: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
2691: [$new_part]);
2692: my $aggtries =$totaltries;
2693: if ($last_resets{$new_part}) {
2694: $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
2695: $new_part);
2696: }
2697:
2698: my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
2699: if ($aggtries > 0) {
2700: &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
2701: $aggregateflag = 1;
2702: }
2703: } elsif ($dropMenu eq '') {
2704: $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ?
2705: $env{'form.GD_BOX'.$newflg.'_'.$new_part} :
2706: $env{'form.RADVAL'.$newflg.'_'.$new_part});
2707: if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
2708: next;
2709: }
2710: $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 :
2711: $env{'form.WGT'.$newflg.'_'.$new_part};
2712: my $partial= $pts/$wgt;
2713: if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
2714: #do not update score for part if not changed.
2715: &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
2716: next;
2717: } else {
2718: push(@parts_graded,$new_part);
2719: }
2720: if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
2721: $newrecord{'resource.'.$new_part.'.awarded'} = $partial;
2722: }
2723: my $reckey = 'resource.'.$new_part.'.solved';
2724: if ($partial == 0) {
2725: if ($record{$reckey} ne 'incorrect_by_override') {
2726: $newrecord{$reckey} = 'incorrect_by_override';
2727: }
2728: } else {
2729: if ($record{$reckey} ne 'correct_by_override') {
2730: $newrecord{$reckey} = 'correct_by_override';
2731: }
2732: }
2733: if ($submitter &&
2734: ($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
2735: $newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
2736: }
2737: $newrecord{'resource.'.$new_part.'.regrader'}=
2738: "$env{'user.name'}:$env{'user.domain'}";
2739: }
2740: # unless problem has been graded, set flag to version the submitted files
2741: unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/ ||
2742: $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
2743: $dropMenu eq 'reset status')
2744: {
2745: push(@version_parts,$new_part);
2746: }
2747: }
2748: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2749: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2750:
2751: if (%newrecord) {
2752: if (@version_parts) {
2753: my @changed_keys = &version_portfiles(\%record, \@parts_graded,
2754: $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
2755: @newrecord{@changed_keys} = @record{@changed_keys};
2756: foreach my $new_part (@version_parts) {
2757: &handback_files($request,$symb,$stuname,$domain,$newflg,
2758: $new_part,\%newrecord);
2759: }
2760: }
2761: &Apache::lonnet::cstore(\%newrecord,$symb,
2762: $env{'request.course.id'},$domain,$stuname);
2763: &check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
2764: $cdom,$cnum,$domain,$stuname);
2765: }
2766: if ($aggregateflag) {
2767: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
2768: $cdom,$cnum);
2769: }
2770: return ('',$pts,$wgt);
2771: }
2772:
2773: sub check_and_remove_from_queue {
2774: my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
2775: my @ungraded_parts;
2776: foreach my $part (@{$parts}) {
2777: if ( $record->{ 'resource.'.$part.'.awarded'} eq ''
2778: && $record->{ 'resource.'.$part.'.solved' } ne 'excused'
2779: && $newrecord->{'resource.'.$part.'.awarded'} eq ''
2780: && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
2781: ) {
2782: push(@ungraded_parts, $part);
2783: }
2784: }
2785: if ( !@ungraded_parts ) {
2786: &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
2787: $cnum,$domain,$stuname);
2788: }
2789: }
2790:
2791: sub handback_files {
2792: my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
2793: my $portfolio_root = '/userfiles/portfolio';
2794: my ($partlist,$handgrade,$responseType) = &response_type($symb);
2795:
2796: my @part_response_id = &flatten_responseType($responseType);
2797: foreach my $part_response_id (@part_response_id) {
2798: my ($part_id,$resp_id) = @{ $part_response_id };
2799: my $part_resp = join('_',@{ $part_response_id });
2800: if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
2801: # if multiple files are uploaded names will be 'returndoc2','returndoc3'
2802: my $file_counter = 1;
2803: my $file_msg;
2804: while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
2805: my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
2806: my ($directory,$answer_file) =
2807: ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
2808: my ($answer_name,$answer_ver,$answer_ext) =
2809: &file_name_version_ext($answer_file);
2810: my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
2811: my $getpropath = 1;
2812: my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
2813: my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
2814: # fix file name
2815: my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
2816: my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
2817: $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
2818: $save_file_name);
2819: if ($result !~ m|^/uploaded/|) {
2820: $request->print('<br /><span class="LC_error">'.
2821: &mt('An error occurred ([_1]) while trying to upload [_2].',
2822: $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
2823: '</span>');
2824: } else {
2825: # mark the file as read only
2826: my @files = ($save_file_name);
2827: my @what = ($symb,$env{'request.course.id'},'handback');
2828: &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
2829: if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
2830: $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
2831: }
2832: $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
2833: $file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
2834:
2835: }
2836: $request->print("<br />".$fname." will be the uploaded file name");
2837: $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
2838: $file_counter++;
2839: }
2840: my $subject = "File Handed Back by Instructor ";
2841: my $message = "A file has been returned that was originally submitted in reponse to: <br />";
2842: $message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
2843: $message .= ' The returned file(s) are named: '. $file_msg;
2844: $message .= " and can be found in your portfolio space.";
2845: my ($feedurl,$showsymb) =
2846: &get_feedurl_and_symb($symb,$domain,$stuname);
2847: my $restitle = &Apache::lonnet::gettitle($symb);
2848: my $msgstatus =
2849: &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
2850: ' (File Returned) ['.$restitle.']',$message,undef,
2851: $feedurl,undef,undef,undef,$showsymb,$restitle);
2852: }
2853: }
2854: return;
2855: }
2856:
2857: sub get_feedurl_and_symb {
2858: my ($symb,$uname,$udom) = @_;
2859: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
2860: $url = &Apache::lonnet::clutter($url);
2861: my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
2862: $symb,$udom,$uname);
2863: if ($encrypturl =~ /^yes$/i) {
2864: &Apache::lonenc::encrypted(\$url,1);
2865: &Apache::lonenc::encrypted(\$symb,1);
2866: }
2867: return ($url,$symb);
2868: }
2869:
2870: sub get_submitted_files {
2871: my ($udom,$uname,$partid,$respid,$record) = @_;
2872: my @files;
2873: if ($$record{"resource.$partid.$respid.portfiles"}) {
2874: my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
2875: foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
2876: push(@files,$file_url.$file);
2877: }
2878: }
2879: if ($$record{"resource.$partid.$respid.uploadedurl"}) {
2880: push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
2881: }
2882: return (\@files);
2883: }
2884:
2885: # ----------- Provides number of tries since last reset.
2886: sub get_num_tries {
2887: my ($record,$last_reset,$part) = @_;
2888: my $timestamp = '';
2889: my $num_tries = 0;
2890: if ($$record{'version'}) {
2891: for (my $version=$$record{'version'};$version>=1;$version--) {
2892: if (exists($$record{$version.':resource.'.$part.'.solved'})) {
2893: $timestamp = $$record{$version.':timestamp'};
2894: if ($timestamp > $last_reset) {
2895: $num_tries ++;
2896: } else {
2897: last;
2898: }
2899: }
2900: }
2901: }
2902: return $num_tries;
2903: }
2904:
2905: # ----------- Determine decrements required in aggregate totals
2906: sub decrement_aggs {
2907: my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
2908: my %decrement = (
2909: attempts => 0,
2910: users => 0,
2911: correct => 0
2912: );
2913: $decrement{'attempts'} = $aggtries;
2914: if ($solvedstatus =~ /^correct/) {
2915: $decrement{'correct'} = 1;
2916: }
2917: if ($aggtries == $totaltries) {
2918: $decrement{'users'} = 1;
2919: }
2920: foreach my $type (keys(%decrement)) {
2921: $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
2922: }
2923: return;
2924: }
2925:
2926: # ----------- Determine timestamps for last reset of aggregate totals for parts
2927: sub get_last_resets {
2928: my ($symb,$courseid,$partids) =@_;
2929: my %last_resets;
2930: my $cdom = $env{'course.'.$courseid.'.domain'};
2931: my $cname = $env{'course.'.$courseid.'.num'};
2932: my @keys;
2933: foreach my $part (@{$partids}) {
2934: push(@keys,"$symb\0$part\0resettime");
2935: }
2936: my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
2937: $cdom,$cname);
2938: foreach my $part (@{$partids}) {
2939: $last_resets{$part}=$results{"$symb\0$part\0resettime"};
2940: }
2941: return %last_resets;
2942: }
2943:
2944: # ----------- Handles creating versions for portfolio files as answers
2945: sub version_portfiles {
2946: my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
2947: my $version_parts = join('|',@$v_flag);
2948: my @returned_keys;
2949: my $parts = join('|', @$parts_graded);
2950: my $portfolio_root = '/userfiles/portfolio';
2951: foreach my $key (keys(%$record)) {
2952: my $new_portfiles;
2953: if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
2954: my @versioned_portfiles;
2955: my @portfiles = split(/\s*,\s*/,$$record{$key});
2956: foreach my $file (@portfiles) {
2957: &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
2958: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
2959: my ($answer_name,$answer_ver,$answer_ext) =
2960: &file_name_version_ext($answer_file);
2961: my $getpropath = 1;
2962: my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
2963: my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
2964: my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
2965: if ($new_answer ne 'problem getting file') {
2966: push(@versioned_portfiles, $directory.$new_answer);
2967: &Apache::lonnet::mark_as_readonly($domain,$stu_name,
2968: [$directory.$new_answer],
2969: [$symb,$env{'request.course.id'},'graded']);
2970: }
2971: }
2972: $$record{$key} = join(',',@versioned_portfiles);
2973: push(@returned_keys,$key);
2974: }
2975: }
2976: return (@returned_keys);
2977: }
2978:
2979: sub get_next_version {
2980: my ($answer_name, $answer_ext, $dir_list) = @_;
2981: my $version;
2982: foreach my $row (@$dir_list) {
2983: my ($file) = split(/\&/,$row,2);
2984: my ($file_name,$file_version,$file_ext) =
2985: &file_name_version_ext($file);
2986: if (($file_name eq $answer_name) &&
2987: ($file_ext eq $answer_ext)) {
2988: # gets here if filename and extension match, regardless of version
2989: if ($file_version ne '') {
2990: # a versioned file is found so save it for later
2991: if ($file_version > $version) {
2992: $version = $file_version;
2993: }
2994: }
2995: }
2996: }
2997: $version ++;
2998: return($version);
2999: }
3000:
3001: sub version_selected_portfile {
3002: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
3003: my ($answer_name,$answer_ver,$answer_ext) =
3004: &file_name_version_ext($file_name);
3005: my $new_answer;
3006: $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
3007: if($env{'form.copy'} eq '-1') {
3008: $new_answer = 'problem getting file';
3009: } else {
3010: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
3011: my $copy_result = &Apache::lonnet::finishuserfileupload(
3012: $stu_name,$domain,'copy',
3013: '/portfolio'.$directory.$new_answer);
3014: }
3015: return ($new_answer);
3016: }
3017:
3018: sub file_name_version_ext {
3019: my ($file)=@_;
3020: my @file_parts = split(/\./, $file);
3021: my ($name,$version,$ext);
3022: if (@file_parts > 1) {
3023: $ext=pop(@file_parts);
3024: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
3025: $version=pop(@file_parts);
3026: }
3027: $name=join('.',@file_parts);
3028: } else {
3029: $name=join('.',@file_parts);
3030: }
3031: return($name,$version,$ext);
3032: }
3033:
3034: #--------------------------------------------------------------------------------------
3035: #
3036: #-------------------------- Next few routines handles grading by section or whole class
3037: #
3038: #--- Javascript to handle grading by section or whole class
3039: sub viewgrades_js {
3040: my ($request) = shift;
3041:
3042: my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
3043: $request->print(<<VIEWJAVASCRIPT);
3044: <script type="text/javascript" language="javascript">
3045: function writePoint(partid,weight,point) {
3046: var radioButton = document.classgrade["RADVAL_"+partid];
3047: var textbox = document.classgrade["TEXTVAL_"+partid];
3048: if (point == "textval") {
3049: point = document.classgrade["TEXTVAL_"+partid].value;
3050: if (isNaN(point) || parseFloat(point) < 0) {
3051: alert("$alertmsg"+parseFloat(point));
3052: var resetbox = false;
3053: for (var i=0; i<radioButton.length; i++) {
3054: if (radioButton[i].checked) {
3055: textbox.value = i;
3056: resetbox = true;
3057: }
3058: }
3059: if (!resetbox) {
3060: textbox.value = "";
3061: }
3062: return;
3063: }
3064: if (parseFloat(point) > parseFloat(weight)) {
3065: var resp = confirm("You entered a value ("+parseFloat(point)+
3066: ") greater than the weight for the part. Accept?");
3067: if (resp == false) {
3068: textbox.value = "";
3069: return;
3070: }
3071: }
3072: for (var i=0; i<radioButton.length; i++) {
3073: radioButton[i].checked=false;
3074: if (parseFloat(point) == i) {
3075: radioButton[i].checked=true;
3076: }
3077: }
3078:
3079: } else {
3080: textbox.value = parseFloat(point);
3081: }
3082: for (i=0;i<document.classgrade.total.value;i++) {
3083: var user = document.classgrade["ctr"+i].value;
3084: user = user.replace(new RegExp(':', 'g'),"_");
3085: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3086: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3087: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3088: if (saveval != "correct") {
3089: scorename.value = point;
3090: if (selname[0].selected != true) {
3091: selname[0].selected = true;
3092: }
3093: }
3094: }
3095: document.classgrade["SELVAL_"+partid][0].selected = true;
3096: }
3097:
3098: function writeRadText(partid,weight) {
3099: var selval = document.classgrade["SELVAL_"+partid];
3100: var radioButton = document.classgrade["RADVAL_"+partid];
3101: var override = document.classgrade["FORCE_"+partid].checked;
3102: var textbox = document.classgrade["TEXTVAL_"+partid];
3103: if (selval[1].selected || selval[2].selected) {
3104: for (var i=0; i<radioButton.length; i++) {
3105: radioButton[i].checked=false;
3106:
3107: }
3108: textbox.value = "";
3109:
3110: for (i=0;i<document.classgrade.total.value;i++) {
3111: var user = document.classgrade["ctr"+i].value;
3112: user = user.replace(new RegExp(':', 'g'),"_");
3113: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3114: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3115: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3116: if ((saveval != "correct") || override) {
3117: scorename.value = "";
3118: if (selval[1].selected) {
3119: selname[1].selected = true;
3120: } else {
3121: selname[2].selected = true;
3122: if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value))
3123: {document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
3124: }
3125: }
3126: }
3127: } else {
3128: for (i=0;i<document.classgrade.total.value;i++) {
3129: var user = document.classgrade["ctr"+i].value;
3130: user = user.replace(new RegExp(':', 'g'),"_");
3131: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3132: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3133: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3134: if ((saveval != "correct") || override) {
3135: scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
3136: selname[0].selected = true;
3137: }
3138: }
3139: }
3140: }
3141:
3142: function changeSelect(partid,user) {
3143: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
3144: var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
3145: var point = textbox.value;
3146: var weight = document.classgrade["weight_"+partid].value;
3147:
3148: if (isNaN(point) || parseFloat(point) < 0) {
3149: alert("$alertmsg"+parseFloat(point));
3150: textbox.value = "";
3151: return;
3152: }
3153: if (parseFloat(point) > parseFloat(weight)) {
3154: var resp = confirm("You entered a value ("+parseFloat(point)+
3155: ") greater than the weight of the part. Accept?");
3156: if (resp == false) {
3157: textbox.value = "";
3158: return;
3159: }
3160: }
3161: selval[0].selected = true;
3162: }
3163:
3164: function changeOneScore(partid,user) {
3165: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
3166: if (selval[1].selected || selval[2].selected) {
3167: document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
3168: if (selval[2].selected) {
3169: document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
3170: }
3171: }
3172: }
3173:
3174: function resetEntry(numpart) {
3175: for (ctpart=0;ctpart<numpart;ctpart++) {
3176: var partid = document.classgrade["partid_"+ctpart].value;
3177: var radioButton = document.classgrade["RADVAL_"+partid];
3178: var textbox = document.classgrade["TEXTVAL_"+partid];
3179: var selval = document.classgrade["SELVAL_"+partid];
3180: for (var i=0; i<radioButton.length; i++) {
3181: radioButton[i].checked=false;
3182:
3183: }
3184: textbox.value = "";
3185: selval[0].selected = true;
3186:
3187: for (i=0;i<document.classgrade.total.value;i++) {
3188: var user = document.classgrade["ctr"+i].value;
3189: user = user.replace(new RegExp(':', 'g'),"_");
3190: var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3191: resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
3192: var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
3193: resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
3194: var saveselval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3195: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3196: if (saveselval == "excused") {
3197: if (selname[1].selected == false) { selname[1].selected = true;}
3198: } else {
3199: if (selname[0].selected == false) {selname[0].selected = true};
3200: }
3201: }
3202: }
3203: }
3204:
3205: </script>
3206: VIEWJAVASCRIPT
3207: }
3208:
3209: #--- show scores for a section or whole class w/ option to change/update a score
3210: sub viewgrades {
3211: my ($request) = shift;
3212: &viewgrades_js($request);
3213:
3214: my ($symb) = &get_symb($request);
3215: #need to make sure we have the correct data for later EXT calls,
3216: #thus invalidate the cache
3217: &Apache::lonnet::devalidatecourseresdata(
3218: $env{'course.'.$env{'request.course.id'}.'.num'},
3219: $env{'course.'.$env{'request.course.id'}.'.domain'});
3220: &Apache::lonnet::clear_EXT_cache_status();
3221:
3222: my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
3223: $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
3224:
3225: #view individual student submission form - called using Javascript viewOneStudent
3226: $result.=&jscriptNform($symb);
3227:
3228: #beginning of class grading form
3229: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
3230: $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
3231: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
3232: '<input type="hidden" name="command" value="editgrades" />'."\n".
3233: &build_section_inputs().
3234: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
3235: '<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
3236: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
3237:
3238: my ($common_header,$specific_header);
3239: if ($env{'form.section'} eq 'all') {
3240: $common_header = &mt('Assign Common Grade to Class');
3241: $specific_header = &mt('Assign Grade to Specific Students in Class');
3242: } elsif ($env{'form.section'} eq 'none') {
3243: $common_header = &mt('Assign Common Grade to Students in no Section');
3244: $specific_header = &mt('Assign Grade to Specific Students in no Section');
3245: } else {
3246: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3247: $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
3248: $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
3249: }
3250: $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
3251: #radio buttons/text box for assigning points for a section or class.
3252: #handles different parts of a problem
3253: my ($partlist,$handgrade,$responseType) = &response_type($symb);
3254: my %weight = ();
3255: my $ctsparts = 0;
3256: my %seen = ();
3257: my @part_response_id = &flatten_responseType($responseType);
3258: foreach my $part_response_id (@part_response_id) {
3259: my ($partid,$respid) = @{ $part_response_id };
3260: my $part_resp = join('_',@{ $part_response_id });
3261: next if $seen{$partid};
3262: $seen{$partid}++;
3263: my $handgrade=$$handgrade{$part_resp};
3264: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
3265: $weight{$partid} = $wgt eq '' ? '1' : $wgt;
3266:
3267: my $display_part=&get_display_part($partid,$symb);
3268: my $radio.='<table border="0"><tr>';
3269: my $ctr = 0;
3270: while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
3271: $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
3272: 'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
3273: ','.$ctr.')" />'.$ctr."</label></td>\n";
3274: $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
3275: $ctr++;
3276: }
3277: $radio.='</tr></table>';
3278: my $line = '<input type="text" name="TEXTVAL_'.
3279: $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
3280: $partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
3281: $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
3282: $line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
3283: 'onChange="javascript:writeRadText(\''.$partid.'\','.
3284: $weight{$partid}.')"> '.
3285: '<option selected="selected"> </option>'.
3286: '<option value="excused">'.&mt('excused').'</option>'.
3287: '<option value="reset status">'.&mt('reset status').'</option>'.
3288: '</select></td>'.
3289: '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
3290: $line.='<input type="hidden" name="partid_'.
3291: $ctsparts.'" value="'.$partid.'" />'."\n";
3292: $line.='<input type="hidden" name="weight_'.
3293: $partid.'" value="'.$weight{$partid}.'" />'."\n";
3294:
3295: $result.=
3296: &Apache::loncommon::start_data_table_row()."\n".
3297: '<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>'.
3298: &Apache::loncommon::end_data_table_row()."\n";
3299: $ctsparts++;
3300: }
3301: $result.=&Apache::loncommon::end_data_table()."\n".
3302: '<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
3303: $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
3304: 'onClick="javascript:resetEntry('.$ctsparts.');" />';
3305:
3306: #table listing all the students in a section/class
3307: #header of table
3308: $result.= '<h3>'.$specific_header.'</h3>'.
3309: &Apache::loncommon::start_data_table().
3310: &Apache::loncommon::start_data_table_header_row().
3311: '<th>'.&mt('No.').'</th>'.
3312: '<th>'.&nameUserString('header')."</th>\n";
3313: my (@parts) = sort(&getpartlist($symb));
3314: my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
3315: my @partids = ();
3316: foreach my $part (@parts) {
3317: my $display=&Apache::lonnet::metadata($url,$part.'.display');
3318: my $narrowtext = &mt('Tries');
3319: $display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
3320: if (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
3321: my ($partid) = &split_part_type($part);
3322: push(@partids,$partid);
3323: my $display_part=&get_display_part($partid,$symb);
3324: if ($display =~ /^Partial Credit Factor/) {
3325: $result.='<th>'.
3326: &mt('Score Part: [_1]<br /> (weight = [_2])',
3327: $display_part,$weight{$partid}).'</th>'."\n";
3328: next;
3329:
3330: } else {
3331: if ($display =~ /Problem Status/) {
3332: my $grade_status_mt = &mt('Grade Status');
3333: $display =~ s{Problem Status}{$grade_status_mt<br />};
3334: }
3335: my $part_mt = &mt('Part:');
3336: $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
3337: }
3338:
3339: $result.='<th>'.$display.'</th>'."\n";
3340: }
3341: $result.=&Apache::loncommon::end_data_table_header_row();
3342:
3343: my %last_resets =
3344: &get_last_resets($symb,$env{'request.course.id'},\@partids);
3345:
3346: #get info for each student
3347: #list all the students - with points and grade status
3348: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
3349: my $ctr = 0;
3350: foreach (sort
3351: {
3352: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
3353: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
3354: }
3355: return $a cmp $b;
3356: } (keys(%$fullname))) {
3357: $ctr++;
3358: $result.=&viewstudentgrade($symb,$env{'request.course.id'},
3359: $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
3360: }
3361: $result.=&Apache::loncommon::end_data_table();
3362: $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
3363: $result.='<input type="button" value="'.&mt('Save').'" '.
3364: 'onClick="javascript:submit();" target="_self" /></form>'."\n";
3365: if (scalar(%$fullname) eq 0) {
3366: my $colspan=3+scalar(@parts);
3367: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3368: my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
3369: $result='<span class="LC_warning">'.
3370: &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
3371: $section_display, $stu_status).
3372: '</span>';
3373: }
3374: $result.=&show_grading_menu_form($symb);
3375: return $result;
3376: }
3377:
3378: #--- call by previous routine to display each student
3379: sub viewstudentgrade {
3380: my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
3381: my ($uname,$udom) = split(/:/,$student);
3382: my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
3383: my %aggregates = ();
3384: my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
3385: '<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
3386: "\n".$ctr.' </td><td> '.
3387: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
3388: '\');" target="_self">'.$fullname.'</a> '.
3389: '<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
3390: $student=~s/:/_/; # colon doen't work in javascript for names
3391: foreach my $apart (@$parts) {
3392: my ($part,$type) = &split_part_type($apart);
3393: my $score=$record{"resource.$part.$type"};
3394: $result.='<td align="center">';
3395: my ($aggtries,$totaltries);
3396: unless (exists($aggregates{$part})) {
3397: $totaltries = $record{'resource.'.$part.'.tries'};
3398:
3399: $aggtries = $totaltries;
3400: if ($$last_resets{$part}) {
3401: $aggtries = &get_num_tries(\%record,$$last_resets{$part},
3402: $part);
3403: }
3404: $result.='<input type="hidden" name="'.
3405: 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
3406: $result.='<input type="hidden" name="'.
3407: 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
3408: $aggregates{$part} = 1;
3409: }
3410: if ($type eq 'awarded') {
3411: my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
3412: $result.='<input type="hidden" name="'.
3413: 'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
3414: $result.='<input type="text" name="'.
3415: 'GD_'.$student.'_'.$part.'_awarded" '.
3416: 'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
3417: '\')" value="'.$pts.'" size="4" /></td>'."\n";
3418: } elsif ($type eq 'solved') {
3419: my ($status,$foo)=split(/_/,$score,2);
3420: $status = 'nothing' if ($status eq '');
3421: $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
3422: $part.'_solved_s" value="'.$status.'" />'."\n";
3423: $result.=' <select name="'.
3424: 'GD_'.$student.'_'.$part.'_solved" '.
3425: 'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
3426: $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>'
3427: : '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
3428: $result.='<option value="reset status">'.&mt('reset status').'</option>';
3429: $result.="</select> </td>\n";
3430: } else {
3431: $result.='<input type="hidden" name="'.
3432: 'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
3433: "\n";
3434: $result.='<input type="text" name="'.
3435: 'GD_'.$student.'_'.$part.'_'.$type.'" '.
3436: 'value="'.$score.'" size="4" /></td>'."\n";
3437: }
3438: }
3439: $result.=&Apache::loncommon::end_data_table_row();
3440: return $result;
3441: }
3442:
3443: #--- change scores for all the students in a section/class
3444: # record does not get update if unchanged
3445: sub editgrades {
3446: my ($request) = @_;
3447:
3448: my $symb=&get_symb($request);
3449: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3450: my $title='<h2>'.&mt('Current Grade Status').'</h2>';
3451: $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
3452: $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
3453:
3454: my $result= &Apache::loncommon::start_data_table().
3455: &Apache::loncommon::start_data_table_header_row().
3456: '<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
3457: '<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
3458: my %scoreptr = (
3459: 'correct' =>'correct_by_override',
3460: 'incorrect'=>'incorrect_by_override',
3461: 'excused' =>'excused',
3462: 'ungraded' =>'ungraded_attempted',
3463: 'nothing' => '',
3464: );
3465: my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
3466:
3467: my (@partid);
3468: my %weight = ();
3469: my %columns = ();
3470: my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
3471:
3472: my (@parts) = sort(&getpartlist($symb));
3473: my $header;
3474: while ($ctr < $env{'form.totalparts'}) {
3475: my $partid = $env{'form.partid_'.$ctr};
3476: push(@partid,$partid);
3477: $weight{$partid} = $env{'form.weight_'.$partid};
3478: $ctr++;
3479: }
3480: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3481: foreach my $partid (@partid) {
3482: $header .= '<th align="center">'.&mt('Old Score').'</th>'.
3483: '<th align="center">'.&mt('New Score').'</th>';
3484: $columns{$partid}=2;
3485: foreach my $stores (@parts) {
3486: my ($part,$type) = &split_part_type($stores);
3487: if ($part !~ m/^\Q$partid\E/) { next;}
3488: if ($type eq 'awarded' || $type eq 'solved') { next; }
3489: my $display=&Apache::lonnet::metadata($url,$stores.'.display');
3490: $display =~ s/\[Part: \Q$part\E\]//;
3491: my $narrowtext = &mt('Tries');
3492: $display =~ s/Number of Attempts/$narrowtext/;
3493: $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
3494: '<th align="center">'.&mt('New').' '.$display.'</th>';
3495: $columns{$partid}+=2;
3496: }
3497: }
3498: foreach my $partid (@partid) {
3499: my $display_part=&get_display_part($partid,$symb);
3500: $result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
3501: &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
3502: '</th>';
3503:
3504: }
3505: $result .= &Apache::loncommon::end_data_table_header_row().
3506: &Apache::loncommon::start_data_table_header_row().
3507: $header.
3508: &Apache::loncommon::end_data_table_header_row();
3509: my @noupdate;
3510: my ($updateCtr,$noupdateCtr) = (1,1);
3511: for ($i=0; $i<$env{'form.total'}; $i++) {
3512: my $line;
3513: my $user = $env{'form.ctr'.$i};
3514: my ($uname,$udom)=split(/:/,$user);
3515: my %newrecord;
3516: my $updateflag = 0;
3517: $line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
3518: my $usec=$classlist->{"$uname:$udom"}[5];
3519: if (!&canmodify($usec)) {
3520: my $numcols=scalar(@partid)*4+2;
3521: push(@noupdate,
3522: $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
3523: &mt('Not allowed to modify student')."</span></td></tr>");
3524: next;
3525: }
3526: my %aggregate = ();
3527: my $aggregateflag = 0;
3528: $user=~s/:/_/; # colon doen't work in javascript for names
3529: foreach (@partid) {
3530: my $old_aw = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
3531: my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
3532: my $old_part = $old_aw eq '' ? '' : $old_part_pcr;
3533: my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
3534: my $awarded = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
3535: my $pcr = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
3536: my $partial = $awarded eq '' ? '' : $pcr;
3537: my $score;
3538: if ($partial eq '') {
3539: $score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
3540: } elsif ($partial > 0) {
3541: $score = 'correct_by_override';
3542: } elsif ($partial == 0) {
3543: $score = 'incorrect_by_override';
3544: }
3545: my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
3546: $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
3547:
3548: $newrecord{'resource.'.$_.'.regrader'}=
3549: "$env{'user.name'}:$env{'user.domain'}";
3550: if ($dropMenu eq 'reset status' &&
3551: $old_score ne '') { # ignore if no previous attempts => nothing to reset
3552: $newrecord{'resource.'.$_.'.tries'} = '';
3553: $newrecord{'resource.'.$_.'.solved'} = '';
3554: $newrecord{'resource.'.$_.'.award'} = '';
3555: $newrecord{'resource.'.$_.'.awarded'} = '';
3556: $updateflag = 1;
3557: if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
3558: my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
3559: my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
3560: my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
3561: &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
3562: $aggregateflag = 1;
3563: }
3564: } elsif (!($old_part eq $partial && $old_score eq $score)) {
3565: $updateflag = 1;
3566: $newrecord{'resource.'.$_.'.awarded'} = $partial if $partial ne '';
3567: $newrecord{'resource.'.$_.'.solved'} = $score;
3568: $rec_update++;
3569: }
3570:
3571: $line .= '<td align="center">'.$old_aw.' </td>'.
3572: '<td align="center">'.$awarded.
3573: ($score eq 'excused' ? $score : '').' </td>';
3574:
3575:
3576: my $partid=$_;
3577: foreach my $stores (@parts) {
3578: my ($part,$type) = &split_part_type($stores);
3579: if ($part !~ m/^\Q$partid\E/) { next;}
3580: if ($type eq 'awarded' || $type eq 'solved') { next; }
3581: my $old_aw = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
3582: my $awarded = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
3583: if ($awarded ne '' && $awarded ne $old_aw) {
3584: $newrecord{'resource.'.$part.'.'.$type}= $awarded;
3585: $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
3586: $updateflag=1;
3587: }
3588: $line .= '<td align="center">'.$old_aw.' </td>'.
3589: '<td align="center">'.$awarded.' </td>';
3590: }
3591: }
3592: $line.="\n";
3593:
3594: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3595: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3596:
3597: if ($updateflag) {
3598: $count++;
3599: &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
3600: $udom,$uname);
3601:
3602: if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
3603: $cnum,$udom,$uname)) {
3604: # need to figure out if should be in queue.
3605: my %record =
3606: &Apache::lonnet::restore($symb,$env{'request.course.id'},
3607: $udom,$uname);
3608: my $all_graded = 1;
3609: my $none_graded = 1;
3610: foreach my $part (@parts) {
3611: if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
3612: $all_graded = 0;
3613: } else {
3614: $none_graded = 0;
3615: }
3616: }
3617:
3618: if ($all_graded || $none_graded) {
3619: &Apache::bridgetask::remove_from_queue('gradingqueue',
3620: $symb,$cdom,$cnum,
3621: $udom,$uname);
3622: }
3623: }
3624:
3625: $result.=&Apache::loncommon::start_data_table_row().
3626: '<td align="right"> '.$updateCtr.' </td>'.$line.
3627: &Apache::loncommon::end_data_table_row();
3628: $updateCtr++;
3629: } else {
3630: push(@noupdate,
3631: '<td align="right"> '.$noupdateCtr.' </td>'.$line);
3632: $noupdateCtr++;
3633: }
3634: if ($aggregateflag) {
3635: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
3636: $cdom,$cnum);
3637: }
3638: }
3639: if (@noupdate) {
3640: # my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
3641: my $numcols=scalar(@partid)*4+2;
3642: $result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
3643: '<td align="center" colspan="'.$numcols.'">'.
3644: &mt('No Changes Occurred For the Students Below').
3645: '</td>'.
3646: &Apache::loncommon::end_data_table_row();
3647: foreach my $line (@noupdate) {
3648: $result.=
3649: &Apache::loncommon::start_data_table_row().
3650: $line.
3651: &Apache::loncommon::end_data_table_row();
3652: }
3653: }
3654: $result .= &Apache::loncommon::end_data_table().
3655: &show_grading_menu_form($symb);
3656: my $msg = '<p><b>'.
3657: &mt('Number of records updated = [_1] for [quant,_2,student].',
3658: $rec_update,$count).'</b><br />'.
3659: '<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
3660: '</b></p>';
3661: return $title.$msg.$result;
3662: }
3663:
3664: sub split_part_type {
3665: my ($partstr) = @_;
3666: my ($temp,@allparts)=split(/_/,$partstr);
3667: my $type=pop(@allparts);
3668: my $part=join('_',@allparts);
3669: return ($part,$type);
3670: }
3671:
3672: #------------- end of section for handling grading by section/class ---------
3673: #
3674: #----------------------------------------------------------------------------
3675:
3676:
3677: #----------------------------------------------------------------------------
3678: #
3679: #-------------------------- Next few routines handles grading by csv upload
3680: #
3681: #--- Javascript to handle csv upload
3682: sub csvupload_javascript_reverse_associate {
3683: my $error1=&mt('You need to specify the username or the student/employee ID');
3684: my $error2=&mt('You need to specify at least one grading field');
3685: return(<<ENDPICK);
3686: function verify(vf) {
3687: var foundsomething=0;
3688: var founduname=0;
3689: var foundID=0;
3690: for (i=0;i<=vf.nfields.value;i++) {
3691: tw=eval('vf.f'+i+'.selectedIndex');
3692: if (i==0 && tw!=0) { foundID=1; }
3693: if (i==1 && tw!=0) { founduname=1; }
3694: if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
3695: }
3696: if (founduname==0 && foundID==0) {
3697: alert('$error1');
3698: return;
3699: }
3700: if (foundsomething==0) {
3701: alert('$error2');
3702: return;
3703: }
3704: vf.submit();
3705: }
3706: function flip(vf,tf) {
3707: var nw=eval('vf.f'+tf+'.selectedIndex');
3708: var i;
3709: for (i=0;i<=vf.nfields.value;i++) {
3710: //can not pick the same destination field for both name and domain
3711: if (((i ==0)||(i ==1)) &&
3712: ((tf==0)||(tf==1)) &&
3713: (i!=tf) &&
3714: (eval('vf.f'+i+'.selectedIndex')==nw)) {
3715: eval('vf.f'+i+'.selectedIndex=0;')
3716: }
3717: }
3718: }
3719: ENDPICK
3720: }
3721:
3722: sub csvupload_javascript_forward_associate {
3723: my $error1=&mt('You need to specify the username or the student/employee ID');
3724: my $error2=&mt('You need to specify at least one grading field');
3725: return(<<ENDPICK);
3726: function verify(vf) {
3727: var foundsomething=0;
3728: var founduname=0;
3729: var foundID=0;
3730: for (i=0;i<=vf.nfields.value;i++) {
3731: tw=eval('vf.f'+i+'.selectedIndex');
3732: if (tw==1) { foundID=1; }
3733: if (tw==2) { founduname=1; }
3734: if (tw>3) { foundsomething=1; }
3735: }
3736: if (founduname==0 && foundID==0) {
3737: alert('$error1');
3738: return;
3739: }
3740: if (foundsomething==0) {
3741: alert('$error2');
3742: return;
3743: }
3744: vf.submit();
3745: }
3746: function flip(vf,tf) {
3747: var nw=eval('vf.f'+tf+'.selectedIndex');
3748: var i;
3749: //can not pick the same destination field twice
3750: for (i=0;i<=vf.nfields.value;i++) {
3751: if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
3752: eval('vf.f'+i+'.selectedIndex=0;')
3753: }
3754: }
3755: }
3756: ENDPICK
3757: }
3758:
3759: sub csvuploadmap_header {
3760: my ($request,$symb,$datatoken,$distotal)= @_;
3761: my $javascript;
3762: if ($env{'form.upfile_associate'} eq 'reverse') {
3763: $javascript=&csvupload_javascript_reverse_associate();
3764: } else {
3765: $javascript=&csvupload_javascript_forward_associate();
3766: }
3767:
3768: my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
3769: my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
3770: my $ignore=&mt('Ignore First Line');
3771: $symb = &Apache::lonenc::check_encrypt($symb);
3772: $request->print(<<ENDPICK);
3773: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3774: <h3><span class="LC_info">Uploading Class Grades</span></h3>
3775: $result
3776: <hr />
3777: <h3>Identify fields</h3>
3778: Total number of records found in file: $distotal <hr />
3779: Enter as many fields as you can. The system will inform you and bring you back
3780: to this page if the data selected is insufficient to run your class.<hr />
3781: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
3782: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
3783: <input type="hidden" name="associate" value="" />
3784: <input type="hidden" name="phase" value="three" />
3785: <input type="hidden" name="datatoken" value="$datatoken" />
3786: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
3787: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
3788: <input type="hidden" name="upfile_associate"
3789: value="$env{'form.upfile_associate'}" />
3790: <input type="hidden" name="symb" value="$symb" />
3791: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
3792: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
3793: <input type="hidden" name="command" value="csvuploadoptions" />
3794: <hr />
3795: <script type="text/javascript" language="Javascript">
3796: $javascript
3797: </script>
3798: ENDPICK
3799: return '';
3800:
3801: }
3802:
3803: sub csvupload_fields {
3804: my ($symb) = @_;
3805: my (@parts) = &getpartlist($symb);
3806: my @fields=(['ID','Student/Employee ID'],
3807: ['username','Student Username'],
3808: ['domain','Student Domain']);
3809: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3810: foreach my $part (sort(@parts)) {
3811: my @datum;
3812: my $display=&Apache::lonnet::metadata($url,$part.'.display');
3813: my $name=$part;
3814: if (!$display) { $display = $name; }
3815: @datum=($name,$display);
3816: if ($name=~/^stores_(.*)_awarded/) {
3817: push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
3818: }
3819: push(@fields,\@datum);
3820: }
3821: return (@fields);
3822: }
3823:
3824: sub csvuploadmap_footer {
3825: my ($request,$i,$keyfields) =@_;
3826: $request->print(<<ENDPICK);
3827: </table>
3828: <input type="hidden" name="nfields" value="$i" />
3829: <input type="hidden" name="keyfields" value="$keyfields" />
3830: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
3831: </form>
3832: ENDPICK
3833: }
3834:
3835: sub checkforfile_js {
3836: my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
3837: my $result =<<CSVFORMJS;
3838: <script type="text/javascript" language="javascript">
3839: function checkUpload(formname) {
3840: if (formname.upfile.value == "") {
3841: alert("$alertmsg");
3842: return false;
3843: }
3844: formname.submit();
3845: }
3846: </script>
3847: CSVFORMJS
3848: return $result;
3849: }
3850:
3851: sub upcsvScores_form {
3852: my ($request) = shift;
3853: my ($symb)=&get_symb($request);
3854: if (!$symb) {return '';}
3855: my $result=&checkforfile_js();
3856: $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
3857: my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
3858: $result.=$table;
3859: $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
3860: $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
3861: $result.=' <b>'.&mt('Specify a file containing the class scores for current resource.').
3862: '</b></td></tr>'."\n";
3863: $result.='<tr bgcolor=#ffffe6><td>'."\n";
3864: my $upload=&mt("Upload Scores");
3865: my $upfile_select=&Apache::loncommon::upfile_select_html();
3866: my $ignore=&mt('Ignore First Line');
3867: $symb = &Apache::lonenc::check_encrypt($symb);
3868: $result.=<<ENDUPFORM;
3869: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3870: <input type="hidden" name="symb" value="$symb" />
3871: <input type="hidden" name="command" value="csvuploadmap" />
3872: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
3873: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
3874: $upfile_select
3875: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
3876: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
3877: </form>
3878: ENDUPFORM
3879: $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
3880: &mt("How do I create a CSV file from a spreadsheet"))
3881: .'</td></tr></table>'."\n";
3882: $result.='</td></tr></table><br /><br />'."\n";
3883: $result.=&show_grading_menu_form($symb);
3884: return $result;
3885: }
3886:
3887:
3888: sub csvuploadmap {
3889: my ($request)= @_;
3890: my ($symb)=&get_symb($request);
3891: if (!$symb) {return '';}
3892:
3893: my $datatoken;
3894: if (!$env{'form.datatoken'}) {
3895: $datatoken=&Apache::loncommon::upfile_store($request);
3896: } else {
3897: $datatoken=$env{'form.datatoken'};
3898: &Apache::loncommon::load_tmp_file($request);
3899: }
3900: my @records=&Apache::loncommon::upfile_record_sep();
3901: if ($env{'form.noFirstLine'}) { shift(@records); }
3902: &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
3903: my ($i,$keyfields);
3904: if (@records) {
3905: my @fields=&csvupload_fields($symb);
3906:
3907: if ($env{'form.upfile_associate'} eq 'reverse') {
3908: &Apache::loncommon::csv_print_samples($request,\@records);
3909: $i=&Apache::loncommon::csv_print_select_table($request,\@records,
3910: \@fields);
3911: foreach (@fields) { $keyfields.=$_->[0].','; }
3912: chop($keyfields);
3913: } else {
3914: unshift(@fields,['none','']);
3915: $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
3916: \@fields);
3917: foreach my $rec (@records) {
3918: my %temp = &Apache::loncommon::record_sep($rec);
3919: if (%temp) {
3920: $keyfields=join(',',sort(keys(%temp)));
3921: last;
3922: }
3923: }
3924: }
3925: }
3926: &csvuploadmap_footer($request,$i,$keyfields);
3927: $request->print(&show_grading_menu_form($symb));
3928:
3929: return '';
3930: }
3931:
3932: sub csvuploadoptions {
3933: my ($request)= @_;
3934: my ($symb)=&get_symb($request);
3935: my $checked=(($env{'form.noFirstLine'})?'1':'0');
3936: my $ignore=&mt('Ignore First Line');
3937: $request->print(<<ENDPICK);
3938: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3939: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
3940: <input type="hidden" name="command" value="csvuploadassign" />
3941: <!--
3942: <p>
3943: <label>
3944: <input type="checkbox" name="show_full_results" />
3945: Show a table of all changes
3946: </label>
3947: </p>
3948: -->
3949: <p>
3950: <label>
3951: <input type="checkbox" name="overwite_scores" checked="checked" />
3952: Overwrite any existing score
3953: </label>
3954: </p>
3955: ENDPICK
3956: my %fields=&get_fields();
3957: if (!defined($fields{'domain'})) {
3958: my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
3959: $request->print("\n<p> Users are in domain: ".$domform."</p>\n");
3960: }
3961: foreach my $key (sort(keys(%env))) {
3962: if ($key !~ /^form\.(.*)$/) { next; }
3963: my $cleankey=$1;
3964: if ($cleankey eq 'command') { next; }
3965: $request->print('<input type="hidden" name="'.$cleankey.
3966: '" value="'.$env{$key}.'" />'."\n");
3967: }
3968: # FIXME do a check for any duplicated user ids...
3969: # FIXME do a check for any invalid user ids?...
3970: $request->print('<input type="submit" value="Assign Grades" /><br />
3971: <hr /></form>'."\n");
3972: $request->print(&show_grading_menu_form($symb));
3973: return '';
3974: }
3975:
3976: sub get_fields {
3977: my %fields;
3978: my @keyfields = split(/\,/,$env{'form.keyfields'});
3979: for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
3980: if ($env{'form.upfile_associate'} eq 'reverse') {
3981: if ($env{'form.f'.$i} ne 'none') {
3982: $fields{$keyfields[$i]}=$env{'form.f'.$i};
3983: }
3984: } else {
3985: if ($env{'form.f'.$i} ne 'none') {
3986: $fields{$env{'form.f'.$i}}=$keyfields[$i];
3987: }
3988: }
3989: }
3990: return %fields;
3991: }
3992:
3993: sub csvuploadassign {
3994: my ($request)= @_;
3995: my ($symb)=&get_symb($request);
3996: if (!$symb) {return '';}
3997: my $error_msg = '';
3998: &Apache::loncommon::load_tmp_file($request);
3999: my @gradedata = &Apache::loncommon::upfile_record_sep();
4000: if ($env{'form.noFirstLine'}) { shift(@gradedata); }
4001: my %fields=&get_fields();
4002: $request->print('<h3>Assigning Grades</h3>');
4003: my $courseid=$env{'request.course.id'};
4004: my ($classlist) = &getclasslist('all',0);
4005: my @notallowed;
4006: my @skipped;
4007: my $countdone=0;
4008: foreach my $grade (@gradedata) {
4009: my %entries=&Apache::loncommon::record_sep($grade);
4010: my $domain;
4011: if ($entries{$fields{'domain'}}) {
4012: $domain=$entries{$fields{'domain'}};
4013: } else {
4014: $domain=$env{'form.default_domain'};
4015: }
4016: $domain=~s/\s//g;
4017: my $username=$entries{$fields{'username'}};
4018: $username=~s/\s//g;
4019: if (!$username) {
4020: my $id=$entries{$fields{'ID'}};
4021: $id=~s/\s//g;
4022: my %ids=&Apache::lonnet::idget($domain,$id);
4023: $username=$ids{$id};
4024: }
4025: if (!exists($$classlist{"$username:$domain"})) {
4026: my $id=$entries{$fields{'ID'}};
4027: $id=~s/\s//g;
4028: if ($id) {
4029: push(@skipped,"$id:$domain");
4030: } else {
4031: push(@skipped,"$username:$domain");
4032: }
4033: next;
4034: }
4035: my $usec=$classlist->{"$username:$domain"}[5];
4036: if (!&canmodify($usec)) {
4037: push(@notallowed,"$username:$domain");
4038: next;
4039: }
4040: my %points;
4041: my %grades;
4042: foreach my $dest (keys(%fields)) {
4043: if ($dest eq 'ID' || $dest eq 'username' ||
4044: $dest eq 'domain') { next; }
4045: if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
4046: if ($dest=~/stores_(.*)_points/) {
4047: my $part=$1;
4048: my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
4049: $symb,$domain,$username);
4050: if ($wgt) {
4051: $entries{$fields{$dest}}=~s/\s//g;
4052: my $pcr=$entries{$fields{$dest}} / $wgt;
4053: my $award=($pcr == 0) ? 'incorrect_by_override'
4054: : 'correct_by_override';
4055: $grades{"resource.$part.awarded"}=$pcr;
4056: $grades{"resource.$part.solved"}=$award;
4057: $points{$part}=1;
4058: } else {
4059: $error_msg = "<br />" .
4060: &mt("Some point values were assigned"
4061: ." for problems with a weight "
4062: ."of zero. These values were "
4063: ."ignored.");
4064: }
4065: } else {
4066: if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
4067: if ($dest=~/stores_(.*)_solved/) { if ($points{$1}) {next;} }
4068: my $store_key=$dest;
4069: $store_key=~s/^stores/resource/;
4070: $store_key=~s/_/\./g;
4071: $grades{$store_key}=$entries{$fields{$dest}};
4072: }
4073: }
4074: if (! %grades) {
4075: push(@skipped,&mt("[_1]: no data to save","$username:$domain"));
4076: } else {
4077: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
4078: my $result=&Apache::lonnet::cstore(\%grades,$symb,
4079: $env{'request.course.id'},
4080: $domain,$username);
4081: if ($result eq 'ok') {
4082: $request->print('.');
4083: } else {
4084: $request->print("<p><span class=\"LC_error\">".
4085: &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
4086: "$username:$domain",$result)."</span></p>");
4087: }
4088: $request->rflush();
4089: $countdone++;
4090: }
4091: }
4092: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
4093: if (@skipped) {
4094: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
4095: $request->print(join(', ',@skipped));
4096: }
4097: if (@notallowed) {
4098: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
4099: $request->print(join(', ',@notallowed));
4100: }
4101: $request->print("<br />\n");
4102: $request->print(&show_grading_menu_form($symb));
4103: return $error_msg;
4104: }
4105: #------------- end of section for handling csv file upload ---------
4106: #
4107: #-------------------------------------------------------------------
4108: #
4109: #-------------- Next few routines handle grading by page/sequence
4110: #
4111: #--- Select a page/sequence and a student to grade
4112: sub pickStudentPage {
4113: my ($request) = shift;
4114:
4115: my $alertmsg = &mt('Please select the student you wish to grade.');
4116: $request->print(<<LISTJAVASCRIPT);
4117: <script type="text/javascript" language="javascript">
4118:
4119: function checkPickOne(formname) {
4120: if (radioSelection(formname.student) == null) {
4121: alert("$alertmsg");
4122: return;
4123: }
4124: ptr = pullDownSelection(formname.selectpage);
4125: formname.page.value = formname["page"+ptr].value;
4126: formname.title.value = formname["title"+ptr].value;
4127: formname.submit();
4128: }
4129:
4130: </script>
4131: LISTJAVASCRIPT
4132: &commonJSfunctions($request);
4133: my ($symb) = &get_symb($request);
4134: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4135: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4136: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4137:
4138: my $result='<h3><span class="LC_info"> '.
4139: &mt('Manual Grading by Page or Sequence').'</span></h3>';
4140:
4141: $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
4142: my ($titles,$symbx) = &getSymbMap();
4143: my ($curpage) =&Apache::lonnet::decode_symb($symb);
4144: # my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb);
4145: # my $type=($curpage =~ /\.(page|sequence)/);
4146: my $select = '<select name="selectpage">'."\n";
4147: my $ctr=0;
4148: foreach (@$titles) {
4149: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4150: $select.='<option value="'.$ctr.'" '.
4151: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
4152: '>'.$showtitle.'</option>'."\n";
4153: $ctr++;
4154: }
4155: $select.= '</select>';
4156: $result.=' <b>'.&mt('Problems from').':</b> '.$select."<br />\n";
4157:
4158: $ctr=0;
4159: foreach (@$titles) {
4160: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4161: $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
4162: $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
4163: $ctr++;
4164: }
4165: $result.='<input type="hidden" name="page" />'."\n".
4166: '<input type="hidden" name="title" />'."\n";
4167:
4168: my $options =
4169: '<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
4170: '<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
4171: $result.=' <b>'.&mt('View Problem Text').': </b>'.$options;
4172:
4173: $options =
4174: '<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
4175: '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
4176: '<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
4177: $result.=' <b>'.&mt('Submissions').': </b>'.$options;
4178:
4179: $result.=&build_section_inputs();
4180: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
4181: $result.='<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
4182: '<input type="hidden" name="command" value="displayPage" />'."\n".
4183: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
4184: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
4185:
4186: $result.=' <b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
4187:
4188: $result.=' <input type="button" '.
4189: 'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' →" /><br />'."\n";
4190:
4191: $request->print($result);
4192:
4193: my $studentTable.=' <b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
4194: &Apache::loncommon::start_data_table().
4195: &Apache::loncommon::start_data_table_header_row().
4196: '<th align="right"> '.&mt('No.').'</th>'.
4197: '<th>'.&nameUserString('header').'</th>'.
4198: '<th align="right"> '.&mt('No.').'</th>'.
4199: '<th>'.&nameUserString('header').'</th>'.
4200: &Apache::loncommon::end_data_table_header_row();
4201:
4202: my (undef,undef,$fullname) = &getclasslist($getsec,'1');
4203: my $ptr = 1;
4204: foreach my $student (sort
4205: {
4206: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
4207: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
4208: }
4209: return $a cmp $b;
4210: } (keys(%$fullname))) {
4211: my ($uname,$udom) = split(/:/,$student);
4212: $studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
4213: : '</td>');
4214: $studentTable.='<td align="right">'.$ptr.' </td>';
4215: $studentTable.='<td> <label><input type="radio" name="student" value="'.$student.'" /> '
4216: .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
4217: $studentTable.=
4218: ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row()
4219: : '');
4220: $ptr++;
4221: }
4222: if ($ptr%2 == 0) {
4223: $studentTable.='</td><td> </td><td> </td>'.
4224: &Apache::loncommon::end_data_table_row();
4225: }
4226: $studentTable.=&Apache::loncommon::end_data_table()."\n";
4227: $studentTable.='<input type="button" '.
4228: 'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' →" /></form>'."\n";
4229:
4230: $studentTable.=&show_grading_menu_form($symb);
4231: $request->print($studentTable);
4232:
4233: return '';
4234: }
4235:
4236: sub getSymbMap {
4237: my $navmap = Apache::lonnavmaps::navmap->new();
4238:
4239: my %symbx = ();
4240: my @titles = ();
4241: my $minder = 0;
4242:
4243: # Gather every sequence that has problems.
4244: my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
4245: 1,0,1);
4246: for my $sequence ($navmap->getById('0.0'), @sequences) {
4247: if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
4248: my $title = $minder.'.'.
4249: &HTML::Entities::encode($sequence->compTitle(),'"\'&');
4250: push(@titles, $title); # minder in case two titles are identical
4251: $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
4252: $minder++;
4253: }
4254: }
4255: return \@titles,\%symbx;
4256: }
4257:
4258: #
4259: #--- Displays a page/sequence w/wo problems, w/wo submissions
4260: sub displayPage {
4261: my ($request) = shift;
4262:
4263: my ($symb) = &get_symb($request);
4264: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4265: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4266: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4267: my $pageTitle = $env{'form.page'};
4268: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
4269: my ($uname,$udom) = split(/:/,$env{'form.student'});
4270: my $usec=$classlist->{$env{'form.student'}}[5];
4271:
4272: #need to make sure we have the correct data for later EXT calls,
4273: #thus invalidate the cache
4274: &Apache::lonnet::devalidatecourseresdata(
4275: $env{'course.'.$env{'request.course.id'}.'.num'},
4276: $env{'course.'.$env{'request.course.id'}.'.domain'});
4277: &Apache::lonnet::clear_EXT_cache_status();
4278:
4279: if (!&canview($usec)) {
4280: $request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
4281: $request->print(&show_grading_menu_form($symb));
4282: return;
4283: }
4284: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
4285: $result.='<h3> '.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
4286: '</h3>'."\n";
4287: $env{'form.CODE'} = uc($env{'form.CODE'});
4288: if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
4289: $result.='<h3> '.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
4290: } else {
4291: delete($env{'form.CODE'});
4292: }
4293: &sub_page_js($request);
4294: $request->print($result);
4295:
4296: my $navmap = Apache::lonnavmaps::navmap->new();
4297: my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
4298: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
4299: if (!$map) {
4300: $request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
4301: $request->print(&show_grading_menu_form($symb));
4302: return;
4303: }
4304: my $iterator = $navmap->getIterator($map->map_start(),
4305: $map->map_finish());
4306:
4307: my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
4308: '<input type="hidden" name="command" value="gradeByPage" />'."\n".
4309: '<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
4310: '<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
4311: '<input type="hidden" name="page" value="'.$pageTitle.'" />'."\n".
4312: '<input type="hidden" name="title" value="'.$env{'form.title'}.'" />'."\n".
4313: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
4314: '<input type="hidden" name="overRideScore" value="no" />'."\n".
4315: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
4316:
4317: if (defined($env{'form.CODE'})) {
4318: $studentTable.=
4319: '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
4320: }
4321: my $checkIcon = '<img alt="'.&mt('Check Mark').
4322: '" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
4323:
4324: $studentTable.=' '.&mt('<b>Note:</b> Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon)."\n".
4325: &Apache::loncommon::start_data_table().
4326: &Apache::loncommon::start_data_table_header_row().
4327: '<th align="center"> Prob. </th>'.
4328: '<th> '.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
4329: &Apache::loncommon::end_data_table_header_row();
4330:
4331: &Apache::lonxml::clear_problem_counter();
4332: my ($depth,$question,$prob) = (1,1,1);
4333: $iterator->next(); # skip the first BEGIN_MAP
4334: my $curRes = $iterator->next(); # for "current resource"
4335: while ($depth > 0) {
4336: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
4337: if($curRes == $iterator->END_MAP) { $depth--; }
4338:
4339: if (ref($curRes) && $curRes->is_problem()) {
4340: my $parts = $curRes->parts();
4341: my $title = $curRes->compTitle();
4342: my $symbx = $curRes->symb();
4343: $studentTable.=
4344: &Apache::loncommon::start_data_table_row().
4345: '<td align="center" valign="top" >'.$prob.
4346: (scalar(@{$parts}) == 1 ? ''
4347: : '<br />('.&mt('[_1] parts)',
4348: scalar(@{$parts}))
4349: ).
4350: '</td>';
4351: $studentTable.='<td valign="top">';
4352: my %form = ('CODE' => $env{'form.CODE'},);
4353: if ($env{'form.vProb'} eq 'yes' ) {
4354: $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
4355: undef,'both',\%form);
4356: } else {
4357: my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
4358: $companswer =~ s|<form(.*?)>||g;
4359: $companswer =~ s|</form>||g;
4360: # while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
4361: # $companswer =~ s/$1/ /ms;
4362: # $request->print('match='.$1."<br />\n");
4363: # }
4364: # $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
4365: $studentTable.=' <b>'.$title.'</b> <br /> <b>'.&mt('Correct answer').':</b><br />'.$companswer;
4366: }
4367:
4368: my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
4369:
4370: if ($env{'form.lastSub'} eq 'datesub') {
4371: if ($record{'version'} eq '') {
4372: $studentTable.='<br /> <span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
4373: } else {
4374: my %responseType = ();
4375: foreach my $partid (@{$parts}) {
4376: my @responseIds =$curRes->responseIds($partid);
4377: my @responseType =$curRes->responseType($partid);
4378: my %responseIds;
4379: for (my $i=0;$i<=$#responseIds;$i++) {
4380: $responseIds{$responseIds[$i]}=$responseType[$i];
4381: }
4382: $responseType{$partid} = \%responseIds;
4383: }
4384: $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
4385:
4386: }
4387: } elsif ($env{'form.lastSub'} eq 'all') {
4388: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
4389: $studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
4390: $env{'request.course.id'},
4391: '','.submission');
4392:
4393: }
4394: if (&canmodify($usec)) {
4395: foreach my $partid (@{$parts}) {
4396: $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
4397: $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
4398: $question++;
4399: }
4400: $prob++;
4401: }
4402: $studentTable.='</td></tr>';
4403:
4404: }
4405: $curRes = $iterator->next();
4406: }
4407:
4408: $studentTable.='</table>'."\n".
4409: '<input type="button" value="'.&mt('Save').'" '.
4410: 'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
4411: '</form>'."\n";
4412: $studentTable.=&show_grading_menu_form($symb);
4413: $request->print($studentTable);
4414:
4415: return '';
4416: }
4417:
4418: sub displaySubByDates {
4419: my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
4420: my $isCODE=0;
4421: my $isTask = ($symb =~/\.task$/);
4422: if (exists($record->{'resource.CODE'})) { $isCODE=1; }
4423: my $studentTable=&Apache::loncommon::start_data_table().
4424: &Apache::loncommon::start_data_table_header_row().
4425: '<th>'.&mt('Date/Time').'</th>'.
4426: ($isCODE?'<th>'.&mt('CODE').'</th>':'').
4427: '<th>'.&mt('Submission').'</th>'.
4428: '<th>'.&mt('Status').'</th>'.
4429: &Apache::loncommon::end_data_table_header_row();
4430: my ($version);
4431: my %mark;
4432: my %orders;
4433: $mark{'correct_by_student'} = $checkIcon;
4434: if (!exists($$record{'1:timestamp'})) {
4435: return '<br /> <span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
4436: }
4437:
4438: my $interaction;
4439: my $no_increment = 1;
4440: for ($version=1;$version<=$$record{'version'};$version++) {
4441: my $timestamp =
4442: &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
4443: if (exists($$record{$version.':resource.0.version'})) {
4444: $interaction = $$record{$version.':resource.0.version'};
4445: }
4446:
4447: my $where = ($isTask ? "$version:resource.$interaction"
4448: : "$version:resource");
4449: $studentTable.=&Apache::loncommon::start_data_table_row().
4450: '<td>'.$timestamp.'</td>';
4451: if ($isCODE) {
4452: $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
4453: }
4454: my @versionKeys = split(/\:/,$$record{$version.':keys'});
4455: my @displaySub = ();
4456: foreach my $partid (@{$parts}) {
4457: my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
4458: : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
4459:
4460:
4461: # next if ($$record{"$version:resource.$partid.solved"} eq '');
4462: my $display_part=&get_display_part($partid,$symb);
4463: foreach my $matchKey (@matchKey) {
4464: if (exists($$record{$version.':'.$matchKey}) &&
4465: $$record{$version.':'.$matchKey} ne '') {
4466:
4467: my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
4468: : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
4469: $displaySub[0].='<b>'.&mt('Part:').'</b> '.$display_part.' ';
4470: $displaySub[0].='<span class="LC_internal_info">('.&mt('ID').' '.
4471: $responseId.')</span> <b>';
4472: if ($$record{"$where.$partid.tries"} eq '') {
4473: $displaySub[0].=&mt('Trial not counted');
4474: } else {
4475: $displaySub[0].=&mt('Trial [_1]',
4476: $$record{"$where.$partid.tries"});
4477: }
4478: my $responseType=($isTask ? 'Task'
4479: : $responseType->{$partid}->{$responseId});
4480: if (!exists($orders{$partid})) { $orders{$partid}={}; }
4481: if (!exists($orders{$partid}->{$responseId})) {
4482: $orders{$partid}->{$responseId}=
4483: &get_order($partid,$responseId,$symb,$uname,$udom,
4484: $no_increment);
4485: }
4486: $displaySub[0].='</b> '.
4487: &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
4488: }
4489: }
4490: if (exists($$record{"$where.$partid.checkedin"})) {
4491: $displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
4492: $$record{"$where.$partid.checkedin"},
4493: $$record{"$where.$partid.checkedin.slot"}).
4494: '<br />';
4495: }
4496: if (exists $$record{"$where.$partid.award"}) {
4497: $displaySub[1].='<b>'.&mt('Part:').'</b> '.$display_part.' '.
4498: lc($$record{"$where.$partid.award"}).' '.
4499: $mark{$$record{"$where.$partid.solved"}}.
4500: '<br />';
4501: }
4502: if (exists $$record{"$where.$partid.regrader"}) {
4503: $displaySub[2].=$$record{"$where.$partid.regrader"}.
4504: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
4505: } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
4506: $displaySub[2].=
4507: $$record{"$version:resource.$partid.regrader"}.
4508: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
4509: }
4510: }
4511: # needed because old essay regrader has not parts info
4512: if (exists $$record{"$version:resource.regrader"}) {
4513: $displaySub[2].=$$record{"$version:resource.regrader"};
4514: }
4515: $studentTable.='<td>'.$displaySub[0].' </td><td>'.$displaySub[1];
4516: if ($displaySub[2]) {
4517: $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
4518: }
4519: $studentTable.=' </td>'.
4520: &Apache::loncommon::end_data_table_row();
4521: }
4522: $studentTable.=&Apache::loncommon::end_data_table();
4523: return $studentTable;
4524: }
4525:
4526: sub updateGradeByPage {
4527: my ($request) = shift;
4528:
4529: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4530: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4531: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4532: my $pageTitle = $env{'form.page'};
4533: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
4534: my ($uname,$udom) = split(/:/,$env{'form.student'});
4535: my $usec=$classlist->{$env{'form.student'}}[5];
4536: if (!&canmodify($usec)) {
4537: $request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
4538: $request->print(&show_grading_menu_form($env{'form.symb'}));
4539: return;
4540: }
4541: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
4542: $result.='<h3> '.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
4543: '</h3>'."\n";
4544:
4545: $request->print($result);
4546:
4547: my $navmap = Apache::lonnavmaps::navmap->new();
4548: my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
4549: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
4550: if (!$map) {
4551: $request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
4552: my ($symb)=&get_symb($request);
4553: $request->print(&show_grading_menu_form($symb));
4554: return;
4555: }
4556: my $iterator = $navmap->getIterator($map->map_start(),
4557: $map->map_finish());
4558:
4559: my $studentTable=
4560: &Apache::loncommon::start_data_table().
4561: &Apache::loncommon::start_data_table_header_row().
4562: '<th align="center"> '.&mt('Prob.').' </th>'.
4563: '<th> '.&mt('Title').' </th>'.
4564: '<th> '.&mt('Previous Score').' </th>'.
4565: '<th> '.&mt('New Score').' </th>'.
4566: &Apache::loncommon::end_data_table_header_row();
4567:
4568: $iterator->next(); # skip the first BEGIN_MAP
4569: my $curRes = $iterator->next(); # for "current resource"
4570: my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
4571: while ($depth > 0) {
4572: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
4573: if($curRes == $iterator->END_MAP) { $depth--; }
4574:
4575: if (ref($curRes) && $curRes->is_problem()) {
4576: my $parts = $curRes->parts();
4577: my $title = $curRes->compTitle();
4578: my $symbx = $curRes->symb();
4579: $studentTable.=
4580: &Apache::loncommon::start_data_table_row().
4581: '<td align="center" valign="top" >'.$prob.
4582: (scalar(@{$parts}) == 1 ? ''
4583: : '<br />('.&mt('[quant,_1, part]',scalar(@{$parts}))
4584: .')').'</td>';
4585: $studentTable.='<td valign="top"> <b>'.$title.'</b> </td>';
4586:
4587: my %newrecord=();
4588: my @displayPts=();
4589: my %aggregate = ();
4590: my $aggregateflag = 0;
4591: foreach my $partid (@{$parts}) {
4592: my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
4593: my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
4594:
4595: my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ?
4596: $env{'form.WGT'.$question.'_'.$partid} : 1;
4597: my $partial = $newpts/$wgt;
4598: my $score;
4599: if ($partial > 0) {
4600: $score = 'correct_by_override';
4601: } elsif ($newpts ne '') { #empty is taken as 0
4602: $score = 'incorrect_by_override';
4603: }
4604: my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
4605: if ($dropMenu eq 'excused') {
4606: $partial = '';
4607: $score = 'excused';
4608: } elsif ($dropMenu eq 'reset status'
4609: && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
4610: $newrecord{'resource.'.$partid.'.tries'} = 0;
4611: $newrecord{'resource.'.$partid.'.solved'} = '';
4612: $newrecord{'resource.'.$partid.'.award'} = '';
4613: $newrecord{'resource.'.$partid.'.awarded'} = 0;
4614: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
4615: $changeflag++;
4616: $newpts = '';
4617:
4618: my $aggtries = $env{'form.aggtries'.$question.'_'.$partid};
4619: my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
4620: my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
4621: if ($aggtries > 0) {
4622: &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
4623: $aggregateflag = 1;
4624: }
4625: }
4626: my $display_part=&get_display_part($partid,$curRes->symb());
4627: my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
4628: $displayPts[0].=' <b>'.&mt('Part').':</b> '.$display_part.' = '.
4629: (($oldstatus eq 'excused') ? 'excused' : $oldpts).
4630: ' <br />';
4631: $displayPts[1].=' <b>'.&mt('Part').':</b> '.$display_part.' = '.
4632: (($score eq 'excused') ? 'excused' : $newpts).
4633: ' <br />';
4634: $question++;
4635: next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
4636:
4637: $newrecord{'resource.'.$partid.'.awarded'} = $partial if $partial ne '';
4638: $newrecord{'resource.'.$partid.'.solved'} = $score if $score ne '';
4639: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
4640: if (scalar(keys(%newrecord)) > 0);
4641:
4642: $changeflag++;
4643: }
4644: if (scalar(keys(%newrecord)) > 0) {
4645: my %record =
4646: &Apache::lonnet::restore($symbx,$env{'request.course.id'},
4647: $udom,$uname);
4648:
4649: if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
4650: $newrecord{'resource.CODE'} = $env{'form.CODE'};
4651: } elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
4652: $newrecord{'resource.CODE'} = '';
4653: }
4654: &Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
4655: $udom,$uname);
4656: %record = &Apache::lonnet::restore($symbx,
4657: $env{'request.course.id'},
4658: $udom,$uname);
4659: &check_and_remove_from_queue($parts,\%record,undef,$symbx,
4660: $cdom,$cnum,$udom,$uname);
4661: }
4662:
4663: if ($aggregateflag) {
4664: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
4665: $env{'course.'.$env{'request.course.id'}.'.domain'},
4666: $env{'course.'.$env{'request.course.id'}.'.num'});
4667: }
4668:
4669: $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
4670: '<td valign="top">'.$displayPts[1].'</td>'.
4671: &Apache::loncommon::end_data_table_row();
4672:
4673: $prob++;
4674: }
4675: $curRes = $iterator->next();
4676: }
4677:
4678: $studentTable.=&Apache::loncommon::end_data_table();
4679: $studentTable.=&show_grading_menu_form($env{'form.symb'});
4680: my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
4681: &mt('The scores were changed for [quant,_1,problem].',
4682: $changeflag));
4683: $request->print($grademsg.$studentTable);
4684:
4685: return '';
4686: }
4687:
4688: #-------- end of section for handling grading by page/sequence ---------
4689: #
4690: #-------------------------------------------------------------------
4691:
4692: #--------------------Scantron Grading-----------------------------------
4693: #
4694: #------ start of section for handling grading by page/sequence ---------
4695:
4696: =pod
4697:
4698: =head1 Bubble sheet grading routines
4699:
4700: For this documentation:
4701:
4702: 'scanline' refers to the full line of characters
4703: from the file that we are parsing that represents one entire sheet
4704:
4705: 'bubble line' refers to the data
4706: representing the line of bubbles that are on the physical bubble sheet
4707:
4708:
4709: The overall process is that a scanned in bubble sheet data is uploaded
4710: into a course. When a user wants to grade, they select a
4711: sequence/folder of resources, a file of bubble sheet info, and pick
4712: one of the predefined configurations for what each scanline looks
4713: like.
4714:
4715: Next each scanline is checked for any errors of either 'missing
4716: bubbles' (it's an error because it may have been mis-scanned
4717: because too light bubbling), 'double bubble' (each bubble line should
4718: have no more that one letter picked), invalid or duplicated CODE,
4719: invalid student/employee ID
4720:
4721: If the CODE option is used that determines the randomization of the
4722: homework problems, either way the student/employee ID is looked up into a
4723: username:domain.
4724:
4725: During the validation phase the instructor can choose to skip scanlines.
4726:
4727: After the validation phase, there are now 3 bubble sheet files
4728:
4729: scantron_original_filename (unmodified original file)
4730: scantron_corrected_filename (file where the corrected information has replaced the original information)
4731: scantron_skipped_filename (contains the exact text of scanlines that where skipped)
4732:
4733: Also there is a separate hash nohist_scantrondata that contains extra
4734: correction information that isn't representable in the bubble sheet
4735: file (see &scantron_getfile() for more information)
4736:
4737: After all scanlines are either valid, marked as valid or skipped, then
4738: foreach line foreach problem in the picked sequence, an ssi request is
4739: made that simulates a user submitting their selected letter(s) against
4740: the homework problem.
4741:
4742: =over 4
4743:
4744:
4745:
4746: =item defaultFormData
4747:
4748: Returns html hidden inputs used to hold context/default values.
4749:
4750: Arguments:
4751: $symb - $symb of the current resource
4752:
4753: =cut
4754:
4755: sub defaultFormData {
4756: my ($symb)=@_;
4757: return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
4758: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
4759: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
4760: }
4761:
4762:
4763: =pod
4764:
4765: =item getSequenceDropDown
4766:
4767: Return html dropdown of possible sequences to grade
4768:
4769: Arguments:
4770: $symb - $symb of the current resource
4771:
4772: =cut
4773:
4774: sub getSequenceDropDown {
4775: my ($symb)=@_;
4776: my $result='<select name="selectpage">'."\n";
4777: my ($titles,$symbx) = &getSymbMap();
4778: my ($curpage)=&Apache::lonnet::decode_symb($symb);
4779: my $ctr=0;
4780: foreach (@$titles) {
4781: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4782: $result.='<option value="'.$$symbx{$_}.'" '.
4783: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
4784: '>'.$showtitle.'</option>'."\n";
4785: $ctr++;
4786: }
4787: $result.= '</select>';
4788: return $result;
4789: }
4790:
4791: my %bubble_lines_per_response; # no. bubble lines for each response.
4792: # key is zero-based index - 0, 1, 2 ...
4793:
4794: my %first_bubble_line; # First bubble line no. for each bubble.
4795:
4796: my %subdivided_bubble_lines; # no. bubble lines for optionresponse,
4797: # matchresponse or rankresponse, where
4798: # an individual response can have multiple
4799: # lines
4800:
4801: my %responsetype_per_response; # responsetype for each response
4802:
4803: # Save and restore the bubble lines array to the form env.
4804:
4805:
4806: sub save_bubble_lines {
4807: foreach my $line (keys(%bubble_lines_per_response)) {
4808: $env{"form.scantron.bubblelines.$line"} = $bubble_lines_per_response{$line};
4809: $env{"form.scantron.first_bubble_line.$line"} =
4810: $first_bubble_line{$line};
4811: $env{"form.scantron.sub_bubblelines.$line"} =
4812: $subdivided_bubble_lines{$line};
4813: $env{"form.scantron.responsetype.$line"} =
4814: $responsetype_per_response{$line};
4815: }
4816: }
4817:
4818:
4819: sub restore_bubble_lines {
4820: my $line = 0;
4821: %bubble_lines_per_response = ();
4822: while ($env{"form.scantron.bubblelines.$line"}) {
4823: my $value = $env{"form.scantron.bubblelines.$line"};
4824: $bubble_lines_per_response{$line} = $value;
4825: $first_bubble_line{$line} =
4826: $env{"form.scantron.first_bubble_line.$line"};
4827: $subdivided_bubble_lines{$line} =
4828: $env{"form.scantron.sub_bubblelines.$line"};
4829: $responsetype_per_response{$line} =
4830: $env{"form.scantron.responsetype.$line"};
4831: $line++;
4832: }
4833: }
4834:
4835: # Given the parsed scanline, get the response for
4836: # 'answer' number n:
4837:
4838: sub get_response_bubbles {
4839: my ($parsed_line, $response) = @_;
4840:
4841: my $bubble_line = $first_bubble_line{$response-1} +1;
4842: my $bubble_lines= $bubble_lines_per_response{$response-1};
4843:
4844: my $selected = "";
4845:
4846: for (my $bline = 0; $bline < $bubble_lines; $bline++) {
4847: $selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
4848: $bubble_line++;
4849: }
4850: return $selected;
4851: }
4852:
4853: =pod
4854:
4855: =item scantron_filenames
4856:
4857: Returns a list of the scantron files in the current course
4858:
4859: =cut
4860:
4861: sub scantron_filenames {
4862: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4863: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
4864: my $getpropath = 1;
4865: my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
4866: $getpropath);
4867: my @possiblenames;
4868: foreach my $filename (sort(@files)) {
4869: ($filename)=split(/&/,$filename);
4870: if ($filename!~/^scantron_orig_/) { next ; }
4871: $filename=~s/^scantron_orig_//;
4872: push(@possiblenames,$filename);
4873: }
4874: return @possiblenames;
4875: }
4876:
4877: =pod
4878:
4879: =item scantron_uploads
4880:
4881: Returns html drop-down list of scantron files in current course.
4882:
4883: Arguments:
4884: $file2grade - filename to set as selected in the dropdown
4885:
4886: =cut
4887:
4888: sub scantron_uploads {
4889: my ($file2grade) = @_;
4890: my $result= '<select name="scantron_selectfile">';
4891: $result.="<option></option>";
4892: foreach my $filename (sort(&scantron_filenames())) {
4893: $result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
4894: }
4895: $result.="</select>";
4896: return $result;
4897: }
4898:
4899: =pod
4900:
4901: =item scantron_scantab
4902:
4903: Returns html drop down of the scantron formats in the scantronformat.tab
4904: file.
4905:
4906: =cut
4907:
4908: sub scantron_scantab {
4909: my $result='<select name="scantron_format">'."\n";
4910: $result.='<option></option>'."\n";
4911: my @lines = &get_scantronformat_file();
4912: if (@lines > 0) {
4913: foreach my $line (@lines) {
4914: next if (($line =~ /^\#/) || ($line eq ''));
4915: my ($name,$descrip)=split(/:/,$line);
4916: $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
4917: }
4918: }
4919: $result.='</select>'."\n";
4920: return $result;
4921: }
4922:
4923: =pod
4924:
4925: =item get_scantronformat_file
4926:
4927: Returns an array containing lines from the scantron format file for
4928: the domain of the course.
4929:
4930: If a url for a custom.tab file is listed in domain's configuration.db,
4931: lines are from this file.
4932:
4933: Otherwise, if a default.tab has been published in RES space by the
4934: domainconfig user, lines are from this file.
4935:
4936: Otherwise, fall back to getting lines from the legacy file on the
4937: local server: /home/httpd/lonTabs/default_scantronformat.tab
4938:
4939: =cut
4940:
4941: sub get_scantronformat_file {
4942: my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
4943: my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
4944: my $gottab = 0;
4945: my @lines;
4946: if (ref($domconfig{'scantron'}) eq 'HASH') {
4947: if ($domconfig{'scantron'}{'scantronformat'} ne '') {
4948: my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
4949: if ($formatfile ne '-1') {
4950: @lines = split("\n",$formatfile,-1);
4951: $gottab = 1;
4952: }
4953: }
4954: }
4955: if (!$gottab) {
4956: my $confname = $cdom.'-domainconfig';
4957: my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
4958: my $formatfile = &Apache::lonnet::getfile($default);
4959: if ($formatfile ne '-1') {
4960: @lines = split("\n",$formatfile,-1);
4961: $gottab = 1;
4962: }
4963: }
4964: if (!$gottab) {
4965: my @domains = &Apache::lonnet::current_machine_domains();
4966: if (grep(/^\Q$cdom\E$/,@domains)) {
4967: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
4968: @lines = <$fh>;
4969: close($fh);
4970: } else {
4971: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
4972: @lines = <$fh>;
4973: close($fh);
4974: }
4975: }
4976: return @lines;
4977: }
4978:
4979: =pod
4980:
4981: =item scantron_CODElist
4982:
4983: Returns html drop down of the saved CODE lists from current course,
4984: generated from earlier printings.
4985:
4986: =cut
4987:
4988: sub scantron_CODElist {
4989: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4990: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4991: my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
4992: my $namechoice='<option></option>';
4993: foreach my $name (sort {uc($a) cmp uc($b)} @names) {
4994: if ($name =~ /^error: 2 /) { next; }
4995: if ($name =~ /^type\0/) { next; }
4996: $namechoice.='<option value="'.$name.'">'.$name.'</option>';
4997: }
4998: $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
4999: return $namechoice;
5000: }
5001:
5002: =pod
5003:
5004: =item scantron_CODEunique
5005:
5006: Returns the html for "Each CODE to be used once" radio.
5007:
5008: =cut
5009:
5010: sub scantron_CODEunique {
5011: my $result='<span class="LC_nobreak">
5012: <label><input type="radio" name="scantron_CODEunique"
5013: value="yes" checked="checked" />'.&mt('Yes').' </label>
5014: </span>
5015: <span class="LC_nobreak">
5016: <label><input type="radio" name="scantron_CODEunique"
5017: value="no" />'.&mt('No').' </label>
5018: </span>';
5019: return $result;
5020: }
5021:
5022: =pod
5023:
5024: =item scantron_selectphase
5025:
5026: Generates the initial screen to start the bubble sheet process.
5027: Allows for - starting a grading run.
5028: - downloading existing scan data (original, corrected
5029: or skipped info)
5030:
5031: - uploading new scan data
5032:
5033: Arguments:
5034: $r - The Apache request object
5035: $file2grade - name of the file that contain the scanned data to score
5036:
5037: =cut
5038:
5039: sub scantron_selectphase {
5040: my ($r,$file2grade) = @_;
5041: my ($symb)=&get_symb($r);
5042: if (!$symb) {return '';}
5043: my $sequence_selector=&getSequenceDropDown($symb);
5044: my $default_form_data=&defaultFormData($symb);
5045: my $grading_menu_button=&show_grading_menu_form($symb);
5046: my $file_selector=&scantron_uploads($file2grade);
5047: my $format_selector=&scantron_scantab();
5048: my $CODE_selector=&scantron_CODElist();
5049: my $CODE_unique=&scantron_CODEunique();
5050: my $result;
5051:
5052: $ssi_error = 0;
5053:
5054: # Chunk of form to prompt for a file to grade and how:
5055:
5056: $result.= '
5057: <br />
5058: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
5059: <input type="hidden" name="command" value="scantron_warning" />
5060: '.$default_form_data.'
5061: '.&Apache::loncommon::start_data_table('LC_scantron_action').'
5062: '.&Apache::loncommon::start_data_table_header_row().'
5063: <th colspan="2">
5064: '.&mt('Specify file and which Folder/Sequence to grade').'
5065: </th>
5066: '.&Apache::loncommon::end_data_table_header_row().'
5067: '.&Apache::loncommon::start_data_table_row().'
5068: <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
5069: '.&Apache::loncommon::end_data_table_row().'
5070: '.&Apache::loncommon::start_data_table_row().'
5071: <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
5072: '.&Apache::loncommon::end_data_table_row().'
5073: '.&Apache::loncommon::start_data_table_row().'
5074: <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
5075: '.&Apache::loncommon::end_data_table_row().'
5076: '.&Apache::loncommon::start_data_table_row().'
5077: <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
5078: '.&Apache::loncommon::end_data_table_row().'
5079: '.&Apache::loncommon::start_data_table_row().'
5080: <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
5081: '.&Apache::loncommon::end_data_table_row().'
5082: '.&Apache::loncommon::start_data_table_row().'
5083: <td> '.&mt('Options:').' </td>
5084: <td>
5085: <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
5086: <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
5087: <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
5088: </td>
5089: '.&Apache::loncommon::end_data_table_row().'
5090: '.&Apache::loncommon::start_data_table_row().'
5091: <td colspan="2">
5092: <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
5093: </td>
5094: '.&Apache::loncommon::end_data_table_row().'
5095: '.&Apache::loncommon::end_data_table().'
5096: </form>
5097: ';
5098:
5099: $r->print($result);
5100:
5101: if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
5102: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
5103:
5104: # Chunk of form to prompt for a scantron file upload.
5105:
5106: $r->print('
5107: <br />
5108: '.&Apache::loncommon::start_data_table('LC_scantron_action').'
5109: '.&Apache::loncommon::start_data_table_header_row().'
5110: <th>
5111: '.&mt('Specify a bubblesheet data file to upload.').'
5112: </th>
5113: '.&Apache::loncommon::end_data_table_header_row().'
5114: '.&Apache::loncommon::start_data_table_row().'
5115: <td>
5116: ');
5117: my $default_form_data=&defaultFormData(&get_symb($r,1));
5118: my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
5119: my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
5120: $r->print('
5121: <script type="text/javascript" language="javascript">
5122: function checkUpload(formname) {
5123: if (formname.upfile.value == "") {
5124: alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
5125: return false;
5126: }
5127: formname.submit();
5128: }
5129: </script>
5130:
5131: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
5132: '.$default_form_data.'
5133: <input name="courseid" type="hidden" value="'.$cnum.'" />
5134: <input name="domainid" type="hidden" value="'.$cdom.'" />
5135: <input name="command" value="scantronupload_save" type="hidden" />
5136: '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
5137: <br />
5138: <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
5139: </form>
5140: ');
5141:
5142: $r->print('
5143: </td>
5144: '.&Apache::loncommon::end_data_table_row().'
5145: '.&Apache::loncommon::end_data_table().'
5146: ');
5147: }
5148:
5149: # Chunk of the form that prompts to view a scoring office file,
5150: # corrected file, skipped records in a file.
5151:
5152: $r->print('
5153: <br />
5154: <form action="/adm/grades" name="scantron_download">
5155: '.$default_form_data.'
5156: <input type="hidden" name="command" value="scantron_download" />
5157: '.&Apache::loncommon::start_data_table('LC_scantron_action').'
5158: '.&Apache::loncommon::start_data_table_header_row().'
5159: <th>
5160: '.&mt('Download a scoring office file').'
5161: </th>
5162: '.&Apache::loncommon::end_data_table_header_row().'
5163: '.&Apache::loncommon::start_data_table_row().'
5164: <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).'
5165: <br />
5166: <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
5167: '.&Apache::loncommon::end_data_table_row().'
5168: '.&Apache::loncommon::end_data_table().'
5169: </form>
5170: <br />
5171: ');
5172:
5173: &Apache::lonpickcode::code_list($r,2);
5174:
5175: $r->print('<br /><form method="post" name="checkscantron">'.
5176: $default_form_data."\n".
5177: &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
5178: &Apache::loncommon::start_data_table_header_row()."\n".
5179: '<th colspan="2">
5180: '.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
5181: '</th>'."\n".
5182: &Apache::loncommon::end_data_table_header_row()."\n".
5183: &Apache::loncommon::start_data_table_row()."\n".
5184: '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
5185: '<td> '.$sequence_selector.' </td>'.
5186: &Apache::loncommon::end_data_table_row()."\n".
5187: &Apache::loncommon::start_data_table_row()."\n".
5188: '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
5189: '<td> '.$file_selector.' </td>'."\n".
5190: &Apache::loncommon::end_data_table_row()."\n".
5191: &Apache::loncommon::start_data_table_row()."\n".
5192: '<td> '.&mt('Format of data file:').' </td>'."\n".
5193: '<td> '.$format_selector.' </td>'."\n".
5194: &Apache::loncommon::end_data_table_row()."\n".
5195: &Apache::loncommon::start_data_table_row()."\n".
5196: '<td> '.&mt('Options').' </td>'."\n".
5197: '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
5198: &Apache::loncommon::end_data_table_row()."\n".
5199: &Apache::loncommon::start_data_table_row()."\n".
5200: '<td colspan="2">'."\n".
5201: '<input type="hidden" name="command" value="checksubmissions" />'."\n".
5202: '<input type="submit" value="'.&mt('Review Scantron Data and Submission Records').'" />'."\n".
5203: '</td>'."\n".
5204: &Apache::loncommon::end_data_table_row()."\n".
5205: &Apache::loncommon::end_data_table()."\n".
5206: '</form><br />');
5207: $r->print($grading_menu_button);
5208: return;
5209: }
5210:
5211: =pod
5212:
5213: =item get_scantron_config
5214:
5215: Parse and return the scantron configuration line selected as a
5216: hash of configuration file fields.
5217:
5218: Arguments:
5219: which - the name of the configuration to parse from the file.
5220:
5221:
5222: Returns:
5223: If the named configuration is not in the file, an empty
5224: hash is returned.
5225: a hash with the fields
5226: name - internal name for the this configuration setup
5227: description - text to display to operator that describes this config
5228: CODElocation - if 0 or the string 'none'
5229: - no CODE exists for this config
5230: if -1 || the string 'letter'
5231: - a CODE exists for this config and is
5232: a string of letters
5233: Unsupported value (but planned for future support)
5234: if a positive integer
5235: - The CODE exists as the first n items from
5236: the question section of the form
5237: if the string 'number'
5238: - The CODE exists for this config and is
5239: a string of numbers
5240: CODEstart - (only matter if a CODE exists) column in the line where
5241: the CODE starts
5242: CODElength - length of the CODE
5243: IDstart - column where the student/employee ID starts
5244: IDlength - length of the student/employee ID info
5245: Qstart - column where the information from the bubbled
5246: 'questions' start
5247: Qlength - number of columns comprising a single bubble line from
5248: the sheet. (usually either 1 or 10)
5249: Qon - either a single character representing the character used
5250: to signal a bubble was chosen in the positional setup, or
5251: the string 'letter' if the letter of the chosen bubble is
5252: in the final, or 'number' if a number representing the
5253: chosen bubble is in the file (1->A 0->J)
5254: Qoff - the character used to represent that a bubble was
5255: left blank
5256: PaperID - if the scanning process generates a unique number for each
5257: sheet scanned the column that this ID number starts in
5258: PaperIDlength - number of columns that comprise the unique ID number
5259: for the sheet of paper
5260: FirstName - column that the first name starts in
5261: FirstNameLength - number of columns that the first name spans
5262:
5263: LastName - column that the last name starts in
5264: LastNameLength - number of columns that the last name spans
5265:
5266: =cut
5267:
5268: sub get_scantron_config {
5269: my ($which) = @_;
5270: my @lines = &get_scantronformat_file();
5271: my %config;
5272: #FIXME probably should move to XML it has already gotten a bit much now
5273: foreach my $line (@lines) {
5274: my ($name,$descrip)=split(/:/,$line);
5275: if ($name ne $which ) { next; }
5276: chomp($line);
5277: my @config=split(/:/,$line);
5278: $config{'name'}=$config[0];
5279: $config{'description'}=$config[1];
5280: $config{'CODElocation'}=$config[2];
5281: $config{'CODEstart'}=$config[3];
5282: $config{'CODElength'}=$config[4];
5283: $config{'IDstart'}=$config[5];
5284: $config{'IDlength'}=$config[6];
5285: $config{'Qstart'}=$config[7];
5286: $config{'Qlength'}=$config[8];
5287: $config{'Qoff'}=$config[9];
5288: $config{'Qon'}=$config[10];
5289: $config{'PaperID'}=$config[11];
5290: $config{'PaperIDlength'}=$config[12];
5291: $config{'FirstName'}=$config[13];
5292: $config{'FirstNamelength'}=$config[14];
5293: $config{'LastName'}=$config[15];
5294: $config{'LastNamelength'}=$config[16];
5295: last;
5296: }
5297: return %config;
5298: }
5299:
5300: =pod
5301:
5302: =item username_to_idmap
5303:
5304: creates a hash keyed by student/employee ID with values of the corresponding
5305: student username:domain.
5306:
5307: Arguments:
5308:
5309: $classlist - reference to the class list hash. This is a hash
5310: keyed by student name:domain whose elements are references
5311: to arrays containing various chunks of information
5312: about the student. (See loncoursedata for more info).
5313:
5314: Returns
5315: %idmap - the constructed hash
5316:
5317: =cut
5318:
5319: sub username_to_idmap {
5320: my ($classlist)= @_;
5321: my %idmap;
5322: foreach my $student (keys(%$classlist)) {
5323: $idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
5324: $student;
5325: }
5326: return %idmap;
5327: }
5328:
5329: =pod
5330:
5331: =item scantron_fixup_scanline
5332:
5333: Process a requested correction to a scanline.
5334:
5335: Arguments:
5336: $scantron_config - hash from &get_scantron_config()
5337: $scan_data - hash of correction information
5338: (see &scantron_getfile())
5339: $line - existing scanline
5340: $whichline - line number of the passed in scanline
5341: $field - type of change to process
5342: (either
5343: 'ID' -> correct the student/employee ID
5344: 'CODE' -> correct the CODE
5345: 'answer' -> fixup the submitted answers)
5346:
5347: $args - hash of additional info,
5348: - 'ID'
5349: 'newid' -> studentID to use in replacement
5350: of existing one
5351: - 'CODE'
5352: 'CODE_ignore_dup' - set to true if duplicates
5353: should be ignored.
5354: 'CODE' - is new code or 'use_unfound'
5355: if the existing unfound code should
5356: be used as is
5357: - 'answer'
5358: 'response' - new answer or 'none' if blank
5359: 'question' - the bubble line to change
5360: 'questionnum' - the question identifier,
5361: may include subquestion.
5362:
5363: Returns:
5364: $line - the modified scanline
5365:
5366: Side effects:
5367: $scan_data - may be updated
5368:
5369: =cut
5370:
5371:
5372: sub scantron_fixup_scanline {
5373: my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
5374: if ($field eq 'ID') {
5375: if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
5376: return ($line,1,'New value too large');
5377: }
5378: if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
5379: $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
5380: $args->{'newid'});
5381: }
5382: substr($line,$$scantron_config{'IDstart'}-1,
5383: $$scantron_config{'IDlength'})=$args->{'newid'};
5384: if ($args->{'newid'}=~/^\s*$/) {
5385: &scan_data($scan_data,"$whichline.user",
5386: $args->{'username'}.':'.$args->{'domain'});
5387: }
5388: } elsif ($field eq 'CODE') {
5389: if ($args->{'CODE_ignore_dup'}) {
5390: &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
5391: }
5392: &scan_data($scan_data,"$whichline.useCODE",'1');
5393: if ($args->{'CODE'} ne 'use_unfound') {
5394: if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
5395: return ($line,1,'New CODE value too large');
5396: }
5397: if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
5398: $args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
5399: }
5400: substr($line,$$scantron_config{'CODEstart'}-1,
5401: $$scantron_config{'CODElength'})=$args->{'CODE'};
5402: }
5403: } elsif ($field eq 'answer') {
5404: my $length=$scantron_config->{'Qlength'};
5405: my $off=$scantron_config->{'Qoff'};
5406: my $on=$scantron_config->{'Qon'};
5407: my $answer=${off}x$length;
5408: if ($args->{'response'} eq 'none') {
5409: &scan_data($scan_data,
5410: "$whichline.no_bubble.".$args->{'questionnum'},'1');
5411: } else {
5412: if ($on eq 'letter') {
5413: my @alphabet=('A'..'Z');
5414: $answer=$alphabet[$args->{'response'}];
5415: } elsif ($on eq 'number') {
5416: $answer=$args->{'response'}+1;
5417: if ($answer == 10) { $answer = '0'; }
5418: } else {
5419: substr($answer,$args->{'response'},1)=$on;
5420: }
5421: &scan_data($scan_data,
5422: "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
5423: }
5424: my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
5425: substr($line,$where-1,$length)=$answer;
5426: }
5427: return $line;
5428: }
5429:
5430: =pod
5431:
5432: =item scan_data
5433:
5434: Edit or look up an item in the scan_data hash.
5435:
5436: Arguments:
5437: $scan_data - The hash (see scantron_getfile)
5438: $key - shorthand of the key to edit (actual key is
5439: scantronfilename_key).
5440: $data - New value of the hash entry.
5441: $delete - If true, the entry is removed from the hash.
5442:
5443: Returns:
5444: The new value of the hash table field (undefined if deleted).
5445:
5446: =cut
5447:
5448:
5449: sub scan_data {
5450: my ($scan_data,$key,$value,$delete)=@_;
5451: my $filename=$env{'form.scantron_selectfile'};
5452: if (defined($value)) {
5453: $scan_data->{$filename.'_'.$key} = $value;
5454: }
5455: if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
5456: return $scan_data->{$filename.'_'.$key};
5457: }
5458:
5459: # ----- These first few routines are general use routines.----
5460:
5461: # Return the number of occurences of a pattern in a string.
5462:
5463: sub occurence_count {
5464: my ($string, $pattern) = @_;
5465:
5466: my @matches = ($string =~ /$pattern/g);
5467:
5468: return scalar(@matches);
5469: }
5470:
5471:
5472: # Take a string known to have digits and convert all the
5473: # digits into letters in the range J,A..I.
5474:
5475: sub digits_to_letters {
5476: my ($input) = @_;
5477:
5478: my @alphabet = ('J', 'A'..'I');
5479:
5480: my @input = split(//, $input);
5481: my $output ='';
5482: for (my $i = 0; $i < scalar(@input); $i++) {
5483: if ($input[$i] =~ /\d/) {
5484: $output .= $alphabet[$input[$i]];
5485: } else {
5486: $output .= $input[$i];
5487: }
5488: }
5489: return $output;
5490: }
5491:
5492: =pod
5493:
5494: =item scantron_parse_scanline
5495:
5496: Decodes a scanline from the selected scantron file
5497:
5498: Arguments:
5499: line - The text of the scantron file line to process
5500: whichline - Line number
5501: scantron_config - Hash describing the format of the scantron lines.
5502: scan_data - Hash of extra information about the scanline
5503: (see scantron_getfile for more information)
5504: just_header - True if should not process question answers but only
5505: the stuff to the left of the answers.
5506: Returns:
5507: Hash containing the result of parsing the scanline
5508:
5509: Keys are all proceeded by the string 'scantron.'
5510:
5511: CODE - the CODE in use for this scanline
5512: useCODE - 1 if the CODE is invalid but it usage has been forced
5513: by the operator
5514: CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
5515: CODEs were selected, but the usage has been
5516: forced by the operator
5517: ID - student/employee ID
5518: PaperID - if used, the ID number printed on the sheet when the
5519: paper was scanned
5520: FirstName - first name from the sheet
5521: LastName - last name from the sheet
5522:
5523: if just_header was not true these key may also exist
5524:
5525: missingerror - a list of bubble ranges that are considered to be answers
5526: to a single question that don't have any bubbles filled in.
5527: Of the form questionnumber:firstbubblenumber:count.
5528: doubleerror - a list of bubble ranges that are considered to be answers
5529: to a single question that have more than one bubble filled in.
5530: Of the form questionnumber::firstbubblenumber:count
5531:
5532: In the above, count is the number of bubble responses in the
5533: input line needed to represent the possible answers to the question.
5534: e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
5535: per line would have count = 2.
5536:
5537: maxquest - the number of the last bubble line that was parsed
5538:
5539: (<number> starts at 1)
5540: <number>.answer - zero or more letters representing the selected
5541: letters from the scanline for the bubble line
5542: <number>.
5543: if blank there was either no bubble or there where
5544: multiple bubbles, (consult the keys missingerror and
5545: doubleerror if this is an error condition)
5546:
5547: =cut
5548:
5549: sub scantron_parse_scanline {
5550: my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
5551:
5552: my %record;
5553: my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
5554: my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos); # Answers
5555: my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # earlier stuff
5556: if (!($$scantron_config{'CODElocation'} eq 0 ||
5557: $$scantron_config{'CODElocation'} eq 'none')) {
5558: if ($$scantron_config{'CODElocation'} < 0 ||
5559: $$scantron_config{'CODElocation'} eq 'letter' ||
5560: $$scantron_config{'CODElocation'} eq 'number') {
5561: $record{'scantron.CODE'}=substr($data,
5562: $$scantron_config{'CODEstart'}-1,
5563: $$scantron_config{'CODElength'});
5564: if (&scan_data($scan_data,"$whichline.useCODE")) {
5565: $record{'scantron.useCODE'}=1;
5566: }
5567: if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
5568: $record{'scantron.CODE_ignore_dup'}=1;
5569: }
5570: } else {
5571: #FIXME interpret first N questions
5572: }
5573: }
5574: $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
5575: $$scantron_config{'IDlength'});
5576: $record{'scantron.PaperID'}=
5577: substr($data,$$scantron_config{'PaperID'}-1,
5578: $$scantron_config{'PaperIDlength'});
5579: $record{'scantron.FirstName'}=
5580: substr($data,$$scantron_config{'FirstName'}-1,
5581: $$scantron_config{'FirstNamelength'});
5582: $record{'scantron.LastName'}=
5583: substr($data,$$scantron_config{'LastName'}-1,
5584: $$scantron_config{'LastNamelength'});
5585: if ($just_header) { return \%record; }
5586:
5587: my @alphabet=('A'..'Z');
5588: my $questnum=0;
5589: my $ansnum =1; # Multiple 'answer lines'/question.
5590:
5591: chomp($questions); # Get rid of any trailing \n.
5592: $questions =~ s/\r$//; # Get rid of trailing \r too (MAC or Win uploads).
5593: while (length($questions)) {
5594: my $answers_needed = $bubble_lines_per_response{$questnum};
5595: my $answer_length = ($$scantron_config{'Qlength'} * $answers_needed)
5596: || 1;
5597: $questnum++;
5598: my $quest_id = $questnum;
5599: my $currentquest = substr($questions,0,$answer_length);
5600: $questions = substr($questions,$answer_length);
5601: if (length($currentquest) < $answer_length) { next; }
5602:
5603: if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
5604: my $subquestnum = 1;
5605: my $subquestions = $currentquest;
5606: my @subanswers_needed =
5607: split(/,/,$subdivided_bubble_lines{$questnum-1});
5608: foreach my $subans (@subanswers_needed) {
5609: my $subans_length =
5610: ($$scantron_config{'Qlength'} * $subans) || 1;
5611: my $currsubquest = substr($subquestions,0,$subans_length);
5612: $subquestions = substr($subquestions,$subans_length);
5613: $quest_id = "$questnum.$subquestnum";
5614: if (($$scantron_config{'Qon'} eq 'letter') ||
5615: ($$scantron_config{'Qon'} eq 'number')) {
5616: $ansnum = &scantron_validator_lettnum($ansnum,
5617: $questnum,$quest_id,$subans,$currsubquest,$whichline,
5618: \@alphabet,\%record,$scantron_config,$scan_data);
5619: } else {
5620: $ansnum = &scantron_validator_positional($ansnum,
5621: $questnum,$quest_id,$subans,$currsubquest,$whichline, \@alphabet,\%record,$scantron_config,$scan_data);
5622: }
5623: $subquestnum ++;
5624: }
5625: } else {
5626: if (($$scantron_config{'Qon'} eq 'letter') ||
5627: ($$scantron_config{'Qon'} eq 'number')) {
5628: $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
5629: $quest_id,$answers_needed,$currentquest,$whichline,
5630: \@alphabet,\%record,$scantron_config,$scan_data);
5631: } else {
5632: $ansnum = &scantron_validator_positional($ansnum,$questnum,
5633: $quest_id,$answers_needed,$currentquest,$whichline,
5634: \@alphabet,\%record,$scantron_config,$scan_data);
5635: }
5636: }
5637: }
5638: $record{'scantron.maxquest'}=$questnum;
5639: return \%record;
5640: }
5641:
5642: sub scantron_validator_lettnum {
5643: my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
5644: $alphabet,$record,$scantron_config,$scan_data) = @_;
5645:
5646: # Qon 'letter' implies for each slot in currquest we have:
5647: # ? or * for doubles, a letter in A-Z for a bubble, and
5648: # about anything else (esp. a value of Qoff) for missing
5649: # bubbles.
5650: #
5651: # Qon 'number' implies each slot gives a digit that indexes the
5652: # bubbles filled, or Qoff, or a non-number for unbubbled lines,
5653: # and * or ? for double bubbles on a single line.
5654: #
5655:
5656: my $matchon;
5657: if ($$scantron_config{'Qon'} eq 'letter') {
5658: $matchon = '[A-Z]';
5659: } elsif ($$scantron_config{'Qon'} eq 'number') {
5660: $matchon = '\d';
5661: }
5662: my $occurrences = 0;
5663: if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
5664: ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
5665: ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
5666: ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
5667: ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
5668: ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
5669: my @singlelines = split('',$currquest);
5670: foreach my $entry (@singlelines) {
5671: $occurrences = &occurence_count($entry,$matchon);
5672: if ($occurrences > 1) {
5673: last;
5674: }
5675: }
5676: } else {
5677: $occurrences = &occurence_count($currquest,$matchon);
5678: }
5679: if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
5680: push(@{$record->{'scantron.doubleerror'}},$quest_id);
5681: for (my $ans=0; $ans<$answers_needed; $ans++) {
5682: my $bubble = substr($currquest,$ans,1);
5683: if ($bubble =~ /$matchon/ ) {
5684: if ($$scantron_config{'Qon'} eq 'number') {
5685: if ($bubble == 0) {
5686: $bubble = 10;
5687: }
5688: $record->{"scantron.$ansnum.answer"} =
5689: $alphabet->[$bubble-1];
5690: } else {
5691: $record->{"scantron.$ansnum.answer"} = $bubble;
5692: }
5693: } else {
5694: $record->{"scantron.$ansnum.answer"}='';
5695: }
5696: $ansnum++;
5697: }
5698: } elsif (!defined($currquest)
5699: || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
5700: || (&occurence_count($currquest,$matchon) == 0)) {
5701: for (my $ans=0; $ans<$answers_needed; $ans++ ) {
5702: $record->{"scantron.$ansnum.answer"}='';
5703: $ansnum++;
5704: }
5705: if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
5706: push(@{$record->{'scantron.missingerror'}},$quest_id);
5707: }
5708: } else {
5709: if ($$scantron_config{'Qon'} eq 'number') {
5710: $currquest = &digits_to_letters($currquest);
5711: }
5712: for (my $ans=0; $ans<$answers_needed; $ans++) {
5713: my $bubble = substr($currquest,$ans,1);
5714: $record->{"scantron.$ansnum.answer"} = $bubble;
5715: $ansnum++;
5716: }
5717: }
5718: return $ansnum;
5719: }
5720:
5721: sub scantron_validator_positional {
5722: my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
5723: $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
5724:
5725: # Otherwise there's a positional notation;
5726: # each bubble line requires Qlength items, and there are filled in
5727: # bubbles for each case where there 'Qon' characters.
5728: #
5729:
5730: my @array=split($$scantron_config{'Qon'},$currquest,-1);
5731:
5732: # If the split only gives us one element.. the full length of the
5733: # answer string, no bubbles are filled in:
5734:
5735: if ($answers_needed eq '') {
5736: return;
5737: }
5738:
5739: if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
5740: for (my $ans=0; $ans<$answers_needed; $ans++ ) {
5741: $record->{"scantron.$ansnum.answer"}='';
5742: $ansnum++;
5743: }
5744: if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
5745: push(@{$record->{"scantron.missingerror"}},$quest_id);
5746: }
5747: } elsif (scalar(@array) == 2) {
5748: my $location = length($array[0]);
5749: my $line_num = int($location / $$scantron_config{'Qlength'});
5750: my $bubble = $alphabet->[$location % $$scantron_config{'Qlength'}];
5751: for (my $ans=0; $ans<$answers_needed; $ans++) {
5752: if ($ans eq $line_num) {
5753: $record->{"scantron.$ansnum.answer"} = $bubble;
5754: } else {
5755: $record->{"scantron.$ansnum.answer"} = ' ';
5756: }
5757: $ansnum++;
5758: }
5759: } else {
5760: # If there's more than one instance of a bubble character
5761: # That's a double bubble; with positional notation we can
5762: # record all the bubbles filled in as well as the
5763: # fact this response consists of multiple bubbles.
5764: #
5765: if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
5766: ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
5767: ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
5768: ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
5769: ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
5770: ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
5771: my $doubleerror = 0;
5772: while (($currquest >= $$scantron_config{'Qlength'}) &&
5773: (!$doubleerror)) {
5774: my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
5775: $currquest = substr($currquest,$$scantron_config{'Qlength'});
5776: my @currarray = split($$scantron_config{'Qon'},$currline,-1);
5777: if (length(@currarray) > 2) {
5778: $doubleerror = 1;
5779: }
5780: }
5781: if ($doubleerror) {
5782: push(@{$record->{'scantron.doubleerror'}},$quest_id);
5783: }
5784: } else {
5785: push(@{$record->{'scantron.doubleerror'}},$quest_id);
5786: }
5787: my $item = $ansnum;
5788: for (my $ans=0; $ans<$answers_needed; $ans++) {
5789: $record->{"scantron.$item.answer"} = '';
5790: $item ++;
5791: }
5792:
5793: my @ans=@array;
5794: my $i=0;
5795: my $increment = 0;
5796: while ($#ans) {
5797: $i+=length($ans[0]) + $increment;
5798: my $line = int($i/$$scantron_config{'Qlength'} + $ansnum);
5799: my $bubble = $i%$$scantron_config{'Qlength'};
5800: $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
5801: shift(@ans);
5802: $increment = 1;
5803: }
5804: $ansnum += $answers_needed;
5805: }
5806: return $ansnum;
5807: }
5808:
5809: =pod
5810:
5811: =item scantron_add_delay
5812:
5813: Adds an error message that occurred during the grading phase to a
5814: queue of messages to be shown after grading pass is complete
5815:
5816: Arguments:
5817: $delayqueue - arrary ref of hash ref of error messages
5818: $scanline - the scanline that caused the error
5819: $errormesage - the error message
5820: $errorcode - a numeric code for the error
5821:
5822: Side Effects:
5823: updates the $delayqueue to have a new hash ref of the error
5824:
5825: =cut
5826:
5827: sub scantron_add_delay {
5828: my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
5829: push(@$delayqueue,
5830: {'line' => $scanline, 'emsg' => $errormessage,
5831: 'ecode' => $errorcode }
5832: );
5833: }
5834:
5835: =pod
5836:
5837: =item scantron_find_student
5838:
5839: Finds the username for the current scanline
5840:
5841: Arguments:
5842: $scantron_record - hash result from scantron_parse_scanline
5843: $scan_data - hash of correction information
5844: (see &scantron_getfile() form more information)
5845: $idmap - hash from &username_to_idmap()
5846: $line - number of current scanline
5847:
5848: Returns:
5849: Either 'username:domain' or undef if unknown
5850:
5851: =cut
5852:
5853: sub scantron_find_student {
5854: my ($scantron_record,$scan_data,$idmap,$line)=@_;
5855: my $scanID=$$scantron_record{'scantron.ID'};
5856: if ($scanID =~ /^\s*$/) {
5857: return &scan_data($scan_data,"$line.user");
5858: }
5859: foreach my $id (keys(%$idmap)) {
5860: if (lc($id) eq lc($scanID)) {
5861: return $$idmap{$id};
5862: }
5863: }
5864: return undef;
5865: }
5866:
5867: =pod
5868:
5869: =item scantron_filter
5870:
5871: Filter sub for lonnavmaps, filters out hidden resources if ignore
5872: hidden resources was selected
5873:
5874: =cut
5875:
5876: sub scantron_filter {
5877: my ($curres)=@_;
5878:
5879: if (ref($curres) && $curres->is_problem()) {
5880: # if the user has asked to not have either hidden
5881: # or 'randomout' controlled resources to be graded
5882: # don't include them
5883: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
5884: && $curres->randomout) {
5885: return 0;
5886: }
5887: return 1;
5888: }
5889: return 0;
5890: }
5891:
5892: =pod
5893:
5894: =item scantron_process_corrections
5895:
5896: Gets correction information out of submitted form data and corrects
5897: the scanline
5898:
5899: =cut
5900:
5901: sub scantron_process_corrections {
5902: my ($r) = @_;
5903: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
5904: my ($scanlines,$scan_data)=&scantron_getfile();
5905: my $classlist=&Apache::loncoursedata::get_classlist();
5906: my $which=$env{'form.scantron_line'};
5907: my $line=&scantron_get_line($scanlines,$scan_data,$which);
5908: my ($skip,$err,$errmsg);
5909: if ($env{'form.scantron_skip_record'}) {
5910: $skip=1;
5911: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
5912: my $newstudent=$env{'form.scantron_username'}.':'.
5913: $env{'form.scantron_domain'};
5914: my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
5915: ($line,$err,$errmsg)=
5916: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
5917: 'ID',{'newid'=>$newid,
5918: 'username'=>$env{'form.scantron_username'},
5919: 'domain'=>$env{'form.scantron_domain'}});
5920: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
5921: my $resolution=$env{'form.scantron_CODE_resolution'};
5922: my $newCODE;
5923: my %args;
5924: if ($resolution eq 'use_unfound') {
5925: $newCODE='use_unfound';
5926: } elsif ($resolution eq 'use_found') {
5927: $newCODE=$env{'form.scantron_CODE_selectedvalue'};
5928: } elsif ($resolution eq 'use_typed') {
5929: $newCODE=$env{'form.scantron_CODE_newvalue'};
5930: } elsif ($resolution =~ /^use_closest_(\d+)/) {
5931: $newCODE=$env{"form.scantron_CODE_closest_$1"};
5932: }
5933: if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
5934: $args{'CODE_ignore_dup'}=1;
5935: }
5936: $args{'CODE'}=$newCODE;
5937: ($line,$err,$errmsg)=
5938: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
5939: 'CODE',\%args);
5940: } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
5941: foreach my $question (split(',',$env{'form.scantron_questions'})) {
5942: ($line,$err,$errmsg)=
5943: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
5944: $which,'answer',
5945: { 'question'=>$question,
5946: 'response'=>$env{"form.scantron_correct_Q_$question"},
5947: 'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
5948: if ($err) { last; }
5949: }
5950: }
5951: if ($err) {
5952: $r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
5953: } else {
5954: &scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
5955: &scantron_putfile($scanlines,$scan_data);
5956: }
5957: }
5958:
5959: =pod
5960:
5961: =item reset_skipping_status
5962:
5963: Forgets the current set of remember skipped scanlines (and thus
5964: reverts back to considering all lines in the
5965: scantron_skipped_<filename> file)
5966:
5967: =cut
5968:
5969: sub reset_skipping_status {
5970: my ($scanlines,$scan_data)=&scantron_getfile();
5971: &scan_data($scan_data,'remember_skipping',undef,1);
5972: &scantron_putfile(undef,$scan_data);
5973: }
5974:
5975: =pod
5976:
5977: =item start_skipping
5978:
5979: Marks a scanline to be skipped.
5980:
5981: =cut
5982:
5983: sub start_skipping {
5984: my ($scan_data,$i)=@_;
5985: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
5986: if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
5987: $remembered{$i}=2;
5988: } else {
5989: $remembered{$i}=1;
5990: }
5991: &scan_data($scan_data,'remember_skipping',join(':',%remembered));
5992: }
5993:
5994: =pod
5995:
5996: =item should_be_skipped
5997:
5998: Checks whether a scanline should be skipped.
5999:
6000: =cut
6001:
6002: sub should_be_skipped {
6003: my ($scanlines,$scan_data,$i)=@_;
6004: if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
6005: # not redoing old skips
6006: if ($scanlines->{'skipped'}[$i]) { return 1; }
6007: return 0;
6008: }
6009: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
6010:
6011: if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
6012: return 0;
6013: }
6014: return 1;
6015: }
6016:
6017: =pod
6018:
6019: =item remember_current_skipped
6020:
6021: Discovers what scanlines are in the scantron_skipped_<filename>
6022: file and remembers them into scan_data for later use.
6023:
6024: =cut
6025:
6026: sub remember_current_skipped {
6027: my ($scanlines,$scan_data)=&scantron_getfile();
6028: my %to_remember;
6029: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6030: if ($scanlines->{'skipped'}[$i]) {
6031: $to_remember{$i}=1;
6032: }
6033: }
6034:
6035: &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
6036: &scantron_putfile(undef,$scan_data);
6037: }
6038:
6039: =pod
6040:
6041: =item check_for_error
6042:
6043: Checks if there was an error when attempting to remove a specific
6044: scantron_.. bubble sheet data file. Prints out an error if
6045: something went wrong.
6046:
6047: =cut
6048:
6049: sub check_for_error {
6050: my ($r,$result)=@_;
6051: if ($result ne 'ok' && $result ne 'not_found' ) {
6052: $r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
6053: }
6054: }
6055:
6056: =pod
6057:
6058: =item scantron_warning_screen
6059:
6060: Interstitial screen to make sure the operator has selected the
6061: correct options before we start the validation phase.
6062:
6063: =cut
6064:
6065: sub scantron_warning_screen {
6066: my ($button_text)=@_;
6067: my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
6068: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6069: my $CODElist;
6070: if ($scantron_config{'CODElocation'} &&
6071: $scantron_config{'CODEstart'} &&
6072: $scantron_config{'CODElength'}) {
6073: $CODElist=$env{'form.scantron_CODElist'};
6074: if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
6075: $CODElist=
6076: '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
6077: $env{'form.scantron_CODElist'}.'</tt></td></tr>';
6078: }
6079: return ('
6080: <p>
6081: <span class="LC_warning">
6082: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
6083: </p>
6084: <table>
6085: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
6086: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
6087: '.$CODElist.'
6088: </table>
6089: <br />
6090: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
6091: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
6092:
6093: <br />
6094: ');
6095: }
6096:
6097: =pod
6098:
6099: =item scantron_do_warning
6100:
6101: Check if the operator has picked something for all required
6102: fields. Error out if something is missing.
6103:
6104: =cut
6105:
6106: sub scantron_do_warning {
6107: my ($r)=@_;
6108: my ($symb)=&get_symb($r);
6109: if (!$symb) {return '';}
6110: my $default_form_data=&defaultFormData($symb);
6111: $r->print(&scantron_form_start().$default_form_data);
6112: if ( $env{'form.selectpage'} eq '' ||
6113: $env{'form.scantron_selectfile'} eq '' ||
6114: $env{'form.scantron_format'} eq '' ) {
6115: $r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
6116: if ( $env{'form.selectpage'} eq '') {
6117: $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
6118: }
6119: if ( $env{'form.scantron_selectfile'} eq '') {
6120: $r->print('<p><span class="LC_error">'.&mt('You have not selected a file that contains the student\'s response data.').'</span></p>');
6121: }
6122: if ( $env{'form.scantron_format'} eq '') {
6123: $r->print('<p><span class="LC_error">'.&mt('You have not selected a the format of the student\'s response data.').'</span></p>');
6124: }
6125: } else {
6126: my $warning=&scantron_warning_screen('Grading: Validate Records');
6127: $r->print('
6128: '.$warning.'
6129: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
6130: <input type="hidden" name="command" value="scantron_validate" />
6131: ');
6132: }
6133: $r->print("</form><br />".&show_grading_menu_form($symb));
6134: return '';
6135: }
6136:
6137: =pod
6138:
6139: =item scantron_form_start
6140:
6141: html hidden input for remembering all selected grading options
6142:
6143: =cut
6144:
6145: sub scantron_form_start {
6146: my ($max_bubble)=@_;
6147: my $result= <<SCANTRONFORM;
6148: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
6149: <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
6150: <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
6151: <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
6152: <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
6153: <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
6154: <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
6155: <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
6156: <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
6157: <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
6158: SCANTRONFORM
6159:
6160: my $line = 0;
6161: while (defined($env{"form.scantron.bubblelines.$line"})) {
6162: my $chunk =
6163: '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
6164: $chunk .=
6165: '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
6166: $chunk .=
6167: '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
6168: $chunk .=
6169: '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
6170: $result .= $chunk;
6171: $line++;
6172: }
6173: return $result;
6174: }
6175:
6176: =pod
6177:
6178: =item scantron_validate_file
6179:
6180: Dispatch routine for doing validation of a bubble sheet data file.
6181:
6182: Also processes any necessary information resets that need to
6183: occur before validation begins (ignore previous corrections,
6184: restarting the skipped records processing)
6185:
6186: =cut
6187:
6188: sub scantron_validate_file {
6189: my ($r) = @_;
6190: my ($symb)=&get_symb($r);
6191: if (!$symb) {return '';}
6192: my $default_form_data=&defaultFormData($symb);
6193:
6194: # do the detection of only doing skipped records first befroe we delete
6195: # them when doing the corrections reset
6196: if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
6197: &reset_skipping_status();
6198: }
6199: if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
6200: &remember_current_skipped();
6201: $env{'form.scantron_options_redo'}='redo_skipped_ready';
6202: }
6203:
6204: if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
6205: &check_for_error($r,&scantron_remove_file('corrected'));
6206: &check_for_error($r,&scantron_remove_file('skipped'));
6207: &check_for_error($r,&scantron_remove_scan_data());
6208: $env{'form.scantron_options_ignore'}='done';
6209: }
6210:
6211: if ($env{'form.scantron_corrections'}) {
6212: &scantron_process_corrections($r);
6213: }
6214: $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
6215: #get the student pick code ready
6216: $r->print(&Apache::loncommon::studentbrowser_javascript());
6217: my $max_bubble=&scantron_get_maxbubble();
6218: my $result=&scantron_form_start($max_bubble).$default_form_data;
6219: $r->print($result);
6220:
6221: my @validate_phases=( 'sequence',
6222: 'ID',
6223: 'CODE',
6224: 'doublebubble',
6225: 'missingbubbles');
6226: if (!$env{'form.validatepass'}) {
6227: $env{'form.validatepass'} = 0;
6228: }
6229: my $currentphase=$env{'form.validatepass'};
6230:
6231:
6232: my $stop=0;
6233: while (!$stop && $currentphase < scalar(@validate_phases)) {
6234: $r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
6235: $r->rflush();
6236: my $which="scantron_validate_".$validate_phases[$currentphase];
6237: {
6238: no strict 'refs';
6239: ($stop,$currentphase)=&$which($r,$currentphase);
6240: }
6241: }
6242: if (!$stop) {
6243: my $warning=&scantron_warning_screen('Start Grading');
6244: $r->print(&mt('Validation process complete.').'<br />'.
6245: $warning.
6246: &mt('Perform verification for each student after storage of submissions?').
6247: ' <span class="LC_nobreak"><label>'.
6248: '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
6249: (' 'x3).'<label>'.
6250: '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
6251: '</label></span><br />'.
6252: &mt('Grading will take longer if you use verification.').'<br />'.
6253: &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
6254: '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
6255: '<input type="hidden" name="command" value="scantron_process" />'."\n");
6256: } else {
6257: $r->print('<input type="hidden" name="command" value="scantron_validate" />');
6258: $r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
6259: }
6260: if ($stop) {
6261: if ($validate_phases[$currentphase] eq 'sequence') {
6262: $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' → " />');
6263: $r->print(' '.&mt('this error').' <br />');
6264:
6265: $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
6266: } else {
6267: if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
6268: $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' →" onclick="javascript:verify_bubble_radio(this.form)" />');
6269: } else {
6270: $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' →" />');
6271: }
6272: $r->print(' '.&mt('using corrected info').' <br />');
6273: $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
6274: $r->print(" ".&mt("this scanline saving it for later."));
6275: }
6276: }
6277: $r->print(" </form><br />".&show_grading_menu_form($symb));
6278: return '';
6279: }
6280:
6281:
6282: =pod
6283:
6284: =item scantron_remove_file
6285:
6286: Removes the requested bubble sheet data file, makes sure that
6287: scantron_original_<filename> is never removed
6288:
6289:
6290: =cut
6291:
6292: sub scantron_remove_file {
6293: my ($which)=@_;
6294: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6295: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6296: my $file='scantron_';
6297: if ($which eq 'corrected' || $which eq 'skipped') {
6298: $file.=$which.'_';
6299: } else {
6300: return 'refused';
6301: }
6302: $file.=$env{'form.scantron_selectfile'};
6303: return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
6304: }
6305:
6306:
6307: =pod
6308:
6309: =item scantron_remove_scan_data
6310:
6311: Removes all scan_data correction for the requested bubble sheet
6312: data file. (In the case that both the are doing skipped records we need
6313: to remember the old skipped lines for the time being so that element
6314: persists for a while.)
6315:
6316: =cut
6317:
6318: sub scantron_remove_scan_data {
6319: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6320: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6321: my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
6322: my @todelete;
6323: my $filename=$env{'form.scantron_selectfile'};
6324: foreach my $key (@keys) {
6325: if ($key=~/^\Q$filename\E_/) {
6326: if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
6327: $key=~/remember_skipping/) {
6328: next;
6329: }
6330: push(@todelete,$key);
6331: }
6332: }
6333: my $result;
6334: if (@todelete) {
6335: $result = &Apache::lonnet::del('nohist_scantrondata',
6336: \@todelete,$cdom,$cname);
6337: } else {
6338: $result = 'ok';
6339: }
6340: return $result;
6341: }
6342:
6343:
6344: =pod
6345:
6346: =item scantron_getfile
6347:
6348: Fetches the requested bubble sheet data file (all 3 versions), and
6349: the scan_data hash
6350:
6351: Arguments:
6352: None
6353:
6354: Returns:
6355: 2 hash references
6356:
6357: - first one has
6358: orig -
6359: corrected -
6360: skipped - each of which points to an array ref of the specified
6361: file broken up into individual lines
6362: count - number of scanlines
6363:
6364: - second is the scan_data hash possible keys are
6365: ($number refers to scanline numbered $number and thus the key affects
6366: only that scanline
6367: $bubline refers to the specific bubble line element and the aspects
6368: refers to that specific bubble line element)
6369:
6370: $number.user - username:domain to use
6371: $number.CODE_ignore_dup
6372: - ignore the duplicate CODE error
6373: $number.useCODE
6374: - use the CODE in the scanline as is
6375: $number.no_bubble.$bubline
6376: - it is valid that there is no bubbled in bubble
6377: at $number $bubline
6378: remember_skipping
6379: - a frozen hash containing keys of $number and values
6380: of either
6381: 1 - we are on a 'do skipped records pass' and plan
6382: on processing this line
6383: 2 - we are on a 'do skipped records pass' and this
6384: scanline has been marked to skip yet again
6385:
6386: =cut
6387:
6388: sub scantron_getfile {
6389: #FIXME really would prefer a scantron directory
6390: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6391: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6392: my $lines;
6393: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
6394: 'scantron_orig_'.$env{'form.scantron_selectfile'});
6395: my %scanlines;
6396: $scanlines{'orig'}=[(split("\n",$lines,-1))];
6397: my $temp=$scanlines{'orig'};
6398: $scanlines{'count'}=$#$temp;
6399:
6400: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
6401: 'scantron_corrected_'.$env{'form.scantron_selectfile'});
6402: if ($lines eq '-1') {
6403: $scanlines{'corrected'}=[];
6404: } else {
6405: $scanlines{'corrected'}=[(split("\n",$lines,-1))];
6406: }
6407: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
6408: 'scantron_skipped_'.$env{'form.scantron_selectfile'});
6409: if ($lines eq '-1') {
6410: $scanlines{'skipped'}=[];
6411: } else {
6412: $scanlines{'skipped'}=[(split("\n",$lines,-1))];
6413: }
6414: my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
6415: if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
6416: my %scan_data = @tmp;
6417: return (\%scanlines,\%scan_data);
6418: }
6419:
6420: =pod
6421:
6422: =item lonnet_putfile
6423:
6424: Wrapper routine to call &Apache::lonnet::finishuserfileupload
6425:
6426: Arguments:
6427: $contents - data to store
6428: $filename - filename to store $contents into
6429:
6430: Returns:
6431: result value from &Apache::lonnet::finishuserfileupload
6432:
6433: =cut
6434:
6435: sub lonnet_putfile {
6436: my ($contents,$filename)=@_;
6437: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
6438: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6439: $env{'form.sillywaytopassafilearound'}=$contents;
6440: &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
6441:
6442: }
6443:
6444: =pod
6445:
6446: =item scantron_putfile
6447:
6448: Stores the current version of the bubble sheet data files, and the
6449: scan_data hash. (Does not modify the original version only the
6450: corrected and skipped versions.
6451:
6452: Arguments:
6453: $scanlines - hash ref that looks like the first return value from
6454: &scantron_getfile()
6455: $scan_data - hash ref that looks like the second return value from
6456: &scantron_getfile()
6457:
6458: =cut
6459:
6460: sub scantron_putfile {
6461: my ($scanlines,$scan_data) = @_;
6462: #FIXME really would prefer a scantron directory
6463: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6464: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6465: if ($scanlines) {
6466: my $prefix='scantron_';
6467: # no need to update orig, shouldn't change
6468: # &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
6469: # $env{'form.scantron_selectfile'});
6470: &lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
6471: $prefix.'corrected_'.
6472: $env{'form.scantron_selectfile'});
6473: &lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
6474: $prefix.'skipped_'.
6475: $env{'form.scantron_selectfile'});
6476: }
6477: &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
6478: }
6479:
6480: =pod
6481:
6482: =item scantron_get_line
6483:
6484: Returns the correct version of the scanline
6485:
6486: Arguments:
6487: $scanlines - hash ref that looks like the first return value from
6488: &scantron_getfile()
6489: $scan_data - hash ref that looks like the second return value from
6490: &scantron_getfile()
6491: $i - number of the requested line (starts at 0)
6492:
6493: Returns:
6494: A scanline, (either the original or the corrected one if it
6495: exists), or undef if the requested scanline should be
6496: skipped. (Either because it's an skipped scanline, or it's an
6497: unskipped scanline and we are not doing a 'do skipped scanlines'
6498: pass.
6499:
6500: =cut
6501:
6502: sub scantron_get_line {
6503: my ($scanlines,$scan_data,$i)=@_;
6504: if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
6505: #if ($scanlines->{'skipped'}[$i]) { return undef; }
6506: if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
6507: return $scanlines->{'orig'}[$i];
6508: }
6509:
6510: =pod
6511:
6512: =item scantron_todo_count
6513:
6514: Counts the number of scanlines that need processing.
6515:
6516: Arguments:
6517: $scanlines - hash ref that looks like the first return value from
6518: &scantron_getfile()
6519: $scan_data - hash ref that looks like the second return value from
6520: &scantron_getfile()
6521:
6522: Returns:
6523: $count - number of scanlines to process
6524:
6525: =cut
6526:
6527: sub get_todo_count {
6528: my ($scanlines,$scan_data)=@_;
6529: my $count=0;
6530: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6531: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6532: if ($line=~/^[\s\cz]*$/) { next; }
6533: $count++;
6534: }
6535: return $count;
6536: }
6537:
6538: =pod
6539:
6540: =item scantron_put_line
6541:
6542: Updates the 'corrected' or 'skipped' versions of the bubble sheet
6543: data file.
6544:
6545: Arguments:
6546: $scanlines - hash ref that looks like the first return value from
6547: &scantron_getfile()
6548: $scan_data - hash ref that looks like the second return value from
6549: &scantron_getfile()
6550: $i - line number to update
6551: $newline - contents of the updated scanline
6552: $skip - if true make the line for skipping and update the
6553: 'skipped' file
6554:
6555: =cut
6556:
6557: sub scantron_put_line {
6558: my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
6559: if ($skip) {
6560: $scanlines->{'skipped'}[$i]=$newline;
6561: &start_skipping($scan_data,$i);
6562: return;
6563: }
6564: $scanlines->{'corrected'}[$i]=$newline;
6565: }
6566:
6567: =pod
6568:
6569: =item scantron_clear_skip
6570:
6571: Remove a line from the 'skipped' file
6572:
6573: Arguments:
6574: $scanlines - hash ref that looks like the first return value from
6575: &scantron_getfile()
6576: $scan_data - hash ref that looks like the second return value from
6577: &scantron_getfile()
6578: $i - line number to update
6579:
6580: =cut
6581:
6582: sub scantron_clear_skip {
6583: my ($scanlines,$scan_data,$i)=@_;
6584: if (exists($scanlines->{'skipped'}[$i])) {
6585: undef($scanlines->{'skipped'}[$i]);
6586: return 1;
6587: }
6588: return 0;
6589: }
6590:
6591: =pod
6592:
6593: =item scantron_filter_not_exam
6594:
6595: Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
6596: filter out resources that are not marked as 'exam' mode
6597:
6598: =cut
6599:
6600: sub scantron_filter_not_exam {
6601: my ($curres)=@_;
6602:
6603: if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
6604: # if the user has asked to not have either hidden
6605: # or 'randomout' controlled resources to be graded
6606: # don't include them
6607: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
6608: && $curres->randomout) {
6609: return 0;
6610: }
6611: return 1;
6612: }
6613: return 0;
6614: }
6615:
6616: =pod
6617:
6618: =item scantron_validate_sequence
6619:
6620: Validates the selected sequence, checking for resource that are
6621: not set to exam mode.
6622:
6623: =cut
6624:
6625: sub scantron_validate_sequence {
6626: my ($r,$currentphase) = @_;
6627:
6628: my $navmap=Apache::lonnavmaps::navmap->new();
6629: my (undef,undef,$sequence)=
6630: &Apache::lonnet::decode_symb($env{'form.selectpage'});
6631:
6632: my $map=$navmap->getResourceByUrl($sequence);
6633:
6634: $r->print('<input type="hidden" name="validate_sequence_exam"
6635: value="ignore" />');
6636: if ($env{'form.validate_sequence_exam'} ne 'ignore') {
6637: my @resources=
6638: $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
6639: if (@resources) {
6640: $r->print("<p>".&mt('Some resources in the sequence currently are not set to exam mode. Grading these resources currently may not work correctly.')."</p>");
6641: return (1,$currentphase);
6642: }
6643: }
6644:
6645: return (0,$currentphase+1);
6646: }
6647:
6648:
6649:
6650: sub scantron_validate_ID {
6651: my ($r,$currentphase) = @_;
6652:
6653: #get student info
6654: my $classlist=&Apache::loncoursedata::get_classlist();
6655: my %idmap=&username_to_idmap($classlist);
6656:
6657: #get scantron line setup
6658: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6659: my ($scanlines,$scan_data)=&scantron_getfile();
6660:
6661: &scantron_get_maxbubble(); # parse needs the bubble_lines.. array.
6662:
6663: my %found=('ids'=>{},'usernames'=>{});
6664: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6665: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6666: if ($line=~/^[\s\cz]*$/) { next; }
6667: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6668: $scan_data);
6669: my $id=$$scan_record{'scantron.ID'};
6670: my $found;
6671: foreach my $checkid (keys(%idmap)) {
6672: if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
6673: }
6674: if ($found) {
6675: my $username=$idmap{$found};
6676: if ($found{'ids'}{$found}) {
6677: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6678: $line,'duplicateID',$found);
6679: return(1,$currentphase);
6680: } elsif ($found{'usernames'}{$username}) {
6681: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6682: $line,'duplicateID',$username);
6683: return(1,$currentphase);
6684: }
6685: #FIXME store away line we previously saw the ID on to use above
6686: $found{'ids'}{$found}++;
6687: $found{'usernames'}{$username}++;
6688: } else {
6689: if ($id =~ /^\s*$/) {
6690: my $username=&scan_data($scan_data,"$i.user");
6691: if (defined($username) && $found{'usernames'}{$username}) {
6692: &scantron_get_correction($r,$i,$scan_record,
6693: \%scantron_config,
6694: $line,'duplicateID',$username);
6695: return(1,$currentphase);
6696: } elsif (!defined($username)) {
6697: &scantron_get_correction($r,$i,$scan_record,
6698: \%scantron_config,
6699: $line,'incorrectID');
6700: return(1,$currentphase);
6701: }
6702: $found{'usernames'}{$username}++;
6703: } else {
6704: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6705: $line,'incorrectID');
6706: return(1,$currentphase);
6707: }
6708: }
6709: }
6710:
6711: return (0,$currentphase+1);
6712: }
6713:
6714:
6715: sub scantron_get_correction {
6716: my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
6717: #FIXME in the case of a duplicated ID the previous line, probably need
6718: #to show both the current line and the previous one and allow skipping
6719: #the previous one or the current one
6720:
6721: if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
6722: $r->print("<p>".&mt("<b>An error was detected ($error)</b>".
6723: " for PaperID <tt>[_1]</tt>",
6724: $$scan_record{'scantron.PaperID'})."</p> \n");
6725: } else {
6726: $r->print("<p>".&mt("<b>An error was detected ($error)</b>".
6727: " in scanline [_1] <pre>[_2]</pre>",
6728: $i,$line)."</p> \n");
6729: }
6730: my $message="<p>".&mt("The ID on the form is <tt>[_1]</tt><br />".
6731: "The name on the paper is [_2],[_3]",
6732: $$scan_record{'scantron.ID'},
6733: $$scan_record{'scantron.LastName'},
6734: $$scan_record{'scantron.FirstName'})."</p>";
6735:
6736: $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
6737: $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
6738: # Array populated for doublebubble or
6739: my @lines_to_correct; # missingbubble errors to build javascript
6740: # to validate radio button checking
6741:
6742: if ($error =~ /ID$/) {
6743: if ($error eq 'incorrectID') {
6744: $r->print("<p>".&mt("The encoded ID is not in the classlist").
6745: "</p>\n");
6746: } elsif ($error eq 'duplicateID') {
6747: $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
6748: }
6749: $r->print($message);
6750: $r->print("<p>".&mt("How should I handle this?")." <br /> \n");
6751: $r->print("\n<ul><li> ");
6752: #FIXME it would be nice if this sent back the user ID and
6753: #could do partial userID matches
6754: $r->print(&Apache::loncommon::selectstudent_link('scantronupload',
6755: 'scantron_username','scantron_domain'));
6756: $r->print(": <input type='text' name='scantron_username' value='' />");
6757: $r->print("\n@".
6758: &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
6759:
6760: $r->print('</li>');
6761: } elsif ($error =~ /CODE$/) {
6762: if ($error eq 'incorrectCODE') {
6763: $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
6764: } elsif ($error eq 'duplicateCODE') {
6765: $r->print("<p>".&mt("The encoded CODE has also been used by a previous paper [_1], and CODEs are supposed to be unique.",join(', ',@{$arg}))."</p>\n");
6766: }
6767: $r->print("<p>".&mt("The CODE on the form is <tt>'[_1]'</tt>",
6768: $$scan_record{'scantron.CODE'})."<br />\n");
6769: $r->print($message);
6770: $r->print("<p>".&mt("How should I handle this?")." <br /> \n");
6771: $r->print("\n<br /> ");
6772: my $i=0;
6773: if ($error eq 'incorrectCODE'
6774: && $$scan_record{'scantron.CODE'}=~/\S/ ) {
6775: my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
6776: if ($closest > 0) {
6777: foreach my $testcode (@{$closest}) {
6778: my $checked='';
6779: if (!$i) { $checked=' checked="checked"'; }
6780: $r->print("
6781: <label>
6782: <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
6783: ".&mt("Use the similar CODE [_1] instead.",
6784: "<b><tt>".$testcode."</tt></b>")."
6785: </label>
6786: <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
6787: $r->print("\n<br />");
6788: $i++;
6789: }
6790: }
6791: }
6792: if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
6793: my $checked; if (!$i) { $checked=' checked="checked"'; }
6794: $r->print("
6795: <label>
6796: <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
6797: ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
6798: "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
6799: </label>");
6800: $r->print("\n<br />");
6801: }
6802:
6803: $r->print(<<ENDSCRIPT);
6804: <script type="text/javascript">
6805: function change_radio(field) {
6806: var slct=document.scantronupload.scantron_CODE_resolution;
6807: var i;
6808: for (i=0;i<slct.length;i++) {
6809: if (slct[i].value==field) { slct[i].checked=true; }
6810: }
6811: }
6812: </script>
6813: ENDSCRIPT
6814: my $href="/adm/pickcode?".
6815: "form=".&escape("scantronupload").
6816: "&scantron_format=".&escape($env{'form.scantron_format'}).
6817: "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
6818: "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
6819: "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
6820: if ($env{'form.scantron_CODElist'} =~ /\S/) {
6821: $r->print("
6822: <label>
6823: <input type='radio' name='scantron_CODE_resolution' value='use_found' />
6824: ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
6825: "<a target='_blank' href='$href'>","</a>")."
6826: </label>
6827: ".&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\')" />'));
6828: $r->print("\n<br />");
6829: }
6830: $r->print("
6831: <label>
6832: <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
6833: ".&mt("Use [_1] as the CODE.",
6834: "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
6835: $r->print("\n<br /><br />");
6836: } elsif ($error eq 'doublebubble') {
6837: $r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
6838:
6839: # The form field scantron_questions is acutally a list of line numbers.
6840: # represented by this form so:
6841:
6842: my $line_list = &questions_to_line_list($arg);
6843:
6844: $r->print('<input type="hidden" name="scantron_questions" value="'.
6845: $line_list.'" />');
6846: $r->print($message);
6847: $r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
6848: foreach my $question (@{$arg}) {
6849: my @linenums = &prompt_for_corrections($r,$question,$scan_config,
6850: $scan_record, $error);
6851: push(@lines_to_correct,@linenums);
6852: }
6853: $r->print(&verify_bubbles_checked(@lines_to_correct));
6854: } elsif ($error eq 'missingbubble') {
6855: $r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
6856: $r->print($message);
6857: $r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
6858: $r->print(&mt("Some questions have no scanned bubbles.")."\n");
6859:
6860: # The form field scantron_questions is actually a list of line numbers not
6861: # a list of question numbers. Therefore:
6862: #
6863:
6864: my $line_list = &questions_to_line_list($arg);
6865:
6866: $r->print('<input type="hidden" name="scantron_questions" value="'.
6867: $line_list.'" />');
6868: foreach my $question (@{$arg}) {
6869: my @linenums = &prompt_for_corrections($r,$question,$scan_config,
6870: $scan_record, $error);
6871: push(@lines_to_correct,@linenums);
6872: }
6873: $r->print(&verify_bubbles_checked(@lines_to_correct));
6874: } else {
6875: $r->print("\n<ul>");
6876: }
6877: $r->print("\n</li></ul>");
6878: }
6879:
6880: sub verify_bubbles_checked {
6881: my (@ansnums) = @_;
6882: my $ansnumstr = join('","',@ansnums);
6883: my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
6884: my $output = (<<ENDSCRIPT);
6885: <script type="text/javascript">
6886: function verify_bubble_radio(form) {
6887: var ansnumArray = new Array ("$ansnumstr");
6888: var need_bubble_count = 0;
6889: for (var i=0; i<ansnumArray.length; i++) {
6890: if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
6891: var bubble_picked = 0;
6892: for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
6893: if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
6894: bubble_picked = 1;
6895: }
6896: }
6897: if (bubble_picked == 0) {
6898: need_bubble_count ++;
6899: }
6900: }
6901: }
6902: if (need_bubble_count) {
6903: alert("$warning");
6904: return;
6905: }
6906: form.submit();
6907: }
6908: </script>
6909: ENDSCRIPT
6910: return $output;
6911: }
6912:
6913: =pod
6914:
6915: =item questions_to_line_list
6916:
6917: Converts a list of questions into a string of comma separated
6918: line numbers in the answer sheet used by the questions. This is
6919: used to fill in the scantron_questions form field.
6920:
6921: Arguments:
6922: questions - Reference to an array of questions.
6923:
6924: =cut
6925:
6926:
6927: sub questions_to_line_list {
6928: my ($questions) = @_;
6929: my @lines;
6930:
6931: foreach my $item (@{$questions}) {
6932: my $question = $item;
6933: my ($first,$count,$last);
6934: if ($item =~ /^(\d+)\.(\d+)$/) {
6935: $question = $1;
6936: my $subquestion = $2;
6937: $first = $first_bubble_line{$question-1} + 1;
6938: my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
6939: my $subcount = 1;
6940: while ($subcount<$subquestion) {
6941: $first += $subans[$subcount-1];
6942: $subcount ++;
6943: }
6944: $count = $subans[$subquestion-1];
6945: } else {
6946: $first = $first_bubble_line{$question-1} + 1;
6947: $count = $bubble_lines_per_response{$question-1};
6948: }
6949: $last = $first+$count-1;
6950: push(@lines, ($first..$last));
6951: }
6952: return join(',', @lines);
6953: }
6954:
6955: =pod
6956:
6957: =item prompt_for_corrections
6958:
6959: Prompts for a potentially multiline correction to the
6960: user's bubbling (factors out common code from scantron_get_correction
6961: for multi and missing bubble cases).
6962:
6963: Arguments:
6964: $r - Apache request object.
6965: $question - The question number to prompt for.
6966: $scan_config - The scantron file configuration hash.
6967: $scan_record - Reference to the hash that has the the parsed scanlines.
6968: $error - Type of error
6969:
6970: Implicit inputs:
6971: %bubble_lines_per_response - Starting line numbers for each question.
6972: Numbered from 0 (but question numbers are from
6973: 1.
6974: %first_bubble_line - Starting bubble line for each question.
6975: %subdivided_bubble_lines - optionresponse, matchresponse and rankresponse
6976: type problems render as separate sub-questions,
6977: in exam mode. This hash contains a
6978: comma-separated list of the lines per
6979: sub-question.
6980: %responsetype_per_response - essayresponse, formularesponse,
6981: stringresponse, imageresponse, reactionresponse,
6982: and organicresponse type problem parts can have
6983: multiple lines per response if the weight
6984: assigned exceeds 10. In this case, only
6985: one bubble per line is permitted, but more
6986: than one line might contain bubbles, e.g.
6987: bubbling of: line 1 - J, line 2 - J,
6988: line 3 - B would assign 22 points.
6989:
6990: =cut
6991:
6992: sub prompt_for_corrections {
6993: my ($r, $question, $scan_config, $scan_record, $error) = @_;
6994: my ($current_line,$lines);
6995: my @linenums;
6996: my $questionnum = $question;
6997: if ($question =~ /^(\d+)\.(\d+)$/) {
6998: $question = $1;
6999: $current_line = $first_bubble_line{$question-1} + 1 ;
7000: my $subquestion = $2;
7001: my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
7002: my $subcount = 1;
7003: while ($subcount<$subquestion) {
7004: $current_line += $subans[$subcount-1];
7005: $subcount ++;
7006: }
7007: $lines = $subans[$subquestion-1];
7008: } else {
7009: $current_line = $first_bubble_line{$question-1} + 1 ;
7010: $lines = $bubble_lines_per_response{$question-1};
7011: }
7012: if ($lines > 1) {
7013: $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
7014: if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
7015: ($responsetype_per_response{$question-1} eq 'formularesponse') ||
7016: ($responsetype_per_response{$question-1} eq 'stringresponse') ||
7017: ($responsetype_per_response{$question-1} eq 'imageresponse') ||
7018: ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
7019: ($responsetype_per_response{$question-1} eq 'organicresponse')) {
7020: $r->print(&mt("Although this particular question type requires handgrading, the instructions for this question in the exam directed students to leave [quant,_1,line] blank on their bubblesheets.",$lines).'<br /><br />'.&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.').'<br />'.&mt('The score for this question will be a sum of the numeric values for the selected bubbles from each line, where A=1 point, B=2 points etc.').'<br />'.&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.").'<br /><br />');
7021: } else {
7022: $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
7023: }
7024: }
7025: for (my $i =0; $i < $lines; $i++) {
7026: my $selected = $$scan_record{"scantron.$current_line.answer"};
7027: &scantron_bubble_selector($r,$scan_config,$current_line,
7028: $questionnum,$error,split('', $selected));
7029: push(@linenums,$current_line);
7030: $current_line++;
7031: }
7032: if ($lines > 1) {
7033: $r->print("<hr /><br />");
7034: }
7035: return @linenums;
7036: }
7037:
7038: =pod
7039:
7040: =item scantron_bubble_selector
7041:
7042: Generates the html radiobuttons to correct a single bubble line
7043: possibly showing the existing the selected bubbles if known
7044:
7045: Arguments:
7046: $r - Apache request object
7047: $scan_config - hash from &get_scantron_config()
7048: $line - Number of the line being displayed.
7049: $questionnum - Question number (may include subquestion)
7050: $error - Type of error.
7051: @selected - Array of bubbles picked on this line.
7052:
7053: =cut
7054:
7055: sub scantron_bubble_selector {
7056: my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
7057: my $max=$$scan_config{'Qlength'};
7058:
7059: my $scmode=$$scan_config{'Qon'};
7060: if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }
7061:
7062: my @alphabet=('A'..'Z');
7063: $r->print(&Apache::loncommon::start_data_table().
7064: &Apache::loncommon::start_data_table_row());
7065: $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
7066: for (my $i=0;$i<$max+1;$i++) {
7067: $r->print("\n".'<td align="center">');
7068: if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
7069: else { $r->print(' '); }
7070: $r->print('</td>');
7071: }
7072: $r->print(&Apache::loncommon::end_data_table_row().
7073: &Apache::loncommon::start_data_table_row());
7074: for (my $i=0;$i<$max;$i++) {
7075: $r->print("\n".
7076: '<td><label><input type="radio" name="scantron_correct_Q_'.
7077: $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
7078: }
7079: my $nobub_checked = ' ';
7080: if ($error eq 'missingbubble') {
7081: $nobub_checked = ' checked = "checked" ';
7082: }
7083: $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
7084: $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
7085: '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
7086: $line.'" value="'.$questionnum.'" /></td>');
7087: $r->print(&Apache::loncommon::end_data_table_row().
7088: &Apache::loncommon::end_data_table());
7089: }
7090:
7091: =pod
7092:
7093: =item num_matches
7094:
7095: Counts the number of characters that are the same between the two arguments.
7096:
7097: Arguments:
7098: $orig - CODE from the scanline
7099: $code - CODE to match against
7100:
7101: Returns:
7102: $count - integer count of the number of same characters between the
7103: two arguments
7104:
7105: =cut
7106:
7107: sub num_matches {
7108: my ($orig,$code) = @_;
7109: my @code=split(//,$code);
7110: my @orig=split(//,$orig);
7111: my $same=0;
7112: for (my $i=0;$i<scalar(@code);$i++) {
7113: if ($code[$i] eq $orig[$i]) { $same++; }
7114: }
7115: return $same;
7116: }
7117:
7118: =pod
7119:
7120: =item scantron_get_closely_matching_CODEs
7121:
7122: Cycles through all CODEs and finds the set that has the greatest
7123: number of same characters as the provided CODE
7124:
7125: Arguments:
7126: $allcodes - hash ref returned by &get_codes()
7127: $CODE - CODE from the current scanline
7128:
7129: Returns:
7130: 2 element list
7131: - first elements is number of how closely matching the best fit is
7132: (5 means best set has 5 matching characters)
7133: - second element is an arrary ref containing the set of valid CODEs
7134: that best fit the passed in CODE
7135:
7136: =cut
7137:
7138: sub scantron_get_closely_matching_CODEs {
7139: my ($allcodes,$CODE)=@_;
7140: my @CODEs;
7141: foreach my $testcode (sort(keys(%{$allcodes}))) {
7142: push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
7143: }
7144:
7145: return ($#CODEs,$CODEs[-1]);
7146: }
7147:
7148: =pod
7149:
7150: =item get_codes
7151:
7152: Builds a hash which has keys of all of the valid CODEs from the selected
7153: set of remembered CODEs.
7154:
7155: Arguments:
7156: $old_name - name of the set of remembered CODEs
7157: $cdom - domain of the course
7158: $cnum - internal course name
7159:
7160: Returns:
7161: %allcodes - keys are the valid CODEs, values are all 1
7162:
7163: =cut
7164:
7165: sub get_codes {
7166: my ($old_name, $cdom, $cnum) = @_;
7167: if (!$old_name) {
7168: $old_name=$env{'form.scantron_CODElist'};
7169: }
7170: if (!$cdom) {
7171: $cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
7172: }
7173: if (!$cnum) {
7174: $cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
7175: }
7176: my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
7177: $cdom,$cnum);
7178: my %allcodes;
7179: if ($result{"type\0$old_name"} eq 'number') {
7180: %allcodes=map {($_,1)} split(',',$result{$old_name});
7181: } else {
7182: %allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
7183: }
7184: return %allcodes;
7185: }
7186:
7187: =pod
7188:
7189: =item scantron_validate_CODE
7190:
7191: Validates all scanlines in the selected file to not have any
7192: invalid or underspecified CODEs and that none of the codes are
7193: duplicated if this was requested.
7194:
7195: =cut
7196:
7197: sub scantron_validate_CODE {
7198: my ($r,$currentphase) = @_;
7199: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7200: if ($scantron_config{'CODElocation'} &&
7201: $scantron_config{'CODEstart'} &&
7202: $scantron_config{'CODElength'}) {
7203: if (!defined($env{'form.scantron_CODElist'})) {
7204: &FIXME_blow_up()
7205: }
7206: } else {
7207: return (0,$currentphase+1);
7208: }
7209:
7210: my %usedCODEs;
7211:
7212: my %allcodes=&get_codes();
7213:
7214: &scantron_get_maxbubble(); # parse needs the lines per response array.
7215:
7216: my ($scanlines,$scan_data)=&scantron_getfile();
7217: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7218: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7219: if ($line=~/^[\s\cz]*$/) { next; }
7220: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7221: $scan_data);
7222: my $CODE=$$scan_record{'scantron.CODE'};
7223: my $error=0;
7224: if (!&Apache::lonnet::validCODE($CODE)) {
7225: &scantron_get_correction($r,$i,$scan_record,
7226: \%scantron_config,
7227: $line,'incorrectCODE',\%allcodes);
7228: return(1,$currentphase);
7229: }
7230: if (%allcodes && !exists($allcodes{$CODE})
7231: && !$$scan_record{'scantron.useCODE'}) {
7232: &scantron_get_correction($r,$i,$scan_record,
7233: \%scantron_config,
7234: $line,'incorrectCODE',\%allcodes);
7235: return(1,$currentphase);
7236: }
7237: if (exists($usedCODEs{$CODE})
7238: && $env{'form.scantron_CODEunique'} eq 'yes'
7239: && !$$scan_record{'scantron.CODE_ignore_dup'}) {
7240: &scantron_get_correction($r,$i,$scan_record,
7241: \%scantron_config,
7242: $line,'duplicateCODE',$usedCODEs{$CODE});
7243: return(1,$currentphase);
7244: }
7245: push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
7246: }
7247: return (0,$currentphase+1);
7248: }
7249:
7250: =pod
7251:
7252: =item scantron_validate_doublebubble
7253:
7254: Validates all scanlines in the selected file to not have any
7255: bubble lines with multiple bubbles marked.
7256:
7257: =cut
7258:
7259: sub scantron_validate_doublebubble {
7260: my ($r,$currentphase) = @_;
7261: #get student info
7262: my $classlist=&Apache::loncoursedata::get_classlist();
7263: my %idmap=&username_to_idmap($classlist);
7264:
7265: #get scantron line setup
7266: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7267: my ($scanlines,$scan_data)=&scantron_getfile();
7268: &scantron_get_maxbubble(); # parse needs the bubble line array.
7269:
7270: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7271: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7272: if ($line=~/^[\s\cz]*$/) { next; }
7273: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7274: $scan_data);
7275: if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
7276: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
7277: 'doublebubble',
7278: $$scan_record{'scantron.doubleerror'});
7279: return (1,$currentphase);
7280: }
7281: return (0,$currentphase+1);
7282: }
7283:
7284:
7285: sub scantron_get_maxbubble {
7286: if (defined($env{'form.scantron_maxbubble'}) &&
7287: $env{'form.scantron_maxbubble'}) {
7288: &restore_bubble_lines();
7289: return $env{'form.scantron_maxbubble'};
7290: }
7291:
7292: my (undef, undef, $sequence) =
7293: &Apache::lonnet::decode_symb($env{'form.selectpage'});
7294:
7295: my $navmap=Apache::lonnavmaps::navmap->new();
7296: my $map=$navmap->getResourceByUrl($sequence);
7297: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
7298:
7299: &Apache::lonxml::clear_problem_counter();
7300:
7301: my $uname = $env{'user.name'};
7302: my $udom = $env{'user.domain'};
7303: my $cid = $env{'request.course.id'};
7304: my $total_lines = 0;
7305: %bubble_lines_per_response = ();
7306: %first_bubble_line = ();
7307: %subdivided_bubble_lines = ();
7308: %responsetype_per_response = ();
7309:
7310: my $response_number = 0;
7311: my $bubble_line = 0;
7312: foreach my $resource (@resources) {
7313: my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
7314: if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
7315: foreach my $part_id (@{$parts}) {
7316: my $lines;
7317:
7318: # TODO - make this a persistent hash not an array.
7319:
7320: # optionresponse, matchresponse and rankresponse type items
7321: # render as separate sub-questions in exam mode.
7322: if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
7323: ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
7324: ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
7325: my ($numbub,$numshown);
7326: if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
7327: if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
7328: $numbub = scalar(@{$analysis->{$part_id.'.options'}});
7329: }
7330: } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
7331: if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
7332: $numbub = scalar(@{$analysis->{$part_id.'.items'}});
7333: }
7334: } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
7335: if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
7336: $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
7337: }
7338: }
7339: if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
7340: $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
7341: }
7342: my $bubbles_per_line = 10;
7343: my $inner_bubble_lines = int($numbub/$bubbles_per_line);
7344: if (($numbub % $bubbles_per_line) != 0) {
7345: $inner_bubble_lines++;
7346: }
7347: for (my $i=0; $i<$numshown; $i++) {
7348: $subdivided_bubble_lines{$response_number} .=
7349: $inner_bubble_lines.',';
7350: }
7351: $subdivided_bubble_lines{$response_number} =~ s/,$//;
7352: $lines = $numshown * $inner_bubble_lines;
7353: } else {
7354: $lines = $analysis->{"$part_id.bubble_lines"};
7355: }
7356:
7357: $first_bubble_line{$response_number} = $bubble_line;
7358: $bubble_lines_per_response{$response_number} = $lines;
7359: $responsetype_per_response{$response_number} =
7360: $analysis->{$part_id.'.type'};
7361: $response_number++;
7362:
7363: $bubble_line += $lines;
7364: $total_lines += $lines;
7365: }
7366: }
7367: }
7368: &Apache::lonnet::delenv('scantron.');
7369:
7370: &save_bubble_lines();
7371: $env{'form.scantron_maxbubble'} =
7372: $total_lines;
7373: return $env{'form.scantron_maxbubble'};
7374: }
7375:
7376: sub scantron_validate_missingbubbles {
7377: my ($r,$currentphase) = @_;
7378: #get student info
7379: my $classlist=&Apache::loncoursedata::get_classlist();
7380: my %idmap=&username_to_idmap($classlist);
7381:
7382: #get scantron line setup
7383: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7384: my ($scanlines,$scan_data)=&scantron_getfile();
7385: my $max_bubble=&scantron_get_maxbubble();
7386: if (!$max_bubble) { $max_bubble=2**31; }
7387: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7388: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7389: if ($line=~/^[\s\cz]*$/) { next; }
7390: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7391: $scan_data);
7392: if (!defined($$scan_record{'scantron.missingerror'})) { next; }
7393: my @to_correct;
7394:
7395: # Probably here's where the error is...
7396:
7397: foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
7398: my $lastbubble;
7399: if ($missing =~ /^(\d+)\.(\d+)$/) {
7400: my $question = $1;
7401: my $subquestion = $2;
7402: if (!defined($first_bubble_line{$question -1})) { next; }
7403: my $first = $first_bubble_line{$question-1};
7404: my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
7405: my $subcount = 1;
7406: while ($subcount<$subquestion) {
7407: $first += $subans[$subcount-1];
7408: $subcount ++;
7409: }
7410: my $count = $subans[$subquestion-1];
7411: $lastbubble = $first + $count;
7412: } else {
7413: if (!defined($first_bubble_line{$missing - 1})) { next; }
7414: $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
7415: }
7416: if ($lastbubble > $max_bubble) { next; }
7417: push(@to_correct,$missing);
7418: }
7419: if (@to_correct) {
7420: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
7421: $line,'missingbubble',\@to_correct);
7422: return (1,$currentphase);
7423: }
7424:
7425: }
7426: return (0,$currentphase+1);
7427: }
7428:
7429:
7430: sub scantron_process_students {
7431: my ($r) = @_;
7432:
7433: my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
7434: my ($symb)=&get_symb($r);
7435: if (!$symb) {
7436: return '';
7437: }
7438: my $default_form_data=&defaultFormData($symb);
7439:
7440: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7441: my ($scanlines,$scan_data)=&scantron_getfile();
7442: my $classlist=&Apache::loncoursedata::get_classlist();
7443: my %idmap=&username_to_idmap($classlist);
7444: my $navmap=Apache::lonnavmaps::navmap->new();
7445: my $map=$navmap->getResourceByUrl($sequence);
7446: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
7447: my (%grader_partids_by_symb,%grader_randomlists_by_symb);
7448: &graders_resources_pass(\@resources,\%grader_partids_by_symb,
7449: \%grader_randomlists_by_symb);
7450: foreach my $resource (@resources) {
7451: my $ressymb = $resource->symb();
7452: my ($analysis,$parts) =
7453: &scantron_partids_tograde($resource,$env{'request.course.id'},
7454: $env{'user.name'},$env{'user.domain'},1);
7455: $grader_partids_by_symb{$ressymb} = $parts;
7456: if (ref($analysis) eq 'HASH') {
7457: if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
7458: $grader_randomlists_by_symb{$ressymb} =
7459: $analysis->{'parts_withrandomlist'};
7460: }
7461: }
7462: }
7463:
7464: my ($uname,$udom);
7465: my $result= <<SCANTRONFORM;
7466: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
7467: <input type="hidden" name="command" value="scantron_configphase" />
7468: $default_form_data
7469: SCANTRONFORM
7470: $r->print($result);
7471:
7472: my @delayqueue;
7473: my (%completedstudents,%scandata);
7474:
7475: my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
7476: my $count=&get_todo_count($scanlines,$scan_data);
7477: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
7478: 'Scantron Progress',$count,
7479: 'inline',undef,'scantronupload');
7480: &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
7481: 'Processing first student');
7482: $r->print('<br />');
7483: my $start=&Time::HiRes::time();
7484: my $i=-1;
7485: my $started;
7486:
7487: &scantron_get_maxbubble(); # Need the bubble lines array to parse.
7488:
7489: # If an ssi failed in scantron_get_maxbubble, put an error message out to
7490: # the user and return.
7491:
7492: if ($ssi_error) {
7493: $r->print("</form>");
7494: &ssi_print_error($r);
7495: $r->print(&show_grading_menu_form($symb));
7496: &Apache::lonnet::remove_lock($lock);
7497: return ''; # Dunno why the other returns return '' rather than just returning.
7498: }
7499:
7500: my %lettdig = &letter_to_digits();
7501: my $numletts = scalar(keys(%lettdig));
7502:
7503: while ($i<$scanlines->{'count'}) {
7504: ($uname,$udom)=('','');
7505: $i++;
7506: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7507: if ($line=~/^[\s\cz]*$/) { next; }
7508: if ($started) {
7509: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
7510: 'last student');
7511: }
7512: $started=1;
7513: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7514: $scan_data);
7515: unless ($uname=&scantron_find_student($scan_record,$scan_data,
7516: \%idmap,$i)) {
7517: &scantron_add_delay(\@delayqueue,$line,
7518: 'Unable to find a student that matches',1);
7519: next;
7520: }
7521: if (exists $completedstudents{$uname}) {
7522: &scantron_add_delay(\@delayqueue,$line,
7523: 'Student '.$uname.' has multiple sheets',2);
7524: next;
7525: }
7526: ($uname,$udom)=split(/:/,$uname);
7527:
7528: my %partids_by_symb;
7529: foreach my $resource (@resources) {
7530: my $ressymb = $resource->symb();
7531: if ((exists($grader_randomlists_by_symb{$ressymb})) ||
7532: (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
7533: my ($analysis,$parts) =
7534: &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
7535: $partids_by_symb{$ressymb} = $parts;
7536: } else {
7537: $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
7538: }
7539: }
7540:
7541: &Apache::lonxml::clear_problem_counter();
7542: &Apache::lonnet::appenv($scan_record);
7543:
7544: if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
7545: &scantron_putfile($scanlines,$scan_data);
7546: }
7547:
7548: my $scancode;
7549: if ((exists($scan_record->{'scantron.CODE'})) &&
7550: (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
7551: $scancode = $scan_record->{'scantron.CODE'};
7552: } else {
7553: $scancode = '';
7554: }
7555:
7556: if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
7557: \@resources,\%partids_by_symb) eq 'ssi_error') {
7558: $ssi_error = 0; # So end of handler error message does not trigger.
7559: $r->print("</form>");
7560: &ssi_print_error($r);
7561: $r->print(&show_grading_menu_form($symb));
7562: &Apache::lonnet::remove_lock($lock);
7563: return ''; # Why return ''? Beats me.
7564: }
7565:
7566: $completedstudents{$uname}={'line'=>$line};
7567: if ($env{'form.verifyrecord'}) {
7568: my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
7569: my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
7570: chomp($studentdata);
7571: $studentdata =~ s/\r$//;
7572: my $studentrecord = '';
7573: my $counter = -1;
7574: foreach my $resource (@resources) {
7575: my $ressymb = $resource->symb();
7576: ($counter,my $recording) =
7577: &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
7578: $counter,$studentdata,$partids_by_symb{$ressymb},
7579: \%scantron_config,\%lettdig,$numletts);
7580: $studentrecord .= $recording;
7581: }
7582: if ($studentrecord ne $studentdata) {
7583: &Apache::lonxml::clear_problem_counter();
7584: if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
7585: \@resources,\%partids_by_symb) eq 'ssi_error') {
7586: $ssi_error = 0; # So end of handler error message does not trigger.
7587: $r->print("</form>");
7588: &ssi_print_error($r);
7589: $r->print(&show_grading_menu_form($symb));
7590: &Apache::lonnet::remove_lock($lock);
7591: delete($completedstudents{$uname});
7592: return '';
7593: }
7594: $counter = -1;
7595: $studentrecord = '';
7596: foreach my $resource (@resources) {
7597: my $ressymb = $resource->symb();
7598: ($counter,my $recording) =
7599: &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
7600: $counter,$studentdata,$partids_by_symb{$ressymb},
7601: \%scantron_config,\%lettdig,$numletts);
7602: $studentrecord .= $recording;
7603: }
7604: if ($studentrecord ne $studentdata) {
7605: $r->print('<p><span class="LC_error">');
7606: if ($scancode eq '') {
7607: $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
7608: $uname.':'.$udom,$scan_record->{'scantron.ID'}));
7609: } else {
7610: $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
7611: $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
7612: }
7613: $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
7614: &Apache::loncommon::start_data_table_header_row()."\n".
7615: '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
7616: &Apache::loncommon::end_data_table_header_row()."\n".
7617: &Apache::loncommon::start_data_table_row().
7618: '<td>'.&mt('Bubble Sheet').'</td>'.
7619: '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
7620: &Apache::loncommon::end_data_table_row().
7621: &Apache::loncommon::start_data_table_row().
7622: '<td>Stored submissions</td>'.
7623: '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
7624: &Apache::loncommon::end_data_table_row().
7625: &Apache::loncommon::end_data_table().'</p>');
7626: } else {
7627: $r->print('<br /><span class="LC_warning">'.
7628: &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 />'.
7629: &mt("As a consequence, this user's submission history records two tries.").
7630: '</span><br />');
7631: }
7632: }
7633: }
7634: if (&Apache::loncommon::connection_aborted($r)) { last; }
7635: } continue {
7636: &Apache::lonxml::clear_problem_counter();
7637: &Apache::lonnet::delenv('scantron.');
7638: }
7639: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
7640: &Apache::lonnet::remove_lock($lock);
7641: # my $lasttime = &Time::HiRes::time()-$start;
7642: # $r->print("<p>took $lasttime</p>");
7643:
7644: $r->print("</form>");
7645: $r->print(&show_grading_menu_form($symb));
7646: return '';
7647: }
7648:
7649: sub graders_resources_pass {
7650: my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
7651: if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) &&
7652: (ref($grader_randomlists_by_symb) eq 'HASH')) {
7653: foreach my $resource (@{$resources}) {
7654: my $ressymb = $resource->symb();
7655: my ($analysis,$parts) =
7656: &scantron_partids_tograde($resource,$env{'request.course.id'},
7657: $env{'user.name'},$env{'user.domain'},1);
7658: $grader_partids_by_symb->{$ressymb} = $parts;
7659: if (ref($analysis) eq 'HASH') {
7660: if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
7661: $grader_randomlists_by_symb->{$ressymb} =
7662: $analysis->{'parts_withrandomlist'};
7663: }
7664: }
7665: }
7666: }
7667: return;
7668: }
7669:
7670: sub grade_student_bubbles {
7671: my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
7672: if (ref($resources) eq 'ARRAY') {
7673: my $count = 0;
7674: foreach my $resource (@{$resources}) {
7675: my $ressymb = $resource->symb();
7676: my %form = ('submitted' => 'scantron',
7677: 'grade_target' => 'grade',
7678: 'grade_username' => $uname,
7679: 'grade_domain' => $udom,
7680: 'grade_courseid' => $env{'request.course.id'},
7681: 'grade_symb' => $ressymb,
7682: 'CODE' => $scancode
7683: );
7684: if (ref($parts) eq 'HASH') {
7685: if (ref($parts->{$ressymb}) eq 'ARRAY') {
7686: foreach my $part (@{$parts->{$ressymb}}) {
7687: $form{'scantron_questnum_start.'.$part} =
7688: 1+$env{'form.scantron.first_bubble_line.'.$count};
7689: $count++;
7690: }
7691: }
7692: }
7693: my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
7694: return 'ssi_error' if ($ssi_error);
7695: last if (&Apache::loncommon::connection_aborted($r));
7696: }
7697: }
7698: return;
7699: }
7700:
7701: sub scantron_upload_scantron_data {
7702: my ($r)=@_;
7703: my $dom = $env{'request.role.domain'};
7704: my $domdesc = &Apache::lonnet::domain($dom,'description');
7705: $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
7706: my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
7707: 'domainid',
7708: 'coursename',$dom);
7709: my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
7710: (' 'x2).&mt('(shows course personnel)');
7711: my $default_form_data=&defaultFormData(&get_symb($r,1));
7712: $r->print('
7713: <script type="text/javascript" language="javascript">
7714: function checkUpload(formname) {
7715: if (formname.upfile.value == "") {
7716: alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
7717: return false;
7718: }
7719: if (formname.courseid.value == "") {
7720: 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.').'");
7721: return false;
7722: }
7723: formname.submit();
7724: }
7725:
7726: function ToSyllabus() {
7727: var cdom = '."'$dom'".';
7728: var cnum = document.rules.courseid.value;
7729: if (cdom == "" || cdom == null) {
7730: return;
7731: }
7732: if (cnum == "" || cnum == null) {
7733: return;
7734: }
7735: syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
7736: "height=350,width=350,scrollbars=yes,menubar=no");
7737: return;
7738: }
7739:
7740: </script>
7741:
7742: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
7743:
7744: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
7745: '.$default_form_data.
7746: &Apache::lonhtmlcommon::start_pick_box().
7747: &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
7748: '<input name="courseid" type="text" size="30" />'.$select_link.
7749: &Apache::lonhtmlcommon::row_closure().
7750: &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
7751: '<input name="coursename" type="text" size="30" />'.$syllabuslink.
7752: &Apache::lonhtmlcommon::row_closure().
7753: &Apache::lonhtmlcommon::row_title(&mt('Domain')).
7754: '<input name="domainid" type="hidden" />'.$domdesc.
7755: &Apache::lonhtmlcommon::row_closure().
7756: &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
7757: '<input type="file" name="upfile" size="50" />'.
7758: &Apache::lonhtmlcommon::row_closure(1).
7759: &Apache::lonhtmlcommon::end_pick_box().'<br />
7760:
7761: <input name="command" value="scantronupload_save" type="hidden" />
7762: <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
7763: </form>
7764: ');
7765: return '';
7766: }
7767:
7768:
7769: sub scantron_upload_scantron_data_save {
7770: my($r)=@_;
7771: my ($symb)=&get_symb($r,1);
7772: my $doanotherupload=
7773: '<br /><form action="/adm/grades" method="post">'."\n".
7774: '<input type="hidden" name="command" value="scantronupload" />'."\n".
7775: '<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
7776: '</form>'."\n";
7777: if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
7778: !&Apache::lonnet::allowed('usc',
7779: $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
7780: $r->print(&mt("You are not allowed to upload Scantron data to the requested course.")."<br />");
7781: if ($symb) {
7782: $r->print(&show_grading_menu_form($symb));
7783: } else {
7784: $r->print($doanotherupload);
7785: }
7786: return '';
7787: }
7788: my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
7789: my $uploadedfile;
7790: $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
7791: if (length($env{'form.upfile'}) < 2) {
7792: $r->print(&mt('[_1]Error:[_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.','<span class="LC_error">','</span>','<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
7793: } else {
7794: my $result =
7795: &Apache::lonnet::userfileupload('upfile','','scantron','','','',
7796: $env{'form.courseid'},$env{'form.domainid'});
7797: if ($result =~ m{^/uploaded/}) {
7798: $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
7799: '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
7800: '<span class="LC_filename">'.$result.'</span>'));
7801: ($uploadedfile) = ($result =~ m{/([^/]+)$});
7802: $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
7803: $env{'form.courseid'},$uploadedfile));
7804: } else {
7805: $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
7806: '<span class="LC_error">','</span>',$result,
7807: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
7808: }
7809: }
7810: if ($symb) {
7811: $r->print(&scantron_selectphase($r,$uploadedfile));
7812: } else {
7813: $r->print($doanotherupload);
7814: }
7815: return '';
7816: }
7817:
7818: sub validate_uploaded_scantron_file {
7819: my ($cdom,$cname,$fname) = @_;
7820: my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
7821: my @lines;
7822: if ($scanlines ne '-1') {
7823: @lines=split("\n",$scanlines,-1);
7824: }
7825: my $output;
7826: if (@lines) {
7827: my (%counts,$max_match_format);
7828: my ($max_match_count,$max_match_pct) = (0,0);
7829: my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
7830: my %idmap = &username_to_idmap($classlist);
7831: foreach my $key (keys(%idmap)) {
7832: my $lckey = lc($key);
7833: $idmap{$lckey} = $idmap{$key};
7834: }
7835: my %unique_formats;
7836: my @formatlines = &get_scantronformat_file();
7837: foreach my $line (@formatlines) {
7838: chomp($line);
7839: my @config = split(/:/,$line);
7840: my $idstart = $config[5];
7841: my $idlength = $config[6];
7842: if (($idstart ne '') && ($idlength > 0)) {
7843: if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
7844: push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]);
7845: } else {
7846: $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
7847: }
7848: }
7849: }
7850: foreach my $key (keys(%unique_formats)) {
7851: my ($idstart,$idlength) = split(':',$key);
7852: %{$counts{$key}} = (
7853: 'found' => 0,
7854: 'total' => 0,
7855: );
7856: foreach my $line (@lines) {
7857: next if ($line =~ /^#/);
7858: next if ($line =~ /^[\s\cz]*$/);
7859: my $id = substr($line,$idstart-1,$idlength);
7860: $id = lc($id);
7861: if (exists($idmap{$id})) {
7862: $counts{$key}{'found'} ++;
7863: }
7864: $counts{$key}{'total'} ++;
7865: }
7866: if ($counts{$key}{'total'}) {
7867: my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
7868: if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
7869: $max_match_pct = $percent_match;
7870: $max_match_format = $key;
7871: $max_match_count = $counts{$key}{'total'};
7872: }
7873: }
7874: }
7875: if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
7876: my $format_descs;
7877: my $numwithformat = @{$unique_formats{$max_match_format}};
7878: for (my $i=0; $i<$numwithformat; $i++) {
7879: my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
7880: if ($i<$numwithformat-2) {
7881: $format_descs .= '"<i>'.$desc.'</i>", ';
7882: } elsif ($i==$numwithformat-2) {
7883: $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
7884: } elsif ($i==$numwithformat-1) {
7885: $format_descs .= '"<i>'.$desc.'</i>"';
7886: }
7887: }
7888: my $showpct = sprintf("%.0f",$max_match_pct).'%';
7889: $output .= '<br />'.&mt('Comparison of student IDs in the uploaded file with the course roster found matches for [_1] of the [_2] entries in the file (for the format defined for [_3]).','<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
7890: '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
7891: '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
7892: '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
7893: '<i>'.$cdom.'</i>').'</li>'.
7894: '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
7895: '<li>'.&mt('The course roster is not up to date').'</li>'.
7896: '</ul>';
7897: }
7898: } else {
7899: $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
7900: }
7901: return $output;
7902: }
7903:
7904: sub valid_file {
7905: my ($requested_file)=@_;
7906: foreach my $filename (sort(&scantron_filenames())) {
7907: if ($requested_file eq $filename) { return 1; }
7908: }
7909: return 0;
7910: }
7911:
7912: sub scantron_download_scantron_data {
7913: my ($r)=@_;
7914: my $default_form_data=&defaultFormData(&get_symb($r,1));
7915: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7916: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7917: my $file=$env{'form.scantron_selectfile'};
7918: if (! &valid_file($file)) {
7919: $r->print('
7920: <p>
7921: '.&mt('The requested file name was invalid.').'
7922: </p>
7923: ');
7924: $r->print(&show_grading_menu_form(&get_symb($r,1)));
7925: return;
7926: }
7927: my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
7928: my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
7929: my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
7930: &Apache::lonnet::allowuploaded('/adm/grades',$orig);
7931: &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
7932: &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
7933: $r->print('
7934: <p>
7935: '.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
7936: '<a href="'.$orig.'">','</a>').'
7937: </p>
7938: <p>
7939: '.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
7940: '<a href="'.$corrected.'">','</a>').'
7941: </p>
7942: <p>
7943: '.&mt('[_1]Skipped[_2], a file of records that were skipped.',
7944: '<a href="'.$skipped.'">','</a>').'
7945: </p>
7946: ');
7947: $r->print(&show_grading_menu_form(&get_symb($r,1)));
7948: return '';
7949: }
7950:
7951: sub checkscantron_results {
7952: my ($r) = @_;
7953: my ($symb)=&get_symb($r);
7954: if (!$symb) {return '';}
7955: my $grading_menu_button=&show_grading_menu_form($symb);
7956: my $cid = $env{'request.course.id'};
7957: my %lettdig = &letter_to_digits();
7958: my $numletts = scalar(keys(%lettdig));
7959: my $cnum = $env{'course.'.$cid.'.num'};
7960: my $cdom = $env{'course.'.$cid.'.domain'};
7961: my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
7962: my %record;
7963: my %scantron_config =
7964: &Apache::grades::get_scantron_config($env{'form.scantron_format'});
7965: my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
7966: my $classlist=&Apache::loncoursedata::get_classlist();
7967: my %idmap=&Apache::grades::username_to_idmap($classlist);
7968: my $navmap=Apache::lonnavmaps::navmap->new();
7969: my $map=$navmap->getResourceByUrl($sequence);
7970: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
7971: my (%grader_partids_by_symb,%grader_randomlists_by_symb);
7972: &graders_resources_pass(\@resources,\%grader_partids_by_symb, \%grader_randomlists_by_symb);
7973:
7974: my ($uname,$udom);
7975: my (%scandata,%lastname,%bylast);
7976: $r->print('
7977: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
7978:
7979: my @delayqueue;
7980: my %completedstudents;
7981:
7982: my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
7983: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron/Submissions Comparison Status',
7984: 'Progress of Scantron Data/Submission Records Comparison',$count,
7985: 'inline',undef,'checkscantron');
7986: my ($username,$domain,$started);
7987:
7988: &scantron_get_maxbubble(); # Need the bubble lines array to parse.
7989:
7990: &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
7991: 'Processing first student');
7992: my $start=&Time::HiRes::time();
7993: my $i=-1;
7994:
7995: while ($i<$scanlines->{'count'}) {
7996: ($username,$domain,$uname)=('','','');
7997: $i++;
7998: my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
7999: if ($line=~/^[\s\cz]*$/) { next; }
8000: if ($started) {
8001: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
8002: 'last student');
8003: }
8004: $started=1;
8005: my $scan_record=
8006: &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
8007: $scan_data);
8008: unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
8009: \%idmap,$i)) {
8010: &Apache::grades::scantron_add_delay(\@delayqueue,$line,
8011: 'Unable to find a student that matches',1);
8012: next;
8013: }
8014: if (exists $completedstudents{$uname}) {
8015: &Apache::grades::scantron_add_delay(\@delayqueue,$line,
8016: 'Student '.$uname.' has multiple sheets',2);
8017: next;
8018: }
8019: my $pid = $scan_record->{'scantron.ID'};
8020: $lastname{$pid} = $scan_record->{'scantron.LastName'};
8021: push(@{$bylast{$lastname{$pid}}},$pid);
8022: my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
8023: $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
8024: chomp($scandata{$pid});
8025: $scandata{$pid} =~ s/\r$//;
8026: ($username,$domain)=split(/:/,$uname);
8027: my $counter = -1;
8028: foreach my $resource (@resources) {
8029: my $parts;
8030: my $ressymb = $resource->symb();
8031: if ((exists($grader_randomlists_by_symb{$ressymb})) ||
8032: (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
8033: (my $analysis,$parts) =
8034: &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
8035: } else {
8036: $parts = $grader_partids_by_symb{$ressymb};
8037: }
8038: ($counter,my $recording) =
8039: &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
8040: $scandata{$pid},$parts,
8041: \%scantron_config,\%lettdig,$numletts);
8042: $record{$pid} .= $recording;
8043: }
8044: }
8045: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
8046: $r->print('<br />');
8047: my ($okstudents,$badstudents,$numstudents,$passed,$failed);
8048: $passed = 0;
8049: $failed = 0;
8050: $numstudents = 0;
8051: foreach my $last (sort(keys(%bylast))) {
8052: if (ref($bylast{$last}) eq 'ARRAY') {
8053: foreach my $pid (sort(@{$bylast{$last}})) {
8054: my $showscandata = $scandata{$pid};
8055: my $showrecord = $record{$pid};
8056: $showscandata =~ s/\s/ /g;
8057: $showrecord =~ s/\s/ /g;
8058: if ($scandata{$pid} eq $record{$pid}) {
8059: my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
8060: $okstudents .= '<tr class="'.$css_class.'">'.
8061: '<td>'.&mt('Scantron').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
8062: '</tr>'."\n".
8063: '<tr class="'.$css_class.'">'."\n".
8064: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
8065: $passed ++;
8066: } else {
8067: my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
8068: $badstudents .= '<tr class="'.$css_class.'"><td>'.&mt('Scantron').'</td><td><span class="LC_nobreak">'.$scandata{$pid}.'</span></td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
8069: '</tr>'."\n".
8070: '<tr class="'.$css_class.'">'."\n".
8071: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
8072: '</tr>'."\n";
8073: $failed ++;
8074: }
8075: $numstudents ++;
8076: }
8077: }
8078: }
8079: $r->print('<p>'.&mt('Comparison of bubblesheet data (including corrections) with corresponding submission records (most recent submission) for <b>[quant,_1,student]</b> ([_2] scantron lines/student).',$numstudents,$env{'form.scantron_maxbubble'}).'</p>');
8080: $r->print('<p>'.&mt('Exact matches for <b>[quant,_1,student]</b>.',$passed).'<br />'.&mt('Discrepancies detected for <b>[quant,_1,student]</b>.',$failed).'</p>');
8081: if ($passed) {
8082: $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
8083: $r->print(&Apache::loncommon::start_data_table()."\n".
8084: &Apache::loncommon::start_data_table_header_row()."\n".
8085: '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
8086: &Apache::loncommon::end_data_table_header_row()."\n".
8087: $okstudents."\n".
8088: &Apache::loncommon::end_data_table().'<br />');
8089: }
8090: if ($failed) {
8091: $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
8092: $r->print(&Apache::loncommon::start_data_table()."\n".
8093: &Apache::loncommon::start_data_table_header_row()."\n".
8094: '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
8095: &Apache::loncommon::end_data_table_header_row()."\n".
8096: $badstudents."\n".
8097: &Apache::loncommon::end_data_table()).'<br />'.
8098: &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.');
8099: }
8100: $r->print('</form><br />'.$grading_menu_button);
8101: return;
8102: }
8103:
8104: sub verify_scantron_grading {
8105: my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
8106: $scantron_config,$lettdig,$numletts) = @_;
8107: my ($record,%expected,%startpos);
8108: return ($counter,$record) if (!ref($resource));
8109: return ($counter,$record) if (!$resource->is_problem());
8110: my $symb = $resource->symb();
8111: return ($counter,$record) if (ref($partids) ne 'ARRAY');
8112: foreach my $part_id (@{$partids}) {
8113: $counter ++;
8114: $expected{$part_id} = 0;
8115: if ($env{"form.scantron.sub_bubblelines.$counter"}) {
8116: my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
8117: foreach my $item (@sub_lines) {
8118: $expected{$part_id} += $item;
8119: }
8120: } else {
8121: $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
8122: }
8123: $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
8124: }
8125: if ($symb) {
8126: my %recorded;
8127: my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
8128: if ($returnhash{'version'}) {
8129: my %lasthash=();
8130: my $version;
8131: for ($version=1;$version<=$returnhash{'version'};$version++) {
8132: foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
8133: $lasthash{$key}=$returnhash{$version.':'.$key};
8134: }
8135: }
8136: foreach my $key (keys(%lasthash)) {
8137: if ($key =~ /\.scantron$/) {
8138: my $value = &unescape($lasthash{$key});
8139: my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
8140: if ($value eq '') {
8141: for (my $i=0; $i<$expected{$part_id}; $i++) {
8142: for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
8143: $recorded{$part_id} .= $scantron_config->{'Qoff'};
8144: }
8145: }
8146: } else {
8147: my @tocheck;
8148: my @items = split(//,$value);
8149: if (($scantron_config->{'Qon'} eq 'letter') ||
8150: ($scantron_config->{'Qon'} eq 'number')) {
8151: if (@items < $expected{$part_id}) {
8152: my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
8153: my @singles = split(//,$fragment);
8154: foreach my $pos (@singles) {
8155: if ($pos eq ' ') {
8156: push(@tocheck,$pos);
8157: } else {
8158: my $next = shift(@items);
8159: push(@tocheck,$next);
8160: }
8161: }
8162: } else {
8163: @tocheck = @items;
8164: }
8165: foreach my $letter (@tocheck) {
8166: if ($scantron_config->{'Qon'} eq 'letter') {
8167: if ($letter !~ /^[A-J]$/) {
8168: $letter = $scantron_config->{'Qoff'};
8169: }
8170: $recorded{$part_id} .= $letter;
8171: } elsif ($scantron_config->{'Qon'} eq 'number') {
8172: my $digit;
8173: if ($letter !~ /^[A-J]$/) {
8174: $digit = $scantron_config->{'Qoff'};
8175: } else {
8176: $digit = $lettdig->{$letter};
8177: }
8178: $recorded{$part_id} .= $digit;
8179: }
8180: }
8181: } else {
8182: @tocheck = @items;
8183: for (my $i=0; $i<$expected{$part_id}; $i++) {
8184: my $curr_sub = shift(@tocheck);
8185: my $digit;
8186: if ($curr_sub =~ /^[A-J]$/) {
8187: $digit = $lettdig->{$curr_sub}-1;
8188: }
8189: if ($curr_sub eq 'J') {
8190: $digit += scalar($numletts);
8191: }
8192: for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
8193: if ($j == $digit) {
8194: $recorded{$part_id} .= $scantron_config->{'Qon'};
8195: } else {
8196: $recorded{$part_id} .= $scantron_config->{'Qoff'};
8197: }
8198: }
8199: }
8200: }
8201: }
8202: }
8203: }
8204: }
8205: foreach my $part_id (@{$partids}) {
8206: if ($recorded{$part_id} eq '') {
8207: for (my $i=0; $i<$expected{$part_id}; $i++) {
8208: for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
8209: $recorded{$part_id} .= $scantron_config->{'Qoff'};
8210: }
8211: }
8212: }
8213: $record .= $recorded{$part_id};
8214: }
8215: }
8216: return ($counter,$record);
8217: }
8218:
8219: sub letter_to_digits {
8220: my %lettdig = (
8221: A => 1,
8222: B => 2,
8223: C => 3,
8224: D => 4,
8225: E => 5,
8226: F => 6,
8227: G => 7,
8228: H => 8,
8229: I => 9,
8230: J => 0,
8231: );
8232: return %lettdig;
8233: }
8234:
8235:
8236: #-------- end of section for handling grading scantron forms -------
8237: #
8238: #-------------------------------------------------------------------
8239:
8240: #-------------------------- Menu interface -------------------------
8241: #
8242: #--- Show a Grading Menu button - Calls the next routine ---
8243: sub show_grading_menu_form {
8244: my ($symb)=@_;
8245: my $result.='<br /><form action="/adm/grades" method="post">'."\n".
8246: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
8247: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
8248: '<input type="hidden" name="command" value="gradingmenu" />'."\n".
8249: '<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
8250: '</form>'."\n";
8251: return $result;
8252: }
8253:
8254: # -- Retrieve choices for grading form
8255: sub savedState {
8256: my %savedState = ();
8257: if ($env{'form.saveState'}) {
8258: foreach (split(/:/,$env{'form.saveState'})) {
8259: my ($key,$value) = split(/=/,$_,2);
8260: $savedState{$key} = $value;
8261: }
8262: }
8263: return \%savedState;
8264: }
8265:
8266: sub grading_menu {
8267: my ($request) = @_;
8268: my ($symb)=&get_symb($request);
8269: if (!$symb) {return '';}
8270: my $probTitle = &Apache::lonnet::gettitle($symb);
8271: my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
8272:
8273: $request->print($table);
8274: my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
8275: 'handgrade'=>$hdgrade,
8276: 'probTitle'=>$probTitle,
8277: 'command'=>'submit_options',
8278: 'saveState'=>"",
8279: 'gradingMenu'=>1,
8280: 'showgrading'=>"yes");
8281:
8282: my $url1 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
8283:
8284: $fields{'command'} = 'csvform';
8285: my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
8286:
8287: $fields{'command'} = 'processclicker';
8288: my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
8289:
8290: $fields{'command'} = 'scantron_selectphase';
8291: my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
8292:
8293: my @menu = ({ categorytitle=>'Course Grading',
8294: items =>[
8295: { linktext => 'Manual Grading/View Submissions',
8296: url => $url1,
8297: permission => 'F',
8298: icon => 'edit-find-replace.png',
8299: linktitle => 'Start the process of hand grading submissions.'
8300: },
8301: { linktext => 'Upload Scores',
8302: url => $url2,
8303: permission => 'F',
8304: icon => 'uploadscores.png',
8305: linktitle => 'Specify a file containing the class scores for current resource.'
8306: },
8307: { linktext => 'Process Clicker',
8308: url => $url3,
8309: permission => 'F',
8310: icon => 'addClickerInfoFile.png',
8311: linktitle => 'Specify a file containing the clicker information for this resource.'
8312: },
8313: { linktext => 'Grade/Manage/Review Scantron Forms',
8314: url => $url4,
8315: permission => 'F',
8316: icon => 'stat.png',
8317: linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
8318: }
8319: ]
8320: });
8321:
8322: #$fields{'command'} = 'verify';
8323: #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
8324: #
8325: # Create the menu
8326: my $Str;
8327: # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
8328: $Str .= '<form method="post" action="" name="gradingMenu">';
8329: $Str .= '<input type="hidden" name="command" value="" />'.
8330: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
8331: '<input type="hidden" name="handgrade" value="'.$hdgrade.'" />'."\n".
8332: '<input type="hidden" name="probTitle" value="'.$probTitle.'" />'."\n".
8333: '<input type="hidden" name="saveState" value="" />'."\n".
8334: '<input type="hidden" name="gradingMenu" value="1" />'."\n".
8335: '<input type="hidden" name="showgrading" value="yes" />'."\n";
8336:
8337: $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
8338: #$menudata->{'jscript'}
8339: $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt').'" '.
8340: ' onClick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
8341: ' /> '.
8342: &Apache::lonnet::recprefix($env{'request.course.id'}).
8343: '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
8344:
8345: $Str .="</form>\n";
8346: my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
8347: $request->print(<<GRADINGMENUJS);
8348: <script type="text/javascript" language="javascript">
8349: function checkChoice(formname,val,cmdx) {
8350: if (val <= 2) {
8351: var cmd = radioSelection(formname.radioChoice);
8352: var cmdsave = cmd;
8353: } else {
8354: cmd = cmdx;
8355: cmdsave = 'submission';
8356: }
8357: formname.command.value = cmd;
8358: if (val < 5) formname.submit();
8359: if (val == 5) {
8360: if (!checkReceiptNo(formname,'notOK')) {
8361: return false;
8362: } else {
8363: formname.submit();
8364: }
8365: }
8366: }
8367:
8368: function checkReceiptNo(formname,nospace) {
8369: var receiptNo = formname.receipt.value;
8370: var checkOpt = false;
8371: if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
8372: if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
8373: if (checkOpt) {
8374: alert("$receiptalert");
8375: formname.receipt.value = "";
8376: formname.receipt.focus();
8377: return false;
8378: }
8379: return true;
8380: }
8381: </script>
8382: GRADINGMENUJS
8383: &commonJSfunctions($request);
8384: return $Str;
8385: }
8386:
8387:
8388: #--- Displays the submissions first page -------
8389: sub submit_options {
8390: my ($request) = @_;
8391: my ($symb)=&get_symb($request);
8392: if (!$symb) {return '';}
8393: my $probTitle = &Apache::lonnet::gettitle($symb);
8394:
8395: my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
8396: $request->print(<<GRADINGMENUJS);
8397: <script type="text/javascript" language="javascript">
8398: function checkChoice(formname,val,cmdx) {
8399: if (val <= 2) {
8400: var cmd = radioSelection(formname.radioChoice);
8401: var cmdsave = cmd;
8402: } else {
8403: cmd = cmdx;
8404: cmdsave = 'submission';
8405: }
8406: formname.command.value = cmd;
8407: formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
8408: ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
8409: if (val < 5) formname.submit();
8410: if (val == 5) {
8411: if (!checkReceiptNo(formname,'notOK')) { return false;}
8412: formname.submit();
8413: }
8414: if (val < 7) formname.submit();
8415: }
8416:
8417: function checkReceiptNo(formname,nospace) {
8418: var receiptNo = formname.receipt.value;
8419: var checkOpt = false;
8420: if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
8421: if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
8422: if (checkOpt) {
8423: alert("$receiptalert");
8424: formname.receipt.value = "";
8425: formname.receipt.focus();
8426: return false;
8427: }
8428: return true;
8429: }
8430: </script>
8431: GRADINGMENUJS
8432: &commonJSfunctions($request);
8433: my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
8434: my $result;
8435: my (undef,$sections) = &getclasslist('all','0');
8436: my $savedState = &savedState();
8437: my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
8438: my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
8439: my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
8440: my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
8441:
8442: # Preselect sections
8443: my $selsec="";
8444: if (ref($sections)) {
8445: foreach my $section (sort(@$sections)) {
8446: $selsec.='<option value="'.$section.'" '.
8447: ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
8448: }
8449: }
8450:
8451: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
8452: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
8453: '<input type="hidden" name="handgrade" value="'.$hdgrade.'" />'."\n".
8454: '<input type="hidden" name="probTitle" value="'.$probTitle.'" />'."\n".
8455: '<input type="hidden" name="command" value="" />'."\n".
8456: '<input type="hidden" name="saveState" value="" />'."\n".
8457: '<input type="hidden" name="gradingMenu" value="1" />'."\n".
8458: '<input type="hidden" name="showgrading" value="yes" />'."\n";
8459:
8460: $result.='
8461: <h2>
8462: '.&mt('Grade Current Resource').'
8463: </h2>
8464: <div>
8465: '.$table.'
8466: </div>
8467:
8468: <div class="LC_columnSection">
8469:
8470: <fieldset>
8471: <legend>
8472: '.&mt('Sections').'
8473: </legend>
8474: <select name="section" multiple="multiple" size="5">'."\n";
8475: $result.= $selsec;
8476: $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> ';
8477: $result.='
8478: </fieldset>
8479:
8480: <fieldset>
8481: <legend>
8482: '.&mt('Groups').'
8483: </legend>
8484: '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
8485: </fieldset>
8486:
8487: <fieldset>
8488: <legend>
8489: '.&mt('Access Status').'
8490: </legend>
8491: '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
8492: </fieldset>
8493:
8494: <fieldset>
8495: <legend>
8496: '.&mt('Submission Status').'
8497: </legend>
8498: <select name="submitonly" size="5">
8499: <option value="yes" '. ($saveSub eq 'yes' ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
8500: <option value="queued" '. ($saveSub eq 'queued' ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
8501: <option value="graded" '. ($saveSub eq 'graded' ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
8502: <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
8503: <option value="all" '. ($saveSub eq 'all' ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
8504: </select>
8505: </fieldset>
8506:
8507: </div>
8508:
8509: <br />
8510: <div>
8511: <div>
8512: <label>
8513: <input type="radio" name="radioChoice" value="submission" '.
8514: ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
8515: &mt('Select individual students to grade and view submissions.').'
8516: </label>
8517: </div>
8518: <div>
8519: <label>
8520: <input type="radio" name="radioChoice" value="viewgrades" '.
8521: ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
8522: &mt('Grade all selected students in a grading table.').'
8523: </label>
8524: </div>
8525: <div>
8526: <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' →" />
8527: </div>
8528: </div>
8529:
8530:
8531: <h2>
8532: '.&mt('Grade Complete Folder for One Student').'
8533: </h2>
8534: <div>
8535: <div>
8536: <label>
8537: <input type="radio" name="radioChoice" value="pickStudentPage" '.
8538: ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
8539: &mt('The <b>complete</b> page/sequence/folder: For one student').'
8540: </label>
8541: </div>
8542: <div>
8543: <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' →" />
8544: </div>
8545: </div>
8546: </form>';
8547: $result .= &show_grading_menu_form($symb);
8548: return $result;
8549: }
8550:
8551: sub reset_perm {
8552: undef(%perm);
8553: }
8554:
8555: sub init_perm {
8556: &reset_perm();
8557: foreach my $test_perm ('vgr','mgr','opa') {
8558:
8559: my $scope = $env{'request.course.id'};
8560: if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
8561:
8562: $scope .= '/'.$env{'request.course.sec'};
8563: if ( $perm{$test_perm}=
8564: &Apache::lonnet::allowed($test_perm,$scope)) {
8565: $perm{$test_perm.'_section'}=$env{'request.course.sec'};
8566: } else {
8567: delete($perm{$test_perm});
8568: }
8569: }
8570: }
8571: }
8572:
8573: sub gather_clicker_ids {
8574: my %clicker_ids;
8575:
8576: my $classlist = &Apache::loncoursedata::get_classlist();
8577:
8578: # Set up a couple variables.
8579: my $username_idx = &Apache::loncoursedata::CL_SNAME();
8580: my $domain_idx = &Apache::loncoursedata::CL_SDOM();
8581: my $status_idx = &Apache::loncoursedata::CL_STATUS();
8582:
8583: foreach my $student (keys(%$classlist)) {
8584: if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
8585: my $username = $classlist->{$student}->[$username_idx];
8586: my $domain = $classlist->{$student}->[$domain_idx];
8587: my $clickers =
8588: (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
8589: foreach my $id (split(/\,/,$clickers)) {
8590: $id=~s/^[\#0]+//;
8591: $id=~s/[\-\:]//g;
8592: if (exists($clicker_ids{$id})) {
8593: $clicker_ids{$id}.=','.$username.':'.$domain;
8594: } else {
8595: $clicker_ids{$id}=$username.':'.$domain;
8596: }
8597: }
8598: }
8599: return %clicker_ids;
8600: }
8601:
8602: sub gather_adv_clicker_ids {
8603: my %clicker_ids;
8604: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
8605: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
8606: my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
8607: foreach my $element (sort(keys(%coursepersonnel))) {
8608: foreach my $person (split(/\,/,$coursepersonnel{$element})) {
8609: my ($puname,$pudom)=split(/\:/,$person);
8610: my $clickers =
8611: (&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
8612: foreach my $id (split(/\,/,$clickers)) {
8613: $id=~s/^[\#0]+//;
8614: $id=~s/[\-\:]//g;
8615: if (exists($clicker_ids{$id})) {
8616: $clicker_ids{$id}.=','.$puname.':'.$pudom;
8617: } else {
8618: $clicker_ids{$id}=$puname.':'.$pudom;
8619: }
8620: }
8621: }
8622: }
8623: return %clicker_ids;
8624: }
8625:
8626: sub clicker_grading_parameters {
8627: return ('gradingmechanism' => 'scalar',
8628: 'upfiletype' => 'scalar',
8629: 'specificid' => 'scalar',
8630: 'pcorrect' => 'scalar',
8631: 'pincorrect' => 'scalar');
8632: }
8633:
8634: sub process_clicker {
8635: my ($r)=@_;
8636: my ($symb)=&get_symb($r);
8637: if (!$symb) {return '';}
8638: my $result=&checkforfile_js();
8639: $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
8640: my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
8641: $result.=$table;
8642: $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
8643: $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
8644: $result.=' <b>'.&mt('Specify a file containing the clicker information for this resource.').
8645: '</b></td></tr>'."\n";
8646: $result.='<tr bgcolor=#ffffe6><td>'."\n";
8647: # Attempt to restore parameters from last session, set defaults if not present
8648: my %Saveable_Parameters=&clicker_grading_parameters();
8649: &Apache::loncommon::restore_course_settings('grades_clicker',
8650: \%Saveable_Parameters);
8651: if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
8652: if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
8653: if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
8654: if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
8655:
8656: my %checked;
8657: foreach my $gradingmechanism ('attendance','personnel','specific','given') {
8658: if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
8659: $checked{$gradingmechanism}=' checked="checked"';
8660: }
8661: }
8662:
8663: my $upload=&mt("Upload File");
8664: my $type=&mt("Type");
8665: my $attendance=&mt("Award points just for participation");
8666: my $personnel=&mt("Correctness determined from response by course personnel");
8667: my $specific=&mt("Correctness determined from response with clicker ID(s)");
8668: my $given=&mt("Correctness determined from given list of answers").' '.
8669: '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
8670: my $pcorrect=&mt("Percentage points for correct solution");
8671: my $pincorrect=&mt("Percentage points for incorrect solution");
8672: my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
8673: ('iclicker' => 'i>clicker',
8674: 'interwrite' => 'interwrite PRS'));
8675: $symb = &Apache::lonenc::check_encrypt($symb);
8676: $result.=<<ENDUPFORM;
8677: <script type="text/javascript">
8678: function sanitycheck() {
8679: // Accept only integer percentages
8680: document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
8681: document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
8682: // Find out grading choice
8683: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
8684: if (document.forms.gradesupload.gradingmechanism[i].checked) {
8685: gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
8686: }
8687: }
8688: // By default, new choice equals user selection
8689: newgradingchoice=gradingchoice;
8690: // Not good to give more points for false answers than correct ones
8691: if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
8692: document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
8693: }
8694: // If new choice is attendance only, and old choice was correctness-based, restore defaults
8695: if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
8696: document.forms.gradesupload.pcorrect.value=100;
8697: document.forms.gradesupload.pincorrect.value=100;
8698: }
8699: // If the values are different, cannot be attendance only
8700: if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
8701: (gradingchoice=='attendance')) {
8702: newgradingchoice='personnel';
8703: }
8704: // Change grading choice to new one
8705: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
8706: if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
8707: document.forms.gradesupload.gradingmechanism[i].checked=true;
8708: } else {
8709: document.forms.gradesupload.gradingmechanism[i].checked=false;
8710: }
8711: }
8712: // Remember the old state
8713: document.forms.gradesupload.waschecked.value=newgradingchoice;
8714: }
8715: </script>
8716: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
8717: <input type="hidden" name="symb" value="$symb" />
8718: <input type="hidden" name="command" value="processclickerfile" />
8719: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
8720: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
8721: <input type="file" name="upfile" size="50" />
8722: <br /><label>$type: $selectform</label>
8723: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
8724: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
8725: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onClick="sanitycheck()" />$specific </label>
8726: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
8727: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onClick="sanitycheck()" />$given </label>
8728: <br />
8729: <input type="text" name="givenanswer" size="50" />
8730: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
8731: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
8732: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
8733: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
8734: </form>
8735: ENDUPFORM
8736: $result.='</td></tr></table>'."\n".
8737: '</td></tr></table><br /><br />'."\n";
8738: $result.=&show_grading_menu_form($symb);
8739: return $result;
8740: }
8741:
8742: sub process_clicker_file {
8743: my ($r)=@_;
8744: my ($symb)=&get_symb($r);
8745: if (!$symb) {return '';}
8746:
8747: my %Saveable_Parameters=&clicker_grading_parameters();
8748: &Apache::loncommon::store_course_settings('grades_clicker',
8749: \%Saveable_Parameters);
8750:
8751: my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
8752: if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
8753: $result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
8754: return $result.&show_grading_menu_form($symb);
8755: }
8756: if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
8757: $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
8758: return $result.&show_grading_menu_form($symb);
8759: }
8760: my $foundgiven=0;
8761: if ($env{'form.gradingmechanism'} eq 'given') {
8762: $env{'form.givenanswer'}=~s/^\s*//gs;
8763: $env{'form.givenanswer'}=~s/\s*$//gs;
8764: $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
8765: $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
8766: my @answers=split(/\,/,$env{'form.givenanswer'});
8767: $foundgiven=$#answers+1;
8768: }
8769: my %clicker_ids=&gather_clicker_ids();
8770: my %correct_ids;
8771: if ($env{'form.gradingmechanism'} eq 'personnel') {
8772: %correct_ids=&gather_adv_clicker_ids();
8773: }
8774: if ($env{'form.gradingmechanism'} eq 'specific') {
8775: foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
8776: $correct_id=~tr/a-z/A-Z/;
8777: $correct_id=~s/\s//gs;
8778: $correct_id=~s/^[\#0]+//;
8779: $correct_id=~s/[\-\:]//g;
8780: if ($correct_id) {
8781: $correct_ids{$correct_id}='specified';
8782: }
8783: }
8784: }
8785: if ($env{'form.gradingmechanism'} eq 'attendance') {
8786: $result.=&mt('Score based on attendance only');
8787: } elsif ($env{'form.gradingmechanism'} eq 'given') {
8788: $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
8789: } else {
8790: my $number=0;
8791: $result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
8792: foreach my $id (sort(keys(%correct_ids))) {
8793: $result.='<br /><tt>'.$id.'</tt> - ';
8794: if ($correct_ids{$id} eq 'specified') {
8795: $result.=&mt('specified');
8796: } else {
8797: my ($uname,$udom)=split(/\:/,$correct_ids{$id});
8798: $result.=&Apache::loncommon::plainname($uname,$udom);
8799: }
8800: $number++;
8801: }
8802: $result.="</p>\n";
8803: if ($number==0) {
8804: $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
8805: return $result.&show_grading_menu_form($symb);
8806: }
8807: }
8808: if (length($env{'form.upfile'}) < 2) {
8809: $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
8810: '<span class="LC_error">',
8811: '</span>',
8812: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
8813: return $result.&show_grading_menu_form($symb);
8814: }
8815:
8816: # Were able to get all the info needed, now analyze the file
8817:
8818: $result.=&Apache::loncommon::studentbrowser_javascript();
8819: $symb = &Apache::lonenc::check_encrypt($symb);
8820: my $heading=&mt('Scanning clicker file');
8821: $result.=(<<ENDHEADER);
8822: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
8823: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
8824: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
8825: <form method="post" action="/adm/grades" name="clickeranalysis">
8826: <input type="hidden" name="symb" value="$symb" />
8827: <input type="hidden" name="command" value="assignclickergrades" />
8828: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
8829: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
8830: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
8831: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
8832: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
8833: ENDHEADER
8834: if ($env{'form.gradingmechanism'} eq 'given') {
8835: $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
8836: }
8837: my %responses;
8838: my @questiontitles;
8839: my $errormsg='';
8840: my $number=0;
8841: if ($env{'form.upfiletype'} eq 'iclicker') {
8842: ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
8843: }
8844: if ($env{'form.upfiletype'} eq 'interwrite') {
8845: ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
8846: }
8847: $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
8848: '<input type="hidden" name="number" value="'.$number.'" />'.
8849: &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
8850: $env{'form.pcorrect'},$env{'form.pincorrect'}).
8851: '<br />';
8852: if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
8853: $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
8854: return $result.&show_grading_menu_form($symb);
8855: }
8856: # Remember Question Titles
8857: # FIXME: Possibly need delimiter other than ":"
8858: for (my $i=0;$i<$number;$i++) {
8859: $result.='<input type="hidden" name="question:'.$i.'" value="'.
8860: &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
8861: }
8862: my $correct_count=0;
8863: my $student_count=0;
8864: my $unknown_count=0;
8865: # Match answers with usernames
8866: # FIXME: Possibly need delimiter other than ":"
8867: foreach my $id (keys(%responses)) {
8868: if ($correct_ids{$id}) {
8869: $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
8870: $correct_count++;
8871: } elsif ($clicker_ids{$id}) {
8872: if ($clicker_ids{$id}=~/\,/) {
8873: # More than one user with the same clicker!
8874: $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
8875: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
8876: "<select name='multi".$id."'>";
8877: foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
8878: $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
8879: }
8880: $result.='</select>';
8881: $unknown_count++;
8882: } else {
8883: # Good: found one and only one user with the right clicker
8884: $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
8885: $student_count++;
8886: }
8887: } else {
8888: $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
8889: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
8890: "\n".&mt("Username").": <input type='text' name='uname".$id."' /> ".
8891: "\n".&mt("Domain").": ".
8892: &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).' '.
8893: &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
8894: $unknown_count++;
8895: }
8896: }
8897: $result.='<hr />'.
8898: &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
8899: if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
8900: if ($correct_count==0) {
8901: $errormsg.="Found no correct answers answers for grading!";
8902: } elsif ($correct_count>1) {
8903: $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
8904: }
8905: }
8906: if ($number<1) {
8907: $errormsg.="Found no questions.";
8908: }
8909: if ($errormsg) {
8910: $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
8911: } else {
8912: $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
8913: }
8914: $result.='</form></td></tr></table>'."\n".
8915: '</td></tr></table><br /><br />'."\n";
8916: return $result.&show_grading_menu_form($symb);
8917: }
8918:
8919: sub iclicker_eval {
8920: my ($questiontitles,$responses)=@_;
8921: my $number=0;
8922: my $errormsg='';
8923: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
8924: my %components=&Apache::loncommon::record_sep($line);
8925: my @entries=map {$components{$_}} (sort(keys(%components)));
8926: if ($entries[0] eq 'Question') {
8927: for (my $i=3;$i<$#entries;$i+=6) {
8928: $$questiontitles[$number]=$entries[$i];
8929: $number++;
8930: }
8931: }
8932: if ($entries[0]=~/^\#/) {
8933: my $id=$entries[0];
8934: my @idresponses;
8935: $id=~s/^[\#0]+//;
8936: for (my $i=0;$i<$number;$i++) {
8937: my $idx=3+$i*6;
8938: push(@idresponses,$entries[$idx]);
8939: }
8940: $$responses{$id}=join(',',@idresponses);
8941: }
8942: }
8943: return ($errormsg,$number);
8944: }
8945:
8946: sub interwrite_eval {
8947: my ($questiontitles,$responses)=@_;
8948: my $number=0;
8949: my $errormsg='';
8950: my $skipline=1;
8951: my $questionnumber=0;
8952: my %idresponses=();
8953: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
8954: my %components=&Apache::loncommon::record_sep($line);
8955: my @entries=map {$components{$_}} (sort(keys(%components)));
8956: if ($entries[1] eq 'Time') { $skipline=0; next; }
8957: if ($entries[1] eq 'Response') { $skipline=1; }
8958: next if $skipline;
8959: if ($entries[0]!=$questionnumber) {
8960: $questionnumber=$entries[0];
8961: $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
8962: $number++;
8963: }
8964: my $id=$entries[4];
8965: $id=~s/^[\#0]+//;
8966: $id=~s/^v\d*\://i;
8967: $id=~s/[\-\:]//g;
8968: $idresponses{$id}[$number]=$entries[6];
8969: }
8970: foreach my $id (keys(%idresponses)) {
8971: $$responses{$id}=join(',',@{$idresponses{$id}});
8972: $$responses{$id}=~s/^\s*\,//;
8973: }
8974: return ($errormsg,$number);
8975: }
8976:
8977: sub assign_clicker_grades {
8978: my ($r)=@_;
8979: my ($symb)=&get_symb($r);
8980: if (!$symb) {return '';}
8981: # See which part we are saving to
8982: my ($partlist,$handgrade,$responseType) = &response_type($symb);
8983: # FIXME: This should probably look for the first handgradeable part
8984: my $part=$$partlist[0];
8985: # Start screen output
8986: my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
8987:
8988: my $heading=&mt('Assigning grades based on clicker file');
8989: $result.=(<<ENDHEADER);
8990: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
8991: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
8992: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
8993: ENDHEADER
8994: # Get correct result
8995: # FIXME: Possibly need delimiter other than ":"
8996: my @correct=();
8997: my $gradingmechanism=$env{'form.gradingmechanism'};
8998: my $number=$env{'form.number'};
8999: if ($gradingmechanism ne 'attendance') {
9000: foreach my $key (keys(%env)) {
9001: if ($key=~/^form\.correct\:/) {
9002: my @input=split(/\,/,$env{$key});
9003: for (my $i=0;$i<=$#input;$i++) {
9004: if (($correct[$i]) && ($input[$i]) &&
9005: ($correct[$i] ne $input[$i])) {
9006: $result.='<br /><span class="LC_warning">'.
9007: &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
9008: $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
9009: } elsif ($input[$i]) {
9010: $correct[$i]=$input[$i];
9011: }
9012: }
9013: }
9014: }
9015: for (my $i=0;$i<$number;$i++) {
9016: if (!$correct[$i]) {
9017: $result.='<br /><span class="LC_error">'.
9018: &mt('No correct result given for question "[_1]"!',
9019: $env{'form.question:'.$i}).'</span>';
9020: }
9021: }
9022: $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
9023: }
9024: # Start grading
9025: my $pcorrect=$env{'form.pcorrect'};
9026: my $pincorrect=$env{'form.pincorrect'};
9027: my $storecount=0;
9028: foreach my $key (keys(%env)) {
9029: my $user='';
9030: if ($key=~/^form\.student\:(.*)$/) {
9031: $user=$1;
9032: }
9033: if ($key=~/^form\.unknown\:(.*)$/) {
9034: my $id=$1;
9035: if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
9036: $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
9037: } elsif ($env{'form.multi'.$id}) {
9038: $user=$env{'form.multi'.$id};
9039: }
9040: }
9041: if ($user) {
9042: my @answer=split(/\,/,$env{$key});
9043: my $sum=0;
9044: my $realnumber=$number;
9045: for (my $i=0;$i<$number;$i++) {
9046: if ($answer[$i]) {
9047: if ($gradingmechanism eq 'attendance') {
9048: $sum+=$pcorrect;
9049: } elsif ($answer[$i] eq '*') {
9050: $sum+=$pcorrect;
9051: } elsif ($answer[$i] eq '-') {
9052: $realnumber--;
9053: } else {
9054: if ($answer[$i] eq $correct[$i]) {
9055: $sum+=$pcorrect;
9056: } else {
9057: $sum+=$pincorrect;
9058: }
9059: }
9060: }
9061: }
9062: my $ave=$sum/(100*$realnumber);
9063: # Store
9064: my ($username,$domain)=split(/\:/,$user);
9065: my %grades=();
9066: $grades{"resource.$part.solved"}='correct_by_override';
9067: $grades{"resource.$part.awarded"}=$ave;
9068: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
9069: my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
9070: $env{'request.course.id'},
9071: $domain,$username);
9072: if ($returncode ne 'ok') {
9073: $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
9074: } else {
9075: $storecount++;
9076: }
9077: }
9078: }
9079: # We are done
9080: $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
9081: '</td></tr></table>'."\n".
9082: '</td></tr></table><br /><br />'."\n";
9083: return $result.&show_grading_menu_form($symb);
9084: }
9085:
9086: sub handler {
9087: my $request=$_[0];
9088: &reset_caches();
9089: if ($env{'browser.mathml'}) {
9090: &Apache::loncommon::content_type($request,'text/xml');
9091: } else {
9092: &Apache::loncommon::content_type($request,'text/html');
9093: }
9094: $request->send_http_header;
9095: return '' if $request->header_only;
9096: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
9097: my $symb=&get_symb($request,1);
9098: my @commands=&Apache::loncommon::get_env_multiple('form.command');
9099: my $command=$commands[0];
9100:
9101: if ($#commands > 0) {
9102: &Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
9103: }
9104:
9105: $ssi_error = 0;
9106: my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
9107: $request->print(&Apache::loncommon::start_page('Grading',undef,
9108: {'bread_crumbs' => $brcrum}));
9109: if ($symb eq '' && $command eq '') {
9110: if ($env{'user.adv'}) {
9111: if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
9112: ($env{'form.codethree'})) {
9113: my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
9114: $env{'form.codethree'};
9115: my ($tsymb,$tuname,$tudom,$tcrsid)=
9116: &Apache::lonnet::checkin($token);
9117: if ($tsymb) {
9118: my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
9119: if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
9120: $request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
9121: ('grade_username' => $tuname,
9122: 'grade_domain' => $tudom,
9123: 'grade_courseid' => $tcrsid,
9124: 'grade_symb' => $tsymb)));
9125: } else {
9126: $request->print('<h3>Not authorized: '.$token.'</h3>');
9127: }
9128: } else {
9129: $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
9130: }
9131: } else {
9132: $request->print(&Apache::lonxml::tokeninputfield());
9133: }
9134: }
9135: } else {
9136: &init_perm();
9137: if ($command eq 'submission' && $perm{'vgr'}) {
9138: ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
9139: } elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
9140: &pickStudentPage($request);
9141: } elsif ($command eq 'displayPage' && $perm{'vgr'}) {
9142: &displayPage($request);
9143: } elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
9144: &updateGradeByPage($request);
9145: } elsif ($command eq 'processGroup' && $perm{'vgr'}) {
9146: &processGroup($request);
9147: } elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
9148: $request->print(&grading_menu($request));
9149: } elsif ($command eq 'submit_options' && $perm{'vgr'}) {
9150: $request->print(&submit_options($request));
9151: } elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
9152: $request->print(&viewgrades($request));
9153: } elsif ($command eq 'handgrade' && $perm{'mgr'}) {
9154: $request->print(&processHandGrade($request));
9155: } elsif ($command eq 'editgrades' && $perm{'mgr'}) {
9156: $request->print(&editgrades($request));
9157: } elsif ($command eq 'verify' && $perm{'vgr'}) {
9158: $request->print(&verifyreceipt($request));
9159: } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
9160: $request->print(&process_clicker($request));
9161: } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
9162: $request->print(&process_clicker_file($request));
9163: } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
9164: $request->print(&assign_clicker_grades($request));
9165: } elsif ($command eq 'csvform' && $perm{'mgr'}) {
9166: $request->print(&upcsvScores_form($request));
9167: } elsif ($command eq 'csvupload' && $perm{'mgr'}) {
9168: $request->print(&csvupload($request));
9169: } elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
9170: $request->print(&csvuploadmap($request));
9171: } elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
9172: if ($env{'form.associate'} ne 'Reverse Association') {
9173: $request->print(&csvuploadoptions($request));
9174: } else {
9175: if ( $env{'form.upfile_associate'} ne 'reverse' ) {
9176: $env{'form.upfile_associate'} = 'reverse';
9177: } else {
9178: $env{'form.upfile_associate'} = 'forward';
9179: }
9180: $request->print(&csvuploadmap($request));
9181: }
9182: } elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
9183: $request->print(&csvuploadassign($request));
9184: } elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
9185: $request->print(&scantron_selectphase($request));
9186: } elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
9187: $request->print(&scantron_do_warning($request));
9188: } elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
9189: $request->print(&scantron_validate_file($request));
9190: } elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
9191: $request->print(&scantron_process_students($request));
9192: } elsif ($command eq 'scantronupload' &&
9193: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
9194: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
9195: $request->print(&scantron_upload_scantron_data($request));
9196: } elsif ($command eq 'scantronupload_save' &&
9197: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
9198: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
9199: $request->print(&scantron_upload_scantron_data_save($request));
9200: } elsif ($command eq 'scantron_download' &&
9201: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
9202: $request->print(&scantron_download_scantron_data($request));
9203: } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
9204: $request->print(&checkscantron_results($request));
9205: } elsif ($command) {
9206: $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
9207: }
9208: }
9209: if ($ssi_error) {
9210: &ssi_print_error($request);
9211: }
9212: $request->print(&Apache::loncommon::end_page());
9213: &reset_caches();
9214: return '';
9215: }
9216:
9217: 1;
9218:
9219: __END__;
9220:
9221:
9222: =head1 NAME
9223:
9224: Apache::grades
9225:
9226: =head1 SYNOPSIS
9227:
9228: Handles the viewing of grades.
9229:
9230: This is part of the LearningOnline Network with CAPA project
9231: described at http://www.lon-capa.org.
9232:
9233: =head1 OVERVIEW
9234:
9235: Do an ssi with retries:
9236: While I'd love to factor out this with the vesrion in lonprintout,
9237: 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
9238: I'm not quite ready to invent (e.g. an ssi_with_retry object).
9239:
9240: At least the logic that drives this has been pulled out into loncommon.
9241:
9242:
9243:
9244: ssi_with_retries - Does the server side include of a resource.
9245: if the ssi call returns an error we'll retry it up to
9246: the number of times requested by the caller.
9247: If we still have a proble, no text is appended to the
9248: output and we set some global variables.
9249: to indicate to the caller an SSI error occurred.
9250: All of this is supposed to deal with the issues described
9251: in LonCAPA BZ 5631 see:
9252: http://bugs.lon-capa.org/show_bug.cgi?id=5631
9253: by informing the user that this happened.
9254:
9255: Parameters:
9256: resource - The resource to include. This is passed directly, without
9257: interpretation to lonnet::ssi.
9258: form - The form hash parameters that guide the interpretation of the resource
9259:
9260: retries - Number of retries allowed before giving up completely.
9261: Returns:
9262: On success, returns the rendered resource identified by the resource parameter.
9263: Side Effects:
9264: The following global variables can be set:
9265: ssi_error - If an unrecoverable error occurred this becomes true.
9266: It is up to the caller to initialize this to false
9267: if desired.
9268: ssi_error_resource - If an unrecoverable error occurred, this is the value
9269: of the resource that could not be rendered by the ssi
9270: call.
9271: ssi_error_message - The error string fetched from the ssi response
9272: in the event of an error.
9273:
9274:
9275: =head1 HANDLER SUBROUTINE
9276:
9277: ssi_with_retries()
9278:
9279: =head1 SUBROUTINES
9280:
9281: =over
9282:
9283: =item scantron_get_correction() :
9284:
9285: Builds the interface screen to interact with the operator to fix a
9286: specific error condition in a specific scanline
9287:
9288: Arguments:
9289: $r - Apache request object
9290: $i - number of the current scanline
9291: $scan_record - hash ref as returned from &scantron_parse_scanline()
9292: $scan_config - hash ref as returned from &get_scantron_config()
9293: $line - full contents of the current scanline
9294: $error - error condition, valid values are
9295: 'incorrectCODE', 'duplicateCODE',
9296: 'doublebubble', 'missingbubble',
9297: 'duplicateID', 'incorrectID'
9298: $arg - extra information needed
9299: For errors:
9300: - duplicateID - paper number that this studentID was seen before on
9301: - duplicateCODE - array ref of the paper numbers this CODE was
9302: seen on before
9303: - incorrectCODE - current incorrect CODE
9304: - doublebubble - array ref of the bubble lines that have double
9305: bubble errors
9306: - missingbubble - array ref of the bubble lines that have missing
9307: bubble errors
9308:
9309: =item scantron_get_maxbubble() :
9310:
9311: Returns the maximum number of bubble lines that are expected to
9312: occur. Does this by walking the selected sequence rendering the
9313: resource and then checking &Apache::lonxml::get_problem_counter()
9314: for what the current value of the problem counter is.
9315:
9316: Caches the results to $env{'form.scantron_maxbubble'},
9317: $env{'form.scantron.bubble_lines.n'},
9318: $env{'form.scantron.first_bubble_line.n'} and
9319: $env{"form.scantron.sub_bubblelines.n"}
9320: which are the total number of bubble, lines, the number of bubble
9321: lines for response n and number of the first bubble line for response n,
9322: and a comma separated list of numbers of bubble lines for sub-questions
9323: (for optionresponse, matchresponse, and rankresponse items), for response n.
9324:
9325:
9326: =item scantron_validate_missingbubbles() :
9327:
9328: Validates all scanlines in the selected file to not have any
9329: answers that don't have bubbles that have not been verified
9330: to be bubble free.
9331:
9332: =item scantron_process_students() :
9333:
9334: Routine that does the actual grading of the bubble sheet information.
9335:
9336: The parsed scanline hash is added to %env
9337:
9338: Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
9339: foreach resource , with the form data of
9340:
9341: 'submitted' =>'scantron'
9342: 'grade_target' =>'grade',
9343: 'grade_username'=> username of student
9344: 'grade_domain' => domain of student
9345: 'grade_courseid'=> of course
9346: 'grade_symb' => symb of resource to grade
9347:
9348: This triggers a grading pass. The problem grading code takes care
9349: of converting the bubbled letter information (now in %env) into a
9350: valid submission.
9351:
9352: =item scantron_upload_scantron_data() :
9353:
9354: Creates the screen for adding a new bubble sheet data file to a course.
9355:
9356: =item scantron_upload_scantron_data_save() :
9357:
9358: Adds a provided bubble information data file to the course if user
9359: has the correct privileges to do so.
9360:
9361: =item valid_file() :
9362:
9363: Validates that the requested bubble data file exists in the course.
9364:
9365: =item scantron_download_scantron_data() :
9366:
9367: Shows a list of the three internal files (original, corrected,
9368: skipped) for a specific bubble sheet data file that exists in the
9369: course.
9370:
9371: =item scantron_validate_ID() :
9372:
9373: Validates all scanlines in the selected file to not have any
9374: invalid or underspecified student/employee IDs
9375:
9376: =back
9377:
9378: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>