1: # The LearningOnline Network with CAPA
2: # The LON-CAPA Grading handler
3: #
4: # $Id: grades.pm,v 1.480 2007/11/05 11:46:08 foxr 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: package Apache::grades;
30: use strict;
31: use Apache::style;
32: use Apache::lonxml;
33: use Apache::lonnet;
34: use Apache::loncommon;
35: use Apache::lonhtmlcommon;
36: use Apache::lonnavmaps;
37: use Apache::lonhomework;
38: use Apache::lonpickcode;
39: use Apache::loncoursedata;
40: use Apache::lonmsg();
41: use Apache::Constants qw(:common);
42: use Apache::lonlocal;
43: use Apache::lonenc;
44: use String::Similarity;
45: use Data::Dumper;
46: use LONCAPA;
47:
48: use POSIX qw(floor);
49:
50:
51: my %perm=();
52: my %bubble_lines_per_response = (); # no. bubble lines for each response.
53: # index is "symb.part_id"
54:
55: my %first_bubble_line = (); # First bubble line no. for each bubble.
56:
57: # Save and restore the bubble lines array to the form env.
58:
59:
60: sub save_bubble_lines {
61: foreach my $line (keys(%bubble_lines_per_response)) {
62: $env{"form.scantron.bubblelines.$line"} = $bubble_lines_per_response{$line};
63: $env{"form.scantron.first_bubble_line.$line"} =
64: $first_bubble_line{$line};
65: }
66: }
67:
68:
69: sub restore_bubble_lines {
70: my $line = 0;
71: %bubble_lines_per_response = ();
72: while ($env{"form.scantron.bubblelines.$line"}) {
73: my $value = $env{"form.scantron.bubblelines.$line"};
74: $bubble_lines_per_response{$line} = $value;
75: $first_bubble_line{$line} =
76: $env{"form.scantron.first_bubble_line.$line"};
77: $line++;
78: }
79:
80: }
81:
82: # Given the parsed scanline, get the response for
83: # 'answer' number n:
84:
85: sub get_response_bubbles {
86: my ($parsed_line, $response) = @_;
87:
88:
89: my $bubble_line = $first_bubble_line{$response-1} +1;
90: my $bubble_lines= $bubble_lines_per_response{$response-1};
91:
92: my $selected = "";
93:
94: for (my $bline = 0; $bline < $bubble_lines; $bline++) {
95: $selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
96: $bubble_line++;
97: }
98: return $selected;
99: }
100:
101:
102: # ----- These first few routines are general use routines.----
103:
104: # Return the number of occurences of a pattern in a string.
105:
106: sub occurence_count {
107: my ($string, $pattern) = @_;
108:
109: my @matches = ($string =~ /$pattern/g);
110:
111: return scalar(@matches);
112: }
113:
114:
115: # Take a string known to have digits and convert all the
116: # digits into letters in the range J,A..I.
117:
118: sub digits_to_letters {
119: my ($input) = @_;
120:
121: my @alphabet = ('J', 'A'..'I');
122:
123: my @input = split(//, $input);
124: my $output ='';
125: for (my $i = 0; $i < scalar(@input); $i++) {
126: if ($input[$i] =~ /\d/) {
127: $output .= $alphabet[$input[$i]];
128: } else {
129: $output .= $input[$i];
130: }
131: }
132: return $output;
133: }
134:
135: #
136: # --- Retrieve the parts from the metadata file.---
137: sub getpartlist {
138: my ($symb) = @_;
139:
140: my $navmap = Apache::lonnavmaps::navmap->new();
141: my $res = $navmap->getBySymb($symb);
142: my $partlist = $res->parts();
143: my $url = $res->src();
144: my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
145:
146: my @stores;
147: foreach my $part (@{ $partlist }) {
148: foreach my $key (@metakeys) {
149: if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
150: }
151: }
152: return @stores;
153: }
154:
155: # --- Get the symbolic name of a problem and the url
156: sub get_symb {
157: my ($request,$silent) = @_;
158: (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
159: my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
160: if ($symb eq '') {
161: if (!$silent) {
162: $request->print("Unable to handle ambiguous references:$url:.");
163: return ();
164: }
165: }
166: &Apache::lonenc::check_decrypt(\$symb);
167: return ($symb);
168: }
169:
170: #--- Format fullname, username:domain if different for display
171: #--- Use anywhere where the student names are listed
172: sub nameUserString {
173: my ($type,$fullname,$uname,$udom) = @_;
174: if ($type eq 'header') {
175: return '<b> Fullname </b><span class="LC_internal_info">(Username)</span>';
176: } else {
177: return ' '.$fullname.'<span class="LC_internal_info"> ('.$uname.
178: ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
179: }
180: }
181:
182: #--- Get the partlist and the response type for a given problem. ---
183: #--- Indicate if a response type is coded handgraded or not. ---
184: sub response_type {
185: my ($symb) = shift;
186:
187: my $navmap = Apache::lonnavmaps::navmap->new();
188: my $res = $navmap->getBySymb($symb);
189: my $partlist = $res->parts();
190: my %vPart =
191: map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
192: my (%response_types,%handgrade);
193: foreach my $part (@{ $partlist }) {
194: next if (%vPart && !exists($vPart{$part}));
195:
196: my @types = $res->responseType($part);
197: my @ids = $res->responseIds($part);
198: for (my $i=0; $i < scalar(@ids); $i++) {
199: $response_types{$part}{$ids[$i]} = $types[$i];
200: $handgrade{$part.'_'.$ids[$i]} =
201: &Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
202: '.handgrade',$symb);
203: }
204: }
205: return ($partlist,\%handgrade,\%response_types);
206: }
207:
208: sub flatten_responseType {
209: my ($responseType) = @_;
210: my @part_response_id =
211: map {
212: my $part = $_;
213: map {
214: [$part,$_]
215: } sort(keys(%{ $responseType->{$part} }));
216: } sort(keys(%$responseType));
217: return @part_response_id;
218: }
219:
220: sub get_display_part {
221: my ($partID,$symb)=@_;
222: my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
223: if (defined($display) and $display ne '') {
224: $display.= " (<span class=\"LC_internal_info\">id $partID</span>)";
225: } else {
226: $display=$partID;
227: }
228: return $display;
229: }
230:
231: #--- Show resource title
232: #--- and parts and response type
233: sub showResourceInfo {
234: my ($symb,$probTitle,$checkboxes) = @_;
235: my $col=3;
236: if ($checkboxes) { $col=4; }
237: my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
238: $result .='<table border="0">';
239: my ($partlist,$handgrade,$responseType) = &response_type($symb);
240: my %resptype = ();
241: my $hdgrade='no';
242: my %partsseen;
243: foreach my $partID (sort keys(%$responseType)) {
244: foreach my $resID (sort keys(%{ $responseType->{$partID} })) {
245: my $handgrade=$$handgrade{$partID.'_'.$resID};
246: my $responsetype = $responseType->{$partID}->{$resID};
247: $hdgrade = $handgrade if ($handgrade eq 'yes');
248: $result.='<tr>';
249: if ($checkboxes) {
250: if (exists($partsseen{$partID})) {
251: $result.="<td> </td>";
252: } else {
253: $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
254: }
255: $partsseen{$partID}=1;
256: }
257: my $display_part=&get_display_part($partID,$symb);
258: $result.='<td><b>Part: </b>'.$display_part.' <span class="LC_internal_info">'.
259: $resID.'</span></td>'.
260: '<td><b>Type: </b>'.$responsetype.'</td></tr>';
261: # '<td><b>Handgrade: </b>'.$handgrade.'</td></tr>';
262: }
263: }
264: $result.='</table>'."\n";
265: return $result,$responseType,$hdgrade,$partlist,$handgrade;
266: }
267:
268: sub reset_caches {
269: &reset_analyze_cache();
270: &reset_perm();
271: }
272:
273: {
274: my %analyze_cache;
275:
276: sub reset_analyze_cache {
277: undef(%analyze_cache);
278: }
279:
280: sub get_analyze {
281: my ($symb,$uname,$udom)=@_;
282: my $key = "$symb\0$uname\0$udom";
283: return $analyze_cache{$key} if (exists($analyze_cache{$key}));
284:
285: my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
286: $url=&Apache::lonnet::clutter($url);
287: my $subresult=&Apache::lonnet::ssi($url,
288: ('grade_target' => 'analyze'),
289: ('grade_domain' => $udom),
290: ('grade_symb' => $symb),
291: ('grade_courseid' =>
292: $env{'request.course.id'}),
293: ('grade_username' => $uname));
294: (undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
295: my %analyze=&Apache::lonnet::str2hash($subresult);
296: return $analyze_cache{$key} = \%analyze;
297: }
298:
299: sub get_order {
300: my ($partid,$respid,$symb,$uname,$udom)=@_;
301: my $analyze = &get_analyze($symb,$uname,$udom);
302: return $analyze->{"$partid.$respid.shown"};
303: }
304:
305: sub get_radiobutton_correct_foil {
306: my ($partid,$respid,$symb,$uname,$udom)=@_;
307: my $analyze = &get_analyze($symb,$uname,$udom);
308: foreach my $foil (@{&get_order($partid,$respid,$symb,$uname,$udom)}) {
309: if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
310: return $foil;
311: }
312: }
313: }
314: }
315:
316: #--- Clean response type for display
317: #--- Currently filters option/rank/radiobutton/match/essay/Task
318: # response types only.
319: sub cleanRecord {
320: my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
321: $uname,$udom) = @_;
322: my $grayFont = '<span class="LC_internal_info">';
323: if ($response =~ /^(option|rank)$/) {
324: my %answer=&Apache::lonnet::str2hash($answer);
325: my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
326: my ($toprow,$bottomrow);
327: foreach my $foil (@$order) {
328: if ($grading{$foil} == 1) {
329: $toprow.='<td><b>'.$answer{$foil}.' </b></td>';
330: } else {
331: $toprow.='<td><i>'.$answer{$foil}.' </i></td>';
332: }
333: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
334: }
335: return '<blockquote><table border="1">'.
336: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
337: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
338: $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
339: } elsif ($response eq 'match') {
340: my %answer=&Apache::lonnet::str2hash($answer);
341: my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
342: my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
343: my ($toprow,$middlerow,$bottomrow);
344: foreach my $foil (@$order) {
345: my $item=shift(@items);
346: if ($grading{$foil} == 1) {
347: $toprow.='<td><b>'.$item.' </b></td>';
348: $middlerow.='<td><b>'.$grayFont.$answer{$foil}.' </span></b></td>';
349: } else {
350: $toprow.='<td><i>'.$item.' </i></td>';
351: $middlerow.='<td><i>'.$grayFont.$answer{$foil}.' </span></i></td>';
352: }
353: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
354: }
355: return '<blockquote><table border="1">'.
356: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
357: '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
358: $middlerow.'</tr>'.
359: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
360: $bottomrow.'</tr>'.'</table></blockquote>';
361: } elsif ($response eq 'radiobutton') {
362: my %answer=&Apache::lonnet::str2hash($answer);
363: my ($toprow,$bottomrow);
364: my $correct =
365: &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
366: foreach my $foil (@$order) {
367: if (exists($answer{$foil})) {
368: if ($foil eq $correct) {
369: $toprow.='<td><b>'.&mt('true').'</b></td>';
370: } else {
371: $toprow.='<td><i>'.&mt('true').'</i></td>';
372: }
373: } else {
374: $toprow.='<td>'.&mt('false').'</td>';
375: }
376: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
377: }
378: return '<blockquote><table border="1">'.
379: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
380: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
381: $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
382: } elsif ($response eq 'essay') {
383: if (! exists ($env{'form.'.$symb})) {
384: my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
385: $env{'course.'.$env{'request.course.id'}.'.domain'},
386: $env{'course.'.$env{'request.course.id'}.'.num'});
387:
388: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
389: $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
390: $env{'form.kwclr'} = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
391: $env{'form.kwsize'} = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
392: $env{'form.kwstyle'} = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
393: $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
394: }
395: $answer =~ s-\n-<br />-g;
396: return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
397: } elsif ( $response eq 'organic') {
398: my $result='Smile representation: "<tt>'.$answer.'</tt>"';
399: my $jme=$record->{$version."resource.$partid.$respid.molecule"};
400: $result.=&Apache::chemresponse::jme_img($jme,$answer,400);
401: return $result;
402: } elsif ( $response eq 'Task') {
403: if ( $answer eq 'SUBMITTED') {
404: my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
405: my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
406: return $result;
407: } elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
408: my @matches = grep(/^\Q$version\E.*?\.instance$/,
409: keys(%{$record}));
410: return join('<br />',($version,@matches));
411:
412:
413: } else {
414: my $result =
415: '<p>'
416: .&mt('Overall result: [_1]',
417: $record->{$version."resource.$respid.$partid.status"})
418: .'</p>';
419:
420: $result .= '<ul>';
421: my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
422: keys(%{$record}));
423: foreach my $grade (sort(@grade)) {
424: my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
425: $result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
426: $dim, $record->{$grade}).
427: '</li>';
428: }
429: $result.='</ul>';
430: return $result;
431: }
432: } elsif ( $response =~ m/(?:numerical|formula)/) {
433: $answer =
434: &Apache::loncommon::format_previous_attempt_value('submission',
435: $answer);
436: }
437: return $answer;
438: }
439:
440: #-- A couple of common js functions
441: sub commonJSfunctions {
442: my $request = shift;
443: $request->print(<<COMMONJSFUNCTIONS);
444: <script type="text/javascript" language="javascript">
445: function radioSelection(radioButton) {
446: var selection=null;
447: if (radioButton.length > 1) {
448: for (var i=0; i<radioButton.length; i++) {
449: if (radioButton[i].checked) {
450: return radioButton[i].value;
451: }
452: }
453: } else {
454: if (radioButton.checked) return radioButton.value;
455: }
456: return selection;
457: }
458:
459: function pullDownSelection(selectOne) {
460: var selection="";
461: if (selectOne.length > 1) {
462: for (var i=0; i<selectOne.length; i++) {
463: if (selectOne[i].selected) {
464: return selectOne[i].value;
465: }
466: }
467: } else {
468: // only one value it must be the selected one
469: return selectOne.value;
470: }
471: }
472: </script>
473: COMMONJSFUNCTIONS
474: }
475:
476: #--- Dumps the class list with usernames,list of sections,
477: #--- section, ids and fullnames for each user.
478: sub getclasslist {
479: my ($getsec,$filterlist,$getgroup) = @_;
480: my @getsec;
481: my @getgroup;
482: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
483: if (!ref($getsec)) {
484: if ($getsec ne '' && $getsec ne 'all') {
485: @getsec=($getsec);
486: }
487: } else {
488: @getsec=@{$getsec};
489: }
490: if (grep(/^all$/,@getsec)) { undef(@getsec); }
491: if (!ref($getgroup)) {
492: if ($getgroup ne '' && $getgroup ne 'all') {
493: @getgroup=($getgroup);
494: }
495: } else {
496: @getgroup=@{$getgroup};
497: }
498: if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
499:
500: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
501: # Bail out if we were unable to get the classlist
502: return if (! defined($classlist));
503: &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
504: #
505: my %sections;
506: my %fullnames;
507: foreach my $student (keys(%$classlist)) {
508: my $end =
509: $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
510: my $start =
511: $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
512: my $id =
513: $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
514: my $section =
515: $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
516: my $fullname =
517: $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
518: my $status =
519: $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
520: my $group =
521: $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
522: # filter students according to status selected
523: if ($filterlist && (!($stu_status =~ /Any/))) {
524: if (!($stu_status =~ $status)) {
525: delete($classlist->{$student});
526: next;
527: }
528: }
529: # filter students according to groups selected
530: my @stu_groups = split(/,/,$group);
531: if (@getgroup) {
532: my $exclude = 1;
533: foreach my $grp (@getgroup) {
534: foreach my $stu_group (@stu_groups) {
535: if ($stu_group eq $grp) {
536: $exclude = 0;
537: }
538: }
539: if (($grp eq 'none') && !$group) {
540: $exclude = 0;
541: }
542: }
543: if ($exclude) {
544: delete($classlist->{$student});
545: }
546: }
547: $section = ($section ne '' ? $section : 'none');
548: if (&canview($section)) {
549: if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
550: $sections{$section}++;
551: if ($classlist->{$student}) {
552: $fullnames{$student}=$fullname;
553: }
554: } else {
555: delete($classlist->{$student});
556: }
557: } else {
558: delete($classlist->{$student});
559: }
560: }
561: my %seen = ();
562: my @sections = sort(keys(%sections));
563: return ($classlist,\@sections,\%fullnames);
564: }
565:
566: sub canmodify {
567: my ($sec)=@_;
568: if ($perm{'mgr'}) {
569: if (!defined($perm{'mgr_section'})) {
570: # can modify whole class
571: return 1;
572: } else {
573: if ($sec eq $perm{'mgr_section'}) {
574: #can modify the requested section
575: return 1;
576: } else {
577: # can't modify the request section
578: return 0;
579: }
580: }
581: }
582: #can't modify
583: return 0;
584: }
585:
586: sub canview {
587: my ($sec)=@_;
588: if ($perm{'vgr'}) {
589: if (!defined($perm{'vgr_section'})) {
590: # can modify whole class
591: return 1;
592: } else {
593: if ($sec eq $perm{'vgr_section'}) {
594: #can modify the requested section
595: return 1;
596: } else {
597: # can't modify the request section
598: return 0;
599: }
600: }
601: }
602: #can't modify
603: return 0;
604: }
605:
606: #--- Retrieve the grade status of a student for all the parts
607: sub student_gradeStatus {
608: my ($symb,$udom,$uname,$partlist) = @_;
609: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
610: my %partstatus = ();
611: foreach (@$partlist) {
612: my ($status,undef) = split(/_/,$record{"resource.$_.solved"},2);
613: $status = 'nothing' if ($status eq '');
614: $partstatus{$_} = $status;
615: my $subkey = "resource.$_.submitted_by";
616: $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
617: }
618: return %partstatus;
619: }
620:
621: # hidden form and javascript that calls the form
622: # Use by verifyscript and viewgrades
623: # Shows a student's view of problem and submission
624: sub jscriptNform {
625: my ($symb) = @_;
626: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
627: my $jscript='<script type="text/javascript" language="javascript">'."\n".
628: ' function viewOneStudent(user,domain) {'."\n".
629: ' document.onestudent.student.value = user;'."\n".
630: ' document.onestudent.userdom.value = domain;'."\n".
631: ' document.onestudent.submit();'."\n".
632: ' }'."\n".
633: '</script>'."\n";
634: $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
635: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
636: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
637: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
638: '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
639: '<input type="hidden" name="command" value="submission" />'."\n".
640: '<input type="hidden" name="student" value="" />'."\n".
641: '<input type="hidden" name="userdom" value="" />'."\n".
642: '</form>'."\n";
643: return $jscript;
644: }
645:
646:
647:
648: # Given the score (as a number [0-1] and the weight) what is the final
649: # point value? This function will round to the nearest tenth, third,
650: # or quarter if one of those is within the tolerance of .00001.
651: sub compute_points {
652: my ($score, $weight) = @_;
653:
654: my $tolerance = .00001;
655: my $points = $score * $weight;
656:
657: # Check for nearness to 1/x.
658: my $check_for_nearness = sub {
659: my ($factor) = @_;
660: my $num = ($points * $factor) + $tolerance;
661: my $floored_num = floor($num);
662: if ($num - $floored_num < 2 * $tolerance * $factor) {
663: return $floored_num / $factor;
664: }
665: return $points;
666: };
667:
668: $points = $check_for_nearness->(10);
669: $points = $check_for_nearness->(3);
670: $points = $check_for_nearness->(4);
671:
672: return $points;
673: }
674:
675: #------------------ End of general use routines --------------------
676:
677: #
678: # Find most similar essay
679: #
680:
681: sub most_similar {
682: my ($uname,$udom,$uessay,$old_essays)=@_;
683:
684: # ignore spaces and punctuation
685:
686: $uessay=~s/\W+/ /gs;
687:
688: # ignore empty submissions (occuring when only files are sent)
689:
690: unless ($uessay=~/\w+/) { return ''; }
691:
692: # these will be returned. Do not care if not at least 50 percent similar
693: my $limit=0.6;
694: my $sname='';
695: my $sdom='';
696: my $scrsid='';
697: my $sessay='';
698: # go through all essays ...
699: foreach my $tkey (keys(%$old_essays)) {
700: my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
701: # ... except the same student
702: next if (($tname eq $uname) && ($tdom eq $udom));
703: my $tessay=$old_essays->{$tkey};
704: $tessay=~s/\W+/ /gs;
705: # String similarity gives up if not even limit
706: my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
707: # Found one
708: if ($tsimilar>$limit) {
709: $limit=$tsimilar;
710: $sname=$tname;
711: $sdom=$tdom;
712: $scrsid=$tcrsid;
713: $sessay=$old_essays->{$tkey};
714: }
715: }
716: if ($limit>0.6) {
717: return ($sname,$sdom,$scrsid,$sessay,$limit);
718: } else {
719: return ('','','','',0);
720: }
721: }
722:
723: #-------------------------------------------------------------------
724:
725: #------------------------------------ Receipt Verification Routines
726: #
727: #--- Check whether a receipt number is valid.---
728: sub verifyreceipt {
729: my $request = shift;
730:
731: my $courseid = $env{'request.course.id'};
732: my $receipt = &Apache::lonnet::recprefix($courseid).'-'.
733: $env{'form.receipt'};
734: $receipt =~ s/[^\-\d]//g;
735: my ($symb) = &get_symb($request);
736:
737: my $title.='<h3><span class="LC_info">Verifying Submission Receipt '.
738: $receipt.'</h3></span>'."\n".
739: '<h4><b>Resource: </b>'.$env{'form.probTitle'}.'</h4><br /><br />'."\n";
740:
741: my ($string,$contents,$matches) = ('','',0);
742: my (undef,undef,$fullname) = &getclasslist('all','0');
743:
744: my $receiptparts=0;
745: if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
746: $env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
747: my $parts=['0'];
748: if ($receiptparts) { ($parts)=&response_type($symb); }
749: foreach (sort
750: {
751: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
752: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
753: }
754: return $a cmp $b;
755: } (keys(%$fullname))) {
756: my ($uname,$udom)=split(/\:/);
757: foreach my $part (@$parts) {
758: if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
759: $contents.='<tr bgcolor="#ffffe6"><td> '."\n".
760: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
761: '\');" target="_self">'.$$fullname{$_}.'</a> </td>'."\n".
762: '<td> '.$uname.' </td>'.
763: '<td> '.$udom.' </td>';
764: if ($receiptparts) {
765: $contents.='<td> '.$part.' </td>';
766: }
767: $contents.='</tr>'."\n";
768:
769: $matches++;
770: }
771: }
772: }
773: if ($matches == 0) {
774: $string = $title.'No match found for the above receipt.';
775: } else {
776: $string = &jscriptNform($symb).$title.
777: 'The above receipt matches the following student'.
778: ($matches <= 1 ? '.' : 's.')."\n".
779: '<table border="0"><tr><td bgcolor="#777777">'."\n".
780: '<table border="0"><tr bgcolor="#e6ffff">'."\n".
781: '<td><b> Fullname </b></td>'."\n".
782: '<td><b> Username </b></td>'."\n".
783: '<td><b> Domain </b></td>';
784: if ($receiptparts) {
785: $string.='<td> Problem Part </td>';
786: }
787: $string.='</tr>'."\n".$contents.
788: '</table></td></tr></table>'."\n";
789: }
790: return $string.&show_grading_menu_form($symb);
791: }
792:
793: #--- This is called by a number of programs.
794: #--- Called from the Grading Menu - View/Grade an individual student
795: #--- Also called directly when one clicks on the subm button
796: # on the problem page.
797: sub listStudents {
798: my ($request) = shift;
799:
800: my ($symb) = &get_symb($request);
801: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
802: my $cnum = $env{"course.$env{'request.course.id'}.num"};
803: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
804: my $getgroup = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
805: my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
806: my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
807: $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ?
808: &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
809:
810: my $result='<h3><span class="LC_info"> '.$viewgrade.
811: ' Submissions for a Student or a Group of Students</span></h3>';
812:
813: my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
814:
815: $request->print(<<LISTJAVASCRIPT);
816: <script type="text/javascript" language="javascript">
817: function checkSelect(checkBox) {
818: var ctr=0;
819: var sense="";
820: if (checkBox.length > 1) {
821: for (var i=0; i<checkBox.length; i++) {
822: if (checkBox[i].checked) {
823: ctr++;
824: }
825: }
826: sense = "a student or group of students";
827: } else {
828: if (checkBox.checked) {
829: ctr = 1;
830: }
831: sense = "the student";
832: }
833: if (ctr == 0) {
834: alert("Please select "+sense+" before clicking on the Next button.");
835: return false;
836: }
837: document.gradesub.submit();
838: }
839:
840: function reLoadList(formname) {
841: if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
842: formname.command.value = 'submission';
843: formname.submit();
844: }
845: </script>
846: LISTJAVASCRIPT
847:
848: &commonJSfunctions($request);
849: $request->print($result);
850:
851: my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
852: my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
853: my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
854: "\n".$table.
855: ' <b>View Problem Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
856: '<label><input type="radio" name="vProb" value="yes" /> one student </label>'."\n".
857: '<label><input type="radio" name="vProb" value="all" /> all students </label><br />'."\n".
858: ' <b>View Answer: </b><label><input type="radio" name="vAns" value="no" /> no </label>'."\n".
859: '<label><input type="radio" name="vAns" value="yes" /> one student </label>'."\n".
860: '<label><input type="radio" name="vAns" value="all" checked="checked" /> all students </label><br />'."\n".
861: ' <b>Submissions: </b>'."\n";
862: if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
863: $gradeTable.='<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> essay part only </label>'."\n";
864: }
865: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
866: my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
867: $env{'form.Status'} = $saveStatus;
868: $gradeTable.='<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> last submission only </label>'."\n".
869: '<label><input type="radio" name="lastSub" value="last" /> last submission & parts info </label>'."\n".
870: '<label><input type="radio" name="lastSub" value="datesub" /> by dates and submissions </label>'."\n".
871: '<label><input type="radio" name="lastSub" value="all" /> all details</label><br />'."\n".
872: ' <b>Grading Increments:</b> <select name="increment">'.
873: '<option value="1">Whole Points</option>'.
874: '<option value=".5">Half Points</option>'.
875: '<option value=".25">Quarter Points</option>'.
876: '<option value=".1">Tenths of a Point</option>'.
877: '</select>'.
878: &build_section_inputs().
879: '<input type="hidden" name="submitonly" value="'.$submitonly.'" />'."\n".
880: '<input type="hidden" name="handgrade" value="'.$env{'form.handgrade'}.'" /><br />'."\n".
881: '<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
882: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
883: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
884: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
885: '<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
886:
887: if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
888: $gradeTable.='<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
889: } else {
890: $gradeTable.='<b>Student Status:</b> '.
891: &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);').'<br />';
892: }
893:
894: $gradeTable.='To '.lc($viewgrade).' a submission or a group of submissions, click on the check box(es) '.
895: 'next to the student\'s name(s). Then click on the Next button.<br />'."\n".
896: '<input type="hidden" name="command" value="processGroup" />'."\n";
897:
898: # checkall buttons
899: $gradeTable.=&check_script('gradesub', 'stuinfo');
900: $gradeTable.='<input type="button" '."\n".
901: 'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
902: 'value="Next->" /> <br />'."\n";
903: $gradeTable.=&check_buttons();
904: $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />Check For Plagiarism</label>';
905: my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
906: $gradeTable.= &Apache::loncommon::start_data_table().
907: &Apache::loncommon::start_data_table_header_row();
908: my $loop = 0;
909: while ($loop < 2) {
910: $gradeTable.='<th>No.</th><th>Select</th>'.
911: '<th>'.&nameUserString('header').' '.'Section/Group</th>';
912: if ($env{'form.showgrading'} eq 'yes'
913: && $submitonly ne 'queued'
914: && $submitonly ne 'all') {
915: foreach (sort(@$partlist)) {
916: my $display_part=&get_display_part((split(/_/))[0],$symb);
917: $gradeTable.='<th>Part: '.$display_part.
918: ' Status</h>';
919: }
920: } elsif ($submitonly eq 'queued') {
921: $gradeTable.='<th>'.&mt('Queue Status').' </th>';
922: }
923: $loop++;
924: # $gradeTable.='<td></td>' if ($loop%2 ==1);
925: }
926: $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
927:
928: my $ctr = 0;
929: foreach my $student (sort
930: {
931: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
932: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
933: }
934: return $a cmp $b;
935: }
936: (keys(%$fullname))) {
937: my ($uname,$udom) = split(/:/,$student);
938:
939: my %status = ();
940:
941: if ($submitonly eq 'queued') {
942: my %queue_status =
943: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
944: $udom,$uname);
945: next if (!defined($queue_status{'gradingqueue'}));
946: $status{'gradingqueue'} = $queue_status{'gradingqueue'};
947: }
948:
949: if ($env{'form.showgrading'} eq 'yes'
950: && $submitonly ne 'queued'
951: && $submitonly ne 'all') {
952: (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
953: my $submitted = 0;
954: my $graded = 0;
955: my $incorrect = 0;
956: foreach (keys(%status)) {
957: $submitted = 1 if ($status{$_} ne 'nothing');
958: $graded = 1 if ($status{$_} =~ /^ungraded/);
959: $incorrect = 1 if ($status{$_} =~ /^incorrect/);
960:
961: my ($foo,$partid,$foo1) = split(/\./,$_);
962: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
963: $submitted = 0;
964: my ($part)=split(/\./,$partid);
965: $gradeTable.='<input type="hidden" name="'.
966: $student.':'.$part.':submitted_by" value="'.
967: $status{'resource.'.$partid.'.submitted_by'}.'" />';
968: }
969: }
970:
971: next if (!$submitted && ($submitonly eq 'yes' ||
972: $submitonly eq 'incorrect' ||
973: $submitonly eq 'graded'));
974: next if (!$graded && ($submitonly eq 'graded'));
975: next if (!$incorrect && $submitonly eq 'incorrect');
976: }
977:
978: $ctr++;
979: my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
980: my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
981: if ( $perm{'vgr'} eq 'F' ) {
982: if ($ctr%2 ==1) {
983: $gradeTable.= &Apache::loncommon::start_data_table_row();
984: }
985: $gradeTable.='<td align="right">'.$ctr.' </td>'.
986: '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
987: $student.':'.$$fullname{$student}.':::SECTION'.$section.
988: ') " /> </label></td>'."\n".'<td>'.
989: &nameUserString(undef,$$fullname{$student},$uname,$udom).
990: ' '.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
991:
992: if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
993: foreach (sort keys(%status)) {
994: next if (/^resource.*?submitted_by$/);
995: $gradeTable.='<td align="center"> '.$status{$_}.' </td>'."\n";
996: }
997: }
998: # $gradeTable.='<td></td>' if ($ctr%2 ==1);
999: if ($ctr%2 ==0) {
1000: $gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
1001: }
1002: }
1003: }
1004: if ($ctr%2 ==1) {
1005: $gradeTable.='<td> </td><td> </td><td> </td>';
1006: if ($env{'form.showgrading'} eq 'yes'
1007: && $submitonly ne 'queued'
1008: && $submitonly ne 'all') {
1009: foreach (@$partlist) {
1010: $gradeTable.='<td> </td>';
1011: }
1012: } elsif ($submitonly eq 'queued') {
1013: $gradeTable.='<td> </td>';
1014: }
1015: $gradeTable.=&Apache::loncommon::end_data_table_row();
1016: }
1017:
1018: $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1019: '<input type="button" '.
1020: 'onClick="javascript:checkSelect(this.form.stuinfo);" '.
1021: 'value="Next->" /></form>'."\n";
1022: if ($ctr == 0) {
1023: my $num_students=(scalar(keys(%$fullname)));
1024: if ($num_students eq 0) {
1025: $gradeTable='<br /> <span class="LC_warning">There are no students currently enrolled.</span>';
1026: } else {
1027: my $submissions='submissions';
1028: if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
1029: if ($submitonly eq 'graded' ) { $submissions = 'ungraded submissions'; }
1030: if ($submitonly eq 'queued' ) { $submissions = 'queued submissions'; }
1031: $gradeTable='<br /> <span class="LC_warning">'.
1032: 'No '.$submissions.' found for this resource for any students. ('.$num_students.
1033: ' students checked for '.$submissions.')</span><br />';
1034: }
1035: } elsif ($ctr == 1) {
1036: $gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1037: }
1038: $gradeTable.=&show_grading_menu_form($symb);
1039: $request->print($gradeTable);
1040: return '';
1041: }
1042:
1043: #---- Called from the listStudents routine
1044:
1045: sub check_script {
1046: my ($form, $type)=@_;
1047: my $chkallscript='<script type="text/javascript">
1048: function checkall() {
1049: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1050: ele = document.forms.'.$form.'.elements[i];
1051: if (ele.name == "'.$type.'") {
1052: document.forms.'.$form.'.elements[i].checked=true;
1053: }
1054: }
1055: }
1056:
1057: function checksec() {
1058: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1059: ele = document.forms.'.$form.'.elements[i];
1060: string = document.forms.'.$form.'.chksec.value;
1061: if
1062: (ele.value.indexOf(":::SECTION"+string)>0) {
1063: document.forms.'.$form.'.elements[i].checked=true;
1064: }
1065: }
1066: }
1067:
1068:
1069: function uncheckall() {
1070: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1071: ele = document.forms.'.$form.'.elements[i];
1072: if (ele.name == "'.$type.'") {
1073: document.forms.'.$form.'.elements[i].checked=false;
1074: }
1075: }
1076: }
1077:
1078: </script>'."\n";
1079: return $chkallscript;
1080: }
1081:
1082: sub check_buttons {
1083: my $buttons.='<input type="button" onclick="checkall()" value="Check All" />';
1084: $buttons.='<input type="button" onclick="uncheckall()" value="Uncheck All" /> ';
1085: $buttons.='<input type="button" onclick="checksec()" value="Check Section/Group" />';
1086: $buttons.='<input type="text" size="5" name="chksec" /> ';
1087: return $buttons;
1088: }
1089:
1090: # Displays the submissions for one student or a group of students
1091: sub processGroup {
1092: my ($request) = shift;
1093: my $ctr = 0;
1094: my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1095: my $total = scalar(@stuchecked)-1;
1096:
1097: foreach my $student (@stuchecked) {
1098: my ($uname,$udom,$fullname) = split(/:/,$student);
1099: $env{'form.student'} = $uname;
1100: $env{'form.userdom'} = $udom;
1101: $env{'form.fullname'} = $fullname;
1102: &submission($request,$ctr,$total);
1103: $ctr++;
1104: }
1105: return '';
1106: }
1107:
1108: #------------------------------------------------------------------------------------
1109: #
1110: #-------------------------- Next few routines handles grading by student, essentially
1111: # handles essay response type problem/part
1112: #
1113: #--- Javascript to handle the submission page functionality ---
1114: sub sub_page_js {
1115: my $request = shift;
1116: $request->print(<<SUBJAVASCRIPT);
1117: <script type="text/javascript" language="javascript">
1118: function updateRadio(formname,id,weight) {
1119: var gradeBox = formname["GD_BOX"+id];
1120: var radioButton = formname["RADVAL"+id];
1121: var oldpts = formname["oldpts"+id].value;
1122: var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1123: gradeBox.value = pts;
1124: var resetbox = false;
1125: if (isNaN(pts) || pts < 0) {
1126: alert("A number equal or greater than 0 is expected. Entered value = "+pts);
1127: for (var i=0; i<radioButton.length; i++) {
1128: if (radioButton[i].checked) {
1129: gradeBox.value = i;
1130: resetbox = true;
1131: }
1132: }
1133: if (!resetbox) {
1134: formtextbox.value = "";
1135: }
1136: return;
1137: }
1138:
1139: if (pts > weight) {
1140: var resp = confirm("You entered a value ("+pts+
1141: ") greater than the weight for the part. Accept?");
1142: if (resp == false) {
1143: gradeBox.value = oldpts;
1144: return;
1145: }
1146: }
1147:
1148: for (var i=0; i<radioButton.length; i++) {
1149: radioButton[i].checked=false;
1150: if (pts == i && pts != "") {
1151: radioButton[i].checked=true;
1152: }
1153: }
1154: updateSelect(formname,id);
1155: formname["stores"+id].value = "0";
1156: }
1157:
1158: function writeBox(formname,id,pts) {
1159: var gradeBox = formname["GD_BOX"+id];
1160: if (checkSolved(formname,id) == 'update') {
1161: gradeBox.value = pts;
1162: } else {
1163: var oldpts = formname["oldpts"+id].value;
1164: gradeBox.value = oldpts;
1165: var radioButton = formname["RADVAL"+id];
1166: for (var i=0; i<radioButton.length; i++) {
1167: radioButton[i].checked=false;
1168: if (i == oldpts) {
1169: radioButton[i].checked=true;
1170: }
1171: }
1172: }
1173: formname["stores"+id].value = "0";
1174: updateSelect(formname,id);
1175: return;
1176: }
1177:
1178: function clearRadBox(formname,id) {
1179: if (checkSolved(formname,id) == 'noupdate') {
1180: updateSelect(formname,id);
1181: return;
1182: }
1183: gradeSelect = formname["GD_SEL"+id];
1184: for (var i=0; i<gradeSelect.length; i++) {
1185: if (gradeSelect[i].selected) {
1186: var selectx=i;
1187: }
1188: }
1189: var stores = formname["stores"+id];
1190: if (selectx == stores.value) { return };
1191: var gradeBox = formname["GD_BOX"+id];
1192: gradeBox.value = "";
1193: var radioButton = formname["RADVAL"+id];
1194: for (var i=0; i<radioButton.length; i++) {
1195: radioButton[i].checked=false;
1196: }
1197: stores.value = selectx;
1198: }
1199:
1200: function checkSolved(formname,id) {
1201: if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1202: var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
1203: if (!reply) {return "noupdate";}
1204: formname.overRideScore.value = 'yes';
1205: }
1206: return "update";
1207: }
1208:
1209: function updateSelect(formname,id) {
1210: formname["GD_SEL"+id][0].selected = true;
1211: return;
1212: }
1213:
1214: //=========== Check that a point is assigned for all the parts ============
1215: function checksubmit(formname,val,total,parttot) {
1216: formname.gradeOpt.value = val;
1217: if (val == "Save & Next") {
1218: for (i=0;i<=total;i++) {
1219: for (j=0;j<parttot;j++) {
1220: var partid = formname["partid"+i+"_"+j].value;
1221: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1222: var points = formname["GD_BOX"+i+"_"+partid].value;
1223: if (points == "") {
1224: var name = formname["name"+i].value;
1225: var studentID = (name != '' ? name : formname["unamedom"+i].value);
1226: var resp = confirm("You did not assign a score for "+studentID+
1227: ", part "+partid+". Continue?");
1228: if (resp == false) {
1229: formname["GD_BOX"+i+"_"+partid].focus();
1230: return false;
1231: }
1232: }
1233: }
1234:
1235: }
1236: }
1237:
1238: }
1239: if (val == "Grade Student") {
1240: formname.showgrading.value = "yes";
1241: if (formname.Status.value == "") {
1242: formname.Status.value = "Active";
1243: }
1244: formname.studentNo.value = total;
1245: }
1246: formname.submit();
1247: }
1248:
1249: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
1250: function checkSubmitPage(formname,total) {
1251: noscore = new Array(100);
1252: var ptr = 0;
1253: for (i=1;i<total;i++) {
1254: var partid = formname["q_"+i].value;
1255: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1256: var points = formname["GD_BOX"+i+"_"+partid].value;
1257: var status = formname["solved"+i+"_"+partid].value;
1258: if (points == "" && status != "correct_by_student") {
1259: noscore[ptr] = i;
1260: ptr++;
1261: }
1262: }
1263: }
1264: if (ptr != 0) {
1265: var sense = ptr == 1 ? ": " : "s: ";
1266: var prolist = "";
1267: if (ptr == 1) {
1268: prolist = noscore[0];
1269: } else {
1270: var i = 0;
1271: while (i < ptr-1) {
1272: prolist += noscore[i]+", ";
1273: i++;
1274: }
1275: prolist += "and "+noscore[i];
1276: }
1277: var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
1278: if (resp == false) {
1279: return false;
1280: }
1281: }
1282:
1283: formname.submit();
1284: }
1285: </script>
1286: SUBJAVASCRIPT
1287: }
1288:
1289: #--- javascript for essay type problem --
1290: sub sub_page_kw_js {
1291: my $request = shift;
1292: my $iconpath = $request->dir_config('lonIconsURL');
1293: &commonJSfunctions($request);
1294:
1295: my $inner_js_msg_central=<<INNERJS;
1296: <script text="text/javascript">
1297: function checkInput() {
1298: opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
1299: var nmsg = opener.document.SCORE.savemsgN.value;
1300: var usrctr = document.msgcenter.usrctr.value;
1301: var newval = opener.document.SCORE["newmsg"+usrctr];
1302: newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
1303:
1304: var msgchk = "";
1305: if (document.msgcenter.subchk.checked) {
1306: msgchk = "msgsub,";
1307: }
1308: var includemsg = 0;
1309: for (var i=1; i<=nmsg; i++) {
1310: var opnmsg = opener.document.SCORE["savemsg"+i];
1311: var frmmsg = document.msgcenter["msg"+i];
1312: opnmsg.value = opener.checkEntities(frmmsg.value);
1313: var showflg = opener.document.SCORE["shownOnce"+i];
1314: showflg.value = "1";
1315: var chkbox = document.msgcenter["msgn"+i];
1316: if (chkbox.checked) {
1317: msgchk += "savemsg"+i+",";
1318: includemsg = 1;
1319: }
1320: }
1321: if (document.msgcenter.newmsgchk.checked) {
1322: msgchk += "newmsg"+usrctr;
1323: includemsg = 1;
1324: }
1325: imgformname = opener.document.SCORE["mailicon"+usrctr];
1326: imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
1327: var includemsg = opener.document.SCORE["includemsg"+usrctr];
1328: includemsg.value = msgchk;
1329:
1330: self.close()
1331:
1332: }
1333: </script>
1334: INNERJS
1335:
1336: my $inner_js_highlight_central=<<INNERJS;
1337: <script type="text/javascript">
1338: function updateChoice(flag) {
1339: opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
1340: opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
1341: opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
1342: opener.document.SCORE.refresh.value = "on";
1343: if (opener.document.SCORE.keywords.value!=""){
1344: opener.document.SCORE.submit();
1345: }
1346: self.close()
1347: }
1348: </script>
1349: INNERJS
1350:
1351: my $start_page_msg_central =
1352: &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
1353: {'js_ready' => 1,
1354: 'only_body' => 1,
1355: 'bgcolor' =>'#FFFFFF',});
1356: my $end_page_msg_central =
1357: &Apache::loncommon::end_page({'js_ready' => 1});
1358:
1359:
1360: my $start_page_highlight_central =
1361: &Apache::loncommon::start_page('Highlight Central',
1362: $inner_js_highlight_central,
1363: {'js_ready' => 1,
1364: 'only_body' => 1,
1365: 'bgcolor' =>'#FFFFFF',});
1366: my $end_page_highlight_central =
1367: &Apache::loncommon::end_page({'js_ready' => 1});
1368:
1369: my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1370: $docopen=~s/^document\.//;
1371: $request->print(<<SUBJAVASCRIPT);
1372: <script type="text/javascript" language="javascript">
1373:
1374: //===================== Show list of keywords ====================
1375: function keywords(formname) {
1376: var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1377: if (nret==null) return;
1378: formname.keywords.value = nret;
1379:
1380: if (formname.keywords.value != "") {
1381: formname.refresh.value = "on";
1382: formname.submit();
1383: }
1384: return;
1385: }
1386:
1387: //===================== Script to view submitted by ==================
1388: function viewSubmitter(submitter) {
1389: document.SCORE.refresh.value = "on";
1390: document.SCORE.NCT.value = "1";
1391: document.SCORE.unamedom0.value = submitter;
1392: document.SCORE.submit();
1393: return;
1394: }
1395:
1396: //===================== Script to add keyword(s) ==================
1397: function getSel() {
1398: if (document.getSelection) txt = document.getSelection();
1399: else if (document.selection) txt = document.selection.createRange().text;
1400: else return;
1401: var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
1402: if (cleantxt=="") {
1403: alert("Please select a word or group of words from document and then click this link.");
1404: return;
1405: }
1406: var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
1407: if (nret==null) return;
1408: document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1409: if (document.SCORE.keywords.value != "") {
1410: document.SCORE.refresh.value = "on";
1411: document.SCORE.submit();
1412: }
1413: return;
1414: }
1415:
1416: //====================== Script for composing message ==============
1417: // preload images
1418: img1 = new Image();
1419: img1.src = "$iconpath/mailbkgrd.gif";
1420: img2 = new Image();
1421: img2.src = "$iconpath/mailto.gif";
1422:
1423: function msgCenter(msgform,usrctr,fullname) {
1424: var Nmsg = msgform.savemsgN.value;
1425: savedMsgHeader(Nmsg,usrctr,fullname);
1426: var subject = msgform.msgsub.value;
1427: var msgchk = document.SCORE["includemsg"+usrctr].value;
1428: re = /msgsub/;
1429: var shwsel = "";
1430: if (re.test(msgchk)) { shwsel = "checked" }
1431: subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
1432: displaySubject(checkEntities(subject),shwsel);
1433: for (var i=1; i<=Nmsg; i++) {
1434: var testmsg = "savemsg"+i+",";
1435: re = new RegExp(testmsg,"g");
1436: shwsel = "";
1437: if (re.test(msgchk)) { shwsel = "checked" }
1438: var message = document.SCORE["savemsg"+i].value;
1439: message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1440: displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
1441: //any < is already converted to <, etc. However, only once!!
1442: }
1443: newmsg = document.SCORE["newmsg"+usrctr].value;
1444: shwsel = "";
1445: re = /newmsg/;
1446: if (re.test(msgchk)) { shwsel = "checked" }
1447: newMsg(newmsg,shwsel);
1448: msgTail();
1449: return;
1450: }
1451:
1452: function checkEntities(strx) {
1453: if (strx.length == 0) return strx;
1454: var orgStr = ["&", "<", ">", '"'];
1455: var newStr = ["&", "<", ">", """];
1456: var counter = 0;
1457: while (counter < 4) {
1458: strx = strReplace(strx,orgStr[counter],newStr[counter]);
1459: counter++;
1460: }
1461: return strx;
1462: }
1463:
1464: function strReplace(strx, orgStr, newStr) {
1465: return strx.split(orgStr).join(newStr);
1466: }
1467:
1468: function savedMsgHeader(Nmsg,usrctr,fullname) {
1469: var height = 70*Nmsg+250;
1470: var scrollbar = "no";
1471: if (height > 600) {
1472: height = 600;
1473: scrollbar = "yes";
1474: }
1475: var xpos = (screen.width-600)/2;
1476: xpos = (xpos < 0) ? '0' : xpos;
1477: var ypos = (screen.height-height)/2-30;
1478: ypos = (ypos < 0) ? '0' : ypos;
1479:
1480: pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1481: pWin.focus();
1482: pDoc = pWin.document;
1483: pDoc.$docopen;
1484: pDoc.write('$start_page_msg_central');
1485:
1486: pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
1487: pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1488: pDoc.write("<h3><span class=\\"LC_info\\"> Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
1489:
1490: pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
1491: pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
1492: pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
1493: }
1494: function displaySubject(msg,shwsel) {
1495: pDoc = pWin.document;
1496: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1497: pDoc.write("<td>Subject<\\/td>");
1498: pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1499: pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1500: }
1501:
1502: function displaySavedMsg(ctr,msg,shwsel) {
1503: pDoc = pWin.document;
1504: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1505: pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
1506: pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1507: pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1508: }
1509:
1510: function newMsg(newmsg,shwsel) {
1511: pDoc = pWin.document;
1512: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1513: pDoc.write("<td align=\\"center\\">New<\\/td>");
1514: pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1515: pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1516: }
1517:
1518: function msgTail() {
1519: pDoc = pWin.document;
1520: pDoc.write("<\\/table>");
1521: pDoc.write("<\\/td><\\/tr><\\/table> ");
1522: pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\"> ");
1523: pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1524: pDoc.write("<\\/form>");
1525: pDoc.write('$end_page_msg_central');
1526: pDoc.close();
1527: }
1528:
1529: //====================== Script for keyword highlight options ==============
1530: function kwhighlight() {
1531: var kwclr = document.SCORE.kwclr.value;
1532: var kwsize = document.SCORE.kwsize.value;
1533: var kwstyle = document.SCORE.kwstyle.value;
1534: var redsel = "";
1535: var grnsel = "";
1536: var blusel = "";
1537: if (kwclr=="red") {var redsel="checked"};
1538: if (kwclr=="green") {var grnsel="checked"};
1539: if (kwclr=="blue") {var blusel="checked"};
1540: var sznsel = "";
1541: var sz1sel = "";
1542: var sz2sel = "";
1543: if (kwsize=="0") {var sznsel="checked"};
1544: if (kwsize=="+1") {var sz1sel="checked"};
1545: if (kwsize=="+2") {var sz2sel="checked"};
1546: var synsel = "";
1547: var syisel = "";
1548: var sybsel = "";
1549: if (kwstyle=="") {var synsel="checked"};
1550: if (kwstyle=="<i>") {var syisel="checked"};
1551: if (kwstyle=="<b>") {var sybsel="checked"};
1552: highlightCentral();
1553: highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
1554: highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
1555: highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
1556: highlightend();
1557: return;
1558: }
1559:
1560: function highlightCentral() {
1561: // if (window.hwdWin) window.hwdWin.close();
1562: var xpos = (screen.width-400)/2;
1563: xpos = (xpos < 0) ? '0' : xpos;
1564: var ypos = (screen.height-330)/2-30;
1565: ypos = (ypos < 0) ? '0' : ypos;
1566:
1567: hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1568: hwdWin.focus();
1569: var hDoc = hwdWin.document;
1570: hDoc.$docopen;
1571: hDoc.write('$start_page_highlight_central');
1572: hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1573: hDoc.write("<h3><span class=\\"LC_info\\"> Keyword Highlight Options<\\/span><\\/h3><br /><br />");
1574:
1575: hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
1576: hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
1577: hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
1578: }
1579:
1580: function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) {
1581: var hDoc = hwdWin.document;
1582: hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1583: hDoc.write("<td align=\\"left\\">");
1584: hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+"> "+clrtxt+"<\\/td>");
1585: hDoc.write("<td align=\\"left\\">");
1586: hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+"> "+sztxt+"<\\/td>");
1587: hDoc.write("<td align=\\"left\\">");
1588: hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+"> "+sytxt+"<\\/td>");
1589: hDoc.write("<\\/tr>");
1590: }
1591:
1592: function highlightend() {
1593: var hDoc = hwdWin.document;
1594: hDoc.write("<\\/table>");
1595: hDoc.write("<\\/td><\\/tr><\\/table> ");
1596: hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\"> ");
1597: hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1598: hDoc.write("<\\/form>");
1599: hDoc.write('$end_page_highlight_central');
1600: hDoc.close();
1601: }
1602:
1603: </script>
1604: SUBJAVASCRIPT
1605: }
1606:
1607: sub get_increment {
1608: my $increment = $env{'form.increment'};
1609: if ($increment != 1 && $increment != .5 && $increment != .25 &&
1610: $increment != .1) {
1611: $increment = 1;
1612: }
1613: return $increment;
1614: }
1615:
1616: #--- displays the grading box, used in essay type problem and grading by page/sequence
1617: sub gradeBox {
1618: my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1619: my $checkIcon = '<img alt="'.&mt('Check Mark').
1620: '" src="'.$request->dir_config('lonIconsURL').
1621: '/check.gif" height="16" border="0" />';
1622: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1623: my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)')
1624: : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1625: $wgt = ($wgt > 0 ? $wgt : '1');
1626: my $score = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1627: '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1628: my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1629: my $display_part= &get_display_part($partid,$symb);
1630: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
1631: [$partid]);
1632: my $aggtries = $$record{'resource.'.$partid.'.tries'};
1633: if ($last_resets{$partid}) {
1634: $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
1635: }
1636: $result.='<table border="0"><tr><td>'.
1637: '<b>Part: </b>'.$display_part.' <b>Points: </b></td><td>'."\n";
1638: my $ctr = 0;
1639: my $thisweight = 0;
1640: my $increment = &get_increment();
1641: $result.='<table border="0"><tr>'."\n"; # display radio buttons in a nice table 10 across
1642: while ($thisweight<=$wgt) {
1643: $result.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1644: 'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1645: $thisweight.')" value="'.$thisweight.'" '.
1646: ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1647: $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1648: $thisweight += $increment;
1649: $ctr++;
1650: }
1651: $result.='</tr></table>';
1652: $result.='</td><td> <b>or</b> </td>'."\n";
1653: $result.='<td><input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1654: ($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1655: 'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1656: $wgt.')" /></td>'."\n";
1657: $result.='<td>/'.$wgt.' '.$wgtmsg.
1658: ($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? ' '.$checkIcon : '').
1659: ' </td><td>'."\n";
1660: $result.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
1661: 'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1662: if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1663: $result.='<option></option>'.
1664: '<option selected="selected">excused</option>';
1665: } else {
1666: $result.='<option selected="selected"></option>'.
1667: '<option>excused</option>';
1668: }
1669: $result.='<option>reset status</option></select>'."\n";
1670: $result.=" \n";
1671: $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
1672: '<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
1673: '<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1674: $$record{'resource.'.$partid.'.solved'}.'" />'."\n".
1675: '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
1676: $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
1677: '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
1678: $aggtries.'" />'."\n";
1679: $result.='</td></tr></table>'."\n";
1680: $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
1681: return $result;
1682: }
1683:
1684: sub handback_box {
1685: my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
1686: my ($partlist,$handgrade,$responseType) = &response_type($symb);
1687: my (@respids);
1688: my @part_response_id = &flatten_responseType($responseType);
1689: foreach my $part_response_id (@part_response_id) {
1690: my ($part,$resp) = @{ $part_response_id };
1691: if ($part eq $partid) {
1692: push(@respids,$resp);
1693: }
1694: }
1695: my $result;
1696: foreach my $respid (@respids) {
1697: my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
1698: my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
1699: next if (!@$files);
1700: my $file_counter = 1;
1701: foreach my $file (@$files) {
1702: if ($file =~ /\/portfolio\//) {
1703: my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1704: my ($name,$version,$ext) = &file_name_version_ext($file_disp);
1705: $file_disp = "$name.$ext";
1706: $file = $file_path.$file_disp;
1707: $result.=&mt('Return commented version of [_1] to student.',
1708: '<span class="LC_filename">'.$file_disp.'</span>');
1709: $result.='<input type="file" name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1710: $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1711: $result.='(File will be uploaded when you click on Save & Next below.)<br />';
1712: $file_counter++;
1713: }
1714: }
1715: }
1716: return $result;
1717: }
1718:
1719: sub show_problem {
1720: my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1721: my $rendered;
1722: my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1723: &Apache::lonxml::remember_problem_counter();
1724: if ($mode eq 'both' or $mode eq 'text') {
1725: $rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1726: $env{'request.course.id'},
1727: undef,\%form);
1728: }
1729: if ($removeform) {
1730: $rendered=~s|<form(.*?)>||g;
1731: $rendered=~s|</form>||g;
1732: $rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1733: }
1734: my $companswer;
1735: if ($mode eq 'both' or $mode eq 'answer') {
1736: &Apache::lonxml::restore_problem_counter();
1737: $companswer=
1738: &Apache::loncommon::get_student_answers($symb,$uname,$udom,
1739: $env{'request.course.id'},
1740: %form);
1741: }
1742: if ($removeform) {
1743: $companswer=~s|<form(.*?)>||g;
1744: $companswer=~s|</form>||g;
1745: $companswer=~s|name="submit"|name="would_have_been_submit"|g;
1746: }
1747: $rendered=
1748: '<div class="LC_grade_show_problem_header">'.
1749: &mt('View of the problem').
1750: '</div><div class="LC_grade_show_problem_problem">'.
1751: $rendered.
1752: '</div>';
1753: $companswer=
1754: '<div class="LC_grade_show_problem_header">'.
1755: &mt('Correct answer').
1756: '</div><div class="LC_grade_show_problem_problem">'.
1757: $companswer.
1758: '</div>';
1759: my $result;
1760: if ($mode eq 'both') {
1761: $result=$rendered.$companswer;
1762: } elsif ($mode eq 'text') {
1763: $result=$rendered;
1764: } elsif ($mode eq 'answer') {
1765: $result=$companswer;
1766: }
1767: $result='<div class="LC_grade_show_problem">'.$result.'</div>';
1768: return $result;
1769: }
1770:
1771: sub files_exist {
1772: my ($r, $symb) = @_;
1773: my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1774:
1775: foreach my $student (@students) {
1776: my ($uname,$udom,$fullname) = split(/:/,$student);
1777: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
1778: $udom,$uname);
1779: my ($string,$timestamp)= &get_last_submission(\%record);
1780: foreach my $submission (@$string) {
1781: my ($partid,$respid) =
1782: ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1783: my $files=&get_submitted_files($udom,$uname,$partid,$respid,
1784: \%record);
1785: return 1 if (@$files);
1786: }
1787: }
1788: return 0;
1789: }
1790:
1791: sub download_all_link {
1792: my ($r,$symb) = @_;
1793: my $all_students =
1794: join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
1795:
1796: my $parts =
1797: join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
1798:
1799: my $identifier = &Apache::loncommon::get_cgi_id();
1800: &Apache::lonnet::appenv('cgi.'.$identifier.'.students' => $all_students,
1801: 'cgi.'.$identifier.'.symb' => $symb,
1802: 'cgi.'.$identifier.'.parts' => $parts,);
1803: $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
1804: &mt('Download All Submitted Documents').'</a>');
1805: return
1806: }
1807:
1808: sub build_section_inputs {
1809: my $section_inputs;
1810: if ($env{'form.section'} eq '') {
1811: $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
1812: } else {
1813: my @sections = &Apache::loncommon::get_env_multiple('form.section');
1814: foreach my $section (@sections) {
1815: $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
1816: }
1817: }
1818: return $section_inputs;
1819: }
1820:
1821: # --------------------------- show submissions of a student, option to grade
1822: sub submission {
1823: my ($request,$counter,$total) = @_;
1824: my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
1825: $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
1826: my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
1827: $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1828: my $symb = &get_symb($request);
1829: if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1830:
1831: if (!&canview($usec)) {
1832: $request->print('<span class="LC_warning">Unable to view requested student.('.
1833: $uname.':'.$udom.' in section '.$usec.' in course id '.
1834: $env{'request.course.id'}.')</span>');
1835: $request->print(&show_grading_menu_form($symb));
1836: return;
1837: }
1838:
1839: if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
1840: if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
1841: if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
1842: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1843: my $checkIcon = '<img alt="'.&mt('Check Mark').
1844: '" src="'.$request->dir_config('lonIconsURL').
1845: '/check.gif" height="16" border="0" />';
1846:
1847: my %old_essays;
1848: # header info
1849: if ($counter == 0) {
1850: &sub_page_js($request);
1851: &sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
1852: $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ?
1853: &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1854: if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1855: &download_all_link($request, $symb);
1856: }
1857: $request->print('<h3> <span class="LC_info">Submission Record</span></h3>'."\n".
1858: '<h4> <b>Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n");
1859:
1860: # option to display problem, only once else it cause problems
1861: # with the form later since the problem has a form.
1862: if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1863: my $mode;
1864: if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1865: $mode='both';
1866: } elsif ($env{'form.vProb'} eq 'yes') {
1867: $mode='text';
1868: } elsif ($env{'form.vAns'} eq 'yes') {
1869: $mode='answer';
1870: }
1871: &Apache::lonxml::clear_problem_counter();
1872: $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1873: }
1874:
1875: # kwclr is the only variable that is guaranteed to be non blank
1876: # if this subroutine has been called once.
1877: my %keyhash = ();
1878: if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1879: %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1880: $env{'course.'.$env{'request.course.id'}.'.domain'},
1881: $env{'course.'.$env{'request.course.id'}.'.num'});
1882:
1883: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1884: $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
1885: $env{'form.kwclr'} = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
1886: $env{'form.kwsize'} = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
1887: $env{'form.kwstyle'} = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
1888: $env{'form.msgsub'} = $keyhash{$symb.'_subject'} ne '' ?
1889: $keyhash{$symb.'_subject'} : $env{'form.probTitle'};
1890: $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1891: }
1892: my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1893: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1894: $request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1895: '<input type="hidden" name="command" value="handgrade" />'."\n".
1896: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1897: '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
1898: '<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1899: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
1900: '<input type="hidden" name="refresh" value="off" />'."\n".
1901: '<input type="hidden" name="studentNo" value="" />'."\n".
1902: '<input type="hidden" name="gradeOpt" value="" />'."\n".
1903: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1904: '<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
1905: '<input type="hidden" name="vProb" value="'.$env{'form.vProb'}.'" />'."\n".
1906: '<input type="hidden" name="vAns" value="'.$env{'form.vAns'}.'" />'."\n".
1907: '<input type="hidden" name="lastSub" value="'.$env{'form.lastSub'}.'" />'."\n".
1908: &build_section_inputs().
1909: '<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1910: '<input type="hidden" name="handgrade" value="'.$env{'form.handgrade'}.'" />'."\n".
1911: '<input type="hidden" name="NCT"'.
1912: ' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1913: if ($env{'form.handgrade'} eq 'yes') {
1914: $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
1915: '<input type="hidden" name="kwclr" value="'.$env{'form.kwclr'}.'" />'."\n".
1916: '<input type="hidden" name="kwsize" value="'.$env{'form.kwsize'}.'" />'."\n".
1917: '<input type="hidden" name="kwstyle" value="'.$env{'form.kwstyle'}.'" />'."\n".
1918: '<input type="hidden" name="msgsub" value="'.$env{'form.msgsub'}.'" />'."\n".
1919: '<input type="hidden" name="shownSub" value="0" />'."\n".
1920: '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1921: foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
1922: $request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
1923: }
1924: }
1925:
1926: my ($cts,$prnmsg) = (1,'');
1927: while ($cts <= $env{'form.savemsgN'}) {
1928: $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1929: (!exists($keyhash{$symb.'_savemsg'.$cts}) ?
1930: &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1931: &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1932: '" />'."\n".
1933: '<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1934: $cts++;
1935: }
1936: $request->print($prnmsg);
1937:
1938: if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1939: #
1940: # Print out the keyword options line
1941: #
1942: $request->print(<<KEYWORDS);
1943: <b>Keyword Options:</b>
1944: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>
1945: <a href="#" onMouseDown="javascript:getSel(); return false"
1946: CLASS="page">Paste Selection to List</a>
1947: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1948: KEYWORDS
1949: #
1950: # Load the other essays for similarity check
1951: #
1952: my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1953: my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1954: $apath=&escape($apath);
1955: $apath=~s/\W/\_/gs;
1956: %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1957: }
1958: }
1959:
1960: # This is where output for one specific student would start
1961: my $add_class = ($counter%2) ? 'LC_grade_show_user_odd_row' : '';
1962: $request->print("\n\n".
1963: '<div class="LC_grade_show_user '.$add_class.'">'.
1964: '<div class="LC_grade_user_name">'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</div>'.
1965: '<div class="LC_grade_show_user_body">'."\n");
1966:
1967: if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1968: my $mode;
1969: if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1970: $mode='both';
1971: } elsif ($env{'form.vProb'} eq 'all' ) {
1972: $mode='text';
1973: } elsif ($env{'form.vAns'} eq 'all') {
1974: $mode='answer';
1975: }
1976: &Apache::lonxml::clear_problem_counter();
1977: $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1978: }
1979:
1980: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1981: my ($partlist,$handgrade,$responseType) = &response_type($symb);
1982:
1983: # Display student info
1984: $request->print(($counter == 0 ? '' : '<br />'));
1985: my $result='<div class="LC_grade_submissions">';
1986:
1987: $result.='<div class="LC_grade_submissions_header">';
1988: $result.= &mt('Submissions');
1989: $result.='<input type="hidden" name="name'.$counter.
1990: '" value="'.$env{'form.fullname'}.'" />'."\n";
1991: if ($env{'form.handgrade'} eq 'no') {
1992: $result.='<span class="LC_grade_check_note">'.
1993: &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)."</span>\n";
1994:
1995: }
1996:
1997:
1998:
1999: # If any part of the problem is an essay-response (handgraded), then check for collaborators
2000: my $fullname;
2001: my $col_fullnames = [];
2002: if ($env{'form.handgrade'} eq 'yes') {
2003: (my $sub_result,$fullname,$col_fullnames)=
2004: &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
2005: $counter);
2006: $result.=$sub_result;
2007: }
2008: $request->print($result."\n");
2009: $request->print('</div>'."\n");
2010: # print student answer/submission
2011: # Options are (1) Handgaded submission only
2012: # (2) Last submission, includes submission that is not handgraded
2013: # (for multi-response type part)
2014: # (3) Last submission plus the parts info
2015: # (4) The whole record for this student
2016: if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
2017: my ($string,$timestamp)= &get_last_submission(\%record);
2018:
2019: my $lastsubonly;
2020:
2021: if ($$timestamp eq '') {
2022: $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>';
2023: } else {
2024: $lastsubonly = '<div class="LC_grade_submissions_body"> <b>Date Submitted:</b> '.$$timestamp."\n";
2025:
2026: my %seenparts;
2027: my @part_response_id = &flatten_responseType($responseType);
2028: foreach my $part (@part_response_id) {
2029: next if ($env{'form.lastSub'} eq 'hdgrade'
2030: && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
2031:
2032: my ($partid,$respid) = @{ $part };
2033: my $display_part=&get_display_part($partid,$symb);
2034: if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
2035: if (exists($seenparts{$partid})) { next; }
2036: $seenparts{$partid}=1;
2037: my $submitby='<b>Part:</b> '.$display_part.
2038: ' <b>Collaborative submission by:</b> '.
2039: '<a href="javascript:viewSubmitter(\''.
2040: $env{"form.$uname:$udom:$partid:submitted_by"}.
2041: '\');" target="_self">'.
2042: $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
2043: $request->print($submitby);
2044: next;
2045: }
2046: my $responsetype = $responseType->{$partid}->{$respid};
2047: if (!exists($record{"resource.$partid.$respid.submission"})) {
2048: $lastsubonly.="\n".'<div class="LC_grade_submission_part"><b>Part:</b> '.
2049: $display_part.' <span class="LC_internal_info">( ID '.$respid.
2050: ' )</span> '.
2051: '<span class="LC_warning">'.&mt('Nothing submitted - no attempts').'</span><br /><br /></div>';
2052: next;
2053: }
2054: foreach my $submission (@$string) {
2055: my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
2056: if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
2057: my ($ressub,$subval) = split(/:/,$submission,2);
2058: # Similarity check
2059: my $similar='';
2060: if($env{'form.checkPlag'}){
2061: my ($oname,$odom,$ocrsid,$oessay,$osim)=
2062: &most_similar($uname,$udom,$subval,\%old_essays);
2063: if ($osim) {
2064: $osim=int($osim*100.0);
2065: my %old_course_desc =
2066: &Apache::lonnet::coursedescription($ocrsid,
2067: {'one_time' => 1});
2068:
2069: $similar="<hr /><h3><span class=\"LC_warning\">".
2070: &mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
2071: $osim,
2072: &Apache::loncommon::plainname($oname,$odom),
2073: $oname,$odom,
2074: $old_course_desc{'description'},
2075: $old_course_desc{'num'},
2076: $old_course_desc{'domain'}).
2077: '</span></h3><blockquote><i>'.
2078: &keywords_highlight($oessay).
2079: '</i></blockquote><hr />';
2080: }
2081: }
2082: my $order=&get_order($partid,$respid,$symb,$uname,$udom);
2083: if ($env{'form.lastSub'} eq 'lastonly' ||
2084: ($env{'form.lastSub'} eq 'hdgrade' &&
2085: $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
2086: my $display_part=&get_display_part($partid,$symb);
2087: $lastsubonly.='<div class="LC_grade_submission_part"><b>Part:</b> '.
2088: $display_part.' <span class="LC_internal_info">( ID '.$respid.
2089: ' )</span> ';
2090: my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
2091: if (@$files) {
2092: $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain virusses').'</span><br />';
2093: my $file_counter = 0;
2094: foreach my $file (@$files) {
2095: $file_counter++;
2096: &Apache::lonnet::allowuploaded('/adm/grades',$file);
2097: $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
2098: }
2099: $lastsubonly.='<br />';
2100: }
2101: $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
2102: &cleanRecord($subval,$responsetype,$symb,$partid,
2103: $respid,\%record,$order);
2104: if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
2105: $lastsubonly.='</div>';
2106: }
2107: }
2108: }
2109: $lastsubonly.='</div>'."\n";
2110: }
2111: $request->print($lastsubonly);
2112: } elsif ($env{'form.lastSub'} eq 'datesub') {
2113: my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
2114: $request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
2115: } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
2116: $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
2117: $env{'request.course.id'},
2118: $last,'.submission',
2119: 'Apache::grades::keywords_highlight'));
2120: }
2121:
2122: $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
2123: .$udom.'" />'."\n");
2124: # return if view submission with no grading option
2125: if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
2126: my $toGrade.='<input type="button" value="Grade Student" '.
2127: 'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
2128: .$counter.'\');" target="_self" /> '."\n" if (&canmodify($usec));
2129: $toGrade.='</div>'."\n";
2130: if (($env{'form.command'} eq 'submission') ||
2131: ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
2132: $toGrade.='</form>'.&show_grading_menu_form($symb);
2133: }
2134: $request->print($toGrade);
2135: return;
2136: } else {
2137: $request->print('</div>'."\n");
2138: }
2139:
2140: # essay grading message center
2141: if ($env{'form.handgrade'} eq 'yes') {
2142: my $result='<div class="LC_grade_message_center">';
2143:
2144: $result.='<div class="LC_grade_message_center_header">'.
2145: &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
2146: my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
2147: my $msgfor = $givenn.' '.$lastname;
2148: if (scalar(@$col_fullnames) > 0) {
2149: my $lastone = pop(@$col_fullnames);
2150: $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
2151: }
2152: $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
2153: $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
2154: '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
2155: $result.=' <a href="javascript:msgCenter(document.SCORE,'.$counter.
2156: ',\''.$msgfor.'\');" target="_self">'.
2157: &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
2158: &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
2159: '<img src="'.$request->dir_config('lonIconsURL').
2160: '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
2161: '<br /> ('.
2162: &mt('Message will be sent when you click on Save & Next below.').")\n";
2163: $result.='</div></div>';
2164: $request->print($result);
2165: }
2166:
2167: my %seen = ();
2168: my @partlist;
2169: my @gradePartRespid;
2170: my @part_response_id = &flatten_responseType($responseType);
2171: $request->print('<div class="LC_grade_assign">'.
2172:
2173: '<div class="LC_grade_assign_header">'.
2174: &mt('Assign Grades').'</div>'.
2175: '<div class="LC_grade_assign_body">');
2176: foreach my $part_response_id (@part_response_id) {
2177: my ($partid,$respid) = @{ $part_response_id };
2178: my $part_resp = join('_',@{ $part_response_id });
2179: next if ($seen{$partid} > 0);
2180: $seen{$partid}++;
2181: next if ($$handgrade{$part_resp} ne 'yes'
2182: && $env{'form.lastSub'} eq 'hdgrade');
2183: push @partlist,$partid;
2184: push @gradePartRespid,$partid.'.'.$respid;
2185: $request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
2186: }
2187: $request->print('</div></div>');
2188:
2189: $request->print('<div class="LC_grade_info_links">');
2190: if ($perm{'vgr'}) {
2191: $request->print(
2192: &Apache::loncommon::track_student_link(&mt('View recent activity'),
2193: $uname,$udom,'check'));
2194: }
2195: if ($perm{'opa'}) {
2196: $request->print(
2197: &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
2198: $uname,$udom,$symb,'check'));
2199: }
2200: $request->print('</div>');
2201:
2202: $result='<input type="hidden" name="partlist'.$counter.
2203: '" value="'.(join ":",@partlist).'" />'."\n";
2204: $result.='<input type="hidden" name="gradePartRespid'.
2205: '" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
2206: my $ctr = 0;
2207: while ($ctr < scalar(@partlist)) {
2208: $result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
2209: $partlist[$ctr].'" />'."\n";
2210: $ctr++;
2211: }
2212: $request->print($result.''."\n");
2213:
2214: # Done with printing info for one student
2215:
2216: $request->print('</div>');#LC_grade_show_user_body
2217: $request->print('</div>');#LC_grade_show_user
2218:
2219:
2220: # print end of form
2221: if ($counter == $total) {
2222: my $endform='<table border="0"><tr><td>'."\n";
2223: $endform.='<input type="button" value="Save & Next" '.
2224: 'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
2225: $total.','.scalar(@partlist).');" target="_self" /> '."\n";
2226: my $ntstu ='<select name="NTSTU">'.
2227: '<option>1</option><option>2</option>'.
2228: '<option>3</option><option>5</option>'.
2229: '<option>7</option><option>10</option></select>'."\n";
2230: my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
2231: $ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
2232: $endform.=$ntstu.'student(s) ';
2233: $endform.='<input type="button" value="Previous" '.
2234: 'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> '."\n".
2235: '<input type="button" value="Next" '.
2236: 'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> ';
2237: $endform.='(Next and Previous (student) do not save the scores.)'."\n" ;
2238: $endform.="<input type='hidden' value='".&get_increment().
2239: "' name='increment' />";
2240: $endform.='</td><tr></table></form>';
2241: $endform.=&show_grading_menu_form($symb);
2242: $request->print($endform);
2243: }
2244: return '';
2245: }
2246:
2247: sub check_collaborators {
2248: my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
2249: my ($result,@col_fullnames);
2250: my ($classlist,undef,$fullname) = &getclasslist('all','0');
2251: foreach my $part (keys(%$handgrade)) {
2252: my $ncol = &Apache::lonnet::EXT('resource.'.$part.
2253: '.maxcollaborators',
2254: $symb,$udom,$uname);
2255: next if ($ncol <= 0);
2256: $part =~ s/\_/\./g;
2257: next if ($record->{'resource.'.$part.'.collaborators'} eq '');
2258: my (@good_collaborators, @bad_collaborators);
2259: foreach my $possible_collaborator
2260: (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) {
2261: $possible_collaborator =~ s/[\$\^\(\)]//g;
2262: next if ($possible_collaborator eq '');
2263: my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
2264: $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
2265: next if ($co_name eq $uname && $co_dom eq $udom);
2266: # Doing this grep allows 'fuzzy' specification
2267: my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i,
2268: keys(%$classlist));
2269: if (! scalar(@matches)) {
2270: push(@bad_collaborators, $possible_collaborator);
2271: } else {
2272: push(@good_collaborators, @matches);
2273: }
2274: }
2275: if (scalar(@good_collaborators) != 0) {
2276: $result.='<br />'.&mt('Collaborators: ');
2277: foreach my $name (@good_collaborators) {
2278: my ($lastname,$givenn) = split(/,/,$$fullname{$name});
2279: push(@col_fullnames, $givenn.' '.$lastname);
2280: $result.=$fullname->{$name}.' ';
2281: }
2282: $result.='<br />'."\n";
2283: my ($part)=split(/\./,$part);
2284: $result.='<input type="hidden" name="collaborator'.$counter.
2285: '" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
2286: "\n";
2287: }
2288: if (scalar(@bad_collaborators) > 0) {
2289: $result.='<div class="LC_warning">';
2290: $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
2291: $result .= '</div>';
2292: }
2293: if (scalar(@bad_collaborators > $ncol)) {
2294: $result .= '<div class="LC_warning">';
2295: $result .= &mt('This student has submitted too many '.
2296: 'collaborators. Maximum is [_1].',$ncol);
2297: $result .= '</div>';
2298: }
2299: }
2300: return ($result,$fullname,\@col_fullnames);
2301: }
2302:
2303: #--- Retrieve the last submission for all the parts
2304: sub get_last_submission {
2305: my ($returnhash)=@_;
2306: my (@string,$timestamp);
2307: if ($$returnhash{'version'}) {
2308: my %lasthash=();
2309: my ($version);
2310: for ($version=1;$version<=$$returnhash{'version'};$version++) {
2311: foreach my $key (sort(split(/\:/,
2312: $$returnhash{$version.':keys'}))) {
2313: $lasthash{$key}=$$returnhash{$version.':'.$key};
2314: $timestamp =
2315: scalar(localtime($$returnhash{$version.':timestamp'}));
2316: }
2317: }
2318: foreach my $key (keys(%lasthash)) {
2319: next if ($key !~ /\.submission$/);
2320:
2321: my ($partid,$foo) = split(/submission$/,$key);
2322: my $draft = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
2323: '<span class="LC_warning">Draft Copy</span> ' : '';
2324: push(@string, join(':', $key, $draft.$lasthash{$key}));
2325: }
2326: }
2327: if (!@string) {
2328: $string[0] =
2329: '<span class="LC_warning">Nothing submitted - no attempts.</span>';
2330: }
2331: return (\@string,\$timestamp);
2332: }
2333:
2334: #--- High light keywords, with style choosen by user.
2335: sub keywords_highlight {
2336: my $string = shift;
2337: my $size = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
2338: my $styleon = $env{'form.kwstyle'} eq '' ? '' : $env{'form.kwstyle'};
2339: (my $styleoff = $styleon) =~ s/\</\<\//;
2340: my @keylist = split(/[,\s+]/,$env{'form.keywords'});
2341: foreach my $keyword (@keylist) {
2342: $string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
2343: }
2344: return $string;
2345: }
2346:
2347: #--- Called from submission routine
2348: sub processHandGrade {
2349: my ($request) = shift;
2350: my $symb = &get_symb($request);
2351: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
2352: my $button = $env{'form.gradeOpt'};
2353: my $ngrade = $env{'form.NCT'};
2354: my $ntstu = $env{'form.NTSTU'};
2355: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2356: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2357:
2358: if ($button eq 'Save & Next') {
2359: my $ctr = 0;
2360: while ($ctr < $ngrade) {
2361: my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
2362: my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
2363: if ($errorflag eq 'no_score') {
2364: $ctr++;
2365: next;
2366: }
2367: if ($errorflag eq 'not_allowed') {
2368: $request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
2369: $ctr++;
2370: next;
2371: }
2372: my $includemsg = $env{'form.includemsg'.$ctr};
2373: my ($subject,$message,$msgstatus) = ('','','');
2374: my $restitle = &Apache::lonnet::gettitle($symb);
2375: my ($feedurl,$showsymb) =
2376: &get_feedurl_and_symb($symb,$uname,$udom);
2377: my $messagetail;
2378: if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
2379: $subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
2380: unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
2381: $subject.=' ['.$restitle.']';
2382: my (@msgnum) = split(/,/,$includemsg);
2383: foreach (@msgnum) {
2384: $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
2385: }
2386: $message =&Apache::lonfeedback::clear_out_html($message);
2387: if ($env{'form.withgrades'.$ctr}) {
2388: $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
2389: $messagetail = " for <a href=\"".
2390: $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
2391: }
2392: $msgstatus =
2393: &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
2394: $message.$messagetail,
2395: undef,$feedurl,undef,
2396: undef,undef,$showsymb,
2397: $restitle);
2398: $request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
2399: $msgstatus);
2400: }
2401: if ($env{'form.collaborator'.$ctr}) {
2402: my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
2403: foreach my $collabstr (@collabstrs) {
2404: my ($part,@collaborators) = split(/:/,$collabstr);
2405: foreach my $collaborator (@collaborators) {
2406: my ($errorflag,$pts,$wgt) =
2407: &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
2408: $env{'form.unamedom'.$ctr},$part);
2409: if ($errorflag eq 'not_allowed') {
2410: $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
2411: next;
2412: } elsif ($message ne '') {
2413: my ($baseurl,$showsymb) =
2414: &get_feedurl_and_symb($symb,$collaborator,
2415: $udom);
2416: if ($env{'form.withgrades'.$ctr}) {
2417: $messagetail = " for <a href=\"".
2418: $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
2419: }
2420: $msgstatus =
2421: &Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
2422: }
2423: }
2424: }
2425: }
2426: $ctr++;
2427: }
2428: }
2429:
2430: if ($env{'form.handgrade'} eq 'yes') {
2431: # Keywords sorted in alphabatical order
2432: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
2433: my %keyhash = ();
2434: $env{'form.keywords'} =~ s/,\s{0,}|\s+/ /g;
2435: $env{'form.keywords'} =~ s/^\s+|\s+$//;
2436: my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
2437: $env{'form.keywords'} = join(' ',@keywords);
2438: $keyhash{$symb.'_keywords'} = $env{'form.keywords'};
2439: $keyhash{$symb.'_subject'} = $env{'form.msgsub'};
2440: $keyhash{$loginuser.'_kwclr'} = $env{'form.kwclr'};
2441: $keyhash{$loginuser.'_kwsize'} = $env{'form.kwsize'};
2442: $keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
2443:
2444: # message center - Order of message gets changed. Blank line is eliminated.
2445: # New messages are saved in env for the next student.
2446: # All messages are saved in nohist_handgrade.db
2447: my ($ctr,$idx) = (1,1);
2448: while ($ctr <= $env{'form.savemsgN'}) {
2449: if ($env{'form.savemsg'.$ctr} ne '') {
2450: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
2451: $idx++;
2452: }
2453: $ctr++;
2454: }
2455: $ctr = 0;
2456: while ($ctr < $ngrade) {
2457: if ($env{'form.newmsg'.$ctr} ne '') {
2458: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2459: $env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2460: $idx++;
2461: }
2462: $ctr++;
2463: }
2464: $env{'form.savemsgN'} = --$idx;
2465: $keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
2466: my $putresult = &Apache::lonnet::put
2467: ('nohist_handgrade',\%keyhash,$cdom,$cnum);
2468: }
2469: # Called by Save & Refresh from Highlight Attribute Window
2470: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
2471: if ($env{'form.refresh'} eq 'on') {
2472: my ($ctr,$total) = (0,0);
2473: while ($ctr < $ngrade) {
2474: $total++ if $env{'form.unamedom'.$ctr} ne '';
2475: $ctr++;
2476: }
2477: $env{'form.NTSTU'}=$ngrade;
2478: $ctr = 0;
2479: while ($ctr < $total) {
2480: my $processUser = $env{'form.unamedom'.$ctr};
2481: ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
2482: $env{'form.fullname'} = $$fullname{$processUser};
2483: &submission($request,$ctr,$total-1);
2484: $ctr++;
2485: }
2486: return '';
2487: }
2488:
2489: # Go directly to grade student - from submission or link from chart page
2490: if ($button eq 'Grade Student') {
2491: (undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
2492: my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
2493: ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
2494: $env{'form.fullname'} = $$fullname{$processUser};
2495: &submission($request,0,0);
2496: return '';
2497: }
2498:
2499: # Get the next/previous one or group of students
2500: my $firststu = $env{'form.unamedom0'};
2501: my $laststu = $env{'form.unamedom'.($ngrade-1)};
2502: my $ctr = 2;
2503: while ($laststu eq '') {
2504: $laststu = $env{'form.unamedom'.($ngrade-$ctr)};
2505: $ctr++;
2506: $laststu = $firststu if ($ctr > $ngrade);
2507: }
2508:
2509: my (@parsedlist,@nextlist);
2510: my ($nextflg) = 0;
2511: foreach (sort
2512: {
2513: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
2514: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
2515: }
2516: return $a cmp $b;
2517: } (keys(%$fullname))) {
2518: if ($nextflg == 1 && $button =~ /Next$/) {
2519: push @parsedlist,$_;
2520: }
2521: $nextflg = 1 if ($_ eq $laststu);
2522: if ($button eq 'Previous') {
2523: last if ($_ eq $firststu);
2524: push @parsedlist,$_;
2525: }
2526: }
2527: $ctr = 0;
2528: @parsedlist = reverse @parsedlist if ($button eq 'Previous');
2529: my ($partlist) = &response_type($symb);
2530: foreach my $student (@parsedlist) {
2531: my $submitonly=$env{'form.submitonly'};
2532: my ($uname,$udom) = split(/:/,$student);
2533:
2534: if ($submitonly eq 'queued') {
2535: my %queue_status =
2536: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
2537: $udom,$uname);
2538: next if (!defined($queue_status{'gradingqueue'}));
2539: }
2540:
2541: if ($submitonly =~ /^(yes|graded|incorrect)$/) {
2542: # my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
2543: my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
2544: my $submitted = 0;
2545: my $ungraded = 0;
2546: my $incorrect = 0;
2547: foreach (keys(%status)) {
2548: $submitted = 1 if ($status{$_} ne 'nothing');
2549: $ungraded = 1 if ($status{$_} =~ /^ungraded/);
2550: $incorrect = 1 if ($status{$_} =~ /^incorrect/);
2551: my ($foo,$partid,$foo1) = split(/\./,$_);
2552: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
2553: $submitted = 0;
2554: }
2555: }
2556: next if (!$submitted && ($submitonly eq 'yes' ||
2557: $submitonly eq 'incorrect' ||
2558: $submitonly eq 'graded'));
2559: next if (!$ungraded && ($submitonly eq 'graded'));
2560: next if (!$incorrect && $submitonly eq 'incorrect');
2561: }
2562: push @nextlist,$student if ($ctr < $ntstu);
2563: last if ($ctr == $ntstu);
2564: $ctr++;
2565: }
2566:
2567: $ctr = 0;
2568: my $total = scalar(@nextlist)-1;
2569:
2570: foreach (sort @nextlist) {
2571: my ($uname,$udom,$submitter) = split(/:/);
2572: $env{'form.student'} = $uname;
2573: $env{'form.userdom'} = $udom;
2574: $env{'form.fullname'} = $$fullname{$_};
2575: &submission($request,$ctr,$total);
2576: $ctr++;
2577: }
2578: if ($total < 0) {
2579: my $the_end = '<h3><span class="LC_info">LON-CAPA User Message</span></h3><br />'."\n";
2580: $the_end.='<b>Message: </b> No more students for this section or class.<br /><br />'."\n";
2581: $the_end.='Click on the button below to return to the grading menu.<br /><br />'."\n";
2582: $the_end.=&show_grading_menu_form($symb);
2583: $request->print($the_end);
2584: }
2585: return '';
2586: }
2587:
2588: #---- Save the score and award for each student, if changed
2589: sub saveHandGrade {
2590: my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
2591: my @version_parts;
2592: my $usec = &Apache::lonnet::getsection($domain,$stuname,
2593: $env{'request.course.id'});
2594: if (!&canmodify($usec)) { return('not_allowed'); }
2595: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
2596: my @parts_graded;
2597: my %newrecord = ();
2598: my ($pts,$wgt) = ('','');
2599: my %aggregate = ();
2600: my $aggregateflag = 0;
2601: my @parts = split(/:/,$env{'form.partlist'.$newflg});
2602: foreach my $new_part (@parts) {
2603: #collaborator ($submi may vary for different parts
2604: if ($submitter && $new_part ne $part) { next; }
2605: my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
2606: if ($dropMenu eq 'excused') {
2607: if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
2608: $newrecord{'resource.'.$new_part.'.solved'} = 'excused';
2609: if (exists($record{'resource.'.$new_part.'.awarded'})) {
2610: $newrecord{'resource.'.$new_part.'.awarded'} = '';
2611: }
2612: $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
2613: }
2614: } elsif ($dropMenu eq 'reset status'
2615: && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
2616: foreach my $key (keys (%record)) {
2617: if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
2618: }
2619: $newrecord{'resource.'.$new_part.'.regrader'}=
2620: "$env{'user.name'}:$env{'user.domain'}";
2621: my $totaltries = $record{'resource.'.$part.'.tries'};
2622:
2623: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
2624: [$new_part]);
2625: my $aggtries =$totaltries;
2626: if ($last_resets{$new_part}) {
2627: $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
2628: $new_part);
2629: }
2630:
2631: my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
2632: if ($aggtries > 0) {
2633: &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
2634: $aggregateflag = 1;
2635: }
2636: } elsif ($dropMenu eq '') {
2637: $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ?
2638: $env{'form.GD_BOX'.$newflg.'_'.$new_part} :
2639: $env{'form.RADVAL'.$newflg.'_'.$new_part});
2640: if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
2641: next;
2642: }
2643: $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 :
2644: $env{'form.WGT'.$newflg.'_'.$new_part};
2645: my $partial= $pts/$wgt;
2646: if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
2647: #do not update score for part if not changed.
2648: &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
2649: next;
2650: } else {
2651: push @parts_graded, $new_part;
2652: }
2653: if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
2654: $newrecord{'resource.'.$new_part.'.awarded'} = $partial;
2655: }
2656: my $reckey = 'resource.'.$new_part.'.solved';
2657: if ($partial == 0) {
2658: if ($record{$reckey} ne 'incorrect_by_override') {
2659: $newrecord{$reckey} = 'incorrect_by_override';
2660: }
2661: } else {
2662: if ($record{$reckey} ne 'correct_by_override') {
2663: $newrecord{$reckey} = 'correct_by_override';
2664: }
2665: }
2666: if ($submitter &&
2667: ($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
2668: $newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
2669: }
2670: $newrecord{'resource.'.$new_part.'.regrader'}=
2671: "$env{'user.name'}:$env{'user.domain'}";
2672: }
2673: # unless problem has been graded, set flag to version the submitted files
2674: unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/ ||
2675: $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
2676: $dropMenu eq 'reset status')
2677: {
2678: push (@version_parts,$new_part);
2679: }
2680: }
2681: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2682: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2683:
2684: if (%newrecord) {
2685: if (@version_parts) {
2686: my @changed_keys = &version_portfiles(\%record, \@parts_graded,
2687: $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
2688: @newrecord{@changed_keys} = @record{@changed_keys};
2689: foreach my $new_part (@version_parts) {
2690: &handback_files($request,$symb,$stuname,$domain,$newflg,
2691: $new_part,\%newrecord);
2692: }
2693: }
2694: &Apache::lonnet::cstore(\%newrecord,$symb,
2695: $env{'request.course.id'},$domain,$stuname);
2696: &check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
2697: $cdom,$cnum,$domain,$stuname);
2698: }
2699: if ($aggregateflag) {
2700: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
2701: $cdom,$cnum);
2702: }
2703: return ('',$pts,$wgt);
2704: }
2705:
2706: sub check_and_remove_from_queue {
2707: my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
2708: my @ungraded_parts;
2709: foreach my $part (@{$parts}) {
2710: if ( $record->{ 'resource.'.$part.'.awarded'} eq ''
2711: && $record->{ 'resource.'.$part.'.solved' } ne 'excused'
2712: && $newrecord->{'resource.'.$part.'.awarded'} eq ''
2713: && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
2714: ) {
2715: push(@ungraded_parts, $part);
2716: }
2717: }
2718: if ( !@ungraded_parts ) {
2719: &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
2720: $cnum,$domain,$stuname);
2721: }
2722: }
2723:
2724: sub handback_files {
2725: my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
2726: my $portfolio_root = &propath($domain,$stuname).'/userfiles/portfolio';
2727: my ($partlist,$handgrade,$responseType) = &response_type($symb);
2728:
2729: my @part_response_id = &flatten_responseType($responseType);
2730: foreach my $part_response_id (@part_response_id) {
2731: my ($part_id,$resp_id) = @{ $part_response_id };
2732: my $part_resp = join('_',@{ $part_response_id });
2733: if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
2734: # if multiple files are uploaded names will be 'returndoc2','returndoc3'
2735: my $file_counter = 1;
2736: my $file_msg;
2737: while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
2738: my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
2739: my ($directory,$answer_file) =
2740: ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
2741: my ($answer_name,$answer_ver,$answer_ext) =
2742: &file_name_version_ext($answer_file);
2743: my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
2744: my @dir_list = &Apache::lonnet::dirlist($portfolio_path,$domain,$stuname,$portfolio_root);
2745: my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
2746: # fix file name
2747: my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
2748: my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
2749: $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
2750: $save_file_name);
2751: if ($result !~ m|^/uploaded/|) {
2752: $request->print('<span class="LC_error">An error occurred ('.$result.
2753: ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</span><br />');
2754: } else {
2755: # mark the file as read only
2756: my @files = ($save_file_name);
2757: my @what = ($symb,$env{'request.course.id'},'handback');
2758: &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
2759: if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
2760: $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
2761: }
2762: $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
2763: $file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
2764:
2765: }
2766: $request->print("<br />".$fname." will be the uploaded file name");
2767: $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
2768: $file_counter++;
2769: }
2770: my $subject = "File Handed Back by Instructor ";
2771: my $message = "A file has been returned that was originally submitted in reponse to: <br />";
2772: $message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
2773: $message .= ' The returned file(s) are named: '. $file_msg;
2774: $message .= " and can be found in your portfolio space.";
2775: my ($feedurl,$showsymb) =
2776: &get_feedurl_and_symb($symb,$domain,$stuname);
2777: my $restitle = &Apache::lonnet::gettitle($symb);
2778: my $msgstatus =
2779: &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
2780: ' (File Returned) ['.$restitle.']',$message,undef,
2781: $feedurl,undef,undef,undef,$showsymb,$restitle);
2782: }
2783: }
2784: return;
2785: }
2786:
2787: sub get_feedurl_and_symb {
2788: my ($symb,$uname,$udom) = @_;
2789: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
2790: $url = &Apache::lonnet::clutter($url);
2791: my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
2792: $symb,$udom,$uname);
2793: if ($encrypturl =~ /^yes$/i) {
2794: &Apache::lonenc::encrypted(\$url,1);
2795: &Apache::lonenc::encrypted(\$symb,1);
2796: }
2797: return ($url,$symb);
2798: }
2799:
2800: sub get_submitted_files {
2801: my ($udom,$uname,$partid,$respid,$record) = @_;
2802: my @files;
2803: if ($$record{"resource.$partid.$respid.portfiles"}) {
2804: my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
2805: foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
2806: push(@files,$file_url.$file);
2807: }
2808: }
2809: if ($$record{"resource.$partid.$respid.uploadedurl"}) {
2810: push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
2811: }
2812: return (\@files);
2813: }
2814:
2815: # ----------- Provides number of tries since last reset.
2816: sub get_num_tries {
2817: my ($record,$last_reset,$part) = @_;
2818: my $timestamp = '';
2819: my $num_tries = 0;
2820: if ($$record{'version'}) {
2821: for (my $version=$$record{'version'};$version>=1;$version--) {
2822: if (exists($$record{$version.':resource.'.$part.'.solved'})) {
2823: $timestamp = $$record{$version.':timestamp'};
2824: if ($timestamp > $last_reset) {
2825: $num_tries ++;
2826: } else {
2827: last;
2828: }
2829: }
2830: }
2831: }
2832: return $num_tries;
2833: }
2834:
2835: # ----------- Determine decrements required in aggregate totals
2836: sub decrement_aggs {
2837: my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
2838: my %decrement = (
2839: attempts => 0,
2840: users => 0,
2841: correct => 0
2842: );
2843: $decrement{'attempts'} = $aggtries;
2844: if ($solvedstatus =~ /^correct/) {
2845: $decrement{'correct'} = 1;
2846: }
2847: if ($aggtries == $totaltries) {
2848: $decrement{'users'} = 1;
2849: }
2850: foreach my $type (keys (%decrement)) {
2851: $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
2852: }
2853: return;
2854: }
2855:
2856: # ----------- Determine timestamps for last reset of aggregate totals for parts
2857: sub get_last_resets {
2858: my ($symb,$courseid,$partids) =@_;
2859: my %last_resets;
2860: my $cdom = $env{'course.'.$courseid.'.domain'};
2861: my $cname = $env{'course.'.$courseid.'.num'};
2862: my @keys;
2863: foreach my $part (@{$partids}) {
2864: push(@keys,"$symb\0$part\0resettime");
2865: }
2866: my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
2867: $cdom,$cname);
2868: foreach my $part (@{$partids}) {
2869: $last_resets{$part}=$results{"$symb\0$part\0resettime"};
2870: }
2871: return %last_resets;
2872: }
2873:
2874: # ----------- Handles creating versions for portfolio files as answers
2875: sub version_portfiles {
2876: my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
2877: my $version_parts = join('|',@$v_flag);
2878: my @returned_keys;
2879: my $parts = join('|', @$parts_graded);
2880: my $portfolio_root = &propath($domain,$stu_name).
2881: '/userfiles/portfolio';
2882: foreach my $key (keys(%$record)) {
2883: my $new_portfiles;
2884: if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
2885: my @versioned_portfiles;
2886: my @portfiles = split(/\s*,\s*/,$$record{$key});
2887: foreach my $file (@portfiles) {
2888: &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
2889: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
2890: my ($answer_name,$answer_ver,$answer_ext) =
2891: &file_name_version_ext($answer_file);
2892: my @dir_list = &Apache::lonnet::dirlist($directory,$domain,$stu_name,$portfolio_root);
2893: my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
2894: my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
2895: if ($new_answer ne 'problem getting file') {
2896: push(@versioned_portfiles, $directory.$new_answer);
2897: &Apache::lonnet::mark_as_readonly($domain,$stu_name,
2898: [$directory.$new_answer],
2899: [$symb,$env{'request.course.id'},'graded']);
2900: }
2901: }
2902: $$record{$key} = join(',',@versioned_portfiles);
2903: push(@returned_keys,$key);
2904: }
2905: }
2906: return (@returned_keys);
2907: }
2908:
2909: sub get_next_version {
2910: my ($answer_name, $answer_ext, $dir_list) = @_;
2911: my $version;
2912: foreach my $row (@$dir_list) {
2913: my ($file) = split(/\&/,$row,2);
2914: my ($file_name,$file_version,$file_ext) =
2915: &file_name_version_ext($file);
2916: if (($file_name eq $answer_name) &&
2917: ($file_ext eq $answer_ext)) {
2918: # gets here if filename and extension match, regardless of version
2919: if ($file_version ne '') {
2920: # a versioned file is found so save it for later
2921: if ($file_version > $version) {
2922: $version = $file_version;
2923: }
2924: }
2925: }
2926: }
2927: $version ++;
2928: return($version);
2929: }
2930:
2931: sub version_selected_portfile {
2932: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
2933: my ($answer_name,$answer_ver,$answer_ext) =
2934: &file_name_version_ext($file_name);
2935: my $new_answer;
2936: $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
2937: if($env{'form.copy'} eq '-1') {
2938: $new_answer = 'problem getting file';
2939: } else {
2940: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
2941: my $copy_result = &Apache::lonnet::finishuserfileupload(
2942: $stu_name,$domain,'copy',
2943: '/portfolio'.$directory.$new_answer);
2944: }
2945: return ($new_answer);
2946: }
2947:
2948: sub file_name_version_ext {
2949: my ($file)=@_;
2950: my @file_parts = split(/\./, $file);
2951: my ($name,$version,$ext);
2952: if (@file_parts > 1) {
2953: $ext=pop(@file_parts);
2954: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
2955: $version=pop(@file_parts);
2956: }
2957: $name=join('.',@file_parts);
2958: } else {
2959: $name=join('.',@file_parts);
2960: }
2961: return($name,$version,$ext);
2962: }
2963:
2964: #--------------------------------------------------------------------------------------
2965: #
2966: #-------------------------- Next few routines handles grading by section or whole class
2967: #
2968: #--- Javascript to handle grading by section or whole class
2969: sub viewgrades_js {
2970: my ($request) = shift;
2971:
2972: $request->print(<<VIEWJAVASCRIPT);
2973: <script type="text/javascript" language="javascript">
2974: function writePoint(partid,weight,point) {
2975: var radioButton = document.classgrade["RADVAL_"+partid];
2976: var textbox = document.classgrade["TEXTVAL_"+partid];
2977: if (point == "textval") {
2978: point = document.classgrade["TEXTVAL_"+partid].value;
2979: if (isNaN(point) || parseFloat(point) < 0) {
2980: alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
2981: var resetbox = false;
2982: for (var i=0; i<radioButton.length; i++) {
2983: if (radioButton[i].checked) {
2984: textbox.value = i;
2985: resetbox = true;
2986: }
2987: }
2988: if (!resetbox) {
2989: textbox.value = "";
2990: }
2991: return;
2992: }
2993: if (parseFloat(point) > parseFloat(weight)) {
2994: var resp = confirm("You entered a value ("+parseFloat(point)+
2995: ") greater than the weight for the part. Accept?");
2996: if (resp == false) {
2997: textbox.value = "";
2998: return;
2999: }
3000: }
3001: for (var i=0; i<radioButton.length; i++) {
3002: radioButton[i].checked=false;
3003: if (parseFloat(point) == i) {
3004: radioButton[i].checked=true;
3005: }
3006: }
3007:
3008: } else {
3009: textbox.value = parseFloat(point);
3010: }
3011: for (i=0;i<document.classgrade.total.value;i++) {
3012: var user = document.classgrade["ctr"+i].value;
3013: user = user.replace(new RegExp(':', 'g'),"_");
3014: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3015: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3016: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3017: if (saveval != "correct") {
3018: scorename.value = point;
3019: if (selname[0].selected != true) {
3020: selname[0].selected = true;
3021: }
3022: }
3023: }
3024: document.classgrade["SELVAL_"+partid][0].selected = true;
3025: }
3026:
3027: function writeRadText(partid,weight) {
3028: var selval = document.classgrade["SELVAL_"+partid];
3029: var radioButton = document.classgrade["RADVAL_"+partid];
3030: var override = document.classgrade["FORCE_"+partid].checked;
3031: var textbox = document.classgrade["TEXTVAL_"+partid];
3032: if (selval[1].selected || selval[2].selected) {
3033: for (var i=0; i<radioButton.length; i++) {
3034: radioButton[i].checked=false;
3035:
3036: }
3037: textbox.value = "";
3038:
3039: for (i=0;i<document.classgrade.total.value;i++) {
3040: var user = document.classgrade["ctr"+i].value;
3041: user = user.replace(new RegExp(':', 'g'),"_");
3042: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3043: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3044: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3045: if ((saveval != "correct") || override) {
3046: scorename.value = "";
3047: if (selval[1].selected) {
3048: selname[1].selected = true;
3049: } else {
3050: selname[2].selected = true;
3051: if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value))
3052: {document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
3053: }
3054: }
3055: }
3056: } else {
3057: for (i=0;i<document.classgrade.total.value;i++) {
3058: var user = document.classgrade["ctr"+i].value;
3059: user = user.replace(new RegExp(':', 'g'),"_");
3060: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3061: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3062: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3063: if ((saveval != "correct") || override) {
3064: scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
3065: selname[0].selected = true;
3066: }
3067: }
3068: }
3069: }
3070:
3071: function changeSelect(partid,user) {
3072: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
3073: var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
3074: var point = textbox.value;
3075: var weight = document.classgrade["weight_"+partid].value;
3076:
3077: if (isNaN(point) || parseFloat(point) < 0) {
3078: alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
3079: textbox.value = "";
3080: return;
3081: }
3082: if (parseFloat(point) > parseFloat(weight)) {
3083: var resp = confirm("You entered a value ("+parseFloat(point)+
3084: ") greater than the weight of the part. Accept?");
3085: if (resp == false) {
3086: textbox.value = "";
3087: return;
3088: }
3089: }
3090: selval[0].selected = true;
3091: }
3092:
3093: function changeOneScore(partid,user) {
3094: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
3095: if (selval[1].selected || selval[2].selected) {
3096: document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
3097: if (selval[2].selected) {
3098: document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
3099: }
3100: }
3101: }
3102:
3103: function resetEntry(numpart) {
3104: for (ctpart=0;ctpart<numpart;ctpart++) {
3105: var partid = document.classgrade["partid_"+ctpart].value;
3106: var radioButton = document.classgrade["RADVAL_"+partid];
3107: var textbox = document.classgrade["TEXTVAL_"+partid];
3108: var selval = document.classgrade["SELVAL_"+partid];
3109: for (var i=0; i<radioButton.length; i++) {
3110: radioButton[i].checked=false;
3111:
3112: }
3113: textbox.value = "";
3114: selval[0].selected = true;
3115:
3116: for (i=0;i<document.classgrade.total.value;i++) {
3117: var user = document.classgrade["ctr"+i].value;
3118: user = user.replace(new RegExp(':', 'g'),"_");
3119: var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3120: resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
3121: var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
3122: resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
3123: var saveselval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3124: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3125: if (saveselval == "excused") {
3126: if (selname[1].selected == false) { selname[1].selected = true;}
3127: } else {
3128: if (selname[0].selected == false) {selname[0].selected = true};
3129: }
3130: }
3131: }
3132: }
3133:
3134: </script>
3135: VIEWJAVASCRIPT
3136: }
3137:
3138: #--- show scores for a section or whole class w/ option to change/update a score
3139: sub viewgrades {
3140: my ($request) = shift;
3141: &viewgrades_js($request);
3142:
3143: my ($symb) = &get_symb($request);
3144: #need to make sure we have the correct data for later EXT calls,
3145: #thus invalidate the cache
3146: &Apache::lonnet::devalidatecourseresdata(
3147: $env{'course.'.$env{'request.course.id'}.'.num'},
3148: $env{'course.'.$env{'request.course.id'}.'.domain'});
3149: &Apache::lonnet::clear_EXT_cache_status();
3150:
3151: my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
3152: $result.='<h4><b>Current Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n";
3153:
3154: #view individual student submission form - called using Javascript viewOneStudent
3155: $result.=&jscriptNform($symb);
3156:
3157: #beginning of class grading form
3158: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
3159: $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
3160: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
3161: '<input type="hidden" name="command" value="editgrades" />'."\n".
3162: &build_section_inputs().
3163: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
3164: '<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
3165: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
3166:
3167: my $sectionClass;
3168: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3169: if ($env{'form.section'} eq 'all') {
3170: $sectionClass='Class </h3>';
3171: } elsif ($env{'form.section'} eq 'none') {
3172: $sectionClass=&mt('Students in no Section').'</h3>';
3173: } else {
3174: $sectionClass=&mt('Students in Section(s) [_1]',$section_display).'</h3>';
3175: }
3176: $result.='<h3>'.&mt('Assign Common Grade To [_1]',$sectionClass);
3177: $result.= &Apache::loncommon::start_data_table();
3178: #radio buttons/text box for assigning points for a section or class.
3179: #handles different parts of a problem
3180: my ($partlist,$handgrade,$responseType) = &response_type($symb);
3181: my %weight = ();
3182: my $ctsparts = 0;
3183: my %seen = ();
3184: my @part_response_id = &flatten_responseType($responseType);
3185: foreach my $part_response_id (@part_response_id) {
3186: my ($partid,$respid) = @{ $part_response_id };
3187: my $part_resp = join('_',@{ $part_response_id });
3188: next if $seen{$partid};
3189: $seen{$partid}++;
3190: my $handgrade=$$handgrade{$part_resp};
3191: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
3192: $weight{$partid} = $wgt eq '' ? '1' : $wgt;
3193:
3194: $result.=&Apache::loncommon::start_data_table_row().'<td>';
3195: $result.='<input type="hidden" name="partid_'.
3196: $ctsparts.'" value="'.$partid.'" />'."\n";
3197: $result.='<input type="hidden" name="weight_'.
3198: $partid.'" value="'.$weight{$partid}.'" />'."\n";
3199: my $display_part=&get_display_part($partid,$symb);
3200: $result.=
3201: '<b>Part:</b> '.$display_part.' <b>Point:</b> </td><td>';
3202: $result.='<table border="0"><tr>';
3203: my $ctr = 0;
3204: while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
3205: $result.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
3206: 'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
3207: ','.$ctr.')" />'.$ctr."</label></td>\n";
3208: $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
3209: $ctr++;
3210: }
3211: $result.='</tr></table>';
3212: $result.= '</td><td><b> or </b><input type="text" name="TEXTVAL_'.
3213: $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
3214: $partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
3215: $weight{$partid}.' (problem weight)</td>'."\n";
3216: $result.= '<td><select name="SELVAL_'.$partid.'"'.
3217: 'onChange="javascript:writeRadText(\''.$partid.'\','.
3218: $weight{$partid}.')"> '.
3219: '<option selected="selected"> </option>'.
3220: '<option>excused</option>'.
3221: '<option>reset status</option></select></td>'.
3222: '<td><label><input type="checkbox" name="FORCE_'.$partid.'" /> Override "Correct"</label></td>'.&Apache::loncommon::end_data_table_row()."\n";
3223: $ctsparts++;
3224: }
3225: $result.=&Apache::loncommon::end_data_table()."\n".
3226: '<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
3227: $result.='<input type="button" value="Revert to Default" '.
3228: 'onClick="javascript:resetEntry('.$ctsparts.');" />';
3229:
3230: #table listing all the students in a section/class
3231: #header of table
3232: $result.= '<h3>Assign Grade to Specific Students in '.$sectionClass;
3233: $result.= &Apache::loncommon::start_data_table().
3234: &Apache::loncommon::start_data_table_header_row().
3235: '<th>No.</th>'.
3236: '<th>'.&nameUserString('header')."</th>\n";
3237: my (@parts) = sort(&getpartlist($symb));
3238: my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
3239: my @partids = ();
3240: foreach my $part (@parts) {
3241: my $display=&Apache::lonnet::metadata($url,$part.'.display');
3242: $display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
3243: if (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
3244: my ($partid) = &split_part_type($part);
3245: push(@partids, $partid);
3246: my $display_part=&get_display_part($partid,$symb);
3247: if ($display =~ /^Partial Credit Factor/) {
3248: $result.='<th>Score Part: '.$display_part.
3249: ' <br />(weight = '.$weight{$partid}.')</th>'."\n";
3250: next;
3251: } else {
3252: $display =~s/\[Part: \Q$partid\E\]/Part:<\/b> $display_part/;
3253: }
3254: $display =~ s|Problem Status|Grade Status<br />|;
3255: $result.='<th>'.$display.'</th>'."\n";
3256: }
3257: $result.=&Apache::loncommon::end_data_table_header_row();
3258:
3259: my %last_resets =
3260: &get_last_resets($symb,$env{'request.course.id'},\@partids);
3261:
3262: #get info for each student
3263: #list all the students - with points and grade status
3264: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
3265: my $ctr = 0;
3266: foreach (sort
3267: {
3268: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
3269: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
3270: }
3271: return $a cmp $b;
3272: } (keys(%$fullname))) {
3273: $ctr++;
3274: $result.=&viewstudentgrade($symb,$env{'request.course.id'},
3275: $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
3276: }
3277: $result.=&Apache::loncommon::end_data_table();
3278: $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
3279: $result.='<input type="button" value="Save" '.
3280: 'onClick="javascript:submit();" target="_self" /></form>'."\n";
3281: if (scalar(%$fullname) eq 0) {
3282: my $colspan=3+scalar(@parts);
3283: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3284: my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
3285: $result='<span class="LC_warning">'.
3286: &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade',
3287: $section_display, $stu_status).
3288: '</span>';
3289: }
3290: $result.=&show_grading_menu_form($symb);
3291: return $result;
3292: }
3293:
3294: #--- call by previous routine to display each student
3295: sub viewstudentgrade {
3296: my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
3297: my ($uname,$udom) = split(/:/,$student);
3298: my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
3299: my %aggregates = ();
3300: my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
3301: '<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
3302: "\n".$ctr.' </td><td> '.
3303: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
3304: '\');" target="_self">'.$fullname.'</a> '.
3305: '<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
3306: $student=~s/:/_/; # colon doen't work in javascript for names
3307: foreach my $apart (@$parts) {
3308: my ($part,$type) = &split_part_type($apart);
3309: my $score=$record{"resource.$part.$type"};
3310: $result.='<td align="center">';
3311: my ($aggtries,$totaltries);
3312: unless (exists($aggregates{$part})) {
3313: $totaltries = $record{'resource.'.$part.'.tries'};
3314:
3315: $aggtries = $totaltries;
3316: if ($$last_resets{$part}) {
3317: $aggtries = &get_num_tries(\%record,$$last_resets{$part},
3318: $part);
3319: }
3320: $result.='<input type="hidden" name="'.
3321: 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
3322: $result.='<input type="hidden" name="'.
3323: 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
3324: $aggregates{$part} = 1;
3325: }
3326: if ($type eq 'awarded') {
3327: my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
3328: $result.='<input type="hidden" name="'.
3329: 'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
3330: $result.='<input type="text" name="'.
3331: 'GD_'.$student.'_'.$part.'_awarded" '.
3332: 'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
3333: '\')" value="'.$pts.'" size="4" /></td>'."\n";
3334: } elsif ($type eq 'solved') {
3335: my ($status,$foo)=split(/_/,$score,2);
3336: $status = 'nothing' if ($status eq '');
3337: $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
3338: $part.'_solved_s" value="'.$status.'" />'."\n";
3339: $result.=' <select name="'.
3340: 'GD_'.$student.'_'.$part.'_solved" '.
3341: 'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
3342: $result.= (($status eq 'excused') ? '<option> </option><option selected="selected">excused</option>'
3343: : '<option selected="selected"> </option><option>excused</option>')."\n";
3344: $result.='<option>reset status</option>';
3345: $result.="</select> </td>\n";
3346: } else {
3347: $result.='<input type="hidden" name="'.
3348: 'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
3349: "\n";
3350: $result.='<input type="text" name="'.
3351: 'GD_'.$student.'_'.$part.'_'.$type.'" '.
3352: 'value="'.$score.'" size="4" /></td>'."\n";
3353: }
3354: }
3355: $result.=&Apache::loncommon::end_data_table_row();
3356: return $result;
3357: }
3358:
3359: #--- change scores for all the students in a section/class
3360: # record does not get update if unchanged
3361: sub editgrades {
3362: my ($request) = @_;
3363:
3364: my $symb=&get_symb($request);
3365: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3366: my $title='<h2>'.&mt('Current Grade Status').'</h2>';
3367: $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
3368: $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
3369:
3370: my $result= &Apache::loncommon::start_data_table().
3371: &Apache::loncommon::start_data_table_header_row().
3372: '<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
3373: '<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
3374: my %scoreptr = (
3375: 'correct' =>'correct_by_override',
3376: 'incorrect'=>'incorrect_by_override',
3377: 'excused' =>'excused',
3378: 'ungraded' =>'ungraded_attempted',
3379: 'nothing' => '',
3380: );
3381: my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
3382:
3383: my (@partid);
3384: my %weight = ();
3385: my %columns = ();
3386: my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
3387:
3388: my (@parts) = sort(&getpartlist($symb));
3389: my $header;
3390: while ($ctr < $env{'form.totalparts'}) {
3391: my $partid = $env{'form.partid_'.$ctr};
3392: push @partid,$partid;
3393: $weight{$partid} = $env{'form.weight_'.$partid};
3394: $ctr++;
3395: }
3396: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3397: foreach my $partid (@partid) {
3398: $header .= '<th align="center">'.&mt('Old Score').'</th>'.
3399: '<th align="center">'.&mt('New Score').'</th>';
3400: $columns{$partid}=2;
3401: foreach my $stores (@parts) {
3402: my ($part,$type) = &split_part_type($stores);
3403: if ($part !~ m/^\Q$partid\E/) { next;}
3404: if ($type eq 'awarded' || $type eq 'solved') { next; }
3405: my $display=&Apache::lonnet::metadata($url,$stores.'.display');
3406: $display =~ s/\[Part: (\w)+\]//;
3407: $display =~ s/Number of Attempts/Tries/;
3408: $header .= '<th align="center">'.&mt('Old '.$display).'</th>'.
3409: '<th align="center">'.&mt('New '.$display).'</th>';
3410: $columns{$partid}+=2;
3411: }
3412: }
3413: foreach my $partid (@partid) {
3414: my $display_part=&get_display_part($partid,$symb);
3415: $result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
3416: &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
3417: '</th>';
3418:
3419: }
3420: $result .= &Apache::loncommon::end_data_table_header_row().
3421: &Apache::loncommon::start_data_table_header_row().
3422: $header.
3423: &Apache::loncommon::end_data_table_header_row();
3424: my @noupdate;
3425: my ($updateCtr,$noupdateCtr) = (1,1);
3426: for ($i=0; $i<$env{'form.total'}; $i++) {
3427: my $line;
3428: my $user = $env{'form.ctr'.$i};
3429: my ($uname,$udom)=split(/:/,$user);
3430: my %newrecord;
3431: my $updateflag = 0;
3432: $line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
3433: my $usec=$classlist->{"$uname:$udom"}[5];
3434: if (!&canmodify($usec)) {
3435: my $numcols=scalar(@partid)*4+2;
3436: push(@noupdate,
3437: $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
3438: &mt('Not allowed to modify student')."</span></td></tr>");
3439: next;
3440: }
3441: my %aggregate = ();
3442: my $aggregateflag = 0;
3443: $user=~s/:/_/; # colon doen't work in javascript for names
3444: foreach (@partid) {
3445: my $old_aw = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
3446: my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
3447: my $old_part = $old_aw eq '' ? '' : $old_part_pcr;
3448: my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
3449: my $awarded = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
3450: my $pcr = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
3451: my $partial = $awarded eq '' ? '' : $pcr;
3452: my $score;
3453: if ($partial eq '') {
3454: $score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
3455: } elsif ($partial > 0) {
3456: $score = 'correct_by_override';
3457: } elsif ($partial == 0) {
3458: $score = 'incorrect_by_override';
3459: }
3460: my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
3461: $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
3462:
3463: $newrecord{'resource.'.$_.'.regrader'}=
3464: "$env{'user.name'}:$env{'user.domain'}";
3465: if ($dropMenu eq 'reset status' &&
3466: $old_score ne '') { # ignore if no previous attempts => nothing to reset
3467: $newrecord{'resource.'.$_.'.tries'} = '';
3468: $newrecord{'resource.'.$_.'.solved'} = '';
3469: $newrecord{'resource.'.$_.'.award'} = '';
3470: $newrecord{'resource.'.$_.'.awarded'} = '';
3471: $updateflag = 1;
3472: if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
3473: my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
3474: my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
3475: my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
3476: &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
3477: $aggregateflag = 1;
3478: }
3479: } elsif (!($old_part eq $partial && $old_score eq $score)) {
3480: $updateflag = 1;
3481: $newrecord{'resource.'.$_.'.awarded'} = $partial if $partial ne '';
3482: $newrecord{'resource.'.$_.'.solved'} = $score;
3483: $rec_update++;
3484: }
3485:
3486: $line .= '<td align="center">'.$old_aw.' </td>'.
3487: '<td align="center">'.$awarded.
3488: ($score eq 'excused' ? $score : '').' </td>';
3489:
3490:
3491: my $partid=$_;
3492: foreach my $stores (@parts) {
3493: my ($part,$type) = &split_part_type($stores);
3494: if ($part !~ m/^\Q$partid\E/) { next;}
3495: if ($type eq 'awarded' || $type eq 'solved') { next; }
3496: my $old_aw = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
3497: my $awarded = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
3498: if ($awarded ne '' && $awarded ne $old_aw) {
3499: $newrecord{'resource.'.$part.'.'.$type}= $awarded;
3500: $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
3501: $updateflag=1;
3502: }
3503: $line .= '<td align="center">'.$old_aw.' </td>'.
3504: '<td align="center">'.$awarded.' </td>';
3505: }
3506: }
3507: $line.="\n";
3508:
3509: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3510: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3511:
3512: if ($updateflag) {
3513: $count++;
3514: &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
3515: $udom,$uname);
3516:
3517: if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
3518: $cnum,$udom,$uname)) {
3519: # need to figure out if should be in queue.
3520: my %record =
3521: &Apache::lonnet::restore($symb,$env{'request.course.id'},
3522: $udom,$uname);
3523: my $all_graded = 1;
3524: my $none_graded = 1;
3525: foreach my $part (@parts) {
3526: if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
3527: $all_graded = 0;
3528: } else {
3529: $none_graded = 0;
3530: }
3531: }
3532:
3533: if ($all_graded || $none_graded) {
3534: &Apache::bridgetask::remove_from_queue('gradingqueue',
3535: $symb,$cdom,$cnum,
3536: $udom,$uname);
3537: }
3538: }
3539:
3540: $result.=&Apache::loncommon::start_data_table_row().
3541: '<td align="right"> '.$updateCtr.' </td>'.$line.
3542: &Apache::loncommon::end_data_table_row();
3543: $updateCtr++;
3544: } else {
3545: push(@noupdate,
3546: '<td align="right"> '.$noupdateCtr.' </td>'.$line);
3547: $noupdateCtr++;
3548: }
3549: if ($aggregateflag) {
3550: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
3551: $cdom,$cnum);
3552: }
3553: }
3554: if (@noupdate) {
3555: # my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
3556: my $numcols=scalar(@partid)*4+2;
3557: $result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
3558: '<td align="center" colspan="'.$numcols.'">'.
3559: &mt('No Changes Occurred For the Students Below').
3560: '</td>'.
3561: &Apache::loncommon::end_data_table_row();
3562: foreach my $line (@noupdate) {
3563: $result.=
3564: &Apache::loncommon::start_data_table_row().
3565: $line.
3566: &Apache::loncommon::end_data_table_row();
3567: }
3568: }
3569: $result .= &Apache::loncommon::end_data_table().
3570: &show_grading_menu_form($symb);
3571: my $msg = '<p><b>'.
3572: &mt('Number of records updated = [_1] for [quant,_2,student].',
3573: $rec_update,$count).'</b><br />'.
3574: '<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
3575: '</b></p>';
3576: return $title.$msg.$result;
3577: }
3578:
3579: sub split_part_type {
3580: my ($partstr) = @_;
3581: my ($temp,@allparts)=split(/_/,$partstr);
3582: my $type=pop(@allparts);
3583: my $part=join('_',@allparts);
3584: return ($part,$type);
3585: }
3586:
3587: #------------- end of section for handling grading by section/class ---------
3588: #
3589: #----------------------------------------------------------------------------
3590:
3591:
3592: #----------------------------------------------------------------------------
3593: #
3594: #-------------------------- Next few routines handles grading by csv upload
3595: #
3596: #--- Javascript to handle csv upload
3597: sub csvupload_javascript_reverse_associate {
3598: my $error1=&mt('You need to specify the username or ID');
3599: my $error2=&mt('You need to specify at least one grading field');
3600: return(<<ENDPICK);
3601: function verify(vf) {
3602: var foundsomething=0;
3603: var founduname=0;
3604: var foundID=0;
3605: for (i=0;i<=vf.nfields.value;i++) {
3606: tw=eval('vf.f'+i+'.selectedIndex');
3607: if (i==0 && tw!=0) { foundID=1; }
3608: if (i==1 && tw!=0) { founduname=1; }
3609: if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
3610: }
3611: if (founduname==0 && foundID==0) {
3612: alert('$error1');
3613: return;
3614: }
3615: if (foundsomething==0) {
3616: alert('$error2');
3617: return;
3618: }
3619: vf.submit();
3620: }
3621: function flip(vf,tf) {
3622: var nw=eval('vf.f'+tf+'.selectedIndex');
3623: var i;
3624: for (i=0;i<=vf.nfields.value;i++) {
3625: //can not pick the same destination field for both name and domain
3626: if (((i ==0)||(i ==1)) &&
3627: ((tf==0)||(tf==1)) &&
3628: (i!=tf) &&
3629: (eval('vf.f'+i+'.selectedIndex')==nw)) {
3630: eval('vf.f'+i+'.selectedIndex=0;')
3631: }
3632: }
3633: }
3634: ENDPICK
3635: }
3636:
3637: sub csvupload_javascript_forward_associate {
3638: my $error1=&mt('You need to specify the username or ID');
3639: my $error2=&mt('You need to specify at least one grading field');
3640: return(<<ENDPICK);
3641: function verify(vf) {
3642: var foundsomething=0;
3643: var founduname=0;
3644: var foundID=0;
3645: for (i=0;i<=vf.nfields.value;i++) {
3646: tw=eval('vf.f'+i+'.selectedIndex');
3647: if (tw==1) { foundID=1; }
3648: if (tw==2) { founduname=1; }
3649: if (tw>3) { foundsomething=1; }
3650: }
3651: if (founduname==0 && foundID==0) {
3652: alert('$error1');
3653: return;
3654: }
3655: if (foundsomething==0) {
3656: alert('$error2');
3657: return;
3658: }
3659: vf.submit();
3660: }
3661: function flip(vf,tf) {
3662: var nw=eval('vf.f'+tf+'.selectedIndex');
3663: var i;
3664: //can not pick the same destination field twice
3665: for (i=0;i<=vf.nfields.value;i++) {
3666: if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
3667: eval('vf.f'+i+'.selectedIndex=0;')
3668: }
3669: }
3670: }
3671: ENDPICK
3672: }
3673:
3674: sub csvuploadmap_header {
3675: my ($request,$symb,$datatoken,$distotal)= @_;
3676: my $javascript;
3677: if ($env{'form.upfile_associate'} eq 'reverse') {
3678: $javascript=&csvupload_javascript_reverse_associate();
3679: } else {
3680: $javascript=&csvupload_javascript_forward_associate();
3681: }
3682:
3683: my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
3684: my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
3685: my $ignore=&mt('Ignore First Line');
3686: $symb = &Apache::lonenc::check_encrypt($symb);
3687: $request->print(<<ENDPICK);
3688: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3689: <h3><span class="LC_info">Uploading Class Grades</span></h3>
3690: $result
3691: <hr />
3692: <h3>Identify fields</h3>
3693: Total number of records found in file: $distotal <hr />
3694: Enter as many fields as you can. The system will inform you and bring you back
3695: to this page if the data selected is insufficient to run your class.<hr />
3696: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
3697: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
3698: <input type="hidden" name="associate" value="" />
3699: <input type="hidden" name="phase" value="three" />
3700: <input type="hidden" name="datatoken" value="$datatoken" />
3701: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
3702: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
3703: <input type="hidden" name="upfile_associate"
3704: value="$env{'form.upfile_associate'}" />
3705: <input type="hidden" name="symb" value="$symb" />
3706: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
3707: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
3708: <input type="hidden" name="command" value="csvuploadoptions" />
3709: <hr />
3710: <script type="text/javascript" language="Javascript">
3711: $javascript
3712: </script>
3713: ENDPICK
3714: return '';
3715:
3716: }
3717:
3718: sub csvupload_fields {
3719: my ($symb) = @_;
3720: my (@parts) = &getpartlist($symb);
3721: my @fields=(['ID','Student ID'],
3722: ['username','Student Username'],
3723: ['domain','Student Domain']);
3724: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3725: foreach my $part (sort(@parts)) {
3726: my @datum;
3727: my $display=&Apache::lonnet::metadata($url,$part.'.display');
3728: my $name=$part;
3729: if (!$display) { $display = $name; }
3730: @datum=($name,$display);
3731: if ($name=~/^stores_(.*)_awarded/) {
3732: push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
3733: }
3734: push(@fields,\@datum);
3735: }
3736: return (@fields);
3737: }
3738:
3739: sub csvuploadmap_footer {
3740: my ($request,$i,$keyfields) =@_;
3741: $request->print(<<ENDPICK);
3742: </table>
3743: <input type="hidden" name="nfields" value="$i" />
3744: <input type="hidden" name="keyfields" value="$keyfields" />
3745: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
3746: </form>
3747: ENDPICK
3748: }
3749:
3750: sub checkforfile_js {
3751: my $result =<<CSVFORMJS;
3752: <script type="text/javascript" language="javascript">
3753: function checkUpload(formname) {
3754: if (formname.upfile.value == "") {
3755: alert("Please use the browse button to select a file from your local directory.");
3756: return false;
3757: }
3758: formname.submit();
3759: }
3760: </script>
3761: CSVFORMJS
3762: return $result;
3763: }
3764:
3765: sub upcsvScores_form {
3766: my ($request) = shift;
3767: my ($symb)=&get_symb($request);
3768: if (!$symb) {return '';}
3769: my $result=&checkforfile_js();
3770: $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
3771: my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
3772: $result.=$table;
3773: $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
3774: $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
3775: $result.=' <b>'.&mt('Specify a file containing the class scores for current resource').
3776: '.</b></td></tr>'."\n";
3777: $result.='<tr bgcolor=#ffffe6><td>'."\n";
3778: my $upload=&mt("Upload Scores");
3779: my $upfile_select=&Apache::loncommon::upfile_select_html();
3780: my $ignore=&mt('Ignore First Line');
3781: $symb = &Apache::lonenc::check_encrypt($symb);
3782: $result.=<<ENDUPFORM;
3783: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3784: <input type="hidden" name="symb" value="$symb" />
3785: <input type="hidden" name="command" value="csvuploadmap" />
3786: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
3787: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
3788: $upfile_select
3789: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
3790: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
3791: </form>
3792: ENDUPFORM
3793: $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
3794: &mt("How do I create a CSV file from a spreadsheet"))
3795: .'</td></tr></table>'."\n";
3796: $result.='</td></tr></table><br /><br />'."\n";
3797: $result.=&show_grading_menu_form($symb);
3798: return $result;
3799: }
3800:
3801:
3802: sub csvuploadmap {
3803: my ($request)= @_;
3804: my ($symb)=&get_symb($request);
3805: if (!$symb) {return '';}
3806:
3807: my $datatoken;
3808: if (!$env{'form.datatoken'}) {
3809: $datatoken=&Apache::loncommon::upfile_store($request);
3810: } else {
3811: $datatoken=$env{'form.datatoken'};
3812: &Apache::loncommon::load_tmp_file($request);
3813: }
3814: my @records=&Apache::loncommon::upfile_record_sep();
3815: if ($env{'form.noFirstLine'}) { shift(@records); }
3816: &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
3817: my ($i,$keyfields);
3818: if (@records) {
3819: my @fields=&csvupload_fields($symb);
3820:
3821: if ($env{'form.upfile_associate'} eq 'reverse') {
3822: &Apache::loncommon::csv_print_samples($request,\@records);
3823: $i=&Apache::loncommon::csv_print_select_table($request,\@records,
3824: \@fields);
3825: foreach (@fields) { $keyfields.=$_->[0].','; }
3826: chop($keyfields);
3827: } else {
3828: unshift(@fields,['none','']);
3829: $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
3830: \@fields);
3831: foreach my $rec (@records) {
3832: my %temp = &Apache::loncommon::record_sep($rec);
3833: if (%temp) {
3834: $keyfields=join(',',sort(keys(%temp)));
3835: last;
3836: }
3837: }
3838: }
3839: }
3840: &csvuploadmap_footer($request,$i,$keyfields);
3841: $request->print(&show_grading_menu_form($symb));
3842:
3843: return '';
3844: }
3845:
3846: sub csvuploadoptions {
3847: my ($request)= @_;
3848: my ($symb)=&get_symb($request);
3849: my $checked=(($env{'form.noFirstLine'})?'1':'0');
3850: my $ignore=&mt('Ignore First Line');
3851: $request->print(<<ENDPICK);
3852: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3853: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
3854: <input type="hidden" name="command" value="csvuploadassign" />
3855: <!--
3856: <p>
3857: <label>
3858: <input type="checkbox" name="show_full_results" />
3859: Show a table of all changes
3860: </label>
3861: </p>
3862: -->
3863: <p>
3864: <label>
3865: <input type="checkbox" name="overwite_scores" checked="checked" />
3866: Overwrite any existing score
3867: </label>
3868: </p>
3869: ENDPICK
3870: my %fields=&get_fields();
3871: if (!defined($fields{'domain'})) {
3872: my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
3873: $request->print("\n<p> Users are in domain: ".$domform."</p>\n");
3874: }
3875: foreach my $key (sort(keys(%env))) {
3876: if ($key !~ /^form\.(.*)$/) { next; }
3877: my $cleankey=$1;
3878: if ($cleankey eq 'command') { next; }
3879: $request->print('<input type="hidden" name="'.$cleankey.
3880: '" value="'.$env{$key}.'" />'."\n");
3881: }
3882: # FIXME do a check for any duplicated user ids...
3883: # FIXME do a check for any invalid user ids?...
3884: $request->print('<input type="submit" value="Assign Grades" /><br />
3885: <hr /></form>'."\n");
3886: $request->print(&show_grading_menu_form($symb));
3887: return '';
3888: }
3889:
3890: sub get_fields {
3891: my %fields;
3892: my @keyfields = split(/\,/,$env{'form.keyfields'});
3893: for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
3894: if ($env{'form.upfile_associate'} eq 'reverse') {
3895: if ($env{'form.f'.$i} ne 'none') {
3896: $fields{$keyfields[$i]}=$env{'form.f'.$i};
3897: }
3898: } else {
3899: if ($env{'form.f'.$i} ne 'none') {
3900: $fields{$env{'form.f'.$i}}=$keyfields[$i];
3901: }
3902: }
3903: }
3904: return %fields;
3905: }
3906:
3907: sub csvuploadassign {
3908: my ($request)= @_;
3909: my ($symb)=&get_symb($request);
3910: if (!$symb) {return '';}
3911: my $error_msg = '';
3912: &Apache::loncommon::load_tmp_file($request);
3913: my @gradedata = &Apache::loncommon::upfile_record_sep();
3914: if ($env{'form.noFirstLine'}) { shift(@gradedata); }
3915: my %fields=&get_fields();
3916: $request->print('<h3>Assigning Grades</h3>');
3917: my $courseid=$env{'request.course.id'};
3918: my ($classlist) = &getclasslist('all',0);
3919: my @notallowed;
3920: my @skipped;
3921: my $countdone=0;
3922: foreach my $grade (@gradedata) {
3923: my %entries=&Apache::loncommon::record_sep($grade);
3924: my $domain;
3925: if ($entries{$fields{'domain'}}) {
3926: $domain=$entries{$fields{'domain'}};
3927: } else {
3928: $domain=$env{'form.default_domain'};
3929: }
3930: $domain=~s/\s//g;
3931: my $username=$entries{$fields{'username'}};
3932: $username=~s/\s//g;
3933: if (!$username) {
3934: my $id=$entries{$fields{'ID'}};
3935: $id=~s/\s//g;
3936: my %ids=&Apache::lonnet::idget($domain,$id);
3937: $username=$ids{$id};
3938: }
3939: if (!exists($$classlist{"$username:$domain"})) {
3940: my $id=$entries{$fields{'ID'}};
3941: $id=~s/\s//g;
3942: if ($id) {
3943: push(@skipped,"$id:$domain");
3944: } else {
3945: push(@skipped,"$username:$domain");
3946: }
3947: next;
3948: }
3949: my $usec=$classlist->{"$username:$domain"}[5];
3950: if (!&canmodify($usec)) {
3951: push(@notallowed,"$username:$domain");
3952: next;
3953: }
3954: my %points;
3955: my %grades;
3956: foreach my $dest (keys(%fields)) {
3957: if ($dest eq 'ID' || $dest eq 'username' ||
3958: $dest eq 'domain') { next; }
3959: if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
3960: if ($dest=~/stores_(.*)_points/) {
3961: my $part=$1;
3962: my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
3963: $symb,$domain,$username);
3964: if ($wgt) {
3965: $entries{$fields{$dest}}=~s/\s//g;
3966: my $pcr=$entries{$fields{$dest}} / $wgt;
3967: my $award=($pcr == 0) ? 'incorrect_by_override'
3968: : 'correct_by_override';
3969: $grades{"resource.$part.awarded"}=$pcr;
3970: $grades{"resource.$part.solved"}=$award;
3971: $points{$part}=1;
3972: } else {
3973: $error_msg = "<br />" .
3974: &mt("Some point values were assigned"
3975: ." for problems with a weight "
3976: ."of zero. These values were "
3977: ."ignored.");
3978: }
3979: } else {
3980: if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
3981: if ($dest=~/stores_(.*)_solved/) { if ($points{$1}) {next;} }
3982: my $store_key=$dest;
3983: $store_key=~s/^stores/resource/;
3984: $store_key=~s/_/\./g;
3985: $grades{$store_key}=$entries{$fields{$dest}};
3986: }
3987: }
3988: if (! %grades) { push(@skipped,"$username:$domain no data to save"); }
3989: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
3990: my $result=&Apache::lonnet::cstore(\%grades,$symb,
3991: $env{'request.course.id'},
3992: $domain,$username);
3993: if ($result eq 'ok') {
3994: $request->print('.');
3995: } else {
3996: $request->print("<p>
3997: <span class=\"LC_error\">
3998: Failed to save student $username:$domain.
3999: Message when trying to save was ($result)
4000: </span>
4001: </p>" );
4002: }
4003: $request->rflush();
4004: $countdone++;
4005: }
4006: $request->print("<br />Saved $countdone students\n");
4007: if (@skipped) {
4008: $request->print('<p><h4><b>Skipped Students</b></h4></p>');
4009: foreach my $student (@skipped) { $request->print("$student<br />\n"); }
4010: }
4011: if (@notallowed) {
4012: $request->print('<p><span class="LC_error">Students Not Allowed to Modify</span></p>');
4013: foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
4014: }
4015: $request->print("<br />\n");
4016: $request->print(&show_grading_menu_form($symb));
4017: return $error_msg;
4018: }
4019: #------------- end of section for handling csv file upload ---------
4020: #
4021: #-------------------------------------------------------------------
4022: #
4023: #-------------- Next few routines handle grading by page/sequence
4024: #
4025: #--- Select a page/sequence and a student to grade
4026: sub pickStudentPage {
4027: my ($request) = shift;
4028:
4029: $request->print(<<LISTJAVASCRIPT);
4030: <script type="text/javascript" language="javascript">
4031:
4032: function checkPickOne(formname) {
4033: if (radioSelection(formname.student) == null) {
4034: alert("Please select the student you wish to grade.");
4035: return;
4036: }
4037: ptr = pullDownSelection(formname.selectpage);
4038: formname.page.value = formname["page"+ptr].value;
4039: formname.title.value = formname["title"+ptr].value;
4040: formname.submit();
4041: }
4042:
4043: </script>
4044: LISTJAVASCRIPT
4045: &commonJSfunctions($request);
4046: my ($symb) = &get_symb($request);
4047: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4048: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4049: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4050:
4051: my $result='<h3><span class="LC_info"> '.
4052: 'Manual Grading by Page or Sequence</span></h3>';
4053:
4054: $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
4055: $result.=' <b>Problems from:</b> <select name="selectpage">'."\n";
4056: my ($titles,$symbx) = &getSymbMap();
4057: my ($curpage) =&Apache::lonnet::decode_symb($symb);
4058: # my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb);
4059: # my $type=($curpage =~ /\.(page|sequence)/);
4060: my $ctr=0;
4061: foreach (@$titles) {
4062: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4063: $result.='<option value="'.$ctr.'" '.
4064: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
4065: '>'.$showtitle.'</option>'."\n";
4066: $ctr++;
4067: }
4068: $result.= '</select>'."<br />\n";
4069: $ctr=0;
4070: foreach (@$titles) {
4071: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4072: $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
4073: $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
4074: $ctr++;
4075: }
4076: $result.='<input type="hidden" name="page" />'."\n".
4077: '<input type="hidden" name="title" />'."\n";
4078:
4079: $result.=' <b>View Problems Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
4080: '<label><input type="radio" name="vProb" value="yes" /> yes </label>'."<br />\n";
4081:
4082: $result.=' <b>Submission Details: </b>'.
4083: '<label><input type="radio" name="lastSub" value="none" /> none</label>'."\n".
4084: '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> by dates and submissions</label>'."\n".
4085: '<label><input type="radio" name="lastSub" value="all" /> all details</label>'."\n";
4086:
4087: $result.=&build_section_inputs();
4088: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
4089: $result.='<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
4090: '<input type="hidden" name="command" value="displayPage" />'."\n".
4091: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
4092: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
4093:
4094: $result.=' <b>'.&mt('Use CODE:').' </b>'.
4095: '<input type="text" name="CODE" value="" /><br />'."\n";
4096:
4097: $result.=' <input type="button" '.
4098: 'onClick="javascript:checkPickOne(this.form);"value="Next->" /><br />'."\n";
4099:
4100: $request->print($result);
4101:
4102: my $studentTable.=' <b>Select a student you wish to grade and then click on the Next button.</b><br />'.
4103: '<table border="0"><tr><td bgcolor="#777777">'.
4104: '<table border="0"><tr bgcolor="#e6ffff">'.
4105: '<td align="right"> <b>No.</b></td>'.
4106: '<td>'.&nameUserString('header').'</td>'.
4107: '<td align="right"> <b>No.</b></td>'.
4108: '<td>'.&nameUserString('header').'</td></tr>';
4109:
4110: my (undef,undef,$fullname) = &getclasslist($getsec,'1');
4111: my $ptr = 1;
4112: foreach my $student (sort
4113: {
4114: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
4115: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
4116: }
4117: return $a cmp $b;
4118: } (keys(%$fullname))) {
4119: my ($uname,$udom) = split(/:/,$student);
4120: $studentTable.=($ptr%2 == 1 ? '<tr bgcolor="#ffffe6">' : '</td>');
4121: $studentTable.='<td align="right">'.$ptr.' </td>';
4122: $studentTable.='<td> <label><input type="radio" name="student" value="'.$student.'" /> '
4123: .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
4124: $studentTable.=($ptr%2 == 0 ? '</td></tr>' : '');
4125: $ptr++;
4126: }
4127: $studentTable.='</td><td> </td><td> </td></tr>' if ($ptr%2 == 0);
4128: $studentTable.='</table></td></tr></table>'."\n";
4129: $studentTable.='<input type="button" '.
4130: 'onClick="javascript:checkPickOne(this.form);"value="Next->" /></form>'."\n";
4131:
4132: $studentTable.=&show_grading_menu_form($symb);
4133: $request->print($studentTable);
4134:
4135: return '';
4136: }
4137:
4138: sub getSymbMap {
4139: my $navmap = Apache::lonnavmaps::navmap->new();
4140:
4141: my %symbx = ();
4142: my @titles = ();
4143: my $minder = 0;
4144:
4145: # Gather every sequence that has problems.
4146: my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
4147: 1,0,1);
4148: for my $sequence ($navmap->getById('0.0'), @sequences) {
4149: if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
4150: my $title = $minder.'.'.
4151: &HTML::Entities::encode($sequence->compTitle(),'"\'&');
4152: push(@titles, $title); # minder in case two titles are identical
4153: $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
4154: $minder++;
4155: }
4156: }
4157: return \@titles,\%symbx;
4158: }
4159:
4160: #
4161: #--- Displays a page/sequence w/wo problems, w/wo submissions
4162: sub displayPage {
4163: my ($request) = shift;
4164:
4165: my ($symb) = &get_symb($request);
4166: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4167: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4168: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4169: my $pageTitle = $env{'form.page'};
4170: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
4171: my ($uname,$udom) = split(/:/,$env{'form.student'});
4172: my $usec=$classlist->{$env{'form.student'}}[5];
4173:
4174: #need to make sure we have the correct data for later EXT calls,
4175: #thus invalidate the cache
4176: &Apache::lonnet::devalidatecourseresdata(
4177: $env{'course.'.$env{'request.course.id'}.'.num'},
4178: $env{'course.'.$env{'request.course.id'}.'.domain'});
4179: &Apache::lonnet::clear_EXT_cache_status();
4180:
4181: if (!&canview($usec)) {
4182: $request->print('<span class="LC_warning">Unable to view requested student.('.$env{'form.student'}.')</span>');
4183: $request->print(&show_grading_menu_form($symb));
4184: return;
4185: }
4186: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
4187: $result.='<h3> Student: '.&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom).
4188: '</h3>'."\n";
4189: if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
4190: $result.='<h3> CODE: '.$env{'form.CODE'}.'</h3>'."\n";
4191: } else {
4192: delete($env{'form.CODE'});
4193: }
4194: &sub_page_js($request);
4195: $request->print($result);
4196:
4197: my $navmap = Apache::lonnavmaps::navmap->new();
4198: my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
4199: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
4200: if (!$map) {
4201: $request->print('<span class="LC_warning">Unable to view requested sequence. ('.$resUrl.')</span>');
4202: $request->print(&show_grading_menu_form($symb));
4203: return;
4204: }
4205: my $iterator = $navmap->getIterator($map->map_start(),
4206: $map->map_finish());
4207:
4208: my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
4209: '<input type="hidden" name="command" value="gradeByPage" />'."\n".
4210: '<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
4211: '<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
4212: '<input type="hidden" name="page" value="'.$pageTitle.'" />'."\n".
4213: '<input type="hidden" name="title" value="'.$env{'form.title'}.'" />'."\n".
4214: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
4215: '<input type="hidden" name="overRideScore" value="no" />'."\n".
4216: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
4217:
4218: if (defined($env{'form.CODE'})) {
4219: $studentTable.=
4220: '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
4221: }
4222: my $checkIcon = '<img alt="'.&mt('Check Mark').
4223: '" src="'.$request->dir_config('lonIconsURL').
4224: '/check.gif" height="16" border="0" />';
4225:
4226: $studentTable.=' <b>Note:</b> Problems graded correct by the computer are marked with a '.$checkIcon.
4227: ' symbol.'."\n".
4228: '<table border="0"><tr><td bgcolor="#777777">'.
4229: '<table border="0"><tr bgcolor="#e6ffff">'.
4230: '<td align="center"><b> Prob. </b></td>'.
4231: '<td><b> '.($env{'form.vProb'} eq 'no' ? 'Title' : 'Problem Text').'/Grade</b></td></tr>';
4232:
4233: &Apache::lonxml::clear_problem_counter();
4234: my ($depth,$question,$prob) = (1,1,1);
4235: $iterator->next(); # skip the first BEGIN_MAP
4236: my $curRes = $iterator->next(); # for "current resource"
4237: while ($depth > 0) {
4238: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
4239: if($curRes == $iterator->END_MAP) { $depth--; }
4240:
4241: if (ref($curRes) && $curRes->is_problem()) {
4242: my $parts = $curRes->parts();
4243: my $title = $curRes->compTitle();
4244: my $symbx = $curRes->symb();
4245: $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
4246: (scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).' parts)').'</td>';
4247: $studentTable.='<td valign="top">';
4248: my %form = ('CODE' => $env{'form.CODE'},);
4249: if ($env{'form.vProb'} eq 'yes' ) {
4250: $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
4251: undef,'both',\%form);
4252: } else {
4253: my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
4254: $companswer =~ s|<form(.*?)>||g;
4255: $companswer =~ s|</form>||g;
4256: # while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
4257: # $companswer =~ s/$1/ /ms;
4258: # $request->print('match='.$1."<br />\n");
4259: # }
4260: # $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
4261: $studentTable.=' <b>'.$title.'</b> <br /> <b>Correct answer:</b><br />'.$companswer;
4262: }
4263:
4264: my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
4265:
4266: if ($env{'form.lastSub'} eq 'datesub') {
4267: if ($record{'version'} eq '') {
4268: $studentTable.='<br /> <span class="LC_warning">No recorded submission for this problem</span><br />';
4269: } else {
4270: my %responseType = ();
4271: foreach my $partid (@{$parts}) {
4272: my @responseIds =$curRes->responseIds($partid);
4273: my @responseType =$curRes->responseType($partid);
4274: my %responseIds;
4275: for (my $i=0;$i<=$#responseIds;$i++) {
4276: $responseIds{$responseIds[$i]}=$responseType[$i];
4277: }
4278: $responseType{$partid} = \%responseIds;
4279: }
4280: $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
4281:
4282: }
4283: } elsif ($env{'form.lastSub'} eq 'all') {
4284: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
4285: $studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
4286: $env{'request.course.id'},
4287: '','.submission');
4288:
4289: }
4290: if (&canmodify($usec)) {
4291: foreach my $partid (@{$parts}) {
4292: $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
4293: $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
4294: $question++;
4295: }
4296: $prob++;
4297: }
4298: $studentTable.='</td></tr>';
4299:
4300: }
4301: $curRes = $iterator->next();
4302: }
4303:
4304: $studentTable.='</table></td></tr></table>'."\n".
4305: '<input type="button" value="Save" '.
4306: 'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
4307: '</form>'."\n";
4308: $studentTable.=&show_grading_menu_form($symb);
4309: $request->print($studentTable);
4310:
4311: return '';
4312: }
4313:
4314: sub displaySubByDates {
4315: my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
4316: my $isCODE=0;
4317: my $isTask = ($symb =~/\.task$/);
4318: if (exists($record->{'resource.CODE'})) { $isCODE=1; }
4319: my $studentTable=&Apache::loncommon::start_data_table().
4320: &Apache::loncommon::start_data_table_header_row().
4321: '<th>'.&mt('Date/Time').'</th>'.
4322: ($isCODE?'<th>'.&mt('CODE').'</th>':'').
4323: '<th>'.&mt('Submission').'</th>'.
4324: '<th>'.&mt('Status').'</th>'.
4325: &Apache::loncommon::end_data_table_header_row();
4326: my ($version);
4327: my %mark;
4328: my %orders;
4329: $mark{'correct_by_student'} = $checkIcon;
4330: if (!exists($$record{'1:timestamp'})) {
4331: return '<br /> <span class="LC_warning">'.&mt('Nothing submitted - no attempts').'</span><br />';
4332: }
4333:
4334: my $interaction;
4335: for ($version=1;$version<=$$record{'version'};$version++) {
4336: my $timestamp =
4337: &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
4338: if (exists($$record{$version.':resource.0.version'})) {
4339: $interaction = $$record{$version.':resource.0.version'};
4340: }
4341:
4342: my $where = ($isTask ? "$version:resource.$interaction"
4343: : "$version:resource");
4344: $studentTable.=&Apache::loncommon::start_data_table_row().
4345: '<td>'.$timestamp.'</td>';
4346: if ($isCODE) {
4347: $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
4348: }
4349: my @versionKeys = split(/\:/,$$record{$version.':keys'});
4350: my @displaySub = ();
4351: foreach my $partid (@{$parts}) {
4352: my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
4353: : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
4354:
4355:
4356: # next if ($$record{"$version:resource.$partid.solved"} eq '');
4357: my $display_part=&get_display_part($partid,$symb);
4358: foreach my $matchKey (@matchKey) {
4359: if (exists($$record{$version.':'.$matchKey}) &&
4360: $$record{$version.':'.$matchKey} ne '') {
4361:
4362: my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
4363: : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
4364: $displaySub[0].='<b>'.&mt('Part:').'</b> '.$display_part.' ';
4365: $displaySub[0].='<span class="LC_internal_info">('.&mt('ID').' '.
4366: $responseId.')</span> <b>';
4367: if ($$record{"$where.$partid.tries"} eq '') {
4368: $displaySub[0].=&mt('Trial not counted');
4369: } else {
4370: $displaySub[0].=&mt('Trial [_1]',
4371: $$record{"$where.$partid.tries"});
4372: }
4373: my $responseType=($isTask ? 'Task'
4374: : $responseType->{$partid}->{$responseId});
4375: if (!exists($orders{$partid})) { $orders{$partid}={}; }
4376: if (!exists($orders{$partid}->{$responseId})) {
4377: $orders{$partid}->{$responseId}=
4378: &get_order($partid,$responseId,$symb,$uname,$udom);
4379: }
4380: $displaySub[0].='</b> '.
4381: &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
4382: }
4383: }
4384: if (exists($$record{"$where.$partid.checkedin"})) {
4385: $displaySub[1].='Checked in by '.
4386: $$record{"$where.$partid.checkedin"}.' into slot '.
4387: $$record{"$where.$partid.checkedin.slot"}.
4388: '<br />';
4389: }
4390: if (exists $$record{"$where.$partid.award"}) {
4391: $displaySub[1].='<b>Part:</b> '.$display_part.' '.
4392: lc($$record{"$where.$partid.award"}).' '.
4393: $mark{$$record{"$where.$partid.solved"}}.
4394: '<br />';
4395: }
4396: if (exists $$record{"$where.$partid.regrader"}) {
4397: $displaySub[2].=$$record{"$where.$partid.regrader"}.
4398: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
4399: } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
4400: $displaySub[2].=
4401: $$record{"$version:resource.$partid.regrader"}.
4402: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
4403: }
4404: }
4405: # needed because old essay regrader has not parts info
4406: if (exists $$record{"$version:resource.regrader"}) {
4407: $displaySub[2].=$$record{"$version:resource.regrader"};
4408: }
4409: $studentTable.='<td>'.$displaySub[0].' </td><td>'.$displaySub[1];
4410: if ($displaySub[2]) {
4411: $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
4412: }
4413: $studentTable.=' </td>'.
4414: &Apache::loncommon::end_data_table_row();
4415: }
4416: $studentTable.=&Apache::loncommon::end_data_table();
4417: return $studentTable;
4418: }
4419:
4420: sub updateGradeByPage {
4421: my ($request) = shift;
4422:
4423: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4424: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4425: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4426: my $pageTitle = $env{'form.page'};
4427: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
4428: my ($uname,$udom) = split(/:/,$env{'form.student'});
4429: my $usec=$classlist->{$env{'form.student'}}[5];
4430: if (!&canmodify($usec)) {
4431: $request->print('<span class="LC_warning">Unable to modify requested student.('.$env{'form.student'}.'</span>');
4432: $request->print(&show_grading_menu_form($env{'form.symb'}));
4433: return;
4434: }
4435: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
4436: $result.='<h3> Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
4437: '</h3>'."\n";
4438:
4439: $request->print($result);
4440:
4441: my $navmap = Apache::lonnavmaps::navmap->new();
4442: my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
4443: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
4444: if (!$map) {
4445: $request->print('<span class="LC_warning">Unable to grade requested sequence. ('.$resUrl.')</span>');
4446: my ($symb)=&get_symb($request);
4447: $request->print(&show_grading_menu_form($symb));
4448: return;
4449: }
4450: my $iterator = $navmap->getIterator($map->map_start(),
4451: $map->map_finish());
4452:
4453: my $studentTable='<table border="0"><tr><td bgcolor="#777777">'.
4454: '<table border="0"><tr bgcolor="#e6ffff">'.
4455: '<td align="center"><b> Prob. </b></td>'.
4456: '<td><b> Title </b></td>'.
4457: '<td><b> Previous Score </b></td>'.
4458: '<td><b> New Score </b></td></tr>';
4459:
4460: $iterator->next(); # skip the first BEGIN_MAP
4461: my $curRes = $iterator->next(); # for "current resource"
4462: my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
4463: while ($depth > 0) {
4464: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
4465: if($curRes == $iterator->END_MAP) { $depth--; }
4466:
4467: if (ref($curRes) && $curRes->is_problem()) {
4468: my $parts = $curRes->parts();
4469: my $title = $curRes->compTitle();
4470: my $symbx = $curRes->symb();
4471: $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
4472: (scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).' parts)').'</td>';
4473: $studentTable.='<td valign="top"> <b>'.$title.'</b> </td>';
4474:
4475: my %newrecord=();
4476: my @displayPts=();
4477: my %aggregate = ();
4478: my $aggregateflag = 0;
4479: foreach my $partid (@{$parts}) {
4480: my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
4481: my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
4482:
4483: my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ?
4484: $env{'form.WGT'.$question.'_'.$partid} : 1;
4485: my $partial = $newpts/$wgt;
4486: my $score;
4487: if ($partial > 0) {
4488: $score = 'correct_by_override';
4489: } elsif ($newpts ne '') { #empty is taken as 0
4490: $score = 'incorrect_by_override';
4491: }
4492: my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
4493: if ($dropMenu eq 'excused') {
4494: $partial = '';
4495: $score = 'excused';
4496: } elsif ($dropMenu eq 'reset status'
4497: && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
4498: $newrecord{'resource.'.$partid.'.tries'} = 0;
4499: $newrecord{'resource.'.$partid.'.solved'} = '';
4500: $newrecord{'resource.'.$partid.'.award'} = '';
4501: $newrecord{'resource.'.$partid.'.awarded'} = 0;
4502: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
4503: $changeflag++;
4504: $newpts = '';
4505:
4506: my $aggtries = $env{'form.aggtries'.$question.'_'.$partid};
4507: my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
4508: my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
4509: if ($aggtries > 0) {
4510: &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
4511: $aggregateflag = 1;
4512: }
4513: }
4514: my $display_part=&get_display_part($partid,$curRes->symb());
4515: my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
4516: $displayPts[0].=' <b>Part:</b> '.$display_part.' = '.
4517: (($oldstatus eq 'excused') ? 'excused' : $oldpts).
4518: ' <br />';
4519: $displayPts[1].=' <b>Part:</b> '.$display_part.' = '.
4520: (($score eq 'excused') ? 'excused' : $newpts).
4521: ' <br />';
4522: $question++;
4523: next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
4524:
4525: $newrecord{'resource.'.$partid.'.awarded'} = $partial if $partial ne '';
4526: $newrecord{'resource.'.$partid.'.solved'} = $score if $score ne '';
4527: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
4528: if (scalar(keys(%newrecord)) > 0);
4529:
4530: $changeflag++;
4531: }
4532: if (scalar(keys(%newrecord)) > 0) {
4533: my %record =
4534: &Apache::lonnet::restore($symbx,$env{'request.course.id'},
4535: $udom,$uname);
4536:
4537: if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
4538: $newrecord{'resource.CODE'} = $env{'form.CODE'};
4539: } elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
4540: $newrecord{'resource.CODE'} = '';
4541: }
4542: &Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
4543: $udom,$uname);
4544: %record = &Apache::lonnet::restore($symbx,
4545: $env{'request.course.id'},
4546: $udom,$uname);
4547: &check_and_remove_from_queue($parts,\%record,undef,$symbx,
4548: $cdom,$cnum,$udom,$uname);
4549: }
4550:
4551: if ($aggregateflag) {
4552: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
4553: $env{'course.'.$env{'request.course.id'}.'.domain'},
4554: $env{'course.'.$env{'request.course.id'}.'.num'});
4555: }
4556:
4557: $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
4558: '<td valign="top">'.$displayPts[1].'</td>'.
4559: '</tr>';
4560:
4561: $prob++;
4562: }
4563: $curRes = $iterator->next();
4564: }
4565:
4566: $studentTable.='</td></tr></table></td></tr></table>';
4567: $studentTable.=&show_grading_menu_form($env{'form.symb'});
4568: my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
4569: 'The scores were changed for '.
4570: $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
4571: $request->print($grademsg.$studentTable);
4572:
4573: return '';
4574: }
4575:
4576: #-------- end of section for handling grading by page/sequence ---------
4577: #
4578: #-------------------------------------------------------------------
4579:
4580: #--------------------Scantron Grading-----------------------------------
4581: #
4582: #------ start of section for handling grading by page/sequence ---------
4583:
4584: =pod
4585:
4586: =head1 Bubble sheet grading routines
4587:
4588: For this documentation:
4589:
4590: 'scanline' refers to the full line of characters
4591: from the file that we are parsing that represents one entire sheet
4592:
4593: 'bubble line' refers to the data
4594: representing the line of bubbles that are on the physical bubble sheet
4595:
4596:
4597: The overall process is that a scanned in bubble sheet data is uploaded
4598: into a course. When a user wants to grade, they select a
4599: sequence/folder of resources, a file of bubble sheet info, and pick
4600: one of the predefined configurations for what each scanline looks
4601: like.
4602:
4603: Next each scanline is checked for any errors of either 'missing
4604: bubbles' (it's an error because it may have been mis-scanned
4605: because too light bubbling), 'double bubble' (each bubble line should
4606: have no more that one letter picked), invalid or duplicated CODE,
4607: invalid student ID
4608:
4609: If the CODE option is used that determines the randomization of the
4610: homework problems, either way the student ID is looked up into a
4611: username:domain.
4612:
4613: During the validation phase the instructor can choose to skip scanlines.
4614:
4615: After the validation phase, there are now 3 bubble sheet files
4616:
4617: scantron_original_filename (unmodified original file)
4618: scantron_corrected_filename (file where the corrected information has replaced the original information)
4619: scantron_skipped_filename (contains the exact text of scanlines that where skipped)
4620:
4621: Also there is a separate hash nohist_scantrondata that contains extra
4622: correction information that isn't representable in the bubble sheet
4623: file (see &scantron_getfile() for more information)
4624:
4625: After all scanlines are either valid, marked as valid or skipped, then
4626: foreach line foreach problem in the picked sequence, an ssi request is
4627: made that simulates a user submitting their selected letter(s) against
4628: the homework problem.
4629:
4630: =over 4
4631:
4632:
4633:
4634: =item defaultFormData
4635:
4636: Returns html hidden inputs used to hold context/default values.
4637:
4638: Arguments:
4639: $symb - $symb of the current resource
4640:
4641: =cut
4642:
4643: sub defaultFormData {
4644: my ($symb)=@_;
4645: return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
4646: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
4647: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
4648: }
4649:
4650:
4651: =pod
4652:
4653: =item getSequenceDropDown
4654:
4655: Return html dropdown of possible sequences to grade
4656:
4657: Arguments:
4658: $symb - $symb of the current resource
4659:
4660: =cut
4661:
4662: sub getSequenceDropDown {
4663: my ($symb)=@_;
4664: my $result='<select name="selectpage">'."\n";
4665: my ($titles,$symbx) = &getSymbMap();
4666: my ($curpage)=&Apache::lonnet::decode_symb($symb);
4667: my $ctr=0;
4668: foreach (@$titles) {
4669: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4670: $result.='<option value="'.$$symbx{$_}.'" '.
4671: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
4672: '>'.$showtitle.'</option>'."\n";
4673: $ctr++;
4674: }
4675: $result.= '</select>';
4676: return $result;
4677: }
4678:
4679:
4680: =pod
4681:
4682: =item scantron_filenames
4683:
4684: Returns a list of the scantron files in the current course
4685:
4686: =cut
4687:
4688: sub scantron_filenames {
4689: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4690: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
4691: my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
4692: &propath($cdom,$cname));
4693: my @possiblenames;
4694: foreach my $filename (sort(@files)) {
4695: ($filename)=split(/&/,$filename);
4696: if ($filename!~/^scantron_orig_/) { next ; }
4697: $filename=~s/^scantron_orig_//;
4698: push(@possiblenames,$filename);
4699: }
4700: return @possiblenames;
4701: }
4702:
4703: =pod
4704:
4705: =item scantron_uploads
4706:
4707: Returns html drop-down list of scantron files in current course.
4708:
4709: Arguments:
4710: $file2grade - filename to set as selected in the dropdown
4711:
4712: =cut
4713:
4714: sub scantron_uploads {
4715: my ($file2grade) = @_;
4716: my $result= '<select name="scantron_selectfile">';
4717: $result.="<option></option>";
4718: foreach my $filename (sort(&scantron_filenames())) {
4719: $result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
4720: }
4721: $result.="</select>";
4722: return $result;
4723: }
4724:
4725: =pod
4726:
4727: =item scantron_scantab
4728:
4729: Returns html drop down of the scantron formats in the scantronformat.tab
4730: file.
4731:
4732: =cut
4733:
4734: sub scantron_scantab {
4735: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
4736: my $result='<select name="scantron_format">'."\n";
4737: $result.='<option></option>'."\n";
4738: foreach my $line (<$fh>) {
4739: my ($name,$descrip)=split(/:/,$line);
4740: if ($name =~ /^\#/) { next; }
4741: $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
4742: }
4743: $result.='</select>'."\n";
4744:
4745: return $result;
4746: }
4747:
4748: =pod
4749:
4750: =item scantron_CODElist
4751:
4752: Returns html drop down of the saved CODE lists from current course,
4753: generated from earlier printings.
4754:
4755: =cut
4756:
4757: sub scantron_CODElist {
4758: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4759: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4760: my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
4761: my $namechoice='<option></option>';
4762: foreach my $name (sort {uc($a) cmp uc($b)} @names) {
4763: if ($name =~ /^error: 2 /) { next; }
4764: if ($name =~ /^type\0/) { next; }
4765: $namechoice.='<option value="'.$name.'">'.$name.'</option>';
4766: }
4767: $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
4768: return $namechoice;
4769: }
4770:
4771: =pod
4772:
4773: =item scantron_CODEunique
4774:
4775: Returns the html for "Each CODE to be used once" radio.
4776:
4777: =cut
4778:
4779: sub scantron_CODEunique {
4780: my $result='<span style="white-space: nowrap;">
4781: <label><input type="radio" name="scantron_CODEunique"
4782: value="yes" checked="checked" />'.&mt('Yes').' </label>
4783: </span>
4784: <span style="white-space: nowrap;">
4785: <label><input type="radio" name="scantron_CODEunique"
4786: value="no" />'.&mt('No').' </label>
4787: </span>';
4788: return $result;
4789: }
4790:
4791: =pod
4792:
4793: =item scantron_selectphase
4794:
4795: Generates the initial screen to start the bubble sheet process.
4796: Allows for - starting a grading run.
4797: - downloading existing scan data (original, corrected
4798: or skipped info)
4799:
4800: - uploading new scan data
4801:
4802: Arguments:
4803: $r - The Apache request object
4804: $file2grade - name of the file that contain the scanned data to score
4805:
4806: =cut
4807:
4808: sub scantron_selectphase {
4809: my ($r,$file2grade) = @_;
4810: my ($symb)=&get_symb($r);
4811: if (!$symb) {return '';}
4812: my $sequence_selector=&getSequenceDropDown($symb);
4813: my $default_form_data=&defaultFormData($symb);
4814: my $grading_menu_button=&show_grading_menu_form($symb);
4815: my $file_selector=&scantron_uploads($file2grade);
4816: my $format_selector=&scantron_scantab();
4817: my $CODE_selector=&scantron_CODElist();
4818: my $CODE_unique=&scantron_CODEunique();
4819: my $result;
4820:
4821: # Chunk of form to prompt for a file to grade and how:
4822:
4823: $result.= <<SCANTRONFORM;
4824: <table width="100%" border="0">
4825: <tr>
4826: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
4827: <td bgcolor="#777777">
4828: <input type="hidden" name="command" value="scantron_warning" />
4829: $default_form_data
4830: <table width="100%" border="0">
4831: <tr bgcolor="#e6ffff">
4832: <td colspan="2">
4833: <b>Specify file and which Folder/Sequence to grade</b>
4834: </td>
4835: </tr>
4836: <tr bgcolor="#ffffe6">
4837: <td> Sequence to grade: </td><td> $sequence_selector </td>
4838: </tr>
4839: <tr bgcolor="#ffffe6">
4840: <td> Filename of scoring office file: </td><td> $file_selector </td>
4841: </tr>
4842: <tr bgcolor="#ffffe6">
4843: <td> Format of data file: </td><td> $format_selector </td>
4844: </tr>
4845: <tr bgcolor="#ffffe6">
4846: <td> Saved CODEs to validate against: </td><td> $CODE_selector</td>
4847: </tr>
4848: <tr bgcolor="#ffffe6">
4849: <td> Each CODE is only to be used once:</td><td> $CODE_unique </td>
4850: </tr>
4851: <tr bgcolor="#ffffe6">
4852: <td> Options: </td>
4853: <td>
4854: <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> Do only previously skipped records</label> <br />
4855: <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> Remove all existing corrections</label> <br />
4856: <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> Skip hidden resources when grading</label>
4857: </td>
4858: </tr>
4859: <tr bgcolor="#ffffe6">
4860: <td colspan="2">
4861: <input type="submit" value="Grading: Validate Scantron Records" />
4862: </td>
4863: </tr>
4864: </table>
4865: </td>
4866: </form>
4867: </tr>
4868: SCANTRONFORM
4869:
4870: $r->print($result);
4871:
4872: if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
4873: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
4874:
4875: # Chunk of form to prompt for a scantron file upload.
4876:
4877: $r->print(<<SCANTRONFORM);
4878: <tr>
4879: <td bgcolor="#777777">
4880: <table width="100%" border="0">
4881: <tr bgcolor="#e6ffff">
4882: <td>
4883: <b>Specify a Scantron data file to upload.</b>
4884: </td>
4885: </tr>
4886: <tr bgcolor="#ffffe6">
4887: <td>
4888: SCANTRONFORM
4889: my $default_form_data=&defaultFormData(&get_symb($r,1));
4890: my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
4891: my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
4892: $r->print(<<UPLOAD);
4893: <script type="text/javascript" language="javascript">
4894: function checkUpload(formname) {
4895: if (formname.upfile.value == "") {
4896: alert("Please use the browse button to select a file from your local directory.");
4897: return false;
4898: }
4899: formname.submit();
4900: }
4901: </script>
4902:
4903: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
4904: $default_form_data
4905: <input name='courseid' type='hidden' value='$cnum' />
4906: <input name='domainid' type='hidden' value='$cdom' />
4907: <input name='command' value='scantronupload_save' type='hidden' />
4908: File to upload:<input type="file" name="upfile" size="50" />
4909: <br />
4910: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
4911: </form>
4912: UPLOAD
4913:
4914: $r->print(<<SCANTRONFORM);
4915: </td>
4916: </tr>
4917: </table>
4918: </td>
4919: </tr>
4920: SCANTRONFORM
4921: }
4922:
4923: # Chunk of the form that prompts to view a scoring office file,
4924: # corrected file, skipped records in a file.
4925:
4926: $r->print(<<SCANTRONFORM);
4927: <tr>
4928: <form action='/adm/grades' name='scantron_download'>
4929: <td bgcolor="#777777">
4930: $default_form_data
4931: <input type="hidden" name="command" value="scantron_download" />
4932: <table width="100%" border="0">
4933: <tr bgcolor="#e6ffff">
4934: <td colspan="2">
4935: <b>Download a scoring office file</b>
4936: </td>
4937: </tr>
4938: <tr bgcolor="#ffffe6">
4939: <td> Filename of scoring office file: </td><td> $file_selector </td>
4940: </tr>
4941: <tr bgcolor="#ffffe6">
4942: <td colspan="2">
4943: <input type="submit" value="Download: Show List of Associated Files" />
4944: </td>
4945: </tr>
4946: </table>
4947: </td>
4948: </form>
4949: </tr>
4950: SCANTRONFORM
4951:
4952: $r->print('<tr><td bgcolor="#777777">');
4953: &Apache::lonpickcode::code_list($r,2);
4954: $r->print('</td></tr></table>');
4955: $r->print($grading_menu_button);
4956: return
4957: }
4958:
4959: =pod
4960:
4961: =item get_scantron_config
4962:
4963: Parse and return the scantron configuration line selected as a
4964: hash of configuration file fields.
4965:
4966: Arguments:
4967: which - the name of the configuration to parse from the file.
4968:
4969:
4970: Returns:
4971: If the named configuration is not in the file, an empty
4972: hash is returned.
4973: a hash with the fields
4974: name - internal name for the this configuration setup
4975: description - text to display to operator that describes this config
4976: CODElocation - if 0 or the string 'none'
4977: - no CODE exists for this config
4978: if -1 || the string 'letter'
4979: - a CODE exists for this config and is
4980: a string of letters
4981: Unsupported value (but planned for future support)
4982: if a positive integer
4983: - The CODE exists as the first n items from
4984: the question section of the form
4985: if the string 'number'
4986: - The CODE exists for this config and is
4987: a string of numbers
4988: CODEstart - (only matter if a CODE exists) column in the line where
4989: the CODE starts
4990: CODElength - length of the CODE
4991: IDstart - column where the student ID number starts
4992: IDlength - length of the student ID info
4993: Qstart - column where the information from the bubbled
4994: 'questions' start
4995: Qlength - number of columns comprising a single bubble line from
4996: the sheet. (usually either 1 or 10)
4997: Qon - either a single character representing the character used
4998: to signal a bubble was chosen in the positional setup, or
4999: the string 'letter' if the letter of the chosen bubble is
5000: in the final, or 'number' if a number representing the
5001: chosen bubble is in the file (1->A 0->J)
5002: Qoff - the character used to represent that a bubble was
5003: left blank
5004: PaperID - if the scanning process generates a unique number for each
5005: sheet scanned the column that this ID number starts in
5006: PaperIDlength - number of columns that comprise the unique ID number
5007: for the sheet of paper
5008: FirstName - column that the first name starts in
5009: FirstNameLength - number of columns that the first name spans
5010:
5011: LastName - column that the last name starts in
5012: LastNameLength - number of columns that the last name spans
5013:
5014: =cut
5015:
5016: sub get_scantron_config {
5017: my ($which) = @_;
5018: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
5019: my %config;
5020: #FIXME probably should move to XML it has already gotten a bit much now
5021: foreach my $line (<$fh>) {
5022: my ($name,$descrip)=split(/:/,$line);
5023: if ($name ne $which ) { next; }
5024: chomp($line);
5025: my @config=split(/:/,$line);
5026: $config{'name'}=$config[0];
5027: $config{'description'}=$config[1];
5028: $config{'CODElocation'}=$config[2];
5029: $config{'CODEstart'}=$config[3];
5030: $config{'CODElength'}=$config[4];
5031: $config{'IDstart'}=$config[5];
5032: $config{'IDlength'}=$config[6];
5033: $config{'Qstart'}=$config[7];
5034: $config{'Qlength'}=$config[8];
5035: $config{'Qoff'}=$config[9];
5036: $config{'Qon'}=$config[10];
5037: $config{'PaperID'}=$config[11];
5038: $config{'PaperIDlength'}=$config[12];
5039: $config{'FirstName'}=$config[13];
5040: $config{'FirstNamelength'}=$config[14];
5041: $config{'LastName'}=$config[15];
5042: $config{'LastNamelength'}=$config[16];
5043: last;
5044: }
5045: return %config;
5046: }
5047:
5048: =pod
5049:
5050: =item username_to_idmap
5051:
5052: creates a hash keyed by student id with values of the corresponding
5053: student username:domain.
5054:
5055: Arguments:
5056:
5057: $classlist - reference to the class list hash. This is a hash
5058: keyed by student name:domain whose elements are references
5059: to arrays containing various chunks of information
5060: about the student. (See loncoursedata for more info).
5061:
5062: Returns
5063: %idmap - the constructed hash
5064:
5065: =cut
5066:
5067: sub username_to_idmap {
5068: my ($classlist)= @_;
5069: my %idmap;
5070: foreach my $student (keys(%$classlist)) {
5071: $idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
5072: $student;
5073: }
5074: return %idmap;
5075: }
5076:
5077: =pod
5078:
5079: =item scantron_fixup_scanline
5080:
5081: Process a requested correction to a scanline.
5082:
5083: Arguments:
5084: $scantron_config - hash from &get_scantron_config()
5085: $scan_data - hash of correction information
5086: (see &scantron_getfile())
5087: $line - existing scanline
5088: $whichline - line number of the passed in scanline
5089: $field - type of change to process
5090: (either
5091: 'ID' -> correct the student ID number
5092: 'CODE' -> correct the CODE
5093: 'answer' -> fixup the submitted answers)
5094:
5095: $args - hash of additional info,
5096: - 'ID'
5097: 'newid' -> studentID to use in replacement
5098: of existing one
5099: - 'CODE'
5100: 'CODE_ignore_dup' - set to true if duplicates
5101: should be ignored.
5102: 'CODE' - is new code or 'use_unfound'
5103: if the existing unfound code should
5104: be used as is
5105: - 'answer'
5106: 'response' - new answer or 'none' if blank
5107: 'question' - the bubble line to change
5108:
5109: Returns:
5110: $line - the modified scanline
5111:
5112: Side effects:
5113: $scan_data - may be updated
5114:
5115: =cut
5116:
5117:
5118: sub scantron_fixup_scanline {
5119: my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
5120:
5121:
5122: if ($field eq 'ID') {
5123: if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
5124: return ($line,1,'New value too large');
5125: }
5126: if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
5127: $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
5128: $args->{'newid'});
5129: }
5130: substr($line,$$scantron_config{'IDstart'}-1,
5131: $$scantron_config{'IDlength'})=$args->{'newid'};
5132: if ($args->{'newid'}=~/^\s*$/) {
5133: &scan_data($scan_data,"$whichline.user",
5134: $args->{'username'}.':'.$args->{'domain'});
5135: }
5136: } elsif ($field eq 'CODE') {
5137: if ($args->{'CODE_ignore_dup'}) {
5138: &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
5139: }
5140: &scan_data($scan_data,"$whichline.useCODE",'1');
5141: if ($args->{'CODE'} ne 'use_unfound') {
5142: if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
5143: return ($line,1,'New CODE value too large');
5144: }
5145: if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
5146: $args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
5147: }
5148: substr($line,$$scantron_config{'CODEstart'}-1,
5149: $$scantron_config{'CODElength'})=$args->{'CODE'};
5150: }
5151: } elsif ($field eq 'answer') {
5152: &scantron_get_maxbubble(); # Need the bubble counter info.
5153: my $length=$scantron_config->{'Qlength'};
5154: my $off=$scantron_config->{'Qoff'};
5155: my $on=$scantron_config->{'Qon'};
5156: my $answer=${off}x$length;
5157: my $question_number = $args->{'question'} -1;
5158: my $first_position = $first_bubble_line{$question_number};
5159: my $bubble_count = $bubble_lines_per_response{$question_number};
5160: my $bubbles_per_line= $$scantron_config{'Qlength'};
5161: my $final_answer;
5162: if ($$scantron_config{'Qon'} eq 'letter' ||
5163: $$scantron_config{'Qon'} eq 'number') {
5164: $bubbles_per_line = 10;
5165: }
5166: if (defined $args->{'response'}) {
5167:
5168: if ($args->{'response'} eq 'none') {
5169: &scan_data($scan_data,
5170: "$whichline.no_bubble.".$args->{'question'},'1');
5171: } else {
5172: my ($bubble_line, $bubble_number) = split(/:/,$args->{'response'});
5173: if ($on eq 'letter') {
5174: my @alphabet=('A'..'Z');
5175: $answer=$alphabet[$bubble_number];
5176: } elsif ($on eq 'number') {
5177: $answer=$args->$bubble_number+1;
5178: if ($answer == 10) { $answer = '0'; }
5179: } else {
5180: substr($answer,$args->{'response'},1)=$on;
5181: }
5182: &scan_data($scan_data,
5183: "$whichline.no_bubble.".$args->{'question'},undef,'1');
5184: for (my $l = 0; $l < $bubble_count; $l++) {
5185: if ($l eq $bubble_line) {
5186: $final_answer .= $answer;
5187: } else {
5188: $final_answer .= ' ';
5189: }
5190: }
5191: }
5192: # $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
5193: #substr($line,$where-1,$length)=$answer;
5194: substr($line,
5195: $scantron_config->{'Qstart'}+$first_position-1,
5196: $bubbles_per_line) = $final_answer;
5197: }
5198: }
5199: return $line;
5200: }
5201:
5202: =pod
5203:
5204: =item scan_data
5205:
5206: Edit or look up an item in the scan_data hash.
5207:
5208: Arguments:
5209: $scan_data - The hash (see scantron_getfile)
5210: $key - shorthand of the key to edit (actual key is
5211: scantronfilename_key).
5212: $data - New value of the hash entry.
5213: $delete - If true, the entry is removed from the hash.
5214:
5215: Returns:
5216: The new value of the hash table field (undefined if deleted).
5217:
5218: =cut
5219:
5220:
5221: sub scan_data {
5222: my ($scan_data,$key,$value,$delete)=@_;
5223: my $filename=$env{'form.scantron_selectfile'};
5224: if (defined($value)) {
5225: $scan_data->{$filename.'_'.$key} = $value;
5226: }
5227: if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
5228: return $scan_data->{$filename.'_'.$key};
5229: }
5230:
5231: =pod
5232:
5233: =item scantron_parse_scanline
5234:
5235: Decodes a scanline from the selected scantron file
5236:
5237: Arguments:
5238: line - The text of the scantron file line to process
5239: whichline - Line number
5240: scantron_config - Hash describing the format of the scantron lines.
5241: scan_data - Hash of extra information about the scanline
5242: (see scantron_getfile for more information)
5243: just_header - True if should not process question answers but only
5244: the stuff to the left of the answers.
5245: Returns:
5246: Hash containing the result of parsing the scanline
5247:
5248: Keys are all proceeded by the string 'scantron.'
5249:
5250: CODE - the CODE in use for this scanline
5251: useCODE - 1 if the CODE is invalid but it usage has been forced
5252: by the operator
5253: CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
5254: CODEs were selected, but the usage has been
5255: forced by the operator
5256: ID - student ID
5257: PaperID - if used, the ID number printed on the sheet when the
5258: paper was scanned
5259: FirstName - first name from the sheet
5260: LastName - last name from the sheet
5261:
5262: if just_header was not true these key may also exist
5263:
5264: missingerror - a list of bubble ranges that are considered to be answers
5265: to a single question that don't have any bubbles filled in.
5266: Of the form questionnumber:firstbubblenumber:count.
5267: doubleerror - a list of bubble ranges that are considered to be answers
5268: to a single question that have more than one bubble filled in.
5269: Of the form questionnumber::firstbubblenumber:count
5270:
5271: In the above, count is the number of bubble responses in the
5272: input line needed to represent the possible answers to the question.
5273: e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
5274: per line would have count = 2.
5275:
5276: maxquest - the number of the last bubble line that was parsed
5277:
5278: (<number> starts at 1)
5279: <number>.answer - zero or more letters representing the selected
5280: letters from the scanline for the bubble line
5281: <number>.
5282: if blank there was either no bubble or there where
5283: multiple bubbles, (consult the keys missingerror and
5284: doubleerror if this is an error condition)
5285:
5286: =cut
5287:
5288: sub scantron_parse_scanline {
5289: my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
5290:
5291: my %record;
5292: my $questions=substr($line,$$scantron_config{'Qstart'}-1); # Answers
5293: my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # earlier stuff
5294: if (!($$scantron_config{'CODElocation'} eq 0 ||
5295: $$scantron_config{'CODElocation'} eq 'none')) {
5296: if ($$scantron_config{'CODElocation'} < 0 ||
5297: $$scantron_config{'CODElocation'} eq 'letter' ||
5298: $$scantron_config{'CODElocation'} eq 'number') {
5299: $record{'scantron.CODE'}=substr($data,
5300: $$scantron_config{'CODEstart'}-1,
5301: $$scantron_config{'CODElength'});
5302: if (&scan_data($scan_data,"$whichline.useCODE")) {
5303: $record{'scantron.useCODE'}=1;
5304: }
5305: if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
5306: $record{'scantron.CODE_ignore_dup'}=1;
5307: }
5308: } else {
5309: #FIXME interpret first N questions
5310: }
5311: }
5312: $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
5313: $$scantron_config{'IDlength'});
5314: $record{'scantron.PaperID'}=
5315: substr($data,$$scantron_config{'PaperID'}-1,
5316: $$scantron_config{'PaperIDlength'});
5317: $record{'scantron.FirstName'}=
5318: substr($data,$$scantron_config{'FirstName'}-1,
5319: $$scantron_config{'FirstNamelength'});
5320: $record{'scantron.LastName'}=
5321: substr($data,$$scantron_config{'LastName'}-1,
5322: $$scantron_config{'LastNamelength'});
5323: if ($just_header) { return \%record; }
5324:
5325: my @alphabet=('A'..'Z');
5326: my $questnum=0;
5327: my $ansnum =1; # Multiple 'answer lines'/question.
5328:
5329: chomp($questions); # Get rid of any trailing \n.
5330: $questions =~ s/\r$//; # Get rid of trailing \r too (MAC or Win uploads).
5331: while (length($questions)) {
5332: my $answers_needed = $bubble_lines_per_response{$questnum};
5333: my $answer_length = $$scantron_config{'Qlength'} * $answers_needed;
5334:
5335:
5336:
5337: $questnum++;
5338: my $currentquest = substr($questions,0,$answer_length);
5339: $questions = substr($questions,0,$answer_length)='';
5340: if (length($currentquest) < $answer_length) { next; }
5341:
5342: # Qon letter implies for each slot in currentquest we have:
5343: # ? or * for doubles a letter in A-Z for a bubble and
5344: # about anything else (esp. a value of Qoff for missing
5345: # bubbles.
5346:
5347:
5348: if ($$scantron_config{'Qon'} eq 'letter') {
5349:
5350: if ($currentquest =~ /\?/
5351: || $currentquest =~ /\*/
5352: || (&occurence_count($currentquest, "[A-Z]") > 1)) {
5353: push(@{$record{'scantron.doubleerror'}},$questnum);
5354: for (my $ans = 0; $ans < $answers_needed; $ans++) {
5355: my $bubble = substr($currentquest, $ans, 1);
5356: if ($bubble =~ /[A-Z]/ ) {
5357: $record{"scantron.$ansnum.answer"} = $bubble;
5358: } else {
5359: $record{"scantron.$ansnum.answer"}='';
5360: }
5361: $ansnum++;
5362: }
5363:
5364: } elsif (!defined($currentquest)
5365: || (&occurence_count($currentquest, $$scantron_config{'Qoff'}) == length($currentquest))
5366: || (&occurence_count($currentquest, "[A-Z]") == 0)) {
5367: for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
5368: $record{"scantron.$ansnum.answer"}='';
5369: $ansnum++;
5370:
5371: }
5372: if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
5373: push(@{$record{"scantron.missingerror"}},$questnum);
5374: # $ansnum += $answers_needed;
5375: }
5376: } else {
5377: for (my $ans = 0; $ans < $answers_needed; $ans++) {
5378: $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
5379: $ansnum++;
5380: }
5381: }
5382:
5383: # Qon 'number' implies each slot gives a digit that indexes the
5384: # the bubbles filled or Qoff or a non number for unbubbled lines.
5385: # and *? for double bubbles on a line.
5386: # these answers are also stored as letters.
5387:
5388: } elsif ($$scantron_config{'Qon'} eq 'number') {
5389: if ($currentquest =~ /\?/
5390: || $currentquest =~ /\*/
5391: || (&occurence_count($currentquest, '\d') > 1)) {
5392: push(@{$record{'scantron.doubleerror'}},$questnum);
5393: for (my $ans = 0; $ans < $answers_needed; $ans++) {
5394: my $bubble = substr($currentquest, $ans, 1);
5395: if ($bubble =~ /\d/) {
5396: $record{"scantron.$ansnum.answer"} = $alphabet[$bubble];
5397: } else {
5398: $record{"scantron.$ansnum.answer"}=' ';
5399: }
5400: $ansnum++;
5401: }
5402:
5403: } elsif (!defined($currentquest)
5404: || (&occurence_count($currentquest,$$scantron_config{'Qoff'}) == length($currentquest))
5405: || (&occurence_count($currentquest, '\d') == 0)) {
5406: for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
5407: $record{"scantron.$ansnum.answer"}='';
5408: $ansnum++;
5409:
5410: }
5411: if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
5412: push(@{$record{"scantron.missingerror"}},$questnum);
5413: $ansnum += $answers_needed;
5414: }
5415:
5416: } else {
5417: $currentquest = &digits_to_letters($currentquest);
5418: for (my $ans =0; $ans < $answers_needed; $ans++) {
5419: $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
5420: $ansnum++;
5421: }
5422: }
5423: } else {
5424:
5425: # Otherwise there's a positional notation;
5426: # each bubble line requires Qlength items, and there are filled in
5427: # bubbles for each case where there 'Qon' characters.
5428: #
5429:
5430: my @array=split($$scantron_config{'Qon'},$currentquest,-1);
5431:
5432: # If the split only giveas us one element.. the full length of the
5433: # answser string, no bubbles are filled in:
5434:
5435: if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
5436: for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
5437: $record{"scantron.$ansnum.answer"}='';
5438: $ansnum++;
5439:
5440: }
5441: if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
5442: push(@{$record{"scantron.missingerror"}},$questnum);
5443: }
5444: } elsif (scalar(@array) lt 2) {
5445:
5446: my $location = length($array[0]);
5447: my $line_num = $location / $$scantron_config{'Qlength'};
5448: my $bubble = $alphabet[$location % $$scantron_config{'Qlength'}];
5449:
5450: for (my $ans = 0; $ans < $answers_needed; $ans++) {
5451: if ($ans eq $line_num) {
5452: $record{"scantron.$ansnum.answer"} = $bubble;
5453: } else {
5454: $record{"scantron.$ansnum.answer"} = ' ';
5455: }
5456: $ansnum++;
5457: }
5458: }
5459: # If there's more than one instance of a bubble character
5460: # That's a double bubble; with positional notation we can
5461: # record all the bubbles filled in as well as the
5462: # fact this response consists of multiple bubbles.
5463: #
5464: else {
5465: push(@{$record{'scantron.doubleerror'}},$questnum);
5466:
5467: my $first_answer = $ansnum;
5468: for (my $ans =0; $ans < $answers_needed; $ans++) {
5469: my $item = $first_answer+$ans;
5470: $record{"scantron.$item.answer"} = '';
5471: }
5472:
5473: my @ans=@array;
5474: my $i=0;
5475: my $increment = 0;
5476: while ($#ans) {
5477: $i+=length($ans[0]) + $increment;
5478: my $line = int($i/$$scantron_config{'Qlength'} + $first_answer);
5479: my $bubble = $i%$$scantron_config{'Qlength'};
5480: $record{"scantron.$line.answer"}.=$alphabet[$bubble];
5481: shift(@ans);
5482: $increment = 1;
5483: }
5484: $ansnum += $answers_needed;
5485: }
5486: }
5487: }
5488: $record{'scantron.maxquest'}=$questnum;
5489: return \%record;
5490: }
5491:
5492: =pod
5493:
5494: =item scantron_add_delay
5495:
5496: Adds an error message that occurred during the grading phase to a
5497: queue of messages to be shown after grading pass is complete
5498:
5499: Arguments:
5500: $delayqueue - arrary ref of hash ref of error messages
5501: $scanline - the scanline that caused the error
5502: $errormesage - the error message
5503: $errorcode - a numeric code for the error
5504:
5505: Side Effects:
5506: updates the $delayqueue to have a new hash ref of the error
5507:
5508: =cut
5509:
5510: sub scantron_add_delay {
5511: my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
5512: push(@$delayqueue,
5513: {'line' => $scanline, 'emsg' => $errormessage,
5514: 'ecode' => $errorcode }
5515: );
5516: }
5517:
5518: =pod
5519:
5520: =item scantron_find_student
5521:
5522: Finds the username for the current scanline
5523:
5524: Arguments:
5525: $scantron_record - hash result from scantron_parse_scanline
5526: $scan_data - hash of correction information
5527: (see &scantron_getfile() form more information)
5528: $idmap - hash from &username_to_idmap()
5529: $line - number of current scanline
5530:
5531: Returns:
5532: Either 'username:domain' or undef if unknown
5533:
5534: =cut
5535:
5536: sub scantron_find_student {
5537: my ($scantron_record,$scan_data,$idmap,$line)=@_;
5538: my $scanID=$$scantron_record{'scantron.ID'};
5539: if ($scanID =~ /^\s*$/) {
5540: return &scan_data($scan_data,"$line.user");
5541: }
5542: foreach my $id (keys(%$idmap)) {
5543: if (lc($id) eq lc($scanID)) {
5544: return $$idmap{$id};
5545: }
5546: }
5547: return undef;
5548: }
5549:
5550: =pod
5551:
5552: =item scantron_filter
5553:
5554: Filter sub for lonnavmaps, filters out hidden resources if ignore
5555: hidden resources was selected
5556:
5557: =cut
5558:
5559: sub scantron_filter {
5560: my ($curres)=@_;
5561:
5562: if (ref($curres) && $curres->is_problem()) {
5563: # if the user has asked to not have either hidden
5564: # or 'randomout' controlled resources to be graded
5565: # don't include them
5566: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
5567: && $curres->randomout) {
5568: return 0;
5569: }
5570: return 1;
5571: }
5572: return 0;
5573: }
5574:
5575: =pod
5576:
5577: =item scantron_process_corrections
5578:
5579: Gets correction information out of submitted form data and corrects
5580: the scanline
5581:
5582: =cut
5583:
5584: sub scantron_process_corrections {
5585: my ($r) = @_;
5586: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
5587: my ($scanlines,$scan_data)=&scantron_getfile();
5588: my $classlist=&Apache::loncoursedata::get_classlist();
5589: my $which=$env{'form.scantron_line'};
5590: my $line=&scantron_get_line($scanlines,$scan_data,$which);
5591: my ($skip,$err,$errmsg);
5592: if ($env{'form.scantron_skip_record'}) {
5593: $skip=1;
5594: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
5595: my $newstudent=$env{'form.scantron_username'}.':'.
5596: $env{'form.scantron_domain'};
5597: my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
5598: ($line,$err,$errmsg)=
5599: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
5600: 'ID',{'newid'=>$newid,
5601: 'username'=>$env{'form.scantron_username'},
5602: 'domain'=>$env{'form.scantron_domain'}});
5603: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
5604: my $resolution=$env{'form.scantron_CODE_resolution'};
5605: my $newCODE;
5606: my %args;
5607: if ($resolution eq 'use_unfound') {
5608: $newCODE='use_unfound';
5609: } elsif ($resolution eq 'use_found') {
5610: $newCODE=$env{'form.scantron_CODE_selectedvalue'};
5611: } elsif ($resolution eq 'use_typed') {
5612: $newCODE=$env{'form.scantron_CODE_newvalue'};
5613: } elsif ($resolution =~ /^use_closest_(\d+)/) {
5614: $newCODE=$env{"form.scantron_CODE_closest_$1"};
5615: }
5616: if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
5617: $args{'CODE_ignore_dup'}=1;
5618: }
5619: $args{'CODE'}=$newCODE;
5620: ($line,$err,$errmsg)=
5621: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
5622: 'CODE',\%args);
5623: } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
5624: foreach my $question (split(',',$env{'form.scantron_questions'})) {
5625: ($line,$err,$errmsg)=
5626: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
5627: $which,'answer',
5628: { 'question'=>$question,
5629: 'response'=>$env{"form.scantron_correct_Q_$question"}});
5630: if ($err) { last; }
5631: }
5632: }
5633: if ($err) {
5634: $r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
5635: } else {
5636: &scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
5637: &scantron_putfile($scanlines,$scan_data);
5638: }
5639: }
5640:
5641: =pod
5642:
5643: =item reset_skipping_status
5644:
5645: Forgets the current set of remember skipped scanlines (and thus
5646: reverts back to considering all lines in the
5647: scantron_skipped_<filename> file)
5648:
5649: =cut
5650:
5651: sub reset_skipping_status {
5652: my ($scanlines,$scan_data)=&scantron_getfile();
5653: &scan_data($scan_data,'remember_skipping',undef,1);
5654: &scantron_putfile(undef,$scan_data);
5655: }
5656:
5657: =pod
5658:
5659: =item start_skipping
5660:
5661: Marks a scanline to be skipped.
5662:
5663: =cut
5664:
5665: sub start_skipping {
5666: my ($scan_data,$i)=@_;
5667: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
5668: if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
5669: $remembered{$i}=2;
5670: } else {
5671: $remembered{$i}=1;
5672: }
5673: &scan_data($scan_data,'remember_skipping',join(':',%remembered));
5674: }
5675:
5676: =pod
5677:
5678: =item should_be_skipped
5679:
5680: Checks whether a scanline should be skipped.
5681:
5682: =cut
5683:
5684: sub should_be_skipped {
5685: my ($scanlines,$scan_data,$i)=@_;
5686: if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
5687: # not redoing old skips
5688: if ($scanlines->{'skipped'}[$i]) { return 1; }
5689: return 0;
5690: }
5691: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
5692:
5693: if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
5694: return 0;
5695: }
5696: return 1;
5697: }
5698:
5699: =pod
5700:
5701: =item remember_current_skipped
5702:
5703: Discovers what scanlines are in the scantron_skipped_<filename>
5704: file and remembers them into scan_data for later use.
5705:
5706: =cut
5707:
5708: sub remember_current_skipped {
5709: my ($scanlines,$scan_data)=&scantron_getfile();
5710: my %to_remember;
5711: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
5712: if ($scanlines->{'skipped'}[$i]) {
5713: $to_remember{$i}=1;
5714: }
5715: }
5716:
5717: &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
5718: &scantron_putfile(undef,$scan_data);
5719: }
5720:
5721: =pod
5722:
5723: =item check_for_error
5724:
5725: Checks if there was an error when attempting to remove a specific
5726: scantron_.. bubble sheet data file. Prints out an error if
5727: something went wrong.
5728:
5729: =cut
5730:
5731: sub check_for_error {
5732: my ($r,$result)=@_;
5733: if ($result ne 'ok' && $result ne 'not_found' ) {
5734: $r->print("An error occurred ($result) when trying to Remove the existing corrections.");
5735: }
5736: }
5737:
5738: =pod
5739:
5740: =item scantron_warning_screen
5741:
5742: Interstitial screen to make sure the operator has selected the
5743: correct options before we start the validation phase.
5744:
5745: =cut
5746:
5747: sub scantron_warning_screen {
5748: my ($button_text)=@_;
5749: my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
5750: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
5751: my $CODElist;
5752: if ($scantron_config{'CODElocation'} &&
5753: $scantron_config{'CODEstart'} &&
5754: $scantron_config{'CODElength'}) {
5755: $CODElist=$env{'form.scantron_CODElist'};
5756: if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
5757: $CODElist=
5758: '<tr><td><b>List of CODES to validate against:</b></td><td><tt>'.
5759: $env{'form.scantron_CODElist'}.'</tt></td></tr>';
5760: }
5761: return (<<STUFF);
5762: <p>
5763: <span class="LC_warning">Please double check the information
5764: below before clicking on '$button_text'</span>
5765: </p>
5766: <table>
5767: <tr><td><b>Sequence to be Graded:</b></td><td>$title</td></tr>
5768: <tr><td><b>Data File that will be used:</b></td><td><tt>$env{'form.scantron_selectfile'}</tt></td></tr>
5769: $CODElist
5770: </table>
5771: <br />
5772: <p> If this information is correct, please click on '$button_text'.</p>
5773: <p> If something is incorrect, please click the 'Grading Menu' button to start over.</p>
5774:
5775: <br />
5776: STUFF
5777: }
5778:
5779: =pod
5780:
5781: =item scantron_do_warning
5782:
5783: Check if the operator has picked something for all required
5784: fields. Error out if something is missing.
5785:
5786: =cut
5787:
5788: sub scantron_do_warning {
5789: my ($r)=@_;
5790: my ($symb)=&get_symb($r);
5791: if (!$symb) {return '';}
5792: my $default_form_data=&defaultFormData($symb);
5793: $r->print(&scantron_form_start().$default_form_data);
5794: if ( $env{'form.selectpage'} eq '' ||
5795: $env{'form.scantron_selectfile'} eq '' ||
5796: $env{'form.scantron_format'} eq '' ) {
5797: $r->print("<p>You have forgetten to specify some information. Please go Back and try again.</p>");
5798: if ( $env{'form.selectpage'} eq '') {
5799: $r->print('<p><span class="LC_error">You have not selected a Sequence to grade</span></p>');
5800: }
5801: if ( $env{'form.scantron_selectfile'} eq '') {
5802: $r->print('<p><span class="LC_error">You have not selected a file that contains the student\'s response data.</span></p>');
5803: }
5804: if ( $env{'form.scantron_format'} eq '') {
5805: $r->print('<p><span class="LC_error">You have not selected a the format of the student\'s response data.</span></p>');
5806: }
5807: } else {
5808: my $warning=&scantron_warning_screen('Grading: Validate Records');
5809: $r->print(<<STUFF);
5810: $warning
5811: <input type="submit" name="submit" value="Grading: Validate Records" />
5812: <input type="hidden" name="command" value="scantron_validate" />
5813: STUFF
5814: }
5815: $r->print("</form><br />".&show_grading_menu_form($symb));
5816: return '';
5817: }
5818:
5819: =pod
5820:
5821: =item scantron_form_start
5822:
5823: html hidden input for remembering all selected grading options
5824:
5825: =cut
5826:
5827: sub scantron_form_start {
5828: my ($max_bubble)=@_;
5829: my $result= <<SCANTRONFORM;
5830: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
5831: <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
5832: <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
5833: <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
5834: <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
5835: <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
5836: <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
5837: <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
5838: <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
5839: <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
5840: SCANTRONFORM
5841:
5842: my $line = 0;
5843: while (defined($env{"form.scantron.bubblelines.$line"})) {
5844: my $chunk =
5845: '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
5846: $chunk .=
5847: '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
5848: $result .= $chunk;
5849: $line++;
5850: }
5851: return $result;
5852: }
5853:
5854: =pod
5855:
5856: =item scantron_validate_file
5857:
5858: Dispatch routine for doing validation of a bubble sheet data file.
5859:
5860: Also processes any necessary information resets that need to
5861: occur before validation begins (ignore previous corrections,
5862: restarting the skipped records processing)
5863:
5864: =cut
5865:
5866: sub scantron_validate_file {
5867: my ($r) = @_;
5868: my ($symb)=&get_symb($r);
5869: if (!$symb) {return '';}
5870: my $default_form_data=&defaultFormData($symb);
5871:
5872: # do the detection of only doing skipped records first befroe we delete
5873: # them when doing the corrections reset
5874: if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
5875: &reset_skipping_status();
5876: }
5877: if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
5878: &remember_current_skipped();
5879: $env{'form.scantron_options_redo'}='redo_skipped_ready';
5880: }
5881:
5882: if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
5883: &check_for_error($r,&scantron_remove_file('corrected'));
5884: &check_for_error($r,&scantron_remove_file('skipped'));
5885: &check_for_error($r,&scantron_remove_scan_data());
5886: $env{'form.scantron_options_ignore'}='done';
5887: }
5888:
5889: if ($env{'form.scantron_corrections'}) {
5890: &scantron_process_corrections($r);
5891: }
5892: $r->print("<p>Gathering necessary info.</p>");$r->rflush();
5893: #get the student pick code ready
5894: $r->print(&Apache::loncommon::studentbrowser_javascript());
5895: my $max_bubble=&scantron_get_maxbubble();
5896: my $result=&scantron_form_start($max_bubble).$default_form_data;
5897: $r->print($result);
5898:
5899: my @validate_phases=( 'sequence',
5900: 'ID',
5901: 'CODE',
5902: 'doublebubble',
5903: 'missingbubbles');
5904: if (!$env{'form.validatepass'}) {
5905: $env{'form.validatepass'} = 0;
5906: }
5907: my $currentphase=$env{'form.validatepass'};
5908:
5909:
5910: my $stop=0;
5911: while (!$stop && $currentphase < scalar(@validate_phases)) {
5912: $r->print("<p> Validating ".$validate_phases[$currentphase]."</p>");
5913: $r->rflush();
5914: my $which="scantron_validate_".$validate_phases[$currentphase];
5915: {
5916: no strict 'refs';
5917: ($stop,$currentphase)=&$which($r,$currentphase);
5918: }
5919: }
5920: if (!$stop) {
5921: my $warning=&scantron_warning_screen('Start Grading');
5922: $r->print(<<STUFF);
5923: Validation process complete.<br />
5924: $warning
5925: <input type="submit" name="submit" value="Start Grading" />
5926: <input type="hidden" name="command" value="scantron_process" />
5927: STUFF
5928:
5929: } else {
5930: $r->print('<input type="hidden" name="command" value="scantron_validate" />');
5931: $r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
5932: }
5933: if ($stop) {
5934: if ($validate_phases[$currentphase] eq 'sequence') {
5935: $r->print('<input type="submit" name="submit" value="Ignore -> " />');
5936: $r->print(' this error <br />');
5937:
5938: $r->print(" <p>Or click the 'Grading Menu' button to start over.</p>");
5939: } else {
5940: $r->print('<input type="submit" name="submit" value="Continue ->" />');
5941: $r->print(' using corrected info <br />');
5942: $r->print("<input type='submit' value='Skip' name='scantron_skip_record' />");
5943: $r->print(" this scanline saving it for later.");
5944: }
5945: }
5946: $r->print(" </form><br />".&show_grading_menu_form($symb));
5947: return '';
5948: }
5949:
5950:
5951: =pod
5952:
5953: =item scantron_remove_file
5954:
5955: Removes the requested bubble sheet data file, makes sure that
5956: scantron_original_<filename> is never removed
5957:
5958:
5959: =cut
5960:
5961: sub scantron_remove_file {
5962: my ($which)=@_;
5963: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5964: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5965: my $file='scantron_';
5966: if ($which eq 'corrected' || $which eq 'skipped') {
5967: $file.=$which.'_';
5968: } else {
5969: return 'refused';
5970: }
5971: $file.=$env{'form.scantron_selectfile'};
5972: return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
5973: }
5974:
5975:
5976: =pod
5977:
5978: =item scantron_remove_scan_data
5979:
5980: Removes all scan_data correction for the requested bubble sheet
5981: data file. (In the case that both the are doing skipped records we need
5982: to remember the old skipped lines for the time being so that element
5983: persists for a while.)
5984:
5985: =cut
5986:
5987: sub scantron_remove_scan_data {
5988: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5989: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5990: my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
5991: my @todelete;
5992: my $filename=$env{'form.scantron_selectfile'};
5993: foreach my $key (@keys) {
5994: if ($key=~/^\Q$filename\E_/) {
5995: if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
5996: $key=~/remember_skipping/) {
5997: next;
5998: }
5999: push(@todelete,$key);
6000: }
6001: }
6002: my $result;
6003: if (@todelete) {
6004: $result=&Apache::lonnet::del('nohist_scantrondata',\@todelete,$cdom,$cname);
6005: }
6006: return $result;
6007: }
6008:
6009:
6010: =pod
6011:
6012: =item scantron_getfile
6013:
6014: Fetches the requested bubble sheet data file (all 3 versions), and
6015: the scan_data hash
6016:
6017: Arguments:
6018: None
6019:
6020: Returns:
6021: 2 hash references
6022:
6023: - first one has
6024: orig -
6025: corrected -
6026: skipped - each of which points to an array ref of the specified
6027: file broken up into individual lines
6028: count - number of scanlines
6029:
6030: - second is the scan_data hash possible keys are
6031: ($number refers to scanline numbered $number and thus the key affects
6032: only that scanline
6033: $bubline refers to the specific bubble line element and the aspects
6034: refers to that specific bubble line element)
6035:
6036: $number.user - username:domain to use
6037: $number.CODE_ignore_dup
6038: - ignore the duplicate CODE error
6039: $number.useCODE
6040: - use the CODE in the scanline as is
6041: $number.no_bubble.$bubline
6042: - it is valid that there is no bubbled in bubble
6043: at $number $bubline
6044: remember_skipping
6045: - a frozen hash containing keys of $number and values
6046: of either
6047: 1 - we are on a 'do skipped records pass' and plan
6048: on processing this line
6049: 2 - we are on a 'do skipped records pass' and this
6050: scanline has been marked to skip yet again
6051:
6052: =cut
6053:
6054: sub scantron_getfile {
6055: #FIXME really would prefer a scantron directory
6056: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6057: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6058: my $lines;
6059: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
6060: 'scantron_orig_'.$env{'form.scantron_selectfile'});
6061: my %scanlines;
6062: $scanlines{'orig'}=[(split("\n",$lines,-1))];
6063: my $temp=$scanlines{'orig'};
6064: $scanlines{'count'}=$#$temp;
6065:
6066: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
6067: 'scantron_corrected_'.$env{'form.scantron_selectfile'});
6068: if ($lines eq '-1') {
6069: $scanlines{'corrected'}=[];
6070: } else {
6071: $scanlines{'corrected'}=[(split("\n",$lines,-1))];
6072: }
6073: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
6074: 'scantron_skipped_'.$env{'form.scantron_selectfile'});
6075: if ($lines eq '-1') {
6076: $scanlines{'skipped'}=[];
6077: } else {
6078: $scanlines{'skipped'}=[(split("\n",$lines,-1))];
6079: }
6080: my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
6081: if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
6082: my %scan_data = @tmp;
6083: return (\%scanlines,\%scan_data);
6084: }
6085:
6086: =pod
6087:
6088: =item lonnet_putfile
6089:
6090: Wrapper routine to call &Apache::lonnet::finishuserfileupload
6091:
6092: Arguments:
6093: $contents - data to store
6094: $filename - filename to store $contents into
6095:
6096: Returns:
6097: result value from &Apache::lonnet::finishuserfileupload
6098:
6099: =cut
6100:
6101: sub lonnet_putfile {
6102: my ($contents,$filename)=@_;
6103: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
6104: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6105: $env{'form.sillywaytopassafilearound'}=$contents;
6106: &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
6107:
6108: }
6109:
6110: =pod
6111:
6112: =item scantron_putfile
6113:
6114: Stores the current version of the bubble sheet data files, and the
6115: scan_data hash. (Does not modify the original version only the
6116: corrected and skipped versions.
6117:
6118: Arguments:
6119: $scanlines - hash ref that looks like the first return value from
6120: &scantron_getfile()
6121: $scan_data - hash ref that looks like the second return value from
6122: &scantron_getfile()
6123:
6124: =cut
6125:
6126: sub scantron_putfile {
6127: my ($scanlines,$scan_data) = @_;
6128: #FIXME really would prefer a scantron directory
6129: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6130: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6131: if ($scanlines) {
6132: my $prefix='scantron_';
6133: # no need to update orig, shouldn't change
6134: # &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
6135: # $env{'form.scantron_selectfile'});
6136: &lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
6137: $prefix.'corrected_'.
6138: $env{'form.scantron_selectfile'});
6139: &lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
6140: $prefix.'skipped_'.
6141: $env{'form.scantron_selectfile'});
6142: }
6143: &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
6144: }
6145:
6146: =pod
6147:
6148: =item scantron_get_line
6149:
6150: Returns the correct version of the scanline
6151:
6152: Arguments:
6153: $scanlines - hash ref that looks like the first return value from
6154: &scantron_getfile()
6155: $scan_data - hash ref that looks like the second return value from
6156: &scantron_getfile()
6157: $i - number of the requested line (starts at 0)
6158:
6159: Returns:
6160: A scanline, (either the original or the corrected one if it
6161: exists), or undef if the requested scanline should be
6162: skipped. (Either because it's an skipped scanline, or it's an
6163: unskipped scanline and we are not doing a 'do skipped scanlines'
6164: pass.
6165:
6166: =cut
6167:
6168: sub scantron_get_line {
6169: my ($scanlines,$scan_data,$i)=@_;
6170: if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
6171: #if ($scanlines->{'skipped'}[$i]) { return undef; }
6172: if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
6173: return $scanlines->{'orig'}[$i];
6174: }
6175:
6176: =pod
6177:
6178: =item scantron_todo_count
6179:
6180: Counts the number of scanlines that need processing.
6181:
6182: Arguments:
6183: $scanlines - hash ref that looks like the first return value from
6184: &scantron_getfile()
6185: $scan_data - hash ref that looks like the second return value from
6186: &scantron_getfile()
6187:
6188: Returns:
6189: $count - number of scanlines to process
6190:
6191: =cut
6192:
6193: sub get_todo_count {
6194: my ($scanlines,$scan_data)=@_;
6195: my $count=0;
6196: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6197: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6198: if ($line=~/^[\s\cz]*$/) { next; }
6199: $count++;
6200: }
6201: return $count;
6202: }
6203:
6204: =pod
6205:
6206: =item scantron_put_line
6207:
6208: Updates the 'corrected' or 'skipped' versions of the bubble sheet
6209: data file.
6210:
6211: Arguments:
6212: $scanlines - hash ref that looks like the first return value from
6213: &scantron_getfile()
6214: $scan_data - hash ref that looks like the second return value from
6215: &scantron_getfile()
6216: $i - line number to update
6217: $newline - contents of the updated scanline
6218: $skip - if true make the line for skipping and update the
6219: 'skipped' file
6220:
6221: =cut
6222:
6223: sub scantron_put_line {
6224: my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
6225: if ($skip) {
6226: $scanlines->{'skipped'}[$i]=$newline;
6227: &start_skipping($scan_data,$i);
6228: return;
6229: }
6230: $scanlines->{'corrected'}[$i]=$newline;
6231: }
6232:
6233: =pod
6234:
6235: =item scantron_clear_skip
6236:
6237: Remove a line from the 'skipped' file
6238:
6239: Arguments:
6240: $scanlines - hash ref that looks like the first return value from
6241: &scantron_getfile()
6242: $scan_data - hash ref that looks like the second return value from
6243: &scantron_getfile()
6244: $i - line number to update
6245:
6246: =cut
6247:
6248: sub scantron_clear_skip {
6249: my ($scanlines,$scan_data,$i)=@_;
6250: if (exists($scanlines->{'skipped'}[$i])) {
6251: undef($scanlines->{'skipped'}[$i]);
6252: return 1;
6253: }
6254: return 0;
6255: }
6256:
6257: =pod
6258:
6259: =item scantron_filter_not_exam
6260:
6261: Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
6262: filter out resources that are not marked as 'exam' mode
6263:
6264: =cut
6265:
6266: sub scantron_filter_not_exam {
6267: my ($curres)=@_;
6268:
6269: if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
6270: # if the user has asked to not have either hidden
6271: # or 'randomout' controlled resources to be graded
6272: # don't include them
6273: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
6274: && $curres->randomout) {
6275: return 0;
6276: }
6277: return 1;
6278: }
6279: return 0;
6280: }
6281:
6282: =pod
6283:
6284: =item scantron_validate_sequence
6285:
6286: Validates the selected sequence, checking for resource that are
6287: not set to exam mode.
6288:
6289: =cut
6290:
6291: sub scantron_validate_sequence {
6292: my ($r,$currentphase) = @_;
6293:
6294: my $navmap=Apache::lonnavmaps::navmap->new();
6295: my (undef,undef,$sequence)=
6296: &Apache::lonnet::decode_symb($env{'form.selectpage'});
6297:
6298: my $map=$navmap->getResourceByUrl($sequence);
6299:
6300: $r->print('<input type="hidden" name="validate_sequence_exam"
6301: value="ignore" />');
6302: if ($env{'form.validate_sequence_exam'} ne 'ignore') {
6303: my @resources=
6304: $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
6305: if (@resources) {
6306: $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>");
6307: return (1,$currentphase);
6308: }
6309: }
6310:
6311: return (0,$currentphase+1);
6312: }
6313:
6314: =pod
6315:
6316: =item scantron_validate_ID
6317:
6318: Validates all scanlines in the selected file to not have any
6319: invalid or underspecified student IDs
6320:
6321: =cut
6322:
6323: sub scantron_validate_ID {
6324: my ($r,$currentphase) = @_;
6325:
6326: #get student info
6327: my $classlist=&Apache::loncoursedata::get_classlist();
6328: my %idmap=&username_to_idmap($classlist);
6329:
6330: #get scantron line setup
6331: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6332: my ($scanlines,$scan_data)=&scantron_getfile();
6333:
6334: &scantron_get_maxbubble(); # parse needs the bubble_lines.. array.
6335:
6336: my %found=('ids'=>{},'usernames'=>{});
6337: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6338: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6339: if ($line=~/^[\s\cz]*$/) { next; }
6340: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6341: $scan_data);
6342: my $id=$$scan_record{'scantron.ID'};
6343: my $found;
6344: foreach my $checkid (keys(%idmap)) {
6345: if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
6346: }
6347: if ($found) {
6348: my $username=$idmap{$found};
6349: if ($found{'ids'}{$found}) {
6350: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6351: $line,'duplicateID',$found);
6352: return(1,$currentphase);
6353: } elsif ($found{'usernames'}{$username}) {
6354: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6355: $line,'duplicateID',$username);
6356: return(1,$currentphase);
6357: }
6358: #FIXME store away line we previously saw the ID on to use above
6359: $found{'ids'}{$found}++;
6360: $found{'usernames'}{$username}++;
6361: } else {
6362: if ($id =~ /^\s*$/) {
6363: my $username=&scan_data($scan_data,"$i.user");
6364: if (defined($username) && $found{'usernames'}{$username}) {
6365: &scantron_get_correction($r,$i,$scan_record,
6366: \%scantron_config,
6367: $line,'duplicateID',$username);
6368: return(1,$currentphase);
6369: } elsif (!defined($username)) {
6370: &scantron_get_correction($r,$i,$scan_record,
6371: \%scantron_config,
6372: $line,'incorrectID');
6373: return(1,$currentphase);
6374: }
6375: $found{'usernames'}{$username}++;
6376: } else {
6377: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6378: $line,'incorrectID');
6379: return(1,$currentphase);
6380: }
6381: }
6382: }
6383:
6384: return (0,$currentphase+1);
6385: }
6386:
6387: =pod
6388:
6389: =item scantron_get_correction
6390:
6391: Builds the interface screen to interact with the operator to fix a
6392: specific error condition in a specific scanline
6393:
6394: Arguments:
6395: $r - Apache request object
6396: $i - number of the current scanline
6397: $scan_record - hash ref as returned from &scantron_parse_scanline()
6398: $scan_config - hash ref as returned from &get_scantron_config()
6399: $line - full contents of the current scanline
6400: $error - error condition, valid values are
6401: 'incorrectCODE', 'duplicateCODE',
6402: 'doublebubble', 'missingbubble',
6403: 'duplicateID', 'incorrectID'
6404: $arg - extra information needed
6405: For errors:
6406: - duplicateID - paper number that this studentID was seen before on
6407: - duplicateCODE - array ref of the paper numbers this CODE was
6408: seen on before
6409: - incorrectCODE - current incorrect CODE
6410: - doublebubble - array ref of the bubble lines that have double
6411: bubble errors
6412: - missingbubble - array ref of the bubble lines that have missing
6413: bubble errors
6414:
6415: =cut
6416:
6417: sub scantron_get_correction {
6418: my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
6419:
6420: #FIXME in the case of a duplicated ID the previous line, probably need
6421: #to show both the current line and the previous one and allow skipping
6422: #the previous one or the current one
6423:
6424: $r->print("<p><b>An error was detected ($error)</b>");
6425: if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
6426: $r->print(" for PaperID <tt>".
6427: $$scan_record{'scantron.PaperID'}."</tt> \n");
6428: } else {
6429: $r->print(" in scanline $i <pre>".
6430: $line."</pre> \n");
6431: }
6432: my $message="<p>The ID on the form is <tt>".
6433: $$scan_record{'scantron.ID'}."</tt><br />\n".
6434: "The name on the paper is ".
6435: $$scan_record{'scantron.LastName'}.",".
6436: $$scan_record{'scantron.FirstName'}."</p>";
6437:
6438: $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
6439: $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
6440: if ($error =~ /ID$/) {
6441: if ($error eq 'incorrectID') {
6442: $r->print("The encoded ID is not in the classlist</p>\n");
6443: } elsif ($error eq 'duplicateID') {
6444: $r->print("The encoded ID has also been used by a previous paper $arg</p>\n");
6445: }
6446: $r->print($message);
6447: $r->print("<p>How should I handle this? <br /> \n");
6448: $r->print("\n<ul><li> ");
6449: #FIXME it would be nice if this sent back the user ID and
6450: #could do partial userID matches
6451: $r->print(&Apache::loncommon::selectstudent_link('scantronupload',
6452: 'scantron_username','scantron_domain'));
6453: $r->print(": <input type='text' name='scantron_username' value='' />");
6454: $r->print("\n@".
6455: &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
6456:
6457: $r->print('</li>');
6458: } elsif ($error =~ /CODE$/) {
6459: if ($error eq 'incorrectCODE') {
6460: $r->print("</p><p>The encoded CODE is not in the list of possible CODEs</p>\n");
6461: } elsif ($error eq 'duplicateCODE') {
6462: $r->print("</p><p>The encoded CODE has also been used by a previous paper ".join(', ',@{$arg}).", and CODEs are supposed to be unique</p>\n");
6463: }
6464: $r->print("<p>The CODE on the form is <tt>'".
6465: $$scan_record{'scantron.CODE'}."'</tt><br />\n");
6466: $r->print($message);
6467: $r->print("<p>How should I handle this? <br /> \n");
6468: $r->print("\n<br /> ");
6469: my $i=0;
6470: if ($error eq 'incorrectCODE'
6471: && $$scan_record{'scantron.CODE'}=~/\S/ ) {
6472: my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
6473: if ($closest > 0) {
6474: foreach my $testcode (@{$closest}) {
6475: my $checked='';
6476: if (!$i) { $checked=' checked="checked" '; }
6477: $r->print("<label><input type='radio' name='scantron_CODE_resolution' value='use_closest_$i' $checked /> Use the similar CODE <b><tt>".$testcode."</tt></b> instead.</label><input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
6478: $r->print("\n<br />");
6479: $i++;
6480: }
6481: }
6482: }
6483: if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
6484: my $checked; if (!$i) { $checked=' checked="checked" '; }
6485: $r->print("<label><input type='radio' name='scantron_CODE_resolution' value='use_unfound' $checked /> Use the CODE <b><tt>".$$scan_record{'scantron.CODE'}."</tt></b> that is was on the paper, ignoring the error.</label>");
6486: $r->print("\n<br />");
6487: }
6488:
6489: $r->print(<<ENDSCRIPT);
6490: <script type="text/javascript">
6491: function change_radio(field) {
6492: var slct=document.scantronupload.scantron_CODE_resolution;
6493: var i;
6494: for (i=0;i<slct.length;i++) {
6495: if (slct[i].value==field) { slct[i].checked=true; }
6496: }
6497: }
6498: </script>
6499: ENDSCRIPT
6500: my $href="/adm/pickcode?".
6501: "form=".&escape("scantronupload").
6502: "&scantron_format=".&escape($env{'form.scantron_format'}).
6503: "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
6504: "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
6505: "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
6506: if ($env{'form.scantron_CODElist'} =~ /\S/) {
6507: $r->print("<label><input type='radio' name='scantron_CODE_resolution' value='use_found' /> <a target='_blank' href='$href'>Select</a> a CODE from the list of all CODEs and use it.</label> Selected CODE is <input readonly='true' type='text' size='8' name='scantron_CODE_selectedvalue' onfocus=\"javascript:change_radio('use_found')\" onchange=\"javascript:change_radio('use_found')\" />");
6508: $r->print("\n<br />");
6509: }
6510: $r->print("<label><input type='radio' name='scantron_CODE_resolution' value='use_typed' /> Use </label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" /> as the CODE.");
6511: $r->print("\n<br /><br />");
6512: } elsif ($error eq 'doublebubble') {
6513: $r->print("<p>There have been multiple bubbles scanned for a some question(s)</p>\n");
6514: $r->print('<input type="hidden" name="scantron_questions" value="'.
6515: join(',',@{$arg}).'" />');
6516: $r->print($message);
6517: $r->print("<p>Please indicate which bubble should be used for grading</p>");
6518: foreach my $question (@{$arg}) {
6519: my $selected = &get_response_bubbles($scan_record, $question);
6520: my @select_array = split(/:/,$selected);
6521: &scantron_bubble_selector($r,$scan_config,$question,
6522: @select_array);
6523: }
6524: } elsif ($error eq 'missingbubble') {
6525: $r->print("<p>There have been <b>no</b> bubbles scanned for some question(s)</p>\n");
6526: $r->print($message);
6527: $r->print("<p>Please indicate which bubble should be used for grading</p>");
6528: $r->print("Some questions have no scanned bubbles\n");
6529: $r->print('<input type="hidden" name="scantron_questions" value="'.
6530: join(',',@{$arg}).'" />');
6531: foreach my $question (@{$arg}) {
6532: my $selected = &get_response_bubbles($scan_record, $question);
6533: my @select_array = split(/:/,$selected); # ought to be an array of empties.
6534: &scantron_bubble_selector($r,$scan_config,$question, @select_array);
6535: }
6536: } else {
6537: $r->print("\n<ul>");
6538: }
6539: $r->print("\n</li></ul>");
6540:
6541: }
6542:
6543: =pod
6544:
6545: =item scantron_bubble_selector
6546:
6547: Generates the html radiobuttons to correct a single bubble line
6548: possibly showing the existing the selected bubbles if known
6549:
6550: Arguments:
6551: $r - Apache request object
6552: $scan_config - hash from &get_scantron_config()
6553: $quest - number of the bubble line to make a corrector for
6554: @lines - array of answer lines.
6555:
6556: =cut
6557:
6558: sub scantron_bubble_selector {
6559: my ($r,$scan_config,$quest,@lines)=@_;
6560: my $max=$$scan_config{'Qlength'};
6561:
6562:
6563: my $scmode=$$scan_config{'Qon'};
6564:
6565: my $bubble_length = scalar(@lines);
6566:
6567:
6568: if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }
6569:
6570: my $response = $quest-1;
6571: my $lines = $bubble_lines_per_response{$response};
6572:
6573: my $total_lines = $lines*2;
6574: my @alphabet=('A'..'Z');
6575:
6576: $r->print("<table border='1'><tr><td rowspan='".$total_lines."'>$quest</td>");
6577:
6578: for (my $l = 0; $l < $lines; $l++) {
6579: if ($l != 0) {
6580: $r->print('<tr>');
6581: }
6582: my @selected = split(//,$lines[$l]);
6583: for (my $i=0;$i<$max;$i++) {
6584: $r->print("\n".'<td align="center">');
6585: if ($selected[0] eq $alphabet[$i]) {
6586: $r->print('X');
6587: shift(@selected) ;
6588: } else {
6589: $r->print(' ');
6590: }
6591: $r->print('</td>');
6592:
6593: }
6594:
6595: if ($l == 0) {
6596: my $lspan = $total_lines * 2; # 2 table rows per bubble line.
6597:
6598: $r->print('<td rowspan='.$lspan.'><label><input type="radio" name="scantron_correct_Q_'.
6599: $quest.'" value="none" /> No bubble </label></td>');
6600:
6601: }
6602:
6603: $r->print('</tr><tr>');
6604:
6605: # FIXME: This may have to be a bit more clever for
6606: # multiline questions (different values e.g..).
6607:
6608: for (my $i=0;$i<$max;$i++) {
6609: my $value = "$l:$i"; # Relative bubble line #: Bubble in line.
6610: $r->print("\n".
6611: '<td><label><input type="radio" name="scantron_correct_Q_'.
6612: $quest.'" value="'.$value.'" />'.$alphabet[$i]."</label></td>");
6613: }
6614: $r->print('</tr>');
6615:
6616:
6617: }
6618: $r->print('</table>');
6619: }
6620:
6621: =pod
6622:
6623: =item num_matches
6624:
6625: Counts the number of characters that are the same between the two arguments.
6626:
6627: Arguments:
6628: $orig - CODE from the scanline
6629: $code - CODE to match against
6630:
6631: Returns:
6632: $count - integer count of the number of same characters between the
6633: two arguments
6634:
6635: =cut
6636:
6637: sub num_matches {
6638: my ($orig,$code) = @_;
6639: my @code=split(//,$code);
6640: my @orig=split(//,$orig);
6641: my $same=0;
6642: for (my $i=0;$i<scalar(@code);$i++) {
6643: if ($code[$i] eq $orig[$i]) { $same++; }
6644: }
6645: return $same;
6646: }
6647:
6648: =pod
6649:
6650: =item scantron_get_closely_matching_CODEs
6651:
6652: Cycles through all CODEs and finds the set that has the greatest
6653: number of same characters as the provided CODE
6654:
6655: Arguments:
6656: $allcodes - hash ref returned by &get_codes()
6657: $CODE - CODE from the current scanline
6658:
6659: Returns:
6660: 2 element list
6661: - first elements is number of how closely matching the best fit is
6662: (5 means best set has 5 matching characters)
6663: - second element is an arrary ref containing the set of valid CODEs
6664: that best fit the passed in CODE
6665:
6666: =cut
6667:
6668: sub scantron_get_closely_matching_CODEs {
6669: my ($allcodes,$CODE)=@_;
6670: my @CODEs;
6671: foreach my $testcode (sort(keys(%{$allcodes}))) {
6672: push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
6673: }
6674:
6675: return ($#CODEs,$CODEs[-1]);
6676: }
6677:
6678: =pod
6679:
6680: =item get_codes
6681:
6682: Builds a hash which has keys of all of the valid CODEs from the selected
6683: set of remembered CODEs.
6684:
6685: Arguments:
6686: $old_name - name of the set of remembered CODEs
6687: $cdom - domain of the course
6688: $cnum - internal course name
6689:
6690: Returns:
6691: %allcodes - keys are the valid CODEs, values are all 1
6692:
6693: =cut
6694:
6695: sub get_codes {
6696: my ($old_name, $cdom, $cnum) = @_;
6697: if (!$old_name) {
6698: $old_name=$env{'form.scantron_CODElist'};
6699: }
6700: if (!$cdom) {
6701: $cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
6702: }
6703: if (!$cnum) {
6704: $cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
6705: }
6706: my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
6707: $cdom,$cnum);
6708: my %allcodes;
6709: if ($result{"type\0$old_name"} eq 'number') {
6710: %allcodes=map {($_,1)} split(',',$result{$old_name});
6711: } else {
6712: %allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
6713: }
6714: return %allcodes;
6715: }
6716:
6717: =pod
6718:
6719: =item scantron_validate_CODE
6720:
6721: Validates all scanlines in the selected file to not have any
6722: invalid or underspecified CODEs and that none of the codes are
6723: duplicated if this was requested.
6724:
6725: =cut
6726:
6727: sub scantron_validate_CODE {
6728: my ($r,$currentphase) = @_;
6729: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6730: if ($scantron_config{'CODElocation'} &&
6731: $scantron_config{'CODEstart'} &&
6732: $scantron_config{'CODElength'}) {
6733: if (!defined($env{'form.scantron_CODElist'})) {
6734: &FIXME_blow_up()
6735: }
6736: } else {
6737: return (0,$currentphase+1);
6738: }
6739:
6740: my %usedCODEs;
6741:
6742: my %allcodes=&get_codes();
6743:
6744: &scantron_get_maxbubble(); # parse needs the lines per response array.
6745:
6746: my ($scanlines,$scan_data)=&scantron_getfile();
6747: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6748: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6749: if ($line=~/^[\s\cz]*$/) { next; }
6750: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6751: $scan_data);
6752: my $CODE=$$scan_record{'scantron.CODE'};
6753: my $error=0;
6754: if (!&Apache::lonnet::validCODE($CODE)) {
6755: &scantron_get_correction($r,$i,$scan_record,
6756: \%scantron_config,
6757: $line,'incorrectCODE',\%allcodes);
6758: return(1,$currentphase);
6759: }
6760: if (%allcodes && !exists($allcodes{$CODE})
6761: && !$$scan_record{'scantron.useCODE'}) {
6762: &scantron_get_correction($r,$i,$scan_record,
6763: \%scantron_config,
6764: $line,'incorrectCODE',\%allcodes);
6765: return(1,$currentphase);
6766: }
6767: if (exists($usedCODEs{$CODE})
6768: && $env{'form.scantron_CODEunique'} eq 'yes'
6769: && !$$scan_record{'scantron.CODE_ignore_dup'}) {
6770: &scantron_get_correction($r,$i,$scan_record,
6771: \%scantron_config,
6772: $line,'duplicateCODE',$usedCODEs{$CODE});
6773: return(1,$currentphase);
6774: }
6775: push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
6776: }
6777: return (0,$currentphase+1);
6778: }
6779:
6780: =pod
6781:
6782: =item scantron_validate_doublebubble
6783:
6784: Validates all scanlines in the selected file to not have any
6785: bubble lines with multiple bubbles marked.
6786:
6787: =cut
6788:
6789: sub scantron_validate_doublebubble {
6790: my ($r,$currentphase) = @_;
6791: #get student info
6792: my $classlist=&Apache::loncoursedata::get_classlist();
6793: my %idmap=&username_to_idmap($classlist);
6794:
6795: #get scantron line setup
6796: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6797: my ($scanlines,$scan_data)=&scantron_getfile();
6798:
6799: &scantron_get_maxbubble(); # parse needs the bubble line array.
6800:
6801: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6802: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6803: if ($line=~/^[\s\cz]*$/) { next; }
6804: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6805: $scan_data);
6806: if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
6807: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
6808: 'doublebubble',
6809: $$scan_record{'scantron.doubleerror'});
6810: return (1,$currentphase);
6811: }
6812: return (0,$currentphase+1);
6813: }
6814:
6815: =pod
6816:
6817: =item scantron_get_maxbubble
6818:
6819: Returns the maximum number of bubble lines that are expected to
6820: occur. Does this by walking the selected sequence rendering the
6821: resource and then checking &Apache::lonxml::get_problem_counter()
6822: for what the current value of the problem counter is.
6823:
6824: Caches the results to $env{'form.scantron_maxbubble'},
6825: $env{'form.scantron.bubble_lines.n'} and
6826: $env{'form.scantron.first_bubble_line.n'}
6827: which are the total number of bubble, lines, the number of bubble
6828: lines for reponse n and number of the first bubble line for response n.
6829:
6830: =cut
6831:
6832: sub scantron_get_maxbubble {
6833: if (defined($env{'form.scantron_maxbubble'}) &&
6834: $env{'form.scantron_maxbubble'}) {
6835: &restore_bubble_lines();
6836: return $env{'form.scantron_maxbubble'};
6837: }
6838:
6839: my (undef, undef, $sequence) =
6840: &Apache::lonnet::decode_symb($env{'form.selectpage'});
6841:
6842: my $navmap=Apache::lonnavmaps::navmap->new();
6843: my $map=$navmap->getResourceByUrl($sequence);
6844: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
6845:
6846: &Apache::lonxml::clear_problem_counter();
6847:
6848: my $uname = $env{'form.student'};
6849: my $udom = $env{'form.userdom'};
6850: my $cid = $env{'request.course.id'};
6851: my $total_lines = 0;
6852: %bubble_lines_per_response = ();
6853: %first_bubble_line = ();
6854:
6855:
6856: my $response_number = 0;
6857: my $bubble_line = 0;
6858: foreach my $resource (@resources) {
6859: my $symb = $resource->symb();
6860: &Apache::lonxml::clear_bubble_lines_for_part();
6861: my $result=&Apache::lonnet::ssi($resource->src(),
6862: ('symb' => $resource->symb()),
6863: ('grade_target' => 'analyze'),
6864: ('grade_courseid' => $cid),
6865: ('grade_domain' => $udom),
6866: ('grade_username' => $uname));
6867: my (undef, $an) =
6868: split(/_HASH_REF__/,$result, 2);
6869:
6870: my %analysis = &Apache::lonnet::str2hash($an);
6871:
6872:
6873:
6874: foreach my $part_id (@{$analysis{'parts'}}) {
6875:
6876:
6877: my $lines = $analysis{"$part_id.bubble_lines"};;
6878:
6879: # TODO - make this a persistent hash not an array.
6880:
6881:
6882: $first_bubble_line{$response_number} = $bubble_line;
6883: $bubble_lines_per_response{$response_number} = $lines;
6884: $response_number++;
6885:
6886: $bubble_line += $lines;
6887: $total_lines += $lines;
6888: }
6889:
6890: }
6891: &Apache::lonnet::delenv('scantron\.');
6892:
6893: &save_bubble_lines();
6894: $env{'form.scantron_maxbubble'} =
6895: $total_lines;
6896: return $env{'form.scantron_maxbubble'};
6897: }
6898:
6899: =pod
6900:
6901: =item scantron_validate_missingbubbles
6902:
6903: Validates all scanlines in the selected file to not have any
6904: answers that don't have bubbles that have not been verified
6905: to be bubble free.
6906:
6907: =cut
6908:
6909: sub scantron_validate_missingbubbles {
6910: my ($r,$currentphase) = @_;
6911: #get student info
6912: my $classlist=&Apache::loncoursedata::get_classlist();
6913: my %idmap=&username_to_idmap($classlist);
6914:
6915: #get scantron line setup
6916: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6917: my ($scanlines,$scan_data)=&scantron_getfile();
6918: my $max_bubble=&scantron_get_maxbubble();
6919: if (!$max_bubble) { $max_bubble=2**31; }
6920: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6921: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6922: if ($line=~/^[\s\cz]*$/) { next; }
6923: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6924: $scan_data);
6925: if (!defined($$scan_record{'scantron.missingerror'})) { next; }
6926: my @to_correct;
6927:
6928: # Probably here's where the error is...
6929:
6930: foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
6931: if ($missing > $max_bubble) { next; }
6932: push(@to_correct,$missing);
6933: }
6934: if (@to_correct) {
6935: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6936: $line,'missingbubble',\@to_correct);
6937: return (1,$currentphase);
6938: }
6939:
6940: }
6941: return (0,$currentphase+1);
6942: }
6943:
6944: =pod
6945:
6946: =item scantron_process_students
6947:
6948: Routine that does the actual grading of the bubble sheet information.
6949:
6950: The parsed scanline hash is added to %env
6951:
6952: Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
6953: foreach resource , with the form data of
6954:
6955: 'submitted' =>'scantron'
6956: 'grade_target' =>'grade',
6957: 'grade_username'=> username of student
6958: 'grade_domain' => domain of student
6959: 'grade_courseid'=> of course
6960: 'grade_symb' => symb of resource to grade
6961:
6962: This triggers a grading pass. The problem grading code takes care
6963: of converting the bubbled letter information (now in %env) into a
6964: valid submission.
6965:
6966: =cut
6967:
6968: sub scantron_process_students {
6969: my ($r) = @_;
6970: my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
6971: my ($symb)=&get_symb($r);
6972: if (!$symb) {return '';}
6973: my $default_form_data=&defaultFormData($symb);
6974:
6975: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6976: my ($scanlines,$scan_data)=&scantron_getfile();
6977: my $classlist=&Apache::loncoursedata::get_classlist();
6978: my %idmap=&username_to_idmap($classlist);
6979: my $navmap=Apache::lonnavmaps::navmap->new();
6980: my $map=$navmap->getResourceByUrl($sequence);
6981: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
6982: # $r->print("geto ".scalar(@resources)."<br />");
6983: my $result= <<SCANTRONFORM;
6984: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
6985: <input type="hidden" name="command" value="scantron_configphase" />
6986: $default_form_data
6987: SCANTRONFORM
6988: $r->print($result);
6989:
6990: my @delayqueue;
6991: my %completedstudents;
6992:
6993: my $count=&get_todo_count($scanlines,$scan_data);
6994: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
6995: 'Scantron Progress',$count,
6996: 'inline',undef,'scantronupload');
6997: &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
6998: 'Processing first student');
6999: my $start=&Time::HiRes::time();
7000: my $i=-1;
7001: my ($uname,$udom,$started);
7002:
7003: &scantron_get_maxbubble(); # Need the bubble lines array to parse.
7004:
7005: while ($i<$scanlines->{'count'}) {
7006: ($uname,$udom)=('','');
7007: $i++;
7008: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7009: if ($line=~/^[\s\cz]*$/) { next; }
7010: if ($started) {
7011: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
7012: 'last student');
7013: }
7014: $started=1;
7015: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7016: $scan_data);
7017: unless ($uname=&scantron_find_student($scan_record,$scan_data,
7018: \%idmap,$i)) {
7019: &scantron_add_delay(\@delayqueue,$line,
7020: 'Unable to find a student that matches',1);
7021: next;
7022: }
7023: if (exists $completedstudents{$uname}) {
7024: &scantron_add_delay(\@delayqueue,$line,
7025: 'Student '.$uname.' has multiple sheets',2);
7026: next;
7027: }
7028: ($uname,$udom)=split(/:/,$uname);
7029:
7030: &Apache::lonxml::clear_problem_counter();
7031: &Apache::lonnet::appenv(%$scan_record);
7032:
7033: if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
7034: &scantron_putfile($scanlines,$scan_data);
7035: }
7036:
7037: my $i=0;
7038: foreach my $resource (@resources) {
7039: $i++;
7040: my %form=('submitted' =>'scantron',
7041: 'grade_target' =>'grade',
7042: 'grade_username'=>$uname,
7043: 'grade_domain' =>$udom,
7044: 'grade_courseid'=>$env{'request.course.id'},
7045: 'grade_symb' =>$resource->symb());
7046: if (exists($scan_record->{'scantron.CODE'})
7047: &&
7048: &Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
7049: $form{'CODE'}=$scan_record->{'scantron.CODE'};
7050: } else {
7051: $form{'CODE'}='';
7052: }
7053: my $result=&Apache::lonnet::ssi($resource->src(),%form);
7054: if ($result ne '') {
7055: }
7056: if (&Apache::loncommon::connection_aborted($r)) { last; }
7057: }
7058: $completedstudents{$uname}={'line'=>$line};
7059: if (&Apache::loncommon::connection_aborted($r)) { last; }
7060: } continue {
7061: &Apache::lonxml::clear_problem_counter();
7062: &Apache::lonnet::delenv('scantron\.');
7063: }
7064: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
7065: # my $lasttime = &Time::HiRes::time()-$start;
7066: # $r->print("<p>took $lasttime</p>");
7067:
7068: $r->print("</form>");
7069: $r->print(&show_grading_menu_form($symb));
7070: return '';
7071: }
7072:
7073: =pod
7074:
7075: =item scantron_upload_scantron_data
7076:
7077: Creates the screen for adding a new bubble sheet data file to a course.
7078:
7079: =cut
7080:
7081: sub scantron_upload_scantron_data {
7082: my ($r)=@_;
7083: $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
7084: my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
7085: 'domainid',
7086: 'coursename');
7087: my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
7088: 'domainid');
7089: my $default_form_data=&defaultFormData(&get_symb($r,1));
7090: $r->print(<<UPLOAD);
7091: <script type="text/javascript" language="javascript">
7092: function checkUpload(formname) {
7093: if (formname.upfile.value == "") {
7094: alert("Please use the browse button to select a file from your local directory.");
7095: return false;
7096: }
7097: formname.submit();
7098: }
7099: </script>
7100:
7101: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
7102: $default_form_data
7103: <table>
7104: <tr><td>$select_link </td></tr>
7105: <tr><td>Course ID: </td><td><input name='courseid' type='text' /> </td></tr>
7106: <tr><td>Course Name: </td><td><input name='coursename' type='text' /></td></tr>
7107: <tr><td>Domain: </td><td>$domsel </td></tr>
7108: <tr><td>File to upload:</td><td><input type="file" name="upfile" size="50" /></td></tr>
7109: </table>
7110: <input name='command' value='scantronupload_save' type='hidden' />
7111: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
7112: </form>
7113: UPLOAD
7114: return '';
7115: }
7116:
7117: =pod
7118:
7119: =item scantron_upload_scantron_data_save
7120:
7121: Adds a provided bubble information data file to the course if user
7122: has the correct privileges to do so.
7123:
7124: =cut
7125:
7126: sub scantron_upload_scantron_data_save {
7127: my($r)=@_;
7128: my ($symb)=&get_symb($r,1);
7129: my $doanotherupload=
7130: '<br /><form action="/adm/grades" method="post">'."\n".
7131: '<input type="hidden" name="command" value="scantronupload" />'."\n".
7132: '<input type="submit" name="submit" value="Do Another Upload" />'."\n".
7133: '</form>'."\n";
7134: if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
7135: !&Apache::lonnet::allowed('usc',
7136: $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
7137: $r->print("You are not allowed to upload Scantron data to the requested course.<br />");
7138: if ($symb) {
7139: $r->print(&show_grading_menu_form($symb));
7140: } else {
7141: $r->print($doanotherupload);
7142: }
7143: return '';
7144: }
7145: my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
7146: $r->print("Doing upload to ".$coursedata{'description'}." <br />");
7147: my $fname=$env{'form.upfile.filename'};
7148: #FIXME
7149: #copied from lonnet::userfileupload()
7150: #make that function able to target a specified course
7151: # Replace Windows backslashes by forward slashes
7152: $fname=~s/\\/\//g;
7153: # Get rid of everything but the actual filename
7154: $fname=~s/^.*\/([^\/]+)$/$1/;
7155: # Replace spaces by underscores
7156: $fname=~s/\s+/\_/g;
7157: # Replace all other weird characters by nothing
7158: $fname=~s/[^\w\.\-]//g;
7159: # See if there is anything left
7160: unless ($fname) { return 'error: no uploaded file'; }
7161: my $uploadedfile=$fname;
7162: $fname='scantron_orig_'.$fname;
7163: if (length($env{'form.upfile'}) < 2) {
7164: $r->print("<span class=\"LC_error\">Error:</span> The file you attempted to upload, <tt>".&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"')."</tt>, contained no information. Please check that you entered the correct filename.");
7165: } else {
7166: my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
7167: if ($result =~ m|^/uploaded/|) {
7168: $r->print("<span class=\"LC_success\">Success:</span> Successfully uploaded ".(length($env{'form.upfile'})-1)." bytes of data into location <tt>".$result."</tt>");
7169: } else {
7170: $r->print("<span class=\"LC_error\">Error:</span> An error (".$result.") occurred when attempting to upload the file, <tt>".&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"')."</tt>");
7171: }
7172: }
7173: if ($symb) {
7174: $r->print(&scantron_selectphase($r,$uploadedfile));
7175: } else {
7176: $r->print($doanotherupload);
7177: }
7178: return '';
7179: }
7180:
7181: =pod
7182:
7183: =item valid_file
7184:
7185: Validates that the requested bubble data file exists in the course.
7186:
7187: =cut
7188:
7189: sub valid_file {
7190: my ($requested_file)=@_;
7191: foreach my $filename (sort(&scantron_filenames())) {
7192: if ($requested_file eq $filename) { return 1; }
7193: }
7194: return 0;
7195: }
7196:
7197: =pod
7198:
7199: =item scantron_download_scantron_data
7200:
7201: Shows a list of the three internal files (original, corrected,
7202: skipped) for a specific bubble sheet data file that exists in the
7203: course.
7204:
7205: =cut
7206:
7207: sub scantron_download_scantron_data {
7208: my ($r)=@_;
7209: my $default_form_data=&defaultFormData(&get_symb($r,1));
7210: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7211: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7212: my $file=$env{'form.scantron_selectfile'};
7213: if (! &valid_file($file)) {
7214: $r->print(<<ERROR);
7215: <p>
7216: The requested file name was invalid.
7217: </p>
7218: ERROR
7219: $r->print(&show_grading_menu_form(&get_symb($r,1)));
7220: return;
7221: }
7222: my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
7223: my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
7224: my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
7225: &Apache::lonnet::allowuploaded('/adm/grades',$orig);
7226: &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
7227: &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
7228: $r->print(<<DOWNLOAD);
7229: <p>
7230: <a href="$orig">Original</a> file as uploaded by the scantron office.
7231: </p>
7232: <p>
7233: <a href="$corrected">Corrections</a>, a file of corrected records that were used in grading.
7234: </p>
7235: <p>
7236: <a href="$skipped">Skipped</a>, a file of records that were skipped.
7237: </p>
7238: DOWNLOAD
7239: $r->print(&show_grading_menu_form(&get_symb($r,1)));
7240: return '';
7241: }
7242:
7243: =pod
7244:
7245: =back
7246:
7247: =cut
7248:
7249: #-------- end of section for handling grading scantron forms -------
7250: #
7251: #-------------------------------------------------------------------
7252:
7253: #-------------------------- Menu interface -------------------------
7254: #
7255: #--- Show a Grading Menu button - Calls the next routine ---
7256: sub show_grading_menu_form {
7257: my ($symb)=@_;
7258: my $result.='<br /><form action="/adm/grades" method="post">'."\n".
7259: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
7260: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
7261: '<input type="hidden" name="command" value="gradingmenu" />'."\n".
7262: '<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
7263: '</form>'."\n";
7264: return $result;
7265: }
7266:
7267: # -- Retrieve choices for grading form
7268: sub savedState {
7269: my %savedState = ();
7270: if ($env{'form.saveState'}) {
7271: foreach (split(/:/,$env{'form.saveState'})) {
7272: my ($key,$value) = split(/=/,$_,2);
7273: $savedState{$key} = $value;
7274: }
7275: }
7276: return \%savedState;
7277: }
7278:
7279: sub grading_menu {
7280: my ($request) = @_;
7281: my ($symb)=&get_symb($request);
7282: if (!$symb) {return '';}
7283: my $probTitle = &Apache::lonnet::gettitle($symb);
7284: my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
7285:
7286: $request->print($table);
7287: my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
7288: 'handgrade'=>$hdgrade,
7289: 'probTitle'=>$probTitle,
7290: 'command'=>'submit_options',
7291: 'saveState'=>"",
7292: 'gradingMenu'=>1,
7293: 'showgrading'=>"yes");
7294: my $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
7295: my @menu = ({ url => $url,
7296: name => &mt('Manual Grading/View Submissions'),
7297: short_description =>
7298: &mt('Start the process of hand grading submissions.'),
7299: });
7300: $fields{'command'} = 'csvform';
7301: $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
7302: push (@menu, { url => $url,
7303: name => &mt('Upload Scores'),
7304: short_description =>
7305: &mt('Specify a file containing the class scores for current resource.')});
7306: $fields{'command'} = 'processclicker';
7307: $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
7308: push (@menu, { url => $url,
7309: name => &mt('Process Clicker'),
7310: short_description =>
7311: &mt('Specify a file containing the clicker information for this resource.')});
7312: $fields{'command'} = 'scantron_selectphase';
7313: $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
7314: push (@menu, { url => $url,
7315: name => &mt('Grade/Manage Scantron Forms'),
7316: short_description =>
7317: &mt('')});
7318: $fields{'command'} = 'verify';
7319: $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
7320: push (@menu, { url => "",
7321: name => &mt('Verify Receipt'),
7322: short_description =>
7323: &mt('')});
7324: #
7325: # Create the menu
7326: my $Str;
7327: # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
7328: $Str .= '<form method="post" action="" name="gradingMenu">';
7329: $Str .= '<input type="hidden" name="command" value="" />'.
7330: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
7331: '<input type="hidden" name="handgrade" value="'.$hdgrade.'" />'."\n".
7332: '<input type="hidden" name="probTitle" value="'.$probTitle.'" />'."\n".
7333: '<input type="hidden" name="saveState" value="" />'."\n".
7334: '<input type="hidden" name="gradingMenu" value="1" />'."\n".
7335: '<input type="hidden" name="showgrading" value="yes" />'."\n";
7336:
7337: foreach my $menudata (@menu) {
7338: if ($menudata->{'name'} ne &mt('Verify Receipt')) {
7339: $Str .=' <h3><a '.
7340: $menudata->{'jscript'}.
7341: ' href="'.
7342: $menudata->{'url'}.'" >'.
7343: $menudata->{'name'}."</a></h3>\n";
7344: } else {
7345: $Str .=' <h3><input type="button" value="Verify Receipt" '.
7346: $menudata->{'jscript'}.
7347: ' onClick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
7348: ' /></h3>';
7349: $Str .= (' 'x8).
7350: ' receipt: '.&Apache::lonnet::recprefix($env{'request.course.id'}).
7351: '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
7352: }
7353: $Str .= ' '.(' 'x8).$menudata->{'short_description'}.
7354: "\n";
7355: }
7356: $Str .="</form>\n";
7357: $request->print(<<GRADINGMENUJS);
7358: <script type="text/javascript" language="javascript">
7359: function checkChoice(formname,val,cmdx) {
7360: if (val <= 2) {
7361: var cmd = radioSelection(formname.radioChoice);
7362: var cmdsave = cmd;
7363: } else {
7364: cmd = cmdx;
7365: cmdsave = 'submission';
7366: }
7367: formname.command.value = cmd;
7368: if (val < 5) formname.submit();
7369: if (val == 5) {
7370: if (!checkReceiptNo(formname,'notOK')) {
7371: return false;
7372: } else {
7373: formname.submit();
7374: }
7375: }
7376: }
7377:
7378: function checkReceiptNo(formname,nospace) {
7379: var receiptNo = formname.receipt.value;
7380: var checkOpt = false;
7381: if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
7382: if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
7383: if (checkOpt) {
7384: alert("Please enter a receipt number given by a student in the receipt box.");
7385: formname.receipt.value = "";
7386: formname.receipt.focus();
7387: return false;
7388: }
7389: return true;
7390: }
7391: </script>
7392: GRADINGMENUJS
7393: &commonJSfunctions($request);
7394: return $Str;
7395: }
7396:
7397:
7398: #--- Displays the submissions first page -------
7399: sub submit_options {
7400: my ($request) = @_;
7401: my ($symb)=&get_symb($request);
7402: if (!$symb) {return '';}
7403: my $probTitle = &Apache::lonnet::gettitle($symb);
7404:
7405: $request->print(<<GRADINGMENUJS);
7406: <script type="text/javascript" language="javascript">
7407: function checkChoice(formname,val,cmdx) {
7408: if (val <= 2) {
7409: var cmd = radioSelection(formname.radioChoice);
7410: var cmdsave = cmd;
7411: } else {
7412: cmd = cmdx;
7413: cmdsave = 'submission';
7414: }
7415: formname.command.value = cmd;
7416: formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
7417: ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
7418: if (val < 5) formname.submit();
7419: if (val == 5) {
7420: if (!checkReceiptNo(formname,'notOK')) { return false;}
7421: formname.submit();
7422: }
7423: if (val < 7) formname.submit();
7424: }
7425:
7426: function checkReceiptNo(formname,nospace) {
7427: var receiptNo = formname.receipt.value;
7428: var checkOpt = false;
7429: if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
7430: if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
7431: if (checkOpt) {
7432: alert("Please enter a receipt number given by a student in the receipt box.");
7433: formname.receipt.value = "";
7434: formname.receipt.focus();
7435: return false;
7436: }
7437: return true;
7438: }
7439: </script>
7440: GRADINGMENUJS
7441: &commonJSfunctions($request);
7442: my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
7443: my $result;
7444: my (undef,$sections) = &getclasslist('all','0');
7445: my $savedState = &savedState();
7446: my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
7447: my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
7448: my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
7449: my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
7450:
7451: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
7452: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
7453: '<input type="hidden" name="handgrade" value="'.$hdgrade.'" />'."\n".
7454: '<input type="hidden" name="probTitle" value="'.$probTitle.'" />'."\n".
7455: '<input type="hidden" name="command" value="" />'."\n".
7456: '<input type="hidden" name="saveState" value="" />'."\n".
7457: '<input type="hidden" name="gradingMenu" value="1" />'."\n".
7458: '<input type="hidden" name="showgrading" value="yes" />'."\n";
7459:
7460: $result.='
7461: <div class="LC_grade_select_mode">
7462: <div class="LC_grade_select_mode_current">
7463: <h2>
7464: '.&mt('Grade Current Resource').'
7465: </h2>
7466: <div class="LC_grade_select_mode_body">
7467: <div class="LC_grades_resource_info">
7468: '.$table.'
7469: </div>
7470: <div class="LC_grade_select_mode_selector">
7471: <div class="LC_grade_select_mode_selector_header">
7472: '.&mt('Sections').'
7473: </div>
7474: <div class="LC_grade_select_mode_selector_body">
7475: <select name="section" multiple="multiple" size="5">'."\n";
7476: if (ref($sections)) {
7477: foreach my $section (sort (@$sections)) {
7478: $result.='<option value="'.$section.'" '.
7479: ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
7480: }
7481: }
7482: $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> ';
7483: $result.='
7484: </div>
7485: </div>
7486: <div class="LC_grade_select_mode_selector">
7487: <div class="LC_grade_select_mode_selector_header">
7488: '.&mt('Groups').'
7489: </div>
7490: <div class="LC_grade_select_mode_selector_body">
7491: '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
7492: </div>
7493: </div>
7494: <div class="LC_grade_select_mode_selector">
7495: <div class="LC_grade_select_mode_selector_header">
7496: '.&mt('Access Status').'
7497: </div>
7498: <div class="LC_grade_select_mode_selector_body">
7499: '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
7500: </div>
7501: </div>
7502: <div class="LC_grade_select_mode_selector">
7503: <div class="LC_grade_select_mode_selector_header">
7504: '.&mt('Submission Status').'
7505: </div>
7506: <div class="LC_grade_select_mode_selector_body">
7507: <select name="submitonly" size="5">
7508: <option value="yes" '. ($saveSub eq 'yes' ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
7509: <option value="queued" '. ($saveSub eq 'queued' ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
7510: <option value="graded" '. ($saveSub eq 'graded' ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
7511: <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
7512: <option value="all" '. ($saveSub eq 'all' ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
7513: </select>
7514: </div>
7515: </div>
7516: <div class="LC_grade_select_mode_type_body">
7517: <div class="LC_grade_select_mode_type">
7518: <label>
7519: <input type="radio" name="radioChoice" value="submission" '.
7520: ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
7521: &mt('Select individual students to grade and view submissions.').'
7522: </label>
7523: </div>
7524: <div class="LC_grade_select_mode_type">
7525: <label>
7526: <input type="radio" name="radioChoice" value="viewgrades" '.
7527: ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
7528: &mt('Grade all selected students in a grading table.').'
7529: </label>
7530: </div>
7531: <div class="LC_grade_select_mode_type">
7532: <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next->').'" />
7533: </div>
7534: </div>
7535: </div>
7536: </div>
7537: <div class="LC_grade_select_mode_page">
7538: <h2>
7539: '.&mt('Grade Complete Folder for One Student').'
7540: </h2>
7541: <div class="LC_grades_select_mode_body">
7542: <div class="LC_grade_select_mode_type_body">
7543: <div class="LC_grade_select_mode_type">
7544: <label>
7545: <input type="radio" name="radioChoice" value="pickStudentPage" '.
7546: ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
7547: &mt('The <b>complete</b> page/sequence/folder: For one student').'
7548: </label>
7549: </div>
7550: <div class="LC_grade_select_mode_type">
7551: <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next->').'" />
7552: </div>
7553: </div>
7554: </div>
7555: </div>
7556: </div>
7557: </form>';
7558: return $result;
7559: }
7560:
7561: sub reset_perm {
7562: undef(%perm);
7563: }
7564:
7565: sub init_perm {
7566: &reset_perm();
7567: foreach my $test_perm ('vgr','mgr','opa') {
7568:
7569: my $scope = $env{'request.course.id'};
7570: if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
7571:
7572: $scope .= '/'.$env{'request.course.sec'};
7573: if ( $perm{$test_perm}=
7574: &Apache::lonnet::allowed($test_perm,$scope)) {
7575: $perm{$test_perm.'_section'}=$env{'request.course.sec'};
7576: } else {
7577: delete($perm{$test_perm});
7578: }
7579: }
7580: }
7581: }
7582:
7583: sub gather_clicker_ids {
7584: my %clicker_ids;
7585:
7586: my $classlist = &Apache::loncoursedata::get_classlist();
7587:
7588: # Set up a couple variables.
7589: my $username_idx = &Apache::loncoursedata::CL_SNAME();
7590: my $domain_idx = &Apache::loncoursedata::CL_SDOM();
7591: my $status_idx = &Apache::loncoursedata::CL_STATUS();
7592:
7593: foreach my $student (keys(%$classlist)) {
7594: if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
7595: my $username = $classlist->{$student}->[$username_idx];
7596: my $domain = $classlist->{$student}->[$domain_idx];
7597: my $clickers =
7598: (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
7599: foreach my $id (split(/\,/,$clickers)) {
7600: $id=~s/^[\#0]+//;
7601: $id=~s/[\-\:]//g;
7602: if (exists($clicker_ids{$id})) {
7603: $clicker_ids{$id}.=','.$username.':'.$domain;
7604: } else {
7605: $clicker_ids{$id}=$username.':'.$domain;
7606: }
7607: }
7608: }
7609: return %clicker_ids;
7610: }
7611:
7612: sub gather_adv_clicker_ids {
7613: my %clicker_ids;
7614: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
7615: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7616: my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
7617: foreach my $element (sort(keys(%coursepersonnel))) {
7618: foreach my $person (split(/\,/,$coursepersonnel{$element})) {
7619: my ($puname,$pudom)=split(/\:/,$person);
7620: my $clickers =
7621: (&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
7622: foreach my $id (split(/\,/,$clickers)) {
7623: $id=~s/^[\#0]+//;
7624: $id=~s/[\-\:]//g;
7625: if (exists($clicker_ids{$id})) {
7626: $clicker_ids{$id}.=','.$puname.':'.$pudom;
7627: } else {
7628: $clicker_ids{$id}=$puname.':'.$pudom;
7629: }
7630: }
7631: }
7632: }
7633: return %clicker_ids;
7634: }
7635:
7636: sub clicker_grading_parameters {
7637: return ('gradingmechanism' => 'scalar',
7638: 'upfiletype' => 'scalar',
7639: 'specificid' => 'scalar',
7640: 'pcorrect' => 'scalar',
7641: 'pincorrect' => 'scalar');
7642: }
7643:
7644: sub process_clicker {
7645: my ($r)=@_;
7646: my ($symb)=&get_symb($r);
7647: if (!$symb) {return '';}
7648: my $result=&checkforfile_js();
7649: $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
7650: my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
7651: $result.=$table;
7652: $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
7653: $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
7654: $result.=' <b>'.&mt('Specify a file containing the clicker information for this resource').
7655: '.</b></td></tr>'."\n";
7656: $result.='<tr bgcolor=#ffffe6><td>'."\n";
7657: # Attempt to restore parameters from last session, set defaults if not present
7658: my %Saveable_Parameters=&clicker_grading_parameters();
7659: &Apache::loncommon::restore_course_settings('grades_clicker',
7660: \%Saveable_Parameters);
7661: if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
7662: if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
7663: if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
7664: if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
7665:
7666: my %checked;
7667: foreach my $gradingmechanism ('attendance','personnel','specific') {
7668: if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
7669: $checked{$gradingmechanism}="checked='checked'";
7670: }
7671: }
7672:
7673: my $upload=&mt("Upload File");
7674: my $type=&mt("Type");
7675: my $attendance=&mt("Award points just for participation");
7676: my $personnel=&mt("Correctness determined from response by course personnel");
7677: my $specific=&mt("Correctness determined from response with clicker ID(s)");
7678: my $pcorrect=&mt("Percentage points for correct solution");
7679: my $pincorrect=&mt("Percentage points for incorrect solution");
7680: my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
7681: ('iclicker' => 'i>clicker',
7682: 'interwrite' => 'interwrite PRS'));
7683: $symb = &Apache::lonenc::check_encrypt($symb);
7684: $result.=<<ENDUPFORM;
7685: <script type="text/javascript">
7686: function sanitycheck() {
7687: // Accept only integer percentages
7688: document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
7689: document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
7690: // Find out grading choice
7691: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
7692: if (document.forms.gradesupload.gradingmechanism[i].checked) {
7693: gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
7694: }
7695: }
7696: // By default, new choice equals user selection
7697: newgradingchoice=gradingchoice;
7698: // Not good to give more points for false answers than correct ones
7699: if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
7700: document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
7701: }
7702: // If new choice is attendance only, and old choice was correctness-based, restore defaults
7703: if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
7704: document.forms.gradesupload.pcorrect.value=100;
7705: document.forms.gradesupload.pincorrect.value=100;
7706: }
7707: // If the values are different, cannot be attendance only
7708: if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
7709: (gradingchoice=='attendance')) {
7710: newgradingchoice='personnel';
7711: }
7712: // Change grading choice to new one
7713: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
7714: if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
7715: document.forms.gradesupload.gradingmechanism[i].checked=true;
7716: } else {
7717: document.forms.gradesupload.gradingmechanism[i].checked=false;
7718: }
7719: }
7720: // Remember the old state
7721: document.forms.gradesupload.waschecked.value=newgradingchoice;
7722: }
7723: </script>
7724: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
7725: <input type="hidden" name="symb" value="$symb" />
7726: <input type="hidden" name="command" value="processclickerfile" />
7727: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
7728: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
7729: <input type="file" name="upfile" size="50" />
7730: <br /><label>$type: $selectform</label>
7731: <br /><label><input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
7732: <br /><label><input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
7733: <br /><label><input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" />$specific </label>
7734: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
7735: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
7736: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
7737: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
7738: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
7739: </form>
7740: ENDUPFORM
7741: $result.='</td></tr></table>'."\n".
7742: '</td></tr></table><br /><br />'."\n";
7743: $result.=&show_grading_menu_form($symb);
7744: return $result;
7745: }
7746:
7747: sub process_clicker_file {
7748: my ($r)=@_;
7749: my ($symb)=&get_symb($r);
7750: if (!$symb) {return '';}
7751:
7752: my %Saveable_Parameters=&clicker_grading_parameters();
7753: &Apache::loncommon::store_course_settings('grades_clicker',
7754: \%Saveable_Parameters);
7755:
7756: my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
7757: if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
7758: $result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
7759: return $result.&show_grading_menu_form($symb);
7760: }
7761: my %clicker_ids=&gather_clicker_ids();
7762: my %correct_ids;
7763: if ($env{'form.gradingmechanism'} eq 'personnel') {
7764: %correct_ids=&gather_adv_clicker_ids();
7765: }
7766: if ($env{'form.gradingmechanism'} eq 'specific') {
7767: foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
7768: $correct_id=~tr/a-z/A-Z/;
7769: $correct_id=~s/\s//gs;
7770: $correct_id=~s/^[\#0]+//;
7771: $correct_id=~s/[\-\:]//g;
7772: if ($correct_id) {
7773: $correct_ids{$correct_id}='specified';
7774: }
7775: }
7776: }
7777: if ($env{'form.gradingmechanism'} eq 'attendance') {
7778: $result.=&mt('Score based on attendance only');
7779: } else {
7780: my $number=0;
7781: $result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
7782: foreach my $id (sort(keys(%correct_ids))) {
7783: $result.='<br /><tt>'.$id.'</tt> - ';
7784: if ($correct_ids{$id} eq 'specified') {
7785: $result.=&mt('specified');
7786: } else {
7787: my ($uname,$udom)=split(/\:/,$correct_ids{$id});
7788: $result.=&Apache::loncommon::plainname($uname,$udom);
7789: }
7790: $number++;
7791: }
7792: $result.="</p>\n";
7793: if ($number==0) {
7794: $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
7795: return $result.&show_grading_menu_form($symb);
7796: }
7797: }
7798: if (length($env{'form.upfile'}) < 2) {
7799: $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
7800: '<span class="LC_error">',
7801: '</span>',
7802: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
7803: return $result.&show_grading_menu_form($symb);
7804: }
7805:
7806: # Were able to get all the info needed, now analyze the file
7807:
7808: $result.=&Apache::loncommon::studentbrowser_javascript();
7809: $symb = &Apache::lonenc::check_encrypt($symb);
7810: my $heading=&mt('Scanning clicker file');
7811: $result.=(<<ENDHEADER);
7812: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
7813: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
7814: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
7815: <form method="post" action="/adm/grades" name="clickeranalysis">
7816: <input type="hidden" name="symb" value="$symb" />
7817: <input type="hidden" name="command" value="assignclickergrades" />
7818: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
7819: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
7820: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
7821: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
7822: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
7823: ENDHEADER
7824: my %responses;
7825: my @questiontitles;
7826: my $errormsg='';
7827: my $number=0;
7828: if ($env{'form.upfiletype'} eq 'iclicker') {
7829: ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
7830: }
7831: if ($env{'form.upfiletype'} eq 'interwrite') {
7832: ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
7833: }
7834: $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
7835: '<input type="hidden" name="number" value="'.$number.'" />'.
7836: &mt('Awarding [_1] percent for corrion(s)',$number).'<br />'.
7837: '<input type="hidden" name="number" value="'.$number.'" />'.
7838: &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
7839: $env{'form.pcorrect'},$env{'form.pincorrect'}).
7840: '<br />';
7841: # Remember Question Titles
7842: # FIXME: Possibly need delimiter other than ":"
7843: for (my $i=0;$i<$number;$i++) {
7844: $result.='<input type="hidden" name="question:'.$i.'" value="'.
7845: &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
7846: }
7847: my $correct_count=0;
7848: my $student_count=0;
7849: my $unknown_count=0;
7850: # Match answers with usernames
7851: # FIXME: Possibly need delimiter other than ":"
7852: foreach my $id (keys(%responses)) {
7853: if ($correct_ids{$id}) {
7854: $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
7855: $correct_count++;
7856: } elsif ($clicker_ids{$id}) {
7857: if ($clicker_ids{$id}=~/\,/) {
7858: # More than one user with the same clicker!
7859: $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
7860: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
7861: "<select name='multi".$id."'>";
7862: foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
7863: $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
7864: }
7865: $result.='</select>';
7866: $unknown_count++;
7867: } else {
7868: # Good: found one and only one user with the right clicker
7869: $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
7870: $student_count++;
7871: }
7872: } else {
7873: $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
7874: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
7875: "\n".&mt("Username").": <input type='text' name='uname".$id."' /> ".
7876: "\n".&mt("Domain").": ".
7877: &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).' '.
7878: &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
7879: $unknown_count++;
7880: }
7881: }
7882: $result.='<hr />'.
7883: &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
7884: if ($env{'form.gradingmechanism'} ne 'attendance') {
7885: if ($correct_count==0) {
7886: $errormsg.="Found no correct answers answers for grading!";
7887: } elsif ($correct_count>1) {
7888: $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
7889: }
7890: }
7891: if ($number<1) {
7892: $errormsg.="Found no questions.";
7893: }
7894: if ($errormsg) {
7895: $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
7896: } else {
7897: $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
7898: }
7899: $result.='</form></td></tr></table>'."\n".
7900: '</td></tr></table><br /><br />'."\n";
7901: return $result.&show_grading_menu_form($symb);
7902: }
7903:
7904: sub iclicker_eval {
7905: my ($questiontitles,$responses)=@_;
7906: my $number=0;
7907: my $errormsg='';
7908: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
7909: my %components=&Apache::loncommon::record_sep($line);
7910: my @entries=map {$components{$_}} (sort(keys(%components)));
7911: if ($entries[0] eq 'Question') {
7912: for (my $i=3;$i<$#entries;$i+=6) {
7913: $$questiontitles[$number]=$entries[$i];
7914: $number++;
7915: }
7916: }
7917: if ($entries[0]=~/^\#/) {
7918: my $id=$entries[0];
7919: my @idresponses;
7920: $id=~s/^[\#0]+//;
7921: for (my $i=0;$i<$number;$i++) {
7922: my $idx=3+$i*6;
7923: push(@idresponses,$entries[$idx]);
7924: }
7925: $$responses{$id}=join(',',@idresponses);
7926: }
7927: }
7928: return ($errormsg,$number);
7929: }
7930:
7931: sub interwrite_eval {
7932: my ($questiontitles,$responses)=@_;
7933: my $number=0;
7934: my $errormsg='';
7935: my $skipline=1;
7936: my $questionnumber=0;
7937: my %idresponses=();
7938: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
7939: my %components=&Apache::loncommon::record_sep($line);
7940: my @entries=map {$components{$_}} (sort(keys(%components)));
7941: if ($entries[1] eq 'Time') { $skipline=0; next; }
7942: if ($entries[1] eq 'Response') { $skipline=1; }
7943: next if $skipline;
7944: if ($entries[0]!=$questionnumber) {
7945: $questionnumber=$entries[0];
7946: $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
7947: $number++;
7948: }
7949: my $id=$entries[4];
7950: $id=~s/^[\#0]+//;
7951: $id=~s/^v\d*\://i;
7952: $id=~s/[\-\:]//g;
7953: $idresponses{$id}[$number]=$entries[6];
7954: }
7955: foreach my $id (keys %idresponses) {
7956: $$responses{$id}=join(',',@{$idresponses{$id}});
7957: $$responses{$id}=~s/^\s*\,//;
7958: }
7959: return ($errormsg,$number);
7960: }
7961:
7962: sub assign_clicker_grades {
7963: my ($r)=@_;
7964: my ($symb)=&get_symb($r);
7965: if (!$symb) {return '';}
7966: # See which part we are saving to
7967: my ($partlist,$handgrade,$responseType) = &response_type($symb);
7968: # FIXME: This should probably look for the first handgradeable part
7969: my $part=$$partlist[0];
7970: # Start screen output
7971: my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
7972:
7973: my $heading=&mt('Assigning grades based on clicker file');
7974: $result.=(<<ENDHEADER);
7975: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
7976: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
7977: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
7978: ENDHEADER
7979: # Get correct result
7980: # FIXME: Possibly need delimiter other than ":"
7981: my @correct=();
7982: my $gradingmechanism=$env{'form.gradingmechanism'};
7983: my $number=$env{'form.number'};
7984: if ($gradingmechanism ne 'attendance') {
7985: foreach my $key (keys(%env)) {
7986: if ($key=~/^form\.correct\:/) {
7987: my @input=split(/\,/,$env{$key});
7988: for (my $i=0;$i<=$#input;$i++) {
7989: if (($correct[$i]) && ($input[$i]) &&
7990: ($correct[$i] ne $input[$i])) {
7991: $result.='<br /><span class="LC_warning">'.
7992: &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
7993: $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
7994: } elsif ($input[$i]) {
7995: $correct[$i]=$input[$i];
7996: }
7997: }
7998: }
7999: }
8000: for (my $i=0;$i<$number;$i++) {
8001: if (!$correct[$i]) {
8002: $result.='<br /><span class="LC_error">'.
8003: &mt('No correct result given for question "[_1]"!',
8004: $env{'form.question:'.$i}).'</span>';
8005: }
8006: }
8007: $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
8008: }
8009: # Start grading
8010: my $pcorrect=$env{'form.pcorrect'};
8011: my $pincorrect=$env{'form.pincorrect'};
8012: my $storecount=0;
8013: foreach my $key (keys(%env)) {
8014: my $user='';
8015: if ($key=~/^form\.student\:(.*)$/) {
8016: $user=$1;
8017: }
8018: if ($key=~/^form\.unknown\:(.*)$/) {
8019: my $id=$1;
8020: if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
8021: $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
8022: } elsif ($env{'form.multi'.$id}) {
8023: $user=$env{'form.multi'.$id};
8024: }
8025: }
8026: if ($user) {
8027: my @answer=split(/\,/,$env{$key});
8028: my $sum=0;
8029: for (my $i=0;$i<$number;$i++) {
8030: if ($answer[$i]) {
8031: if ($gradingmechanism eq 'attendance') {
8032: $sum+=$pcorrect;
8033: } else {
8034: if ($answer[$i] eq $correct[$i]) {
8035: $sum+=$pcorrect;
8036: } else {
8037: $sum+=$pincorrect;
8038: }
8039: }
8040: }
8041: }
8042: my $ave=$sum/(100*$number);
8043: # Store
8044: my ($username,$domain)=split(/\:/,$user);
8045: my %grades=();
8046: $grades{"resource.$part.solved"}='correct_by_override';
8047: $grades{"resource.$part.awarded"}=$ave;
8048: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
8049: my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
8050: $env{'request.course.id'},
8051: $domain,$username);
8052: if ($returncode ne 'ok') {
8053: $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
8054: } else {
8055: $storecount++;
8056: }
8057: }
8058: }
8059: # We are done
8060: $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
8061: '</td></tr></table>'."\n".
8062: '</td></tr></table><br /><br />'."\n";
8063: return $result.&show_grading_menu_form($symb);
8064: }
8065:
8066: sub handler {
8067: my $request=$_[0];
8068: &reset_caches();
8069: if ($env{'browser.mathml'}) {
8070: &Apache::loncommon::content_type($request,'text/xml');
8071: } else {
8072: &Apache::loncommon::content_type($request,'text/html');
8073: }
8074: $request->send_http_header;
8075: return '' if $request->header_only;
8076: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
8077: my $symb=&get_symb($request,1);
8078: my @commands=&Apache::loncommon::get_env_multiple('form.command');
8079: my $command=$commands[0];
8080:
8081: if ($#commands > 0) {
8082: &Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
8083: }
8084:
8085:
8086: $request->print(&Apache::loncommon::start_page('Grading'));
8087: if ($symb eq '' && $command eq '') {
8088: if ($env{'user.adv'}) {
8089: if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
8090: ($env{'form.codethree'})) {
8091: my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
8092: $env{'form.codethree'};
8093: my ($tsymb,$tuname,$tudom,$tcrsid)=
8094: &Apache::lonnet::checkin($token);
8095: if ($tsymb) {
8096: my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
8097: if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
8098: $request->print(&Apache::lonnet::ssi_body('/res/'.$url,
8099: ('grade_username' => $tuname,
8100: 'grade_domain' => $tudom,
8101: 'grade_courseid' => $tcrsid,
8102: 'grade_symb' => $tsymb)));
8103: } else {
8104: $request->print('<h3>Not authorized: '.$token.'</h3>');
8105: }
8106: } else {
8107: $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
8108: }
8109: } else {
8110: $request->print(&Apache::lonxml::tokeninputfield());
8111: }
8112: }
8113: } else {
8114: &init_perm();
8115: if ($command eq 'submission' && $perm{'vgr'}) {
8116: ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
8117: } elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
8118: &pickStudentPage($request);
8119: } elsif ($command eq 'displayPage' && $perm{'vgr'}) {
8120: &displayPage($request);
8121: } elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
8122: &updateGradeByPage($request);
8123: } elsif ($command eq 'processGroup' && $perm{'vgr'}) {
8124: &processGroup($request);
8125: } elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
8126: $request->print(&grading_menu($request));
8127: } elsif ($command eq 'submit_options' && $perm{'vgr'}) {
8128: $request->print(&submit_options($request));
8129: } elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
8130: $request->print(&viewgrades($request));
8131: } elsif ($command eq 'handgrade' && $perm{'mgr'}) {
8132: $request->print(&processHandGrade($request));
8133: } elsif ($command eq 'editgrades' && $perm{'mgr'}) {
8134: $request->print(&editgrades($request));
8135: } elsif ($command eq 'verify' && $perm{'vgr'}) {
8136: $request->print(&verifyreceipt($request));
8137: } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
8138: $request->print(&process_clicker($request));
8139: } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
8140: $request->print(&process_clicker_file($request));
8141: } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
8142: $request->print(&assign_clicker_grades($request));
8143: } elsif ($command eq 'csvform' && $perm{'mgr'}) {
8144: $request->print(&upcsvScores_form($request));
8145: } elsif ($command eq 'csvupload' && $perm{'mgr'}) {
8146: $request->print(&csvupload($request));
8147: } elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
8148: $request->print(&csvuploadmap($request));
8149: } elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
8150: if ($env{'form.associate'} ne 'Reverse Association') {
8151: $request->print(&csvuploadoptions($request));
8152: } else {
8153: if ( $env{'form.upfile_associate'} ne 'reverse' ) {
8154: $env{'form.upfile_associate'} = 'reverse';
8155: } else {
8156: $env{'form.upfile_associate'} = 'forward';
8157: }
8158: $request->print(&csvuploadmap($request));
8159: }
8160: } elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
8161: $request->print(&csvuploadassign($request));
8162: } elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
8163: $request->print(&scantron_selectphase($request));
8164: } elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
8165: $request->print(&scantron_do_warning($request));
8166: } elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
8167: $request->print(&scantron_validate_file($request));
8168: } elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
8169: $request->print(&scantron_process_students($request));
8170: } elsif ($command eq 'scantronupload' &&
8171: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
8172: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
8173: $request->print(&scantron_upload_scantron_data($request));
8174: } elsif ($command eq 'scantronupload_save' &&
8175: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
8176: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
8177: $request->print(&scantron_upload_scantron_data_save($request));
8178: } elsif ($command eq 'scantron_download' &&
8179: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
8180: $request->print(&scantron_download_scantron_data($request));
8181: } elsif ($command) {
8182: $request->print("Access Denied ($command)");
8183: }
8184: }
8185: $request->print(&Apache::loncommon::end_page());
8186: &reset_caches();
8187: return '';
8188: }
8189:
8190: 1;
8191:
8192: __END__;
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>