1: # The LearningOnline Network with CAPA
2: # The LON-CAPA Grading handler
3: #
4: # $Id: grades.pm,v 1.486 2007/11/08 19:57:30 albertel 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 LONCAPA;
46:
47: use POSIX qw(floor);
48:
49:
50: my %perm=();
51: my %bubble_lines_per_response = (); # no. bubble lines for each response.
52: # index is "symb.part_id"
53:
54: my %first_bubble_line = (); # First bubble line no. for each bubble.
55:
56: # Save and restore the bubble lines array to the form env.
57:
58:
59: sub save_bubble_lines {
60: foreach my $line (keys(%bubble_lines_per_response)) {
61: $env{"form.scantron.bubblelines.$line"} = $bubble_lines_per_response{$line};
62: $env{"form.scantron.first_bubble_line.$line"} =
63: $first_bubble_line{$line};
64: }
65: }
66:
67:
68: sub restore_bubble_lines {
69: my $line = 0;
70: %bubble_lines_per_response = ();
71: while ($env{"form.scantron.bubblelines.$line"}) {
72: my $value = $env{"form.scantron.bubblelines.$line"};
73: $bubble_lines_per_response{$line} = $value;
74: $first_bubble_line{$line} =
75: $env{"form.scantron.first_bubble_line.$line"};
76: $line++;
77: }
78:
79: }
80:
81: # Given the parsed scanline, get the response for
82: # 'answer' number n:
83:
84: sub get_response_bubbles {
85: my ($parsed_line, $response) = @_;
86:
87:
88: my $bubble_line = $first_bubble_line{$response-1} +1;
89: my $bubble_lines= $bubble_lines_per_response{$response-1};
90:
91: my $selected = "";
92:
93: for (my $bline = 0; $bline < $bubble_lines; $bline++) {
94: $selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
95: $bubble_line++;
96: }
97: return $selected;
98: }
99:
100:
101: # ----- These first few routines are general use routines.----
102:
103: # Return the number of occurences of a pattern in a string.
104:
105: sub occurence_count {
106: my ($string, $pattern) = @_;
107:
108: my @matches = ($string =~ /$pattern/g);
109:
110: return scalar(@matches);
111: }
112:
113:
114: # Take a string known to have digits and convert all the
115: # digits into letters in the range J,A..I.
116:
117: sub digits_to_letters {
118: my ($input) = @_;
119:
120: my @alphabet = ('J', 'A'..'I');
121:
122: my @input = split(//, $input);
123: my $output ='';
124: for (my $i = 0; $i < scalar(@input); $i++) {
125: if ($input[$i] =~ /\d/) {
126: $output .= $alphabet[$input[$i]];
127: } else {
128: $output .= $input[$i];
129: }
130: }
131: return $output;
132: }
133:
134: #
135: # --- Retrieve the parts from the metadata file.---
136: sub getpartlist {
137: my ($symb) = @_;
138:
139: my $navmap = Apache::lonnavmaps::navmap->new();
140: my $res = $navmap->getBySymb($symb);
141: my $partlist = $res->parts();
142: my $url = $res->src();
143: my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
144:
145: my @stores;
146: foreach my $part (@{ $partlist }) {
147: foreach my $key (@metakeys) {
148: if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
149: }
150: }
151: return @stores;
152: }
153:
154: # --- Get the symbolic name of a problem and the url
155: sub get_symb {
156: my ($request,$silent) = @_;
157: (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
158: my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
159: if ($symb eq '') {
160: if (!$silent) {
161: $request->print("Unable to handle ambiguous references:$url:.");
162: return ();
163: }
164: }
165: &Apache::lonenc::check_decrypt(\$symb);
166: return ($symb);
167: }
168:
169: #--- Format fullname, username:domain if different for display
170: #--- Use anywhere where the student names are listed
171: sub nameUserString {
172: my ($type,$fullname,$uname,$udom) = @_;
173: if ($type eq 'header') {
174: return '<b> '.&mt('Fullname').' </b><span class="LC_internal_info">('.&mt('Username').')</span>';
175: } else {
176: return ' '.$fullname.'<span class="LC_internal_info"> ('.$uname.
177: ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
178: }
179: }
180:
181: #--- Get the partlist and the response type for a given problem. ---
182: #--- Indicate if a response type is coded handgraded or not. ---
183: sub response_type {
184: my ($symb) = shift;
185:
186: my $navmap = Apache::lonnavmaps::navmap->new();
187: my $res = $navmap->getBySymb($symb);
188: my $partlist = $res->parts();
189: my %vPart =
190: map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
191: my (%response_types,%handgrade);
192: foreach my $part (@{ $partlist }) {
193: next if (%vPart && !exists($vPart{$part}));
194:
195: my @types = $res->responseType($part);
196: my @ids = $res->responseIds($part);
197: for (my $i=0; $i < scalar(@ids); $i++) {
198: $response_types{$part}{$ids[$i]} = $types[$i];
199: $handgrade{$part.'_'.$ids[$i]} =
200: &Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
201: '.handgrade',$symb);
202: }
203: }
204: return ($partlist,\%handgrade,\%response_types);
205: }
206:
207: sub flatten_responseType {
208: my ($responseType) = @_;
209: my @part_response_id =
210: map {
211: my $part = $_;
212: map {
213: [$part,$_]
214: } sort(keys(%{ $responseType->{$part} }));
215: } sort(keys(%$responseType));
216: return @part_response_id;
217: }
218:
219: sub get_display_part {
220: my ($partID,$symb)=@_;
221: my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
222: if (defined($display) and $display ne '') {
223: $display.= " (<span class=\"LC_internal_info\">id $partID</span>)";
224: } else {
225: $display=$partID;
226: }
227: return $display;
228: }
229:
230: #--- Show resource title
231: #--- and parts and response type
232: sub showResourceInfo {
233: my ($symb,$probTitle,$checkboxes) = @_;
234: my $col=3;
235: if ($checkboxes) { $col=4; }
236: my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
237: $result .='<table border="0">';
238: my ($partlist,$handgrade,$responseType) = &response_type($symb);
239: my %resptype = ();
240: my $hdgrade='no';
241: my %partsseen;
242: foreach my $partID (sort keys(%$responseType)) {
243: foreach my $resID (sort keys(%{ $responseType->{$partID} })) {
244: my $handgrade=$$handgrade{$partID.'_'.$resID};
245: my $responsetype = $responseType->{$partID}->{$resID};
246: $hdgrade = $handgrade if ($handgrade eq 'yes');
247: $result.='<tr>';
248: if ($checkboxes) {
249: if (exists($partsseen{$partID})) {
250: $result.="<td> </td>";
251: } else {
252: $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
253: }
254: $partsseen{$partID}=1;
255: }
256: my $display_part=&get_display_part($partID,$symb);
257: $result.='<td>'.&mt('<b>Part: </b>[_1]',$display_part).' <span class="LC_internal_info">'.
258: $resID.'</span></td>'.
259: '<td>'.&mt('<b>Type: </b>[_1]',$responsetype).'</td></tr>';
260: # '<td>'.&mt('<b>Handgrade: </b>[_1]',$handgrade).'</td></tr>';
261: }
262: }
263: $result.='</table>'."\n";
264: return $result,$responseType,$hdgrade,$partlist,$handgrade;
265: }
266:
267: sub reset_caches {
268: &reset_analyze_cache();
269: &reset_perm();
270: }
271:
272: {
273: my %analyze_cache;
274:
275: sub reset_analyze_cache {
276: undef(%analyze_cache);
277: }
278:
279: sub get_analyze {
280: my ($symb,$uname,$udom)=@_;
281: my $key = "$symb\0$uname\0$udom";
282: return $analyze_cache{$key} if (exists($analyze_cache{$key}));
283:
284: my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
285: $url=&Apache::lonnet::clutter($url);
286: my $subresult=&Apache::lonnet::ssi($url,
287: ('grade_target' => 'analyze'),
288: ('grade_domain' => $udom),
289: ('grade_symb' => $symb),
290: ('grade_courseid' =>
291: $env{'request.course.id'}),
292: ('grade_username' => $uname));
293: (undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
294: my %analyze=&Apache::lonnet::str2hash($subresult);
295: return $analyze_cache{$key} = \%analyze;
296: }
297:
298: sub get_order {
299: my ($partid,$respid,$symb,$uname,$udom)=@_;
300: my $analyze = &get_analyze($symb,$uname,$udom);
301: return $analyze->{"$partid.$respid.shown"};
302: }
303:
304: sub get_radiobutton_correct_foil {
305: my ($partid,$respid,$symb,$uname,$udom)=@_;
306: my $analyze = &get_analyze($symb,$uname,$udom);
307: foreach my $foil (@{&get_order($partid,$respid,$symb,$uname,$udom)}) {
308: if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
309: return $foil;
310: }
311: }
312: }
313: }
314:
315: #--- Clean response type for display
316: #--- Currently filters option/rank/radiobutton/match/essay/Task
317: # response types only.
318: sub cleanRecord {
319: my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
320: $uname,$udom) = @_;
321: my $grayFont = '<span class="LC_internal_info">';
322: if ($response =~ /^(option|rank)$/) {
323: my %answer=&Apache::lonnet::str2hash($answer);
324: my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
325: my ($toprow,$bottomrow);
326: foreach my $foil (@$order) {
327: if ($grading{$foil} == 1) {
328: $toprow.='<td><b>'.$answer{$foil}.' </b></td>';
329: } else {
330: $toprow.='<td><i>'.$answer{$foil}.' </i></td>';
331: }
332: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
333: }
334: return '<blockquote><table border="1">'.
335: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
336: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
337: $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
338: } elsif ($response eq 'match') {
339: my %answer=&Apache::lonnet::str2hash($answer);
340: my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
341: my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
342: my ($toprow,$middlerow,$bottomrow);
343: foreach my $foil (@$order) {
344: my $item=shift(@items);
345: if ($grading{$foil} == 1) {
346: $toprow.='<td><b>'.$item.' </b></td>';
347: $middlerow.='<td><b>'.$grayFont.$answer{$foil}.' </span></b></td>';
348: } else {
349: $toprow.='<td><i>'.$item.' </i></td>';
350: $middlerow.='<td><i>'.$grayFont.$answer{$foil}.' </span></i></td>';
351: }
352: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
353: }
354: return '<blockquote><table border="1">'.
355: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
356: '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
357: $middlerow.'</tr>'.
358: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
359: $bottomrow.'</tr>'.'</table></blockquote>';
360: } elsif ($response eq 'radiobutton') {
361: my %answer=&Apache::lonnet::str2hash($answer);
362: my ($toprow,$bottomrow);
363: my $correct =
364: &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
365: foreach my $foil (@$order) {
366: if (exists($answer{$foil})) {
367: if ($foil eq $correct) {
368: $toprow.='<td><b>'.&mt('true').'</b></td>';
369: } else {
370: $toprow.='<td><i>'.&mt('true').'</i></td>';
371: }
372: } else {
373: $toprow.='<td>'.&mt('false').'</td>';
374: }
375: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
376: }
377: return '<blockquote><table border="1">'.
378: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
379: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
380: $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
381: } elsif ($response eq 'essay') {
382: if (! exists ($env{'form.'.$symb})) {
383: my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
384: $env{'course.'.$env{'request.course.id'}.'.domain'},
385: $env{'course.'.$env{'request.course.id'}.'.num'});
386:
387: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
388: $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
389: $env{'form.kwclr'} = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
390: $env{'form.kwsize'} = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
391: $env{'form.kwstyle'} = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
392: $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
393: }
394: $answer =~ s-\n-<br />-g;
395: return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
396: } elsif ( $response eq 'organic') {
397: my $result='Smile representation: "<tt>'.$answer.'</tt>"';
398: my $jme=$record->{$version."resource.$partid.$respid.molecule"};
399: $result.=&Apache::chemresponse::jme_img($jme,$answer,400);
400: return $result;
401: } elsif ( $response eq 'Task') {
402: if ( $answer eq 'SUBMITTED') {
403: my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
404: my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
405: return $result;
406: } elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
407: my @matches = grep(/^\Q$version\E.*?\.instance$/,
408: keys(%{$record}));
409: return join('<br />',($version,@matches));
410:
411:
412: } else {
413: my $result =
414: '<p>'
415: .&mt('Overall result: [_1]',
416: $record->{$version."resource.$respid.$partid.status"})
417: .'</p>';
418:
419: $result .= '<ul>';
420: my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
421: keys(%{$record}));
422: foreach my $grade (sort(@grade)) {
423: my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
424: $result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
425: $dim, $record->{$grade}).
426: '</li>';
427: }
428: $result.='</ul>';
429: return $result;
430: }
431: } elsif ( $response =~ m/(?:numerical|formula)/) {
432: $answer =
433: &Apache::loncommon::format_previous_attempt_value('submission',
434: $answer);
435: }
436: return $answer;
437: }
438:
439: #-- A couple of common js functions
440: sub commonJSfunctions {
441: my $request = shift;
442: $request->print(<<COMMONJSFUNCTIONS);
443: <script type="text/javascript" language="javascript">
444: function radioSelection(radioButton) {
445: var selection=null;
446: if (radioButton.length > 1) {
447: for (var i=0; i<radioButton.length; i++) {
448: if (radioButton[i].checked) {
449: return radioButton[i].value;
450: }
451: }
452: } else {
453: if (radioButton.checked) return radioButton.value;
454: }
455: return selection;
456: }
457:
458: function pullDownSelection(selectOne) {
459: var selection="";
460: if (selectOne.length > 1) {
461: for (var i=0; i<selectOne.length; i++) {
462: if (selectOne[i].selected) {
463: return selectOne[i].value;
464: }
465: }
466: } else {
467: // only one value it must be the selected one
468: return selectOne.value;
469: }
470: }
471: </script>
472: COMMONJSFUNCTIONS
473: }
474:
475: #--- Dumps the class list with usernames,list of sections,
476: #--- section, ids and fullnames for each user.
477: sub getclasslist {
478: my ($getsec,$filterlist,$getgroup) = @_;
479: my @getsec;
480: my @getgroup;
481: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
482: if (!ref($getsec)) {
483: if ($getsec ne '' && $getsec ne 'all') {
484: @getsec=($getsec);
485: }
486: } else {
487: @getsec=@{$getsec};
488: }
489: if (grep(/^all$/,@getsec)) { undef(@getsec); }
490: if (!ref($getgroup)) {
491: if ($getgroup ne '' && $getgroup ne 'all') {
492: @getgroup=($getgroup);
493: }
494: } else {
495: @getgroup=@{$getgroup};
496: }
497: if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
498:
499: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
500: # Bail out if we were unable to get the classlist
501: return if (! defined($classlist));
502: &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
503: #
504: my %sections;
505: my %fullnames;
506: foreach my $student (keys(%$classlist)) {
507: my $end =
508: $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
509: my $start =
510: $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
511: my $id =
512: $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
513: my $section =
514: $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
515: my $fullname =
516: $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
517: my $status =
518: $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
519: my $group =
520: $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
521: # filter students according to status selected
522: if ($filterlist && (!($stu_status =~ /Any/))) {
523: if (!($stu_status =~ $status)) {
524: delete($classlist->{$student});
525: next;
526: }
527: }
528: # filter students according to groups selected
529: my @stu_groups = split(/,/,$group);
530: if (@getgroup) {
531: my $exclude = 1;
532: foreach my $grp (@getgroup) {
533: foreach my $stu_group (@stu_groups) {
534: if ($stu_group eq $grp) {
535: $exclude = 0;
536: }
537: }
538: if (($grp eq 'none') && !$group) {
539: $exclude = 0;
540: }
541: }
542: if ($exclude) {
543: delete($classlist->{$student});
544: }
545: }
546: $section = ($section ne '' ? $section : 'none');
547: if (&canview($section)) {
548: if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
549: $sections{$section}++;
550: if ($classlist->{$student}) {
551: $fullnames{$student}=$fullname;
552: }
553: } else {
554: delete($classlist->{$student});
555: }
556: } else {
557: delete($classlist->{$student});
558: }
559: }
560: my %seen = ();
561: my @sections = sort(keys(%sections));
562: return ($classlist,\@sections,\%fullnames);
563: }
564:
565: sub canmodify {
566: my ($sec)=@_;
567: if ($perm{'mgr'}) {
568: if (!defined($perm{'mgr_section'})) {
569: # can modify whole class
570: return 1;
571: } else {
572: if ($sec eq $perm{'mgr_section'}) {
573: #can modify the requested section
574: return 1;
575: } else {
576: # can't modify the request section
577: return 0;
578: }
579: }
580: }
581: #can't modify
582: return 0;
583: }
584:
585: sub canview {
586: my ($sec)=@_;
587: if ($perm{'vgr'}) {
588: if (!defined($perm{'vgr_section'})) {
589: # can modify whole class
590: return 1;
591: } else {
592: if ($sec eq $perm{'vgr_section'}) {
593: #can modify the requested section
594: return 1;
595: } else {
596: # can't modify the request section
597: return 0;
598: }
599: }
600: }
601: #can't modify
602: return 0;
603: }
604:
605: #--- Retrieve the grade status of a student for all the parts
606: sub student_gradeStatus {
607: my ($symb,$udom,$uname,$partlist) = @_;
608: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
609: my %partstatus = ();
610: foreach (@$partlist) {
611: my ($status,undef) = split(/_/,$record{"resource.$_.solved"},2);
612: $status = 'nothing' if ($status eq '');
613: $partstatus{$_} = $status;
614: my $subkey = "resource.$_.submitted_by";
615: $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
616: }
617: return %partstatus;
618: }
619:
620: # hidden form and javascript that calls the form
621: # Use by verifyscript and viewgrades
622: # Shows a student's view of problem and submission
623: sub jscriptNform {
624: my ($symb) = @_;
625: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
626: my $jscript='<script type="text/javascript" language="javascript">'."\n".
627: ' function viewOneStudent(user,domain) {'."\n".
628: ' document.onestudent.student.value = user;'."\n".
629: ' document.onestudent.userdom.value = domain;'."\n".
630: ' document.onestudent.submit();'."\n".
631: ' }'."\n".
632: '</script>'."\n";
633: $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
634: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
635: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
636: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
637: '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
638: '<input type="hidden" name="command" value="submission" />'."\n".
639: '<input type="hidden" name="student" value="" />'."\n".
640: '<input type="hidden" name="userdom" value="" />'."\n".
641: '</form>'."\n";
642: return $jscript;
643: }
644:
645:
646:
647: # Given the score (as a number [0-1] and the weight) what is the final
648: # point value? This function will round to the nearest tenth, third,
649: # or quarter if one of those is within the tolerance of .00001.
650: sub compute_points {
651: my ($score, $weight) = @_;
652:
653: my $tolerance = .00001;
654: my $points = $score * $weight;
655:
656: # Check for nearness to 1/x.
657: my $check_for_nearness = sub {
658: my ($factor) = @_;
659: my $num = ($points * $factor) + $tolerance;
660: my $floored_num = floor($num);
661: if ($num - $floored_num < 2 * $tolerance * $factor) {
662: return $floored_num / $factor;
663: }
664: return $points;
665: };
666:
667: $points = $check_for_nearness->(10);
668: $points = $check_for_nearness->(3);
669: $points = $check_for_nearness->(4);
670:
671: return $points;
672: }
673:
674: #------------------ End of general use routines --------------------
675:
676: #
677: # Find most similar essay
678: #
679:
680: sub most_similar {
681: my ($uname,$udom,$uessay,$old_essays)=@_;
682:
683: # ignore spaces and punctuation
684:
685: $uessay=~s/\W+/ /gs;
686:
687: # ignore empty submissions (occuring when only files are sent)
688:
689: unless ($uessay=~/\w+/) { return ''; }
690:
691: # these will be returned. Do not care if not at least 50 percent similar
692: my $limit=0.6;
693: my $sname='';
694: my $sdom='';
695: my $scrsid='';
696: my $sessay='';
697: # go through all essays ...
698: foreach my $tkey (keys(%$old_essays)) {
699: my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
700: # ... except the same student
701: next if (($tname eq $uname) && ($tdom eq $udom));
702: my $tessay=$old_essays->{$tkey};
703: $tessay=~s/\W+/ /gs;
704: # String similarity gives up if not even limit
705: my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
706: # Found one
707: if ($tsimilar>$limit) {
708: $limit=$tsimilar;
709: $sname=$tname;
710: $sdom=$tdom;
711: $scrsid=$tcrsid;
712: $sessay=$old_essays->{$tkey};
713: }
714: }
715: if ($limit>0.6) {
716: return ($sname,$sdom,$scrsid,$sessay,$limit);
717: } else {
718: return ('','','','',0);
719: }
720: }
721:
722: #-------------------------------------------------------------------
723:
724: #------------------------------------ Receipt Verification Routines
725: #
726: #--- Check whether a receipt number is valid.---
727: sub verifyreceipt {
728: my $request = shift;
729:
730: my $courseid = $env{'request.course.id'};
731: my $receipt = &Apache::lonnet::recprefix($courseid).'-'.
732: $env{'form.receipt'};
733: $receipt =~ s/[^\-\d]//g;
734: my ($symb) = &get_symb($request);
735:
736: my $title.='<h3><span class="LC_info">Verifying Submission Receipt '.
737: $receipt.'</h3></span>'."\n".
738: '<h4><b>Resource: </b>'.$env{'form.probTitle'}.'</h4><br /><br />'."\n";
739:
740: my ($string,$contents,$matches) = ('','',0);
741: my (undef,undef,$fullname) = &getclasslist('all','0');
742:
743: my $receiptparts=0;
744: if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
745: $env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
746: my $parts=['0'];
747: if ($receiptparts) { ($parts)=&response_type($symb); }
748:
749: my $header =
750: &Apache::loncommon::start_data_table().
751: &Apache::loncommon::start_data_table_header_row().
752: '<th> Fullname </th>'."\n".
753: '<th> Username </th>'."\n".
754: '<th> Domain </th>';
755: if ($receiptparts) {
756: $header.='<th> Problem Part </th>';
757: }
758: $header.=
759: &Apache::loncommon::end_data_table_header_row();
760:
761: foreach (sort
762: {
763: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
764: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
765: }
766: return $a cmp $b;
767: } (keys(%$fullname))) {
768: my ($uname,$udom)=split(/\:/);
769: foreach my $part (@$parts) {
770: if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
771: $contents.=
772: &Apache::loncommon::start_data_table_row().
773: '<td> '."\n".
774: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
775: '\');" target="_self">'.$$fullname{$_}.'</a> </td>'."\n".
776: '<td> '.$uname.' </td>'.
777: '<td> '.$udom.' </td>';
778: if ($receiptparts) {
779: $contents.='<td> '.$part.' </td>';
780: }
781: $contents.=
782: &Apache::loncommon::end_data_table_row()."\n";
783:
784: $matches++;
785: }
786: }
787: }
788: if ($matches == 0) {
789: $string = $title.'No match found for the above receipt.';
790: } else {
791: $string = &jscriptNform($symb).$title.
792: 'The above receipt matches the following student'.
793: ($matches <= 1 ? '.' : 's.')."\n".
794: $header.
795: $contents.
796: &Apache::loncommon::end_data_table()."\n";
797: }
798: return $string.&show_grading_menu_form($symb);
799: }
800:
801: #--- This is called by a number of programs.
802: #--- Called from the Grading Menu - View/Grade an individual student
803: #--- Also called directly when one clicks on the subm button
804: # on the problem page.
805: sub listStudents {
806: my ($request) = shift;
807:
808: my ($symb) = &get_symb($request);
809: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
810: my $cnum = $env{"course.$env{'request.course.id'}.num"};
811: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
812: my $getgroup = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
813: my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
814: my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
815: $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ?
816: &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
817:
818: my $result='<h3><span class="LC_info"> '.
819: &mt($viewgrade.' Submissions for a Student or a Group of Students')
820: .'</span></h3>';
821:
822: my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
823:
824: my %lt = ( 'multiple' =>
825: "Please select a student or group of students before clicking on the Next button.",
826: 'single' =>
827: "Please select the student before clicking on the Next button.",
828: );
829: %lt = &Apache::lonlocal::texthash(%lt);
830: $request->print(<<LISTJAVASCRIPT);
831: <script type="text/javascript" language="javascript">
832: function checkSelect(checkBox) {
833: var ctr=0;
834: var sense="";
835: if (checkBox.length > 1) {
836: for (var i=0; i<checkBox.length; i++) {
837: if (checkBox[i].checked) {
838: ctr++;
839: }
840: }
841: sense = '$lt{'multiple'}';
842: } else {
843: if (checkBox.checked) {
844: ctr = 1;
845: }
846: sense = '$lt{'single'}';
847: }
848: if (ctr == 0) {
849: alert(sense);
850: return false;
851: }
852: document.gradesub.submit();
853: }
854:
855: function reLoadList(formname) {
856: if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
857: formname.command.value = 'submission';
858: formname.submit();
859: }
860: </script>
861: LISTJAVASCRIPT
862:
863: &commonJSfunctions($request);
864: $request->print($result);
865:
866: my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
867: my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
868: my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
869: "\n".$table;
870:
871: $gradeTable .=
872: ' '.
873: &mt('<b>View Problem Text: </b>[_1]',
874: '<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
875: '<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n".
876: '<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label>').'<br />'."\n";
877: $gradeTable .=
878: ' '.
879: &mt('<b>View Answer: </b>[_1]',
880: '<label><input type="radio" name="vAns" value="no" /> '.&mt('no').' </label>'."\n".
881: '<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n".
882: '<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label>').'<br />'."\n";
883:
884: my $submission_options;
885: if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
886: $submission_options.=
887: '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
888: }
889: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
890: my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
891: $env{'form.Status'} = $saveStatus;
892: $submission_options.=
893: '<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.&mt('last submission only').' </label>'."\n".
894: '<label><input type="radio" name="lastSub" value="last" /> '.&mt('last submission & parts info').' </label>'."\n".
895: '<label><input type="radio" name="lastSub" value="datesub" /> '.&mt('by dates and submissions').' </label>'."\n".
896: '<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').'</label>';
897: $gradeTable .=
898: ' '.
899: &mt('<b>Submissions: </b>[_1]',$submission_options).'<br />'."\n";
900:
901: $gradeTable .=
902: ' '.
903: &mt('<b>Grading Increments:</b> [_1]',
904: '<select name="increment">'.
905: '<option value="1">'.&mt('Whole Points').'</option>'.
906: '<option value=".5">'.&mt('Half Points').'</option>'.
907: '<option value=".25">'.&mt('Quarter Points').'</option>'.
908: '<option value=".1">'.&mt('Tenths of a Point').'</option>'.
909: '</select>');
910:
911: $gradeTable .=
912: &build_section_inputs().
913: '<input type="hidden" name="submitonly" value="'.$submitonly.'" />'."\n".
914: '<input type="hidden" name="handgrade" value="'.$env{'form.handgrade'}.'" /><br />'."\n".
915: '<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
916: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
917: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
918: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
919: '<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
920:
921: if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
922: $gradeTable.='<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
923: } else {
924: $gradeTable.=&mt('<b>Student Status:</b> [_1]',
925: &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);')).'<br />';
926: }
927:
928: $gradeTable.=&mt('To '.lc($viewgrade).' a submission or a group of submissions, click on the check box(es) '.
929: 'next to the student\'s name(s). Then click on the Next button.').'<br />'."\n".
930: '<input type="hidden" name="command" value="processGroup" />'."\n";
931:
932: # checkall buttons
933: $gradeTable.=&check_script('gradesub', 'stuinfo');
934: $gradeTable.='<input type="button" '."\n".
935: 'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
936: 'value="'.&mt('Next->').'" /> <br />'."\n";
937: $gradeTable.=&check_buttons();
938: $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />'.&mt('Check For Plagiarism').'</label>';
939: my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
940: $gradeTable.= &Apache::loncommon::start_data_table().
941: &Apache::loncommon::start_data_table_header_row();
942: my $loop = 0;
943: while ($loop < 2) {
944: $gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
945: '<th>'.&nameUserString('header').' '.&mt('Section/Group').'</th>';
946: if ($env{'form.showgrading'} eq 'yes'
947: && $submitonly ne 'queued'
948: && $submitonly ne 'all') {
949: foreach my $part (sort(@$partlist)) {
950: my $display_part=
951: &get_display_part((split(/_/,$part))[0],$symb);
952: $gradeTable.=
953: '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
954: }
955: } elsif ($submitonly eq 'queued') {
956: $gradeTable.='<th>'.&mt('Queue Status').' </th>';
957: }
958: $loop++;
959: # $gradeTable.='<td></td>' if ($loop%2 ==1);
960: }
961: $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
962:
963: my $ctr = 0;
964: foreach my $student (sort
965: {
966: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
967: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
968: }
969: return $a cmp $b;
970: }
971: (keys(%$fullname))) {
972: my ($uname,$udom) = split(/:/,$student);
973:
974: my %status = ();
975:
976: if ($submitonly eq 'queued') {
977: my %queue_status =
978: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
979: $udom,$uname);
980: next if (!defined($queue_status{'gradingqueue'}));
981: $status{'gradingqueue'} = $queue_status{'gradingqueue'};
982: }
983:
984: if ($env{'form.showgrading'} eq 'yes'
985: && $submitonly ne 'queued'
986: && $submitonly ne 'all') {
987: (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
988: my $submitted = 0;
989: my $graded = 0;
990: my $incorrect = 0;
991: foreach (keys(%status)) {
992: $submitted = 1 if ($status{$_} ne 'nothing');
993: $graded = 1 if ($status{$_} =~ /^ungraded/);
994: $incorrect = 1 if ($status{$_} =~ /^incorrect/);
995:
996: my ($foo,$partid,$foo1) = split(/\./,$_);
997: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
998: $submitted = 0;
999: my ($part)=split(/\./,$partid);
1000: $gradeTable.='<input type="hidden" name="'.
1001: $student.':'.$part.':submitted_by" value="'.
1002: $status{'resource.'.$partid.'.submitted_by'}.'" />';
1003: }
1004: }
1005:
1006: next if (!$submitted && ($submitonly eq 'yes' ||
1007: $submitonly eq 'incorrect' ||
1008: $submitonly eq 'graded'));
1009: next if (!$graded && ($submitonly eq 'graded'));
1010: next if (!$incorrect && $submitonly eq 'incorrect');
1011: }
1012:
1013: $ctr++;
1014: my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1015: my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1016: if ( $perm{'vgr'} eq 'F' ) {
1017: if ($ctr%2 ==1) {
1018: $gradeTable.= &Apache::loncommon::start_data_table_row();
1019: }
1020: $gradeTable.='<td align="right">'.$ctr.' </td>'.
1021: '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
1022: $student.':'.$$fullname{$student}.':::SECTION'.$section.
1023: ') " /> </label></td>'."\n".'<td>'.
1024: &nameUserString(undef,$$fullname{$student},$uname,$udom).
1025: ' '.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1026:
1027: if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1028: foreach (sort keys(%status)) {
1029: next if ($_ =~ /^resource.*?submitted_by$/);
1030: $gradeTable.='<td align="center"> '.&mt($status{$_}).' </td>'."\n";
1031: }
1032: }
1033: # $gradeTable.='<td></td>' if ($ctr%2 ==1);
1034: if ($ctr%2 ==0) {
1035: $gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
1036: }
1037: }
1038: }
1039: if ($ctr%2 ==1) {
1040: $gradeTable.='<td> </td><td> </td><td> </td>';
1041: if ($env{'form.showgrading'} eq 'yes'
1042: && $submitonly ne 'queued'
1043: && $submitonly ne 'all') {
1044: foreach (@$partlist) {
1045: $gradeTable.='<td> </td>';
1046: }
1047: } elsif ($submitonly eq 'queued') {
1048: $gradeTable.='<td> </td>';
1049: }
1050: $gradeTable.=&Apache::loncommon::end_data_table_row();
1051: }
1052:
1053: $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1054: '<input type="button" '.
1055: 'onClick="javascript:checkSelect(this.form.stuinfo);" '.
1056: 'value="'.&mt('Next->').'" /></form>'."\n";
1057: if ($ctr == 0) {
1058: my $num_students=(scalar(keys(%$fullname)));
1059: if ($num_students eq 0) {
1060: $gradeTable='<br /> <span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1061: } else {
1062: my $submissions='submissions';
1063: if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
1064: if ($submitonly eq 'graded' ) { $submissions = 'ungraded submissions'; }
1065: if ($submitonly eq 'queued' ) { $submissions = 'queued submissions'; }
1066: $gradeTable='<br /> <span class="LC_warning">'.
1067: &mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
1068: $num_students).
1069: '</span><br />';
1070: }
1071: } elsif ($ctr == 1) {
1072: $gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1073: }
1074: $gradeTable.=&show_grading_menu_form($symb);
1075: $request->print($gradeTable);
1076: return '';
1077: }
1078:
1079: #---- Called from the listStudents routine
1080:
1081: sub check_script {
1082: my ($form, $type)=@_;
1083: my $chkallscript='<script type="text/javascript">
1084: function checkall() {
1085: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1086: ele = document.forms.'.$form.'.elements[i];
1087: if (ele.name == "'.$type.'") {
1088: document.forms.'.$form.'.elements[i].checked=true;
1089: }
1090: }
1091: }
1092:
1093: function checksec() {
1094: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1095: ele = document.forms.'.$form.'.elements[i];
1096: string = document.forms.'.$form.'.chksec.value;
1097: if
1098: (ele.value.indexOf(":::SECTION"+string)>0) {
1099: document.forms.'.$form.'.elements[i].checked=true;
1100: }
1101: }
1102: }
1103:
1104:
1105: function uncheckall() {
1106: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1107: ele = document.forms.'.$form.'.elements[i];
1108: if (ele.name == "'.$type.'") {
1109: document.forms.'.$form.'.elements[i].checked=false;
1110: }
1111: }
1112: }
1113:
1114: </script>'."\n";
1115: return $chkallscript;
1116: }
1117:
1118: sub check_buttons {
1119: my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
1120: $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" /> ';
1121: $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1122: $buttons.='<input type="text" size="5" name="chksec" /> ';
1123: return $buttons;
1124: }
1125:
1126: # Displays the submissions for one student or a group of students
1127: sub processGroup {
1128: my ($request) = shift;
1129: my $ctr = 0;
1130: my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1131: my $total = scalar(@stuchecked)-1;
1132:
1133: foreach my $student (@stuchecked) {
1134: my ($uname,$udom,$fullname) = split(/:/,$student);
1135: $env{'form.student'} = $uname;
1136: $env{'form.userdom'} = $udom;
1137: $env{'form.fullname'} = $fullname;
1138: &submission($request,$ctr,$total);
1139: $ctr++;
1140: }
1141: return '';
1142: }
1143:
1144: #------------------------------------------------------------------------------------
1145: #
1146: #-------------------------- Next few routines handles grading by student, essentially
1147: # handles essay response type problem/part
1148: #
1149: #--- Javascript to handle the submission page functionality ---
1150: sub sub_page_js {
1151: my $request = shift;
1152: $request->print(<<SUBJAVASCRIPT);
1153: <script type="text/javascript" language="javascript">
1154: function updateRadio(formname,id,weight) {
1155: var gradeBox = formname["GD_BOX"+id];
1156: var radioButton = formname["RADVAL"+id];
1157: var oldpts = formname["oldpts"+id].value;
1158: var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1159: gradeBox.value = pts;
1160: var resetbox = false;
1161: if (isNaN(pts) || pts < 0) {
1162: alert("A number equal or greater than 0 is expected. Entered value = "+pts);
1163: for (var i=0; i<radioButton.length; i++) {
1164: if (radioButton[i].checked) {
1165: gradeBox.value = i;
1166: resetbox = true;
1167: }
1168: }
1169: if (!resetbox) {
1170: formtextbox.value = "";
1171: }
1172: return;
1173: }
1174:
1175: if (pts > weight) {
1176: var resp = confirm("You entered a value ("+pts+
1177: ") greater than the weight for the part. Accept?");
1178: if (resp == false) {
1179: gradeBox.value = oldpts;
1180: return;
1181: }
1182: }
1183:
1184: for (var i=0; i<radioButton.length; i++) {
1185: radioButton[i].checked=false;
1186: if (pts == i && pts != "") {
1187: radioButton[i].checked=true;
1188: }
1189: }
1190: updateSelect(formname,id);
1191: formname["stores"+id].value = "0";
1192: }
1193:
1194: function writeBox(formname,id,pts) {
1195: var gradeBox = formname["GD_BOX"+id];
1196: if (checkSolved(formname,id) == 'update') {
1197: gradeBox.value = pts;
1198: } else {
1199: var oldpts = formname["oldpts"+id].value;
1200: gradeBox.value = oldpts;
1201: var radioButton = formname["RADVAL"+id];
1202: for (var i=0; i<radioButton.length; i++) {
1203: radioButton[i].checked=false;
1204: if (i == oldpts) {
1205: radioButton[i].checked=true;
1206: }
1207: }
1208: }
1209: formname["stores"+id].value = "0";
1210: updateSelect(formname,id);
1211: return;
1212: }
1213:
1214: function clearRadBox(formname,id) {
1215: if (checkSolved(formname,id) == 'noupdate') {
1216: updateSelect(formname,id);
1217: return;
1218: }
1219: gradeSelect = formname["GD_SEL"+id];
1220: for (var i=0; i<gradeSelect.length; i++) {
1221: if (gradeSelect[i].selected) {
1222: var selectx=i;
1223: }
1224: }
1225: var stores = formname["stores"+id];
1226: if (selectx == stores.value) { return };
1227: var gradeBox = formname["GD_BOX"+id];
1228: gradeBox.value = "";
1229: var radioButton = formname["RADVAL"+id];
1230: for (var i=0; i<radioButton.length; i++) {
1231: radioButton[i].checked=false;
1232: }
1233: stores.value = selectx;
1234: }
1235:
1236: function checkSolved(formname,id) {
1237: if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1238: var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
1239: if (!reply) {return "noupdate";}
1240: formname.overRideScore.value = 'yes';
1241: }
1242: return "update";
1243: }
1244:
1245: function updateSelect(formname,id) {
1246: formname["GD_SEL"+id][0].selected = true;
1247: return;
1248: }
1249:
1250: //=========== Check that a point is assigned for all the parts ============
1251: function checksubmit(formname,val,total,parttot) {
1252: formname.gradeOpt.value = val;
1253: if (val == "Save & Next") {
1254: for (i=0;i<=total;i++) {
1255: for (j=0;j<parttot;j++) {
1256: var partid = formname["partid"+i+"_"+j].value;
1257: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1258: var points = formname["GD_BOX"+i+"_"+partid].value;
1259: if (points == "") {
1260: var name = formname["name"+i].value;
1261: var studentID = (name != '' ? name : formname["unamedom"+i].value);
1262: var resp = confirm("You did not assign a score for "+studentID+
1263: ", part "+partid+". Continue?");
1264: if (resp == false) {
1265: formname["GD_BOX"+i+"_"+partid].focus();
1266: return false;
1267: }
1268: }
1269: }
1270:
1271: }
1272: }
1273:
1274: }
1275: if (val == "Grade Student") {
1276: formname.showgrading.value = "yes";
1277: if (formname.Status.value == "") {
1278: formname.Status.value = "Active";
1279: }
1280: formname.studentNo.value = total;
1281: }
1282: formname.submit();
1283: }
1284:
1285: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
1286: function checkSubmitPage(formname,total) {
1287: noscore = new Array(100);
1288: var ptr = 0;
1289: for (i=1;i<total;i++) {
1290: var partid = formname["q_"+i].value;
1291: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1292: var points = formname["GD_BOX"+i+"_"+partid].value;
1293: var status = formname["solved"+i+"_"+partid].value;
1294: if (points == "" && status != "correct_by_student") {
1295: noscore[ptr] = i;
1296: ptr++;
1297: }
1298: }
1299: }
1300: if (ptr != 0) {
1301: var sense = ptr == 1 ? ": " : "s: ";
1302: var prolist = "";
1303: if (ptr == 1) {
1304: prolist = noscore[0];
1305: } else {
1306: var i = 0;
1307: while (i < ptr-1) {
1308: prolist += noscore[i]+", ";
1309: i++;
1310: }
1311: prolist += "and "+noscore[i];
1312: }
1313: var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
1314: if (resp == false) {
1315: return false;
1316: }
1317: }
1318:
1319: formname.submit();
1320: }
1321: </script>
1322: SUBJAVASCRIPT
1323: }
1324:
1325: #--- javascript for essay type problem --
1326: sub sub_page_kw_js {
1327: my $request = shift;
1328: my $iconpath = $request->dir_config('lonIconsURL');
1329: &commonJSfunctions($request);
1330:
1331: my $inner_js_msg_central=<<INNERJS;
1332: <script text="text/javascript">
1333: function checkInput() {
1334: opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
1335: var nmsg = opener.document.SCORE.savemsgN.value;
1336: var usrctr = document.msgcenter.usrctr.value;
1337: var newval = opener.document.SCORE["newmsg"+usrctr];
1338: newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
1339:
1340: var msgchk = "";
1341: if (document.msgcenter.subchk.checked) {
1342: msgchk = "msgsub,";
1343: }
1344: var includemsg = 0;
1345: for (var i=1; i<=nmsg; i++) {
1346: var opnmsg = opener.document.SCORE["savemsg"+i];
1347: var frmmsg = document.msgcenter["msg"+i];
1348: opnmsg.value = opener.checkEntities(frmmsg.value);
1349: var showflg = opener.document.SCORE["shownOnce"+i];
1350: showflg.value = "1";
1351: var chkbox = document.msgcenter["msgn"+i];
1352: if (chkbox.checked) {
1353: msgchk += "savemsg"+i+",";
1354: includemsg = 1;
1355: }
1356: }
1357: if (document.msgcenter.newmsgchk.checked) {
1358: msgchk += "newmsg"+usrctr;
1359: includemsg = 1;
1360: }
1361: imgformname = opener.document.SCORE["mailicon"+usrctr];
1362: imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
1363: var includemsg = opener.document.SCORE["includemsg"+usrctr];
1364: includemsg.value = msgchk;
1365:
1366: self.close()
1367:
1368: }
1369: </script>
1370: INNERJS
1371:
1372: my $inner_js_highlight_central=<<INNERJS;
1373: <script type="text/javascript">
1374: function updateChoice(flag) {
1375: opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
1376: opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
1377: opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
1378: opener.document.SCORE.refresh.value = "on";
1379: if (opener.document.SCORE.keywords.value!=""){
1380: opener.document.SCORE.submit();
1381: }
1382: self.close()
1383: }
1384: </script>
1385: INNERJS
1386:
1387: my $start_page_msg_central =
1388: &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
1389: {'js_ready' => 1,
1390: 'only_body' => 1,
1391: 'bgcolor' =>'#FFFFFF',});
1392: my $end_page_msg_central =
1393: &Apache::loncommon::end_page({'js_ready' => 1});
1394:
1395:
1396: my $start_page_highlight_central =
1397: &Apache::loncommon::start_page('Highlight Central',
1398: $inner_js_highlight_central,
1399: {'js_ready' => 1,
1400: 'only_body' => 1,
1401: 'bgcolor' =>'#FFFFFF',});
1402: my $end_page_highlight_central =
1403: &Apache::loncommon::end_page({'js_ready' => 1});
1404:
1405: my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1406: $docopen=~s/^document\.//;
1407: $request->print(<<SUBJAVASCRIPT);
1408: <script type="text/javascript" language="javascript">
1409:
1410: //===================== Show list of keywords ====================
1411: function keywords(formname) {
1412: var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1413: if (nret==null) return;
1414: formname.keywords.value = nret;
1415:
1416: if (formname.keywords.value != "") {
1417: formname.refresh.value = "on";
1418: formname.submit();
1419: }
1420: return;
1421: }
1422:
1423: //===================== Script to view submitted by ==================
1424: function viewSubmitter(submitter) {
1425: document.SCORE.refresh.value = "on";
1426: document.SCORE.NCT.value = "1";
1427: document.SCORE.unamedom0.value = submitter;
1428: document.SCORE.submit();
1429: return;
1430: }
1431:
1432: //===================== Script to add keyword(s) ==================
1433: function getSel() {
1434: if (document.getSelection) txt = document.getSelection();
1435: else if (document.selection) txt = document.selection.createRange().text;
1436: else return;
1437: var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
1438: if (cleantxt=="") {
1439: alert("Please select a word or group of words from document and then click this link.");
1440: return;
1441: }
1442: var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
1443: if (nret==null) return;
1444: document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1445: if (document.SCORE.keywords.value != "") {
1446: document.SCORE.refresh.value = "on";
1447: document.SCORE.submit();
1448: }
1449: return;
1450: }
1451:
1452: //====================== Script for composing message ==============
1453: // preload images
1454: img1 = new Image();
1455: img1.src = "$iconpath/mailbkgrd.gif";
1456: img2 = new Image();
1457: img2.src = "$iconpath/mailto.gif";
1458:
1459: function msgCenter(msgform,usrctr,fullname) {
1460: var Nmsg = msgform.savemsgN.value;
1461: savedMsgHeader(Nmsg,usrctr,fullname);
1462: var subject = msgform.msgsub.value;
1463: var msgchk = document.SCORE["includemsg"+usrctr].value;
1464: re = /msgsub/;
1465: var shwsel = "";
1466: if (re.test(msgchk)) { shwsel = "checked" }
1467: subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
1468: displaySubject(checkEntities(subject),shwsel);
1469: for (var i=1; i<=Nmsg; i++) {
1470: var testmsg = "savemsg"+i+",";
1471: re = new RegExp(testmsg,"g");
1472: shwsel = "";
1473: if (re.test(msgchk)) { shwsel = "checked" }
1474: var message = document.SCORE["savemsg"+i].value;
1475: message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1476: displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
1477: //any < is already converted to <, etc. However, only once!!
1478: }
1479: newmsg = document.SCORE["newmsg"+usrctr].value;
1480: shwsel = "";
1481: re = /newmsg/;
1482: if (re.test(msgchk)) { shwsel = "checked" }
1483: newMsg(newmsg,shwsel);
1484: msgTail();
1485: return;
1486: }
1487:
1488: function checkEntities(strx) {
1489: if (strx.length == 0) return strx;
1490: var orgStr = ["&", "<", ">", '"'];
1491: var newStr = ["&", "<", ">", """];
1492: var counter = 0;
1493: while (counter < 4) {
1494: strx = strReplace(strx,orgStr[counter],newStr[counter]);
1495: counter++;
1496: }
1497: return strx;
1498: }
1499:
1500: function strReplace(strx, orgStr, newStr) {
1501: return strx.split(orgStr).join(newStr);
1502: }
1503:
1504: function savedMsgHeader(Nmsg,usrctr,fullname) {
1505: var height = 70*Nmsg+250;
1506: var scrollbar = "no";
1507: if (height > 600) {
1508: height = 600;
1509: scrollbar = "yes";
1510: }
1511: var xpos = (screen.width-600)/2;
1512: xpos = (xpos < 0) ? '0' : xpos;
1513: var ypos = (screen.height-height)/2-30;
1514: ypos = (ypos < 0) ? '0' : ypos;
1515:
1516: pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1517: pWin.focus();
1518: pDoc = pWin.document;
1519: pDoc.$docopen;
1520: pDoc.write('$start_page_msg_central');
1521:
1522: pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
1523: pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1524: pDoc.write("<h3><span class=\\"LC_info\\"> Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
1525:
1526: pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
1527: pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
1528: pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
1529: }
1530: function displaySubject(msg,shwsel) {
1531: pDoc = pWin.document;
1532: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1533: pDoc.write("<td>Subject<\\/td>");
1534: pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1535: pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1536: }
1537:
1538: function displaySavedMsg(ctr,msg,shwsel) {
1539: pDoc = pWin.document;
1540: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1541: pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
1542: pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1543: pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1544: }
1545:
1546: function newMsg(newmsg,shwsel) {
1547: pDoc = pWin.document;
1548: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1549: pDoc.write("<td align=\\"center\\">New<\\/td>");
1550: pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1551: pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1552: }
1553:
1554: function msgTail() {
1555: pDoc = pWin.document;
1556: pDoc.write("<\\/table>");
1557: pDoc.write("<\\/td><\\/tr><\\/table> ");
1558: pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\"> ");
1559: pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1560: pDoc.write("<\\/form>");
1561: pDoc.write('$end_page_msg_central');
1562: pDoc.close();
1563: }
1564:
1565: //====================== Script for keyword highlight options ==============
1566: function kwhighlight() {
1567: var kwclr = document.SCORE.kwclr.value;
1568: var kwsize = document.SCORE.kwsize.value;
1569: var kwstyle = document.SCORE.kwstyle.value;
1570: var redsel = "";
1571: var grnsel = "";
1572: var blusel = "";
1573: if (kwclr=="red") {var redsel="checked"};
1574: if (kwclr=="green") {var grnsel="checked"};
1575: if (kwclr=="blue") {var blusel="checked"};
1576: var sznsel = "";
1577: var sz1sel = "";
1578: var sz2sel = "";
1579: if (kwsize=="0") {var sznsel="checked"};
1580: if (kwsize=="+1") {var sz1sel="checked"};
1581: if (kwsize=="+2") {var sz2sel="checked"};
1582: var synsel = "";
1583: var syisel = "";
1584: var sybsel = "";
1585: if (kwstyle=="") {var synsel="checked"};
1586: if (kwstyle=="<i>") {var syisel="checked"};
1587: if (kwstyle=="<b>") {var sybsel="checked"};
1588: highlightCentral();
1589: highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
1590: highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
1591: highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
1592: highlightend();
1593: return;
1594: }
1595:
1596: function highlightCentral() {
1597: // if (window.hwdWin) window.hwdWin.close();
1598: var xpos = (screen.width-400)/2;
1599: xpos = (xpos < 0) ? '0' : xpos;
1600: var ypos = (screen.height-330)/2-30;
1601: ypos = (ypos < 0) ? '0' : ypos;
1602:
1603: hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1604: hwdWin.focus();
1605: var hDoc = hwdWin.document;
1606: hDoc.$docopen;
1607: hDoc.write('$start_page_highlight_central');
1608: hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1609: hDoc.write("<h3><span class=\\"LC_info\\"> Keyword Highlight Options<\\/span><\\/h3><br /><br />");
1610:
1611: hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
1612: hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
1613: hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
1614: }
1615:
1616: function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) {
1617: var hDoc = hwdWin.document;
1618: hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1619: hDoc.write("<td align=\\"left\\">");
1620: hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+"> "+clrtxt+"<\\/td>");
1621: hDoc.write("<td align=\\"left\\">");
1622: hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+"> "+sztxt+"<\\/td>");
1623: hDoc.write("<td align=\\"left\\">");
1624: hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+"> "+sytxt+"<\\/td>");
1625: hDoc.write("<\\/tr>");
1626: }
1627:
1628: function highlightend() {
1629: var hDoc = hwdWin.document;
1630: hDoc.write("<\\/table>");
1631: hDoc.write("<\\/td><\\/tr><\\/table> ");
1632: hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\"> ");
1633: hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1634: hDoc.write("<\\/form>");
1635: hDoc.write('$end_page_highlight_central');
1636: hDoc.close();
1637: }
1638:
1639: </script>
1640: SUBJAVASCRIPT
1641: }
1642:
1643: sub get_increment {
1644: my $increment = $env{'form.increment'};
1645: if ($increment != 1 && $increment != .5 && $increment != .25 &&
1646: $increment != .1) {
1647: $increment = 1;
1648: }
1649: return $increment;
1650: }
1651:
1652: #--- displays the grading box, used in essay type problem and grading by page/sequence
1653: sub gradeBox {
1654: my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1655: my $checkIcon = '<img alt="'.&mt('Check Mark').
1656: '" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1657: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1658: my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)')
1659: : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1660: $wgt = ($wgt > 0 ? $wgt : '1');
1661: my $score = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1662: '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1663: my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1664: my $display_part= &get_display_part($partid,$symb);
1665: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
1666: [$partid]);
1667: my $aggtries = $$record{'resource.'.$partid.'.tries'};
1668: if ($last_resets{$partid}) {
1669: $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
1670: }
1671: $result.='<table border="0"><tr>';
1672: my $ctr = 0;
1673: my $thisweight = 0;
1674: my $increment = &get_increment();
1675:
1676: my $radio.='<table border="0"><tr>'."\n"; # display radio buttons in a nice table 10 across
1677: while ($thisweight<=$wgt) {
1678: $radio.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1679: 'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1680: $thisweight.')" value="'.$thisweight.'" '.
1681: ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1682: $radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1683: $thisweight += $increment;
1684: $ctr++;
1685: }
1686: $radio.='</tr></table>';
1687:
1688: my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1689: ($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1690: 'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1691: $wgt.')" /></td>'."\n";
1692: $line.='<td>/'.$wgt.' '.$wgtmsg.
1693: ($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? ' '.$checkIcon : '').
1694: ' </td><td>'."\n";
1695: $line.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
1696: 'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1697: if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1698: $line.='<option></option>'.
1699: '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1700: } else {
1701: $line.='<option selected="selected"></option>'.
1702: '<option value="excused" >'.&mt('excused').'</option>';
1703: }
1704: $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
1705:
1706:
1707: $result .=
1708: &mt('<td><b>Part:</b></td><td>[_1]</td><td><b>Points:</b></td><td>[_2]</td><td>or</td><td>[_3]</td>',$display_part,$radio,$line);
1709:
1710:
1711: $result.='</tr></table>'."\n";
1712: $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
1713: '<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
1714: '<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1715: $$record{'resource.'.$partid.'.solved'}.'" />'."\n".
1716: '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
1717: $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
1718: '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
1719: $aggtries.'" />'."\n";
1720: $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
1721: return $result;
1722: }
1723:
1724: sub handback_box {
1725: my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
1726: my ($partlist,$handgrade,$responseType) = &response_type($symb);
1727: my (@respids);
1728: my @part_response_id = &flatten_responseType($responseType);
1729: foreach my $part_response_id (@part_response_id) {
1730: my ($part,$resp) = @{ $part_response_id };
1731: if ($part eq $partid) {
1732: push(@respids,$resp);
1733: }
1734: }
1735: my $result;
1736: foreach my $respid (@respids) {
1737: my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
1738: my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
1739: next if (!@$files);
1740: my $file_counter = 1;
1741: foreach my $file (@$files) {
1742: if ($file =~ /\/portfolio\//) {
1743: my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1744: my ($name,$version,$ext) = &file_name_version_ext($file_disp);
1745: $file_disp = "$name.$ext";
1746: $file = $file_path.$file_disp;
1747: $result.=&mt('Return commented version of [_1] to student.',
1748: '<span class="LC_filename">'.$file_disp.'</span>');
1749: $result.='<input type="file" name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1750: $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1751: $result.='('.&mt('File will be uploaded when you click on Save & Next below.').')<br />';
1752: $file_counter++;
1753: }
1754: }
1755: }
1756: return $result;
1757: }
1758:
1759: sub show_problem {
1760: my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1761: my $rendered;
1762: my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1763: &Apache::lonxml::remember_problem_counter();
1764: if ($mode eq 'both' or $mode eq 'text') {
1765: $rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1766: $env{'request.course.id'},
1767: undef,\%form);
1768: }
1769: if ($removeform) {
1770: $rendered=~s|<form(.*?)>||g;
1771: $rendered=~s|</form>||g;
1772: $rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1773: }
1774: my $companswer;
1775: if ($mode eq 'both' or $mode eq 'answer') {
1776: &Apache::lonxml::restore_problem_counter();
1777: $companswer=
1778: &Apache::loncommon::get_student_answers($symb,$uname,$udom,
1779: $env{'request.course.id'},
1780: %form);
1781: }
1782: if ($removeform) {
1783: $companswer=~s|<form(.*?)>||g;
1784: $companswer=~s|</form>||g;
1785: $companswer=~s|name="submit"|name="would_have_been_submit"|g;
1786: }
1787: $rendered=
1788: '<div class="LC_grade_show_problem_header">'.
1789: &mt('View of the problem').
1790: '</div><div class="LC_grade_show_problem_problem">'.
1791: $rendered.
1792: '</div>';
1793: $companswer=
1794: '<div class="LC_grade_show_problem_header">'.
1795: &mt('Correct answer').
1796: '</div><div class="LC_grade_show_problem_problem">'.
1797: $companswer.
1798: '</div>';
1799: my $result;
1800: if ($mode eq 'both') {
1801: $result=$rendered.$companswer;
1802: } elsif ($mode eq 'text') {
1803: $result=$rendered;
1804: } elsif ($mode eq 'answer') {
1805: $result=$companswer;
1806: }
1807: $result='<div class="LC_grade_show_problem">'.$result.'</div>';
1808: return $result;
1809: }
1810:
1811: sub files_exist {
1812: my ($r, $symb) = @_;
1813: my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1814:
1815: foreach my $student (@students) {
1816: my ($uname,$udom,$fullname) = split(/:/,$student);
1817: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
1818: $udom,$uname);
1819: my ($string,$timestamp)= &get_last_submission(\%record);
1820: foreach my $submission (@$string) {
1821: my ($partid,$respid) =
1822: ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1823: my $files=&get_submitted_files($udom,$uname,$partid,$respid,
1824: \%record);
1825: return 1 if (@$files);
1826: }
1827: }
1828: return 0;
1829: }
1830:
1831: sub download_all_link {
1832: my ($r,$symb) = @_;
1833: my $all_students =
1834: join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
1835:
1836: my $parts =
1837: join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
1838:
1839: my $identifier = &Apache::loncommon::get_cgi_id();
1840: &Apache::lonnet::appenv('cgi.'.$identifier.'.students' => $all_students,
1841: 'cgi.'.$identifier.'.symb' => $symb,
1842: 'cgi.'.$identifier.'.parts' => $parts,);
1843: $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
1844: &mt('Download All Submitted Documents').'</a>');
1845: return
1846: }
1847:
1848: sub build_section_inputs {
1849: my $section_inputs;
1850: if ($env{'form.section'} eq '') {
1851: $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
1852: } else {
1853: my @sections = &Apache::loncommon::get_env_multiple('form.section');
1854: foreach my $section (@sections) {
1855: $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
1856: }
1857: }
1858: return $section_inputs;
1859: }
1860:
1861: # --------------------------- show submissions of a student, option to grade
1862: sub submission {
1863: my ($request,$counter,$total) = @_;
1864: my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
1865: $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
1866: my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
1867: $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1868: my $symb = &get_symb($request);
1869: if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1870:
1871: if (!&canview($usec)) {
1872: $request->print('<span class="LC_warning">Unable to view requested student.('.
1873: $uname.':'.$udom.' in section '.$usec.' in course id '.
1874: $env{'request.course.id'}.')</span>');
1875: $request->print(&show_grading_menu_form($symb));
1876: return;
1877: }
1878:
1879: if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
1880: if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
1881: if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
1882: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1883: my $checkIcon = '<img alt="'.&mt('Check Mark').
1884: '" src="'.$request->dir_config('lonIconsURL').
1885: '/check.gif" height="16" border="0" />';
1886:
1887: my %old_essays;
1888: # header info
1889: if ($counter == 0) {
1890: &sub_page_js($request);
1891: &sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
1892: $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ?
1893: &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1894: if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1895: &download_all_link($request, $symb);
1896: }
1897: $request->print('<h3> <span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
1898: '<h4> '.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
1899:
1900: # option to display problem, only once else it cause problems
1901: # with the form later since the problem has a form.
1902: if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1903: my $mode;
1904: if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1905: $mode='both';
1906: } elsif ($env{'form.vProb'} eq 'yes') {
1907: $mode='text';
1908: } elsif ($env{'form.vAns'} eq 'yes') {
1909: $mode='answer';
1910: }
1911: &Apache::lonxml::clear_problem_counter();
1912: $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1913: }
1914:
1915: # kwclr is the only variable that is guaranteed to be non blank
1916: # if this subroutine has been called once.
1917: my %keyhash = ();
1918: if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1919: %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1920: $env{'course.'.$env{'request.course.id'}.'.domain'},
1921: $env{'course.'.$env{'request.course.id'}.'.num'});
1922:
1923: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1924: $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
1925: $env{'form.kwclr'} = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
1926: $env{'form.kwsize'} = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
1927: $env{'form.kwstyle'} = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
1928: $env{'form.msgsub'} = $keyhash{$symb.'_subject'} ne '' ?
1929: $keyhash{$symb.'_subject'} : $env{'form.probTitle'};
1930: $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1931: }
1932: my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1933: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1934: $request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1935: '<input type="hidden" name="command" value="handgrade" />'."\n".
1936: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1937: '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
1938: '<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1939: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
1940: '<input type="hidden" name="refresh" value="off" />'."\n".
1941: '<input type="hidden" name="studentNo" value="" />'."\n".
1942: '<input type="hidden" name="gradeOpt" value="" />'."\n".
1943: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1944: '<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
1945: '<input type="hidden" name="vProb" value="'.$env{'form.vProb'}.'" />'."\n".
1946: '<input type="hidden" name="vAns" value="'.$env{'form.vAns'}.'" />'."\n".
1947: '<input type="hidden" name="lastSub" value="'.$env{'form.lastSub'}.'" />'."\n".
1948: &build_section_inputs().
1949: '<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1950: '<input type="hidden" name="handgrade" value="'.$env{'form.handgrade'}.'" />'."\n".
1951: '<input type="hidden" name="NCT"'.
1952: ' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1953: if ($env{'form.handgrade'} eq 'yes') {
1954: $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
1955: '<input type="hidden" name="kwclr" value="'.$env{'form.kwclr'}.'" />'."\n".
1956: '<input type="hidden" name="kwsize" value="'.$env{'form.kwsize'}.'" />'."\n".
1957: '<input type="hidden" name="kwstyle" value="'.$env{'form.kwstyle'}.'" />'."\n".
1958: '<input type="hidden" name="msgsub" value="'.$env{'form.msgsub'}.'" />'."\n".
1959: '<input type="hidden" name="shownSub" value="0" />'."\n".
1960: '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1961: foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
1962: $request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
1963: }
1964: }
1965:
1966: my ($cts,$prnmsg) = (1,'');
1967: while ($cts <= $env{'form.savemsgN'}) {
1968: $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1969: (!exists($keyhash{$symb.'_savemsg'.$cts}) ?
1970: &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1971: &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1972: '" />'."\n".
1973: '<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1974: $cts++;
1975: }
1976: $request->print($prnmsg);
1977:
1978: if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1979: #
1980: # Print out the keyword options line
1981: #
1982: $request->print(<<KEYWORDS);
1983: <b>Keyword Options:</b>
1984: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>
1985: <a href="#" onMouseDown="javascript:getSel(); return false"
1986: CLASS="page">Paste Selection to List</a>
1987: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1988: KEYWORDS
1989: #
1990: # Load the other essays for similarity check
1991: #
1992: my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1993: my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1994: $apath=&escape($apath);
1995: $apath=~s/\W/\_/gs;
1996: %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1997: }
1998: }
1999:
2000: # This is where output for one specific student would start
2001: my $add_class = ($counter%2) ? 'LC_grade_show_user_odd_row' : '';
2002: $request->print("\n\n".
2003: '<div class="LC_grade_show_user '.$add_class.'">'.
2004: '<div class="LC_grade_user_name">'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</div>'.
2005: '<div class="LC_grade_show_user_body">'."\n");
2006:
2007: if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
2008: my $mode;
2009: if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
2010: $mode='both';
2011: } elsif ($env{'form.vProb'} eq 'all' ) {
2012: $mode='text';
2013: } elsif ($env{'form.vAns'} eq 'all') {
2014: $mode='answer';
2015: }
2016: &Apache::lonxml::clear_problem_counter();
2017: $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
2018: }
2019:
2020: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
2021: my ($partlist,$handgrade,$responseType) = &response_type($symb);
2022:
2023: # Display student info
2024: $request->print(($counter == 0 ? '' : '<br />'));
2025: my $result='<div class="LC_grade_submissions">';
2026:
2027: $result.='<div class="LC_grade_submissions_header">';
2028: $result.= &mt('Submissions');
2029: $result.='<input type="hidden" name="name'.$counter.
2030: '" value="'.$env{'form.fullname'}.'" />'."\n";
2031: if ($env{'form.handgrade'} eq 'no') {
2032: $result.='<span class="LC_grade_check_note">'.
2033: &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)."</span>\n";
2034:
2035: }
2036:
2037:
2038:
2039: # If any part of the problem is an essay-response (handgraded), then check for collaborators
2040: my $fullname;
2041: my $col_fullnames = [];
2042: if ($env{'form.handgrade'} eq 'yes') {
2043: (my $sub_result,$fullname,$col_fullnames)=
2044: &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
2045: $counter);
2046: $result.=$sub_result;
2047: }
2048: $request->print($result."\n");
2049: $request->print('</div>'."\n");
2050: # print student answer/submission
2051: # Options are (1) Handgaded submission only
2052: # (2) Last submission, includes submission that is not handgraded
2053: # (for multi-response type part)
2054: # (3) Last submission plus the parts info
2055: # (4) The whole record for this student
2056: if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
2057: my ($string,$timestamp)= &get_last_submission(\%record);
2058:
2059: my $lastsubonly;
2060:
2061: if ($$timestamp eq '') {
2062: $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>';
2063: } else {
2064: $lastsubonly = '<div class="LC_grade_submissions_body"> <b>Date Submitted:</b> '.$$timestamp."\n";
2065:
2066: my %seenparts;
2067: my @part_response_id = &flatten_responseType($responseType);
2068: foreach my $part (@part_response_id) {
2069: next if ($env{'form.lastSub'} eq 'hdgrade'
2070: && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
2071:
2072: my ($partid,$respid) = @{ $part };
2073: my $display_part=&get_display_part($partid,$symb);
2074: if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
2075: if (exists($seenparts{$partid})) { next; }
2076: $seenparts{$partid}=1;
2077: my $submitby='<b>Part:</b> '.$display_part.
2078: ' <b>Collaborative submission by:</b> '.
2079: '<a href="javascript:viewSubmitter(\''.
2080: $env{"form.$uname:$udom:$partid:submitted_by"}.
2081: '\');" target="_self">'.
2082: $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
2083: $request->print($submitby);
2084: next;
2085: }
2086: my $responsetype = $responseType->{$partid}->{$respid};
2087: if (!exists($record{"resource.$partid.$respid.submission"})) {
2088: $lastsubonly.="\n".'<div class="LC_grade_submission_part"><b>Part:</b> '.
2089: $display_part.' <span class="LC_internal_info">( ID '.$respid.
2090: ' )</span> '.
2091: '<span class="LC_warning">'.&mt('Nothing submitted - no attempts').'</span><br /><br /></div>';
2092: next;
2093: }
2094: foreach my $submission (@$string) {
2095: my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
2096: if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
2097: my ($ressub,$subval) = split(/:/,$submission,2);
2098: # Similarity check
2099: my $similar='';
2100: if($env{'form.checkPlag'}){
2101: my ($oname,$odom,$ocrsid,$oessay,$osim)=
2102: &most_similar($uname,$udom,$subval,\%old_essays);
2103: if ($osim) {
2104: $osim=int($osim*100.0);
2105: my %old_course_desc =
2106: &Apache::lonnet::coursedescription($ocrsid,
2107: {'one_time' => 1});
2108:
2109: $similar="<hr /><h3><span class=\"LC_warning\">".
2110: &mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
2111: $osim,
2112: &Apache::loncommon::plainname($oname,$odom),
2113: $oname,$odom,
2114: $old_course_desc{'description'},
2115: $old_course_desc{'num'},
2116: $old_course_desc{'domain'}).
2117: '</span></h3><blockquote><i>'.
2118: &keywords_highlight($oessay).
2119: '</i></blockquote><hr />';
2120: }
2121: }
2122: my $order=&get_order($partid,$respid,$symb,$uname,$udom);
2123: if ($env{'form.lastSub'} eq 'lastonly' ||
2124: ($env{'form.lastSub'} eq 'hdgrade' &&
2125: $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
2126: my $display_part=&get_display_part($partid,$symb);
2127: $lastsubonly.='<div class="LC_grade_submission_part"><b>Part:</b> '.
2128: $display_part.' <span class="LC_internal_info">( ID '.$respid.
2129: ' )</span> ';
2130: my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
2131: if (@$files) {
2132: $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain virusses').'</span><br />';
2133: my $file_counter = 0;
2134: foreach my $file (@$files) {
2135: $file_counter++;
2136: &Apache::lonnet::allowuploaded('/adm/grades',$file);
2137: $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
2138: }
2139: $lastsubonly.='<br />';
2140: }
2141: $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
2142: &cleanRecord($subval,$responsetype,$symb,$partid,
2143: $respid,\%record,$order);
2144: if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
2145: $lastsubonly.='</div>';
2146: }
2147: }
2148: }
2149: $lastsubonly.='</div>'."\n";
2150: }
2151: $request->print($lastsubonly);
2152: } elsif ($env{'form.lastSub'} eq 'datesub') {
2153: my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
2154: $request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
2155: } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
2156: $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
2157: $env{'request.course.id'},
2158: $last,'.submission',
2159: 'Apache::grades::keywords_highlight'));
2160: }
2161:
2162: $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
2163: .$udom.'" />'."\n");
2164: # return if view submission with no grading option
2165: if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
2166: my $toGrade.='<input type="button" value="Grade Student" '.
2167: 'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
2168: .$counter.'\');" target="_self" /> '."\n" if (&canmodify($usec));
2169: $toGrade.='</div>'."\n";
2170: if (($env{'form.command'} eq 'submission') ||
2171: ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
2172: $toGrade.='</form>'.&show_grading_menu_form($symb);
2173: }
2174: $request->print($toGrade);
2175: return;
2176: } else {
2177: $request->print('</div>'."\n");
2178: }
2179:
2180: # essay grading message center
2181: if ($env{'form.handgrade'} eq 'yes') {
2182: my $result='<div class="LC_grade_message_center">';
2183:
2184: $result.='<div class="LC_grade_message_center_header">'.
2185: &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
2186: my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
2187: my $msgfor = $givenn.' '.$lastname;
2188: if (scalar(@$col_fullnames) > 0) {
2189: my $lastone = pop(@$col_fullnames);
2190: $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
2191: }
2192: $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
2193: $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
2194: '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
2195: $result.=' <a href="javascript:msgCenter(document.SCORE,'.$counter.
2196: ',\''.$msgfor.'\');" target="_self">'.
2197: &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
2198: &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
2199: '<img src="'.$request->dir_config('lonIconsURL').
2200: '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
2201: '<br /> ('.
2202: &mt('Message will be sent when you click on Save & Next below.').")\n";
2203: $result.='</div></div>';
2204: $request->print($result);
2205: }
2206:
2207: my %seen = ();
2208: my @partlist;
2209: my @gradePartRespid;
2210: my @part_response_id = &flatten_responseType($responseType);
2211: $request->print('<div class="LC_grade_assign">'.
2212:
2213: '<div class="LC_grade_assign_header">'.
2214: &mt('Assign Grades').'</div>'.
2215: '<div class="LC_grade_assign_body">');
2216: foreach my $part_response_id (@part_response_id) {
2217: my ($partid,$respid) = @{ $part_response_id };
2218: my $part_resp = join('_',@{ $part_response_id });
2219: next if ($seen{$partid} > 0);
2220: $seen{$partid}++;
2221: next if ($$handgrade{$part_resp} ne 'yes'
2222: && $env{'form.lastSub'} eq 'hdgrade');
2223: push @partlist,$partid;
2224: push @gradePartRespid,$partid.'.'.$respid;
2225: $request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
2226: }
2227: $request->print('</div></div>');
2228:
2229: $request->print('<div class="LC_grade_info_links">');
2230: if ($perm{'vgr'}) {
2231: $request->print(
2232: &Apache::loncommon::track_student_link(&mt('View recent activity'),
2233: $uname,$udom,'check'));
2234: }
2235: if ($perm{'opa'}) {
2236: $request->print(
2237: &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
2238: $uname,$udom,$symb,'check'));
2239: }
2240: $request->print('</div>');
2241:
2242: $result='<input type="hidden" name="partlist'.$counter.
2243: '" value="'.(join ":",@partlist).'" />'."\n";
2244: $result.='<input type="hidden" name="gradePartRespid'.
2245: '" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
2246: my $ctr = 0;
2247: while ($ctr < scalar(@partlist)) {
2248: $result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
2249: $partlist[$ctr].'" />'."\n";
2250: $ctr++;
2251: }
2252: $request->print($result.''."\n");
2253:
2254: # Done with printing info for one student
2255:
2256: $request->print('</div>');#LC_grade_show_user_body
2257: $request->print('</div>');#LC_grade_show_user
2258:
2259:
2260: # print end of form
2261: if ($counter == $total) {
2262: my $endform='<table border="0"><tr><td>'."\n";
2263: $endform.='<input type="button" value="'.&mt('Save & Next').'" '.
2264: 'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
2265: $total.','.scalar(@partlist).');" target="_self" /> '."\n";
2266: my $ntstu ='<select name="NTSTU">'.
2267: '<option>1</option><option>2</option>'.
2268: '<option>3</option><option>5</option>'.
2269: '<option>7</option><option>10</option></select>'."\n";
2270: my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
2271: $ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
2272: $endform.=&mt('[_1]student(s)',$ntstu);
2273: $endform.=' <input type="button" value="'.&mt('Previous').'" '.
2274: 'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> '."\n".
2275: '<input type="button" value="'.&mt('Next').'" '.
2276: 'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> ';
2277: $endform.=&mt('(Next and Previous (student) do not save the scores.)')."\n" ;
2278: $endform.="<input type='hidden' value='".&get_increment().
2279: "' name='increment' />";
2280: $endform.='</td></tr></table></form>';
2281: $endform.=&show_grading_menu_form($symb);
2282: $request->print($endform);
2283: }
2284: return '';
2285: }
2286:
2287: sub check_collaborators {
2288: my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
2289: my ($result,@col_fullnames);
2290: my ($classlist,undef,$fullname) = &getclasslist('all','0');
2291: foreach my $part (keys(%$handgrade)) {
2292: my $ncol = &Apache::lonnet::EXT('resource.'.$part.
2293: '.maxcollaborators',
2294: $symb,$udom,$uname);
2295: next if ($ncol <= 0);
2296: $part =~ s/\_/\./g;
2297: next if ($record->{'resource.'.$part.'.collaborators'} eq '');
2298: my (@good_collaborators, @bad_collaborators);
2299: foreach my $possible_collaborator
2300: (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) {
2301: $possible_collaborator =~ s/[\$\^\(\)]//g;
2302: next if ($possible_collaborator eq '');
2303: my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
2304: $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
2305: next if ($co_name eq $uname && $co_dom eq $udom);
2306: # Doing this grep allows 'fuzzy' specification
2307: my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i,
2308: keys(%$classlist));
2309: if (! scalar(@matches)) {
2310: push(@bad_collaborators, $possible_collaborator);
2311: } else {
2312: push(@good_collaborators, @matches);
2313: }
2314: }
2315: if (scalar(@good_collaborators) != 0) {
2316: $result.='<br />'.&mt('Collaborators: ');
2317: foreach my $name (@good_collaborators) {
2318: my ($lastname,$givenn) = split(/,/,$$fullname{$name});
2319: push(@col_fullnames, $givenn.' '.$lastname);
2320: $result.=$fullname->{$name}.' ';
2321: }
2322: $result.='<br />'."\n";
2323: my ($part)=split(/\./,$part);
2324: $result.='<input type="hidden" name="collaborator'.$counter.
2325: '" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
2326: "\n";
2327: }
2328: if (scalar(@bad_collaborators) > 0) {
2329: $result.='<div class="LC_warning">';
2330: $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
2331: $result .= '</div>';
2332: }
2333: if (scalar(@bad_collaborators > $ncol)) {
2334: $result .= '<div class="LC_warning">';
2335: $result .= &mt('This student has submitted too many '.
2336: 'collaborators. Maximum is [_1].',$ncol);
2337: $result .= '</div>';
2338: }
2339: }
2340: return ($result,$fullname,\@col_fullnames);
2341: }
2342:
2343: #--- Retrieve the last submission for all the parts
2344: sub get_last_submission {
2345: my ($returnhash)=@_;
2346: my (@string,$timestamp);
2347: if ($$returnhash{'version'}) {
2348: my %lasthash=();
2349: my ($version);
2350: for ($version=1;$version<=$$returnhash{'version'};$version++) {
2351: foreach my $key (sort(split(/\:/,
2352: $$returnhash{$version.':keys'}))) {
2353: $lasthash{$key}=$$returnhash{$version.':'.$key};
2354: $timestamp =
2355: scalar(localtime($$returnhash{$version.':timestamp'}));
2356: }
2357: }
2358: foreach my $key (keys(%lasthash)) {
2359: next if ($key !~ /\.submission$/);
2360:
2361: my ($partid,$foo) = split(/submission$/,$key);
2362: my $draft = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
2363: '<span class="LC_warning">Draft Copy</span> ' : '';
2364: push(@string, join(':', $key, $draft.$lasthash{$key}));
2365: }
2366: }
2367: if (!@string) {
2368: $string[0] =
2369: '<span class="LC_warning">Nothing submitted - no attempts.</span>';
2370: }
2371: return (\@string,\$timestamp);
2372: }
2373:
2374: #--- High light keywords, with style choosen by user.
2375: sub keywords_highlight {
2376: my $string = shift;
2377: my $size = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
2378: my $styleon = $env{'form.kwstyle'} eq '' ? '' : $env{'form.kwstyle'};
2379: (my $styleoff = $styleon) =~ s/\</\<\//;
2380: my @keylist = split(/[,\s+]/,$env{'form.keywords'});
2381: foreach my $keyword (@keylist) {
2382: $string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
2383: }
2384: return $string;
2385: }
2386:
2387: #--- Called from submission routine
2388: sub processHandGrade {
2389: my ($request) = shift;
2390: my $symb = &get_symb($request);
2391: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
2392: my $button = $env{'form.gradeOpt'};
2393: my $ngrade = $env{'form.NCT'};
2394: my $ntstu = $env{'form.NTSTU'};
2395: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2396: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2397:
2398: if ($button eq 'Save & Next') {
2399: my $ctr = 0;
2400: while ($ctr < $ngrade) {
2401: my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
2402: my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
2403: if ($errorflag eq 'no_score') {
2404: $ctr++;
2405: next;
2406: }
2407: if ($errorflag eq 'not_allowed') {
2408: $request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
2409: $ctr++;
2410: next;
2411: }
2412: my $includemsg = $env{'form.includemsg'.$ctr};
2413: my ($subject,$message,$msgstatus) = ('','','');
2414: my $restitle = &Apache::lonnet::gettitle($symb);
2415: my ($feedurl,$showsymb) =
2416: &get_feedurl_and_symb($symb,$uname,$udom);
2417: my $messagetail;
2418: if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
2419: $subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
2420: unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
2421: $subject.=' ['.$restitle.']';
2422: my (@msgnum) = split(/,/,$includemsg);
2423: foreach (@msgnum) {
2424: $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
2425: }
2426: $message =&Apache::lonfeedback::clear_out_html($message);
2427: if ($env{'form.withgrades'.$ctr}) {
2428: $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
2429: $messagetail = " for <a href=\"".
2430: $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
2431: }
2432: $msgstatus =
2433: &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
2434: $message.$messagetail,
2435: undef,$feedurl,undef,
2436: undef,undef,$showsymb,
2437: $restitle);
2438: $request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
2439: $msgstatus);
2440: }
2441: if ($env{'form.collaborator'.$ctr}) {
2442: my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
2443: foreach my $collabstr (@collabstrs) {
2444: my ($part,@collaborators) = split(/:/,$collabstr);
2445: foreach my $collaborator (@collaborators) {
2446: my ($errorflag,$pts,$wgt) =
2447: &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
2448: $env{'form.unamedom'.$ctr},$part);
2449: if ($errorflag eq 'not_allowed') {
2450: $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
2451: next;
2452: } elsif ($message ne '') {
2453: my ($baseurl,$showsymb) =
2454: &get_feedurl_and_symb($symb,$collaborator,
2455: $udom);
2456: if ($env{'form.withgrades'.$ctr}) {
2457: $messagetail = " for <a href=\"".
2458: $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
2459: }
2460: $msgstatus =
2461: &Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
2462: }
2463: }
2464: }
2465: }
2466: $ctr++;
2467: }
2468: }
2469:
2470: if ($env{'form.handgrade'} eq 'yes') {
2471: # Keywords sorted in alphabatical order
2472: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
2473: my %keyhash = ();
2474: $env{'form.keywords'} =~ s/,\s{0,}|\s+/ /g;
2475: $env{'form.keywords'} =~ s/^\s+|\s+$//;
2476: my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
2477: $env{'form.keywords'} = join(' ',@keywords);
2478: $keyhash{$symb.'_keywords'} = $env{'form.keywords'};
2479: $keyhash{$symb.'_subject'} = $env{'form.msgsub'};
2480: $keyhash{$loginuser.'_kwclr'} = $env{'form.kwclr'};
2481: $keyhash{$loginuser.'_kwsize'} = $env{'form.kwsize'};
2482: $keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
2483:
2484: # message center - Order of message gets changed. Blank line is eliminated.
2485: # New messages are saved in env for the next student.
2486: # All messages are saved in nohist_handgrade.db
2487: my ($ctr,$idx) = (1,1);
2488: while ($ctr <= $env{'form.savemsgN'}) {
2489: if ($env{'form.savemsg'.$ctr} ne '') {
2490: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
2491: $idx++;
2492: }
2493: $ctr++;
2494: }
2495: $ctr = 0;
2496: while ($ctr < $ngrade) {
2497: if ($env{'form.newmsg'.$ctr} ne '') {
2498: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2499: $env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2500: $idx++;
2501: }
2502: $ctr++;
2503: }
2504: $env{'form.savemsgN'} = --$idx;
2505: $keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
2506: my $putresult = &Apache::lonnet::put
2507: ('nohist_handgrade',\%keyhash,$cdom,$cnum);
2508: }
2509: # Called by Save & Refresh from Highlight Attribute Window
2510: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
2511: if ($env{'form.refresh'} eq 'on') {
2512: my ($ctr,$total) = (0,0);
2513: while ($ctr < $ngrade) {
2514: $total++ if $env{'form.unamedom'.$ctr} ne '';
2515: $ctr++;
2516: }
2517: $env{'form.NTSTU'}=$ngrade;
2518: $ctr = 0;
2519: while ($ctr < $total) {
2520: my $processUser = $env{'form.unamedom'.$ctr};
2521: ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
2522: $env{'form.fullname'} = $$fullname{$processUser};
2523: &submission($request,$ctr,$total-1);
2524: $ctr++;
2525: }
2526: return '';
2527: }
2528:
2529: # Go directly to grade student - from submission or link from chart page
2530: if ($button eq 'Grade Student') {
2531: (undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
2532: my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
2533: ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
2534: $env{'form.fullname'} = $$fullname{$processUser};
2535: &submission($request,0,0);
2536: return '';
2537: }
2538:
2539: # Get the next/previous one or group of students
2540: my $firststu = $env{'form.unamedom0'};
2541: my $laststu = $env{'form.unamedom'.($ngrade-1)};
2542: my $ctr = 2;
2543: while ($laststu eq '') {
2544: $laststu = $env{'form.unamedom'.($ngrade-$ctr)};
2545: $ctr++;
2546: $laststu = $firststu if ($ctr > $ngrade);
2547: }
2548:
2549: my (@parsedlist,@nextlist);
2550: my ($nextflg) = 0;
2551: foreach (sort
2552: {
2553: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
2554: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
2555: }
2556: return $a cmp $b;
2557: } (keys(%$fullname))) {
2558: if ($nextflg == 1 && $button =~ /Next$/) {
2559: push @parsedlist,$_;
2560: }
2561: $nextflg = 1 if ($_ eq $laststu);
2562: if ($button eq 'Previous') {
2563: last if ($_ eq $firststu);
2564: push @parsedlist,$_;
2565: }
2566: }
2567: $ctr = 0;
2568: @parsedlist = reverse @parsedlist if ($button eq 'Previous');
2569: my ($partlist) = &response_type($symb);
2570: foreach my $student (@parsedlist) {
2571: my $submitonly=$env{'form.submitonly'};
2572: my ($uname,$udom) = split(/:/,$student);
2573:
2574: if ($submitonly eq 'queued') {
2575: my %queue_status =
2576: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
2577: $udom,$uname);
2578: next if (!defined($queue_status{'gradingqueue'}));
2579: }
2580:
2581: if ($submitonly =~ /^(yes|graded|incorrect)$/) {
2582: # my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
2583: my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
2584: my $submitted = 0;
2585: my $ungraded = 0;
2586: my $incorrect = 0;
2587: foreach (keys(%status)) {
2588: $submitted = 1 if ($status{$_} ne 'nothing');
2589: $ungraded = 1 if ($status{$_} =~ /^ungraded/);
2590: $incorrect = 1 if ($status{$_} =~ /^incorrect/);
2591: my ($foo,$partid,$foo1) = split(/\./,$_);
2592: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
2593: $submitted = 0;
2594: }
2595: }
2596: next if (!$submitted && ($submitonly eq 'yes' ||
2597: $submitonly eq 'incorrect' ||
2598: $submitonly eq 'graded'));
2599: next if (!$ungraded && ($submitonly eq 'graded'));
2600: next if (!$incorrect && $submitonly eq 'incorrect');
2601: }
2602: push @nextlist,$student if ($ctr < $ntstu);
2603: last if ($ctr == $ntstu);
2604: $ctr++;
2605: }
2606:
2607: $ctr = 0;
2608: my $total = scalar(@nextlist)-1;
2609:
2610: foreach (sort @nextlist) {
2611: my ($uname,$udom,$submitter) = split(/:/);
2612: $env{'form.student'} = $uname;
2613: $env{'form.userdom'} = $udom;
2614: $env{'form.fullname'} = $$fullname{$_};
2615: &submission($request,$ctr,$total);
2616: $ctr++;
2617: }
2618: if ($total < 0) {
2619: my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
2620: $the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
2621: $the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
2622: $the_end.=&show_grading_menu_form($symb);
2623: $request->print($the_end);
2624: }
2625: return '';
2626: }
2627:
2628: #---- Save the score and award for each student, if changed
2629: sub saveHandGrade {
2630: my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
2631: my @version_parts;
2632: my $usec = &Apache::lonnet::getsection($domain,$stuname,
2633: $env{'request.course.id'});
2634: if (!&canmodify($usec)) { return('not_allowed'); }
2635: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
2636: my @parts_graded;
2637: my %newrecord = ();
2638: my ($pts,$wgt) = ('','');
2639: my %aggregate = ();
2640: my $aggregateflag = 0;
2641: my @parts = split(/:/,$env{'form.partlist'.$newflg});
2642: foreach my $new_part (@parts) {
2643: #collaborator ($submi may vary for different parts
2644: if ($submitter && $new_part ne $part) { next; }
2645: my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
2646: if ($dropMenu eq 'excused') {
2647: if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
2648: $newrecord{'resource.'.$new_part.'.solved'} = 'excused';
2649: if (exists($record{'resource.'.$new_part.'.awarded'})) {
2650: $newrecord{'resource.'.$new_part.'.awarded'} = '';
2651: }
2652: $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
2653: }
2654: } elsif ($dropMenu eq 'reset status'
2655: && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
2656: foreach my $key (keys (%record)) {
2657: if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
2658: }
2659: $newrecord{'resource.'.$new_part.'.regrader'}=
2660: "$env{'user.name'}:$env{'user.domain'}";
2661: my $totaltries = $record{'resource.'.$part.'.tries'};
2662:
2663: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
2664: [$new_part]);
2665: my $aggtries =$totaltries;
2666: if ($last_resets{$new_part}) {
2667: $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
2668: $new_part);
2669: }
2670:
2671: my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
2672: if ($aggtries > 0) {
2673: &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
2674: $aggregateflag = 1;
2675: }
2676: } elsif ($dropMenu eq '') {
2677: $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ?
2678: $env{'form.GD_BOX'.$newflg.'_'.$new_part} :
2679: $env{'form.RADVAL'.$newflg.'_'.$new_part});
2680: if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
2681: next;
2682: }
2683: $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 :
2684: $env{'form.WGT'.$newflg.'_'.$new_part};
2685: my $partial= $pts/$wgt;
2686: if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
2687: #do not update score for part if not changed.
2688: &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
2689: next;
2690: } else {
2691: push @parts_graded, $new_part;
2692: }
2693: if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
2694: $newrecord{'resource.'.$new_part.'.awarded'} = $partial;
2695: }
2696: my $reckey = 'resource.'.$new_part.'.solved';
2697: if ($partial == 0) {
2698: if ($record{$reckey} ne 'incorrect_by_override') {
2699: $newrecord{$reckey} = 'incorrect_by_override';
2700: }
2701: } else {
2702: if ($record{$reckey} ne 'correct_by_override') {
2703: $newrecord{$reckey} = 'correct_by_override';
2704: }
2705: }
2706: if ($submitter &&
2707: ($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
2708: $newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
2709: }
2710: $newrecord{'resource.'.$new_part.'.regrader'}=
2711: "$env{'user.name'}:$env{'user.domain'}";
2712: }
2713: # unless problem has been graded, set flag to version the submitted files
2714: unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/ ||
2715: $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
2716: $dropMenu eq 'reset status')
2717: {
2718: push (@version_parts,$new_part);
2719: }
2720: }
2721: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2722: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2723:
2724: if (%newrecord) {
2725: if (@version_parts) {
2726: my @changed_keys = &version_portfiles(\%record, \@parts_graded,
2727: $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
2728: @newrecord{@changed_keys} = @record{@changed_keys};
2729: foreach my $new_part (@version_parts) {
2730: &handback_files($request,$symb,$stuname,$domain,$newflg,
2731: $new_part,\%newrecord);
2732: }
2733: }
2734: &Apache::lonnet::cstore(\%newrecord,$symb,
2735: $env{'request.course.id'},$domain,$stuname);
2736: &check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
2737: $cdom,$cnum,$domain,$stuname);
2738: }
2739: if ($aggregateflag) {
2740: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
2741: $cdom,$cnum);
2742: }
2743: return ('',$pts,$wgt);
2744: }
2745:
2746: sub check_and_remove_from_queue {
2747: my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
2748: my @ungraded_parts;
2749: foreach my $part (@{$parts}) {
2750: if ( $record->{ 'resource.'.$part.'.awarded'} eq ''
2751: && $record->{ 'resource.'.$part.'.solved' } ne 'excused'
2752: && $newrecord->{'resource.'.$part.'.awarded'} eq ''
2753: && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
2754: ) {
2755: push(@ungraded_parts, $part);
2756: }
2757: }
2758: if ( !@ungraded_parts ) {
2759: &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
2760: $cnum,$domain,$stuname);
2761: }
2762: }
2763:
2764: sub handback_files {
2765: my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
2766: my $portfolio_root = &propath($domain,$stuname).'/userfiles/portfolio';
2767: my ($partlist,$handgrade,$responseType) = &response_type($symb);
2768:
2769: my @part_response_id = &flatten_responseType($responseType);
2770: foreach my $part_response_id (@part_response_id) {
2771: my ($part_id,$resp_id) = @{ $part_response_id };
2772: my $part_resp = join('_',@{ $part_response_id });
2773: if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
2774: # if multiple files are uploaded names will be 'returndoc2','returndoc3'
2775: my $file_counter = 1;
2776: my $file_msg;
2777: while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
2778: my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
2779: my ($directory,$answer_file) =
2780: ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
2781: my ($answer_name,$answer_ver,$answer_ext) =
2782: &file_name_version_ext($answer_file);
2783: my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
2784: my @dir_list = &Apache::lonnet::dirlist($portfolio_path,$domain,$stuname,$portfolio_root);
2785: my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
2786: # fix file name
2787: my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
2788: my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
2789: $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
2790: $save_file_name);
2791: if ($result !~ m|^/uploaded/|) {
2792: $request->print('<span class="LC_error">An error occurred ('.$result.
2793: ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</span><br />');
2794: } else {
2795: # mark the file as read only
2796: my @files = ($save_file_name);
2797: my @what = ($symb,$env{'request.course.id'},'handback');
2798: &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
2799: if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
2800: $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
2801: }
2802: $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
2803: $file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
2804:
2805: }
2806: $request->print("<br />".$fname." will be the uploaded file name");
2807: $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
2808: $file_counter++;
2809: }
2810: my $subject = "File Handed Back by Instructor ";
2811: my $message = "A file has been returned that was originally submitted in reponse to: <br />";
2812: $message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
2813: $message .= ' The returned file(s) are named: '. $file_msg;
2814: $message .= " and can be found in your portfolio space.";
2815: my ($feedurl,$showsymb) =
2816: &get_feedurl_and_symb($symb,$domain,$stuname);
2817: my $restitle = &Apache::lonnet::gettitle($symb);
2818: my $msgstatus =
2819: &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
2820: ' (File Returned) ['.$restitle.']',$message,undef,
2821: $feedurl,undef,undef,undef,$showsymb,$restitle);
2822: }
2823: }
2824: return;
2825: }
2826:
2827: sub get_feedurl_and_symb {
2828: my ($symb,$uname,$udom) = @_;
2829: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
2830: $url = &Apache::lonnet::clutter($url);
2831: my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
2832: $symb,$udom,$uname);
2833: if ($encrypturl =~ /^yes$/i) {
2834: &Apache::lonenc::encrypted(\$url,1);
2835: &Apache::lonenc::encrypted(\$symb,1);
2836: }
2837: return ($url,$symb);
2838: }
2839:
2840: sub get_submitted_files {
2841: my ($udom,$uname,$partid,$respid,$record) = @_;
2842: my @files;
2843: if ($$record{"resource.$partid.$respid.portfiles"}) {
2844: my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
2845: foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
2846: push(@files,$file_url.$file);
2847: }
2848: }
2849: if ($$record{"resource.$partid.$respid.uploadedurl"}) {
2850: push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
2851: }
2852: return (\@files);
2853: }
2854:
2855: # ----------- Provides number of tries since last reset.
2856: sub get_num_tries {
2857: my ($record,$last_reset,$part) = @_;
2858: my $timestamp = '';
2859: my $num_tries = 0;
2860: if ($$record{'version'}) {
2861: for (my $version=$$record{'version'};$version>=1;$version--) {
2862: if (exists($$record{$version.':resource.'.$part.'.solved'})) {
2863: $timestamp = $$record{$version.':timestamp'};
2864: if ($timestamp > $last_reset) {
2865: $num_tries ++;
2866: } else {
2867: last;
2868: }
2869: }
2870: }
2871: }
2872: return $num_tries;
2873: }
2874:
2875: # ----------- Determine decrements required in aggregate totals
2876: sub decrement_aggs {
2877: my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
2878: my %decrement = (
2879: attempts => 0,
2880: users => 0,
2881: correct => 0
2882: );
2883: $decrement{'attempts'} = $aggtries;
2884: if ($solvedstatus =~ /^correct/) {
2885: $decrement{'correct'} = 1;
2886: }
2887: if ($aggtries == $totaltries) {
2888: $decrement{'users'} = 1;
2889: }
2890: foreach my $type (keys (%decrement)) {
2891: $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
2892: }
2893: return;
2894: }
2895:
2896: # ----------- Determine timestamps for last reset of aggregate totals for parts
2897: sub get_last_resets {
2898: my ($symb,$courseid,$partids) =@_;
2899: my %last_resets;
2900: my $cdom = $env{'course.'.$courseid.'.domain'};
2901: my $cname = $env{'course.'.$courseid.'.num'};
2902: my @keys;
2903: foreach my $part (@{$partids}) {
2904: push(@keys,"$symb\0$part\0resettime");
2905: }
2906: my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
2907: $cdom,$cname);
2908: foreach my $part (@{$partids}) {
2909: $last_resets{$part}=$results{"$symb\0$part\0resettime"};
2910: }
2911: return %last_resets;
2912: }
2913:
2914: # ----------- Handles creating versions for portfolio files as answers
2915: sub version_portfiles {
2916: my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
2917: my $version_parts = join('|',@$v_flag);
2918: my @returned_keys;
2919: my $parts = join('|', @$parts_graded);
2920: my $portfolio_root = &propath($domain,$stu_name).
2921: '/userfiles/portfolio';
2922: foreach my $key (keys(%$record)) {
2923: my $new_portfiles;
2924: if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
2925: my @versioned_portfiles;
2926: my @portfiles = split(/\s*,\s*/,$$record{$key});
2927: foreach my $file (@portfiles) {
2928: &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
2929: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
2930: my ($answer_name,$answer_ver,$answer_ext) =
2931: &file_name_version_ext($answer_file);
2932: my @dir_list = &Apache::lonnet::dirlist($directory,$domain,$stu_name,$portfolio_root);
2933: my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
2934: my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
2935: if ($new_answer ne 'problem getting file') {
2936: push(@versioned_portfiles, $directory.$new_answer);
2937: &Apache::lonnet::mark_as_readonly($domain,$stu_name,
2938: [$directory.$new_answer],
2939: [$symb,$env{'request.course.id'},'graded']);
2940: }
2941: }
2942: $$record{$key} = join(',',@versioned_portfiles);
2943: push(@returned_keys,$key);
2944: }
2945: }
2946: return (@returned_keys);
2947: }
2948:
2949: sub get_next_version {
2950: my ($answer_name, $answer_ext, $dir_list) = @_;
2951: my $version;
2952: foreach my $row (@$dir_list) {
2953: my ($file) = split(/\&/,$row,2);
2954: my ($file_name,$file_version,$file_ext) =
2955: &file_name_version_ext($file);
2956: if (($file_name eq $answer_name) &&
2957: ($file_ext eq $answer_ext)) {
2958: # gets here if filename and extension match, regardless of version
2959: if ($file_version ne '') {
2960: # a versioned file is found so save it for later
2961: if ($file_version > $version) {
2962: $version = $file_version;
2963: }
2964: }
2965: }
2966: }
2967: $version ++;
2968: return($version);
2969: }
2970:
2971: sub version_selected_portfile {
2972: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
2973: my ($answer_name,$answer_ver,$answer_ext) =
2974: &file_name_version_ext($file_name);
2975: my $new_answer;
2976: $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
2977: if($env{'form.copy'} eq '-1') {
2978: $new_answer = 'problem getting file';
2979: } else {
2980: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
2981: my $copy_result = &Apache::lonnet::finishuserfileupload(
2982: $stu_name,$domain,'copy',
2983: '/portfolio'.$directory.$new_answer);
2984: }
2985: return ($new_answer);
2986: }
2987:
2988: sub file_name_version_ext {
2989: my ($file)=@_;
2990: my @file_parts = split(/\./, $file);
2991: my ($name,$version,$ext);
2992: if (@file_parts > 1) {
2993: $ext=pop(@file_parts);
2994: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
2995: $version=pop(@file_parts);
2996: }
2997: $name=join('.',@file_parts);
2998: } else {
2999: $name=join('.',@file_parts);
3000: }
3001: return($name,$version,$ext);
3002: }
3003:
3004: #--------------------------------------------------------------------------------------
3005: #
3006: #-------------------------- Next few routines handles grading by section or whole class
3007: #
3008: #--- Javascript to handle grading by section or whole class
3009: sub viewgrades_js {
3010: my ($request) = shift;
3011:
3012: $request->print(<<VIEWJAVASCRIPT);
3013: <script type="text/javascript" language="javascript">
3014: function writePoint(partid,weight,point) {
3015: var radioButton = document.classgrade["RADVAL_"+partid];
3016: var textbox = document.classgrade["TEXTVAL_"+partid];
3017: if (point == "textval") {
3018: point = document.classgrade["TEXTVAL_"+partid].value;
3019: if (isNaN(point) || parseFloat(point) < 0) {
3020: alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
3021: var resetbox = false;
3022: for (var i=0; i<radioButton.length; i++) {
3023: if (radioButton[i].checked) {
3024: textbox.value = i;
3025: resetbox = true;
3026: }
3027: }
3028: if (!resetbox) {
3029: textbox.value = "";
3030: }
3031: return;
3032: }
3033: if (parseFloat(point) > parseFloat(weight)) {
3034: var resp = confirm("You entered a value ("+parseFloat(point)+
3035: ") greater than the weight for the part. Accept?");
3036: if (resp == false) {
3037: textbox.value = "";
3038: return;
3039: }
3040: }
3041: for (var i=0; i<radioButton.length; i++) {
3042: radioButton[i].checked=false;
3043: if (parseFloat(point) == i) {
3044: radioButton[i].checked=true;
3045: }
3046: }
3047:
3048: } else {
3049: textbox.value = parseFloat(point);
3050: }
3051: for (i=0;i<document.classgrade.total.value;i++) {
3052: var user = document.classgrade["ctr"+i].value;
3053: user = user.replace(new RegExp(':', 'g'),"_");
3054: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3055: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3056: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3057: if (saveval != "correct") {
3058: scorename.value = point;
3059: if (selname[0].selected != true) {
3060: selname[0].selected = true;
3061: }
3062: }
3063: }
3064: document.classgrade["SELVAL_"+partid][0].selected = true;
3065: }
3066:
3067: function writeRadText(partid,weight) {
3068: var selval = document.classgrade["SELVAL_"+partid];
3069: var radioButton = document.classgrade["RADVAL_"+partid];
3070: var override = document.classgrade["FORCE_"+partid].checked;
3071: var textbox = document.classgrade["TEXTVAL_"+partid];
3072: if (selval[1].selected || selval[2].selected) {
3073: for (var i=0; i<radioButton.length; i++) {
3074: radioButton[i].checked=false;
3075:
3076: }
3077: textbox.value = "";
3078:
3079: for (i=0;i<document.classgrade.total.value;i++) {
3080: var user = document.classgrade["ctr"+i].value;
3081: user = user.replace(new RegExp(':', 'g'),"_");
3082: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3083: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3084: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3085: if ((saveval != "correct") || override) {
3086: scorename.value = "";
3087: if (selval[1].selected) {
3088: selname[1].selected = true;
3089: } else {
3090: selname[2].selected = true;
3091: if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value))
3092: {document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
3093: }
3094: }
3095: }
3096: } else {
3097: for (i=0;i<document.classgrade.total.value;i++) {
3098: var user = document.classgrade["ctr"+i].value;
3099: user = user.replace(new RegExp(':', 'g'),"_");
3100: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3101: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3102: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3103: if ((saveval != "correct") || override) {
3104: scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
3105: selname[0].selected = true;
3106: }
3107: }
3108: }
3109: }
3110:
3111: function changeSelect(partid,user) {
3112: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
3113: var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
3114: var point = textbox.value;
3115: var weight = document.classgrade["weight_"+partid].value;
3116:
3117: if (isNaN(point) || parseFloat(point) < 0) {
3118: alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
3119: textbox.value = "";
3120: return;
3121: }
3122: if (parseFloat(point) > parseFloat(weight)) {
3123: var resp = confirm("You entered a value ("+parseFloat(point)+
3124: ") greater than the weight of the part. Accept?");
3125: if (resp == false) {
3126: textbox.value = "";
3127: return;
3128: }
3129: }
3130: selval[0].selected = true;
3131: }
3132:
3133: function changeOneScore(partid,user) {
3134: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
3135: if (selval[1].selected || selval[2].selected) {
3136: document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
3137: if (selval[2].selected) {
3138: document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
3139: }
3140: }
3141: }
3142:
3143: function resetEntry(numpart) {
3144: for (ctpart=0;ctpart<numpart;ctpart++) {
3145: var partid = document.classgrade["partid_"+ctpart].value;
3146: var radioButton = document.classgrade["RADVAL_"+partid];
3147: var textbox = document.classgrade["TEXTVAL_"+partid];
3148: var selval = document.classgrade["SELVAL_"+partid];
3149: for (var i=0; i<radioButton.length; i++) {
3150: radioButton[i].checked=false;
3151:
3152: }
3153: textbox.value = "";
3154: selval[0].selected = true;
3155:
3156: for (i=0;i<document.classgrade.total.value;i++) {
3157: var user = document.classgrade["ctr"+i].value;
3158: user = user.replace(new RegExp(':', 'g'),"_");
3159: var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3160: resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
3161: var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
3162: resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
3163: var saveselval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3164: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3165: if (saveselval == "excused") {
3166: if (selname[1].selected == false) { selname[1].selected = true;}
3167: } else {
3168: if (selname[0].selected == false) {selname[0].selected = true};
3169: }
3170: }
3171: }
3172: }
3173:
3174: </script>
3175: VIEWJAVASCRIPT
3176: }
3177:
3178: #--- show scores for a section or whole class w/ option to change/update a score
3179: sub viewgrades {
3180: my ($request) = shift;
3181: &viewgrades_js($request);
3182:
3183: my ($symb) = &get_symb($request);
3184: #need to make sure we have the correct data for later EXT calls,
3185: #thus invalidate the cache
3186: &Apache::lonnet::devalidatecourseresdata(
3187: $env{'course.'.$env{'request.course.id'}.'.num'},
3188: $env{'course.'.$env{'request.course.id'}.'.domain'});
3189: &Apache::lonnet::clear_EXT_cache_status();
3190:
3191: my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
3192: $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
3193:
3194: #view individual student submission form - called using Javascript viewOneStudent
3195: $result.=&jscriptNform($symb);
3196:
3197: #beginning of class grading form
3198: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
3199: $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
3200: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
3201: '<input type="hidden" name="command" value="editgrades" />'."\n".
3202: &build_section_inputs().
3203: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
3204: '<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
3205: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
3206:
3207: my $sectionClass;
3208: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3209: if ($env{'form.section'} eq 'all') {
3210: $sectionClass='Class';
3211: } elsif ($env{'form.section'} eq 'none') {
3212: $sectionClass='Students in no Section';
3213: } else {
3214: $sectionClass='Students in Section(s) [_1]';
3215: }
3216: $result.=
3217: '<h3>'.
3218: &mt("Assign Common Grade To $sectionClass",$section_display).'</h3>';
3219: $result.= &Apache::loncommon::start_data_table();
3220: #radio buttons/text box for assigning points for a section or class.
3221: #handles different parts of a problem
3222: my ($partlist,$handgrade,$responseType) = &response_type($symb);
3223: my %weight = ();
3224: my $ctsparts = 0;
3225: my %seen = ();
3226: my @part_response_id = &flatten_responseType($responseType);
3227: foreach my $part_response_id (@part_response_id) {
3228: my ($partid,$respid) = @{ $part_response_id };
3229: my $part_resp = join('_',@{ $part_response_id });
3230: next if $seen{$partid};
3231: $seen{$partid}++;
3232: my $handgrade=$$handgrade{$part_resp};
3233: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
3234: $weight{$partid} = $wgt eq '' ? '1' : $wgt;
3235:
3236: my $display_part=&get_display_part($partid,$symb);
3237: my $radio.='<table border="0"><tr>';
3238: my $ctr = 0;
3239: while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
3240: $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
3241: 'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
3242: ','.$ctr.')" />'.$ctr."</label></td>\n";
3243: $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
3244: $ctr++;
3245: }
3246: $radio.='</tr></table>';
3247: my $line = '<input type="text" name="TEXTVAL_'.
3248: $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
3249: $partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
3250: $weight{$partid}.' (problem weight)</td>'."\n";
3251: $line.= '<td><select name="SELVAL_'.$partid.'"'.
3252: 'onChange="javascript:writeRadText(\''.$partid.'\','.
3253: $weight{$partid}.')"> '.
3254: '<option selected="selected"> </option>'.
3255: '<option value="excused">'.&mt('excused').'</option>'.
3256: '<option value="reset status">'.&mt('reset status').'</option>'.
3257: '</select></td>'.
3258: '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
3259: $line.='<input type="hidden" name="partid_'.
3260: $ctsparts.'" value="'.$partid.'" />'."\n";
3261: $line.='<input type="hidden" name="weight_'.
3262: $partid.'" value="'.$weight{$partid}.'" />'."\n";
3263:
3264: $result.=
3265: &Apache::loncommon::start_data_table_row()."\n".
3266: &mt('<td><b>Part:</b></td><td>[_1]</td><td><b>Points:</b></td><td>[_2]</td><td>or</td><td>[_3]</td>',$display_part,$radio,$line).
3267: &Apache::loncommon::end_data_table_row()."\n";
3268: $ctsparts++;
3269: }
3270: $result.=&Apache::loncommon::end_data_table()."\n".
3271: '<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
3272: $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
3273: 'onClick="javascript:resetEntry('.$ctsparts.');" />';
3274:
3275: #table listing all the students in a section/class
3276: #header of table
3277: $result.= '<h3>'.&mt('Assign Grade to Specific Students in '.$sectionClass,
3278: $section_display).'</h3>';
3279: $result.= &Apache::loncommon::start_data_table().
3280: &Apache::loncommon::start_data_table_header_row().
3281: '<th>'.&mt('No.').'</th>'.
3282: '<th>'.&nameUserString('header')."</th>\n";
3283: my (@parts) = sort(&getpartlist($symb));
3284: my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
3285: my @partids = ();
3286: foreach my $part (@parts) {
3287: my $display=&Apache::lonnet::metadata($url,$part.'.display');
3288: $display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
3289: if (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
3290: my ($partid) = &split_part_type($part);
3291: push(@partids, $partid);
3292: my $display_part=&get_display_part($partid,$symb);
3293: if ($display =~ /^Partial Credit Factor/) {
3294: $result.='<th>'.
3295: &mt('Score Part: [_1]<br /> (weight = [_2])',
3296: $display_part,$weight{$partid}).'</th>'."\n";
3297: next;
3298:
3299: } else {
3300: if ($display =~ /Problem Status/) {
3301: my $grade_status_mt = &mt('Grade Status');
3302: $display =~ s{Problem Status}{$grade_status_mt<br />};
3303: }
3304: my $part_mt = &mt('Part:');
3305: $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
3306: }
3307:
3308: $result.='<th>'.$display.'</th>'."\n";
3309: }
3310: $result.=&Apache::loncommon::end_data_table_header_row();
3311:
3312: my %last_resets =
3313: &get_last_resets($symb,$env{'request.course.id'},\@partids);
3314:
3315: #get info for each student
3316: #list all the students - with points and grade status
3317: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
3318: my $ctr = 0;
3319: foreach (sort
3320: {
3321: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
3322: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
3323: }
3324: return $a cmp $b;
3325: } (keys(%$fullname))) {
3326: $ctr++;
3327: $result.=&viewstudentgrade($symb,$env{'request.course.id'},
3328: $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
3329: }
3330: $result.=&Apache::loncommon::end_data_table();
3331: $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
3332: $result.='<input type="button" value="'.&mt('Save').'" '.
3333: 'onClick="javascript:submit();" target="_self" /></form>'."\n";
3334: if (scalar(%$fullname) eq 0) {
3335: my $colspan=3+scalar(@parts);
3336: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3337: my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
3338: $result='<span class="LC_warning">'.
3339: &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
3340: $section_display, $stu_status).
3341: '</span>';
3342: }
3343: $result.=&show_grading_menu_form($symb);
3344: return $result;
3345: }
3346:
3347: #--- call by previous routine to display each student
3348: sub viewstudentgrade {
3349: my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
3350: my ($uname,$udom) = split(/:/,$student);
3351: my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
3352: my %aggregates = ();
3353: my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
3354: '<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
3355: "\n".$ctr.' </td><td> '.
3356: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
3357: '\');" target="_self">'.$fullname.'</a> '.
3358: '<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
3359: $student=~s/:/_/; # colon doen't work in javascript for names
3360: foreach my $apart (@$parts) {
3361: my ($part,$type) = &split_part_type($apart);
3362: my $score=$record{"resource.$part.$type"};
3363: $result.='<td align="center">';
3364: my ($aggtries,$totaltries);
3365: unless (exists($aggregates{$part})) {
3366: $totaltries = $record{'resource.'.$part.'.tries'};
3367:
3368: $aggtries = $totaltries;
3369: if ($$last_resets{$part}) {
3370: $aggtries = &get_num_tries(\%record,$$last_resets{$part},
3371: $part);
3372: }
3373: $result.='<input type="hidden" name="'.
3374: 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
3375: $result.='<input type="hidden" name="'.
3376: 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
3377: $aggregates{$part} = 1;
3378: }
3379: if ($type eq 'awarded') {
3380: my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
3381: $result.='<input type="hidden" name="'.
3382: 'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
3383: $result.='<input type="text" name="'.
3384: 'GD_'.$student.'_'.$part.'_awarded" '.
3385: 'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
3386: '\')" value="'.$pts.'" size="4" /></td>'."\n";
3387: } elsif ($type eq 'solved') {
3388: my ($status,$foo)=split(/_/,$score,2);
3389: $status = 'nothing' if ($status eq '');
3390: $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
3391: $part.'_solved_s" value="'.$status.'" />'."\n";
3392: $result.=' <select name="'.
3393: 'GD_'.$student.'_'.$part.'_solved" '.
3394: 'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
3395: $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>'
3396: : '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
3397: $result.='<option value="reset status">'.&mt('reset status').'</option>';
3398: $result.="</select> </td>\n";
3399: } else {
3400: $result.='<input type="hidden" name="'.
3401: 'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
3402: "\n";
3403: $result.='<input type="text" name="'.
3404: 'GD_'.$student.'_'.$part.'_'.$type.'" '.
3405: 'value="'.$score.'" size="4" /></td>'."\n";
3406: }
3407: }
3408: $result.=&Apache::loncommon::end_data_table_row();
3409: return $result;
3410: }
3411:
3412: #--- change scores for all the students in a section/class
3413: # record does not get update if unchanged
3414: sub editgrades {
3415: my ($request) = @_;
3416:
3417: my $symb=&get_symb($request);
3418: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3419: my $title='<h2>'.&mt('Current Grade Status').'</h2>';
3420: $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
3421: $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
3422:
3423: my $result= &Apache::loncommon::start_data_table().
3424: &Apache::loncommon::start_data_table_header_row().
3425: '<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
3426: '<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
3427: my %scoreptr = (
3428: 'correct' =>'correct_by_override',
3429: 'incorrect'=>'incorrect_by_override',
3430: 'excused' =>'excused',
3431: 'ungraded' =>'ungraded_attempted',
3432: 'nothing' => '',
3433: );
3434: my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
3435:
3436: my (@partid);
3437: my %weight = ();
3438: my %columns = ();
3439: my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
3440:
3441: my (@parts) = sort(&getpartlist($symb));
3442: my $header;
3443: while ($ctr < $env{'form.totalparts'}) {
3444: my $partid = $env{'form.partid_'.$ctr};
3445: push @partid,$partid;
3446: $weight{$partid} = $env{'form.weight_'.$partid};
3447: $ctr++;
3448: }
3449: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3450: foreach my $partid (@partid) {
3451: $header .= '<th align="center">'.&mt('Old Score').'</th>'.
3452: '<th align="center">'.&mt('New Score').'</th>';
3453: $columns{$partid}=2;
3454: foreach my $stores (@parts) {
3455: my ($part,$type) = &split_part_type($stores);
3456: if ($part !~ m/^\Q$partid\E/) { next;}
3457: if ($type eq 'awarded' || $type eq 'solved') { next; }
3458: my $display=&Apache::lonnet::metadata($url,$stores.'.display');
3459: $display =~ s/\[Part: (\w)+\]//;
3460: $display =~ s/Number of Attempts/Tries/;
3461: $header .= '<th align="center">'.&mt('Old '.$display).'</th>'.
3462: '<th align="center">'.&mt('New '.$display).'</th>';
3463: $columns{$partid}+=2;
3464: }
3465: }
3466: foreach my $partid (@partid) {
3467: my $display_part=&get_display_part($partid,$symb);
3468: $result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
3469: &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
3470: '</th>';
3471:
3472: }
3473: $result .= &Apache::loncommon::end_data_table_header_row().
3474: &Apache::loncommon::start_data_table_header_row().
3475: $header.
3476: &Apache::loncommon::end_data_table_header_row();
3477: my @noupdate;
3478: my ($updateCtr,$noupdateCtr) = (1,1);
3479: for ($i=0; $i<$env{'form.total'}; $i++) {
3480: my $line;
3481: my $user = $env{'form.ctr'.$i};
3482: my ($uname,$udom)=split(/:/,$user);
3483: my %newrecord;
3484: my $updateflag = 0;
3485: $line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
3486: my $usec=$classlist->{"$uname:$udom"}[5];
3487: if (!&canmodify($usec)) {
3488: my $numcols=scalar(@partid)*4+2;
3489: push(@noupdate,
3490: $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
3491: &mt('Not allowed to modify student')."</span></td></tr>");
3492: next;
3493: }
3494: my %aggregate = ();
3495: my $aggregateflag = 0;
3496: $user=~s/:/_/; # colon doen't work in javascript for names
3497: foreach (@partid) {
3498: my $old_aw = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
3499: my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
3500: my $old_part = $old_aw eq '' ? '' : $old_part_pcr;
3501: my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
3502: my $awarded = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
3503: my $pcr = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
3504: my $partial = $awarded eq '' ? '' : $pcr;
3505: my $score;
3506: if ($partial eq '') {
3507: $score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
3508: } elsif ($partial > 0) {
3509: $score = 'correct_by_override';
3510: } elsif ($partial == 0) {
3511: $score = 'incorrect_by_override';
3512: }
3513: my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
3514: $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
3515:
3516: $newrecord{'resource.'.$_.'.regrader'}=
3517: "$env{'user.name'}:$env{'user.domain'}";
3518: if ($dropMenu eq 'reset status' &&
3519: $old_score ne '') { # ignore if no previous attempts => nothing to reset
3520: $newrecord{'resource.'.$_.'.tries'} = '';
3521: $newrecord{'resource.'.$_.'.solved'} = '';
3522: $newrecord{'resource.'.$_.'.award'} = '';
3523: $newrecord{'resource.'.$_.'.awarded'} = '';
3524: $updateflag = 1;
3525: if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
3526: my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
3527: my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
3528: my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
3529: &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
3530: $aggregateflag = 1;
3531: }
3532: } elsif (!($old_part eq $partial && $old_score eq $score)) {
3533: $updateflag = 1;
3534: $newrecord{'resource.'.$_.'.awarded'} = $partial if $partial ne '';
3535: $newrecord{'resource.'.$_.'.solved'} = $score;
3536: $rec_update++;
3537: }
3538:
3539: $line .= '<td align="center">'.$old_aw.' </td>'.
3540: '<td align="center">'.$awarded.
3541: ($score eq 'excused' ? $score : '').' </td>';
3542:
3543:
3544: my $partid=$_;
3545: foreach my $stores (@parts) {
3546: my ($part,$type) = &split_part_type($stores);
3547: if ($part !~ m/^\Q$partid\E/) { next;}
3548: if ($type eq 'awarded' || $type eq 'solved') { next; }
3549: my $old_aw = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
3550: my $awarded = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
3551: if ($awarded ne '' && $awarded ne $old_aw) {
3552: $newrecord{'resource.'.$part.'.'.$type}= $awarded;
3553: $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
3554: $updateflag=1;
3555: }
3556: $line .= '<td align="center">'.$old_aw.' </td>'.
3557: '<td align="center">'.$awarded.' </td>';
3558: }
3559: }
3560: $line.="\n";
3561:
3562: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3563: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3564:
3565: if ($updateflag) {
3566: $count++;
3567: &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
3568: $udom,$uname);
3569:
3570: if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
3571: $cnum,$udom,$uname)) {
3572: # need to figure out if should be in queue.
3573: my %record =
3574: &Apache::lonnet::restore($symb,$env{'request.course.id'},
3575: $udom,$uname);
3576: my $all_graded = 1;
3577: my $none_graded = 1;
3578: foreach my $part (@parts) {
3579: if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
3580: $all_graded = 0;
3581: } else {
3582: $none_graded = 0;
3583: }
3584: }
3585:
3586: if ($all_graded || $none_graded) {
3587: &Apache::bridgetask::remove_from_queue('gradingqueue',
3588: $symb,$cdom,$cnum,
3589: $udom,$uname);
3590: }
3591: }
3592:
3593: $result.=&Apache::loncommon::start_data_table_row().
3594: '<td align="right"> '.$updateCtr.' </td>'.$line.
3595: &Apache::loncommon::end_data_table_row();
3596: $updateCtr++;
3597: } else {
3598: push(@noupdate,
3599: '<td align="right"> '.$noupdateCtr.' </td>'.$line);
3600: $noupdateCtr++;
3601: }
3602: if ($aggregateflag) {
3603: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
3604: $cdom,$cnum);
3605: }
3606: }
3607: if (@noupdate) {
3608: # my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
3609: my $numcols=scalar(@partid)*4+2;
3610: $result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
3611: '<td align="center" colspan="'.$numcols.'">'.
3612: &mt('No Changes Occurred For the Students Below').
3613: '</td>'.
3614: &Apache::loncommon::end_data_table_row();
3615: foreach my $line (@noupdate) {
3616: $result.=
3617: &Apache::loncommon::start_data_table_row().
3618: $line.
3619: &Apache::loncommon::end_data_table_row();
3620: }
3621: }
3622: $result .= &Apache::loncommon::end_data_table().
3623: &show_grading_menu_form($symb);
3624: my $msg = '<p><b>'.
3625: &mt('Number of records updated = [_1] for [quant,_2,student].',
3626: $rec_update,$count).'</b><br />'.
3627: '<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
3628: '</b></p>';
3629: return $title.$msg.$result;
3630: }
3631:
3632: sub split_part_type {
3633: my ($partstr) = @_;
3634: my ($temp,@allparts)=split(/_/,$partstr);
3635: my $type=pop(@allparts);
3636: my $part=join('_',@allparts);
3637: return ($part,$type);
3638: }
3639:
3640: #------------- end of section for handling grading by section/class ---------
3641: #
3642: #----------------------------------------------------------------------------
3643:
3644:
3645: #----------------------------------------------------------------------------
3646: #
3647: #-------------------------- Next few routines handles grading by csv upload
3648: #
3649: #--- Javascript to handle csv upload
3650: sub csvupload_javascript_reverse_associate {
3651: my $error1=&mt('You need to specify the username or ID');
3652: my $error2=&mt('You need to specify at least one grading field');
3653: return(<<ENDPICK);
3654: function verify(vf) {
3655: var foundsomething=0;
3656: var founduname=0;
3657: var foundID=0;
3658: for (i=0;i<=vf.nfields.value;i++) {
3659: tw=eval('vf.f'+i+'.selectedIndex');
3660: if (i==0 && tw!=0) { foundID=1; }
3661: if (i==1 && tw!=0) { founduname=1; }
3662: if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
3663: }
3664: if (founduname==0 && foundID==0) {
3665: alert('$error1');
3666: return;
3667: }
3668: if (foundsomething==0) {
3669: alert('$error2');
3670: return;
3671: }
3672: vf.submit();
3673: }
3674: function flip(vf,tf) {
3675: var nw=eval('vf.f'+tf+'.selectedIndex');
3676: var i;
3677: for (i=0;i<=vf.nfields.value;i++) {
3678: //can not pick the same destination field for both name and domain
3679: if (((i ==0)||(i ==1)) &&
3680: ((tf==0)||(tf==1)) &&
3681: (i!=tf) &&
3682: (eval('vf.f'+i+'.selectedIndex')==nw)) {
3683: eval('vf.f'+i+'.selectedIndex=0;')
3684: }
3685: }
3686: }
3687: ENDPICK
3688: }
3689:
3690: sub csvupload_javascript_forward_associate {
3691: my $error1=&mt('You need to specify the username or ID');
3692: my $error2=&mt('You need to specify at least one grading field');
3693: return(<<ENDPICK);
3694: function verify(vf) {
3695: var foundsomething=0;
3696: var founduname=0;
3697: var foundID=0;
3698: for (i=0;i<=vf.nfields.value;i++) {
3699: tw=eval('vf.f'+i+'.selectedIndex');
3700: if (tw==1) { foundID=1; }
3701: if (tw==2) { founduname=1; }
3702: if (tw>3) { foundsomething=1; }
3703: }
3704: if (founduname==0 && foundID==0) {
3705: alert('$error1');
3706: return;
3707: }
3708: if (foundsomething==0) {
3709: alert('$error2');
3710: return;
3711: }
3712: vf.submit();
3713: }
3714: function flip(vf,tf) {
3715: var nw=eval('vf.f'+tf+'.selectedIndex');
3716: var i;
3717: //can not pick the same destination field twice
3718: for (i=0;i<=vf.nfields.value;i++) {
3719: if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
3720: eval('vf.f'+i+'.selectedIndex=0;')
3721: }
3722: }
3723: }
3724: ENDPICK
3725: }
3726:
3727: sub csvuploadmap_header {
3728: my ($request,$symb,$datatoken,$distotal)= @_;
3729: my $javascript;
3730: if ($env{'form.upfile_associate'} eq 'reverse') {
3731: $javascript=&csvupload_javascript_reverse_associate();
3732: } else {
3733: $javascript=&csvupload_javascript_forward_associate();
3734: }
3735:
3736: my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
3737: my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
3738: my $ignore=&mt('Ignore First Line');
3739: $symb = &Apache::lonenc::check_encrypt($symb);
3740: $request->print(<<ENDPICK);
3741: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3742: <h3><span class="LC_info">Uploading Class Grades</span></h3>
3743: $result
3744: <hr />
3745: <h3>Identify fields</h3>
3746: Total number of records found in file: $distotal <hr />
3747: Enter as many fields as you can. The system will inform you and bring you back
3748: to this page if the data selected is insufficient to run your class.<hr />
3749: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
3750: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
3751: <input type="hidden" name="associate" value="" />
3752: <input type="hidden" name="phase" value="three" />
3753: <input type="hidden" name="datatoken" value="$datatoken" />
3754: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
3755: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
3756: <input type="hidden" name="upfile_associate"
3757: value="$env{'form.upfile_associate'}" />
3758: <input type="hidden" name="symb" value="$symb" />
3759: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
3760: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
3761: <input type="hidden" name="command" value="csvuploadoptions" />
3762: <hr />
3763: <script type="text/javascript" language="Javascript">
3764: $javascript
3765: </script>
3766: ENDPICK
3767: return '';
3768:
3769: }
3770:
3771: sub csvupload_fields {
3772: my ($symb) = @_;
3773: my (@parts) = &getpartlist($symb);
3774: my @fields=(['ID','Student ID'],
3775: ['username','Student Username'],
3776: ['domain','Student Domain']);
3777: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3778: foreach my $part (sort(@parts)) {
3779: my @datum;
3780: my $display=&Apache::lonnet::metadata($url,$part.'.display');
3781: my $name=$part;
3782: if (!$display) { $display = $name; }
3783: @datum=($name,$display);
3784: if ($name=~/^stores_(.*)_awarded/) {
3785: push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
3786: }
3787: push(@fields,\@datum);
3788: }
3789: return (@fields);
3790: }
3791:
3792: sub csvuploadmap_footer {
3793: my ($request,$i,$keyfields) =@_;
3794: $request->print(<<ENDPICK);
3795: </table>
3796: <input type="hidden" name="nfields" value="$i" />
3797: <input type="hidden" name="keyfields" value="$keyfields" />
3798: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
3799: </form>
3800: ENDPICK
3801: }
3802:
3803: sub checkforfile_js {
3804: my $result =<<CSVFORMJS;
3805: <script type="text/javascript" language="javascript">
3806: function checkUpload(formname) {
3807: if (formname.upfile.value == "") {
3808: alert("Please use the browse button to select a file from your local directory.");
3809: return false;
3810: }
3811: formname.submit();
3812: }
3813: </script>
3814: CSVFORMJS
3815: return $result;
3816: }
3817:
3818: sub upcsvScores_form {
3819: my ($request) = shift;
3820: my ($symb)=&get_symb($request);
3821: if (!$symb) {return '';}
3822: my $result=&checkforfile_js();
3823: $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
3824: my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
3825: $result.=$table;
3826: $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
3827: $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
3828: $result.=' <b>'.&mt('Specify a file containing the class scores for current resource').
3829: '.</b></td></tr>'."\n";
3830: $result.='<tr bgcolor=#ffffe6><td>'."\n";
3831: my $upload=&mt("Upload Scores");
3832: my $upfile_select=&Apache::loncommon::upfile_select_html();
3833: my $ignore=&mt('Ignore First Line');
3834: $symb = &Apache::lonenc::check_encrypt($symb);
3835: $result.=<<ENDUPFORM;
3836: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3837: <input type="hidden" name="symb" value="$symb" />
3838: <input type="hidden" name="command" value="csvuploadmap" />
3839: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
3840: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
3841: $upfile_select
3842: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
3843: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
3844: </form>
3845: ENDUPFORM
3846: $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
3847: &mt("How do I create a CSV file from a spreadsheet"))
3848: .'</td></tr></table>'."\n";
3849: $result.='</td></tr></table><br /><br />'."\n";
3850: $result.=&show_grading_menu_form($symb);
3851: return $result;
3852: }
3853:
3854:
3855: sub csvuploadmap {
3856: my ($request)= @_;
3857: my ($symb)=&get_symb($request);
3858: if (!$symb) {return '';}
3859:
3860: my $datatoken;
3861: if (!$env{'form.datatoken'}) {
3862: $datatoken=&Apache::loncommon::upfile_store($request);
3863: } else {
3864: $datatoken=$env{'form.datatoken'};
3865: &Apache::loncommon::load_tmp_file($request);
3866: }
3867: my @records=&Apache::loncommon::upfile_record_sep();
3868: if ($env{'form.noFirstLine'}) { shift(@records); }
3869: &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
3870: my ($i,$keyfields);
3871: if (@records) {
3872: my @fields=&csvupload_fields($symb);
3873:
3874: if ($env{'form.upfile_associate'} eq 'reverse') {
3875: &Apache::loncommon::csv_print_samples($request,\@records);
3876: $i=&Apache::loncommon::csv_print_select_table($request,\@records,
3877: \@fields);
3878: foreach (@fields) { $keyfields.=$_->[0].','; }
3879: chop($keyfields);
3880: } else {
3881: unshift(@fields,['none','']);
3882: $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
3883: \@fields);
3884: foreach my $rec (@records) {
3885: my %temp = &Apache::loncommon::record_sep($rec);
3886: if (%temp) {
3887: $keyfields=join(',',sort(keys(%temp)));
3888: last;
3889: }
3890: }
3891: }
3892: }
3893: &csvuploadmap_footer($request,$i,$keyfields);
3894: $request->print(&show_grading_menu_form($symb));
3895:
3896: return '';
3897: }
3898:
3899: sub csvuploadoptions {
3900: my ($request)= @_;
3901: my ($symb)=&get_symb($request);
3902: my $checked=(($env{'form.noFirstLine'})?'1':'0');
3903: my $ignore=&mt('Ignore First Line');
3904: $request->print(<<ENDPICK);
3905: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3906: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
3907: <input type="hidden" name="command" value="csvuploadassign" />
3908: <!--
3909: <p>
3910: <label>
3911: <input type="checkbox" name="show_full_results" />
3912: Show a table of all changes
3913: </label>
3914: </p>
3915: -->
3916: <p>
3917: <label>
3918: <input type="checkbox" name="overwite_scores" checked="checked" />
3919: Overwrite any existing score
3920: </label>
3921: </p>
3922: ENDPICK
3923: my %fields=&get_fields();
3924: if (!defined($fields{'domain'})) {
3925: my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
3926: $request->print("\n<p> Users are in domain: ".$domform."</p>\n");
3927: }
3928: foreach my $key (sort(keys(%env))) {
3929: if ($key !~ /^form\.(.*)$/) { next; }
3930: my $cleankey=$1;
3931: if ($cleankey eq 'command') { next; }
3932: $request->print('<input type="hidden" name="'.$cleankey.
3933: '" value="'.$env{$key}.'" />'."\n");
3934: }
3935: # FIXME do a check for any duplicated user ids...
3936: # FIXME do a check for any invalid user ids?...
3937: $request->print('<input type="submit" value="Assign Grades" /><br />
3938: <hr /></form>'."\n");
3939: $request->print(&show_grading_menu_form($symb));
3940: return '';
3941: }
3942:
3943: sub get_fields {
3944: my %fields;
3945: my @keyfields = split(/\,/,$env{'form.keyfields'});
3946: for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
3947: if ($env{'form.upfile_associate'} eq 'reverse') {
3948: if ($env{'form.f'.$i} ne 'none') {
3949: $fields{$keyfields[$i]}=$env{'form.f'.$i};
3950: }
3951: } else {
3952: if ($env{'form.f'.$i} ne 'none') {
3953: $fields{$env{'form.f'.$i}}=$keyfields[$i];
3954: }
3955: }
3956: }
3957: return %fields;
3958: }
3959:
3960: sub csvuploadassign {
3961: my ($request)= @_;
3962: my ($symb)=&get_symb($request);
3963: if (!$symb) {return '';}
3964: my $error_msg = '';
3965: &Apache::loncommon::load_tmp_file($request);
3966: my @gradedata = &Apache::loncommon::upfile_record_sep();
3967: if ($env{'form.noFirstLine'}) { shift(@gradedata); }
3968: my %fields=&get_fields();
3969: $request->print('<h3>Assigning Grades</h3>');
3970: my $courseid=$env{'request.course.id'};
3971: my ($classlist) = &getclasslist('all',0);
3972: my @notallowed;
3973: my @skipped;
3974: my $countdone=0;
3975: foreach my $grade (@gradedata) {
3976: my %entries=&Apache::loncommon::record_sep($grade);
3977: my $domain;
3978: if ($entries{$fields{'domain'}}) {
3979: $domain=$entries{$fields{'domain'}};
3980: } else {
3981: $domain=$env{'form.default_domain'};
3982: }
3983: $domain=~s/\s//g;
3984: my $username=$entries{$fields{'username'}};
3985: $username=~s/\s//g;
3986: if (!$username) {
3987: my $id=$entries{$fields{'ID'}};
3988: $id=~s/\s//g;
3989: my %ids=&Apache::lonnet::idget($domain,$id);
3990: $username=$ids{$id};
3991: }
3992: if (!exists($$classlist{"$username:$domain"})) {
3993: my $id=$entries{$fields{'ID'}};
3994: $id=~s/\s//g;
3995: if ($id) {
3996: push(@skipped,"$id:$domain");
3997: } else {
3998: push(@skipped,"$username:$domain");
3999: }
4000: next;
4001: }
4002: my $usec=$classlist->{"$username:$domain"}[5];
4003: if (!&canmodify($usec)) {
4004: push(@notallowed,"$username:$domain");
4005: next;
4006: }
4007: my %points;
4008: my %grades;
4009: foreach my $dest (keys(%fields)) {
4010: if ($dest eq 'ID' || $dest eq 'username' ||
4011: $dest eq 'domain') { next; }
4012: if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
4013: if ($dest=~/stores_(.*)_points/) {
4014: my $part=$1;
4015: my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
4016: $symb,$domain,$username);
4017: if ($wgt) {
4018: $entries{$fields{$dest}}=~s/\s//g;
4019: my $pcr=$entries{$fields{$dest}} / $wgt;
4020: my $award=($pcr == 0) ? 'incorrect_by_override'
4021: : 'correct_by_override';
4022: $grades{"resource.$part.awarded"}=$pcr;
4023: $grades{"resource.$part.solved"}=$award;
4024: $points{$part}=1;
4025: } else {
4026: $error_msg = "<br />" .
4027: &mt("Some point values were assigned"
4028: ." for problems with a weight "
4029: ."of zero. These values were "
4030: ."ignored.");
4031: }
4032: } else {
4033: if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
4034: if ($dest=~/stores_(.*)_solved/) { if ($points{$1}) {next;} }
4035: my $store_key=$dest;
4036: $store_key=~s/^stores/resource/;
4037: $store_key=~s/_/\./g;
4038: $grades{$store_key}=$entries{$fields{$dest}};
4039: }
4040: }
4041: if (! %grades) { push(@skipped,"$username:$domain no data to save"); }
4042: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
4043: my $result=&Apache::lonnet::cstore(\%grades,$symb,
4044: $env{'request.course.id'},
4045: $domain,$username);
4046: if ($result eq 'ok') {
4047: $request->print('.');
4048: } else {
4049: $request->print("<p>
4050: <span class=\"LC_error\">
4051: Failed to save student $username:$domain.
4052: Message when trying to save was ($result)
4053: </span>
4054: </p>" );
4055: }
4056: $request->rflush();
4057: $countdone++;
4058: }
4059: $request->print("<br />Saved $countdone students\n");
4060: if (@skipped) {
4061: $request->print('<p><h4><b>Skipped Students</b></h4></p>');
4062: foreach my $student (@skipped) { $request->print("$student<br />\n"); }
4063: }
4064: if (@notallowed) {
4065: $request->print('<p><span class="LC_error">Students Not Allowed to Modify</span></p>');
4066: foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
4067: }
4068: $request->print("<br />\n");
4069: $request->print(&show_grading_menu_form($symb));
4070: return $error_msg;
4071: }
4072: #------------- end of section for handling csv file upload ---------
4073: #
4074: #-------------------------------------------------------------------
4075: #
4076: #-------------- Next few routines handle grading by page/sequence
4077: #
4078: #--- Select a page/sequence and a student to grade
4079: sub pickStudentPage {
4080: my ($request) = shift;
4081:
4082: $request->print(<<LISTJAVASCRIPT);
4083: <script type="text/javascript" language="javascript">
4084:
4085: function checkPickOne(formname) {
4086: if (radioSelection(formname.student) == null) {
4087: alert("Please select the student you wish to grade.");
4088: return;
4089: }
4090: ptr = pullDownSelection(formname.selectpage);
4091: formname.page.value = formname["page"+ptr].value;
4092: formname.title.value = formname["title"+ptr].value;
4093: formname.submit();
4094: }
4095:
4096: </script>
4097: LISTJAVASCRIPT
4098: &commonJSfunctions($request);
4099: my ($symb) = &get_symb($request);
4100: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4101: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4102: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4103:
4104: my $result='<h3><span class="LC_info"> '.
4105: &mt('Manual Grading by Page or Sequence').'</span></h3>';
4106:
4107: $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
4108: my ($titles,$symbx) = &getSymbMap();
4109: my ($curpage) =&Apache::lonnet::decode_symb($symb);
4110: # my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb);
4111: # my $type=($curpage =~ /\.(page|sequence)/);
4112: my $select = '<select name="selectpage">'."\n";
4113: my $ctr=0;
4114: foreach (@$titles) {
4115: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4116: $select.='<option value="'.$ctr.'" '.
4117: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
4118: '>'.$showtitle.'</option>'."\n";
4119: $ctr++;
4120: }
4121: $select.= '</select>';
4122: $result.=&mt(' <b>Problems from:</b> [_1]',$select)."<br />\n";
4123:
4124: $ctr=0;
4125: foreach (@$titles) {
4126: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4127: $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
4128: $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
4129: $ctr++;
4130: }
4131: $result.='<input type="hidden" name="page" />'."\n".
4132: '<input type="hidden" name="title" />'."\n";
4133:
4134: my $options =
4135: '<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
4136: '<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
4137: $result.=' '.&mt('<b>View Problems Text: </b> [_1]',$options);
4138:
4139: $options =
4140: '<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
4141: '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
4142: '<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
4143: $result.=' '.&mt('<b>Submission Details: </b>[_1]',$options);
4144:
4145: $result.=&build_section_inputs();
4146: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
4147: $result.='<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
4148: '<input type="hidden" name="command" value="displayPage" />'."\n".
4149: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
4150: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
4151:
4152: $result.=' '.&mt('<b>Use CODE: [_1] </b>',
4153: '<input type="text" name="CODE" value="" />').
4154: '<br />'."\n";
4155:
4156: $result.=' <input type="button" '.
4157: 'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next->').'" /><br />'."\n";
4158:
4159: $request->print($result);
4160:
4161: my $studentTable.=' <b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
4162: &Apache::loncommon::start_data_table().
4163: &Apache::loncommon::start_data_table_header_row().
4164: '<th align="right"> '.&mt('No.').'</th>'.
4165: '<th>'.&nameUserString('header').'</th>'.
4166: '<th align="right"> '.&mt('No.').'</th>'.
4167: '<th>'.&nameUserString('header').'</th>'.
4168: &Apache::loncommon::end_data_table_header_row();
4169:
4170: my (undef,undef,$fullname) = &getclasslist($getsec,'1');
4171: my $ptr = 1;
4172: foreach my $student (sort
4173: {
4174: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
4175: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
4176: }
4177: return $a cmp $b;
4178: } (keys(%$fullname))) {
4179: my ($uname,$udom) = split(/:/,$student);
4180: $studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
4181: : '</td>');
4182: $studentTable.='<td align="right">'.$ptr.' </td>';
4183: $studentTable.='<td> <label><input type="radio" name="student" value="'.$student.'" /> '
4184: .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
4185: $studentTable.=
4186: ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row()
4187: : '');
4188: $ptr++;
4189: }
4190: if ($ptr%2 == 0) {
4191: $studentTable.='</td><td> </td><td> </td>'.
4192: &Apache::loncommon::end_data_table_row();
4193: }
4194: $studentTable.=&Apache::loncommon::end_data_table()."\n";
4195: $studentTable.='<input type="button" '.
4196: 'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next->').'" /></form>'."\n";
4197:
4198: $studentTable.=&show_grading_menu_form($symb);
4199: $request->print($studentTable);
4200:
4201: return '';
4202: }
4203:
4204: sub getSymbMap {
4205: my $navmap = Apache::lonnavmaps::navmap->new();
4206:
4207: my %symbx = ();
4208: my @titles = ();
4209: my $minder = 0;
4210:
4211: # Gather every sequence that has problems.
4212: my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
4213: 1,0,1);
4214: for my $sequence ($navmap->getById('0.0'), @sequences) {
4215: if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
4216: my $title = $minder.'.'.
4217: &HTML::Entities::encode($sequence->compTitle(),'"\'&');
4218: push(@titles, $title); # minder in case two titles are identical
4219: $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
4220: $minder++;
4221: }
4222: }
4223: return \@titles,\%symbx;
4224: }
4225:
4226: #
4227: #--- Displays a page/sequence w/wo problems, w/wo submissions
4228: sub displayPage {
4229: my ($request) = shift;
4230:
4231: my ($symb) = &get_symb($request);
4232: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4233: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4234: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4235: my $pageTitle = $env{'form.page'};
4236: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
4237: my ($uname,$udom) = split(/:/,$env{'form.student'});
4238: my $usec=$classlist->{$env{'form.student'}}[5];
4239:
4240: #need to make sure we have the correct data for later EXT calls,
4241: #thus invalidate the cache
4242: &Apache::lonnet::devalidatecourseresdata(
4243: $env{'course.'.$env{'request.course.id'}.'.num'},
4244: $env{'course.'.$env{'request.course.id'}.'.domain'});
4245: &Apache::lonnet::clear_EXT_cache_status();
4246:
4247: if (!&canview($usec)) {
4248: $request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
4249: $request->print(&show_grading_menu_form($symb));
4250: return;
4251: }
4252: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
4253: $result.='<h3> '.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
4254: '</h3>'."\n";
4255: if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
4256: $result.='<h3> '.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
4257: } else {
4258: delete($env{'form.CODE'});
4259: }
4260: &sub_page_js($request);
4261: $request->print($result);
4262:
4263: my $navmap = Apache::lonnavmaps::navmap->new();
4264: my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
4265: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
4266: if (!$map) {
4267: $request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
4268: $request->print(&show_grading_menu_form($symb));
4269: return;
4270: }
4271: my $iterator = $navmap->getIterator($map->map_start(),
4272: $map->map_finish());
4273:
4274: my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
4275: '<input type="hidden" name="command" value="gradeByPage" />'."\n".
4276: '<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
4277: '<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
4278: '<input type="hidden" name="page" value="'.$pageTitle.'" />'."\n".
4279: '<input type="hidden" name="title" value="'.$env{'form.title'}.'" />'."\n".
4280: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
4281: '<input type="hidden" name="overRideScore" value="no" />'."\n".
4282: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
4283:
4284: if (defined($env{'form.CODE'})) {
4285: $studentTable.=
4286: '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
4287: }
4288: my $checkIcon = '<img alt="'.&mt('Check Mark').
4289: '" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
4290:
4291: $studentTable.=' '.&mt('<b>Note:</b> Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon)."\n".
4292: &Apache::loncommon::start_data_table().
4293: &Apache::loncommon::start_data_table_header_row().
4294: '<th align="center"> Prob. </th>'.
4295: '<th> '.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
4296: &Apache::loncommon::end_data_table_header_row();
4297:
4298: &Apache::lonxml::clear_problem_counter();
4299: my ($depth,$question,$prob) = (1,1,1);
4300: $iterator->next(); # skip the first BEGIN_MAP
4301: my $curRes = $iterator->next(); # for "current resource"
4302: while ($depth > 0) {
4303: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
4304: if($curRes == $iterator->END_MAP) { $depth--; }
4305:
4306: if (ref($curRes) && $curRes->is_problem()) {
4307: my $parts = $curRes->parts();
4308: my $title = $curRes->compTitle();
4309: my $symbx = $curRes->symb();
4310: $studentTable.=
4311: &Apache::loncommon::start_data_table_row().
4312: '<td align="center" valign="top" >'.$prob.
4313: (scalar(@{$parts}) == 1 ? ''
4314: : '<br />('.&mt('[_1] parts)',
4315: scalar(@{$parts}))
4316: ).
4317: '</td>';
4318: $studentTable.='<td valign="top">';
4319: my %form = ('CODE' => $env{'form.CODE'},);
4320: if ($env{'form.vProb'} eq 'yes' ) {
4321: $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
4322: undef,'both',\%form);
4323: } else {
4324: my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
4325: $companswer =~ s|<form(.*?)>||g;
4326: $companswer =~ s|</form>||g;
4327: # while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
4328: # $companswer =~ s/$1/ /ms;
4329: # $request->print('match='.$1."<br />\n");
4330: # }
4331: # $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
4332: $studentTable.=' <b>'.$title.'</b> <br /> '.&mt('<b>Correct answer:</b><br />[_1]',$companswer);
4333: }
4334:
4335: my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
4336:
4337: if ($env{'form.lastSub'} eq 'datesub') {
4338: if ($record{'version'} eq '') {
4339: $studentTable.='<br /> <span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
4340: } else {
4341: my %responseType = ();
4342: foreach my $partid (@{$parts}) {
4343: my @responseIds =$curRes->responseIds($partid);
4344: my @responseType =$curRes->responseType($partid);
4345: my %responseIds;
4346: for (my $i=0;$i<=$#responseIds;$i++) {
4347: $responseIds{$responseIds[$i]}=$responseType[$i];
4348: }
4349: $responseType{$partid} = \%responseIds;
4350: }
4351: $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
4352:
4353: }
4354: } elsif ($env{'form.lastSub'} eq 'all') {
4355: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
4356: $studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
4357: $env{'request.course.id'},
4358: '','.submission');
4359:
4360: }
4361: if (&canmodify($usec)) {
4362: foreach my $partid (@{$parts}) {
4363: $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
4364: $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
4365: $question++;
4366: }
4367: $prob++;
4368: }
4369: $studentTable.='</td></tr>';
4370:
4371: }
4372: $curRes = $iterator->next();
4373: }
4374:
4375: $studentTable.='</table>'."\n".
4376: '<input type="button" value="'.&mt('Save').'" '.
4377: 'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
4378: '</form>'."\n";
4379: $studentTable.=&show_grading_menu_form($symb);
4380: $request->print($studentTable);
4381:
4382: return '';
4383: }
4384:
4385: sub displaySubByDates {
4386: my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
4387: my $isCODE=0;
4388: my $isTask = ($symb =~/\.task$/);
4389: if (exists($record->{'resource.CODE'})) { $isCODE=1; }
4390: my $studentTable=&Apache::loncommon::start_data_table().
4391: &Apache::loncommon::start_data_table_header_row().
4392: '<th>'.&mt('Date/Time').'</th>'.
4393: ($isCODE?'<th>'.&mt('CODE').'</th>':'').
4394: '<th>'.&mt('Submission').'</th>'.
4395: '<th>'.&mt('Status').'</th>'.
4396: &Apache::loncommon::end_data_table_header_row();
4397: my ($version);
4398: my %mark;
4399: my %orders;
4400: $mark{'correct_by_student'} = $checkIcon;
4401: if (!exists($$record{'1:timestamp'})) {
4402: return '<br /> <span class="LC_warning">'.&mt('Nothing submitted - no attempts').'</span><br />';
4403: }
4404:
4405: my $interaction;
4406: for ($version=1;$version<=$$record{'version'};$version++) {
4407: my $timestamp =
4408: &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
4409: if (exists($$record{$version.':resource.0.version'})) {
4410: $interaction = $$record{$version.':resource.0.version'};
4411: }
4412:
4413: my $where = ($isTask ? "$version:resource.$interaction"
4414: : "$version:resource");
4415: $studentTable.=&Apache::loncommon::start_data_table_row().
4416: '<td>'.$timestamp.'</td>';
4417: if ($isCODE) {
4418: $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
4419: }
4420: my @versionKeys = split(/\:/,$$record{$version.':keys'});
4421: my @displaySub = ();
4422: foreach my $partid (@{$parts}) {
4423: my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
4424: : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
4425:
4426:
4427: # next if ($$record{"$version:resource.$partid.solved"} eq '');
4428: my $display_part=&get_display_part($partid,$symb);
4429: foreach my $matchKey (@matchKey) {
4430: if (exists($$record{$version.':'.$matchKey}) &&
4431: $$record{$version.':'.$matchKey} ne '') {
4432:
4433: my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
4434: : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
4435: $displaySub[0].='<b>'.&mt('Part:').'</b> '.$display_part.' ';
4436: $displaySub[0].='<span class="LC_internal_info">('.&mt('ID').' '.
4437: $responseId.')</span> <b>';
4438: if ($$record{"$where.$partid.tries"} eq '') {
4439: $displaySub[0].=&mt('Trial not counted');
4440: } else {
4441: $displaySub[0].=&mt('Trial [_1]',
4442: $$record{"$where.$partid.tries"});
4443: }
4444: my $responseType=($isTask ? 'Task'
4445: : $responseType->{$partid}->{$responseId});
4446: if (!exists($orders{$partid})) { $orders{$partid}={}; }
4447: if (!exists($orders{$partid}->{$responseId})) {
4448: $orders{$partid}->{$responseId}=
4449: &get_order($partid,$responseId,$symb,$uname,$udom);
4450: }
4451: $displaySub[0].='</b> '.
4452: &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
4453: }
4454: }
4455: if (exists($$record{"$where.$partid.checkedin"})) {
4456: $displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
4457: $$record{"$where.$partid.checkedin"},
4458: $$record{"$where.$partid.checkedin.slot"}).
4459: '<br />';
4460: }
4461: if (exists $$record{"$where.$partid.award"}) {
4462: $displaySub[1].='<b>'.&mt('Part:').'</b> '.$display_part.' '.
4463: lc($$record{"$where.$partid.award"}).' '.
4464: $mark{$$record{"$where.$partid.solved"}}.
4465: '<br />';
4466: }
4467: if (exists $$record{"$where.$partid.regrader"}) {
4468: $displaySub[2].=$$record{"$where.$partid.regrader"}.
4469: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
4470: } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
4471: $displaySub[2].=
4472: $$record{"$version:resource.$partid.regrader"}.
4473: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
4474: }
4475: }
4476: # needed because old essay regrader has not parts info
4477: if (exists $$record{"$version:resource.regrader"}) {
4478: $displaySub[2].=$$record{"$version:resource.regrader"};
4479: }
4480: $studentTable.='<td>'.$displaySub[0].' </td><td>'.$displaySub[1];
4481: if ($displaySub[2]) {
4482: $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
4483: }
4484: $studentTable.=' </td>'.
4485: &Apache::loncommon::end_data_table_row();
4486: }
4487: $studentTable.=&Apache::loncommon::end_data_table();
4488: return $studentTable;
4489: }
4490:
4491: sub updateGradeByPage {
4492: my ($request) = shift;
4493:
4494: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4495: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4496: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4497: my $pageTitle = $env{'form.page'};
4498: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
4499: my ($uname,$udom) = split(/:/,$env{'form.student'});
4500: my $usec=$classlist->{$env{'form.student'}}[5];
4501: if (!&canmodify($usec)) {
4502: $request->print('<span class="LC_warning">Unable to modify requested student.('.$env{'form.student'}.'</span>');
4503: $request->print(&show_grading_menu_form($env{'form.symb'}));
4504: return;
4505: }
4506: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
4507: $result.='<h3> Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
4508: '</h3>'."\n";
4509:
4510: $request->print($result);
4511:
4512: my $navmap = Apache::lonnavmaps::navmap->new();
4513: my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
4514: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
4515: if (!$map) {
4516: $request->print('<span class="LC_warning">Unable to grade requested sequence. ('.$resUrl.')</span>');
4517: my ($symb)=&get_symb($request);
4518: $request->print(&show_grading_menu_form($symb));
4519: return;
4520: }
4521: my $iterator = $navmap->getIterator($map->map_start(),
4522: $map->map_finish());
4523:
4524: my $studentTable=
4525: &Apache::loncommon::start_data_table().
4526: &Apache::loncommon::start_data_table_header_row().
4527: '<th align="center"> '.&mt('Prob.').' </th>'.
4528: '<th> '.&mt('Title').' </th>'.
4529: '<th> '.&mt('Previous Score').' </th>'.
4530: '<th> '.&mt('New Score').' </th>'.
4531: &Apache::loncommon::end_data_table_header_row();
4532:
4533: $iterator->next(); # skip the first BEGIN_MAP
4534: my $curRes = $iterator->next(); # for "current resource"
4535: my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
4536: while ($depth > 0) {
4537: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
4538: if($curRes == $iterator->END_MAP) { $depth--; }
4539:
4540: if (ref($curRes) && $curRes->is_problem()) {
4541: my $parts = $curRes->parts();
4542: my $title = $curRes->compTitle();
4543: my $symbx = $curRes->symb();
4544: $studentTable.=
4545: &Apache::loncommon::start_data_table_row().
4546: '<td align="center" valign="top" >'.$prob.
4547: (scalar(@{$parts}) == 1 ? ''
4548: : '<br />('.&mt('[quant,_1, parts]',scalar(@{$parts}))
4549: ).')</td>';
4550: $studentTable.='<td valign="top"> <b>'.$title.'</b> </td>';
4551:
4552: my %newrecord=();
4553: my @displayPts=();
4554: my %aggregate = ();
4555: my $aggregateflag = 0;
4556: foreach my $partid (@{$parts}) {
4557: my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
4558: my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
4559:
4560: my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ?
4561: $env{'form.WGT'.$question.'_'.$partid} : 1;
4562: my $partial = $newpts/$wgt;
4563: my $score;
4564: if ($partial > 0) {
4565: $score = 'correct_by_override';
4566: } elsif ($newpts ne '') { #empty is taken as 0
4567: $score = 'incorrect_by_override';
4568: }
4569: my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
4570: if ($dropMenu eq 'excused') {
4571: $partial = '';
4572: $score = 'excused';
4573: } elsif ($dropMenu eq 'reset status'
4574: && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
4575: $newrecord{'resource.'.$partid.'.tries'} = 0;
4576: $newrecord{'resource.'.$partid.'.solved'} = '';
4577: $newrecord{'resource.'.$partid.'.award'} = '';
4578: $newrecord{'resource.'.$partid.'.awarded'} = 0;
4579: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
4580: $changeflag++;
4581: $newpts = '';
4582:
4583: my $aggtries = $env{'form.aggtries'.$question.'_'.$partid};
4584: my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
4585: my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
4586: if ($aggtries > 0) {
4587: &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
4588: $aggregateflag = 1;
4589: }
4590: }
4591: my $display_part=&get_display_part($partid,$curRes->symb());
4592: my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
4593: $displayPts[0].=' <b>Part:</b> '.$display_part.' = '.
4594: (($oldstatus eq 'excused') ? 'excused' : $oldpts).
4595: ' <br />';
4596: $displayPts[1].=' <b>Part:</b> '.$display_part.' = '.
4597: (($score eq 'excused') ? 'excused' : $newpts).
4598: ' <br />';
4599: $question++;
4600: next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
4601:
4602: $newrecord{'resource.'.$partid.'.awarded'} = $partial if $partial ne '';
4603: $newrecord{'resource.'.$partid.'.solved'} = $score if $score ne '';
4604: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
4605: if (scalar(keys(%newrecord)) > 0);
4606:
4607: $changeflag++;
4608: }
4609: if (scalar(keys(%newrecord)) > 0) {
4610: my %record =
4611: &Apache::lonnet::restore($symbx,$env{'request.course.id'},
4612: $udom,$uname);
4613:
4614: if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
4615: $newrecord{'resource.CODE'} = $env{'form.CODE'};
4616: } elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
4617: $newrecord{'resource.CODE'} = '';
4618: }
4619: &Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
4620: $udom,$uname);
4621: %record = &Apache::lonnet::restore($symbx,
4622: $env{'request.course.id'},
4623: $udom,$uname);
4624: &check_and_remove_from_queue($parts,\%record,undef,$symbx,
4625: $cdom,$cnum,$udom,$uname);
4626: }
4627:
4628: if ($aggregateflag) {
4629: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
4630: $env{'course.'.$env{'request.course.id'}.'.domain'},
4631: $env{'course.'.$env{'request.course.id'}.'.num'});
4632: }
4633:
4634: $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
4635: '<td valign="top">'.$displayPts[1].'</td>'.
4636: &Apache::loncommon::end_data_table_row();
4637:
4638: $prob++;
4639: }
4640: $curRes = $iterator->next();
4641: }
4642:
4643: $studentTable.=&Apache::loncommon::end_data_table();
4644: $studentTable.=&show_grading_menu_form($env{'form.symb'});
4645: my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
4646: 'The scores were changed for '.
4647: $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
4648: $request->print($grademsg.$studentTable);
4649:
4650: return '';
4651: }
4652:
4653: #-------- end of section for handling grading by page/sequence ---------
4654: #
4655: #-------------------------------------------------------------------
4656:
4657: #--------------------Scantron Grading-----------------------------------
4658: #
4659: #------ start of section for handling grading by page/sequence ---------
4660:
4661: =pod
4662:
4663: =head1 Bubble sheet grading routines
4664:
4665: For this documentation:
4666:
4667: 'scanline' refers to the full line of characters
4668: from the file that we are parsing that represents one entire sheet
4669:
4670: 'bubble line' refers to the data
4671: representing the line of bubbles that are on the physical bubble sheet
4672:
4673:
4674: The overall process is that a scanned in bubble sheet data is uploaded
4675: into a course. When a user wants to grade, they select a
4676: sequence/folder of resources, a file of bubble sheet info, and pick
4677: one of the predefined configurations for what each scanline looks
4678: like.
4679:
4680: Next each scanline is checked for any errors of either 'missing
4681: bubbles' (it's an error because it may have been mis-scanned
4682: because too light bubbling), 'double bubble' (each bubble line should
4683: have no more that one letter picked), invalid or duplicated CODE,
4684: invalid student ID
4685:
4686: If the CODE option is used that determines the randomization of the
4687: homework problems, either way the student ID is looked up into a
4688: username:domain.
4689:
4690: During the validation phase the instructor can choose to skip scanlines.
4691:
4692: After the validation phase, there are now 3 bubble sheet files
4693:
4694: scantron_original_filename (unmodified original file)
4695: scantron_corrected_filename (file where the corrected information has replaced the original information)
4696: scantron_skipped_filename (contains the exact text of scanlines that where skipped)
4697:
4698: Also there is a separate hash nohist_scantrondata that contains extra
4699: correction information that isn't representable in the bubble sheet
4700: file (see &scantron_getfile() for more information)
4701:
4702: After all scanlines are either valid, marked as valid or skipped, then
4703: foreach line foreach problem in the picked sequence, an ssi request is
4704: made that simulates a user submitting their selected letter(s) against
4705: the homework problem.
4706:
4707: =over 4
4708:
4709:
4710:
4711: =item defaultFormData
4712:
4713: Returns html hidden inputs used to hold context/default values.
4714:
4715: Arguments:
4716: $symb - $symb of the current resource
4717:
4718: =cut
4719:
4720: sub defaultFormData {
4721: my ($symb)=@_;
4722: return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
4723: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
4724: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
4725: }
4726:
4727:
4728: =pod
4729:
4730: =item getSequenceDropDown
4731:
4732: Return html dropdown of possible sequences to grade
4733:
4734: Arguments:
4735: $symb - $symb of the current resource
4736:
4737: =cut
4738:
4739: sub getSequenceDropDown {
4740: my ($symb)=@_;
4741: my $result='<select name="selectpage">'."\n";
4742: my ($titles,$symbx) = &getSymbMap();
4743: my ($curpage)=&Apache::lonnet::decode_symb($symb);
4744: my $ctr=0;
4745: foreach (@$titles) {
4746: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4747: $result.='<option value="'.$$symbx{$_}.'" '.
4748: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
4749: '>'.$showtitle.'</option>'."\n";
4750: $ctr++;
4751: }
4752: $result.= '</select>';
4753: return $result;
4754: }
4755:
4756:
4757: =pod
4758:
4759: =item scantron_filenames
4760:
4761: Returns a list of the scantron files in the current course
4762:
4763: =cut
4764:
4765: sub scantron_filenames {
4766: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4767: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
4768: my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
4769: &propath($cdom,$cname));
4770: my @possiblenames;
4771: foreach my $filename (sort(@files)) {
4772: ($filename)=split(/&/,$filename);
4773: if ($filename!~/^scantron_orig_/) { next ; }
4774: $filename=~s/^scantron_orig_//;
4775: push(@possiblenames,$filename);
4776: }
4777: return @possiblenames;
4778: }
4779:
4780: =pod
4781:
4782: =item scantron_uploads
4783:
4784: Returns html drop-down list of scantron files in current course.
4785:
4786: Arguments:
4787: $file2grade - filename to set as selected in the dropdown
4788:
4789: =cut
4790:
4791: sub scantron_uploads {
4792: my ($file2grade) = @_;
4793: my $result= '<select name="scantron_selectfile">';
4794: $result.="<option></option>";
4795: foreach my $filename (sort(&scantron_filenames())) {
4796: $result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
4797: }
4798: $result.="</select>";
4799: return $result;
4800: }
4801:
4802: =pod
4803:
4804: =item scantron_scantab
4805:
4806: Returns html drop down of the scantron formats in the scantronformat.tab
4807: file.
4808:
4809: =cut
4810:
4811: sub scantron_scantab {
4812: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
4813: my $result='<select name="scantron_format">'."\n";
4814: $result.='<option></option>'."\n";
4815: foreach my $line (<$fh>) {
4816: my ($name,$descrip)=split(/:/,$line);
4817: if ($name =~ /^\#/) { next; }
4818: $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
4819: }
4820: $result.='</select>'."\n";
4821:
4822: return $result;
4823: }
4824:
4825: =pod
4826:
4827: =item scantron_CODElist
4828:
4829: Returns html drop down of the saved CODE lists from current course,
4830: generated from earlier printings.
4831:
4832: =cut
4833:
4834: sub scantron_CODElist {
4835: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4836: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4837: my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
4838: my $namechoice='<option></option>';
4839: foreach my $name (sort {uc($a) cmp uc($b)} @names) {
4840: if ($name =~ /^error: 2 /) { next; }
4841: if ($name =~ /^type\0/) { next; }
4842: $namechoice.='<option value="'.$name.'">'.$name.'</option>';
4843: }
4844: $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
4845: return $namechoice;
4846: }
4847:
4848: =pod
4849:
4850: =item scantron_CODEunique
4851:
4852: Returns the html for "Each CODE to be used once" radio.
4853:
4854: =cut
4855:
4856: sub scantron_CODEunique {
4857: my $result='<span style="white-space: nowrap;">
4858: <label><input type="radio" name="scantron_CODEunique"
4859: value="yes" checked="checked" />'.&mt('Yes').' </label>
4860: </span>
4861: <span style="white-space: nowrap;">
4862: <label><input type="radio" name="scantron_CODEunique"
4863: value="no" />'.&mt('No').' </label>
4864: </span>';
4865: return $result;
4866: }
4867:
4868: =pod
4869:
4870: =item scantron_selectphase
4871:
4872: Generates the initial screen to start the bubble sheet process.
4873: Allows for - starting a grading run.
4874: - downloading existing scan data (original, corrected
4875: or skipped info)
4876:
4877: - uploading new scan data
4878:
4879: Arguments:
4880: $r - The Apache request object
4881: $file2grade - name of the file that contain the scanned data to score
4882:
4883: =cut
4884:
4885: sub scantron_selectphase {
4886: my ($r,$file2grade) = @_;
4887: my ($symb)=&get_symb($r);
4888: if (!$symb) {return '';}
4889: my $sequence_selector=&getSequenceDropDown($symb);
4890: my $default_form_data=&defaultFormData($symb);
4891: my $grading_menu_button=&show_grading_menu_form($symb);
4892: my $file_selector=&scantron_uploads($file2grade);
4893: my $format_selector=&scantron_scantab();
4894: my $CODE_selector=&scantron_CODElist();
4895: my $CODE_unique=&scantron_CODEunique();
4896: my $result;
4897:
4898: # Chunk of form to prompt for a file to grade and how:
4899:
4900: $result.= <<SCANTRONFORM;
4901: <table width="100%" border="0">
4902: <tr>
4903: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
4904: <td bgcolor="#777777">
4905: <input type="hidden" name="command" value="scantron_warning" />
4906: $default_form_data
4907: <table width="100%" border="0">
4908: <tr bgcolor="#e6ffff">
4909: <td colspan="2">
4910: <b>Specify file and which Folder/Sequence to grade</b>
4911: </td>
4912: </tr>
4913: <tr bgcolor="#ffffe6">
4914: <td> Sequence to grade: </td><td> $sequence_selector </td>
4915: </tr>
4916: <tr bgcolor="#ffffe6">
4917: <td> Filename of scoring office file: </td><td> $file_selector </td>
4918: </tr>
4919: <tr bgcolor="#ffffe6">
4920: <td> Format of data file: </td><td> $format_selector </td>
4921: </tr>
4922: <tr bgcolor="#ffffe6">
4923: <td> Saved CODEs to validate against: </td><td> $CODE_selector</td>
4924: </tr>
4925: <tr bgcolor="#ffffe6">
4926: <td> Each CODE is only to be used once:</td><td> $CODE_unique </td>
4927: </tr>
4928: <tr bgcolor="#ffffe6">
4929: <td> Options: </td>
4930: <td>
4931: <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> Do only previously skipped records</label> <br />
4932: <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> Remove all existing corrections</label> <br />
4933: <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> Skip hidden resources when grading</label>
4934: </td>
4935: </tr>
4936: <tr bgcolor="#ffffe6">
4937: <td colspan="2">
4938: <input type="submit" value="Grading: Validate Scantron Records" />
4939: </td>
4940: </tr>
4941: </table>
4942: </td>
4943: </form>
4944: </tr>
4945: SCANTRONFORM
4946:
4947: $r->print($result);
4948:
4949: if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
4950: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
4951:
4952: # Chunk of form to prompt for a scantron file upload.
4953:
4954: $r->print(<<SCANTRONFORM);
4955: <tr>
4956: <td bgcolor="#777777">
4957: <table width="100%" border="0">
4958: <tr bgcolor="#e6ffff">
4959: <td>
4960: <b>Specify a Scantron data file to upload.</b>
4961: </td>
4962: </tr>
4963: <tr bgcolor="#ffffe6">
4964: <td>
4965: SCANTRONFORM
4966: my $default_form_data=&defaultFormData(&get_symb($r,1));
4967: my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
4968: my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
4969: $r->print(<<UPLOAD);
4970: <script type="text/javascript" language="javascript">
4971: function checkUpload(formname) {
4972: if (formname.upfile.value == "") {
4973: alert("Please use the browse button to select a file from your local directory.");
4974: return false;
4975: }
4976: formname.submit();
4977: }
4978: </script>
4979:
4980: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
4981: $default_form_data
4982: <input name='courseid' type='hidden' value='$cnum' />
4983: <input name='domainid' type='hidden' value='$cdom' />
4984: <input name='command' value='scantronupload_save' type='hidden' />
4985: File to upload:<input type="file" name="upfile" size="50" />
4986: <br />
4987: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
4988: </form>
4989: UPLOAD
4990:
4991: $r->print(<<SCANTRONFORM);
4992: </td>
4993: </tr>
4994: </table>
4995: </td>
4996: </tr>
4997: SCANTRONFORM
4998: }
4999:
5000: # Chunk of the form that prompts to view a scoring office file,
5001: # corrected file, skipped records in a file.
5002:
5003: $r->print(<<SCANTRONFORM);
5004: <tr>
5005: <form action='/adm/grades' name='scantron_download'>
5006: <td bgcolor="#777777">
5007: $default_form_data
5008: <input type="hidden" name="command" value="scantron_download" />
5009: <table width="100%" border="0">
5010: <tr bgcolor="#e6ffff">
5011: <td colspan="2">
5012: <b>Download a scoring office file</b>
5013: </td>
5014: </tr>
5015: <tr bgcolor="#ffffe6">
5016: <td> Filename of scoring office file: </td><td> $file_selector </td>
5017: </tr>
5018: <tr bgcolor="#ffffe6">
5019: <td colspan="2">
5020: <input type="submit" value="Download: Show List of Associated Files" />
5021: </td>
5022: </tr>
5023: </table>
5024: </td>
5025: </form>
5026: </tr>
5027: SCANTRONFORM
5028:
5029: $r->print('<tr><td bgcolor="#777777">');
5030: &Apache::lonpickcode::code_list($r,2);
5031: $r->print('</td></tr></table>');
5032: $r->print($grading_menu_button);
5033: return
5034: }
5035:
5036: =pod
5037:
5038: =item get_scantron_config
5039:
5040: Parse and return the scantron configuration line selected as a
5041: hash of configuration file fields.
5042:
5043: Arguments:
5044: which - the name of the configuration to parse from the file.
5045:
5046:
5047: Returns:
5048: If the named configuration is not in the file, an empty
5049: hash is returned.
5050: a hash with the fields
5051: name - internal name for the this configuration setup
5052: description - text to display to operator that describes this config
5053: CODElocation - if 0 or the string 'none'
5054: - no CODE exists for this config
5055: if -1 || the string 'letter'
5056: - a CODE exists for this config and is
5057: a string of letters
5058: Unsupported value (but planned for future support)
5059: if a positive integer
5060: - The CODE exists as the first n items from
5061: the question section of the form
5062: if the string 'number'
5063: - The CODE exists for this config and is
5064: a string of numbers
5065: CODEstart - (only matter if a CODE exists) column in the line where
5066: the CODE starts
5067: CODElength - length of the CODE
5068: IDstart - column where the student ID number starts
5069: IDlength - length of the student ID info
5070: Qstart - column where the information from the bubbled
5071: 'questions' start
5072: Qlength - number of columns comprising a single bubble line from
5073: the sheet. (usually either 1 or 10)
5074: Qon - either a single character representing the character used
5075: to signal a bubble was chosen in the positional setup, or
5076: the string 'letter' if the letter of the chosen bubble is
5077: in the final, or 'number' if a number representing the
5078: chosen bubble is in the file (1->A 0->J)
5079: Qoff - the character used to represent that a bubble was
5080: left blank
5081: PaperID - if the scanning process generates a unique number for each
5082: sheet scanned the column that this ID number starts in
5083: PaperIDlength - number of columns that comprise the unique ID number
5084: for the sheet of paper
5085: FirstName - column that the first name starts in
5086: FirstNameLength - number of columns that the first name spans
5087:
5088: LastName - column that the last name starts in
5089: LastNameLength - number of columns that the last name spans
5090:
5091: =cut
5092:
5093: sub get_scantron_config {
5094: my ($which) = @_;
5095: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
5096: my %config;
5097: #FIXME probably should move to XML it has already gotten a bit much now
5098: foreach my $line (<$fh>) {
5099: my ($name,$descrip)=split(/:/,$line);
5100: if ($name ne $which ) { next; }
5101: chomp($line);
5102: my @config=split(/:/,$line);
5103: $config{'name'}=$config[0];
5104: $config{'description'}=$config[1];
5105: $config{'CODElocation'}=$config[2];
5106: $config{'CODEstart'}=$config[3];
5107: $config{'CODElength'}=$config[4];
5108: $config{'IDstart'}=$config[5];
5109: $config{'IDlength'}=$config[6];
5110: $config{'Qstart'}=$config[7];
5111: $config{'Qlength'}=$config[8];
5112: $config{'Qoff'}=$config[9];
5113: $config{'Qon'}=$config[10];
5114: $config{'PaperID'}=$config[11];
5115: $config{'PaperIDlength'}=$config[12];
5116: $config{'FirstName'}=$config[13];
5117: $config{'FirstNamelength'}=$config[14];
5118: $config{'LastName'}=$config[15];
5119: $config{'LastNamelength'}=$config[16];
5120: last;
5121: }
5122: return %config;
5123: }
5124:
5125: =pod
5126:
5127: =item username_to_idmap
5128:
5129: creates a hash keyed by student id with values of the corresponding
5130: student username:domain.
5131:
5132: Arguments:
5133:
5134: $classlist - reference to the class list hash. This is a hash
5135: keyed by student name:domain whose elements are references
5136: to arrays containing various chunks of information
5137: about the student. (See loncoursedata for more info).
5138:
5139: Returns
5140: %idmap - the constructed hash
5141:
5142: =cut
5143:
5144: sub username_to_idmap {
5145: my ($classlist)= @_;
5146: my %idmap;
5147: foreach my $student (keys(%$classlist)) {
5148: $idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
5149: $student;
5150: }
5151: return %idmap;
5152: }
5153:
5154: =pod
5155:
5156: =item scantron_fixup_scanline
5157:
5158: Process a requested correction to a scanline.
5159:
5160: Arguments:
5161: $scantron_config - hash from &get_scantron_config()
5162: $scan_data - hash of correction information
5163: (see &scantron_getfile())
5164: $line - existing scanline
5165: $whichline - line number of the passed in scanline
5166: $field - type of change to process
5167: (either
5168: 'ID' -> correct the student ID number
5169: 'CODE' -> correct the CODE
5170: 'answer' -> fixup the submitted answers)
5171:
5172: $args - hash of additional info,
5173: - 'ID'
5174: 'newid' -> studentID to use in replacement
5175: of existing one
5176: - 'CODE'
5177: 'CODE_ignore_dup' - set to true if duplicates
5178: should be ignored.
5179: 'CODE' - is new code or 'use_unfound'
5180: if the existing unfound code should
5181: be used as is
5182: - 'answer'
5183: 'response' - new answer or 'none' if blank
5184: 'question' - the bubble line to change
5185:
5186: Returns:
5187: $line - the modified scanline
5188:
5189: Side effects:
5190: $scan_data - may be updated
5191:
5192: =cut
5193:
5194:
5195: sub scantron_fixup_scanline {
5196: my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
5197:
5198:
5199: if ($field eq 'ID') {
5200: if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
5201: return ($line,1,'New value too large');
5202: }
5203: if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
5204: $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
5205: $args->{'newid'});
5206: }
5207: substr($line,$$scantron_config{'IDstart'}-1,
5208: $$scantron_config{'IDlength'})=$args->{'newid'};
5209: if ($args->{'newid'}=~/^\s*$/) {
5210: &scan_data($scan_data,"$whichline.user",
5211: $args->{'username'}.':'.$args->{'domain'});
5212: }
5213: } elsif ($field eq 'CODE') {
5214: if ($args->{'CODE_ignore_dup'}) {
5215: &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
5216: }
5217: &scan_data($scan_data,"$whichline.useCODE",'1');
5218: if ($args->{'CODE'} ne 'use_unfound') {
5219: if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
5220: return ($line,1,'New CODE value too large');
5221: }
5222: if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
5223: $args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
5224: }
5225: substr($line,$$scantron_config{'CODEstart'}-1,
5226: $$scantron_config{'CODElength'})=$args->{'CODE'};
5227: }
5228: } elsif ($field eq 'answer') {
5229: &scantron_get_maxbubble(); # Need the bubble counter info.
5230: my $length =$scantron_config->{'Qlength'};
5231: my $off=$scantron_config->{'Qoff'};
5232: my $on=$scantron_config->{'Qon'};
5233: my $question_number = $args->{'question'} -1;
5234: my $first_position = $first_bubble_line{$question_number};
5235: my $bubble_count = $bubble_lines_per_response{$question_number};
5236: my $bubbles_per_line= $$scantron_config{'Qlength'};
5237: my $answer=${off}x($bubbles_per_line*$bubble_count);
5238: my $final_answer;
5239: if ($$scantron_config{'Qon'} eq 'letter' ||
5240: $$scantron_config{'Qon'} eq 'number') {
5241: $bubbles_per_line = 10;
5242: }
5243: if (defined $args->{'response'}) {
5244:
5245: if ($args->{'response'} eq 'none') {
5246: &scan_data($scan_data,
5247: "$whichline.no_bubble.".$args->{'question'},'1');
5248: } else {
5249: my ($bubble_line, $bubble_number) = split(/:/,$args->{'response'});
5250: if ($on eq 'letter') {
5251: my @alphabet=('A'..'Z');
5252: $answer=$alphabet[$bubble_number];
5253: } elsif ($on eq 'number') {
5254: $answer= $bubble_number+1;
5255: if ($answer == 10) { $answer = '0'; }
5256: } else {
5257: substr($answer,$bubble_number+$bubble_line*$bubbles_per_line,1)=$on;
5258: $final_answer = $answer;
5259: }
5260: &scan_data($scan_data,
5261: "$whichline.no_bubble.".$args->{'question'},undef,'1');
5262:
5263: # Positional notation already has the right final answer length..
5264:
5265: if (($on eq 'letter') || ($on eq 'number')) {
5266: for (my $l = 0; $l < $bubble_count; $l++) {
5267: if ($l eq $bubble_line) {
5268: $final_answer .= $answer;
5269: } else {
5270: $final_answer .= ' ';
5271: }
5272: }
5273: }
5274: }
5275: # $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
5276: #substr($line,$where-1,$length)=$answer;
5277: substr($line,
5278: $scantron_config->{'Qstart'}+$first_position-1,
5279: $bubbles_per_line*$length) = $final_answer;
5280: }
5281: }
5282: return $line;
5283: }
5284:
5285: =pod
5286:
5287: =item scan_data
5288:
5289: Edit or look up an item in the scan_data hash.
5290:
5291: Arguments:
5292: $scan_data - The hash (see scantron_getfile)
5293: $key - shorthand of the key to edit (actual key is
5294: scantronfilename_key).
5295: $data - New value of the hash entry.
5296: $delete - If true, the entry is removed from the hash.
5297:
5298: Returns:
5299: The new value of the hash table field (undefined if deleted).
5300:
5301: =cut
5302:
5303:
5304: sub scan_data {
5305: my ($scan_data,$key,$value,$delete)=@_;
5306: my $filename=$env{'form.scantron_selectfile'};
5307: if (defined($value)) {
5308: $scan_data->{$filename.'_'.$key} = $value;
5309: }
5310: if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
5311: return $scan_data->{$filename.'_'.$key};
5312: }
5313:
5314: =pod
5315:
5316: =item scantron_parse_scanline
5317:
5318: Decodes a scanline from the selected scantron file
5319:
5320: Arguments:
5321: line - The text of the scantron file line to process
5322: whichline - Line number
5323: scantron_config - Hash describing the format of the scantron lines.
5324: scan_data - Hash of extra information about the scanline
5325: (see scantron_getfile for more information)
5326: just_header - True if should not process question answers but only
5327: the stuff to the left of the answers.
5328: Returns:
5329: Hash containing the result of parsing the scanline
5330:
5331: Keys are all proceeded by the string 'scantron.'
5332:
5333: CODE - the CODE in use for this scanline
5334: useCODE - 1 if the CODE is invalid but it usage has been forced
5335: by the operator
5336: CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
5337: CODEs were selected, but the usage has been
5338: forced by the operator
5339: ID - student ID
5340: PaperID - if used, the ID number printed on the sheet when the
5341: paper was scanned
5342: FirstName - first name from the sheet
5343: LastName - last name from the sheet
5344:
5345: if just_header was not true these key may also exist
5346:
5347: missingerror - a list of bubble ranges that are considered to be answers
5348: to a single question that don't have any bubbles filled in.
5349: Of the form questionnumber:firstbubblenumber:count.
5350: doubleerror - a list of bubble ranges that are considered to be answers
5351: to a single question that have more than one bubble filled in.
5352: Of the form questionnumber::firstbubblenumber:count
5353:
5354: In the above, count is the number of bubble responses in the
5355: input line needed to represent the possible answers to the question.
5356: e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
5357: per line would have count = 2.
5358:
5359: maxquest - the number of the last bubble line that was parsed
5360:
5361: (<number> starts at 1)
5362: <number>.answer - zero or more letters representing the selected
5363: letters from the scanline for the bubble line
5364: <number>.
5365: if blank there was either no bubble or there where
5366: multiple bubbles, (consult the keys missingerror and
5367: doubleerror if this is an error condition)
5368:
5369: =cut
5370:
5371: sub scantron_parse_scanline {
5372: my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
5373:
5374: my %record;
5375: my $questions=substr($line,$$scantron_config{'Qstart'}-1); # Answers
5376: my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # earlier stuff
5377: if (!($$scantron_config{'CODElocation'} eq 0 ||
5378: $$scantron_config{'CODElocation'} eq 'none')) {
5379: if ($$scantron_config{'CODElocation'} < 0 ||
5380: $$scantron_config{'CODElocation'} eq 'letter' ||
5381: $$scantron_config{'CODElocation'} eq 'number') {
5382: $record{'scantron.CODE'}=substr($data,
5383: $$scantron_config{'CODEstart'}-1,
5384: $$scantron_config{'CODElength'});
5385: if (&scan_data($scan_data,"$whichline.useCODE")) {
5386: $record{'scantron.useCODE'}=1;
5387: }
5388: if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
5389: $record{'scantron.CODE_ignore_dup'}=1;
5390: }
5391: } else {
5392: #FIXME interpret first N questions
5393: }
5394: }
5395: $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
5396: $$scantron_config{'IDlength'});
5397: $record{'scantron.PaperID'}=
5398: substr($data,$$scantron_config{'PaperID'}-1,
5399: $$scantron_config{'PaperIDlength'});
5400: $record{'scantron.FirstName'}=
5401: substr($data,$$scantron_config{'FirstName'}-1,
5402: $$scantron_config{'FirstNamelength'});
5403: $record{'scantron.LastName'}=
5404: substr($data,$$scantron_config{'LastName'}-1,
5405: $$scantron_config{'LastNamelength'});
5406: if ($just_header) { return \%record; }
5407:
5408: my @alphabet=('A'..'Z');
5409: my $questnum=0;
5410: my $ansnum =1; # Multiple 'answer lines'/question.
5411:
5412: chomp($questions); # Get rid of any trailing \n.
5413: $questions =~ s/\r$//; # Get rid of trailing \r too (MAC or Win uploads).
5414: while (length($questions)) {
5415: my $answers_needed = $bubble_lines_per_response{$questnum};
5416: my $answer_length = $$scantron_config{'Qlength'} * $answers_needed;
5417:
5418:
5419:
5420: $questnum++;
5421: my $currentquest = substr($questions,0,$answer_length);
5422: $questions = substr($questions,0,$answer_length)='';
5423: if (length($currentquest) < $answer_length) { next; }
5424:
5425: # Qon letter implies for each slot in currentquest we have:
5426: # ? or * for doubles a letter in A-Z for a bubble and
5427: # about anything else (esp. a value of Qoff for missing
5428: # bubbles.
5429:
5430:
5431: if ($$scantron_config{'Qon'} eq 'letter') {
5432:
5433: if ($currentquest =~ /\?/
5434: || $currentquest =~ /\*/
5435: || (&occurence_count($currentquest, "[A-Z]") > 1)) {
5436: push(@{$record{'scantron.doubleerror'}},$questnum);
5437: for (my $ans = 0; $ans < $answers_needed; $ans++) {
5438: my $bubble = substr($currentquest, $ans, 1);
5439: if ($bubble =~ /[A-Z]/ ) {
5440: $record{"scantron.$ansnum.answer"} = $bubble;
5441: } else {
5442: $record{"scantron.$ansnum.answer"}='';
5443: }
5444: $ansnum++;
5445: }
5446:
5447: } elsif (!defined($currentquest)
5448: || (&occurence_count($currentquest, $$scantron_config{'Qoff'}) == length($currentquest))
5449: || (&occurence_count($currentquest, "[A-Z]") == 0)) {
5450: for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
5451: $record{"scantron.$ansnum.answer"}='';
5452: $ansnum++;
5453:
5454: }
5455: if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
5456: push(@{$record{"scantron.missingerror"}},$questnum);
5457: # $ansnum += $answers_needed;
5458: }
5459: } else {
5460: for (my $ans = 0; $ans < $answers_needed; $ans++) {
5461: $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
5462: $ansnum++;
5463: }
5464: }
5465:
5466: # Qon 'number' implies each slot gives a digit that indexes the
5467: # the bubbles filled or Qoff or a non number for unbubbled lines.
5468: # and *? for double bubbles on a line.
5469: # these answers are also stored as letters.
5470:
5471: } elsif ($$scantron_config{'Qon'} eq 'number') {
5472: if ($currentquest =~ /\?/
5473: || $currentquest =~ /\*/
5474: || (&occurence_count($currentquest, '\d') > 1)) {
5475: push(@{$record{'scantron.doubleerror'}},$questnum);
5476: for (my $ans = 0; $ans < $answers_needed; $ans++) {
5477: my $bubble = substr($currentquest, $ans, 1);
5478: if ($bubble =~ /\d/) {
5479: $record{"scantron.$ansnum.answer"} = $alphabet[$bubble];
5480: } else {
5481: $record{"scantron.$ansnum.answer"}=' ';
5482: }
5483: $ansnum++;
5484: }
5485:
5486: } elsif (!defined($currentquest)
5487: || (&occurence_count($currentquest,$$scantron_config{'Qoff'}) == length($currentquest))
5488: || (&occurence_count($currentquest, '\d') == 0)) {
5489: for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
5490: $record{"scantron.$ansnum.answer"}='';
5491: $ansnum++;
5492:
5493: }
5494: if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
5495: push(@{$record{"scantron.missingerror"}},$questnum);
5496: $ansnum += $answers_needed;
5497: }
5498:
5499: } else {
5500: $currentquest = &digits_to_letters($currentquest);
5501: for (my $ans =0; $ans < $answers_needed; $ans++) {
5502: $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
5503: $ansnum++;
5504: }
5505: }
5506: } else {
5507:
5508: # Otherwise there's a positional notation;
5509: # each bubble line requires Qlength items, and there are filled in
5510: # bubbles for each case where there 'Qon' characters.
5511: #
5512:
5513: my @array=split($$scantron_config{'Qon'},$currentquest,-1);
5514:
5515: # If the split only giveas us one element.. the full length of the
5516: # answser string, no bubbles are filled in:
5517:
5518: if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
5519: for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
5520: $record{"scantron.$ansnum.answer"}='';
5521: $ansnum++;
5522:
5523: }
5524: if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
5525: push(@{$record{"scantron.missingerror"}},$questnum);
5526: }
5527:
5528: # If the bubble is not the last position, there will be
5529: # 2 elements. If it is the last position, there will be 1 element.
5530:
5531: } elsif (scalar(@array) le 2) {
5532:
5533: my $location = length($array[0]);
5534: my $line_num = int($location / $$scantron_config{'Qlength'});
5535: my $bubble = $alphabet[$location % $$scantron_config{'Qlength'}];
5536:
5537:
5538: for (my $ans = 0; $ans < $answers_needed; $ans++) {
5539: if ($ans eq $line_num) {
5540: $record{"scantron.$ansnum.answer"} = $bubble;
5541: } else {
5542: $record{"scantron.$ansnum.answer"} = ' ';
5543: }
5544: $ansnum++;
5545: }
5546: }
5547: # If there's more than one instance of a bubble character
5548: # That's a double bubble; with positional notation we can
5549: # record all the bubbles filled in as well as the
5550: # fact this response consists of multiple bubbles.
5551: #
5552: else {
5553: push(@{$record{'scantron.doubleerror'}},$questnum);
5554:
5555: my $first_answer = $ansnum;
5556: for (my $ans =0; $ans < $answers_needed; $ans++) {
5557: my $item = $first_answer+$ans;
5558: $record{"scantron.$item.answer"} = '';
5559: }
5560:
5561: my @ans=@array;
5562: my $i=0;
5563: my $increment = 0;
5564: while ($#ans) {
5565: $i+=length($ans[0]) + $increment;
5566: my $line = int($i/$$scantron_config{'Qlength'} + $first_answer);
5567: my $bubble = $i%$$scantron_config{'Qlength'};
5568: $record{"scantron.$line.answer"}.=$alphabet[$bubble];
5569: shift(@ans);
5570: $increment = 1;
5571: }
5572: $ansnum += $answers_needed;
5573: }
5574: }
5575: }
5576: $record{'scantron.maxquest'}=$questnum;
5577: return \%record;
5578: }
5579:
5580: =pod
5581:
5582: =item scantron_add_delay
5583:
5584: Adds an error message that occurred during the grading phase to a
5585: queue of messages to be shown after grading pass is complete
5586:
5587: Arguments:
5588: $delayqueue - arrary ref of hash ref of error messages
5589: $scanline - the scanline that caused the error
5590: $errormesage - the error message
5591: $errorcode - a numeric code for the error
5592:
5593: Side Effects:
5594: updates the $delayqueue to have a new hash ref of the error
5595:
5596: =cut
5597:
5598: sub scantron_add_delay {
5599: my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
5600: push(@$delayqueue,
5601: {'line' => $scanline, 'emsg' => $errormessage,
5602: 'ecode' => $errorcode }
5603: );
5604: }
5605:
5606: =pod
5607:
5608: =item scantron_find_student
5609:
5610: Finds the username for the current scanline
5611:
5612: Arguments:
5613: $scantron_record - hash result from scantron_parse_scanline
5614: $scan_data - hash of correction information
5615: (see &scantron_getfile() form more information)
5616: $idmap - hash from &username_to_idmap()
5617: $line - number of current scanline
5618:
5619: Returns:
5620: Either 'username:domain' or undef if unknown
5621:
5622: =cut
5623:
5624: sub scantron_find_student {
5625: my ($scantron_record,$scan_data,$idmap,$line)=@_;
5626: my $scanID=$$scantron_record{'scantron.ID'};
5627: if ($scanID =~ /^\s*$/) {
5628: return &scan_data($scan_data,"$line.user");
5629: }
5630: foreach my $id (keys(%$idmap)) {
5631: if (lc($id) eq lc($scanID)) {
5632: return $$idmap{$id};
5633: }
5634: }
5635: return undef;
5636: }
5637:
5638: =pod
5639:
5640: =item scantron_filter
5641:
5642: Filter sub for lonnavmaps, filters out hidden resources if ignore
5643: hidden resources was selected
5644:
5645: =cut
5646:
5647: sub scantron_filter {
5648: my ($curres)=@_;
5649:
5650: if (ref($curres) && $curres->is_problem()) {
5651: # if the user has asked to not have either hidden
5652: # or 'randomout' controlled resources to be graded
5653: # don't include them
5654: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
5655: && $curres->randomout) {
5656: return 0;
5657: }
5658: return 1;
5659: }
5660: return 0;
5661: }
5662:
5663: =pod
5664:
5665: =item scantron_process_corrections
5666:
5667: Gets correction information out of submitted form data and corrects
5668: the scanline
5669:
5670: =cut
5671:
5672: sub scantron_process_corrections {
5673: my ($r) = @_;
5674: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
5675: my ($scanlines,$scan_data)=&scantron_getfile();
5676: my $classlist=&Apache::loncoursedata::get_classlist();
5677: my $which=$env{'form.scantron_line'};
5678: my $line=&scantron_get_line($scanlines,$scan_data,$which);
5679: my ($skip,$err,$errmsg);
5680: if ($env{'form.scantron_skip_record'}) {
5681: $skip=1;
5682: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
5683: my $newstudent=$env{'form.scantron_username'}.':'.
5684: $env{'form.scantron_domain'};
5685: my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
5686: ($line,$err,$errmsg)=
5687: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
5688: 'ID',{'newid'=>$newid,
5689: 'username'=>$env{'form.scantron_username'},
5690: 'domain'=>$env{'form.scantron_domain'}});
5691: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
5692: my $resolution=$env{'form.scantron_CODE_resolution'};
5693: my $newCODE;
5694: my %args;
5695: if ($resolution eq 'use_unfound') {
5696: $newCODE='use_unfound';
5697: } elsif ($resolution eq 'use_found') {
5698: $newCODE=$env{'form.scantron_CODE_selectedvalue'};
5699: } elsif ($resolution eq 'use_typed') {
5700: $newCODE=$env{'form.scantron_CODE_newvalue'};
5701: } elsif ($resolution =~ /^use_closest_(\d+)/) {
5702: $newCODE=$env{"form.scantron_CODE_closest_$1"};
5703: }
5704: if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
5705: $args{'CODE_ignore_dup'}=1;
5706: }
5707: $args{'CODE'}=$newCODE;
5708: ($line,$err,$errmsg)=
5709: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
5710: 'CODE',\%args);
5711: } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
5712: foreach my $question (split(',',$env{'form.scantron_questions'})) {
5713: ($line,$err,$errmsg)=
5714: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
5715: $which,'answer',
5716: { 'question'=>$question,
5717: 'response'=>$env{"form.scantron_correct_Q_$question"}});
5718: if ($err) { last; }
5719: }
5720: }
5721: if ($err) {
5722: $r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
5723: } else {
5724: &scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
5725: &scantron_putfile($scanlines,$scan_data);
5726: }
5727: }
5728:
5729: =pod
5730:
5731: =item reset_skipping_status
5732:
5733: Forgets the current set of remember skipped scanlines (and thus
5734: reverts back to considering all lines in the
5735: scantron_skipped_<filename> file)
5736:
5737: =cut
5738:
5739: sub reset_skipping_status {
5740: my ($scanlines,$scan_data)=&scantron_getfile();
5741: &scan_data($scan_data,'remember_skipping',undef,1);
5742: &scantron_putfile(undef,$scan_data);
5743: }
5744:
5745: =pod
5746:
5747: =item start_skipping
5748:
5749: Marks a scanline to be skipped.
5750:
5751: =cut
5752:
5753: sub start_skipping {
5754: my ($scan_data,$i)=@_;
5755: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
5756: if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
5757: $remembered{$i}=2;
5758: } else {
5759: $remembered{$i}=1;
5760: }
5761: &scan_data($scan_data,'remember_skipping',join(':',%remembered));
5762: }
5763:
5764: =pod
5765:
5766: =item should_be_skipped
5767:
5768: Checks whether a scanline should be skipped.
5769:
5770: =cut
5771:
5772: sub should_be_skipped {
5773: my ($scanlines,$scan_data,$i)=@_;
5774: if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
5775: # not redoing old skips
5776: if ($scanlines->{'skipped'}[$i]) { return 1; }
5777: return 0;
5778: }
5779: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
5780:
5781: if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
5782: return 0;
5783: }
5784: return 1;
5785: }
5786:
5787: =pod
5788:
5789: =item remember_current_skipped
5790:
5791: Discovers what scanlines are in the scantron_skipped_<filename>
5792: file and remembers them into scan_data for later use.
5793:
5794: =cut
5795:
5796: sub remember_current_skipped {
5797: my ($scanlines,$scan_data)=&scantron_getfile();
5798: my %to_remember;
5799: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
5800: if ($scanlines->{'skipped'}[$i]) {
5801: $to_remember{$i}=1;
5802: }
5803: }
5804:
5805: &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
5806: &scantron_putfile(undef,$scan_data);
5807: }
5808:
5809: =pod
5810:
5811: =item check_for_error
5812:
5813: Checks if there was an error when attempting to remove a specific
5814: scantron_.. bubble sheet data file. Prints out an error if
5815: something went wrong.
5816:
5817: =cut
5818:
5819: sub check_for_error {
5820: my ($r,$result)=@_;
5821: if ($result ne 'ok' && $result ne 'not_found' ) {
5822: $r->print("An error occurred ($result) when trying to Remove the existing corrections.");
5823: }
5824: }
5825:
5826: =pod
5827:
5828: =item scantron_warning_screen
5829:
5830: Interstitial screen to make sure the operator has selected the
5831: correct options before we start the validation phase.
5832:
5833: =cut
5834:
5835: sub scantron_warning_screen {
5836: my ($button_text)=@_;
5837: my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
5838: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
5839: my $CODElist;
5840: if ($scantron_config{'CODElocation'} &&
5841: $scantron_config{'CODEstart'} &&
5842: $scantron_config{'CODElength'}) {
5843: $CODElist=$env{'form.scantron_CODElist'};
5844: if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
5845: $CODElist=
5846: '<tr><td><b>List of CODES to validate against:</b></td><td><tt>'.
5847: $env{'form.scantron_CODElist'}.'</tt></td></tr>';
5848: }
5849: return (<<STUFF);
5850: <p>
5851: <span class="LC_warning">Please double check the information
5852: below before clicking on '$button_text'</span>
5853: </p>
5854: <table>
5855: <tr><td><b>Sequence to be Graded:</b></td><td>$title</td></tr>
5856: <tr><td><b>Data File that will be used:</b></td><td><tt>$env{'form.scantron_selectfile'}</tt></td></tr>
5857: $CODElist
5858: </table>
5859: <br />
5860: <p> If this information is correct, please click on '$button_text'.</p>
5861: <p> If something is incorrect, please click the 'Grading Menu' button to start over.</p>
5862:
5863: <br />
5864: STUFF
5865: }
5866:
5867: =pod
5868:
5869: =item scantron_do_warning
5870:
5871: Check if the operator has picked something for all required
5872: fields. Error out if something is missing.
5873:
5874: =cut
5875:
5876: sub scantron_do_warning {
5877: my ($r)=@_;
5878: my ($symb)=&get_symb($r);
5879: if (!$symb) {return '';}
5880: my $default_form_data=&defaultFormData($symb);
5881: $r->print(&scantron_form_start().$default_form_data);
5882: if ( $env{'form.selectpage'} eq '' ||
5883: $env{'form.scantron_selectfile'} eq '' ||
5884: $env{'form.scantron_format'} eq '' ) {
5885: $r->print("<p>You have forgetten to specify some information. Please go Back and try again.</p>");
5886: if ( $env{'form.selectpage'} eq '') {
5887: $r->print('<p><span class="LC_error">You have not selected a Sequence to grade</span></p>');
5888: }
5889: if ( $env{'form.scantron_selectfile'} eq '') {
5890: $r->print('<p><span class="LC_error">You have not selected a file that contains the student\'s response data.</span></p>');
5891: }
5892: if ( $env{'form.scantron_format'} eq '') {
5893: $r->print('<p><span class="LC_error">You have not selected a the format of the student\'s response data.</span></p>');
5894: }
5895: } else {
5896: my $warning=&scantron_warning_screen('Grading: Validate Records');
5897: $r->print(<<STUFF);
5898: $warning
5899: <input type="submit" name="submit" value="Grading: Validate Records" />
5900: <input type="hidden" name="command" value="scantron_validate" />
5901: STUFF
5902: }
5903: $r->print("</form><br />".&show_grading_menu_form($symb));
5904: return '';
5905: }
5906:
5907: =pod
5908:
5909: =item scantron_form_start
5910:
5911: html hidden input for remembering all selected grading options
5912:
5913: =cut
5914:
5915: sub scantron_form_start {
5916: my ($max_bubble)=@_;
5917: my $result= <<SCANTRONFORM;
5918: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
5919: <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
5920: <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
5921: <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
5922: <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
5923: <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
5924: <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
5925: <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
5926: <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
5927: <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
5928: SCANTRONFORM
5929:
5930: my $line = 0;
5931: while (defined($env{"form.scantron.bubblelines.$line"})) {
5932: my $chunk =
5933: '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
5934: $chunk .=
5935: '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
5936: $result .= $chunk;
5937: $line++;
5938: }
5939: return $result;
5940: }
5941:
5942: =pod
5943:
5944: =item scantron_validate_file
5945:
5946: Dispatch routine for doing validation of a bubble sheet data file.
5947:
5948: Also processes any necessary information resets that need to
5949: occur before validation begins (ignore previous corrections,
5950: restarting the skipped records processing)
5951:
5952: =cut
5953:
5954: sub scantron_validate_file {
5955: my ($r) = @_;
5956: my ($symb)=&get_symb($r);
5957: if (!$symb) {return '';}
5958: my $default_form_data=&defaultFormData($symb);
5959:
5960: # do the detection of only doing skipped records first befroe we delete
5961: # them when doing the corrections reset
5962: if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
5963: &reset_skipping_status();
5964: }
5965: if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
5966: &remember_current_skipped();
5967: $env{'form.scantron_options_redo'}='redo_skipped_ready';
5968: }
5969:
5970: if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
5971: &check_for_error($r,&scantron_remove_file('corrected'));
5972: &check_for_error($r,&scantron_remove_file('skipped'));
5973: &check_for_error($r,&scantron_remove_scan_data());
5974: $env{'form.scantron_options_ignore'}='done';
5975: }
5976:
5977: if ($env{'form.scantron_corrections'}) {
5978: &scantron_process_corrections($r);
5979: }
5980: $r->print("<p>Gathering necessary info.</p>");$r->rflush();
5981: #get the student pick code ready
5982: $r->print(&Apache::loncommon::studentbrowser_javascript());
5983: my $max_bubble=&scantron_get_maxbubble();
5984: my $result=&scantron_form_start($max_bubble).$default_form_data;
5985: $r->print($result);
5986:
5987: my @validate_phases=( 'sequence',
5988: 'ID',
5989: 'CODE',
5990: 'doublebubble',
5991: 'missingbubbles');
5992: if (!$env{'form.validatepass'}) {
5993: $env{'form.validatepass'} = 0;
5994: }
5995: my $currentphase=$env{'form.validatepass'};
5996:
5997:
5998: my $stop=0;
5999: while (!$stop && $currentphase < scalar(@validate_phases)) {
6000: $r->print("<p> Validating ".$validate_phases[$currentphase]."</p>");
6001: $r->rflush();
6002: my $which="scantron_validate_".$validate_phases[$currentphase];
6003: {
6004: no strict 'refs';
6005: ($stop,$currentphase)=&$which($r,$currentphase);
6006: }
6007: }
6008: if (!$stop) {
6009: my $warning=&scantron_warning_screen('Start Grading');
6010: $r->print(<<STUFF);
6011: Validation process complete.<br />
6012: $warning
6013: <input type="submit" name="submit" value="Start Grading" />
6014: <input type="hidden" name="command" value="scantron_process" />
6015: STUFF
6016:
6017: } else {
6018: $r->print('<input type="hidden" name="command" value="scantron_validate" />');
6019: $r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
6020: }
6021: if ($stop) {
6022: if ($validate_phases[$currentphase] eq 'sequence') {
6023: $r->print('<input type="submit" name="submit" value="Ignore -> " />');
6024: $r->print(' this error <br />');
6025:
6026: $r->print(" <p>Or click the 'Grading Menu' button to start over.</p>");
6027: } else {
6028: $r->print('<input type="submit" name="submit" value="Continue ->" />');
6029: $r->print(' using corrected info <br />');
6030: $r->print("<input type='submit' value='Skip' name='scantron_skip_record' />");
6031: $r->print(" this scanline saving it for later.");
6032: }
6033: }
6034: $r->print(" </form><br />".&show_grading_menu_form($symb));
6035: return '';
6036: }
6037:
6038:
6039: =pod
6040:
6041: =item scantron_remove_file
6042:
6043: Removes the requested bubble sheet data file, makes sure that
6044: scantron_original_<filename> is never removed
6045:
6046:
6047: =cut
6048:
6049: sub scantron_remove_file {
6050: my ($which)=@_;
6051: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6052: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6053: my $file='scantron_';
6054: if ($which eq 'corrected' || $which eq 'skipped') {
6055: $file.=$which.'_';
6056: } else {
6057: return 'refused';
6058: }
6059: $file.=$env{'form.scantron_selectfile'};
6060: return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
6061: }
6062:
6063:
6064: =pod
6065:
6066: =item scantron_remove_scan_data
6067:
6068: Removes all scan_data correction for the requested bubble sheet
6069: data file. (In the case that both the are doing skipped records we need
6070: to remember the old skipped lines for the time being so that element
6071: persists for a while.)
6072:
6073: =cut
6074:
6075: sub scantron_remove_scan_data {
6076: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6077: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6078: my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
6079: my @todelete;
6080: my $filename=$env{'form.scantron_selectfile'};
6081: foreach my $key (@keys) {
6082: if ($key=~/^\Q$filename\E_/) {
6083: if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
6084: $key=~/remember_skipping/) {
6085: next;
6086: }
6087: push(@todelete,$key);
6088: }
6089: }
6090: my $result;
6091: if (@todelete) {
6092: $result=&Apache::lonnet::del('nohist_scantrondata',\@todelete,$cdom,$cname);
6093: }
6094: return $result;
6095: }
6096:
6097:
6098: =pod
6099:
6100: =item scantron_getfile
6101:
6102: Fetches the requested bubble sheet data file (all 3 versions), and
6103: the scan_data hash
6104:
6105: Arguments:
6106: None
6107:
6108: Returns:
6109: 2 hash references
6110:
6111: - first one has
6112: orig -
6113: corrected -
6114: skipped - each of which points to an array ref of the specified
6115: file broken up into individual lines
6116: count - number of scanlines
6117:
6118: - second is the scan_data hash possible keys are
6119: ($number refers to scanline numbered $number and thus the key affects
6120: only that scanline
6121: $bubline refers to the specific bubble line element and the aspects
6122: refers to that specific bubble line element)
6123:
6124: $number.user - username:domain to use
6125: $number.CODE_ignore_dup
6126: - ignore the duplicate CODE error
6127: $number.useCODE
6128: - use the CODE in the scanline as is
6129: $number.no_bubble.$bubline
6130: - it is valid that there is no bubbled in bubble
6131: at $number $bubline
6132: remember_skipping
6133: - a frozen hash containing keys of $number and values
6134: of either
6135: 1 - we are on a 'do skipped records pass' and plan
6136: on processing this line
6137: 2 - we are on a 'do skipped records pass' and this
6138: scanline has been marked to skip yet again
6139:
6140: =cut
6141:
6142: sub scantron_getfile {
6143: #FIXME really would prefer a scantron directory
6144: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6145: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6146: my $lines;
6147: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
6148: 'scantron_orig_'.$env{'form.scantron_selectfile'});
6149: my %scanlines;
6150: $scanlines{'orig'}=[(split("\n",$lines,-1))];
6151: my $temp=$scanlines{'orig'};
6152: $scanlines{'count'}=$#$temp;
6153:
6154: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
6155: 'scantron_corrected_'.$env{'form.scantron_selectfile'});
6156: if ($lines eq '-1') {
6157: $scanlines{'corrected'}=[];
6158: } else {
6159: $scanlines{'corrected'}=[(split("\n",$lines,-1))];
6160: }
6161: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
6162: 'scantron_skipped_'.$env{'form.scantron_selectfile'});
6163: if ($lines eq '-1') {
6164: $scanlines{'skipped'}=[];
6165: } else {
6166: $scanlines{'skipped'}=[(split("\n",$lines,-1))];
6167: }
6168: my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
6169: if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
6170: my %scan_data = @tmp;
6171: return (\%scanlines,\%scan_data);
6172: }
6173:
6174: =pod
6175:
6176: =item lonnet_putfile
6177:
6178: Wrapper routine to call &Apache::lonnet::finishuserfileupload
6179:
6180: Arguments:
6181: $contents - data to store
6182: $filename - filename to store $contents into
6183:
6184: Returns:
6185: result value from &Apache::lonnet::finishuserfileupload
6186:
6187: =cut
6188:
6189: sub lonnet_putfile {
6190: my ($contents,$filename)=@_;
6191: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
6192: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6193: $env{'form.sillywaytopassafilearound'}=$contents;
6194: &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
6195:
6196: }
6197:
6198: =pod
6199:
6200: =item scantron_putfile
6201:
6202: Stores the current version of the bubble sheet data files, and the
6203: scan_data hash. (Does not modify the original version only the
6204: corrected and skipped versions.
6205:
6206: Arguments:
6207: $scanlines - hash ref that looks like the first return value from
6208: &scantron_getfile()
6209: $scan_data - hash ref that looks like the second return value from
6210: &scantron_getfile()
6211:
6212: =cut
6213:
6214: sub scantron_putfile {
6215: my ($scanlines,$scan_data) = @_;
6216: #FIXME really would prefer a scantron directory
6217: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6218: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6219: if ($scanlines) {
6220: my $prefix='scantron_';
6221: # no need to update orig, shouldn't change
6222: # &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
6223: # $env{'form.scantron_selectfile'});
6224: &lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
6225: $prefix.'corrected_'.
6226: $env{'form.scantron_selectfile'});
6227: &lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
6228: $prefix.'skipped_'.
6229: $env{'form.scantron_selectfile'});
6230: }
6231: &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
6232: }
6233:
6234: =pod
6235:
6236: =item scantron_get_line
6237:
6238: Returns the correct version of the scanline
6239:
6240: Arguments:
6241: $scanlines - hash ref that looks like the first return value from
6242: &scantron_getfile()
6243: $scan_data - hash ref that looks like the second return value from
6244: &scantron_getfile()
6245: $i - number of the requested line (starts at 0)
6246:
6247: Returns:
6248: A scanline, (either the original or the corrected one if it
6249: exists), or undef if the requested scanline should be
6250: skipped. (Either because it's an skipped scanline, or it's an
6251: unskipped scanline and we are not doing a 'do skipped scanlines'
6252: pass.
6253:
6254: =cut
6255:
6256: sub scantron_get_line {
6257: my ($scanlines,$scan_data,$i)=@_;
6258: if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
6259: #if ($scanlines->{'skipped'}[$i]) { return undef; }
6260: if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
6261: return $scanlines->{'orig'}[$i];
6262: }
6263:
6264: =pod
6265:
6266: =item scantron_todo_count
6267:
6268: Counts the number of scanlines that need processing.
6269:
6270: Arguments:
6271: $scanlines - hash ref that looks like the first return value from
6272: &scantron_getfile()
6273: $scan_data - hash ref that looks like the second return value from
6274: &scantron_getfile()
6275:
6276: Returns:
6277: $count - number of scanlines to process
6278:
6279: =cut
6280:
6281: sub get_todo_count {
6282: my ($scanlines,$scan_data)=@_;
6283: my $count=0;
6284: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6285: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6286: if ($line=~/^[\s\cz]*$/) { next; }
6287: $count++;
6288: }
6289: return $count;
6290: }
6291:
6292: =pod
6293:
6294: =item scantron_put_line
6295:
6296: Updates the 'corrected' or 'skipped' versions of the bubble sheet
6297: data file.
6298:
6299: Arguments:
6300: $scanlines - hash ref that looks like the first return value from
6301: &scantron_getfile()
6302: $scan_data - hash ref that looks like the second return value from
6303: &scantron_getfile()
6304: $i - line number to update
6305: $newline - contents of the updated scanline
6306: $skip - if true make the line for skipping and update the
6307: 'skipped' file
6308:
6309: =cut
6310:
6311: sub scantron_put_line {
6312: my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
6313: if ($skip) {
6314: $scanlines->{'skipped'}[$i]=$newline;
6315: &start_skipping($scan_data,$i);
6316: return;
6317: }
6318: $scanlines->{'corrected'}[$i]=$newline;
6319: }
6320:
6321: =pod
6322:
6323: =item scantron_clear_skip
6324:
6325: Remove a line from the 'skipped' file
6326:
6327: Arguments:
6328: $scanlines - hash ref that looks like the first return value from
6329: &scantron_getfile()
6330: $scan_data - hash ref that looks like the second return value from
6331: &scantron_getfile()
6332: $i - line number to update
6333:
6334: =cut
6335:
6336: sub scantron_clear_skip {
6337: my ($scanlines,$scan_data,$i)=@_;
6338: if (exists($scanlines->{'skipped'}[$i])) {
6339: undef($scanlines->{'skipped'}[$i]);
6340: return 1;
6341: }
6342: return 0;
6343: }
6344:
6345: =pod
6346:
6347: =item scantron_filter_not_exam
6348:
6349: Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
6350: filter out resources that are not marked as 'exam' mode
6351:
6352: =cut
6353:
6354: sub scantron_filter_not_exam {
6355: my ($curres)=@_;
6356:
6357: if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
6358: # if the user has asked to not have either hidden
6359: # or 'randomout' controlled resources to be graded
6360: # don't include them
6361: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
6362: && $curres->randomout) {
6363: return 0;
6364: }
6365: return 1;
6366: }
6367: return 0;
6368: }
6369:
6370: =pod
6371:
6372: =item scantron_validate_sequence
6373:
6374: Validates the selected sequence, checking for resource that are
6375: not set to exam mode.
6376:
6377: =cut
6378:
6379: sub scantron_validate_sequence {
6380: my ($r,$currentphase) = @_;
6381:
6382: my $navmap=Apache::lonnavmaps::navmap->new();
6383: my (undef,undef,$sequence)=
6384: &Apache::lonnet::decode_symb($env{'form.selectpage'});
6385:
6386: my $map=$navmap->getResourceByUrl($sequence);
6387:
6388: $r->print('<input type="hidden" name="validate_sequence_exam"
6389: value="ignore" />');
6390: if ($env{'form.validate_sequence_exam'} ne 'ignore') {
6391: my @resources=
6392: $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
6393: if (@resources) {
6394: $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>");
6395: return (1,$currentphase);
6396: }
6397: }
6398:
6399: return (0,$currentphase+1);
6400: }
6401:
6402: =pod
6403:
6404: =item scantron_validate_ID
6405:
6406: Validates all scanlines in the selected file to not have any
6407: invalid or underspecified student IDs
6408:
6409: =cut
6410:
6411: sub scantron_validate_ID {
6412: my ($r,$currentphase) = @_;
6413:
6414: #get student info
6415: my $classlist=&Apache::loncoursedata::get_classlist();
6416: my %idmap=&username_to_idmap($classlist);
6417:
6418: #get scantron line setup
6419: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6420: my ($scanlines,$scan_data)=&scantron_getfile();
6421:
6422: &scantron_get_maxbubble(); # parse needs the bubble_lines.. array.
6423:
6424: my %found=('ids'=>{},'usernames'=>{});
6425: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6426: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6427: if ($line=~/^[\s\cz]*$/) { next; }
6428: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6429: $scan_data);
6430: my $id=$$scan_record{'scantron.ID'};
6431: my $found;
6432: foreach my $checkid (keys(%idmap)) {
6433: if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
6434: }
6435: if ($found) {
6436: my $username=$idmap{$found};
6437: if ($found{'ids'}{$found}) {
6438: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6439: $line,'duplicateID',$found);
6440: return(1,$currentphase);
6441: } elsif ($found{'usernames'}{$username}) {
6442: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6443: $line,'duplicateID',$username);
6444: return(1,$currentphase);
6445: }
6446: #FIXME store away line we previously saw the ID on to use above
6447: $found{'ids'}{$found}++;
6448: $found{'usernames'}{$username}++;
6449: } else {
6450: if ($id =~ /^\s*$/) {
6451: my $username=&scan_data($scan_data,"$i.user");
6452: if (defined($username) && $found{'usernames'}{$username}) {
6453: &scantron_get_correction($r,$i,$scan_record,
6454: \%scantron_config,
6455: $line,'duplicateID',$username);
6456: return(1,$currentphase);
6457: } elsif (!defined($username)) {
6458: &scantron_get_correction($r,$i,$scan_record,
6459: \%scantron_config,
6460: $line,'incorrectID');
6461: return(1,$currentphase);
6462: }
6463: $found{'usernames'}{$username}++;
6464: } else {
6465: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6466: $line,'incorrectID');
6467: return(1,$currentphase);
6468: }
6469: }
6470: }
6471:
6472: return (0,$currentphase+1);
6473: }
6474:
6475: =pod
6476:
6477: =item scantron_get_correction
6478:
6479: Builds the interface screen to interact with the operator to fix a
6480: specific error condition in a specific scanline
6481:
6482: Arguments:
6483: $r - Apache request object
6484: $i - number of the current scanline
6485: $scan_record - hash ref as returned from &scantron_parse_scanline()
6486: $scan_config - hash ref as returned from &get_scantron_config()
6487: $line - full contents of the current scanline
6488: $error - error condition, valid values are
6489: 'incorrectCODE', 'duplicateCODE',
6490: 'doublebubble', 'missingbubble',
6491: 'duplicateID', 'incorrectID'
6492: $arg - extra information needed
6493: For errors:
6494: - duplicateID - paper number that this studentID was seen before on
6495: - duplicateCODE - array ref of the paper numbers this CODE was
6496: seen on before
6497: - incorrectCODE - current incorrect CODE
6498: - doublebubble - array ref of the bubble lines that have double
6499: bubble errors
6500: - missingbubble - array ref of the bubble lines that have missing
6501: bubble errors
6502:
6503: =cut
6504:
6505: sub scantron_get_correction {
6506: my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
6507:
6508: #FIXME in the case of a duplicated ID the previous line, probably need
6509: #to show both the current line and the previous one and allow skipping
6510: #the previous one or the current one
6511:
6512: $r->print("<p><b>An error was detected ($error)</b>");
6513: if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
6514: $r->print(" for PaperID <tt>".
6515: $$scan_record{'scantron.PaperID'}."</tt> \n");
6516: } else {
6517: $r->print(" in scanline $i <pre>".
6518: $line."</pre> \n");
6519: }
6520: my $message="<p>The ID on the form is <tt>".
6521: $$scan_record{'scantron.ID'}."</tt><br />\n".
6522: "The name on the paper is ".
6523: $$scan_record{'scantron.LastName'}.",".
6524: $$scan_record{'scantron.FirstName'}."</p>";
6525:
6526: $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
6527: $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
6528: if ($error =~ /ID$/) {
6529: if ($error eq 'incorrectID') {
6530: $r->print("The encoded ID is not in the classlist</p>\n");
6531: } elsif ($error eq 'duplicateID') {
6532: $r->print("The encoded ID has also been used by a previous paper $arg</p>\n");
6533: }
6534: $r->print($message);
6535: $r->print("<p>How should I handle this? <br /> \n");
6536: $r->print("\n<ul><li> ");
6537: #FIXME it would be nice if this sent back the user ID and
6538: #could do partial userID matches
6539: $r->print(&Apache::loncommon::selectstudent_link('scantronupload',
6540: 'scantron_username','scantron_domain'));
6541: $r->print(": <input type='text' name='scantron_username' value='' />");
6542: $r->print("\n@".
6543: &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
6544:
6545: $r->print('</li>');
6546: } elsif ($error =~ /CODE$/) {
6547: if ($error eq 'incorrectCODE') {
6548: $r->print("</p><p>The encoded CODE is not in the list of possible CODEs</p>\n");
6549: } elsif ($error eq 'duplicateCODE') {
6550: $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");
6551: }
6552: $r->print("<p>The CODE on the form is <tt>'".
6553: $$scan_record{'scantron.CODE'}."'</tt><br />\n");
6554: $r->print($message);
6555: $r->print("<p>How should I handle this? <br /> \n");
6556: $r->print("\n<br /> ");
6557: my $i=0;
6558: if ($error eq 'incorrectCODE'
6559: && $$scan_record{'scantron.CODE'}=~/\S/ ) {
6560: my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
6561: if ($closest > 0) {
6562: foreach my $testcode (@{$closest}) {
6563: my $checked='';
6564: if (!$i) { $checked=' checked="checked" '; }
6565: $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' />");
6566: $r->print("\n<br />");
6567: $i++;
6568: }
6569: }
6570: }
6571: if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
6572: my $checked; if (!$i) { $checked=' checked="checked" '; }
6573: $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>");
6574: $r->print("\n<br />");
6575: }
6576:
6577: $r->print(<<ENDSCRIPT);
6578: <script type="text/javascript">
6579: function change_radio(field) {
6580: var slct=document.scantronupload.scantron_CODE_resolution;
6581: var i;
6582: for (i=0;i<slct.length;i++) {
6583: if (slct[i].value==field) { slct[i].checked=true; }
6584: }
6585: }
6586: </script>
6587: ENDSCRIPT
6588: my $href="/adm/pickcode?".
6589: "form=".&escape("scantronupload").
6590: "&scantron_format=".&escape($env{'form.scantron_format'}).
6591: "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
6592: "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
6593: "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
6594: if ($env{'form.scantron_CODElist'} =~ /\S/) {
6595: $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')\" />");
6596: $r->print("\n<br />");
6597: }
6598: $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.");
6599: $r->print("\n<br /><br />");
6600: } elsif ($error eq 'doublebubble') {
6601: $r->print("<p>There have been multiple bubbles scanned for a some question(s)</p>\n");
6602: $r->print('<input type="hidden" name="scantron_questions" value="'.
6603: join(',',@{$arg}).'" />');
6604: $r->print($message);
6605: $r->print("<p>Please indicate which bubble should be used for grading</p>");
6606: foreach my $question (@{$arg}) {
6607: my $selected = &get_response_bubbles($scan_record, $question);
6608: my @select_array = split(/:/,$selected);
6609: &scantron_bubble_selector($r,$scan_config,$question,
6610: @select_array);
6611: }
6612: } elsif ($error eq 'missingbubble') {
6613: $r->print("<p>There have been <b>no</b> bubbles scanned for some question(s)</p>\n");
6614: $r->print($message);
6615: $r->print("<p>Please indicate which bubble should be used for grading</p>");
6616: $r->print("Some questions have no scanned bubbles\n");
6617: $r->print('<input type="hidden" name="scantron_questions" value="'.
6618: join(',',@{$arg}).'" />');
6619: foreach my $question (@{$arg}) {
6620: my $selected = &get_response_bubbles($scan_record, $question);
6621: my @select_array = split(/:/,$selected); # ought to be an array of empties.
6622: &scantron_bubble_selector($r,$scan_config,$question, @select_array);
6623: }
6624: } else {
6625: $r->print("\n<ul>");
6626: }
6627: $r->print("\n</li></ul>");
6628:
6629: }
6630:
6631: =pod
6632:
6633: =item scantron_bubble_selector
6634:
6635: Generates the html radiobuttons to correct a single bubble line
6636: possibly showing the existing the selected bubbles if known
6637:
6638: Arguments:
6639: $r - Apache request object
6640: $scan_config - hash from &get_scantron_config()
6641: $quest - number of the bubble line to make a corrector for
6642: @lines - array of answer lines.
6643:
6644: =cut
6645:
6646: sub scantron_bubble_selector {
6647: my ($r,$scan_config,$quest,@lines)=@_;
6648: my $max=$$scan_config{'Qlength'};
6649:
6650:
6651: my $scmode=$$scan_config{'Qon'};
6652:
6653: my $bubble_length = scalar(@lines);
6654:
6655:
6656: if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }
6657:
6658: my $response = $quest-1;
6659: my $lines = $bubble_lines_per_response{$response};
6660:
6661: my $total_lines = $lines*2;
6662: my @alphabet=('A'..'Z');
6663:
6664: $r->print("<table border='1'><tr><td rowspan='".$total_lines."'>$quest</td>");
6665:
6666: for (my $l = 0; $l < $lines; $l++) {
6667: if ($l != 0) {
6668: $r->print('<tr>');
6669: }
6670: my @selected = split(//,$lines[$l]);
6671: for (my $i=0;$i<$max;$i++) {
6672: $r->print("\n".'<td align="center">');
6673: if ($selected[0] eq $alphabet[$i]) {
6674: $r->print('X');
6675: shift(@selected) ;
6676: } else {
6677: $r->print(' ');
6678: }
6679: $r->print('</td>');
6680:
6681: }
6682:
6683: if ($l == 0) {
6684: my $lspan = $total_lines * 2; # 2 table rows per bubble line.
6685:
6686: $r->print('<td rowspan='.$lspan.'><label><input type="radio" name="scantron_correct_Q_'.
6687: $quest.'" value="none" /> No bubble </label></td>');
6688:
6689: }
6690:
6691: $r->print('</tr><tr>');
6692:
6693: # FIXME: This may have to be a bit more clever for
6694: # multiline questions (different values e.g..).
6695:
6696: for (my $i=0;$i<$max;$i++) {
6697: my $value = "$l:$i"; # Relative bubble line #: Bubble in line.
6698: $r->print("\n".
6699: '<td><label><input type="radio" name="scantron_correct_Q_'.
6700: $quest.'" value="'.$value.'" />'.$alphabet[$i]."</label></td>");
6701: }
6702: $r->print('</tr>');
6703:
6704:
6705: }
6706: $r->print('</table>');
6707: }
6708:
6709: =pod
6710:
6711: =item num_matches
6712:
6713: Counts the number of characters that are the same between the two arguments.
6714:
6715: Arguments:
6716: $orig - CODE from the scanline
6717: $code - CODE to match against
6718:
6719: Returns:
6720: $count - integer count of the number of same characters between the
6721: two arguments
6722:
6723: =cut
6724:
6725: sub num_matches {
6726: my ($orig,$code) = @_;
6727: my @code=split(//,$code);
6728: my @orig=split(//,$orig);
6729: my $same=0;
6730: for (my $i=0;$i<scalar(@code);$i++) {
6731: if ($code[$i] eq $orig[$i]) { $same++; }
6732: }
6733: return $same;
6734: }
6735:
6736: =pod
6737:
6738: =item scantron_get_closely_matching_CODEs
6739:
6740: Cycles through all CODEs and finds the set that has the greatest
6741: number of same characters as the provided CODE
6742:
6743: Arguments:
6744: $allcodes - hash ref returned by &get_codes()
6745: $CODE - CODE from the current scanline
6746:
6747: Returns:
6748: 2 element list
6749: - first elements is number of how closely matching the best fit is
6750: (5 means best set has 5 matching characters)
6751: - second element is an arrary ref containing the set of valid CODEs
6752: that best fit the passed in CODE
6753:
6754: =cut
6755:
6756: sub scantron_get_closely_matching_CODEs {
6757: my ($allcodes,$CODE)=@_;
6758: my @CODEs;
6759: foreach my $testcode (sort(keys(%{$allcodes}))) {
6760: push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
6761: }
6762:
6763: return ($#CODEs,$CODEs[-1]);
6764: }
6765:
6766: =pod
6767:
6768: =item get_codes
6769:
6770: Builds a hash which has keys of all of the valid CODEs from the selected
6771: set of remembered CODEs.
6772:
6773: Arguments:
6774: $old_name - name of the set of remembered CODEs
6775: $cdom - domain of the course
6776: $cnum - internal course name
6777:
6778: Returns:
6779: %allcodes - keys are the valid CODEs, values are all 1
6780:
6781: =cut
6782:
6783: sub get_codes {
6784: my ($old_name, $cdom, $cnum) = @_;
6785: if (!$old_name) {
6786: $old_name=$env{'form.scantron_CODElist'};
6787: }
6788: if (!$cdom) {
6789: $cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
6790: }
6791: if (!$cnum) {
6792: $cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
6793: }
6794: my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
6795: $cdom,$cnum);
6796: my %allcodes;
6797: if ($result{"type\0$old_name"} eq 'number') {
6798: %allcodes=map {($_,1)} split(',',$result{$old_name});
6799: } else {
6800: %allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
6801: }
6802: return %allcodes;
6803: }
6804:
6805: =pod
6806:
6807: =item scantron_validate_CODE
6808:
6809: Validates all scanlines in the selected file to not have any
6810: invalid or underspecified CODEs and that none of the codes are
6811: duplicated if this was requested.
6812:
6813: =cut
6814:
6815: sub scantron_validate_CODE {
6816: my ($r,$currentphase) = @_;
6817: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6818: if ($scantron_config{'CODElocation'} &&
6819: $scantron_config{'CODEstart'} &&
6820: $scantron_config{'CODElength'}) {
6821: if (!defined($env{'form.scantron_CODElist'})) {
6822: &FIXME_blow_up()
6823: }
6824: } else {
6825: return (0,$currentphase+1);
6826: }
6827:
6828: my %usedCODEs;
6829:
6830: my %allcodes=&get_codes();
6831:
6832: &scantron_get_maxbubble(); # parse needs the lines per response array.
6833:
6834: my ($scanlines,$scan_data)=&scantron_getfile();
6835: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6836: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6837: if ($line=~/^[\s\cz]*$/) { next; }
6838: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6839: $scan_data);
6840: my $CODE=$$scan_record{'scantron.CODE'};
6841: my $error=0;
6842: if (!&Apache::lonnet::validCODE($CODE)) {
6843: &scantron_get_correction($r,$i,$scan_record,
6844: \%scantron_config,
6845: $line,'incorrectCODE',\%allcodes);
6846: return(1,$currentphase);
6847: }
6848: if (%allcodes && !exists($allcodes{$CODE})
6849: && !$$scan_record{'scantron.useCODE'}) {
6850: &scantron_get_correction($r,$i,$scan_record,
6851: \%scantron_config,
6852: $line,'incorrectCODE',\%allcodes);
6853: return(1,$currentphase);
6854: }
6855: if (exists($usedCODEs{$CODE})
6856: && $env{'form.scantron_CODEunique'} eq 'yes'
6857: && !$$scan_record{'scantron.CODE_ignore_dup'}) {
6858: &scantron_get_correction($r,$i,$scan_record,
6859: \%scantron_config,
6860: $line,'duplicateCODE',$usedCODEs{$CODE});
6861: return(1,$currentphase);
6862: }
6863: push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
6864: }
6865: return (0,$currentphase+1);
6866: }
6867:
6868: =pod
6869:
6870: =item scantron_validate_doublebubble
6871:
6872: Validates all scanlines in the selected file to not have any
6873: bubble lines with multiple bubbles marked.
6874:
6875: =cut
6876:
6877: sub scantron_validate_doublebubble {
6878: my ($r,$currentphase) = @_;
6879: #get student info
6880: my $classlist=&Apache::loncoursedata::get_classlist();
6881: my %idmap=&username_to_idmap($classlist);
6882:
6883: #get scantron line setup
6884: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6885: my ($scanlines,$scan_data)=&scantron_getfile();
6886:
6887: &scantron_get_maxbubble(); # parse needs the bubble line array.
6888:
6889: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6890: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6891: if ($line=~/^[\s\cz]*$/) { next; }
6892: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6893: $scan_data);
6894: if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
6895: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
6896: 'doublebubble',
6897: $$scan_record{'scantron.doubleerror'});
6898: return (1,$currentphase);
6899: }
6900: return (0,$currentphase+1);
6901: }
6902:
6903: =pod
6904:
6905: =item scantron_get_maxbubble
6906:
6907: Returns the maximum number of bubble lines that are expected to
6908: occur. Does this by walking the selected sequence rendering the
6909: resource and then checking &Apache::lonxml::get_problem_counter()
6910: for what the current value of the problem counter is.
6911:
6912: Caches the results to $env{'form.scantron_maxbubble'},
6913: $env{'form.scantron.bubble_lines.n'} and
6914: $env{'form.scantron.first_bubble_line.n'}
6915: which are the total number of bubble, lines, the number of bubble
6916: lines for reponse n and number of the first bubble line for response n.
6917:
6918: =cut
6919:
6920: sub scantron_get_maxbubble {
6921: if (defined($env{'form.scantron_maxbubble'}) &&
6922: $env{'form.scantron_maxbubble'}) {
6923: &restore_bubble_lines();
6924: return $env{'form.scantron_maxbubble'};
6925: }
6926:
6927: my (undef, undef, $sequence) =
6928: &Apache::lonnet::decode_symb($env{'form.selectpage'});
6929:
6930: my $navmap=Apache::lonnavmaps::navmap->new();
6931: my $map=$navmap->getResourceByUrl($sequence);
6932: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
6933:
6934: &Apache::lonxml::clear_problem_counter();
6935:
6936: my $uname = $env{'form.student'};
6937: my $udom = $env{'form.userdom'};
6938: my $cid = $env{'request.course.id'};
6939: my $total_lines = 0;
6940: %bubble_lines_per_response = ();
6941: %first_bubble_line = ();
6942:
6943:
6944: my $response_number = 0;
6945: my $bubble_line = 0;
6946: foreach my $resource (@resources) {
6947: my $symb = $resource->symb();
6948: &Apache::lonxml::clear_bubble_lines_for_part();
6949: my $result=&Apache::lonnet::ssi($resource->src(),
6950: ('symb' => $resource->symb()),
6951: ('grade_target' => 'analyze'),
6952: ('grade_courseid' => $cid),
6953: ('grade_domain' => $udom),
6954: ('grade_username' => $uname));
6955: my (undef, $an) =
6956: split(/_HASH_REF__/,$result, 2);
6957:
6958: my %analysis = &Apache::lonnet::str2hash($an);
6959:
6960:
6961:
6962: foreach my $part_id (@{$analysis{'parts'}}) {
6963:
6964:
6965: my $lines = $analysis{"$part_id.bubble_lines"};;
6966:
6967: # TODO - make this a persistent hash not an array.
6968:
6969:
6970: $first_bubble_line{$response_number} = $bubble_line;
6971: $bubble_lines_per_response{$response_number} = $lines;
6972: $response_number++;
6973:
6974: $bubble_line += $lines;
6975: $total_lines += $lines;
6976: }
6977:
6978: }
6979: &Apache::lonnet::delenv('scantron\.');
6980:
6981: &save_bubble_lines();
6982: $env{'form.scantron_maxbubble'} =
6983: $total_lines;
6984: return $env{'form.scantron_maxbubble'};
6985: }
6986:
6987: =pod
6988:
6989: =item scantron_validate_missingbubbles
6990:
6991: Validates all scanlines in the selected file to not have any
6992: answers that don't have bubbles that have not been verified
6993: to be bubble free.
6994:
6995: =cut
6996:
6997: sub scantron_validate_missingbubbles {
6998: my ($r,$currentphase) = @_;
6999: #get student info
7000: my $classlist=&Apache::loncoursedata::get_classlist();
7001: my %idmap=&username_to_idmap($classlist);
7002:
7003: #get scantron line setup
7004: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7005: my ($scanlines,$scan_data)=&scantron_getfile();
7006: my $max_bubble=&scantron_get_maxbubble();
7007: if (!$max_bubble) { $max_bubble=2**31; }
7008: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7009: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7010: if ($line=~/^[\s\cz]*$/) { next; }
7011: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7012: $scan_data);
7013: if (!defined($$scan_record{'scantron.missingerror'})) { next; }
7014: my @to_correct;
7015:
7016: # Probably here's where the error is...
7017:
7018: foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
7019: if ($missing > $max_bubble) { next; }
7020: push(@to_correct,$missing);
7021: }
7022: if (@to_correct) {
7023: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
7024: $line,'missingbubble',\@to_correct);
7025: return (1,$currentphase);
7026: }
7027:
7028: }
7029: return (0,$currentphase+1);
7030: }
7031:
7032: =pod
7033:
7034: =item scantron_process_students
7035:
7036: Routine that does the actual grading of the bubble sheet information.
7037:
7038: The parsed scanline hash is added to %env
7039:
7040: Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
7041: foreach resource , with the form data of
7042:
7043: 'submitted' =>'scantron'
7044: 'grade_target' =>'grade',
7045: 'grade_username'=> username of student
7046: 'grade_domain' => domain of student
7047: 'grade_courseid'=> of course
7048: 'grade_symb' => symb of resource to grade
7049:
7050: This triggers a grading pass. The problem grading code takes care
7051: of converting the bubbled letter information (now in %env) into a
7052: valid submission.
7053:
7054: =cut
7055:
7056: sub scantron_process_students {
7057: my ($r) = @_;
7058: my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
7059: my ($symb)=&get_symb($r);
7060: if (!$symb) {return '';}
7061: my $default_form_data=&defaultFormData($symb);
7062:
7063: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7064: my ($scanlines,$scan_data)=&scantron_getfile();
7065: my $classlist=&Apache::loncoursedata::get_classlist();
7066: my %idmap=&username_to_idmap($classlist);
7067: my $navmap=Apache::lonnavmaps::navmap->new();
7068: my $map=$navmap->getResourceByUrl($sequence);
7069: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
7070: # $r->print("geto ".scalar(@resources)."<br />");
7071: my $result= <<SCANTRONFORM;
7072: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
7073: <input type="hidden" name="command" value="scantron_configphase" />
7074: $default_form_data
7075: SCANTRONFORM
7076: $r->print($result);
7077:
7078: my @delayqueue;
7079: my %completedstudents;
7080:
7081: my $count=&get_todo_count($scanlines,$scan_data);
7082: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
7083: 'Scantron Progress',$count,
7084: 'inline',undef,'scantronupload');
7085: &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
7086: 'Processing first student');
7087: my $start=&Time::HiRes::time();
7088: my $i=-1;
7089: my ($uname,$udom,$started);
7090:
7091: &scantron_get_maxbubble(); # Need the bubble lines array to parse.
7092:
7093: while ($i<$scanlines->{'count'}) {
7094: ($uname,$udom)=('','');
7095: $i++;
7096: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7097: if ($line=~/^[\s\cz]*$/) { next; }
7098: if ($started) {
7099: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
7100: 'last student');
7101: }
7102: $started=1;
7103: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7104: $scan_data);
7105: unless ($uname=&scantron_find_student($scan_record,$scan_data,
7106: \%idmap,$i)) {
7107: &scantron_add_delay(\@delayqueue,$line,
7108: 'Unable to find a student that matches',1);
7109: next;
7110: }
7111: if (exists $completedstudents{$uname}) {
7112: &scantron_add_delay(\@delayqueue,$line,
7113: 'Student '.$uname.' has multiple sheets',2);
7114: next;
7115: }
7116: ($uname,$udom)=split(/:/,$uname);
7117:
7118: &Apache::lonxml::clear_problem_counter();
7119: &Apache::lonnet::appenv(%$scan_record);
7120:
7121: if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
7122: &scantron_putfile($scanlines,$scan_data);
7123: }
7124:
7125: my $i=0;
7126: foreach my $resource (@resources) {
7127: $i++;
7128: my %form=('submitted' =>'scantron',
7129: 'grade_target' =>'grade',
7130: 'grade_username'=>$uname,
7131: 'grade_domain' =>$udom,
7132: 'grade_courseid'=>$env{'request.course.id'},
7133: 'grade_symb' =>$resource->symb());
7134: if (exists($scan_record->{'scantron.CODE'})
7135: &&
7136: &Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
7137: $form{'CODE'}=$scan_record->{'scantron.CODE'};
7138: } else {
7139: $form{'CODE'}='';
7140: }
7141: my $result=&Apache::lonnet::ssi($resource->src(),%form);
7142: if ($result ne '') {
7143: }
7144: if (&Apache::loncommon::connection_aborted($r)) { last; }
7145: }
7146: $completedstudents{$uname}={'line'=>$line};
7147: if (&Apache::loncommon::connection_aborted($r)) { last; }
7148: } continue {
7149: &Apache::lonxml::clear_problem_counter();
7150: &Apache::lonnet::delenv('scantron\.');
7151: }
7152: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
7153: # my $lasttime = &Time::HiRes::time()-$start;
7154: # $r->print("<p>took $lasttime</p>");
7155:
7156: $r->print("</form>");
7157: $r->print(&show_grading_menu_form($symb));
7158: return '';
7159: }
7160:
7161: =pod
7162:
7163: =item scantron_upload_scantron_data
7164:
7165: Creates the screen for adding a new bubble sheet data file to a course.
7166:
7167: =cut
7168:
7169: sub scantron_upload_scantron_data {
7170: my ($r)=@_;
7171: $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
7172: my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
7173: 'domainid',
7174: 'coursename');
7175: my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
7176: 'domainid');
7177: my $default_form_data=&defaultFormData(&get_symb($r,1));
7178: $r->print(<<UPLOAD);
7179: <script type="text/javascript" language="javascript">
7180: function checkUpload(formname) {
7181: if (formname.upfile.value == "") {
7182: alert("Please use the browse button to select a file from your local directory.");
7183: return false;
7184: }
7185: formname.submit();
7186: }
7187: </script>
7188:
7189: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
7190: $default_form_data
7191: <table>
7192: <tr><td>$select_link </td></tr>
7193: <tr><td>Course ID: </td><td><input name='courseid' type='text' /> </td></tr>
7194: <tr><td>Course Name: </td><td><input name='coursename' type='text' /></td></tr>
7195: <tr><td>Domain: </td><td>$domsel </td></tr>
7196: <tr><td>File to upload:</td><td><input type="file" name="upfile" size="50" /></td></tr>
7197: </table>
7198: <input name='command' value='scantronupload_save' type='hidden' />
7199: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
7200: </form>
7201: UPLOAD
7202: return '';
7203: }
7204:
7205: =pod
7206:
7207: =item scantron_upload_scantron_data_save
7208:
7209: Adds a provided bubble information data file to the course if user
7210: has the correct privileges to do so.
7211:
7212: =cut
7213:
7214: sub scantron_upload_scantron_data_save {
7215: my($r)=@_;
7216: my ($symb)=&get_symb($r,1);
7217: my $doanotherupload=
7218: '<br /><form action="/adm/grades" method="post">'."\n".
7219: '<input type="hidden" name="command" value="scantronupload" />'."\n".
7220: '<input type="submit" name="submit" value="Do Another Upload" />'."\n".
7221: '</form>'."\n";
7222: if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
7223: !&Apache::lonnet::allowed('usc',
7224: $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
7225: $r->print("You are not allowed to upload Scantron data to the requested course.<br />");
7226: if ($symb) {
7227: $r->print(&show_grading_menu_form($symb));
7228: } else {
7229: $r->print($doanotherupload);
7230: }
7231: return '';
7232: }
7233: my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
7234: $r->print("Doing upload to ".$coursedata{'description'}." <br />");
7235: my $fname=$env{'form.upfile.filename'};
7236: #FIXME
7237: #copied from lonnet::userfileupload()
7238: #make that function able to target a specified course
7239: # Replace Windows backslashes by forward slashes
7240: $fname=~s/\\/\//g;
7241: # Get rid of everything but the actual filename
7242: $fname=~s/^.*\/([^\/]+)$/$1/;
7243: # Replace spaces by underscores
7244: $fname=~s/\s+/\_/g;
7245: # Replace all other weird characters by nothing
7246: $fname=~s/[^\w\.\-]//g;
7247: # See if there is anything left
7248: unless ($fname) { return 'error: no uploaded file'; }
7249: my $uploadedfile=$fname;
7250: $fname='scantron_orig_'.$fname;
7251: if (length($env{'form.upfile'}) < 2) {
7252: $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.");
7253: } else {
7254: my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
7255: if ($result =~ m|^/uploaded/|) {
7256: $r->print("<span class=\"LC_success\">Success:</span> Successfully uploaded ".(length($env{'form.upfile'})-1)." bytes of data into location <tt>".$result."</tt>");
7257: } else {
7258: $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>");
7259: }
7260: }
7261: if ($symb) {
7262: $r->print(&scantron_selectphase($r,$uploadedfile));
7263: } else {
7264: $r->print($doanotherupload);
7265: }
7266: return '';
7267: }
7268:
7269: =pod
7270:
7271: =item valid_file
7272:
7273: Validates that the requested bubble data file exists in the course.
7274:
7275: =cut
7276:
7277: sub valid_file {
7278: my ($requested_file)=@_;
7279: foreach my $filename (sort(&scantron_filenames())) {
7280: if ($requested_file eq $filename) { return 1; }
7281: }
7282: return 0;
7283: }
7284:
7285: =pod
7286:
7287: =item scantron_download_scantron_data
7288:
7289: Shows a list of the three internal files (original, corrected,
7290: skipped) for a specific bubble sheet data file that exists in the
7291: course.
7292:
7293: =cut
7294:
7295: sub scantron_download_scantron_data {
7296: my ($r)=@_;
7297: my $default_form_data=&defaultFormData(&get_symb($r,1));
7298: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7299: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7300: my $file=$env{'form.scantron_selectfile'};
7301: if (! &valid_file($file)) {
7302: $r->print(<<ERROR);
7303: <p>
7304: The requested file name was invalid.
7305: </p>
7306: ERROR
7307: $r->print(&show_grading_menu_form(&get_symb($r,1)));
7308: return;
7309: }
7310: my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
7311: my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
7312: my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
7313: &Apache::lonnet::allowuploaded('/adm/grades',$orig);
7314: &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
7315: &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
7316: $r->print(<<DOWNLOAD);
7317: <p>
7318: <a href="$orig">Original</a> file as uploaded by the scantron office.
7319: </p>
7320: <p>
7321: <a href="$corrected">Corrections</a>, a file of corrected records that were used in grading.
7322: </p>
7323: <p>
7324: <a href="$skipped">Skipped</a>, a file of records that were skipped.
7325: </p>
7326: DOWNLOAD
7327: $r->print(&show_grading_menu_form(&get_symb($r,1)));
7328: return '';
7329: }
7330:
7331: =pod
7332:
7333: =back
7334:
7335: =cut
7336:
7337: #-------- end of section for handling grading scantron forms -------
7338: #
7339: #-------------------------------------------------------------------
7340:
7341: #-------------------------- Menu interface -------------------------
7342: #
7343: #--- Show a Grading Menu button - Calls the next routine ---
7344: sub show_grading_menu_form {
7345: my ($symb)=@_;
7346: my $result.='<br /><form action="/adm/grades" method="post">'."\n".
7347: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
7348: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
7349: '<input type="hidden" name="command" value="gradingmenu" />'."\n".
7350: '<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
7351: '</form>'."\n";
7352: return $result;
7353: }
7354:
7355: # -- Retrieve choices for grading form
7356: sub savedState {
7357: my %savedState = ();
7358: if ($env{'form.saveState'}) {
7359: foreach (split(/:/,$env{'form.saveState'})) {
7360: my ($key,$value) = split(/=/,$_,2);
7361: $savedState{$key} = $value;
7362: }
7363: }
7364: return \%savedState;
7365: }
7366:
7367: sub grading_menu {
7368: my ($request) = @_;
7369: my ($symb)=&get_symb($request);
7370: if (!$symb) {return '';}
7371: my $probTitle = &Apache::lonnet::gettitle($symb);
7372: my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
7373:
7374: $request->print($table);
7375: my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
7376: 'handgrade'=>$hdgrade,
7377: 'probTitle'=>$probTitle,
7378: 'command'=>'submit_options',
7379: 'saveState'=>"",
7380: 'gradingMenu'=>1,
7381: 'showgrading'=>"yes");
7382: my $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
7383: my @menu = ({ url => $url,
7384: name => &mt('Manual Grading/View Submissions'),
7385: short_description =>
7386: &mt('Start the process of hand grading submissions.'),
7387: });
7388: $fields{'command'} = 'csvform';
7389: $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
7390: push (@menu, { url => $url,
7391: name => &mt('Upload Scores'),
7392: short_description =>
7393: &mt('Specify a file containing the class scores for current resource.')});
7394: $fields{'command'} = 'processclicker';
7395: $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
7396: push (@menu, { url => $url,
7397: name => &mt('Process Clicker'),
7398: short_description =>
7399: &mt('Specify a file containing the clicker information for this resource.')});
7400: $fields{'command'} = 'scantron_selectphase';
7401: $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
7402: push (@menu, { url => $url,
7403: name => &mt('Grade/Manage Scantron Forms'),
7404: short_description =>
7405: &mt('')});
7406: $fields{'command'} = 'verify';
7407: $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
7408: push (@menu, { url => "",
7409: name => &mt('Verify Receipt'),
7410: short_description =>
7411: &mt('')});
7412: #
7413: # Create the menu
7414: my $Str;
7415: # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
7416: $Str .= '<form method="post" action="" name="gradingMenu">';
7417: $Str .= '<input type="hidden" name="command" value="" />'.
7418: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
7419: '<input type="hidden" name="handgrade" value="'.$hdgrade.'" />'."\n".
7420: '<input type="hidden" name="probTitle" value="'.$probTitle.'" />'."\n".
7421: '<input type="hidden" name="saveState" value="" />'."\n".
7422: '<input type="hidden" name="gradingMenu" value="1" />'."\n".
7423: '<input type="hidden" name="showgrading" value="yes" />'."\n";
7424:
7425: foreach my $menudata (@menu) {
7426: if ($menudata->{'name'} ne &mt('Verify Receipt')) {
7427: $Str .=' <h3><a '.
7428: $menudata->{'jscript'}.
7429: ' href="'.
7430: $menudata->{'url'}.'" >'.
7431: $menudata->{'name'}."</a></h3>\n";
7432: } else {
7433: $Str .=' <h3><input type="button" value="'.&mt('Verify Receipt').'" '.
7434: $menudata->{'jscript'}.
7435: ' onClick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
7436: ' /></h3>';
7437: $Str .= (' 'x8).
7438: &mt(' receipt: [_1]',
7439: &Apache::lonnet::recprefix($env{'request.course.id'}).
7440: '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />');
7441: }
7442: $Str .= ' '.(' 'x8).$menudata->{'short_description'}.
7443: "\n";
7444: }
7445: $Str .="</form>\n";
7446: $request->print(<<GRADINGMENUJS);
7447: <script type="text/javascript" language="javascript">
7448: function checkChoice(formname,val,cmdx) {
7449: if (val <= 2) {
7450: var cmd = radioSelection(formname.radioChoice);
7451: var cmdsave = cmd;
7452: } else {
7453: cmd = cmdx;
7454: cmdsave = 'submission';
7455: }
7456: formname.command.value = cmd;
7457: if (val < 5) formname.submit();
7458: if (val == 5) {
7459: if (!checkReceiptNo(formname,'notOK')) {
7460: return false;
7461: } else {
7462: formname.submit();
7463: }
7464: }
7465: }
7466:
7467: function checkReceiptNo(formname,nospace) {
7468: var receiptNo = formname.receipt.value;
7469: var checkOpt = false;
7470: if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
7471: if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
7472: if (checkOpt) {
7473: alert("Please enter a receipt number given by a student in the receipt box.");
7474: formname.receipt.value = "";
7475: formname.receipt.focus();
7476: return false;
7477: }
7478: return true;
7479: }
7480: </script>
7481: GRADINGMENUJS
7482: &commonJSfunctions($request);
7483: return $Str;
7484: }
7485:
7486:
7487: #--- Displays the submissions first page -------
7488: sub submit_options {
7489: my ($request) = @_;
7490: my ($symb)=&get_symb($request);
7491: if (!$symb) {return '';}
7492: my $probTitle = &Apache::lonnet::gettitle($symb);
7493:
7494: $request->print(<<GRADINGMENUJS);
7495: <script type="text/javascript" language="javascript">
7496: function checkChoice(formname,val,cmdx) {
7497: if (val <= 2) {
7498: var cmd = radioSelection(formname.radioChoice);
7499: var cmdsave = cmd;
7500: } else {
7501: cmd = cmdx;
7502: cmdsave = 'submission';
7503: }
7504: formname.command.value = cmd;
7505: formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
7506: ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
7507: if (val < 5) formname.submit();
7508: if (val == 5) {
7509: if (!checkReceiptNo(formname,'notOK')) { return false;}
7510: formname.submit();
7511: }
7512: if (val < 7) formname.submit();
7513: }
7514:
7515: function checkReceiptNo(formname,nospace) {
7516: var receiptNo = formname.receipt.value;
7517: var checkOpt = false;
7518: if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
7519: if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
7520: if (checkOpt) {
7521: alert("Please enter a receipt number given by a student in the receipt box.");
7522: formname.receipt.value = "";
7523: formname.receipt.focus();
7524: return false;
7525: }
7526: return true;
7527: }
7528: </script>
7529: GRADINGMENUJS
7530: &commonJSfunctions($request);
7531: my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
7532: my $result;
7533: my (undef,$sections) = &getclasslist('all','0');
7534: my $savedState = &savedState();
7535: my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
7536: my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
7537: my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
7538: my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
7539:
7540: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
7541: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
7542: '<input type="hidden" name="handgrade" value="'.$hdgrade.'" />'."\n".
7543: '<input type="hidden" name="probTitle" value="'.$probTitle.'" />'."\n".
7544: '<input type="hidden" name="command" value="" />'."\n".
7545: '<input type="hidden" name="saveState" value="" />'."\n".
7546: '<input type="hidden" name="gradingMenu" value="1" />'."\n".
7547: '<input type="hidden" name="showgrading" value="yes" />'."\n";
7548:
7549: $result.='
7550: <div class="LC_grade_select_mode">
7551: <div class="LC_grade_select_mode_current">
7552: <h2>
7553: '.&mt('Grade Current Resource').'
7554: </h2>
7555: <div class="LC_grade_select_mode_body">
7556: <div class="LC_grades_resource_info">
7557: '.$table.'
7558: </div>
7559: <div class="LC_grade_select_mode_selector">
7560: <div class="LC_grade_select_mode_selector_header">
7561: '.&mt('Sections').'
7562: </div>
7563: <div class="LC_grade_select_mode_selector_body">
7564: <select name="section" multiple="multiple" size="5">'."\n";
7565: if (ref($sections)) {
7566: foreach my $section (sort (@$sections)) {
7567: $result.='<option value="'.$section.'" '.
7568: ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
7569: }
7570: }
7571: $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> ';
7572: $result.='
7573: </div>
7574: </div>
7575: <div class="LC_grade_select_mode_selector">
7576: <div class="LC_grade_select_mode_selector_header">
7577: '.&mt('Groups').'
7578: </div>
7579: <div class="LC_grade_select_mode_selector_body">
7580: '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
7581: </div>
7582: </div>
7583: <div class="LC_grade_select_mode_selector">
7584: <div class="LC_grade_select_mode_selector_header">
7585: '.&mt('Access Status').'
7586: </div>
7587: <div class="LC_grade_select_mode_selector_body">
7588: '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
7589: </div>
7590: </div>
7591: <div class="LC_grade_select_mode_selector">
7592: <div class="LC_grade_select_mode_selector_header">
7593: '.&mt('Submission Status').'
7594: </div>
7595: <div class="LC_grade_select_mode_selector_body">
7596: <select name="submitonly" size="5">
7597: <option value="yes" '. ($saveSub eq 'yes' ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
7598: <option value="queued" '. ($saveSub eq 'queued' ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
7599: <option value="graded" '. ($saveSub eq 'graded' ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
7600: <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
7601: <option value="all" '. ($saveSub eq 'all' ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
7602: </select>
7603: </div>
7604: </div>
7605: <div class="LC_grade_select_mode_type_body">
7606: <div class="LC_grade_select_mode_type">
7607: <label>
7608: <input type="radio" name="radioChoice" value="submission" '.
7609: ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
7610: &mt('Select individual students to grade and view submissions.').'
7611: </label>
7612: </div>
7613: <div class="LC_grade_select_mode_type">
7614: <label>
7615: <input type="radio" name="radioChoice" value="viewgrades" '.
7616: ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
7617: &mt('Grade all selected students in a grading table.').'
7618: </label>
7619: </div>
7620: <div class="LC_grade_select_mode_type">
7621: <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next->').'" />
7622: </div>
7623: </div>
7624: </div>
7625: </div>
7626: <div class="LC_grade_select_mode_page">
7627: <h2>
7628: '.&mt('Grade Complete Folder for One Student').'
7629: </h2>
7630: <div class="LC_grades_select_mode_body">
7631: <div class="LC_grade_select_mode_type_body">
7632: <div class="LC_grade_select_mode_type">
7633: <label>
7634: <input type="radio" name="radioChoice" value="pickStudentPage" '.
7635: ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
7636: &mt('The <b>complete</b> page/sequence/folder: For one student').'
7637: </label>
7638: </div>
7639: <div class="LC_grade_select_mode_type">
7640: <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next->').'" />
7641: </div>
7642: </div>
7643: </div>
7644: </div>
7645: </div>
7646: </form>';
7647: return $result;
7648: }
7649:
7650: sub reset_perm {
7651: undef(%perm);
7652: }
7653:
7654: sub init_perm {
7655: &reset_perm();
7656: foreach my $test_perm ('vgr','mgr','opa') {
7657:
7658: my $scope = $env{'request.course.id'};
7659: if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
7660:
7661: $scope .= '/'.$env{'request.course.sec'};
7662: if ( $perm{$test_perm}=
7663: &Apache::lonnet::allowed($test_perm,$scope)) {
7664: $perm{$test_perm.'_section'}=$env{'request.course.sec'};
7665: } else {
7666: delete($perm{$test_perm});
7667: }
7668: }
7669: }
7670: }
7671:
7672: sub gather_clicker_ids {
7673: my %clicker_ids;
7674:
7675: my $classlist = &Apache::loncoursedata::get_classlist();
7676:
7677: # Set up a couple variables.
7678: my $username_idx = &Apache::loncoursedata::CL_SNAME();
7679: my $domain_idx = &Apache::loncoursedata::CL_SDOM();
7680: my $status_idx = &Apache::loncoursedata::CL_STATUS();
7681:
7682: foreach my $student (keys(%$classlist)) {
7683: if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
7684: my $username = $classlist->{$student}->[$username_idx];
7685: my $domain = $classlist->{$student}->[$domain_idx];
7686: my $clickers =
7687: (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
7688: foreach my $id (split(/\,/,$clickers)) {
7689: $id=~s/^[\#0]+//;
7690: $id=~s/[\-\:]//g;
7691: if (exists($clicker_ids{$id})) {
7692: $clicker_ids{$id}.=','.$username.':'.$domain;
7693: } else {
7694: $clicker_ids{$id}=$username.':'.$domain;
7695: }
7696: }
7697: }
7698: return %clicker_ids;
7699: }
7700:
7701: sub gather_adv_clicker_ids {
7702: my %clicker_ids;
7703: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
7704: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7705: my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
7706: foreach my $element (sort(keys(%coursepersonnel))) {
7707: foreach my $person (split(/\,/,$coursepersonnel{$element})) {
7708: my ($puname,$pudom)=split(/\:/,$person);
7709: my $clickers =
7710: (&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
7711: foreach my $id (split(/\,/,$clickers)) {
7712: $id=~s/^[\#0]+//;
7713: $id=~s/[\-\:]//g;
7714: if (exists($clicker_ids{$id})) {
7715: $clicker_ids{$id}.=','.$puname.':'.$pudom;
7716: } else {
7717: $clicker_ids{$id}=$puname.':'.$pudom;
7718: }
7719: }
7720: }
7721: }
7722: return %clicker_ids;
7723: }
7724:
7725: sub clicker_grading_parameters {
7726: return ('gradingmechanism' => 'scalar',
7727: 'upfiletype' => 'scalar',
7728: 'specificid' => 'scalar',
7729: 'pcorrect' => 'scalar',
7730: 'pincorrect' => 'scalar');
7731: }
7732:
7733: sub process_clicker {
7734: my ($r)=@_;
7735: my ($symb)=&get_symb($r);
7736: if (!$symb) {return '';}
7737: my $result=&checkforfile_js();
7738: $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
7739: my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
7740: $result.=$table;
7741: $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
7742: $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
7743: $result.=' <b>'.&mt('Specify a file containing the clicker information for this resource').
7744: '.</b></td></tr>'."\n";
7745: $result.='<tr bgcolor=#ffffe6><td>'."\n";
7746: # Attempt to restore parameters from last session, set defaults if not present
7747: my %Saveable_Parameters=&clicker_grading_parameters();
7748: &Apache::loncommon::restore_course_settings('grades_clicker',
7749: \%Saveable_Parameters);
7750: if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
7751: if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
7752: if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
7753: if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
7754:
7755: my %checked;
7756: foreach my $gradingmechanism ('attendance','personnel','specific') {
7757: if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
7758: $checked{$gradingmechanism}="checked='checked'";
7759: }
7760: }
7761:
7762: my $upload=&mt("Upload File");
7763: my $type=&mt("Type");
7764: my $attendance=&mt("Award points just for participation");
7765: my $personnel=&mt("Correctness determined from response by course personnel");
7766: my $specific=&mt("Correctness determined from response with clicker ID(s)");
7767: my $pcorrect=&mt("Percentage points for correct solution");
7768: my $pincorrect=&mt("Percentage points for incorrect solution");
7769: my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
7770: ('iclicker' => 'i>clicker',
7771: 'interwrite' => 'interwrite PRS'));
7772: $symb = &Apache::lonenc::check_encrypt($symb);
7773: $result.=<<ENDUPFORM;
7774: <script type="text/javascript">
7775: function sanitycheck() {
7776: // Accept only integer percentages
7777: document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
7778: document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
7779: // Find out grading choice
7780: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
7781: if (document.forms.gradesupload.gradingmechanism[i].checked) {
7782: gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
7783: }
7784: }
7785: // By default, new choice equals user selection
7786: newgradingchoice=gradingchoice;
7787: // Not good to give more points for false answers than correct ones
7788: if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
7789: document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
7790: }
7791: // If new choice is attendance only, and old choice was correctness-based, restore defaults
7792: if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
7793: document.forms.gradesupload.pcorrect.value=100;
7794: document.forms.gradesupload.pincorrect.value=100;
7795: }
7796: // If the values are different, cannot be attendance only
7797: if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
7798: (gradingchoice=='attendance')) {
7799: newgradingchoice='personnel';
7800: }
7801: // Change grading choice to new one
7802: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
7803: if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
7804: document.forms.gradesupload.gradingmechanism[i].checked=true;
7805: } else {
7806: document.forms.gradesupload.gradingmechanism[i].checked=false;
7807: }
7808: }
7809: // Remember the old state
7810: document.forms.gradesupload.waschecked.value=newgradingchoice;
7811: }
7812: </script>
7813: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
7814: <input type="hidden" name="symb" value="$symb" />
7815: <input type="hidden" name="command" value="processclickerfile" />
7816: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
7817: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
7818: <input type="file" name="upfile" size="50" />
7819: <br /><label>$type: $selectform</label>
7820: <br /><label><input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
7821: <br /><label><input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
7822: <br /><label><input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" />$specific </label>
7823: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
7824: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
7825: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
7826: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
7827: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
7828: </form>
7829: ENDUPFORM
7830: $result.='</td></tr></table>'."\n".
7831: '</td></tr></table><br /><br />'."\n";
7832: $result.=&show_grading_menu_form($symb);
7833: return $result;
7834: }
7835:
7836: sub process_clicker_file {
7837: my ($r)=@_;
7838: my ($symb)=&get_symb($r);
7839: if (!$symb) {return '';}
7840:
7841: my %Saveable_Parameters=&clicker_grading_parameters();
7842: &Apache::loncommon::store_course_settings('grades_clicker',
7843: \%Saveable_Parameters);
7844:
7845: my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
7846: if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
7847: $result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
7848: return $result.&show_grading_menu_form($symb);
7849: }
7850: my %clicker_ids=&gather_clicker_ids();
7851: my %correct_ids;
7852: if ($env{'form.gradingmechanism'} eq 'personnel') {
7853: %correct_ids=&gather_adv_clicker_ids();
7854: }
7855: if ($env{'form.gradingmechanism'} eq 'specific') {
7856: foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
7857: $correct_id=~tr/a-z/A-Z/;
7858: $correct_id=~s/\s//gs;
7859: $correct_id=~s/^[\#0]+//;
7860: $correct_id=~s/[\-\:]//g;
7861: if ($correct_id) {
7862: $correct_ids{$correct_id}='specified';
7863: }
7864: }
7865: }
7866: if ($env{'form.gradingmechanism'} eq 'attendance') {
7867: $result.=&mt('Score based on attendance only');
7868: } else {
7869: my $number=0;
7870: $result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
7871: foreach my $id (sort(keys(%correct_ids))) {
7872: $result.='<br /><tt>'.$id.'</tt> - ';
7873: if ($correct_ids{$id} eq 'specified') {
7874: $result.=&mt('specified');
7875: } else {
7876: my ($uname,$udom)=split(/\:/,$correct_ids{$id});
7877: $result.=&Apache::loncommon::plainname($uname,$udom);
7878: }
7879: $number++;
7880: }
7881: $result.="</p>\n";
7882: if ($number==0) {
7883: $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
7884: return $result.&show_grading_menu_form($symb);
7885: }
7886: }
7887: if (length($env{'form.upfile'}) < 2) {
7888: $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
7889: '<span class="LC_error">',
7890: '</span>',
7891: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
7892: return $result.&show_grading_menu_form($symb);
7893: }
7894:
7895: # Were able to get all the info needed, now analyze the file
7896:
7897: $result.=&Apache::loncommon::studentbrowser_javascript();
7898: $symb = &Apache::lonenc::check_encrypt($symb);
7899: my $heading=&mt('Scanning clicker file');
7900: $result.=(<<ENDHEADER);
7901: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
7902: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
7903: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
7904: <form method="post" action="/adm/grades" name="clickeranalysis">
7905: <input type="hidden" name="symb" value="$symb" />
7906: <input type="hidden" name="command" value="assignclickergrades" />
7907: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
7908: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
7909: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
7910: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
7911: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
7912: ENDHEADER
7913: my %responses;
7914: my @questiontitles;
7915: my $errormsg='';
7916: my $number=0;
7917: if ($env{'form.upfiletype'} eq 'iclicker') {
7918: ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
7919: }
7920: if ($env{'form.upfiletype'} eq 'interwrite') {
7921: ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
7922: }
7923: $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
7924: '<input type="hidden" name="number" value="'.$number.'" />'.
7925: &mt('Awarding [_1] percent for corrion(s)',$number).'<br />'.
7926: '<input type="hidden" name="number" value="'.$number.'" />'.
7927: &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
7928: $env{'form.pcorrect'},$env{'form.pincorrect'}).
7929: '<br />';
7930: # Remember Question Titles
7931: # FIXME: Possibly need delimiter other than ":"
7932: for (my $i=0;$i<$number;$i++) {
7933: $result.='<input type="hidden" name="question:'.$i.'" value="'.
7934: &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
7935: }
7936: my $correct_count=0;
7937: my $student_count=0;
7938: my $unknown_count=0;
7939: # Match answers with usernames
7940: # FIXME: Possibly need delimiter other than ":"
7941: foreach my $id (keys(%responses)) {
7942: if ($correct_ids{$id}) {
7943: $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
7944: $correct_count++;
7945: } elsif ($clicker_ids{$id}) {
7946: if ($clicker_ids{$id}=~/\,/) {
7947: # More than one user with the same clicker!
7948: $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
7949: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
7950: "<select name='multi".$id."'>";
7951: foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
7952: $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
7953: }
7954: $result.='</select>';
7955: $unknown_count++;
7956: } else {
7957: # Good: found one and only one user with the right clicker
7958: $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
7959: $student_count++;
7960: }
7961: } else {
7962: $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
7963: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
7964: "\n".&mt("Username").": <input type='text' name='uname".$id."' /> ".
7965: "\n".&mt("Domain").": ".
7966: &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).' '.
7967: &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
7968: $unknown_count++;
7969: }
7970: }
7971: $result.='<hr />'.
7972: &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
7973: if ($env{'form.gradingmechanism'} ne 'attendance') {
7974: if ($correct_count==0) {
7975: $errormsg.="Found no correct answers answers for grading!";
7976: } elsif ($correct_count>1) {
7977: $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
7978: }
7979: }
7980: if ($number<1) {
7981: $errormsg.="Found no questions.";
7982: }
7983: if ($errormsg) {
7984: $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
7985: } else {
7986: $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
7987: }
7988: $result.='</form></td></tr></table>'."\n".
7989: '</td></tr></table><br /><br />'."\n";
7990: return $result.&show_grading_menu_form($symb);
7991: }
7992:
7993: sub iclicker_eval {
7994: my ($questiontitles,$responses)=@_;
7995: my $number=0;
7996: my $errormsg='';
7997: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
7998: my %components=&Apache::loncommon::record_sep($line);
7999: my @entries=map {$components{$_}} (sort(keys(%components)));
8000: if ($entries[0] eq 'Question') {
8001: for (my $i=3;$i<$#entries;$i+=6) {
8002: $$questiontitles[$number]=$entries[$i];
8003: $number++;
8004: }
8005: }
8006: if ($entries[0]=~/^\#/) {
8007: my $id=$entries[0];
8008: my @idresponses;
8009: $id=~s/^[\#0]+//;
8010: for (my $i=0;$i<$number;$i++) {
8011: my $idx=3+$i*6;
8012: push(@idresponses,$entries[$idx]);
8013: }
8014: $$responses{$id}=join(',',@idresponses);
8015: }
8016: }
8017: return ($errormsg,$number);
8018: }
8019:
8020: sub interwrite_eval {
8021: my ($questiontitles,$responses)=@_;
8022: my $number=0;
8023: my $errormsg='';
8024: my $skipline=1;
8025: my $questionnumber=0;
8026: my %idresponses=();
8027: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
8028: my %components=&Apache::loncommon::record_sep($line);
8029: my @entries=map {$components{$_}} (sort(keys(%components)));
8030: if ($entries[1] eq 'Time') { $skipline=0; next; }
8031: if ($entries[1] eq 'Response') { $skipline=1; }
8032: next if $skipline;
8033: if ($entries[0]!=$questionnumber) {
8034: $questionnumber=$entries[0];
8035: $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
8036: $number++;
8037: }
8038: my $id=$entries[4];
8039: $id=~s/^[\#0]+//;
8040: $id=~s/^v\d*\://i;
8041: $id=~s/[\-\:]//g;
8042: $idresponses{$id}[$number]=$entries[6];
8043: }
8044: foreach my $id (keys %idresponses) {
8045: $$responses{$id}=join(',',@{$idresponses{$id}});
8046: $$responses{$id}=~s/^\s*\,//;
8047: }
8048: return ($errormsg,$number);
8049: }
8050:
8051: sub assign_clicker_grades {
8052: my ($r)=@_;
8053: my ($symb)=&get_symb($r);
8054: if (!$symb) {return '';}
8055: # See which part we are saving to
8056: my ($partlist,$handgrade,$responseType) = &response_type($symb);
8057: # FIXME: This should probably look for the first handgradeable part
8058: my $part=$$partlist[0];
8059: # Start screen output
8060: my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
8061:
8062: my $heading=&mt('Assigning grades based on clicker file');
8063: $result.=(<<ENDHEADER);
8064: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
8065: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
8066: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
8067: ENDHEADER
8068: # Get correct result
8069: # FIXME: Possibly need delimiter other than ":"
8070: my @correct=();
8071: my $gradingmechanism=$env{'form.gradingmechanism'};
8072: my $number=$env{'form.number'};
8073: if ($gradingmechanism ne 'attendance') {
8074: foreach my $key (keys(%env)) {
8075: if ($key=~/^form\.correct\:/) {
8076: my @input=split(/\,/,$env{$key});
8077: for (my $i=0;$i<=$#input;$i++) {
8078: if (($correct[$i]) && ($input[$i]) &&
8079: ($correct[$i] ne $input[$i])) {
8080: $result.='<br /><span class="LC_warning">'.
8081: &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
8082: $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
8083: } elsif ($input[$i]) {
8084: $correct[$i]=$input[$i];
8085: }
8086: }
8087: }
8088: }
8089: for (my $i=0;$i<$number;$i++) {
8090: if (!$correct[$i]) {
8091: $result.='<br /><span class="LC_error">'.
8092: &mt('No correct result given for question "[_1]"!',
8093: $env{'form.question:'.$i}).'</span>';
8094: }
8095: }
8096: $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
8097: }
8098: # Start grading
8099: my $pcorrect=$env{'form.pcorrect'};
8100: my $pincorrect=$env{'form.pincorrect'};
8101: my $storecount=0;
8102: foreach my $key (keys(%env)) {
8103: my $user='';
8104: if ($key=~/^form\.student\:(.*)$/) {
8105: $user=$1;
8106: }
8107: if ($key=~/^form\.unknown\:(.*)$/) {
8108: my $id=$1;
8109: if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
8110: $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
8111: } elsif ($env{'form.multi'.$id}) {
8112: $user=$env{'form.multi'.$id};
8113: }
8114: }
8115: if ($user) {
8116: my @answer=split(/\,/,$env{$key});
8117: my $sum=0;
8118: for (my $i=0;$i<$number;$i++) {
8119: if ($answer[$i]) {
8120: if ($gradingmechanism eq 'attendance') {
8121: $sum+=$pcorrect;
8122: } else {
8123: if ($answer[$i] eq $correct[$i]) {
8124: $sum+=$pcorrect;
8125: } else {
8126: $sum+=$pincorrect;
8127: }
8128: }
8129: }
8130: }
8131: my $ave=$sum/(100*$number);
8132: # Store
8133: my ($username,$domain)=split(/\:/,$user);
8134: my %grades=();
8135: $grades{"resource.$part.solved"}='correct_by_override';
8136: $grades{"resource.$part.awarded"}=$ave;
8137: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
8138: my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
8139: $env{'request.course.id'},
8140: $domain,$username);
8141: if ($returncode ne 'ok') {
8142: $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
8143: } else {
8144: $storecount++;
8145: }
8146: }
8147: }
8148: # We are done
8149: $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
8150: '</td></tr></table>'."\n".
8151: '</td></tr></table><br /><br />'."\n";
8152: return $result.&show_grading_menu_form($symb);
8153: }
8154:
8155: sub handler {
8156: my $request=$_[0];
8157: &reset_caches();
8158: if ($env{'browser.mathml'}) {
8159: &Apache::loncommon::content_type($request,'text/xml');
8160: } else {
8161: &Apache::loncommon::content_type($request,'text/html');
8162: }
8163: $request->send_http_header;
8164: return '' if $request->header_only;
8165: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
8166: my $symb=&get_symb($request,1);
8167: my @commands=&Apache::loncommon::get_env_multiple('form.command');
8168: my $command=$commands[0];
8169:
8170: if ($#commands > 0) {
8171: &Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
8172: }
8173:
8174:
8175: $request->print(&Apache::loncommon::start_page('Grading'));
8176: if ($symb eq '' && $command eq '') {
8177: if ($env{'user.adv'}) {
8178: if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
8179: ($env{'form.codethree'})) {
8180: my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
8181: $env{'form.codethree'};
8182: my ($tsymb,$tuname,$tudom,$tcrsid)=
8183: &Apache::lonnet::checkin($token);
8184: if ($tsymb) {
8185: my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
8186: if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
8187: $request->print(&Apache::lonnet::ssi_body('/res/'.$url,
8188: ('grade_username' => $tuname,
8189: 'grade_domain' => $tudom,
8190: 'grade_courseid' => $tcrsid,
8191: 'grade_symb' => $tsymb)));
8192: } else {
8193: $request->print('<h3>Not authorized: '.$token.'</h3>');
8194: }
8195: } else {
8196: $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
8197: }
8198: } else {
8199: $request->print(&Apache::lonxml::tokeninputfield());
8200: }
8201: }
8202: } else {
8203: &init_perm();
8204: if ($command eq 'submission' && $perm{'vgr'}) {
8205: ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
8206: } elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
8207: &pickStudentPage($request);
8208: } elsif ($command eq 'displayPage' && $perm{'vgr'}) {
8209: &displayPage($request);
8210: } elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
8211: &updateGradeByPage($request);
8212: } elsif ($command eq 'processGroup' && $perm{'vgr'}) {
8213: &processGroup($request);
8214: } elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
8215: $request->print(&grading_menu($request));
8216: } elsif ($command eq 'submit_options' && $perm{'vgr'}) {
8217: $request->print(&submit_options($request));
8218: } elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
8219: $request->print(&viewgrades($request));
8220: } elsif ($command eq 'handgrade' && $perm{'mgr'}) {
8221: $request->print(&processHandGrade($request));
8222: } elsif ($command eq 'editgrades' && $perm{'mgr'}) {
8223: $request->print(&editgrades($request));
8224: } elsif ($command eq 'verify' && $perm{'vgr'}) {
8225: $request->print(&verifyreceipt($request));
8226: } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
8227: $request->print(&process_clicker($request));
8228: } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
8229: $request->print(&process_clicker_file($request));
8230: } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
8231: $request->print(&assign_clicker_grades($request));
8232: } elsif ($command eq 'csvform' && $perm{'mgr'}) {
8233: $request->print(&upcsvScores_form($request));
8234: } elsif ($command eq 'csvupload' && $perm{'mgr'}) {
8235: $request->print(&csvupload($request));
8236: } elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
8237: $request->print(&csvuploadmap($request));
8238: } elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
8239: if ($env{'form.associate'} ne 'Reverse Association') {
8240: $request->print(&csvuploadoptions($request));
8241: } else {
8242: if ( $env{'form.upfile_associate'} ne 'reverse' ) {
8243: $env{'form.upfile_associate'} = 'reverse';
8244: } else {
8245: $env{'form.upfile_associate'} = 'forward';
8246: }
8247: $request->print(&csvuploadmap($request));
8248: }
8249: } elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
8250: $request->print(&csvuploadassign($request));
8251: } elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
8252: $request->print(&scantron_selectphase($request));
8253: } elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
8254: $request->print(&scantron_do_warning($request));
8255: } elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
8256: $request->print(&scantron_validate_file($request));
8257: } elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
8258: $request->print(&scantron_process_students($request));
8259: } elsif ($command eq 'scantronupload' &&
8260: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
8261: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
8262: $request->print(&scantron_upload_scantron_data($request));
8263: } elsif ($command eq 'scantronupload_save' &&
8264: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
8265: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
8266: $request->print(&scantron_upload_scantron_data_save($request));
8267: } elsif ($command eq 'scantron_download' &&
8268: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
8269: $request->print(&scantron_download_scantron_data($request));
8270: } elsif ($command) {
8271: $request->print("Access Denied ($command)");
8272: }
8273: }
8274: $request->print(&Apache::loncommon::end_page());
8275: &reset_caches();
8276: return '';
8277: }
8278:
8279: 1;
8280:
8281: __END__;
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>