1: # The LearningOnline Network with CAPA
2: # The LON-CAPA Grading handler
3: #
4: # $Id: grades.pm,v 1.449 2007/10/09 19:33:56 banghart 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::loncoursedata;
39: use Apache::lonmsg();
40: use Apache::Constants qw(:common);
41: use Apache::lonlocal;
42: use Apache::lonenc;
43: use String::Similarity;
44: use LONCAPA;
45:
46: use POSIX qw(floor);
47:
48:
49: my %perm=();
50: my %bubble_lines_per_response = (); # no. bubble lines for each response.
51: # index is "symb.part_id"
52:
53: my %first_bubble_line = (); # First bubble line no. for each bubble.
54:
55: # Save and restore the bubble lines array to the form env.
56:
57:
58: sub save_bubble_lines {
59: &Apache::lonnet::logthis("Saving bubble_lines...");
60: foreach my $line (keys(%bubble_lines_per_response)) {
61: &Apache::lonnet::logthis("Saving form.scantron.bubblelines.$line value: $bubble_lines_per_response{$line}");
62: $env{"form.scantron.bubblelines.$line"} = $bubble_lines_per_response{$line};
63: $env{"form.scantron.first_bubble_line.$line"} =
64: $first_bubble_line{$line};
65: }
66: }
67:
68:
69: sub restore_bubble_lines {
70: my $line = 0;
71: %bubble_lines_per_response = ();
72: while ($env{"form.scantron.bubblelines.$line"}) {
73: my $value = $env{"form.scantron.bubblelines.$line"};
74: &Apache::lonnet::logthis("Restoring form.scantron.bubblelines.$line value: $value");
75: $bubble_lines_per_response{$line} = $value;
76: $first_bubble_line{$line} =
77: $env{"form.scantron.first_bubble_line.$line"};
78: $line++;
79: }
80:
81: }
82:
83: # Given the parsed scanline, get the response for
84: # 'answer' number n:
85:
86: sub get_response_bubbles {
87: my ($parsed_line, $response) = @_;
88:
89: my $bubble_line = $first_bubble_line{$response};
90: my $bubble_lines= $bubble_lines_per_response{$response};
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> Fullname </b><span class="LC_internal_info">(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><b>Part: </b>'.$display_part.' <span class="LC_internal_info">'.
258: $resID.'</span></td>'.
259: '<td><b>Type: </b>'.$responsetype.'</td></tr>';
260: # '<td><b>Handgrade: </b>'.$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>Answer</td>'.$toprow.'</tr>'.
336: '<tr valign="top"><td>'.$grayFont.'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>Answer</td>'.$toprow.'</tr>'.
356: '<tr valign="top"><td>'.$grayFont.'Item ID</span></td>'.
357: $middlerow.'</tr>'.
358: '<tr valign="top"><td>'.$grayFont.'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>true</b></td>';
369: } else {
370: $toprow.='<td><i>true</i></td>';
371: }
372: } else {
373: $toprow.='<td>false</td>';
374: }
375: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
376: }
377: return '<blockquote><table border="1">'.
378: '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
379: '<tr valign="top"><td>'.$grayFont.'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 $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
481: if (!ref($getsec)) {
482: if ($getsec ne '' && $getsec ne 'all') {
483: @getsec=($getsec);
484: }
485: } else {
486: @getsec=@{$getsec};
487: }
488: if (grep(/^all$/,@getsec)) { undef(@getsec); }
489:
490: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
491: # Bail out if we were unable to get the classlist
492: return if (! defined($classlist));
493: &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
494: #
495: my %sections;
496: my %fullnames;
497: foreach my $student (keys(%$classlist)) {
498: my $end =
499: $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
500: my $start =
501: $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
502: my $id =
503: $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
504: my $section =
505: $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
506: my $fullname =
507: $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
508: my $status =
509: $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
510: my $group =
511: $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
512: # filter students according to status selected
513: if ($filterlist && (!($stu_status =~ /Any/))) {
514: if (!($stu_status =~ $status)) {
515: delete ($classlist->{$student});
516: next;
517: }
518: }
519: $section = ($section ne '' ? $section : 'none');
520: if (&canview($section)) {
521: if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
522: $sections{$section}++;
523: $fullnames{$student}=$fullname;
524: } else {
525: delete($classlist->{$student});
526: }
527: } else {
528: delete($classlist->{$student});
529: }
530: }
531: my %seen = ();
532: my @sections = sort(keys(%sections));
533: return ($classlist,\@sections,\%fullnames);
534: }
535:
536: sub canmodify {
537: my ($sec)=@_;
538: if ($perm{'mgr'}) {
539: if (!defined($perm{'mgr_section'})) {
540: # can modify whole class
541: return 1;
542: } else {
543: if ($sec eq $perm{'mgr_section'}) {
544: #can modify the requested section
545: return 1;
546: } else {
547: # can't modify the request section
548: return 0;
549: }
550: }
551: }
552: #can't modify
553: return 0;
554: }
555:
556: sub canview {
557: my ($sec)=@_;
558: if ($perm{'vgr'}) {
559: if (!defined($perm{'vgr_section'})) {
560: # can modify whole class
561: return 1;
562: } else {
563: if ($sec eq $perm{'vgr_section'}) {
564: #can modify the requested section
565: return 1;
566: } else {
567: # can't modify the request section
568: return 0;
569: }
570: }
571: }
572: #can't modify
573: return 0;
574: }
575:
576: #--- Retrieve the grade status of a student for all the parts
577: sub student_gradeStatus {
578: my ($symb,$udom,$uname,$partlist) = @_;
579: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
580: my %partstatus = ();
581: foreach (@$partlist) {
582: my ($status,undef) = split(/_/,$record{"resource.$_.solved"},2);
583: $status = 'nothing' if ($status eq '');
584: $partstatus{$_} = $status;
585: my $subkey = "resource.$_.submitted_by";
586: $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
587: }
588: return %partstatus;
589: }
590:
591: # hidden form and javascript that calls the form
592: # Use by verifyscript and viewgrades
593: # Shows a student's view of problem and submission
594: sub jscriptNform {
595: my ($symb) = @_;
596: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
597: my $jscript='<script type="text/javascript" language="javascript">'."\n".
598: ' function viewOneStudent(user,domain) {'."\n".
599: ' document.onestudent.student.value = user;'."\n".
600: ' document.onestudent.userdom.value = domain;'."\n".
601: ' document.onestudent.submit();'."\n".
602: ' }'."\n".
603: '</script>'."\n";
604: $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
605: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
606: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
607: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
608: '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
609: '<input type="hidden" name="command" value="submission" />'."\n".
610: '<input type="hidden" name="student" value="" />'."\n".
611: '<input type="hidden" name="userdom" value="" />'."\n".
612: '</form>'."\n";
613: return $jscript;
614: }
615:
616:
617:
618: # Given the score (as a number [0-1] and the weight) what is the final
619: # point value? This function will round to the nearest tenth, third,
620: # or quarter if one of those is within the tolerance of .00001.
621: sub compute_points {
622: my ($score, $weight) = @_;
623:
624: my $tolerance = .00001;
625: my $points = $score * $weight;
626:
627: # Check for nearness to 1/x.
628: my $check_for_nearness = sub {
629: my ($factor) = @_;
630: my $num = ($points * $factor) + $tolerance;
631: my $floored_num = floor($num);
632: if ($num - $floored_num < 2 * $tolerance * $factor) {
633: return $floored_num / $factor;
634: }
635: return $points;
636: };
637:
638: $points = $check_for_nearness->(10);
639: $points = $check_for_nearness->(3);
640: $points = $check_for_nearness->(4);
641:
642: return $points;
643: }
644:
645: #------------------ End of general use routines --------------------
646:
647: #
648: # Find most similar essay
649: #
650:
651: sub most_similar {
652: my ($uname,$udom,$uessay,$old_essays)=@_;
653:
654: # ignore spaces and punctuation
655:
656: $uessay=~s/\W+/ /gs;
657:
658: # ignore empty submissions (occuring when only files are sent)
659:
660: unless ($uessay=~/\w+/) { return ''; }
661:
662: # these will be returned. Do not care if not at least 50 percent similar
663: my $limit=0.6;
664: my $sname='';
665: my $sdom='';
666: my $scrsid='';
667: my $sessay='';
668: # go through all essays ...
669: foreach my $tkey (keys(%$old_essays)) {
670: my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
671: # ... except the same student
672: next if (($tname eq $uname) && ($tdom eq $udom));
673: my $tessay=$old_essays->{$tkey};
674: $tessay=~s/\W+/ /gs;
675: # String similarity gives up if not even limit
676: my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
677: # Found one
678: if ($tsimilar>$limit) {
679: $limit=$tsimilar;
680: $sname=$tname;
681: $sdom=$tdom;
682: $scrsid=$tcrsid;
683: $sessay=$old_essays->{$tkey};
684: }
685: }
686: if ($limit>0.6) {
687: return ($sname,$sdom,$scrsid,$sessay,$limit);
688: } else {
689: return ('','','','',0);
690: }
691: }
692:
693: #-------------------------------------------------------------------
694:
695: #------------------------------------ Receipt Verification Routines
696: #
697: #--- Check whether a receipt number is valid.---
698: sub verifyreceipt {
699: my $request = shift;
700:
701: my $courseid = $env{'request.course.id'};
702: my $receipt = &Apache::lonnet::recprefix($courseid).'-'.
703: $env{'form.receipt'};
704: $receipt =~ s/[^\-\d]//g;
705: my ($symb) = &get_symb($request);
706:
707: my $title.='<h3><span class="LC_info">Verifying Submission Receipt '.
708: $receipt.'</h3></span>'."\n".
709: '<h4><b>Resource: </b>'.$env{'form.probTitle'}.'</h4><br /><br />'."\n";
710:
711: my ($string,$contents,$matches) = ('','',0);
712: my (undef,undef,$fullname) = &getclasslist('all','0');
713:
714: my $receiptparts=0;
715: if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
716: $env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
717: my $parts=['0'];
718: if ($receiptparts) { ($parts)=&response_type($symb); }
719: foreach (sort
720: {
721: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
722: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
723: }
724: return $a cmp $b;
725: } (keys(%$fullname))) {
726: my ($uname,$udom)=split(/\:/);
727: foreach my $part (@$parts) {
728: if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
729: $contents.='<tr bgcolor="#ffffe6"><td> '."\n".
730: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
731: '\');" target="_self">'.$$fullname{$_}.'</a> </td>'."\n".
732: '<td> '.$uname.' </td>'.
733: '<td> '.$udom.' </td>';
734: if ($receiptparts) {
735: $contents.='<td> '.$part.' </td>';
736: }
737: $contents.='</tr>'."\n";
738:
739: $matches++;
740: }
741: }
742: }
743: if ($matches == 0) {
744: $string = $title.'No match found for the above receipt.';
745: } else {
746: $string = &jscriptNform($symb).$title.
747: 'The above receipt matches the following student'.
748: ($matches <= 1 ? '.' : 's.')."\n".
749: '<table border="0"><tr><td bgcolor="#777777">'."\n".
750: '<table border="0"><tr bgcolor="#e6ffff">'."\n".
751: '<td><b> Fullname </b></td>'."\n".
752: '<td><b> Username </b></td>'."\n".
753: '<td><b> Domain </b></td>';
754: if ($receiptparts) {
755: $string.='<td> Problem Part </td>';
756: }
757: $string.='</tr>'."\n".$contents.
758: '</table></td></tr></table>'."\n";
759: }
760: return $string.&show_grading_menu_form($symb);
761: }
762:
763: #--- This is called by a number of programs.
764: #--- Called from the Grading Menu - View/Grade an individual student
765: #--- Also called directly when one clicks on the subm button
766: # on the problem page.
767: sub listStudents {
768: my ($request) = shift;
769:
770: my ($symb) = &get_symb($request);
771: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
772: my $cnum = $env{"course.$env{'request.course.id'}.num"};
773: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
774: my $getgroup = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
775: my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
776: my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
777: $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ?
778: &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
779:
780: my $result='<h3><span class="LC_info"> '.$viewgrade.
781: ' Submissions for a Student or a Group of Students</span></h3>';
782:
783: my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
784:
785: $request->print(<<LISTJAVASCRIPT);
786: <script type="text/javascript" language="javascript">
787: function checkSelect(checkBox) {
788: var ctr=0;
789: var sense="";
790: if (checkBox.length > 1) {
791: for (var i=0; i<checkBox.length; i++) {
792: if (checkBox[i].checked) {
793: ctr++;
794: }
795: }
796: sense = "a student or group of students";
797: } else {
798: if (checkBox.checked) {
799: ctr = 1;
800: }
801: sense = "the student";
802: }
803: if (ctr == 0) {
804: alert("Please select "+sense+" before clicking on the Next button.");
805: return false;
806: }
807: document.gradesub.submit();
808: }
809:
810: function reLoadList(formname) {
811: if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
812: formname.command.value = 'submission';
813: formname.submit();
814: }
815: </script>
816: LISTJAVASCRIPT
817:
818: &commonJSfunctions($request);
819: $request->print($result);
820:
821: my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
822: my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
823: my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
824: "\n".$table.
825: ' <b>View Problem Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
826: '<label><input type="radio" name="vProb" value="yes" /> one student </label>'."\n".
827: '<label><input type="radio" name="vProb" value="all" /> all students </label><br />'."\n".
828: ' <b>View Answer: </b><label><input type="radio" name="vAns" value="no" /> no </label>'."\n".
829: '<label><input type="radio" name="vAns" value="yes" /> one student </label>'."\n".
830: '<label><input type="radio" name="vAns" value="all" checked="checked" /> all students </label><br />'."\n".
831: ' <b>Submissions: </b>'."\n";
832: if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
833: $gradeTable.='<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> essay part only </label>'."\n";
834: }
835: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
836: my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
837: $env{'form.Status'} = $saveStatus;
838: $gradeTable.='<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> last submission only </label>'."\n".
839: '<label><input type="radio" name="lastSub" value="last" /> last submission & parts info </label>'."\n".
840: '<label><input type="radio" name="lastSub" value="datesub" /> by dates and submissions </label>'."\n".
841: '<label><input type="radio" name="lastSub" value="all" /> all details</label><br />'."\n".
842: ' <b>Grading Increments:</b> <select name="increment">'.
843: '<option value="1">Whole Points</option>'.
844: '<option value=".5">Half Points</option>'.
845: '<option value=".25">Quarter Points</option>'.
846: '<option value=".1">Tenths of a Point</option>'.
847: '</select>'.
848: &build_section_inputs().
849: '<input type="hidden" name="submitonly" value="'.$submitonly.'" />'."\n".
850: '<input type="hidden" name="handgrade" value="'.$env{'form.handgrade'}.'" /><br />'."\n".
851: '<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
852: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
853: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
854: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
855: '<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
856:
857: if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
858: $gradeTable.='<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
859: } else {
860: $gradeTable.='<b>Student Status:</b> '.
861: &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);').'<br />';
862: }
863:
864: $gradeTable.='To '.lc($viewgrade).' a submission or a group of submissions, click on the check box(es) '.
865: 'next to the student\'s name(s). Then click on the Next button.<br />'."\n".
866: '<input type="hidden" name="command" value="processGroup" />'."\n";
867:
868: # checkall buttons
869: $gradeTable.=&check_script('gradesub', 'stuinfo');
870: $gradeTable.='<input type="button" '."\n".
871: 'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
872: 'value="Next->" /> <br />'."\n";
873: $gradeTable.=&check_buttons();
874: $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />Check For Plagiarism</label>';
875: my ($classlist, undef, $fullname) = &getclasslist($getsec,'1');
876: $gradeTable.='<table border="0"><tr><td bgcolor="#777777">'.
877: '<table border="0"><tr bgcolor="#e6ffff">';
878: my $loop = 0;
879: while ($loop < 2) {
880: $gradeTable.='<td><b> No.</b> </td><td><b> Select </b></td>'.
881: '<td>'.&nameUserString('header').' Section/Group</td>';
882: if ($env{'form.showgrading'} eq 'yes'
883: && $submitonly ne 'queued'
884: && $submitonly ne 'all') {
885: foreach (sort(@$partlist)) {
886: my $display_part=&get_display_part((split(/_/))[0],$symb);
887: $gradeTable.='<td><b> Part: '.$display_part.
888: ' Status </b></td>';
889: }
890: } elsif ($submitonly eq 'queued') {
891: $gradeTable.='<td><b> '.&mt('Queue Status').' </b></td>';
892: }
893: $loop++;
894: # $gradeTable.='<td></td>' if ($loop%2 ==1);
895: }
896: $gradeTable.='</tr>'."\n";
897:
898: my $ctr = 0;
899: foreach my $student (sort
900: {
901: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
902: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
903: }
904: return $a cmp $b;
905: }
906: (keys(%$fullname))) {
907: my ($uname,$udom) = split(/:/,$student);
908:
909: my %status = ();
910:
911: if ($submitonly eq 'queued') {
912: my %queue_status =
913: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
914: $udom,$uname);
915: next if (!defined($queue_status{'gradingqueue'}));
916: $status{'gradingqueue'} = $queue_status{'gradingqueue'};
917: }
918:
919: if ($env{'form.showgrading'} eq 'yes'
920: && $submitonly ne 'queued'
921: && $submitonly ne 'all') {
922: (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
923: my $submitted = 0;
924: my $graded = 0;
925: my $incorrect = 0;
926: foreach (keys(%status)) {
927: $submitted = 1 if ($status{$_} ne 'nothing');
928: $graded = 1 if ($status{$_} =~ /^ungraded/);
929: $incorrect = 1 if ($status{$_} =~ /^incorrect/);
930:
931: my ($foo,$partid,$foo1) = split(/\./,$_);
932: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
933: $submitted = 0;
934: my ($part)=split(/\./,$partid);
935: $gradeTable.='<input type="hidden" name="'.
936: $student.':'.$part.':submitted_by" value="'.
937: $status{'resource.'.$partid.'.submitted_by'}.'" />';
938: }
939: }
940:
941: next if (!$submitted && ($submitonly eq 'yes' ||
942: $submitonly eq 'incorrect' ||
943: $submitonly eq 'graded'));
944: next if (!$graded && ($submitonly eq 'graded'));
945: next if (!$incorrect && $submitonly eq 'incorrect');
946: }
947:
948: $ctr++;
949: my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
950:
951: if ( $perm{'vgr'} eq 'F' ) {
952: $gradeTable.='<tr bgcolor="#ffffe6">' if ($ctr%2 ==1);
953: $gradeTable.='<td align="right">'.$ctr.' </td>'.
954: '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
955: $student.':'.$$fullname{$student}.':::SECTION'.$section.
956: ') " /> </label></td>'."\n".'<td>'.
957: &nameUserString(undef,$$fullname{$student},$uname,$udom).
958: ' '.$section.'</td>'."\n";
959:
960: if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
961: foreach (sort keys(%status)) {
962: next if (/^resource.*?submitted_by$/);
963: $gradeTable.='<td align="center"> '.$status{$_}.' </td>'."\n";
964: }
965: }
966: # $gradeTable.='<td></td>' if ($ctr%2 ==1);
967: $gradeTable.='</tr>'."\n" if ($ctr%2 ==0);
968: }
969: }
970: if ($ctr%2 ==1) {
971: $gradeTable.='<td> </td><td> </td><td> </td>';
972: if ($env{'form.showgrading'} eq 'yes'
973: && $submitonly ne 'queued'
974: && $submitonly ne 'all') {
975: foreach (@$partlist) {
976: $gradeTable.='<td> </td>';
977: }
978: } elsif ($submitonly eq 'queued') {
979: $gradeTable.='<td> </td>';
980: }
981: $gradeTable.='</tr>';
982: }
983:
984: $gradeTable.='</table></td></tr></table>'."\n".
985: '<input type="button" '.
986: 'onClick="javascript:checkSelect(this.form.stuinfo);" '.
987: 'value="Next->" /></form>'."\n";
988: if ($ctr == 0) {
989: my $num_students=(scalar(keys(%$fullname)));
990: if ($num_students eq 0) {
991: $gradeTable='<br /> <span class="LC_warning">There are no students currently enrolled.</span>';
992: } else {
993: my $submissions='submissions';
994: if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
995: if ($submitonly eq 'graded' ) { $submissions = 'ungraded submissions'; }
996: if ($submitonly eq 'queued' ) { $submissions = 'queued submissions'; }
997: $gradeTable='<br /> <span class="LC_warning">'.
998: 'No '.$submissions.' found for this resource for any students. ('.$num_students.
999: ' students checked for '.$submissions.')</span><br />';
1000: }
1001: } elsif ($ctr == 1) {
1002: $gradeTable =~ s/type=checkbox/type=checkbox checked/;
1003: }
1004: $gradeTable.=&show_grading_menu_form($symb);
1005: $request->print($gradeTable);
1006: return '';
1007: }
1008:
1009: #---- Called from the listStudents routine
1010:
1011: sub check_script {
1012: my ($form, $type)=@_;
1013: my $chkallscript='<script type="text/javascript">
1014: function checkall() {
1015: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1016: ele = document.forms.'.$form.'.elements[i];
1017: if (ele.name == "'.$type.'") {
1018: document.forms.'.$form.'.elements[i].checked=true;
1019: }
1020: }
1021: }
1022:
1023: function checksec() {
1024: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1025: ele = document.forms.'.$form.'.elements[i];
1026: string = document.forms.'.$form.'.chksec.value;
1027: if
1028: (ele.value.indexOf(":::SECTION"+string)>0) {
1029: document.forms.'.$form.'.elements[i].checked=true;
1030: }
1031: }
1032: }
1033:
1034:
1035: function uncheckall() {
1036: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1037: ele = document.forms.'.$form.'.elements[i];
1038: if (ele.name == "'.$type.'") {
1039: document.forms.'.$form.'.elements[i].checked=false;
1040: }
1041: }
1042: }
1043:
1044: </script>'."\n";
1045: return $chkallscript;
1046: }
1047:
1048: sub check_buttons {
1049: my $buttons.='<input type="button" onclick="checkall()" value="Check All" />';
1050: $buttons.='<input type="button" onclick="uncheckall()" value="Uncheck All" /> ';
1051: $buttons.='<input type="button" onclick="checksec()" value="Check Section/Group" />';
1052: $buttons.='<input type="text" size="5" name="chksec" /> ';
1053: return $buttons;
1054: }
1055:
1056: # Displays the submissions for one student or a group of students
1057: sub processGroup {
1058: my ($request) = shift;
1059: my $ctr = 0;
1060: my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1061: my $total = scalar(@stuchecked)-1;
1062:
1063: foreach my $student (@stuchecked) {
1064: my ($uname,$udom,$fullname) = split(/:/,$student);
1065: $env{'form.student'} = $uname;
1066: $env{'form.userdom'} = $udom;
1067: $env{'form.fullname'} = $fullname;
1068: &submission($request,$ctr,$total);
1069: $ctr++;
1070: }
1071: return '';
1072: }
1073:
1074: #------------------------------------------------------------------------------------
1075: #
1076: #-------------------------- Next few routines handles grading by student, essentially
1077: # handles essay response type problem/part
1078: #
1079: #--- Javascript to handle the submission page functionality ---
1080: sub sub_page_js {
1081: my $request = shift;
1082: $request->print(<<SUBJAVASCRIPT);
1083: <script type="text/javascript" language="javascript">
1084: function updateRadio(formname,id,weight) {
1085: var gradeBox = formname["GD_BOX"+id];
1086: var radioButton = formname["RADVAL"+id];
1087: var oldpts = formname["oldpts"+id].value;
1088: var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1089: gradeBox.value = pts;
1090: var resetbox = false;
1091: if (isNaN(pts) || pts < 0) {
1092: alert("A number equal or greater than 0 is expected. Entered value = "+pts);
1093: for (var i=0; i<radioButton.length; i++) {
1094: if (radioButton[i].checked) {
1095: gradeBox.value = i;
1096: resetbox = true;
1097: }
1098: }
1099: if (!resetbox) {
1100: formtextbox.value = "";
1101: }
1102: return;
1103: }
1104:
1105: if (pts > weight) {
1106: var resp = confirm("You entered a value ("+pts+
1107: ") greater than the weight for the part. Accept?");
1108: if (resp == false) {
1109: gradeBox.value = oldpts;
1110: return;
1111: }
1112: }
1113:
1114: for (var i=0; i<radioButton.length; i++) {
1115: radioButton[i].checked=false;
1116: if (pts == i && pts != "") {
1117: radioButton[i].checked=true;
1118: }
1119: }
1120: updateSelect(formname,id);
1121: formname["stores"+id].value = "0";
1122: }
1123:
1124: function writeBox(formname,id,pts) {
1125: var gradeBox = formname["GD_BOX"+id];
1126: if (checkSolved(formname,id) == 'update') {
1127: gradeBox.value = pts;
1128: } else {
1129: var oldpts = formname["oldpts"+id].value;
1130: gradeBox.value = oldpts;
1131: var radioButton = formname["RADVAL"+id];
1132: for (var i=0; i<radioButton.length; i++) {
1133: radioButton[i].checked=false;
1134: if (i == oldpts) {
1135: radioButton[i].checked=true;
1136: }
1137: }
1138: }
1139: formname["stores"+id].value = "0";
1140: updateSelect(formname,id);
1141: return;
1142: }
1143:
1144: function clearRadBox(formname,id) {
1145: if (checkSolved(formname,id) == 'noupdate') {
1146: updateSelect(formname,id);
1147: return;
1148: }
1149: gradeSelect = formname["GD_SEL"+id];
1150: for (var i=0; i<gradeSelect.length; i++) {
1151: if (gradeSelect[i].selected) {
1152: var selectx=i;
1153: }
1154: }
1155: var stores = formname["stores"+id];
1156: if (selectx == stores.value) { return };
1157: var gradeBox = formname["GD_BOX"+id];
1158: gradeBox.value = "";
1159: var radioButton = formname["RADVAL"+id];
1160: for (var i=0; i<radioButton.length; i++) {
1161: radioButton[i].checked=false;
1162: }
1163: stores.value = selectx;
1164: }
1165:
1166: function checkSolved(formname,id) {
1167: if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1168: var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
1169: if (!reply) {return "noupdate";}
1170: formname.overRideScore.value = 'yes';
1171: }
1172: return "update";
1173: }
1174:
1175: function updateSelect(formname,id) {
1176: formname["GD_SEL"+id][0].selected = true;
1177: return;
1178: }
1179:
1180: //=========== Check that a point is assigned for all the parts ============
1181: function checksubmit(formname,val,total,parttot) {
1182: formname.gradeOpt.value = val;
1183: if (val == "Save & Next") {
1184: for (i=0;i<=total;i++) {
1185: for (j=0;j<parttot;j++) {
1186: var partid = formname["partid"+i+"_"+j].value;
1187: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1188: var points = formname["GD_BOX"+i+"_"+partid].value;
1189: if (points == "") {
1190: var name = formname["name"+i].value;
1191: var studentID = (name != '' ? name : formname["unamedom"+i].value);
1192: var resp = confirm("You did not assign a score for "+studentID+
1193: ", part "+partid+". Continue?");
1194: if (resp == false) {
1195: formname["GD_BOX"+i+"_"+partid].focus();
1196: return false;
1197: }
1198: }
1199: }
1200:
1201: }
1202: }
1203:
1204: }
1205: if (val == "Grade Student") {
1206: formname.showgrading.value = "yes";
1207: if (formname.Status.value == "") {
1208: formname.Status.value = "Active";
1209: }
1210: formname.studentNo.value = total;
1211: }
1212: formname.submit();
1213: }
1214:
1215: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
1216: function checkSubmitPage(formname,total) {
1217: noscore = new Array(100);
1218: var ptr = 0;
1219: for (i=1;i<total;i++) {
1220: var partid = formname["q_"+i].value;
1221: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1222: var points = formname["GD_BOX"+i+"_"+partid].value;
1223: var status = formname["solved"+i+"_"+partid].value;
1224: if (points == "" && status != "correct_by_student") {
1225: noscore[ptr] = i;
1226: ptr++;
1227: }
1228: }
1229: }
1230: if (ptr != 0) {
1231: var sense = ptr == 1 ? ": " : "s: ";
1232: var prolist = "";
1233: if (ptr == 1) {
1234: prolist = noscore[0];
1235: } else {
1236: var i = 0;
1237: while (i < ptr-1) {
1238: prolist += noscore[i]+", ";
1239: i++;
1240: }
1241: prolist += "and "+noscore[i];
1242: }
1243: var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
1244: if (resp == false) {
1245: return false;
1246: }
1247: }
1248:
1249: formname.submit();
1250: }
1251: </script>
1252: SUBJAVASCRIPT
1253: }
1254:
1255: #--- javascript for essay type problem --
1256: sub sub_page_kw_js {
1257: my $request = shift;
1258: my $iconpath = $request->dir_config('lonIconsURL');
1259: &commonJSfunctions($request);
1260:
1261: my $inner_js_msg_central=<<INNERJS;
1262: <script text="text/javascript">
1263: function checkInput() {
1264: opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
1265: var nmsg = opener.document.SCORE.savemsgN.value;
1266: var usrctr = document.msgcenter.usrctr.value;
1267: var newval = opener.document.SCORE["newmsg"+usrctr];
1268: newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
1269:
1270: var msgchk = "";
1271: if (document.msgcenter.subchk.checked) {
1272: msgchk = "msgsub,";
1273: }
1274: var includemsg = 0;
1275: for (var i=1; i<=nmsg; i++) {
1276: var opnmsg = opener.document.SCORE["savemsg"+i];
1277: var frmmsg = document.msgcenter["msg"+i];
1278: opnmsg.value = opener.checkEntities(frmmsg.value);
1279: var showflg = opener.document.SCORE["shownOnce"+i];
1280: showflg.value = "1";
1281: var chkbox = document.msgcenter["msgn"+i];
1282: if (chkbox.checked) {
1283: msgchk += "savemsg"+i+",";
1284: includemsg = 1;
1285: }
1286: }
1287: if (document.msgcenter.newmsgchk.checked) {
1288: msgchk += "newmsg"+usrctr;
1289: includemsg = 1;
1290: }
1291: imgformname = opener.document.SCORE["mailicon"+usrctr];
1292: imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
1293: var includemsg = opener.document.SCORE["includemsg"+usrctr];
1294: includemsg.value = msgchk;
1295:
1296: self.close()
1297:
1298: }
1299: </script>
1300: INNERJS
1301:
1302: my $inner_js_highlight_central=<<INNERJS;
1303: <script type="text/javascript">
1304: function updateChoice(flag) {
1305: opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
1306: opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
1307: opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
1308: opener.document.SCORE.refresh.value = "on";
1309: if (opener.document.SCORE.keywords.value!=""){
1310: opener.document.SCORE.submit();
1311: }
1312: self.close()
1313: }
1314: </script>
1315: INNERJS
1316:
1317: my $start_page_msg_central =
1318: &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
1319: {'js_ready' => 1,
1320: 'only_body' => 1,
1321: 'bgcolor' =>'#FFFFFF',});
1322: my $end_page_msg_central =
1323: &Apache::loncommon::end_page({'js_ready' => 1});
1324:
1325:
1326: my $start_page_highlight_central =
1327: &Apache::loncommon::start_page('Highlight Central',
1328: $inner_js_highlight_central,
1329: {'js_ready' => 1,
1330: 'only_body' => 1,
1331: 'bgcolor' =>'#FFFFFF',});
1332: my $end_page_highlight_central =
1333: &Apache::loncommon::end_page({'js_ready' => 1});
1334:
1335: my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1336: $docopen=~s/^document\.//;
1337: $request->print(<<SUBJAVASCRIPT);
1338: <script type="text/javascript" language="javascript">
1339:
1340: //===================== Show list of keywords ====================
1341: function keywords(formname) {
1342: var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1343: if (nret==null) return;
1344: formname.keywords.value = nret;
1345:
1346: if (formname.keywords.value != "") {
1347: formname.refresh.value = "on";
1348: formname.submit();
1349: }
1350: return;
1351: }
1352:
1353: //===================== Script to view submitted by ==================
1354: function viewSubmitter(submitter) {
1355: document.SCORE.refresh.value = "on";
1356: document.SCORE.NCT.value = "1";
1357: document.SCORE.unamedom0.value = submitter;
1358: document.SCORE.submit();
1359: return;
1360: }
1361:
1362: //===================== Script to add keyword(s) ==================
1363: function getSel() {
1364: if (document.getSelection) txt = document.getSelection();
1365: else if (document.selection) txt = document.selection.createRange().text;
1366: else return;
1367: var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
1368: if (cleantxt=="") {
1369: alert("Please select a word or group of words from document and then click this link.");
1370: return;
1371: }
1372: var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
1373: if (nret==null) return;
1374: document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1375: if (document.SCORE.keywords.value != "") {
1376: document.SCORE.refresh.value = "on";
1377: document.SCORE.submit();
1378: }
1379: return;
1380: }
1381:
1382: //====================== Script for composing message ==============
1383: // preload images
1384: img1 = new Image();
1385: img1.src = "$iconpath/mailbkgrd.gif";
1386: img2 = new Image();
1387: img2.src = "$iconpath/mailto.gif";
1388:
1389: function msgCenter(msgform,usrctr,fullname) {
1390: var Nmsg = msgform.savemsgN.value;
1391: savedMsgHeader(Nmsg,usrctr,fullname);
1392: var subject = msgform.msgsub.value;
1393: var msgchk = document.SCORE["includemsg"+usrctr].value;
1394: re = /msgsub/;
1395: var shwsel = "";
1396: if (re.test(msgchk)) { shwsel = "checked" }
1397: subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
1398: displaySubject(checkEntities(subject),shwsel);
1399: for (var i=1; i<=Nmsg; i++) {
1400: var testmsg = "savemsg"+i+",";
1401: re = new RegExp(testmsg,"g");
1402: shwsel = "";
1403: if (re.test(msgchk)) { shwsel = "checked" }
1404: var message = document.SCORE["savemsg"+i].value;
1405: message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1406: displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
1407: //any < is already converted to <, etc. However, only once!!
1408: }
1409: newmsg = document.SCORE["newmsg"+usrctr].value;
1410: shwsel = "";
1411: re = /newmsg/;
1412: if (re.test(msgchk)) { shwsel = "checked" }
1413: newMsg(newmsg,shwsel);
1414: msgTail();
1415: return;
1416: }
1417:
1418: function checkEntities(strx) {
1419: if (strx.length == 0) return strx;
1420: var orgStr = ["&", "<", ">", '"'];
1421: var newStr = ["&", "<", ">", """];
1422: var counter = 0;
1423: while (counter < 4) {
1424: strx = strReplace(strx,orgStr[counter],newStr[counter]);
1425: counter++;
1426: }
1427: return strx;
1428: }
1429:
1430: function strReplace(strx, orgStr, newStr) {
1431: return strx.split(orgStr).join(newStr);
1432: }
1433:
1434: function savedMsgHeader(Nmsg,usrctr,fullname) {
1435: var height = 70*Nmsg+250;
1436: var scrollbar = "no";
1437: if (height > 600) {
1438: height = 600;
1439: scrollbar = "yes";
1440: }
1441: var xpos = (screen.width-600)/2;
1442: xpos = (xpos < 0) ? '0' : xpos;
1443: var ypos = (screen.height-height)/2-30;
1444: ypos = (ypos < 0) ? '0' : ypos;
1445:
1446: pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1447: pWin.focus();
1448: pDoc = pWin.document;
1449: pDoc.$docopen;
1450: pDoc.write('$start_page_msg_central');
1451:
1452: pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
1453: pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1454: pDoc.write("<h3><span class=\\"LC_info\\"> Compose Message for \"+fullname+\"</span></h3><br /><br />");
1455:
1456: pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
1457: pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
1458: pDoc.write("<td><b>Type</b></td><td><b>Include</b></td><td><b>Message</td></tr>");
1459: }
1460: function displaySubject(msg,shwsel) {
1461: pDoc = pWin.document;
1462: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1463: pDoc.write("<td>Subject</td>");
1464: pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
1465: pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"></td></tr>");
1466: }
1467:
1468: function displaySavedMsg(ctr,msg,shwsel) {
1469: pDoc = pWin.document;
1470: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1471: pDoc.write("<td align=\\"center\\">"+ctr+"</td>");
1472: pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"></td>");
1473: pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"</textarea></td></tr>");
1474: }
1475:
1476: function newMsg(newmsg,shwsel) {
1477: pDoc = pWin.document;
1478: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1479: pDoc.write("<td align=\\"center\\">New</td>");
1480: pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
1481: pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"</textarea></td></tr>");
1482: }
1483:
1484: function msgTail() {
1485: pDoc = pWin.document;
1486: pDoc.write("</table>");
1487: pDoc.write("</td></tr></table> ");
1488: pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\"> ");
1489: pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1490: pDoc.write("</form>");
1491: pDoc.write('$end_page_msg_central');
1492: pDoc.close();
1493: }
1494:
1495: //====================== Script for keyword highlight options ==============
1496: function kwhighlight() {
1497: var kwclr = document.SCORE.kwclr.value;
1498: var kwsize = document.SCORE.kwsize.value;
1499: var kwstyle = document.SCORE.kwstyle.value;
1500: var redsel = "";
1501: var grnsel = "";
1502: var blusel = "";
1503: if (kwclr=="red") {var redsel="checked"};
1504: if (kwclr=="green") {var grnsel="checked"};
1505: if (kwclr=="blue") {var blusel="checked"};
1506: var sznsel = "";
1507: var sz1sel = "";
1508: var sz2sel = "";
1509: if (kwsize=="0") {var sznsel="checked"};
1510: if (kwsize=="+1") {var sz1sel="checked"};
1511: if (kwsize=="+2") {var sz2sel="checked"};
1512: var synsel = "";
1513: var syisel = "";
1514: var sybsel = "";
1515: if (kwstyle=="") {var synsel="checked"};
1516: if (kwstyle=="<i>") {var syisel="checked"};
1517: if (kwstyle=="<b>") {var sybsel="checked"};
1518: highlightCentral();
1519: highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
1520: highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
1521: highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
1522: highlightend();
1523: return;
1524: }
1525:
1526: function highlightCentral() {
1527: // if (window.hwdWin) window.hwdWin.close();
1528: var xpos = (screen.width-400)/2;
1529: xpos = (xpos < 0) ? '0' : xpos;
1530: var ypos = (screen.height-330)/2-30;
1531: ypos = (ypos < 0) ? '0' : ypos;
1532:
1533: hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1534: hwdWin.focus();
1535: var hDoc = hwdWin.document;
1536: hDoc.$docopen;
1537: hDoc.write('$start_page_highlight_central');
1538: hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1539: hDoc.write("<h3><span class=\\"LC_info\\"> Keyword Highlight Options</span></h3><br /><br />");
1540:
1541: hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
1542: hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
1543: hDoc.write("<td><b>Text Color</b></td><td><b>Font Size</b></td><td><b>Font Style</td></tr>");
1544: }
1545:
1546: function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) {
1547: var hDoc = hwdWin.document;
1548: hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1549: hDoc.write("<td align=\\"left\\">");
1550: hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+"> "+clrtxt+"</td>");
1551: hDoc.write("<td align=\\"left\\">");
1552: hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+"> "+sztxt+"</td>");
1553: hDoc.write("<td align=\\"left\\">");
1554: hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+"> "+sytxt+"</td>");
1555: hDoc.write("</tr>");
1556: }
1557:
1558: function highlightend() {
1559: var hDoc = hwdWin.document;
1560: hDoc.write("</table>");
1561: hDoc.write("</td></tr></table> ");
1562: hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\"> ");
1563: hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1564: hDoc.write("</form>");
1565: hDoc.write('$end_page_highlight_central');
1566: hDoc.close();
1567: }
1568:
1569: </script>
1570: SUBJAVASCRIPT
1571: }
1572:
1573: sub get_increment {
1574: my $increment = $env{'form.increment'};
1575: if ($increment != 1 && $increment != .5 && $increment != .25 &&
1576: $increment != .1) {
1577: $increment = 1;
1578: }
1579: return $increment;
1580: }
1581:
1582: #--- displays the grading box, used in essay type problem and grading by page/sequence
1583: sub gradeBox {
1584: my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1585: my $checkIcon = '<img alt="'.&mt('Check Mark').
1586: '" src="'.$request->dir_config('lonIconsURL').
1587: '/check.gif" height="16" border="0" />';
1588: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1589: my $wgtmsg = ($wgt > 0 ? '(problem weight)' :
1590: '<span class="LC_info">problem weight assigned by computer</span>');
1591: $wgt = ($wgt > 0 ? $wgt : '1');
1592: my $score = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1593: '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1594: my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1595: my $display_part=&get_display_part($partid,$symb);
1596: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
1597: [$partid]);
1598: my $aggtries = $$record{'resource.'.$partid.'.tries'};
1599: if ($last_resets{$partid}) {
1600: $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
1601: }
1602: $result.='<table border="0"><tr><td>'.
1603: '<b>Part: </b>'.$display_part.' <b>Points: </b></td><td>'."\n";
1604: my $ctr = 0;
1605: my $thisweight = 0;
1606: my $increment = &get_increment();
1607: $result.='<table border="0"><tr>'."\n"; # display radio buttons in a nice table 10 across
1608: while ($thisweight<=$wgt) {
1609: $result.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1610: 'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1611: $thisweight.')" value="'.$thisweight.'" '.
1612: ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1613: $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1614: $thisweight += $increment;
1615: $ctr++;
1616: }
1617: $result.='</tr></table>';
1618: $result.='</td><td> <b>or</b> </td>'."\n";
1619: $result.='<td><input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1620: ($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1621: 'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1622: $wgt.')" /></td>'."\n";
1623: $result.='<td>/'.$wgt.' '.$wgtmsg.
1624: ($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? ' '.$checkIcon : '').
1625: ' </td><td>'."\n";
1626: $result.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
1627: 'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1628: if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1629: $result.='<option></option>'.
1630: '<option selected="selected">excused</option>';
1631: } else {
1632: $result.='<option selected="selected"></option>'.
1633: '<option>excused</option>';
1634: }
1635: $result.='<option>reset status</option></select>'."\n";
1636: $result.=" \n";
1637: $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
1638: '<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
1639: '<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1640: $$record{'resource.'.$partid.'.solved'}.'" />'."\n".
1641: '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
1642: $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
1643: '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
1644: $aggtries.'" />'."\n";
1645: $result.='</td></tr></table>'."\n";
1646: $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
1647: return $result;
1648: }
1649:
1650: sub handback_box {
1651: my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
1652: my ($partlist,$handgrade,$responseType) = &response_type($symb);
1653: my (@respids);
1654: my @part_response_id = &flatten_responseType($responseType);
1655: foreach my $part_response_id (@part_response_id) {
1656: my ($part,$resp) = @{ $part_response_id };
1657: if ($part eq $partid) {
1658: push(@respids,$resp);
1659: }
1660: }
1661: my $result;
1662: foreach my $respid (@respids) {
1663: my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
1664: my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
1665: next if (!@$files);
1666: my $file_counter = 1;
1667: foreach my $file (@$files) {
1668: if ($file =~ /\/portfolio\//) {
1669: my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1670: my ($name,$version,$ext) = &file_name_version_ext($file_disp);
1671: $file_disp = "$name.$ext";
1672: $file = $file_path.$file_disp;
1673: $result.=&mt('Return commented version of [_1] to student.',
1674: '<span class="LC_filename">'.$file_disp.'</span>');
1675: $result.='<input type="file" name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1676: $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1677: $result.='(File will be uploaded when you click on Save & Next below.)<br />';
1678: $file_counter++;
1679: }
1680: }
1681: }
1682: return $result;
1683: }
1684:
1685: sub show_problem {
1686: my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1687: my $rendered;
1688: my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1689: &Apache::lonxml::remember_problem_counter();
1690: if ($mode eq 'both' or $mode eq 'text') {
1691: $rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1692: $env{'request.course.id'},
1693: undef,\%form);
1694: }
1695: if ($removeform) {
1696: $rendered=~s|<form(.*?)>||g;
1697: $rendered=~s|</form>||g;
1698: $rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1699: }
1700: my $companswer;
1701: if ($mode eq 'both' or $mode eq 'answer') {
1702: &Apache::lonxml::restore_problem_counter();
1703: $companswer=
1704: &Apache::loncommon::get_student_answers($symb,$uname,$udom,
1705: $env{'request.course.id'},
1706: %form);
1707: }
1708: if ($removeform) {
1709: $companswer=~s|<form(.*?)>||g;
1710: $companswer=~s|</form>||g;
1711: $companswer=~s|name="submit"|name="would_have_been_submit"|g;
1712: }
1713: my $result.='<table border="0" width="100%"><tr><td bgcolor="#777777">';
1714: $result.='<table border="0" width="100%">';
1715: if ($viewon) {
1716: $result.='<tr><td bgcolor="#e6ffff"><b> ';
1717: if ($mode eq 'both' or $mode eq 'text') {
1718: $result.='View of the problem - ';
1719: } else {
1720: $result.='Correct answer: ';
1721: }
1722: $result.=$env{'form.fullname'}.'</b></td></tr>';
1723: }
1724: if ($mode eq 'both') {
1725: $result.='<tr><td bgcolor="#ffffff">'.$rendered.'<br />';
1726: $result.='<b>Correct answer:</b><br />'.$companswer;
1727: } elsif ($mode eq 'text') {
1728: $result.='<tr><td bgcolor="#ffffff">'.$rendered;
1729: } elsif ($mode eq 'answer') {
1730: $result.='<tr><td bgcolor="#ffffff">'.$companswer;
1731: }
1732: $result.='</td></tr></table>';
1733: $result.='</td></tr></table><br />';
1734: return $result;
1735: }
1736:
1737: sub files_exist {
1738: my ($r, $symb) = @_;
1739: my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1740:
1741: foreach my $student (@students) {
1742: my ($uname,$udom,$fullname) = split(/:/,$student);
1743: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
1744: $udom,$uname);
1745: my ($string,$timestamp)= &get_last_submission(\%record);
1746: foreach my $submission (@$string) {
1747: my ($partid,$respid) =
1748: ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1749: my $files=&get_submitted_files($udom,$uname,$partid,$respid,
1750: \%record);
1751: return 1 if (@$files);
1752: }
1753: }
1754: return 0;
1755: }
1756:
1757: sub download_all_link {
1758: my ($r,$symb) = @_;
1759: my $all_students =
1760: join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
1761:
1762: my $parts =
1763: join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
1764:
1765: my $identifier = &Apache::loncommon::get_cgi_id();
1766: &Apache::lonnet::appenv('cgi.'.$identifier.'.students' => $all_students,
1767: 'cgi.'.$identifier.'.symb' => $symb,
1768: 'cgi.'.$identifier.'.parts' => $parts,);
1769: $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
1770: &mt('Download All Submitted Documents').'</a>');
1771: return
1772: }
1773:
1774: sub build_section_inputs {
1775: my $section_inputs;
1776: if ($env{'form.section'} eq '') {
1777: $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
1778: } else {
1779: my @sections = &Apache::loncommon::get_env_multiple('form.section');
1780: foreach my $section (@sections) {
1781: $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
1782: }
1783: }
1784: return $section_inputs;
1785: }
1786:
1787: # --------------------------- show submissions of a student, option to grade
1788: sub submission {
1789: my ($request,$counter,$total) = @_;
1790: my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
1791: $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
1792: my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
1793: $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1794: my $symb = &get_symb($request);
1795: if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1796:
1797: if (!&canview($usec)) {
1798: $request->print('<span class="LC_warning">Unable to view requested student.('.
1799: $uname.':'.$udom.' in section '.$usec.' in course id '.
1800: $env{'request.course.id'}.')</span>');
1801: $request->print(&show_grading_menu_form($symb));
1802: return;
1803: }
1804:
1805: if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
1806: if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
1807: if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
1808: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1809: my $checkIcon = '<img alt="'.&mt('Check Mark').
1810: '" src="'.$request->dir_config('lonIconsURL').
1811: '/check.gif" height="16" border="0" />';
1812:
1813: my %old_essays;
1814: # header info
1815: if ($counter == 0) {
1816: &sub_page_js($request);
1817: &sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
1818: $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ?
1819: &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1820: if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1821: &download_all_link($request, $symb);
1822: }
1823: $request->print('<h3> <span class="LC_info">Submission Record</span></h3>'."\n".
1824: '<h4> <b>Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n");
1825:
1826: if ($env{'form.handgrade'} eq 'no') {
1827: my $checkMark='<br /><br /> <b>Note:</b> Part(s) graded correct by the computer is marked with a '.
1828: $checkIcon.' symbol.'."\n";
1829: $request->print($checkMark);
1830: }
1831:
1832: # option to display problem, only once else it cause problems
1833: # with the form later since the problem has a form.
1834: if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1835: my $mode;
1836: if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1837: $mode='both';
1838: } elsif ($env{'form.vProb'} eq 'yes') {
1839: $mode='text';
1840: } elsif ($env{'form.vAns'} eq 'yes') {
1841: $mode='answer';
1842: }
1843: &Apache::lonxml::clear_problem_counter();
1844: $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1845: }
1846:
1847: # kwclr is the only variable that is guaranteed to be non blank
1848: # if this subroutine has been called once.
1849: my %keyhash = ();
1850: if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1851: %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1852: $env{'course.'.$env{'request.course.id'}.'.domain'},
1853: $env{'course.'.$env{'request.course.id'}.'.num'});
1854:
1855: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1856: $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
1857: $env{'form.kwclr'} = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
1858: $env{'form.kwsize'} = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
1859: $env{'form.kwstyle'} = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
1860: $env{'form.msgsub'} = $keyhash{$symb.'_subject'} ne '' ?
1861: $keyhash{$symb.'_subject'} : $env{'form.probTitle'};
1862: $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1863: }
1864: my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1865: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1866: $request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1867: '<input type="hidden" name="command" value="handgrade" />'."\n".
1868: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1869: '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
1870: '<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1871: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
1872: '<input type="hidden" name="refresh" value="off" />'."\n".
1873: '<input type="hidden" name="studentNo" value="" />'."\n".
1874: '<input type="hidden" name="gradeOpt" value="" />'."\n".
1875: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1876: '<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
1877: '<input type="hidden" name="vProb" value="'.$env{'form.vProb'}.'" />'."\n".
1878: '<input type="hidden" name="vAns" value="'.$env{'form.vAns'}.'" />'."\n".
1879: '<input type="hidden" name="lastSub" value="'.$env{'form.lastSub'}.'" />'."\n".
1880: &build_section_inputs().
1881: '<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1882: '<input type="hidden" name="handgrade" value="'.$env{'form.handgrade'}.'" />'."\n".
1883: '<input type="hidden" name="NCT"'.
1884: ' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1885: if ($env{'form.handgrade'} eq 'yes') {
1886: $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
1887: '<input type="hidden" name="kwclr" value="'.$env{'form.kwclr'}.'" />'."\n".
1888: '<input type="hidden" name="kwsize" value="'.$env{'form.kwsize'}.'" />'."\n".
1889: '<input type="hidden" name="kwstyle" value="'.$env{'form.kwstyle'}.'" />'."\n".
1890: '<input type="hidden" name="msgsub" value="'.$env{'form.msgsub'}.'" />'."\n".
1891: '<input type="hidden" name="shownSub" value="0" />'."\n".
1892: '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1893: foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
1894: $request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
1895: }
1896: }
1897:
1898: my ($cts,$prnmsg) = (1,'');
1899: while ($cts <= $env{'form.savemsgN'}) {
1900: $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1901: (!exists($keyhash{$symb.'_savemsg'.$cts}) ?
1902: &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1903: &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1904: '" />'."\n".
1905: '<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1906: $cts++;
1907: }
1908: $request->print($prnmsg);
1909:
1910: if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1911: #
1912: # Print out the keyword options line
1913: #
1914: $request->print(<<KEYWORDS);
1915: <b>Keyword Options:</b>
1916: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>
1917: <a href="#" onMouseDown="javascript:getSel(); return false"
1918: CLASS="page">Paste Selection to List</a>
1919: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1920: KEYWORDS
1921: #
1922: # Load the other essays for similarity check
1923: #
1924: my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1925: my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1926: $apath=&escape($apath);
1927: $apath=~s/\W/\_/gs;
1928: %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1929: }
1930: }
1931:
1932: # This is where output for one specific student would start
1933: my $bgcolor='#DDEEDD';
1934: if (int($counter/2) eq $counter) { $bgcolor='#DDDDEE'; }
1935: $request->print("\n\n".
1936: '<p><table border="2"><tr><th bgcolor="'.$bgcolor.'">'.$env{'form.fullname'}.'</th></tr><tr><td bgcolor="'.$bgcolor.'">');
1937:
1938: if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1939: my $mode;
1940: if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1941: $mode='both';
1942: } elsif ($env{'form.vProb'} eq 'all' ) {
1943: $mode='text';
1944: } elsif ($env{'form.vAns'} eq 'all') {
1945: $mode='answer';
1946: }
1947: &Apache::lonxml::clear_problem_counter();
1948: $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode));
1949: }
1950:
1951: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1952: my ($partlist,$handgrade,$responseType) = &response_type($symb);
1953:
1954: # Display student info
1955: $request->print(($counter == 0 ? '' : '<br />'));
1956: my $result='<table border="0" width="100%"><tr><td bgcolor="#777777">'."\n".
1957: '<table border="0" width="100%"><tr bgcolor="#edffff"><td>'."\n";
1958:
1959: $result.='<b>Fullname: </b>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'<br />'."\n";
1960: $result.='<input type="hidden" name="name'.$counter.
1961: '" value="'.$env{'form.fullname'}.'" />'."\n";
1962:
1963: # If any part of the problem is an essay-response (handgraded), then check for collaborators
1964: my @col_fullnames;
1965: my ($classlist,$fullname);
1966: if ($env{'form.handgrade'} eq 'yes') {
1967: ($classlist,undef,$fullname) = &getclasslist('all','0');
1968: for (keys (%$handgrade)) {
1969: my $ncol = &Apache::lonnet::EXT('resource.'.$_.
1970: '.maxcollaborators',
1971: $symb,$udom,$uname);
1972: next if ($ncol <= 0);
1973: s/\_/\./g;
1974: next if ($record{'resource.'.$_.'.collaborators'} eq '');
1975: my @goodcollaborators = ();
1976: my @badcollaborators = ();
1977: foreach (split(/,?\s+/,$record{'resource.'.$_.'.collaborators'})) {
1978: $_ =~ s/[\$\^\(\)]//g;
1979: next if ($_ eq '');
1980: my ($co_name,$co_dom) = split /\@|:/,$_;
1981: $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
1982: next if ($co_name eq $uname && $co_dom eq $udom);
1983: # Doing this grep allows 'fuzzy' specification
1984: my @Matches = grep /^$co_name:$co_dom$/i,keys %$classlist;
1985: if (! scalar(@Matches)) {
1986: push @badcollaborators,$_;
1987: } else {
1988: push @goodcollaborators, @Matches;
1989: }
1990: }
1991: if (scalar(@goodcollaborators) != 0) {
1992: $result.='<b>Collaborators: </b>';
1993: foreach (@goodcollaborators) {
1994: my ($lastname,$givenn) = split(/,/,$$fullname{$_});
1995: push @col_fullnames, $givenn.' '.$lastname;
1996: $result.=$$fullname{$_}.' ';
1997: }
1998: $result.='<br />'."\n";
1999: my ($part)=split(/\./,$_);
2000: $result.='<input type="hidden" name="collaborator'.$counter.
2001: '" value="'.$part.':'.(join ':',@goodcollaborators).'" />'.
2002: "\n";
2003: }
2004: if (scalar(@badcollaborators) > 0) {
2005: $result.='<table border="0"><tr bgcolor="#ffbbbb"><td>';
2006: $result.='This student has submitted ';
2007: $result.=(scalar(@badcollaborators) == 1) ? 'an invalid collaborator' : 'invalid collaborators';
2008: $result .= ': '.join(', ',@badcollaborators);
2009: $result .= '</td></tr></table>';
2010: }
2011: if (scalar(@badcollaborators > $ncol)) {
2012: $result .= '<table border="0"><tr bgcolor="#ffbbbb"><td>';
2013: $result .= 'This student has submitted too many '.
2014: 'collaborators. Maximum is '.$ncol.'.';
2015: $result .= '</td></tr></table>';
2016: }
2017: }
2018: }
2019: $request->print($result."\n");
2020:
2021: # print student answer/submission
2022: # Options are (1) Handgaded submission only
2023: # (2) Last submission, includes submission that is not handgraded
2024: # (for multi-response type part)
2025: # (3) Last submission plus the parts info
2026: # (4) The whole record for this student
2027: if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
2028: my ($string,$timestamp)= &get_last_submission(\%record);
2029: my $lastsubonly=''.
2030: ($$timestamp eq '' ? '' : '<b>Date Submitted:</b> '.
2031: $$timestamp)."</td></tr>\n";
2032: if ($$timestamp eq '') {
2033: $lastsubonly.='<tr><td bgcolor="#ffffe6">'.$$string[0];
2034: } else {
2035: my %seenparts;
2036: my @part_response_id = &flatten_responseType($responseType);
2037: foreach my $part (@part_response_id) {
2038: next if ($env{'form.lastSub'} eq 'hdgrade'
2039: && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
2040:
2041: my ($partid,$respid) = @{ $part };
2042: my $display_part=&get_display_part($partid,$symb);
2043: if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
2044: if (exists($seenparts{$partid})) { next; }
2045: $seenparts{$partid}=1;
2046: my $submitby='<b>Part:</b> '.$display_part.
2047: ' <b>Collaborative submission by:</b> '.
2048: '<a href="javascript:viewSubmitter(\''.
2049: $env{"form.$uname:$udom:$partid:submitted_by"}.
2050: '\');" target="_self">'.
2051: $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
2052: $request->print($submitby);
2053: next;
2054: }
2055: my $responsetype = $responseType->{$partid}->{$respid};
2056: if (!exists($record{"resource.$partid.$respid.submission"})) {
2057: $lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
2058: $display_part.' <span class="LC_internal_info">( ID '.$respid.
2059: ' )</span> '.
2060: '<span class="LC_warning">Nothing submitted - no attempts</span><br /><br />';
2061: next;
2062: }
2063: foreach (@$string) {
2064: my ($partid,$respid) = /^resource\.([^\.]*)\.([^\.]*)\.submission/;
2065: if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
2066: my ($ressub,$subval) = split(/:/,$_,2);
2067: # Similarity check
2068: my $similar='';
2069: if($env{'form.checkPlag'}){
2070: my ($oname,$odom,$ocrsid,$oessay,$osim)=
2071: &most_similar($uname,$udom,$subval,\%old_essays);
2072: if ($osim) {
2073: $osim=int($osim*100.0);
2074: my %old_course_desc =
2075: &Apache::lonnet::coursedescription($ocrsid,
2076: {'one_time' => 1});
2077:
2078: $similar="<hr /><h3><span class=\"LC_warning\">".
2079: &mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
2080: $osim,
2081: &Apache::loncommon::plainname($oname,$odom),
2082: $oname,$odom,
2083: $old_course_desc{'description'},
2084: $old_course_desc{'num'},
2085: $old_course_desc{'domain'}).
2086: '</span></h3><blockquote><i>'.
2087: &keywords_highlight($oessay).
2088: '</i></blockquote><hr />';
2089: }
2090: }
2091: my $order=&get_order($partid,$respid,$symb,$uname,$udom);
2092: if ($env{'form.lastSub'} eq 'lastonly' ||
2093: ($env{'form.lastSub'} eq 'hdgrade' &&
2094: $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
2095: my $display_part=&get_display_part($partid,$symb);
2096: $lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
2097: $display_part.' <span class="LC_internal_info">( ID '.$respid.
2098: ' )</span> ';
2099: my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
2100: if (@$files) {
2101: $lastsubonly.='<br /><span class="LC_warning">Like all files provided by users, this file may contain virusses</span><br />';
2102: my $file_counter = 0;
2103: foreach my $file (@$files) {
2104: $file_counter ++;
2105: &Apache::lonnet::allowuploaded('/adm/grades',$file);
2106: $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
2107: }
2108: $lastsubonly.='<br />';
2109: }
2110: $lastsubonly.='<b>Submitted Answer: </b>'.
2111: &cleanRecord($subval,$responsetype,$symb,$partid,
2112: $respid,\%record,$order);
2113: if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
2114: }
2115: }
2116: }
2117: }
2118: $lastsubonly.='</td></tr><tr bgcolor="#ffffff"><td>'."\n";
2119: $request->print($lastsubonly);
2120: } elsif ($env{'form.lastSub'} eq 'datesub') {
2121: my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
2122: $request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
2123: } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
2124: $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
2125: $env{'request.course.id'},
2126: $last,'.submission',
2127: 'Apache::grades::keywords_highlight'));
2128: }
2129:
2130: $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
2131: .$udom.'" />'."\n");
2132:
2133: # return if view submission with no grading option
2134: if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
2135: my $toGrade.='<input type="button" value="Grade Student" '.
2136: 'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
2137: .$counter.'\');" target="_self" /> '."\n" if (&canmodify($usec));
2138: $toGrade.='</td></tr></table></td></tr></table>'."\n";
2139: if (($env{'form.command'} eq 'submission') ||
2140: ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
2141: $toGrade.='</form>'.&show_grading_menu_form($symb);
2142: }
2143: $request->print($toGrade);
2144: return;
2145: } else {
2146: $request->print('</td></tr></table></td></tr></table>'."\n");
2147: }
2148:
2149: # essay grading message center
2150: if ($env{'form.handgrade'} eq 'yes') {
2151: my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
2152: my $msgfor = $givenn.' '.$lastname;
2153: if (scalar(@col_fullnames) > 0) {
2154: my $lastone = pop @col_fullnames;
2155: $msgfor .= ', '.(join ', ',@col_fullnames).' and '.$lastone.'.';
2156: }
2157: $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
2158: $result='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
2159: '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
2160: $result.=' <a href="javascript:msgCenter(document.SCORE,'.$counter.
2161: ',\''.$msgfor.'\');" target="_self">'.
2162: &mt('Compose message to student').(scalar(@col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
2163: &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
2164: '<img src="'.$request->dir_config('lonIconsURL').
2165: '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
2166: '<br /> ('.
2167: &mt('Message will be sent when you click on Save & Next below.').")\n";
2168: $request->print($result);
2169: }
2170: if ($perm{'vgr'}) {
2171: $request->print('<br />'.
2172: &Apache::loncommon::track_student_link(&mt('View recent activity'),
2173: $uname,$udom,'check'));
2174: }
2175: if ($perm{'opa'}) {
2176: $request->print('<br />'.
2177: &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
2178: $uname,$udom,$symb,'check'));
2179: }
2180:
2181: my %seen = ();
2182: my @partlist;
2183: my @gradePartRespid;
2184: my @part_response_id = &flatten_responseType($responseType);
2185: foreach my $part_response_id (@part_response_id) {
2186: my ($partid,$respid) = @{ $part_response_id };
2187: my $part_resp = join('_',@{ $part_response_id });
2188: next if ($seen{$partid} > 0);
2189: $seen{$partid}++;
2190: next if ($$handgrade{$part_resp} ne 'yes'
2191: && $env{'form.lastSub'} eq 'hdgrade');
2192: push @partlist,$partid;
2193: push @gradePartRespid,$partid.'.'.$respid;
2194: $request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
2195: }
2196: $result='<input type="hidden" name="partlist'.$counter.
2197: '" value="'.(join ":",@partlist).'" />'."\n";
2198: $result.='<input type="hidden" name="gradePartRespid'.
2199: '" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
2200: my $ctr = 0;
2201: while ($ctr < scalar(@partlist)) {
2202: $result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
2203: $partlist[$ctr].'" />'."\n";
2204: $ctr++;
2205: }
2206: $request->print($result.'</td></tr></table></td></tr></table>'."\n");
2207:
2208: # Done with printing info for one student
2209:
2210: $request->print('</td></tr></table></p>');
2211:
2212:
2213: # print end of form
2214: if ($counter == $total) {
2215: my $endform='<table border="0"><tr><td>'."\n";
2216: $endform.='<input type="button" value="Save & Next" '.
2217: 'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
2218: $total.','.scalar(@partlist).');" target="_self" /> '."\n";
2219: my $ntstu ='<select name="NTSTU">'.
2220: '<option>1</option><option>2</option>'.
2221: '<option>3</option><option>5</option>'.
2222: '<option>7</option><option>10</option></select>'."\n";
2223: my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
2224: $ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
2225: $endform.=$ntstu.'student(s) ';
2226: $endform.='<input type="button" value="Previous" '.
2227: 'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> '."\n".
2228: '<input type="button" value="Next" '.
2229: 'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> ';
2230: $endform.='(Next and Previous (student) do not save the scores.)'."\n" ;
2231: $endform.="<input type='hidden' value='".&get_increment().
2232: "' name='increment' />";
2233: $endform.='</td><tr></table></form>';
2234: $endform.=&show_grading_menu_form($symb);
2235: $request->print($endform);
2236: }
2237: return '';
2238: }
2239:
2240: #--- Retrieve the last submission for all the parts
2241: sub get_last_submission {
2242: my ($returnhash)=@_;
2243: my (@string,$timestamp);
2244: if ($$returnhash{'version'}) {
2245: my %lasthash=();
2246: my ($version);
2247: for ($version=1;$version<=$$returnhash{'version'};$version++) {
2248: foreach my $key (sort(split(/\:/,
2249: $$returnhash{$version.':keys'}))) {
2250: $lasthash{$key}=$$returnhash{$version.':'.$key};
2251: $timestamp =
2252: scalar(localtime($$returnhash{$version.':timestamp'}));
2253: }
2254: }
2255: foreach my $key (keys(%lasthash)) {
2256: next if ($key !~ /\.submission$/);
2257:
2258: my ($partid,$foo) = split(/submission$/,$key);
2259: my $draft = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
2260: '<span class="LC_warning">Draft Copy</span> ' : '';
2261: push(@string, join(':', $key, $draft.$lasthash{$key}));
2262: }
2263: }
2264: if (!@string) {
2265: $string[0] =
2266: '<span class="LC_warning">Nothing submitted - no attempts.</span>';
2267: }
2268: return (\@string,\$timestamp);
2269: }
2270:
2271: #--- High light keywords, with style choosen by user.
2272: sub keywords_highlight {
2273: my $string = shift;
2274: my $size = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
2275: my $styleon = $env{'form.kwstyle'} eq '' ? '' : $env{'form.kwstyle'};
2276: (my $styleoff = $styleon) =~ s/\</\<\//;
2277: my @keylist = split(/[,\s+]/,$env{'form.keywords'});
2278: foreach my $keyword (@keylist) {
2279: $string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
2280: }
2281: return $string;
2282: }
2283:
2284: #--- Called from submission routine
2285: sub processHandGrade {
2286: my ($request) = shift;
2287: my $symb = &get_symb($request);
2288: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
2289: my $button = $env{'form.gradeOpt'};
2290: my $ngrade = $env{'form.NCT'};
2291: my $ntstu = $env{'form.NTSTU'};
2292: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2293: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2294:
2295: if ($button eq 'Save & Next') {
2296: my $ctr = 0;
2297: while ($ctr < $ngrade) {
2298: my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
2299: my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
2300: if ($errorflag eq 'no_score') {
2301: $ctr++;
2302: next;
2303: }
2304: if ($errorflag eq 'not_allowed') {
2305: $request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
2306: $ctr++;
2307: next;
2308: }
2309: my $includemsg = $env{'form.includemsg'.$ctr};
2310: my ($subject,$message,$msgstatus) = ('','','');
2311: my $restitle = &Apache::lonnet::gettitle($symb);
2312: my ($feedurl,$showsymb) =
2313: &get_feedurl_and_symb($symb,$uname,$udom);
2314: my $messagetail;
2315: if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
2316: $subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
2317: unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
2318: $subject.=' ['.$restitle.']';
2319: my (@msgnum) = split(/,/,$includemsg);
2320: foreach (@msgnum) {
2321: $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
2322: }
2323: $message =&Apache::lonfeedback::clear_out_html($message);
2324: if ($env{'form.withgrades'.$ctr}) {
2325: $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
2326: $messagetail = " for <a href=\"".
2327: $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
2328: }
2329: $msgstatus =
2330: &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
2331: $message.$messagetail,
2332: undef,$feedurl,undef,
2333: undef,undef,$showsymb,
2334: $restitle);
2335: $request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
2336: $msgstatus);
2337: }
2338: if ($env{'form.collaborator'.$ctr}) {
2339: my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
2340: foreach my $collabstr (@collabstrs) {
2341: my ($part,@collaborators) = split(/:/,$collabstr);
2342: foreach my $collaborator (@collaborators) {
2343: my ($errorflag,$pts,$wgt) =
2344: &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
2345: $env{'form.unamedom'.$ctr},$part);
2346: if ($errorflag eq 'not_allowed') {
2347: $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
2348: next;
2349: } elsif ($message ne '') {
2350: my ($baseurl,$showsymb) =
2351: &get_feedurl_and_symb($symb,$collaborator,
2352: $udom);
2353: if ($env{'form.withgrades'.$ctr}) {
2354: $messagetail = " for <a href=\"".
2355: $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
2356: }
2357: $msgstatus =
2358: &Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
2359: }
2360: }
2361: }
2362: }
2363: $ctr++;
2364: }
2365: }
2366:
2367: if ($env{'form.handgrade'} eq 'yes') {
2368: # Keywords sorted in alphabatical order
2369: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
2370: my %keyhash = ();
2371: $env{'form.keywords'} =~ s/,\s{0,}|\s+/ /g;
2372: $env{'form.keywords'} =~ s/^\s+|\s+$//;
2373: my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
2374: $env{'form.keywords'} = join(' ',@keywords);
2375: $keyhash{$symb.'_keywords'} = $env{'form.keywords'};
2376: $keyhash{$symb.'_subject'} = $env{'form.msgsub'};
2377: $keyhash{$loginuser.'_kwclr'} = $env{'form.kwclr'};
2378: $keyhash{$loginuser.'_kwsize'} = $env{'form.kwsize'};
2379: $keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
2380:
2381: # message center - Order of message gets changed. Blank line is eliminated.
2382: # New messages are saved in env for the next student.
2383: # All messages are saved in nohist_handgrade.db
2384: my ($ctr,$idx) = (1,1);
2385: while ($ctr <= $env{'form.savemsgN'}) {
2386: if ($env{'form.savemsg'.$ctr} ne '') {
2387: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
2388: $idx++;
2389: }
2390: $ctr++;
2391: }
2392: $ctr = 0;
2393: while ($ctr < $ngrade) {
2394: if ($env{'form.newmsg'.$ctr} ne '') {
2395: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2396: $env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2397: $idx++;
2398: }
2399: $ctr++;
2400: }
2401: $env{'form.savemsgN'} = --$idx;
2402: $keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
2403: my $putresult = &Apache::lonnet::put
2404: ('nohist_handgrade',\%keyhash,$cdom,$cnum);
2405: }
2406: # Called by Save & Refresh from Highlight Attribute Window
2407: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
2408: if ($env{'form.refresh'} eq 'on') {
2409: my ($ctr,$total) = (0,0);
2410: while ($ctr < $ngrade) {
2411: $total++ if $env{'form.unamedom'.$ctr} ne '';
2412: $ctr++;
2413: }
2414: $env{'form.NTSTU'}=$ngrade;
2415: $ctr = 0;
2416: while ($ctr < $total) {
2417: my $processUser = $env{'form.unamedom'.$ctr};
2418: ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
2419: $env{'form.fullname'} = $$fullname{$processUser};
2420: &submission($request,$ctr,$total-1);
2421: $ctr++;
2422: }
2423: return '';
2424: }
2425:
2426: # Go directly to grade student - from submission or link from chart page
2427: if ($button eq 'Grade Student') {
2428: (undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
2429: my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
2430: ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
2431: $env{'form.fullname'} = $$fullname{$processUser};
2432: &submission($request,0,0);
2433: return '';
2434: }
2435:
2436: # Get the next/previous one or group of students
2437: my $firststu = $env{'form.unamedom0'};
2438: my $laststu = $env{'form.unamedom'.($ngrade-1)};
2439: my $ctr = 2;
2440: while ($laststu eq '') {
2441: $laststu = $env{'form.unamedom'.($ngrade-$ctr)};
2442: $ctr++;
2443: $laststu = $firststu if ($ctr > $ngrade);
2444: }
2445:
2446: my (@parsedlist,@nextlist);
2447: my ($nextflg) = 0;
2448: foreach (sort
2449: {
2450: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
2451: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
2452: }
2453: return $a cmp $b;
2454: } (keys(%$fullname))) {
2455: if ($nextflg == 1 && $button =~ /Next$/) {
2456: push @parsedlist,$_;
2457: }
2458: $nextflg = 1 if ($_ eq $laststu);
2459: if ($button eq 'Previous') {
2460: last if ($_ eq $firststu);
2461: push @parsedlist,$_;
2462: }
2463: }
2464: $ctr = 0;
2465: @parsedlist = reverse @parsedlist if ($button eq 'Previous');
2466: my ($partlist) = &response_type($symb);
2467: foreach my $student (@parsedlist) {
2468: my $submitonly=$env{'form.submitonly'};
2469: my ($uname,$udom) = split(/:/,$student);
2470:
2471: if ($submitonly eq 'queued') {
2472: my %queue_status =
2473: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
2474: $udom,$uname);
2475: next if (!defined($queue_status{'gradingqueue'}));
2476: }
2477:
2478: if ($submitonly =~ /^(yes|graded|incorrect)$/) {
2479: # my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
2480: my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
2481: my $submitted = 0;
2482: my $ungraded = 0;
2483: my $incorrect = 0;
2484: foreach (keys(%status)) {
2485: $submitted = 1 if ($status{$_} ne 'nothing');
2486: $ungraded = 1 if ($status{$_} =~ /^ungraded/);
2487: $incorrect = 1 if ($status{$_} =~ /^incorrect/);
2488: my ($foo,$partid,$foo1) = split(/\./,$_);
2489: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
2490: $submitted = 0;
2491: }
2492: }
2493: next if (!$submitted && ($submitonly eq 'yes' ||
2494: $submitonly eq 'incorrect' ||
2495: $submitonly eq 'graded'));
2496: next if (!$ungraded && ($submitonly eq 'graded'));
2497: next if (!$incorrect && $submitonly eq 'incorrect');
2498: }
2499: push @nextlist,$student if ($ctr < $ntstu);
2500: last if ($ctr == $ntstu);
2501: $ctr++;
2502: }
2503:
2504: $ctr = 0;
2505: my $total = scalar(@nextlist)-1;
2506:
2507: foreach (sort @nextlist) {
2508: my ($uname,$udom,$submitter) = split(/:/);
2509: $env{'form.student'} = $uname;
2510: $env{'form.userdom'} = $udom;
2511: $env{'form.fullname'} = $$fullname{$_};
2512: &submission($request,$ctr,$total);
2513: $ctr++;
2514: }
2515: if ($total < 0) {
2516: my $the_end = '<h3><span class="LC_info">LON-CAPA User Message</span></h3><br />'."\n";
2517: $the_end.='<b>Message: </b> No more students for this section or class.<br /><br />'."\n";
2518: $the_end.='Click on the button below to return to the grading menu.<br /><br />'."\n";
2519: $the_end.=&show_grading_menu_form($symb);
2520: $request->print($the_end);
2521: }
2522: return '';
2523: }
2524:
2525: #---- Save the score and award for each student, if changed
2526: sub saveHandGrade {
2527: my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
2528: my @version_parts;
2529: my $usec = &Apache::lonnet::getsection($domain,$stuname,
2530: $env{'request.course.id'});
2531: if (!&canmodify($usec)) { return('not_allowed'); }
2532: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
2533: my @parts_graded;
2534: my %newrecord = ();
2535: my ($pts,$wgt) = ('','');
2536: my %aggregate = ();
2537: my $aggregateflag = 0;
2538: my @parts = split(/:/,$env{'form.partlist'.$newflg});
2539: foreach my $new_part (@parts) {
2540: #collaborator ($submi may vary for different parts
2541: if ($submitter && $new_part ne $part) { next; }
2542: my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
2543: if ($dropMenu eq 'excused') {
2544: if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
2545: $newrecord{'resource.'.$new_part.'.solved'} = 'excused';
2546: if (exists($record{'resource.'.$new_part.'.awarded'})) {
2547: $newrecord{'resource.'.$new_part.'.awarded'} = '';
2548: }
2549: $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
2550: }
2551: } elsif ($dropMenu eq 'reset status'
2552: && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
2553: foreach my $key (keys (%record)) {
2554: if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
2555: }
2556: $newrecord{'resource.'.$new_part.'.regrader'}=
2557: "$env{'user.name'}:$env{'user.domain'}";
2558: my $totaltries = $record{'resource.'.$part.'.tries'};
2559:
2560: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
2561: [$new_part]);
2562: my $aggtries =$totaltries;
2563: if ($last_resets{$new_part}) {
2564: $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
2565: $new_part);
2566: }
2567:
2568: my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
2569: if ($aggtries > 0) {
2570: &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
2571: $aggregateflag = 1;
2572: }
2573: } elsif ($dropMenu eq '') {
2574: $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ?
2575: $env{'form.GD_BOX'.$newflg.'_'.$new_part} :
2576: $env{'form.RADVAL'.$newflg.'_'.$new_part});
2577: if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
2578: next;
2579: }
2580: $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 :
2581: $env{'form.WGT'.$newflg.'_'.$new_part};
2582: my $partial= $pts/$wgt;
2583: if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
2584: #do not update score for part if not changed.
2585: &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
2586: next;
2587: } else {
2588: push @parts_graded, $new_part;
2589: }
2590: if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
2591: $newrecord{'resource.'.$new_part.'.awarded'} = $partial;
2592: }
2593: my $reckey = 'resource.'.$new_part.'.solved';
2594: if ($partial == 0) {
2595: if ($record{$reckey} ne 'incorrect_by_override') {
2596: $newrecord{$reckey} = 'incorrect_by_override';
2597: }
2598: } else {
2599: if ($record{$reckey} ne 'correct_by_override') {
2600: $newrecord{$reckey} = 'correct_by_override';
2601: }
2602: }
2603: if ($submitter &&
2604: ($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
2605: $newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
2606: }
2607: $newrecord{'resource.'.$new_part.'.regrader'}=
2608: "$env{'user.name'}:$env{'user.domain'}";
2609: }
2610: # unless problem has been graded, set flag to version the submitted files
2611: unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/ ||
2612: $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
2613: $dropMenu eq 'reset status')
2614: {
2615: push (@version_parts,$new_part);
2616: }
2617: }
2618: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2619: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2620:
2621: if (%newrecord) {
2622: if (@version_parts) {
2623: my @changed_keys = &version_portfiles(\%record, \@parts_graded,
2624: $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
2625: @newrecord{@changed_keys} = @record{@changed_keys};
2626: foreach my $new_part (@version_parts) {
2627: &handback_files($request,$symb,$stuname,$domain,$newflg,
2628: $new_part,\%newrecord);
2629: }
2630: }
2631: &Apache::lonnet::cstore(\%newrecord,$symb,
2632: $env{'request.course.id'},$domain,$stuname);
2633: &check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
2634: $cdom,$cnum,$domain,$stuname);
2635: }
2636: if ($aggregateflag) {
2637: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
2638: $cdom,$cnum);
2639: }
2640: return ('',$pts,$wgt);
2641: }
2642:
2643: sub check_and_remove_from_queue {
2644: my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
2645: my @ungraded_parts;
2646: foreach my $part (@{$parts}) {
2647: if ( $record->{ 'resource.'.$part.'.awarded'} eq ''
2648: && $record->{ 'resource.'.$part.'.solved' } ne 'excused'
2649: && $newrecord->{'resource.'.$part.'.awarded'} eq ''
2650: && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
2651: ) {
2652: push(@ungraded_parts, $part);
2653: }
2654: }
2655: if ( !@ungraded_parts ) {
2656: &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
2657: $cnum,$domain,$stuname);
2658: }
2659: }
2660:
2661: sub handback_files {
2662: my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
2663: my $portfolio_root = &propath($domain,$stuname).'/userfiles/portfolio';
2664: my ($partlist,$handgrade,$responseType) = &response_type($symb);
2665:
2666: my @part_response_id = &flatten_responseType($responseType);
2667: foreach my $part_response_id (@part_response_id) {
2668: my ($part_id,$resp_id) = @{ $part_response_id };
2669: my $part_resp = join('_',@{ $part_response_id });
2670: if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
2671: # if multiple files are uploaded names will be 'returndoc2','returndoc3'
2672: my $file_counter = 1;
2673: my $file_msg;
2674: while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
2675: my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
2676: my ($directory,$answer_file) =
2677: ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
2678: my ($answer_name,$answer_ver,$answer_ext) =
2679: &file_name_version_ext($answer_file);
2680: my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
2681: my @dir_list = &Apache::lonnet::dirlist($portfolio_path,$domain,$stuname,$portfolio_root);
2682: my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
2683: # fix file name
2684: my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
2685: my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
2686: $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
2687: $save_file_name);
2688: if ($result !~ m|^/uploaded/|) {
2689: $request->print('<span class="LC_error">An error occurred ('.$result.
2690: ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</span><br />');
2691: } else {
2692: # mark the file as read only
2693: my @files = ($save_file_name);
2694: my @what = ($symb,$env{'request.course.id'},'handback');
2695: &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
2696: if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
2697: $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
2698: }
2699: $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
2700: $file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
2701:
2702: }
2703: $request->print("<br />".$fname." will be the uploaded file name");
2704: $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
2705: $file_counter++;
2706: }
2707: my $subject = "File Handed Back by Instructor ";
2708: my $message = "A file has been returned that was originally submitted in reponse to: <br />";
2709: $message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
2710: $message .= ' The returned file(s) are named: '. $file_msg;
2711: $message .= " and can be found in your portfolio space.";
2712: my ($feedurl,$showsymb) =
2713: &get_feedurl_and_symb($symb,$domain,$stuname);
2714: my $restitle = &Apache::lonnet::gettitle($symb);
2715: my $msgstatus =
2716: &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
2717: ' (File Returned) ['.$restitle.']',$message,undef,
2718: $feedurl,undef,undef,undef,$showsymb,$restitle);
2719: }
2720: }
2721: return;
2722: }
2723:
2724: sub get_feedurl_and_symb {
2725: my ($symb,$uname,$udom) = @_;
2726: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
2727: $url = &Apache::lonnet::clutter($url);
2728: my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
2729: $symb,$udom,$uname);
2730: if ($encrypturl =~ /^yes$/i) {
2731: &Apache::lonenc::encrypted(\$url,1);
2732: &Apache::lonenc::encrypted(\$symb,1);
2733: }
2734: return ($url,$symb);
2735: }
2736:
2737: sub get_submitted_files {
2738: my ($udom,$uname,$partid,$respid,$record) = @_;
2739: my @files;
2740: if ($$record{"resource.$partid.$respid.portfiles"}) {
2741: my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
2742: foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
2743: push(@files,$file_url.$file);
2744: }
2745: }
2746: if ($$record{"resource.$partid.$respid.uploadedurl"}) {
2747: push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
2748: }
2749: return (\@files);
2750: }
2751:
2752: # ----------- Provides number of tries since last reset.
2753: sub get_num_tries {
2754: my ($record,$last_reset,$part) = @_;
2755: my $timestamp = '';
2756: my $num_tries = 0;
2757: if ($$record{'version'}) {
2758: for (my $version=$$record{'version'};$version>=1;$version--) {
2759: if (exists($$record{$version.':resource.'.$part.'.solved'})) {
2760: $timestamp = $$record{$version.':timestamp'};
2761: if ($timestamp > $last_reset) {
2762: $num_tries ++;
2763: } else {
2764: last;
2765: }
2766: }
2767: }
2768: }
2769: return $num_tries;
2770: }
2771:
2772: # ----------- Determine decrements required in aggregate totals
2773: sub decrement_aggs {
2774: my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
2775: my %decrement = (
2776: attempts => 0,
2777: users => 0,
2778: correct => 0
2779: );
2780: $decrement{'attempts'} = $aggtries;
2781: if ($solvedstatus =~ /^correct/) {
2782: $decrement{'correct'} = 1;
2783: }
2784: if ($aggtries == $totaltries) {
2785: $decrement{'users'} = 1;
2786: }
2787: foreach my $type (keys (%decrement)) {
2788: $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
2789: }
2790: return;
2791: }
2792:
2793: # ----------- Determine timestamps for last reset of aggregate totals for parts
2794: sub get_last_resets {
2795: my ($symb,$courseid,$partids) =@_;
2796: my %last_resets;
2797: my $cdom = $env{'course.'.$courseid.'.domain'};
2798: my $cname = $env{'course.'.$courseid.'.num'};
2799: my @keys;
2800: foreach my $part (@{$partids}) {
2801: push(@keys,"$symb\0$part\0resettime");
2802: }
2803: my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
2804: $cdom,$cname);
2805: foreach my $part (@{$partids}) {
2806: $last_resets{$part}=$results{"$symb\0$part\0resettime"};
2807: }
2808: return %last_resets;
2809: }
2810:
2811: # ----------- Handles creating versions for portfolio files as answers
2812: sub version_portfiles {
2813: my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
2814: my $version_parts = join('|',@$v_flag);
2815: my @returned_keys;
2816: my $parts = join('|', @$parts_graded);
2817: my $portfolio_root = &propath($domain,$stu_name).
2818: '/userfiles/portfolio';
2819: foreach my $key (keys(%$record)) {
2820: my $new_portfiles;
2821: if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
2822: my @versioned_portfiles;
2823: my @portfiles = split(/\s*,\s*/,$$record{$key});
2824: foreach my $file (@portfiles) {
2825: &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
2826: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
2827: my ($answer_name,$answer_ver,$answer_ext) =
2828: &file_name_version_ext($answer_file);
2829: my @dir_list = &Apache::lonnet::dirlist($directory,$domain,$stu_name,$portfolio_root);
2830: my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
2831: my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
2832: if ($new_answer ne 'problem getting file') {
2833: push(@versioned_portfiles, $directory.$new_answer);
2834: &Apache::lonnet::mark_as_readonly($domain,$stu_name,
2835: [$directory.$new_answer],
2836: [$symb,$env{'request.course.id'},'graded']);
2837: }
2838: }
2839: $$record{$key} = join(',',@versioned_portfiles);
2840: push(@returned_keys,$key);
2841: }
2842: }
2843: return (@returned_keys);
2844: }
2845:
2846: sub get_next_version {
2847: my ($answer_name, $answer_ext, $dir_list) = @_;
2848: my $version;
2849: foreach my $row (@$dir_list) {
2850: my ($file) = split(/\&/,$row,2);
2851: my ($file_name,$file_version,$file_ext) =
2852: &file_name_version_ext($file);
2853: if (($file_name eq $answer_name) &&
2854: ($file_ext eq $answer_ext)) {
2855: # gets here if filename and extension match, regardless of version
2856: if ($file_version ne '') {
2857: # a versioned file is found so save it for later
2858: if ($file_version > $version) {
2859: $version = $file_version;
2860: }
2861: }
2862: }
2863: }
2864: $version ++;
2865: return($version);
2866: }
2867:
2868: sub version_selected_portfile {
2869: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
2870: my ($answer_name,$answer_ver,$answer_ext) =
2871: &file_name_version_ext($file_name);
2872: my $new_answer;
2873: $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
2874: if($env{'form.copy'} eq '-1') {
2875: $new_answer = 'problem getting file';
2876: } else {
2877: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
2878: my $copy_result = &Apache::lonnet::finishuserfileupload(
2879: $stu_name,$domain,'copy',
2880: '/portfolio'.$directory.$new_answer);
2881: }
2882: return ($new_answer);
2883: }
2884:
2885: sub file_name_version_ext {
2886: my ($file)=@_;
2887: my @file_parts = split(/\./, $file);
2888: my ($name,$version,$ext);
2889: if (@file_parts > 1) {
2890: $ext=pop(@file_parts);
2891: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
2892: $version=pop(@file_parts);
2893: }
2894: $name=join('.',@file_parts);
2895: } else {
2896: $name=join('.',@file_parts);
2897: }
2898: return($name,$version,$ext);
2899: }
2900:
2901: #--------------------------------------------------------------------------------------
2902: #
2903: #-------------------------- Next few routines handles grading by section or whole class
2904: #
2905: #--- Javascript to handle grading by section or whole class
2906: sub viewgrades_js {
2907: my ($request) = shift;
2908:
2909: $request->print(<<VIEWJAVASCRIPT);
2910: <script type="text/javascript" language="javascript">
2911: function writePoint(partid,weight,point) {
2912: var radioButton = document.classgrade["RADVAL_"+partid];
2913: var textbox = document.classgrade["TEXTVAL_"+partid];
2914: if (point == "textval") {
2915: point = document.classgrade["TEXTVAL_"+partid].value;
2916: if (isNaN(point) || parseFloat(point) < 0) {
2917: alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
2918: var resetbox = false;
2919: for (var i=0; i<radioButton.length; i++) {
2920: if (radioButton[i].checked) {
2921: textbox.value = i;
2922: resetbox = true;
2923: }
2924: }
2925: if (!resetbox) {
2926: textbox.value = "";
2927: }
2928: return;
2929: }
2930: if (parseFloat(point) > parseFloat(weight)) {
2931: var resp = confirm("You entered a value ("+parseFloat(point)+
2932: ") greater than the weight for the part. Accept?");
2933: if (resp == false) {
2934: textbox.value = "";
2935: return;
2936: }
2937: }
2938: for (var i=0; i<radioButton.length; i++) {
2939: radioButton[i].checked=false;
2940: if (parseFloat(point) == i) {
2941: radioButton[i].checked=true;
2942: }
2943: }
2944:
2945: } else {
2946: textbox.value = parseFloat(point);
2947: }
2948: for (i=0;i<document.classgrade.total.value;i++) {
2949: var user = document.classgrade["ctr"+i].value;
2950: user = user.replace(new RegExp(':', 'g'),"_");
2951: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
2952: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
2953: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
2954: if (saveval != "correct") {
2955: scorename.value = point;
2956: if (selname[0].selected != true) {
2957: selname[0].selected = true;
2958: }
2959: }
2960: }
2961: document.classgrade["SELVAL_"+partid][0].selected = true;
2962: }
2963:
2964: function writeRadText(partid,weight) {
2965: var selval = document.classgrade["SELVAL_"+partid];
2966: var radioButton = document.classgrade["RADVAL_"+partid];
2967: var override = document.classgrade["FORCE_"+partid].checked;
2968: var textbox = document.classgrade["TEXTVAL_"+partid];
2969: if (selval[1].selected || selval[2].selected) {
2970: for (var i=0; i<radioButton.length; i++) {
2971: radioButton[i].checked=false;
2972:
2973: }
2974: textbox.value = "";
2975:
2976: for (i=0;i<document.classgrade.total.value;i++) {
2977: var user = document.classgrade["ctr"+i].value;
2978: user = user.replace(new RegExp(':', 'g'),"_");
2979: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
2980: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
2981: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
2982: if ((saveval != "correct") || override) {
2983: scorename.value = "";
2984: if (selval[1].selected) {
2985: selname[1].selected = true;
2986: } else {
2987: selname[2].selected = true;
2988: if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value))
2989: {document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
2990: }
2991: }
2992: }
2993: } else {
2994: for (i=0;i<document.classgrade.total.value;i++) {
2995: var user = document.classgrade["ctr"+i].value;
2996: user = user.replace(new RegExp(':', 'g'),"_");
2997: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
2998: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
2999: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3000: if ((saveval != "correct") || override) {
3001: scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
3002: selname[0].selected = true;
3003: }
3004: }
3005: }
3006: }
3007:
3008: function changeSelect(partid,user) {
3009: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
3010: var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
3011: var point = textbox.value;
3012: var weight = document.classgrade["weight_"+partid].value;
3013:
3014: if (isNaN(point) || parseFloat(point) < 0) {
3015: alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
3016: textbox.value = "";
3017: return;
3018: }
3019: if (parseFloat(point) > parseFloat(weight)) {
3020: var resp = confirm("You entered a value ("+parseFloat(point)+
3021: ") greater than the weight of the part. Accept?");
3022: if (resp == false) {
3023: textbox.value = "";
3024: return;
3025: }
3026: }
3027: selval[0].selected = true;
3028: }
3029:
3030: function changeOneScore(partid,user) {
3031: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
3032: if (selval[1].selected || selval[2].selected) {
3033: document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
3034: if (selval[2].selected) {
3035: document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
3036: }
3037: }
3038: }
3039:
3040: function resetEntry(numpart) {
3041: for (ctpart=0;ctpart<numpart;ctpart++) {
3042: var partid = document.classgrade["partid_"+ctpart].value;
3043: var radioButton = document.classgrade["RADVAL_"+partid];
3044: var textbox = document.classgrade["TEXTVAL_"+partid];
3045: var selval = document.classgrade["SELVAL_"+partid];
3046: for (var i=0; i<radioButton.length; i++) {
3047: radioButton[i].checked=false;
3048:
3049: }
3050: textbox.value = "";
3051: selval[0].selected = true;
3052:
3053: for (i=0;i<document.classgrade.total.value;i++) {
3054: var user = document.classgrade["ctr"+i].value;
3055: user = user.replace(new RegExp(':', 'g'),"_");
3056: var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3057: resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
3058: var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
3059: resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
3060: var saveselval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3061: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3062: if (saveselval == "excused") {
3063: if (selname[1].selected == false) { selname[1].selected = true;}
3064: } else {
3065: if (selname[0].selected == false) {selname[0].selected = true};
3066: }
3067: }
3068: }
3069: }
3070:
3071: </script>
3072: VIEWJAVASCRIPT
3073: }
3074:
3075: #--- show scores for a section or whole class w/ option to change/update a score
3076: sub viewgrades {
3077: my ($request) = shift;
3078: &viewgrades_js($request);
3079:
3080: my ($symb) = &get_symb($request);
3081: #need to make sure we have the correct data for later EXT calls,
3082: #thus invalidate the cache
3083: &Apache::lonnet::devalidatecourseresdata(
3084: $env{'course.'.$env{'request.course.id'}.'.num'},
3085: $env{'course.'.$env{'request.course.id'}.'.domain'});
3086: &Apache::lonnet::clear_EXT_cache_status();
3087:
3088: my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
3089: $result.='<h4><b>Current Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n";
3090:
3091: #view individual student submission form - called using Javascript viewOneStudent
3092: $result.=&jscriptNform($symb);
3093:
3094: #beginning of class grading form
3095: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
3096: $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
3097: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
3098: '<input type="hidden" name="command" value="editgrades" />'."\n".
3099: &build_section_inputs().
3100: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
3101: '<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
3102: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
3103:
3104: my $sectionClass;
3105: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3106: if ($env{'form.section'} eq 'all') {
3107: $sectionClass='Class </h3>';
3108: } elsif ($env{'form.section'} eq 'none') {
3109: $sectionClass=&mt('Students in no Section').'</h3>';
3110: } else {
3111: $sectionClass=&mt('Students in Section(s) [_1]',$section_display).'</h3>';
3112: }
3113: $result.='<h3>'.&mt('Assign Common Grade To [_1]',$sectionClass);
3114: $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
3115: '<table border=0><tr bgcolor="#ffffdd"><td>';
3116: #radio buttons/text box for assigning points for a section or class.
3117: #handles different parts of a problem
3118: my ($partlist,$handgrade,$responseType) = &response_type($symb);
3119: my %weight = ();
3120: my $ctsparts = 0;
3121: $result.='<table border="0">';
3122: my %seen = ();
3123: my @part_response_id = &flatten_responseType($responseType);
3124: foreach my $part_response_id (@part_response_id) {
3125: my ($partid,$respid) = @{ $part_response_id };
3126: my $part_resp = join('_',@{ $part_response_id });
3127: next if $seen{$partid};
3128: $seen{$partid}++;
3129: my $handgrade=$$handgrade{$part_resp};
3130: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
3131: $weight{$partid} = $wgt eq '' ? '1' : $wgt;
3132:
3133: $result.='<input type="hidden" name="partid_'.
3134: $ctsparts.'" value="'.$partid.'" />'."\n";
3135: $result.='<input type="hidden" name="weight_'.
3136: $partid.'" value="'.$weight{$partid}.'" />'."\n";
3137: my $display_part=&get_display_part($partid,$symb);
3138: $result.='<tr><td><b>Part:</b> '.$display_part.' <b>Point:</b> </td><td>';
3139: $result.='<table border="0"><tr>';
3140: my $ctr = 0;
3141: while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
3142: $result.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
3143: 'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
3144: ','.$ctr.')" />'.$ctr."</label></td>\n";
3145: $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
3146: $ctr++;
3147: }
3148: $result.='</tr></table>';
3149: $result.= '</td><td><b> or </b><input type="text" name="TEXTVAL_'.
3150: $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
3151: $partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
3152: $weight{$partid}.' (problem weight)</td>'."\n";
3153: $result.= '</td><td><select name="SELVAL_'.$partid.'"'.
3154: 'onChange="javascript:writeRadText(\''.$partid.'\','.
3155: $weight{$partid}.')"> '.
3156: '<option selected="selected"> </option>'.
3157: '<option>excused</option>'.
3158: '<option>reset status</option></select></td>'.
3159: '<td><label><input type="checkbox" name="FORCE_'.$partid.'" /> Override "Correct"</label></td></tr>'."\n";
3160: $ctsparts++;
3161: }
3162: $result.='</table>'.'</td></tr></table>'.'</td></tr></table>'."\n".
3163: '<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
3164: $result.='<input type="button" value="Revert to Default" '.
3165: 'onClick="javascript:resetEntry('.$ctsparts.');" target="_self" />';
3166:
3167: #table listing all the students in a section/class
3168: #header of table
3169: $result.= '<h3>Assign Grade to Specific Students in '.$sectionClass;
3170: $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
3171: '<table border=0><tr bgcolor="#deffff"><td> <b>No.</b> </td>'.
3172: '<td>'.&nameUserString('header')."</td>\n";
3173: my (@parts) = sort(&getpartlist($symb));
3174: my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
3175: my @partids = ();
3176: foreach my $part (@parts) {
3177: my $display=&Apache::lonnet::metadata($url,$part.'.display');
3178: $display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
3179: if (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
3180: my ($partid) = &split_part_type($part);
3181: push(@partids, $partid);
3182: my $display_part=&get_display_part($partid,$symb);
3183: if ($display =~ /^Partial Credit Factor/) {
3184: $result.='<td><b>Score Part:</b> '.$display_part.
3185: ' <br /><b>(weight = '.$weight{$partid}.')</b></td>'."\n";
3186: next;
3187: } else {
3188: $display =~s/\[Part: \Q$partid\E\]/Part:<\/b> $display_part/;
3189: }
3190: $display =~ s|Problem Status|Grade Status<br />|;
3191: $result.='<td><b>'.$display.'</td>'."\n";
3192: }
3193: $result.='</tr>';
3194:
3195: my %last_resets =
3196: &get_last_resets($symb,$env{'request.course.id'},\@partids);
3197:
3198: #get info for each student
3199: #list all the students - with points and grade status
3200: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
3201: my $ctr = 0;
3202: foreach (sort
3203: {
3204: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
3205: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
3206: }
3207: return $a cmp $b;
3208: } (keys(%$fullname))) {
3209: $ctr++;
3210: $result.=&viewstudentgrade($symb,$env{'request.course.id'},
3211: $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
3212: }
3213: $result.='</table></td></tr></table>';
3214: $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
3215: $result.='<input type="button" value="Save" '.
3216: 'onClick="javascript:submit();" target="_self" /></form>'."\n";
3217: if (scalar(%$fullname) eq 0) {
3218: my $colspan=3+scalar(@parts);
3219: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3220: my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
3221: $result='<span class="LC_warning">'.
3222: &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade',
3223: $section_display, $stu_status).
3224: '</span>';
3225: }
3226: $result.=&show_grading_menu_form($symb);
3227: return $result;
3228: }
3229:
3230: #--- call by previous routine to display each student
3231: sub viewstudentgrade {
3232: my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
3233: my ($uname,$udom) = split(/:/,$student);
3234: my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
3235: my %aggregates = ();
3236: my $result='<tr bgcolor="#ffffdd"><td align="right">'.
3237: '<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
3238: "\n".$ctr.' </td><td> '.
3239: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
3240: '\');" target="_self">'.$fullname.'</a> '.
3241: '<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
3242: $student=~s/:/_/; # colon doen't work in javascript for names
3243: foreach my $apart (@$parts) {
3244: my ($part,$type) = &split_part_type($apart);
3245: my $score=$record{"resource.$part.$type"};
3246: $result.='<td align="center">';
3247: my ($aggtries,$totaltries);
3248: unless (exists($aggregates{$part})) {
3249: $totaltries = $record{'resource.'.$part.'.tries'};
3250:
3251: $aggtries = $totaltries;
3252: if ($$last_resets{$part}) {
3253: $aggtries = &get_num_tries(\%record,$$last_resets{$part},
3254: $part);
3255: }
3256: $result.='<input type="hidden" name="'.
3257: 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
3258: $result.='<input type="hidden" name="'.
3259: 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
3260: $aggregates{$part} = 1;
3261: }
3262: if ($type eq 'awarded') {
3263: my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
3264: $result.='<input type="hidden" name="'.
3265: 'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
3266: $result.='<input type="text" name="'.
3267: 'GD_'.$student.'_'.$part.'_awarded" '.
3268: 'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
3269: '\')" value="'.$pts.'" size="4" /></td>'."\n";
3270: } elsif ($type eq 'solved') {
3271: my ($status,$foo)=split(/_/,$score,2);
3272: $status = 'nothing' if ($status eq '');
3273: $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
3274: $part.'_solved_s" value="'.$status.'" />'."\n";
3275: $result.=' <select name="'.
3276: 'GD_'.$student.'_'.$part.'_solved" '.
3277: 'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
3278: $result.= (($status eq 'excused') ? '<option> </option><option selected="selected">excused</option>'
3279: : '<option selected="selected"> </option><option>excused</option>')."\n";
3280: $result.='<option>reset status</option>';
3281: $result.="</select> </td>\n";
3282: } else {
3283: $result.='<input type="hidden" name="'.
3284: 'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
3285: "\n";
3286: $result.='<input type="text" name="'.
3287: 'GD_'.$student.'_'.$part.'_'.$type.'" '.
3288: 'value="'.$score.'" size="4" /></td>'."\n";
3289: }
3290: }
3291: $result.='</tr>';
3292: return $result;
3293: }
3294:
3295: #--- change scores for all the students in a section/class
3296: # record does not get update if unchanged
3297: sub editgrades {
3298: my ($request) = @_;
3299:
3300: my $symb=&get_symb($request);
3301: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3302: my $title='<h3><span class="LC_info">'.&mt('Current Grade Status').'</span></h3>';
3303: $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4><br />'."\n";
3304: $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
3305:
3306: my $result= '<table border="0"><tr><td bgcolor="#777777">'."\n";
3307: $result.= '<table border="0"><tr bgcolor="#deffff">'.
3308: '<td rowspan=2 valign="center"> <b>No.</b> </td>'.
3309: '<td rowspan=2 valign="center">'.&nameUserString('header')."</td>\n";
3310:
3311: my %scoreptr = (
3312: 'correct' =>'correct_by_override',
3313: 'incorrect'=>'incorrect_by_override',
3314: 'excused' =>'excused',
3315: 'ungraded' =>'ungraded_attempted',
3316: 'nothing' => '',
3317: );
3318: my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
3319:
3320: my (@partid);
3321: my %weight = ();
3322: my %columns = ();
3323: my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
3324:
3325: my (@parts) = sort(&getpartlist($symb));
3326: my $header;
3327: while ($ctr < $env{'form.totalparts'}) {
3328: my $partid = $env{'form.partid_'.$ctr};
3329: push @partid,$partid;
3330: $weight{$partid} = $env{'form.weight_'.$partid};
3331: $ctr++;
3332: }
3333: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3334: foreach my $partid (@partid) {
3335: $header .= '<td align="center"> <b>Old Score</b> </td>'.
3336: '<td align="center"> <b>New Score</b> </td>';
3337: $columns{$partid}=2;
3338: foreach my $stores (@parts) {
3339: my ($part,$type) = &split_part_type($stores);
3340: if ($part !~ m/^\Q$partid\E/) { next;}
3341: if ($type eq 'awarded' || $type eq 'solved') { next; }
3342: my $display=&Apache::lonnet::metadata($url,$stores.'.display');
3343: $display =~ s/\[Part: (\w)+\]//;
3344: $display =~ s/Number of Attempts/Tries/;
3345: $header .= '<td align="center"> <b>Old '.$display.'</b> </td>'.
3346: '<td align="center"> <b>New '.$display.'</b> </td>';
3347: $columns{$partid}+=2;
3348: }
3349: }
3350: foreach my $partid (@partid) {
3351: my $display_part=&get_display_part($partid,$symb);
3352: $result .= '<td colspan="'.$columns{$partid}.
3353: '" align="center"><b>Part:</b> '.$display_part.
3354: ' (Weight = '.$weight{$partid}.')</td>';
3355:
3356: }
3357: $result .= '</tr><tr bgcolor="#deffff">';
3358: $result .= $header;
3359: $result .= '</tr>'."\n";
3360: my $noupdate;
3361: my ($updateCtr,$noupdateCtr) = (1,1);
3362: for ($i=0; $i<$env{'form.total'}; $i++) {
3363: my $line;
3364: my $user = $env{'form.ctr'.$i};
3365: my ($uname,$udom)=split(/:/,$user);
3366: my %newrecord;
3367: my $updateflag = 0;
3368: $line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
3369: my $usec=$classlist->{"$uname:$udom"}[5];
3370: if (!&canmodify($usec)) {
3371: my $numcols=scalar(@partid)*4+2;
3372: $noupdate.=$line."<td colspan=\"$numcols\"><span class=\"LC_warning\">Not allowed to modify student</span></td></tr>";
3373: next;
3374: }
3375: my %aggregate = ();
3376: my $aggregateflag = 0;
3377: $user=~s/:/_/; # colon doen't work in javascript for names
3378: foreach (@partid) {
3379: my $old_aw = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
3380: my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
3381: my $old_part = $old_aw eq '' ? '' : $old_part_pcr;
3382: my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
3383: my $awarded = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
3384: my $pcr = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
3385: my $partial = $awarded eq '' ? '' : $pcr;
3386: my $score;
3387: if ($partial eq '') {
3388: $score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
3389: } elsif ($partial > 0) {
3390: $score = 'correct_by_override';
3391: } elsif ($partial == 0) {
3392: $score = 'incorrect_by_override';
3393: }
3394: my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
3395: $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
3396:
3397: $newrecord{'resource.'.$_.'.regrader'}=
3398: "$env{'user.name'}:$env{'user.domain'}";
3399: if ($dropMenu eq 'reset status' &&
3400: $old_score ne '') { # ignore if no previous attempts => nothing to reset
3401: $newrecord{'resource.'.$_.'.tries'} = '';
3402: $newrecord{'resource.'.$_.'.solved'} = '';
3403: $newrecord{'resource.'.$_.'.award'} = '';
3404: $newrecord{'resource.'.$_.'.awarded'} = '';
3405: $updateflag = 1;
3406: if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
3407: my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
3408: my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
3409: my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
3410: &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
3411: $aggregateflag = 1;
3412: }
3413: } elsif (!($old_part eq $partial && $old_score eq $score)) {
3414: $updateflag = 1;
3415: $newrecord{'resource.'.$_.'.awarded'} = $partial if $partial ne '';
3416: $newrecord{'resource.'.$_.'.solved'} = $score;
3417: $rec_update++;
3418: }
3419:
3420: $line .= '<td align="center">'.$old_aw.' </td>'.
3421: '<td align="center">'.$awarded.
3422: ($score eq 'excused' ? $score : '').' </td>';
3423:
3424:
3425: my $partid=$_;
3426: foreach my $stores (@parts) {
3427: my ($part,$type) = &split_part_type($stores);
3428: if ($part !~ m/^\Q$partid\E/) { next;}
3429: if ($type eq 'awarded' || $type eq 'solved') { next; }
3430: my $old_aw = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
3431: my $awarded = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
3432: if ($awarded ne '' && $awarded ne $old_aw) {
3433: $newrecord{'resource.'.$part.'.'.$type}= $awarded;
3434: $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
3435: $updateflag=1;
3436: }
3437: $line .= '<td align="center">'.$old_aw.' </td>'.
3438: '<td align="center">'.$awarded.' </td>';
3439: }
3440: }
3441: $line.='</tr>'."\n";
3442:
3443: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3444: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3445:
3446: if ($updateflag) {
3447: $count++;
3448: &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
3449: $udom,$uname);
3450:
3451: if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
3452: $cnum,$udom,$uname)) {
3453: # need to figure out if should be in queue.
3454: my %record =
3455: &Apache::lonnet::restore($symb,$env{'request.course.id'},
3456: $udom,$uname);
3457: my $all_graded = 1;
3458: my $none_graded = 1;
3459: foreach my $part (@parts) {
3460: if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
3461: $all_graded = 0;
3462: } else {
3463: $none_graded = 0;
3464: }
3465: }
3466:
3467: if ($all_graded || $none_graded) {
3468: &Apache::bridgetask::remove_from_queue('gradingqueue',
3469: $symb,$cdom,$cnum,
3470: $udom,$uname);
3471: }
3472: }
3473:
3474: $result.='<tr bgcolor="#ffffde"><td align="right"> '.$updateCtr.' </td>'.$line;
3475: $updateCtr++;
3476: } else {
3477: $noupdate.='<tr bgcolor="#ffffde"><td align="right"> '.$noupdateCtr.' </td>'.$line;
3478: $noupdateCtr++;
3479: }
3480: if ($aggregateflag) {
3481: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
3482: $cdom,$cnum);
3483: }
3484: }
3485: if ($noupdate) {
3486: # my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
3487: my $numcols=scalar(@partid)*4+2;
3488: $result .= '<tr bgcolor="#ffffff"><td align="center" colspan="'.$numcols.'">No Changes Occurred For the Students Below</td></tr><tr bgcolor="#ffffde">'.$noupdate;
3489: }
3490: $result .= '</table></td></tr></table>'."\n".
3491: &show_grading_menu_form ($symb);
3492: my $msg = '<br /><b>Number of records updated = '.$rec_update.
3493: ' for '.$count.' student'.($count <= 1 ? '' : 's').'.</b><br />'.
3494: '<b>Total number of students = '.$env{'form.total'}.'</b><br />';
3495: return $title.$msg.$result;
3496: }
3497:
3498: sub split_part_type {
3499: my ($partstr) = @_;
3500: my ($temp,@allparts)=split(/_/,$partstr);
3501: my $type=pop(@allparts);
3502: my $part=join('_',@allparts);
3503: return ($part,$type);
3504: }
3505:
3506: #------------- end of section for handling grading by section/class ---------
3507: #
3508: #----------------------------------------------------------------------------
3509:
3510:
3511: #----------------------------------------------------------------------------
3512: #
3513: #-------------------------- Next few routines handles grading by csv upload
3514: #
3515: #--- Javascript to handle csv upload
3516: sub csvupload_javascript_reverse_associate {
3517: my $error1=&mt('You need to specify the username or ID');
3518: my $error2=&mt('You need to specify at least one grading field');
3519: return(<<ENDPICK);
3520: function verify(vf) {
3521: var foundsomething=0;
3522: var founduname=0;
3523: var foundID=0;
3524: for (i=0;i<=vf.nfields.value;i++) {
3525: tw=eval('vf.f'+i+'.selectedIndex');
3526: if (i==0 && tw!=0) { foundID=1; }
3527: if (i==1 && tw!=0) { founduname=1; }
3528: if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
3529: }
3530: if (founduname==0 && foundID==0) {
3531: alert('$error1');
3532: return;
3533: }
3534: if (foundsomething==0) {
3535: alert('$error2');
3536: return;
3537: }
3538: vf.submit();
3539: }
3540: function flip(vf,tf) {
3541: var nw=eval('vf.f'+tf+'.selectedIndex');
3542: var i;
3543: for (i=0;i<=vf.nfields.value;i++) {
3544: //can not pick the same destination field for both name and domain
3545: if (((i ==0)||(i ==1)) &&
3546: ((tf==0)||(tf==1)) &&
3547: (i!=tf) &&
3548: (eval('vf.f'+i+'.selectedIndex')==nw)) {
3549: eval('vf.f'+i+'.selectedIndex=0;')
3550: }
3551: }
3552: }
3553: ENDPICK
3554: }
3555:
3556: sub csvupload_javascript_forward_associate {
3557: my $error1=&mt('You need to specify the username or ID');
3558: my $error2=&mt('You need to specify at least one grading field');
3559: return(<<ENDPICK);
3560: function verify(vf) {
3561: var foundsomething=0;
3562: var founduname=0;
3563: var foundID=0;
3564: for (i=0;i<=vf.nfields.value;i++) {
3565: tw=eval('vf.f'+i+'.selectedIndex');
3566: if (tw==1) { foundID=1; }
3567: if (tw==2) { founduname=1; }
3568: if (tw>3) { foundsomething=1; }
3569: }
3570: if (founduname==0 && foundID==0) {
3571: alert('$error1');
3572: return;
3573: }
3574: if (foundsomething==0) {
3575: alert('$error2');
3576: return;
3577: }
3578: vf.submit();
3579: }
3580: function flip(vf,tf) {
3581: var nw=eval('vf.f'+tf+'.selectedIndex');
3582: var i;
3583: //can not pick the same destination field twice
3584: for (i=0;i<=vf.nfields.value;i++) {
3585: if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
3586: eval('vf.f'+i+'.selectedIndex=0;')
3587: }
3588: }
3589: }
3590: ENDPICK
3591: }
3592:
3593: sub csvuploadmap_header {
3594: my ($request,$symb,$datatoken,$distotal)= @_;
3595: my $javascript;
3596: if ($env{'form.upfile_associate'} eq 'reverse') {
3597: $javascript=&csvupload_javascript_reverse_associate();
3598: } else {
3599: $javascript=&csvupload_javascript_forward_associate();
3600: }
3601:
3602: my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
3603: my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
3604: my $ignore=&mt('Ignore First Line');
3605: $symb = &Apache::lonenc::check_encrypt($symb);
3606: $request->print(<<ENDPICK);
3607: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3608: <h3><span class="LC_info">Uploading Class Grades</span></h3>
3609: $result
3610: <hr />
3611: <h3>Identify fields</h3>
3612: Total number of records found in file: $distotal <hr />
3613: Enter as many fields as you can. The system will inform you and bring you back
3614: to this page if the data selected is insufficient to run your class.<hr />
3615: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
3616: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
3617: <input type="hidden" name="associate" value="" />
3618: <input type="hidden" name="phase" value="three" />
3619: <input type="hidden" name="datatoken" value="$datatoken" />
3620: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
3621: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
3622: <input type="hidden" name="upfile_associate"
3623: value="$env{'form.upfile_associate'}" />
3624: <input type="hidden" name="symb" value="$symb" />
3625: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
3626: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
3627: <input type="hidden" name="command" value="csvuploadoptions" />
3628: <hr />
3629: <script type="text/javascript" language="Javascript">
3630: $javascript
3631: </script>
3632: ENDPICK
3633: return '';
3634:
3635: }
3636:
3637: sub csvupload_fields {
3638: my ($symb) = @_;
3639: my (@parts) = &getpartlist($symb);
3640: my @fields=(['ID','Student ID'],
3641: ['username','Student Username'],
3642: ['domain','Student Domain']);
3643: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3644: foreach my $part (sort(@parts)) {
3645: my @datum;
3646: my $display=&Apache::lonnet::metadata($url,$part.'.display');
3647: my $name=$part;
3648: if (!$display) { $display = $name; }
3649: @datum=($name,$display);
3650: if ($name=~/^stores_(.*)_awarded/) {
3651: push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
3652: }
3653: push(@fields,\@datum);
3654: }
3655: return (@fields);
3656: }
3657:
3658: sub csvuploadmap_footer {
3659: my ($request,$i,$keyfields) =@_;
3660: $request->print(<<ENDPICK);
3661: </table>
3662: <input type="hidden" name="nfields" value="$i" />
3663: <input type="hidden" name="keyfields" value="$keyfields" />
3664: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
3665: </form>
3666: ENDPICK
3667: }
3668:
3669: sub checkforfile_js {
3670: my $result =<<CSVFORMJS;
3671: <script type="text/javascript" language="javascript">
3672: function checkUpload(formname) {
3673: if (formname.upfile.value == "") {
3674: alert("Please use the browse button to select a file from your local directory.");
3675: return false;
3676: }
3677: formname.submit();
3678: }
3679: </script>
3680: CSVFORMJS
3681: return $result;
3682: }
3683:
3684: sub upcsvScores_form {
3685: my ($request) = shift;
3686: my ($symb)=&get_symb($request);
3687: if (!$symb) {return '';}
3688: my $result=&checkforfile_js();
3689: $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
3690: my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
3691: $result.=$table;
3692: $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
3693: $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
3694: $result.=' <b>'.&mt('Specify a file containing the class scores for current resource').
3695: '.</b></td></tr>'."\n";
3696: $result.='<tr bgcolor=#ffffe6><td>'."\n";
3697: my $upload=&mt("Upload Scores");
3698: my $upfile_select=&Apache::loncommon::upfile_select_html();
3699: my $ignore=&mt('Ignore First Line');
3700: $symb = &Apache::lonenc::check_encrypt($symb);
3701: $result.=<<ENDUPFORM;
3702: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3703: <input type="hidden" name="symb" value="$symb" />
3704: <input type="hidden" name="command" value="csvuploadmap" />
3705: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
3706: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
3707: $upfile_select
3708: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
3709: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
3710: </form>
3711: ENDUPFORM
3712: $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
3713: &mt("How do I create a CSV file from a spreadsheet"))
3714: .'</td></tr></table>'."\n";
3715: $result.='</td></tr></table><br /><br />'."\n";
3716: $result.=&show_grading_menu_form($symb);
3717: return $result;
3718: }
3719:
3720:
3721: sub csvuploadmap {
3722: my ($request)= @_;
3723: my ($symb)=&get_symb($request);
3724: if (!$symb) {return '';}
3725:
3726: my $datatoken;
3727: if (!$env{'form.datatoken'}) {
3728: $datatoken=&Apache::loncommon::upfile_store($request);
3729: } else {
3730: $datatoken=$env{'form.datatoken'};
3731: &Apache::loncommon::load_tmp_file($request);
3732: }
3733: my @records=&Apache::loncommon::upfile_record_sep();
3734: if ($env{'form.noFirstLine'}) { shift(@records); }
3735: &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
3736: my ($i,$keyfields);
3737: if (@records) {
3738: my @fields=&csvupload_fields($symb);
3739:
3740: if ($env{'form.upfile_associate'} eq 'reverse') {
3741: &Apache::loncommon::csv_print_samples($request,\@records);
3742: $i=&Apache::loncommon::csv_print_select_table($request,\@records,
3743: \@fields);
3744: foreach (@fields) { $keyfields.=$_->[0].','; }
3745: chop($keyfields);
3746: } else {
3747: unshift(@fields,['none','']);
3748: $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
3749: \@fields);
3750: foreach my $rec (@records) {
3751: my %temp = &Apache::loncommon::record_sep($rec);
3752: if (%temp) {
3753: $keyfields=join(',',sort(keys(%temp)));
3754: last;
3755: }
3756: }
3757: }
3758: }
3759: &csvuploadmap_footer($request,$i,$keyfields);
3760: $request->print(&show_grading_menu_form($symb));
3761:
3762: return '';
3763: }
3764:
3765: sub csvuploadoptions {
3766: my ($request)= @_;
3767: my ($symb)=&get_symb($request);
3768: my $checked=(($env{'form.noFirstLine'})?'1':'0');
3769: my $ignore=&mt('Ignore First Line');
3770: $request->print(<<ENDPICK);
3771: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3772: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
3773: <input type="hidden" name="command" value="csvuploadassign" />
3774: <!--
3775: <p>
3776: <label>
3777: <input type="checkbox" name="show_full_results" />
3778: Show a table of all changes
3779: </label>
3780: </p>
3781: -->
3782: <p>
3783: <label>
3784: <input type="checkbox" name="overwite_scores" checked="checked" />
3785: Overwrite any existing score
3786: </label>
3787: </p>
3788: ENDPICK
3789: my %fields=&get_fields();
3790: if (!defined($fields{'domain'})) {
3791: my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
3792: $request->print("\n<p> Users are in domain: ".$domform."</p>\n");
3793: }
3794: foreach my $key (sort(keys(%env))) {
3795: if ($key !~ /^form\.(.*)$/) { next; }
3796: my $cleankey=$1;
3797: if ($cleankey eq 'command') { next; }
3798: $request->print('<input type="hidden" name="'.$cleankey.
3799: '" value="'.$env{$key}.'" />'."\n");
3800: }
3801: # FIXME do a check for any duplicated user ids...
3802: # FIXME do a check for any invalid user ids?...
3803: $request->print('<input type="submit" value="Assign Grades" /><br />
3804: <hr /></form>'."\n");
3805: $request->print(&show_grading_menu_form($symb));
3806: return '';
3807: }
3808:
3809: sub get_fields {
3810: my %fields;
3811: my @keyfields = split(/\,/,$env{'form.keyfields'});
3812: for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
3813: if ($env{'form.upfile_associate'} eq 'reverse') {
3814: if ($env{'form.f'.$i} ne 'none') {
3815: $fields{$keyfields[$i]}=$env{'form.f'.$i};
3816: }
3817: } else {
3818: if ($env{'form.f'.$i} ne 'none') {
3819: $fields{$env{'form.f'.$i}}=$keyfields[$i];
3820: }
3821: }
3822: }
3823: return %fields;
3824: }
3825:
3826: sub csvuploadassign {
3827: my ($request)= @_;
3828: my ($symb)=&get_symb($request);
3829: if (!$symb) {return '';}
3830: my $error_msg = '';
3831: &Apache::loncommon::load_tmp_file($request);
3832: my @gradedata = &Apache::loncommon::upfile_record_sep();
3833: if ($env{'form.noFirstLine'}) { shift(@gradedata); }
3834: my %fields=&get_fields();
3835: $request->print('<h3>Assigning Grades</h3>');
3836: my $courseid=$env{'request.course.id'};
3837: my ($classlist) = &getclasslist('all',0);
3838: my @notallowed;
3839: my @skipped;
3840: my $countdone=0;
3841: foreach my $grade (@gradedata) {
3842: my %entries=&Apache::loncommon::record_sep($grade);
3843: my $domain;
3844: if ($entries{$fields{'domain'}}) {
3845: $domain=$entries{$fields{'domain'}};
3846: } else {
3847: $domain=$env{'form.default_domain'};
3848: }
3849: $domain=~s/\s//g;
3850: my $username=$entries{$fields{'username'}};
3851: $username=~s/\s//g;
3852: if (!$username) {
3853: my $id=$entries{$fields{'ID'}};
3854: $id=~s/\s//g;
3855: my %ids=&Apache::lonnet::idget($domain,$id);
3856: $username=$ids{$id};
3857: }
3858: if (!exists($$classlist{"$username:$domain"})) {
3859: my $id=$entries{$fields{'ID'}};
3860: $id=~s/\s//g;
3861: if ($id) {
3862: push(@skipped,"$id:$domain");
3863: } else {
3864: push(@skipped,"$username:$domain");
3865: }
3866: next;
3867: }
3868: my $usec=$classlist->{"$username:$domain"}[5];
3869: if (!&canmodify($usec)) {
3870: push(@notallowed,"$username:$domain");
3871: next;
3872: }
3873: my %points;
3874: my %grades;
3875: foreach my $dest (keys(%fields)) {
3876: if ($dest eq 'ID' || $dest eq 'username' ||
3877: $dest eq 'domain') { next; }
3878: if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
3879: if ($dest=~/stores_(.*)_points/) {
3880: my $part=$1;
3881: my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
3882: $symb,$domain,$username);
3883: if ($wgt) {
3884: $entries{$fields{$dest}}=~s/\s//g;
3885: my $pcr=$entries{$fields{$dest}} / $wgt;
3886: my $award='correct_by_override';
3887: $grades{"resource.$part.awarded"}=$pcr;
3888: $grades{"resource.$part.solved"}=$award;
3889: $points{$part}=1;
3890: } else {
3891: $error_msg = "<br />" .
3892: &mt("Some point values were assigned"
3893: ." for problems with a weight "
3894: ."of zero. These values were "
3895: ."ignored.");
3896: }
3897: } else {
3898: if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
3899: if ($dest=~/stores_(.*)_solved/) { if ($points{$1}) {next;} }
3900: my $store_key=$dest;
3901: $store_key=~s/^stores/resource/;
3902: $store_key=~s/_/\./g;
3903: $grades{$store_key}=$entries{$fields{$dest}};
3904: }
3905: }
3906: if (! %grades) { push(@skipped,"$username:$domain no data to save"); }
3907: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
3908: my $result=&Apache::lonnet::cstore(\%grades,$symb,
3909: $env{'request.course.id'},
3910: $domain,$username);
3911: if ($result eq 'ok') {
3912: $request->print('.');
3913: } else {
3914: $request->print("<p>
3915: <span class=\"LC_error\">
3916: Failed to save student $username:$domain.
3917: Message when trying to save was ($result)
3918: </span>
3919: </p>" );
3920: }
3921: $request->rflush();
3922: $countdone++;
3923: }
3924: $request->print("<br />Saved $countdone students\n");
3925: if (@skipped) {
3926: $request->print('<p><h4><b>Skipped Students</b></h4></p>');
3927: foreach my $student (@skipped) { $request->print("$student<br />\n"); }
3928: }
3929: if (@notallowed) {
3930: $request->print('<p><span class="LC_error">Students Not Allowed to Modify</span></p>');
3931: foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
3932: }
3933: $request->print("<br />\n");
3934: $request->print(&show_grading_menu_form($symb));
3935: return $error_msg;
3936: }
3937: #------------- end of section for handling csv file upload ---------
3938: #
3939: #-------------------------------------------------------------------
3940: #
3941: #-------------- Next few routines handle grading by page/sequence
3942: #
3943: #--- Select a page/sequence and a student to grade
3944: sub pickStudentPage {
3945: my ($request) = shift;
3946:
3947: $request->print(<<LISTJAVASCRIPT);
3948: <script type="text/javascript" language="javascript">
3949:
3950: function checkPickOne(formname) {
3951: if (radioSelection(formname.student) == null) {
3952: alert("Please select the student you wish to grade.");
3953: return;
3954: }
3955: ptr = pullDownSelection(formname.selectpage);
3956: formname.page.value = formname["page"+ptr].value;
3957: formname.title.value = formname["title"+ptr].value;
3958: formname.submit();
3959: }
3960:
3961: </script>
3962: LISTJAVASCRIPT
3963: &commonJSfunctions($request);
3964: my ($symb) = &get_symb($request);
3965: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
3966: my $cnum = $env{"course.$env{'request.course.id'}.num"};
3967: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
3968:
3969: my $result='<h3><span class="LC_info"> '.
3970: 'Manual Grading by Page or Sequence</span></h3>';
3971:
3972: $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
3973: $result.=' <b>Problems from:</b> <select name="selectpage">'."\n";
3974: my ($titles,$symbx) = &getSymbMap();
3975: my ($curpage) =&Apache::lonnet::decode_symb($symb);
3976: # my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb);
3977: # my $type=($curpage =~ /\.(page|sequence)/);
3978: my $ctr=0;
3979: foreach (@$titles) {
3980: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
3981: $result.='<option value="'.$ctr.'" '.
3982: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
3983: '>'.$showtitle.'</option>'."\n";
3984: $ctr++;
3985: }
3986: $result.= '</select>'."<br />\n";
3987: $ctr=0;
3988: foreach (@$titles) {
3989: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
3990: $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
3991: $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
3992: $ctr++;
3993: }
3994: $result.='<input type="hidden" name="page" />'."\n".
3995: '<input type="hidden" name="title" />'."\n";
3996:
3997: $result.=' <b>View Problems Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
3998: '<label><input type="radio" name="vProb" value="yes" /> yes </label>'."<br />\n";
3999:
4000: $result.=' <b>Submission Details: </b>'.
4001: '<label><input type="radio" name="lastSub" value="none" /> none</label>'."\n".
4002: '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> by dates and submissions</label>'."\n".
4003: '<label><input type="radio" name="lastSub" value="all" /> all details</label>'."\n";
4004:
4005: $result.=&build_section_inputs();
4006: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
4007: $result.='<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
4008: '<input type="hidden" name="command" value="displayPage" />'."\n".
4009: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
4010: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
4011:
4012: $result.=' <b>'.&mt('Use CODE:').' </b>'.
4013: '<input type="text" name="CODE" value="" /><br />'."\n";
4014:
4015: $result.=' <input type="button" '.
4016: 'onClick="javascript:checkPickOne(this.form);"value="Next->" /><br />'."\n";
4017:
4018: $request->print($result);
4019:
4020: my $studentTable.=' <b>Select a student you wish to grade and then click on the Next button.</b><br />'.
4021: '<table border="0"><tr><td bgcolor="#777777">'.
4022: '<table border="0"><tr bgcolor="#e6ffff">'.
4023: '<td align="right"> <b>No.</b></td>'.
4024: '<td>'.&nameUserString('header').'</td>'.
4025: '<td align="right"> <b>No.</b></td>'.
4026: '<td>'.&nameUserString('header').'</td></tr>';
4027:
4028: my (undef,undef,$fullname) = &getclasslist($getsec,'1');
4029: my $ptr = 1;
4030: foreach my $student (sort
4031: {
4032: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
4033: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
4034: }
4035: return $a cmp $b;
4036: } (keys(%$fullname))) {
4037: my ($uname,$udom) = split(/:/,$student);
4038: $studentTable.=($ptr%2 == 1 ? '<tr bgcolor="#ffffe6">' : '</td>');
4039: $studentTable.='<td align="right">'.$ptr.' </td>';
4040: $studentTable.='<td> <label><input type="radio" name="student" value="'.$student.'" /> '
4041: .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
4042: $studentTable.=($ptr%2 == 0 ? '</td></tr>' : '');
4043: $ptr++;
4044: }
4045: $studentTable.='</td><td> </td><td> </td></tr>' if ($ptr%2 == 0);
4046: $studentTable.='</table></td></tr></table>'."\n";
4047: $studentTable.='<input type="button" '.
4048: 'onClick="javascript:checkPickOne(this.form);"value="Next->" /></form>'."\n";
4049:
4050: $studentTable.=&show_grading_menu_form($symb);
4051: $request->print($studentTable);
4052:
4053: return '';
4054: }
4055:
4056: sub getSymbMap {
4057: my $navmap = Apache::lonnavmaps::navmap->new();
4058:
4059: my %symbx = ();
4060: my @titles = ();
4061: my $minder = 0;
4062:
4063: # Gather every sequence that has problems.
4064: my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
4065: 1,0,1);
4066: for my $sequence ($navmap->getById('0.0'), @sequences) {
4067: if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
4068: my $title = $minder.'.'.
4069: &HTML::Entities::encode($sequence->compTitle(),'"\'&');
4070: push(@titles, $title); # minder in case two titles are identical
4071: $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
4072: $minder++;
4073: }
4074: }
4075: return \@titles,\%symbx;
4076: }
4077:
4078: #
4079: #--- Displays a page/sequence w/wo problems, w/wo submissions
4080: sub displayPage {
4081: my ($request) = shift;
4082:
4083: my ($symb) = &get_symb($request);
4084: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4085: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4086: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4087: my $pageTitle = $env{'form.page'};
4088: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
4089: my ($uname,$udom) = split(/:/,$env{'form.student'});
4090: my $usec=$classlist->{$env{'form.student'}}[5];
4091:
4092: #need to make sure we have the correct data for later EXT calls,
4093: #thus invalidate the cache
4094: &Apache::lonnet::devalidatecourseresdata(
4095: $env{'course.'.$env{'request.course.id'}.'.num'},
4096: $env{'course.'.$env{'request.course.id'}.'.domain'});
4097: &Apache::lonnet::clear_EXT_cache_status();
4098:
4099: if (!&canview($usec)) {
4100: $request->print('<span class="LC_warning">Unable to view requested student.('.$env{'form.student'}.')</span>');
4101: $request->print(&show_grading_menu_form($symb));
4102: return;
4103: }
4104: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
4105: $result.='<h3> Student: '.&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom).
4106: '</h3>'."\n";
4107: if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
4108: $result.='<h3> CODE: '.$env{'form.CODE'}.'</h3>'."\n";
4109: } else {
4110: delete($env{'form.CODE'});
4111: }
4112: &sub_page_js($request);
4113: $request->print($result);
4114:
4115: my $navmap = Apache::lonnavmaps::navmap->new();
4116: my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
4117: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
4118: if (!$map) {
4119: $request->print('<span class="LC_warning">Unable to view requested sequence. ('.$resUrl.')</span>');
4120: $request->print(&show_grading_menu_form($symb));
4121: return;
4122: }
4123: my $iterator = $navmap->getIterator($map->map_start(),
4124: $map->map_finish());
4125:
4126: my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
4127: '<input type="hidden" name="command" value="gradeByPage" />'."\n".
4128: '<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
4129: '<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
4130: '<input type="hidden" name="page" value="'.$pageTitle.'" />'."\n".
4131: '<input type="hidden" name="title" value="'.$env{'form.title'}.'" />'."\n".
4132: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
4133: '<input type="hidden" name="overRideScore" value="no" />'."\n".
4134: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
4135:
4136: if (defined($env{'form.CODE'})) {
4137: $studentTable.=
4138: '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
4139: }
4140: my $checkIcon = '<img alt="'.&mt('Check Mark').
4141: '" src="'.$request->dir_config('lonIconsURL').
4142: '/check.gif" height="16" border="0" />';
4143:
4144: $studentTable.=' <b>Note:</b> Problems graded correct by the computer are marked with a '.$checkIcon.
4145: ' symbol.'."\n".
4146: '<table border="0"><tr><td bgcolor="#777777">'.
4147: '<table border="0"><tr bgcolor="#e6ffff">'.
4148: '<td align="center"><b> Prob. </b></td>'.
4149: '<td><b> '.($env{'form.vProb'} eq 'no' ? 'Title' : 'Problem Text').'/Grade</b></td></tr>';
4150:
4151: &Apache::lonxml::clear_problem_counter();
4152: my ($depth,$question,$prob) = (1,1,1);
4153: $iterator->next(); # skip the first BEGIN_MAP
4154: my $curRes = $iterator->next(); # for "current resource"
4155: while ($depth > 0) {
4156: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
4157: if($curRes == $iterator->END_MAP) { $depth--; }
4158:
4159: if (ref($curRes) && $curRes->is_problem()) {
4160: my $parts = $curRes->parts();
4161: my $title = $curRes->compTitle();
4162: my $symbx = $curRes->symb();
4163: $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
4164: (scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).' parts)').'</td>';
4165: $studentTable.='<td valign="top">';
4166: my %form = ('CODE' => $env{'form.CODE'},);
4167: if ($env{'form.vProb'} eq 'yes' ) {
4168: $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
4169: undef,'both',\%form);
4170: } else {
4171: my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
4172: $companswer =~ s|<form(.*?)>||g;
4173: $companswer =~ s|</form>||g;
4174: # while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
4175: # $companswer =~ s/$1/ /ms;
4176: # $request->print('match='.$1."<br />\n");
4177: # }
4178: # $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
4179: $studentTable.=' <b>'.$title.'</b> <br /> <b>Correct answer:</b><br />'.$companswer;
4180: }
4181:
4182: my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
4183:
4184: if ($env{'form.lastSub'} eq 'datesub') {
4185: if ($record{'version'} eq '') {
4186: $studentTable.='<br /> <span class="LC_warning">No recorded submission for this problem</span><br />';
4187: } else {
4188: my %responseType = ();
4189: foreach my $partid (@{$parts}) {
4190: my @responseIds =$curRes->responseIds($partid);
4191: my @responseType =$curRes->responseType($partid);
4192: my %responseIds;
4193: for (my $i=0;$i<=$#responseIds;$i++) {
4194: $responseIds{$responseIds[$i]}=$responseType[$i];
4195: }
4196: $responseType{$partid} = \%responseIds;
4197: }
4198: $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
4199:
4200: }
4201: } elsif ($env{'form.lastSub'} eq 'all') {
4202: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
4203: $studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
4204: $env{'request.course.id'},
4205: '','.submission');
4206:
4207: }
4208: if (&canmodify($usec)) {
4209: foreach my $partid (@{$parts}) {
4210: $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
4211: $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
4212: $question++;
4213: }
4214: $prob++;
4215: }
4216: $studentTable.='</td></tr>';
4217:
4218: }
4219: $curRes = $iterator->next();
4220: }
4221:
4222: $studentTable.='</table></td></tr></table>'."\n".
4223: '<input type="button" value="Save" '.
4224: 'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
4225: '</form>'."\n";
4226: $studentTable.=&show_grading_menu_form($symb);
4227: $request->print($studentTable);
4228:
4229: return '';
4230: }
4231:
4232: sub displaySubByDates {
4233: my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
4234: my $isCODE=0;
4235: my $isTask = ($symb =~/\.task$/);
4236: if (exists($record->{'resource.CODE'})) { $isCODE=1; }
4237: my $studentTable='<table border="0" width="100%"><tr><td bgcolor="#777777">'.
4238: '<table border="0" width="100%"><tr bgcolor="#e6ffff">'.
4239: '<td><b>Date/Time</b></td>'.
4240: ($isCODE?'<td><b>CODE</b></td>':'').
4241: '<td><b>Submission</b></td>'.
4242: '<td><b>Status </b></td></tr>';
4243: my ($version);
4244: my %mark;
4245: my %orders;
4246: $mark{'correct_by_student'} = $checkIcon;
4247: if (!exists($$record{'1:timestamp'})) {
4248: return '<br /> <span class="LC_warning">Nothing submitted - no attempts</span><br />';
4249: }
4250:
4251: my $interaction;
4252: for ($version=1;$version<=$$record{'version'};$version++) {
4253: my $timestamp = scalar(localtime($$record{$version.':timestamp'}));
4254: if (exists($$record{$version.':resource.0.version'})) {
4255: $interaction = $$record{$version.':resource.0.version'};
4256: }
4257:
4258: my $where = ($isTask ? "$version:resource.$interaction"
4259: : "$version:resource");
4260: $studentTable.='<tr bgcolor="#ffffff" valign="top"><td>'.$timestamp.'</td>';
4261: if ($isCODE) {
4262: $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
4263: }
4264: my @versionKeys = split(/\:/,$$record{$version.':keys'});
4265: my @displaySub = ();
4266: foreach my $partid (@{$parts}) {
4267: my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
4268: : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
4269:
4270:
4271: # next if ($$record{"$version:resource.$partid.solved"} eq '');
4272: my $display_part=&get_display_part($partid,$symb);
4273: foreach my $matchKey (@matchKey) {
4274: if (exists($$record{$version.':'.$matchKey}) &&
4275: $$record{$version.':'.$matchKey} ne '') {
4276:
4277: my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
4278: : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
4279: $displaySub[0].='<b>Part:</b> '.$display_part.' ';
4280: $displaySub[0].='<span class="LC_internal_info">(ID '.
4281: $responseId.')</span> <b>';
4282: if ($$record{"$where.$partid.tries"} eq '') {
4283: $displaySub[0].='Trial not counted';
4284: } else {
4285: $displaySub[0].='Trial '.
4286: $$record{"$where.$partid.tries"};
4287: }
4288: my $responseType=($isTask ? 'Task'
4289: : $responseType->{$partid}->{$responseId});
4290: if (!exists($orders{$partid})) { $orders{$partid}={}; }
4291: if (!exists($orders{$partid}->{$responseId})) {
4292: $orders{$partid}->{$responseId}=
4293: &get_order($partid,$responseId,$symb,$uname,$udom);
4294: }
4295: $displaySub[0].='</b> '.
4296: &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
4297: }
4298: }
4299: if (exists($$record{"$where.$partid.checkedin"})) {
4300: $displaySub[1].='Checked in by '.
4301: $$record{"$where.$partid.checkedin"}.' into slot '.
4302: $$record{"$where.$partid.checkedin.slot"}.
4303: '<br />';
4304: }
4305: if (exists $$record{"$where.$partid.award"}) {
4306: $displaySub[1].='<b>Part:</b> '.$display_part.' '.
4307: lc($$record{"$where.$partid.award"}).' '.
4308: $mark{$$record{"$where.$partid.solved"}}.
4309: '<br />';
4310: }
4311: if (exists $$record{"$where.$partid.regrader"}) {
4312: $displaySub[2].=$$record{"$where.$partid.regrader"}.
4313: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
4314: } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
4315: $displaySub[2].=
4316: $$record{"$version:resource.$partid.regrader"}.
4317: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
4318: }
4319: }
4320: # needed because old essay regrader has not parts info
4321: if (exists $$record{"$version:resource.regrader"}) {
4322: $displaySub[2].=$$record{"$version:resource.regrader"};
4323: }
4324: $studentTable.='<td>'.$displaySub[0].' </td><td>'.$displaySub[1];
4325: if ($displaySub[2]) {
4326: $studentTable.='Manually graded by '.$displaySub[2];
4327: }
4328: $studentTable.=' </td></tr>';
4329:
4330: }
4331: $studentTable.='</table></td></tr></table>';
4332: return $studentTable;
4333: }
4334:
4335: sub updateGradeByPage {
4336: my ($request) = shift;
4337:
4338: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4339: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4340: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4341: my $pageTitle = $env{'form.page'};
4342: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
4343: my ($uname,$udom) = split(/:/,$env{'form.student'});
4344: my $usec=$classlist->{$env{'form.student'}}[5];
4345: if (!&canmodify($usec)) {
4346: $request->print('<span class="LC_warning">Unable to modify requested student.('.$env{'form.student'}.'</span>');
4347: $request->print(&show_grading_menu_form($env{'form.symb'}));
4348: return;
4349: }
4350: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
4351: $result.='<h3> Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
4352: '</h3>'."\n";
4353:
4354: $request->print($result);
4355:
4356: my $navmap = Apache::lonnavmaps::navmap->new();
4357: my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
4358: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
4359: if (!$map) {
4360: $request->print('<span class="LC_warning">Unable to grade requested sequence. ('.$resUrl.')</span>');
4361: my ($symb)=&get_symb($request);
4362: $request->print(&show_grading_menu_form($symb));
4363: return;
4364: }
4365: my $iterator = $navmap->getIterator($map->map_start(),
4366: $map->map_finish());
4367:
4368: my $studentTable='<table border="0"><tr><td bgcolor="#777777">'.
4369: '<table border="0"><tr bgcolor="#e6ffff">'.
4370: '<td align="center"><b> Prob. </b></td>'.
4371: '<td><b> Title </b></td>'.
4372: '<td><b> Previous Score </b></td>'.
4373: '<td><b> New Score </b></td></tr>';
4374:
4375: $iterator->next(); # skip the first BEGIN_MAP
4376: my $curRes = $iterator->next(); # for "current resource"
4377: my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
4378: while ($depth > 0) {
4379: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
4380: if($curRes == $iterator->END_MAP) { $depth--; }
4381:
4382: if (ref($curRes) && $curRes->is_problem()) {
4383: my $parts = $curRes->parts();
4384: my $title = $curRes->compTitle();
4385: my $symbx = $curRes->symb();
4386: $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
4387: (scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).' parts)').'</td>';
4388: $studentTable.='<td valign="top"> <b>'.$title.'</b> </td>';
4389:
4390: my %newrecord=();
4391: my @displayPts=();
4392: my %aggregate = ();
4393: my $aggregateflag = 0;
4394: foreach my $partid (@{$parts}) {
4395: my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
4396: my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
4397:
4398: my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ?
4399: $env{'form.WGT'.$question.'_'.$partid} : 1;
4400: my $partial = $newpts/$wgt;
4401: my $score;
4402: if ($partial > 0) {
4403: $score = 'correct_by_override';
4404: } elsif ($newpts ne '') { #empty is taken as 0
4405: $score = 'incorrect_by_override';
4406: }
4407: my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
4408: if ($dropMenu eq 'excused') {
4409: $partial = '';
4410: $score = 'excused';
4411: } elsif ($dropMenu eq 'reset status'
4412: && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
4413: $newrecord{'resource.'.$partid.'.tries'} = 0;
4414: $newrecord{'resource.'.$partid.'.solved'} = '';
4415: $newrecord{'resource.'.$partid.'.award'} = '';
4416: $newrecord{'resource.'.$partid.'.awarded'} = 0;
4417: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
4418: $changeflag++;
4419: $newpts = '';
4420:
4421: my $aggtries = $env{'form.aggtries'.$question.'_'.$partid};
4422: my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
4423: my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
4424: if ($aggtries > 0) {
4425: &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
4426: $aggregateflag = 1;
4427: }
4428: }
4429: my $display_part=&get_display_part($partid,$curRes->symb());
4430: my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
4431: $displayPts[0].=' <b>Part:</b> '.$display_part.' = '.
4432: (($oldstatus eq 'excused') ? 'excused' : $oldpts).
4433: ' <br />';
4434: $displayPts[1].=' <b>Part:</b> '.$display_part.' = '.
4435: (($score eq 'excused') ? 'excused' : $newpts).
4436: ' <br />';
4437: $question++;
4438: next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
4439:
4440: $newrecord{'resource.'.$partid.'.awarded'} = $partial if $partial ne '';
4441: $newrecord{'resource.'.$partid.'.solved'} = $score if $score ne '';
4442: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
4443: if (scalar(keys(%newrecord)) > 0);
4444:
4445: $changeflag++;
4446: }
4447: if (scalar(keys(%newrecord)) > 0) {
4448: my %record =
4449: &Apache::lonnet::restore($symbx,$env{'request.course.id'},
4450: $udom,$uname);
4451:
4452: if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
4453: $newrecord{'resource.CODE'} = $env{'form.CODE'};
4454: } elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
4455: $newrecord{'resource.CODE'} = '';
4456: }
4457: &Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
4458: $udom,$uname);
4459: %record = &Apache::lonnet::restore($symbx,
4460: $env{'request.course.id'},
4461: $udom,$uname);
4462: &check_and_remove_from_queue($parts,\%record,undef,$symbx,
4463: $cdom,$cnum,$udom,$uname);
4464: }
4465:
4466: if ($aggregateflag) {
4467: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
4468: $env{'course.'.$env{'request.course.id'}.'.domain'},
4469: $env{'course.'.$env{'request.course.id'}.'.num'});
4470: }
4471:
4472: $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
4473: '<td valign="top">'.$displayPts[1].'</td>'.
4474: '</tr>';
4475:
4476: $prob++;
4477: }
4478: $curRes = $iterator->next();
4479: }
4480:
4481: $studentTable.='</td></tr></table></td></tr></table>';
4482: $studentTable.=&show_grading_menu_form($env{'form.symb'});
4483: my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
4484: 'The scores were changed for '.
4485: $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
4486: $request->print($grademsg.$studentTable);
4487:
4488: return '';
4489: }
4490:
4491: #-------- end of section for handling grading by page/sequence ---------
4492: #
4493: #-------------------------------------------------------------------
4494:
4495: #--------------------Scantron Grading-----------------------------------
4496: #
4497: #------ start of section for handling grading by page/sequence ---------
4498:
4499: =pod
4500:
4501: =head1 Bubble sheet grading routines
4502:
4503: For this documentation:
4504:
4505: 'scanline' refers to the full line of characters
4506: from the file that we are parsing that represents one entire sheet
4507:
4508: 'bubble line' refers to the data
4509: representing the line of bubbles that are on the physical bubble sheet
4510:
4511:
4512: The overall process is that a scanned in bubble sheet data is uploaded
4513: into a course. When a user wants to grade, they select a
4514: sequence/folder of resources, a file of bubble sheet info, and pick
4515: one of the predefined configurations for what each scanline looks
4516: like.
4517:
4518: Next each scanline is checked for any errors of either 'missing
4519: bubbles' (it's an error because it may have been mis-scanned
4520: because too light bubbling), 'double bubble' (each bubble line should
4521: have no more that one letter picked), invalid or duplicated CODE,
4522: invalid student ID
4523:
4524: If the CODE option is used that determines the randomization of the
4525: homework problems, either way the student ID is looked up into a
4526: username:domain.
4527:
4528: During the validation phase the instructor can choose to skip scanlines.
4529:
4530: After the validation phase, there are now 3 bubble sheet files
4531:
4532: scantron_original_filename (unmodified original file)
4533: scantron_corrected_filename (file where the corrected information has replaced the original information)
4534: scantron_skipped_filename (contains the exact text of scanlines that where skipped)
4535:
4536: Also there is a separate hash nohist_scantrondata that contains extra
4537: correction information that isn't representable in the bubble sheet
4538: file (see &scantron_getfile() for more information)
4539:
4540: After all scanlines are either valid, marked as valid or skipped, then
4541: foreach line foreach problem in the picked sequence, an ssi request is
4542: made that simulates a user submitting their selected letter(s) against
4543: the homework problem.
4544:
4545: =over 4
4546:
4547:
4548:
4549: =item defaultFormData
4550:
4551: Returns html hidden inputs used to hold context/default values.
4552:
4553: Arguments:
4554: $symb - $symb of the current resource
4555:
4556: =cut
4557:
4558: sub defaultFormData {
4559: my ($symb)=@_;
4560: return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
4561: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
4562: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
4563: }
4564:
4565:
4566: =pod
4567:
4568: =item getSequenceDropDown
4569:
4570: Return html dropdown of possible sequences to grade
4571:
4572: Arguments:
4573: $symb - $symb of the current resource
4574:
4575: =cut
4576:
4577: sub getSequenceDropDown {
4578: my ($symb)=@_;
4579: my $result='<select name="selectpage">'."\n";
4580: my ($titles,$symbx) = &getSymbMap();
4581: my ($curpage)=&Apache::lonnet::decode_symb($symb);
4582: my $ctr=0;
4583: foreach (@$titles) {
4584: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4585: $result.='<option value="'.$$symbx{$_}.'" '.
4586: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
4587: '>'.$showtitle.'</option>'."\n";
4588: $ctr++;
4589: }
4590: $result.= '</select>';
4591: return $result;
4592: }
4593:
4594:
4595: =pod
4596:
4597: =item scantron_filenames
4598:
4599: Returns a list of the scantron files in the current course
4600:
4601: =cut
4602:
4603: sub scantron_filenames {
4604: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4605: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
4606: my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
4607: &propath($cdom,$cname));
4608: my @possiblenames;
4609: foreach my $filename (sort(@files)) {
4610: ($filename)=split(/&/,$filename);
4611: if ($filename!~/^scantron_orig_/) { next ; }
4612: $filename=~s/^scantron_orig_//;
4613: push(@possiblenames,$filename);
4614: }
4615: return @possiblenames;
4616: }
4617:
4618: =pod
4619:
4620: =item scantron_uploads
4621:
4622: Returns html drop-down list of scantron files in current course.
4623:
4624: Arguments:
4625: $file2grade - filename to set as selected in the dropdown
4626:
4627: =cut
4628:
4629: sub scantron_uploads {
4630: my ($file2grade) = @_;
4631: my $result= '<select name="scantron_selectfile">';
4632: $result.="<option></option>";
4633: foreach my $filename (sort(&scantron_filenames())) {
4634: $result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
4635: }
4636: $result.="</select>";
4637: return $result;
4638: }
4639:
4640: =pod
4641:
4642: =item scantron_scantab
4643:
4644: Returns html drop down of the scantron formats in the scantronformat.tab
4645: file.
4646:
4647: =cut
4648:
4649: sub scantron_scantab {
4650: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
4651: my $result='<select name="scantron_format">'."\n";
4652: $result.='<option></option>'."\n";
4653: foreach my $line (<$fh>) {
4654: my ($name,$descrip)=split(/:/,$line);
4655: if ($name =~ /^\#/) { next; }
4656: $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
4657: }
4658: $result.='</select>'."\n";
4659:
4660: return $result;
4661: }
4662:
4663: =pod
4664:
4665: =item scantron_CODElist
4666:
4667: Returns html drop down of the saved CODE lists from current course,
4668: generated from earlier printings.
4669:
4670: =cut
4671:
4672: sub scantron_CODElist {
4673: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4674: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4675: my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
4676: my $namechoice='<option></option>';
4677: foreach my $name (sort {uc($a) cmp uc($b)} @names) {
4678: if ($name =~ /^error: 2 /) { next; }
4679: if ($name =~ /^type\0/) { next; }
4680: $namechoice.='<option value="'.$name.'">'.$name.'</option>';
4681: }
4682: $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
4683: return $namechoice;
4684: }
4685:
4686: =pod
4687:
4688: =item scantron_CODEunique
4689:
4690: Returns the html for "Each CODE to be used once" radio.
4691:
4692: =cut
4693:
4694: sub scantron_CODEunique {
4695: my $result='<span style="white-space: nowrap;">
4696: <label><input type="radio" name="scantron_CODEunique"
4697: value="yes" checked="checked" />'.&mt('Yes').' </label>
4698: </span>
4699: <span style="white-space: nowrap;">
4700: <label><input type="radio" name="scantron_CODEunique"
4701: value="no" />'.&mt('No').' </label>
4702: </span>';
4703: return $result;
4704: }
4705:
4706: =pod
4707:
4708: =item scantron_selectphase
4709:
4710: Generates the initial screen to start the bubble sheet process.
4711: Allows for - starting a grading run.
4712: - downloading existing scan data (original, corrected
4713: or skipped info)
4714:
4715: - uploading new scan data
4716:
4717: Arguments:
4718: $r - The Apache request object
4719: $file2grade - name of the file that contain the scanned data to score
4720:
4721: =cut
4722:
4723: sub scantron_selectphase {
4724: my ($r,$file2grade) = @_;
4725: my ($symb)=&get_symb($r);
4726: if (!$symb) {return '';}
4727: my $sequence_selector=&getSequenceDropDown($symb);
4728: my $default_form_data=&defaultFormData($symb);
4729: my $grading_menu_button=&show_grading_menu_form($symb);
4730: my $file_selector=&scantron_uploads($file2grade);
4731: my $format_selector=&scantron_scantab();
4732: my $CODE_selector=&scantron_CODElist();
4733: my $CODE_unique=&scantron_CODEunique();
4734: my $result;
4735:
4736: # Chunk of form to prompt for a file to grade and how:
4737:
4738: $result.= <<SCANTRONFORM;
4739: <table width="100%" border="0">
4740: <tr>
4741: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
4742: <td bgcolor="#777777">
4743: <input type="hidden" name="command" value="scantron_warning" />
4744: $default_form_data
4745: <table width="100%" border="0">
4746: <tr bgcolor="#e6ffff">
4747: <td colspan="2">
4748: <b>Specify file and which Folder/Sequence to grade</b>
4749: </td>
4750: </tr>
4751: <tr bgcolor="#ffffe6">
4752: <td> Sequence to grade: </td><td> $sequence_selector </td>
4753: </tr>
4754: <tr bgcolor="#ffffe6">
4755: <td> Filename of scoring office file: </td><td> $file_selector </td>
4756: </tr>
4757: <tr bgcolor="#ffffe6">
4758: <td> Format of data file: </td><td> $format_selector </td>
4759: </tr>
4760: <tr bgcolor="#ffffe6">
4761: <td> Saved CODEs to validate against: </td><td> $CODE_selector</td>
4762: </tr>
4763: <tr bgcolor="#ffffe6">
4764: <td> Each CODE is only to be used once:</td><td> $CODE_unique </td>
4765: </tr>
4766: <tr bgcolor="#ffffe6">
4767: <td> Options: </td>
4768: <td>
4769: <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> Do only previously skipped records</label> <br />
4770: <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> Remove all existing corrections</label> <br />
4771: <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> Skip hidden resources when grading</label>
4772: </td>
4773: </tr>
4774: <tr bgcolor="#ffffe6">
4775: <td colspan="2">
4776: <input type="submit" value="Grading: Validate Scantron Records" />
4777: </td>
4778: </tr>
4779: </table>
4780: </td>
4781: </form>
4782: </tr>
4783: SCANTRONFORM
4784:
4785: $r->print($result);
4786:
4787: if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
4788: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
4789:
4790: # Chunk of form to prompt for a scantron file upload.
4791:
4792: $r->print(<<SCANTRONFORM);
4793: <tr>
4794: <td bgcolor="#777777">
4795: <table width="100%" border="0">
4796: <tr bgcolor="#e6ffff">
4797: <td>
4798: <b>Specify a Scantron data file to upload.</b>
4799: </td>
4800: </tr>
4801: <tr bgcolor="#ffffe6">
4802: <td>
4803: SCANTRONFORM
4804: my $default_form_data=&defaultFormData(&get_symb($r,1));
4805: my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
4806: my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
4807: $r->print(<<UPLOAD);
4808: <script type="text/javascript" language="javascript">
4809: function checkUpload(formname) {
4810: if (formname.upfile.value == "") {
4811: alert("Please use the browse button to select a file from your local directory.");
4812: return false;
4813: }
4814: formname.submit();
4815: }
4816: </script>
4817:
4818: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
4819: $default_form_data
4820: <input name='courseid' type='hidden' value='$cnum' />
4821: <input name='domainid' type='hidden' value='$cdom' />
4822: <input name='command' value='scantronupload_save' type='hidden' />
4823: File to upload:<input type="file" name="upfile" size="50" />
4824: <br />
4825: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
4826: </form>
4827: UPLOAD
4828:
4829: $r->print(<<SCANTRONFORM);
4830: </td>
4831: </tr>
4832: </table>
4833: </td>
4834: </tr>
4835: SCANTRONFORM
4836: }
4837:
4838: # Chunk of the form that prompts to view a scoring office file,
4839: # corrected file, skipped records in a file.
4840:
4841: $r->print(<<SCANTRONFORM);
4842: <tr>
4843: <form action='/adm/grades' name='scantron_download'>
4844: <td bgcolor="#777777">
4845: $default_form_data
4846: <input type="hidden" name="command" value="scantron_download" />
4847: <table width="100%" border="0">
4848: <tr bgcolor="#e6ffff">
4849: <td colspan="2">
4850: <b>Download a scoring office file</b>
4851: </td>
4852: </tr>
4853: <tr bgcolor="#ffffe6">
4854: <td> Filename of scoring office file: </td><td> $file_selector </td>
4855: </tr>
4856: <tr bgcolor="#ffffe6">
4857: <td colspan="2">
4858: <input type="submit" value="Download: Show List of Associated Files" />
4859: </td>
4860: </tr>
4861: </table>
4862: </td>
4863: </form>
4864: </tr>
4865: SCANTRONFORM
4866:
4867: $r->print(<<SCANTRONFORM);
4868: </table>
4869: $grading_menu_button
4870: SCANTRONFORM
4871:
4872: return
4873: }
4874:
4875: =pod
4876:
4877: =item get_scantron_config
4878:
4879: Parse and return the scantron configuration line selected as a
4880: hash of configuration file fields.
4881:
4882: Arguments:
4883: which - the name of the configuration to parse from the file.
4884:
4885:
4886: Returns:
4887: If the named configuration is not in the file, an empty
4888: hash is returned.
4889: a hash with the fields
4890: name - internal name for the this configuration setup
4891: description - text to display to operator that describes this config
4892: CODElocation - if 0 or the string 'none'
4893: - no CODE exists for this config
4894: if -1 || the string 'letter'
4895: - a CODE exists for this config and is
4896: a string of letters
4897: Unsupported value (but planned for future support)
4898: if a positive integer
4899: - The CODE exists as the first n items from
4900: the question section of the form
4901: if the string 'number'
4902: - The CODE exists for this config and is
4903: a string of numbers
4904: CODEstart - (only matter if a CODE exists) column in the line where
4905: the CODE starts
4906: CODElength - length of the CODE
4907: IDstart - column where the student ID number starts
4908: IDlength - length of the student ID info
4909: Qstart - column where the information from the bubbled
4910: 'questions' start
4911: Qlength - number of columns comprising a single bubble line from
4912: the sheet. (usually either 1 or 10)
4913: Qon - either a single character representing the character used
4914: to signal a bubble was chosen in the positional setup, or
4915: the string 'letter' if the letter of the chosen bubble is
4916: in the final, or 'number' if a number representing the
4917: chosen bubble is in the file (1->A 0->J)
4918: Qoff - the character used to represent that a bubble was
4919: left blank
4920: PaperID - if the scanning process generates a unique number for each
4921: sheet scanned the column that this ID number starts in
4922: PaperIDlength - number of columns that comprise the unique ID number
4923: for the sheet of paper
4924: FirstName - column that the first name starts in
4925: FirstNameLength - number of columns that the first name spans
4926:
4927: LastName - column that the last name starts in
4928: LastNameLength - number of columns that the last name spans
4929:
4930: =cut
4931:
4932: sub get_scantron_config {
4933: my ($which) = @_;
4934: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
4935: my %config;
4936: #FIXME probably should move to XML it has already gotten a bit much now
4937: foreach my $line (<$fh>) {
4938: my ($name,$descrip)=split(/:/,$line);
4939: if ($name ne $which ) { next; }
4940: chomp($line);
4941: my @config=split(/:/,$line);
4942: $config{'name'}=$config[0];
4943: $config{'description'}=$config[1];
4944: $config{'CODElocation'}=$config[2];
4945: $config{'CODEstart'}=$config[3];
4946: $config{'CODElength'}=$config[4];
4947: $config{'IDstart'}=$config[5];
4948: $config{'IDlength'}=$config[6];
4949: $config{'Qstart'}=$config[7];
4950: $config{'Qlength'}=$config[8];
4951: $config{'Qoff'}=$config[9];
4952: $config{'Qon'}=$config[10];
4953: $config{'PaperID'}=$config[11];
4954: $config{'PaperIDlength'}=$config[12];
4955: $config{'FirstName'}=$config[13];
4956: $config{'FirstNamelength'}=$config[14];
4957: $config{'LastName'}=$config[15];
4958: $config{'LastNamelength'}=$config[16];
4959: last;
4960: }
4961: return %config;
4962: }
4963:
4964: =pod
4965:
4966: =item username_to_idmap
4967:
4968: creates a hash keyed by student id with values of the corresponding
4969: student username:domain.
4970:
4971: Arguments:
4972:
4973: $classlist - reference to the class list hash. This is a hash
4974: keyed by student name:domain whose elements are references
4975: to arrays containing various chunks of information
4976: about the student. (See loncoursedata for more info).
4977:
4978: Returns
4979: %idmap - the constructed hash
4980:
4981: =cut
4982:
4983: sub username_to_idmap {
4984: my ($classlist)= @_;
4985: my %idmap;
4986: foreach my $student (keys(%$classlist)) {
4987: $idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
4988: $student;
4989: }
4990: return %idmap;
4991: }
4992:
4993: =pod
4994:
4995: =item scantron_fixup_scanline
4996:
4997: Process a requested correction to a scanline.
4998:
4999: Arguments:
5000: $scantron_config - hash from &get_scantron_config()
5001: $scan_data - hash of correction information
5002: (see &scantron_getfile())
5003: $line - existing scanline
5004: $whichline - line number of the passed in scanline
5005: $field - type of change to process
5006: (either
5007: 'ID' -> correct the student ID number
5008: 'CODE' -> correct the CODE
5009: 'answer' -> fixup the submitted answers)
5010:
5011: $args - hash of additional info,
5012: - 'ID'
5013: 'newid' -> studentID to use in replacement
5014: of existing one
5015: - 'CODE'
5016: 'CODE_ignore_dup' - set to true if duplicates
5017: should be ignored.
5018: 'CODE' - is new code or 'use_unfound'
5019: if the existing unfound code should
5020: be used as is
5021: - 'answer'
5022: 'response' - new answer or 'none' if blank
5023: 'question' - the bubble line to change
5024:
5025: Returns:
5026: $line - the modified scanline
5027:
5028: Side effects:
5029: $scan_data - may be updated
5030:
5031: =cut
5032:
5033:
5034: sub scantron_fixup_scanline {
5035: my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
5036:
5037: if ($field eq 'ID') {
5038: if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
5039: return ($line,1,'New value too large');
5040: }
5041: if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
5042: $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
5043: $args->{'newid'});
5044: }
5045: substr($line,$$scantron_config{'IDstart'}-1,
5046: $$scantron_config{'IDlength'})=$args->{'newid'};
5047: if ($args->{'newid'}=~/^\s*$/) {
5048: &scan_data($scan_data,"$whichline.user",
5049: $args->{'username'}.':'.$args->{'domain'});
5050: }
5051: } elsif ($field eq 'CODE') {
5052: if ($args->{'CODE_ignore_dup'}) {
5053: &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
5054: }
5055: &scan_data($scan_data,"$whichline.useCODE",'1');
5056: if ($args->{'CODE'} ne 'use_unfound') {
5057: if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
5058: return ($line,1,'New CODE value too large');
5059: }
5060: if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
5061: $args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
5062: }
5063: substr($line,$$scantron_config{'CODEstart'}-1,
5064: $$scantron_config{'CODElength'})=$args->{'CODE'};
5065: }
5066: } elsif ($field eq 'answer') {
5067: my $length=$scantron_config->{'Qlength'};
5068: my $off=$scantron_config->{'Qoff'};
5069: my $on=$scantron_config->{'Qon'};
5070: my $answer=${off}x$length;
5071: if ($args->{'response'} eq 'none') {
5072: &scan_data($scan_data,
5073: "$whichline.no_bubble.".$args->{'question'},'1');
5074: } else {
5075: if ($on eq 'letter') {
5076: my @alphabet=('A'..'Z');
5077: $answer=$alphabet[$args->{'response'}];
5078: } elsif ($on eq 'number') {
5079: $answer=$args->{'response'}+1;
5080: if ($answer == 10) { $answer = '0'; }
5081: } else {
5082: substr($answer,$args->{'response'},1)=$on;
5083: }
5084: &scan_data($scan_data,
5085: "$whichline.no_bubble.".$args->{'question'},undef,'1');
5086: }
5087: my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
5088: substr($line,$where-1,$length)=$answer;
5089: }
5090: return $line;
5091: }
5092:
5093: =pod
5094:
5095: =item scan_data
5096:
5097: Edit or look up an item in the scan_data hash.
5098:
5099: Arguments:
5100: $scan_data - The hash (see scantron_getfile)
5101: $key - shorthand of the key to edit (actual key is
5102: scantronfilename_key).
5103: $data - New value of the hash entry.
5104: $delete - If true, the entry is removed from the hash.
5105:
5106: Returns:
5107: The new value of the hash table field (undefined if deleted).
5108:
5109: =cut
5110:
5111:
5112: sub scan_data {
5113: my ($scan_data,$key,$value,$delete)=@_;
5114: my $filename=$env{'form.scantron_selectfile'};
5115: if (defined($value)) {
5116: $scan_data->{$filename.'_'.$key} = $value;
5117: }
5118: if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
5119: return $scan_data->{$filename.'_'.$key};
5120: }
5121:
5122: =pod
5123:
5124: =item scantron_parse_scanline
5125:
5126: Decodes a scanline from the selected scantron file
5127:
5128: Arguments:
5129: line - The text of the scantron file line to process
5130: whichline - Line number
5131: scantron_config - Hash describing the format of the scantron lines.
5132: scan_data - Hash of extra information about the scanline
5133: (see scantron_getfile for more information)
5134: just_header - True if should not process question answers but only
5135: the stuff to the left of the answers.
5136: Returns:
5137: Hash containing the result of parsing the scanline
5138:
5139: Keys are all proceeded by the string 'scantron.'
5140:
5141: CODE - the CODE in use for this scanline
5142: useCODE - 1 if the CODE is invalid but it usage has been forced
5143: by the operator
5144: CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
5145: CODEs were selected, but the usage has been
5146: forced by the operator
5147: ID - student ID
5148: PaperID - if used, the ID number printed on the sheet when the
5149: paper was scanned
5150: FirstName - first name from the sheet
5151: LastName - last name from the sheet
5152:
5153: if just_header was not true these key may also exist
5154:
5155: missingerror - a list of bubble ranges that are considered to be answers
5156: to a single question that don't have any bubbles filled in.
5157: Of the form questionnumber:firstbubblenumber:count.
5158: doubleerror - a list of bubble ranges that are considered to be answers
5159: to a single question that have more than one bubble filled in.
5160: Of the form questionnumber::firstbubblenumber:count
5161:
5162: In the above, count is the number of bubble responses in the
5163: input line needed to represent the possible answers to the question.
5164: e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
5165: per line would have count = 2.
5166:
5167: maxquest - the number of the last bubble line that was parsed
5168:
5169: (<number> starts at 1)
5170: <number>.answer - zero or more letters representing the selected
5171: letters from the scanline for the bubble line
5172: <number>.
5173: if blank there was either no bubble or there where
5174: multiple bubbles, (consult the keys missingerror and
5175: doubleerror if this is an error condition)
5176:
5177: =cut
5178:
5179: sub scantron_parse_scanline {
5180: my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
5181: my %record;
5182: my $questions=substr($line,$$scantron_config{'Qstart'}-1); # Answers
5183: my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # earlier stuff
5184: if (!($$scantron_config{'CODElocation'} eq 0 ||
5185: $$scantron_config{'CODElocation'} eq 'none')) {
5186: if ($$scantron_config{'CODElocation'} < 0 ||
5187: $$scantron_config{'CODElocation'} eq 'letter' ||
5188: $$scantron_config{'CODElocation'} eq 'number') {
5189: $record{'scantron.CODE'}=substr($data,
5190: $$scantron_config{'CODEstart'}-1,
5191: $$scantron_config{'CODElength'});
5192: if (&scan_data($scan_data,"$whichline.useCODE")) {
5193: $record{'scantron.useCODE'}=1;
5194: }
5195: if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
5196: $record{'scantron.CODE_ignore_dup'}=1;
5197: }
5198: } else {
5199: #FIXME interpret first N questions
5200: }
5201: }
5202: $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
5203: $$scantron_config{'IDlength'});
5204: $record{'scantron.PaperID'}=
5205: substr($data,$$scantron_config{'PaperID'}-1,
5206: $$scantron_config{'PaperIDlength'});
5207: $record{'scantron.FirstName'}=
5208: substr($data,$$scantron_config{'FirstName'}-1,
5209: $$scantron_config{'FirstNamelength'});
5210: $record{'scantron.LastName'}=
5211: substr($data,$$scantron_config{'LastName'}-1,
5212: $$scantron_config{'LastNamelength'});
5213: if ($just_header) { return \%record; }
5214:
5215: my @alphabet=('A'..'Z');
5216: my $questnum=0;
5217: my $ansnum =1; # Multiple 'answer lines'/question.
5218:
5219: while ($questions) {
5220: my $answers_needed = $bubble_lines_per_response{$questnum};
5221: my $answer_length = $$scantron_config{'Qlength'} * $answers_needed;
5222:
5223:
5224:
5225: $questnum++;
5226: my $currentquest = substr($questions,0,$answer_length);
5227: $questions = substr($questions,0,$answer_length)='';
5228: if (length($currentquest) < $answer_length) { next; }
5229:
5230: # Qon letter implies for each slot in currentquest we have:
5231: # ? or * for doubles a letter in A-Z for a bubble and
5232: # about anything else (esp. a value of Qoff for missing
5233: # bubbles.
5234:
5235:
5236: if ($$scantron_config{'Qon'} eq 'letter') {
5237:
5238: if ($currentquest =~ /\?/
5239: || $currentquest =~ /\*/
5240: || (&occurence_count($currentquest, "[A-Z]") > 1)) {
5241: push(@{$record{'scantron.doubleerror'}},$questnum);
5242: for (my $ans = 0; $ans < $answers_needed; $ans++) {
5243: $record{"scantron.$ansnum.answer"}='';
5244: $ansnum++;
5245: }
5246:
5247: } elsif (!defined($currentquest)
5248: || (&occurence_count($currentquest, $$scantron_config{'Qoff'}) == length($currentquest))
5249: || (&occurence_count($currentquest, "[A-Z]") == 0)) {
5250: for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
5251: $record{"scantron.$ansnum.answer"}='';
5252: $ansnum++;
5253:
5254: }
5255: if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
5256: push(@{$record{"scantron.missingerror"}},$questnum);
5257: $ansnum += $answers_needed;
5258: }
5259:
5260: } else {
5261: for (my $ans = 0; $ans < $answers_needed; $ans++) {
5262: $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
5263: $ansnum++;
5264: }
5265: }
5266:
5267: # Qon 'number' implies each slot gives a digit that indexes the
5268: # the bubbles filled or Qoff or a non number for unbubbled lines.
5269: # and *? for double bubbles on a line.
5270: # these answers are also stored as letters.
5271:
5272: } elsif ($$scantron_config{'Qon'} eq 'number') {
5273: if ($currentquest =~ /\?/
5274: || $currentquest =~ /\*/
5275: || (&occurence_count($currentquest, '\d') > 1)) {
5276: push(@{$record{'scantron.doubleerror'}},$questnum);
5277: for (my $ans = 0; $ans < $answers_needed; $ans++) {
5278: $record{"scantron.$ansnum.answer"}='';
5279: $ansnum++;
5280: }
5281:
5282: } elsif (!defined($currentquest)
5283: || (&occurence_count($currentquest,$$scantron_config{'Qoff'}) == length($currentquest))
5284: || (&occurence_count($currentquest, '\d') == 0)) {
5285: for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
5286: $record{"scantron.$ansnum.answer"}='';
5287: $ansnum++;
5288:
5289: }
5290: if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
5291: push(@{$record{"scantron.missingerror"}},$questnum);
5292: $ansnum += $answers_needed;
5293: }
5294:
5295: } else {
5296: $currentquest = &digits_to_letters($currentquest);
5297: for (my $ans =0; $ans < $answers_needed; $ans++) {
5298: $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
5299: $ansnum++;
5300: }
5301: }
5302: } else {
5303:
5304: # Otherwise there's a positional notation;
5305: # each bubble line requires Qlength items, and there are filled in
5306: # bubbles for each case where there 'Qon' characters.
5307: #
5308:
5309: my @array=split($$scantron_config{'Qon'},$currentquest,-1);
5310:
5311: # If the split only giveas us one element.. the full length of the
5312: # answser string, no bubbles are filled in:
5313:
5314: if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
5315: for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
5316: $record{"scantron.$ansnum.answer"}='';
5317: $ansnum++;
5318:
5319: }
5320: if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
5321: push(@{$record{"scantron.missingerror"}},$questnum);
5322: }
5323: } elsif (scalar(@array) lt 2) {
5324:
5325: my $location = [length($array[0])];
5326: my $line_num = $location / $$scantron_config{'Qlength'};
5327: my $bubble = $alphabet[$location % $$scantron_config{'Qlength'}];
5328:
5329: for (my $ans = 0; $ans < $answers_needed; $ans++) {
5330: if ($ans eq $line_num) {
5331: $record{"scantron.$ansnum.answer"} = $bubble;
5332: } else {
5333: $record{"scantron.$ansnum.answer"} = ' ';
5334: }
5335: $ansnum++;
5336: }
5337: }
5338: # If there's more than one instance of a bubble character
5339: # That's a double bubble; with positional notation we can
5340: # record all the bubbles filled in as well as the
5341: # fact this response consists of multiple bubbles.
5342: #
5343: else {
5344: push(@{$record{'scantron.doubleerror'}},$questnum);
5345:
5346: my $first_answer = $ansnum;
5347: for (my $ans =0; $ans < $answers_needed; $ans++) {
5348: $record{"scantron.$ansnum.answer"} = '';
5349: $ans++;
5350: }
5351:
5352: my @ans=@array;
5353: my $i=length($ans[0]);shift(@ans);
5354: while ($#ans) {
5355: $i+=length($ans[0])+1;
5356: my $line = $i/$$scantron_config{'Qlength'} + $first_answer;
5357: my $bubble = $i%$$scantron_config{'Qlength'};
5358:
5359: $record{"scantron.$line.answer"}.=$alphabet[$bubble];
5360: shift(@ans);
5361: }
5362: }
5363: }
5364: }
5365: $record{'scantron.maxquest'}=$questnum;
5366: return \%record;
5367: }
5368:
5369: =pod
5370:
5371: =item scantron_add_delay
5372:
5373: Adds an error message that occurred during the grading phase to a
5374: queue of messages to be shown after grading pass is complete
5375:
5376: Arguments:
5377: $delayqueue - arrary ref of hash ref of error messages
5378: $scanline - the scanline that caused the error
5379: $errormesage - the error message
5380: $errorcode - a numeric code for the error
5381:
5382: Side Effects:
5383: updates the $delayqueue to have a new hash ref of the error
5384:
5385: =cut
5386:
5387: sub scantron_add_delay {
5388: my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
5389: push(@$delayqueue,
5390: {'line' => $scanline, 'emsg' => $errormessage,
5391: 'ecode' => $errorcode }
5392: );
5393: }
5394:
5395: =pod
5396:
5397: =item scantron_find_student
5398:
5399: Finds the username for the current scanline
5400:
5401: Arguments:
5402: $scantron_record - hash result from scantron_parse_scanline
5403: $scan_data - hash of correction information
5404: (see &scantron_getfile() form more information)
5405: $idmap - hash from &username_to_idmap()
5406: $line - number of current scanline
5407:
5408: Returns:
5409: Either 'username:domain' or undef if unknown
5410:
5411: =cut
5412:
5413: sub scantron_find_student {
5414: my ($scantron_record,$scan_data,$idmap,$line)=@_;
5415: my $scanID=$$scantron_record{'scantron.ID'};
5416: if ($scanID =~ /^\s*$/) {
5417: return &scan_data($scan_data,"$line.user");
5418: }
5419: foreach my $id (keys(%$idmap)) {
5420: if (lc($id) eq lc($scanID)) {
5421: return $$idmap{$id};
5422: }
5423: }
5424: return undef;
5425: }
5426:
5427: =pod
5428:
5429: =item scantron_filter
5430:
5431: Filter sub for lonnavmaps, filters out hidden resources if ignore
5432: hidden resources was selected
5433:
5434: =cut
5435:
5436: sub scantron_filter {
5437: my ($curres)=@_;
5438:
5439: if (ref($curres) && $curres->is_problem()) {
5440: # if the user has asked to not have either hidden
5441: # or 'randomout' controlled resources to be graded
5442: # don't include them
5443: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
5444: && $curres->randomout) {
5445: return 0;
5446: }
5447: return 1;
5448: }
5449: return 0;
5450: }
5451:
5452: =pod
5453:
5454: =item scantron_process_corrections
5455:
5456: Gets correction information out of submitted form data and corrects
5457: the scanline
5458:
5459: =cut
5460:
5461: sub scantron_process_corrections {
5462: my ($r) = @_;
5463: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
5464: my ($scanlines,$scan_data)=&scantron_getfile();
5465: my $classlist=&Apache::loncoursedata::get_classlist();
5466: my $which=$env{'form.scantron_line'};
5467: my $line=&scantron_get_line($scanlines,$scan_data,$which);
5468: my ($skip,$err,$errmsg);
5469: if ($env{'form.scantron_skip_record'}) {
5470: $skip=1;
5471: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
5472: my $newstudent=$env{'form.scantron_username'}.':'.
5473: $env{'form.scantron_domain'};
5474: my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
5475: ($line,$err,$errmsg)=
5476: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
5477: 'ID',{'newid'=>$newid,
5478: 'username'=>$env{'form.scantron_username'},
5479: 'domain'=>$env{'form.scantron_domain'}});
5480: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
5481: my $resolution=$env{'form.scantron_CODE_resolution'};
5482: my $newCODE;
5483: my %args;
5484: if ($resolution eq 'use_unfound') {
5485: $newCODE='use_unfound';
5486: } elsif ($resolution eq 'use_found') {
5487: $newCODE=$env{'form.scantron_CODE_selectedvalue'};
5488: } elsif ($resolution eq 'use_typed') {
5489: $newCODE=$env{'form.scantron_CODE_newvalue'};
5490: } elsif ($resolution =~ /^use_closest_(\d+)/) {
5491: $newCODE=$env{"form.scantron_CODE_closest_$1"};
5492: }
5493: if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
5494: $args{'CODE_ignore_dup'}=1;
5495: }
5496: $args{'CODE'}=$newCODE;
5497: ($line,$err,$errmsg)=
5498: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
5499: 'CODE',\%args);
5500: } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
5501: foreach my $question (split(',',$env{'form.scantron_questions'})) {
5502: ($line,$err,$errmsg)=
5503: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
5504: $which,'answer',
5505: { 'question'=>$question,
5506: 'response'=>$env{"form.scantron_correct_Q_$question"}});
5507: if ($err) { last; }
5508: }
5509: }
5510: if ($err) {
5511: $r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
5512: } else {
5513: &scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
5514: &scantron_putfile($scanlines,$scan_data);
5515: }
5516: }
5517:
5518: =pod
5519:
5520: =item reset_skipping_status
5521:
5522: Forgets the current set of remember skipped scanlines (and thus
5523: reverts back to considering all lines in the
5524: scantron_skipped_<filename> file)
5525:
5526: =cut
5527:
5528: sub reset_skipping_status {
5529: my ($scanlines,$scan_data)=&scantron_getfile();
5530: &scan_data($scan_data,'remember_skipping',undef,1);
5531: &scantron_putfile(undef,$scan_data);
5532: }
5533:
5534: =pod
5535:
5536: =item start_skipping
5537:
5538: Marks a scanline to be skipped.
5539:
5540: =cut
5541:
5542: sub start_skipping {
5543: my ($scan_data,$i)=@_;
5544: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
5545: if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
5546: $remembered{$i}=2;
5547: } else {
5548: $remembered{$i}=1;
5549: }
5550: &scan_data($scan_data,'remember_skipping',join(':',%remembered));
5551: }
5552:
5553: =pod
5554:
5555: =item should_be_skipped
5556:
5557: Checks whether a scanline should be skipped.
5558:
5559: =cut
5560:
5561: sub should_be_skipped {
5562: my ($scanlines,$scan_data,$i)=@_;
5563: if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
5564: # not redoing old skips
5565: if ($scanlines->{'skipped'}[$i]) { return 1; }
5566: return 0;
5567: }
5568: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
5569:
5570: if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
5571: return 0;
5572: }
5573: return 1;
5574: }
5575:
5576: =pod
5577:
5578: =item remember_current_skipped
5579:
5580: Discovers what scanlines are in the scantron_skipped_<filename>
5581: file and remembers them into scan_data for later use.
5582:
5583: =cut
5584:
5585: sub remember_current_skipped {
5586: my ($scanlines,$scan_data)=&scantron_getfile();
5587: my %to_remember;
5588: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
5589: if ($scanlines->{'skipped'}[$i]) {
5590: $to_remember{$i}=1;
5591: }
5592: }
5593:
5594: &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
5595: &scantron_putfile(undef,$scan_data);
5596: }
5597:
5598: =pod
5599:
5600: =item check_for_error
5601:
5602: Checks if there was an error when attempting to remove a specific
5603: scantron_.. bubble sheet data file. Prints out an error if
5604: something went wrong.
5605:
5606: =cut
5607:
5608: sub check_for_error {
5609: my ($r,$result)=@_;
5610: if ($result ne 'ok' && $result ne 'not_found' ) {
5611: $r->print("An error occurred ($result) when trying to Remove the existing corrections.");
5612: }
5613: }
5614:
5615: =pod
5616:
5617: =item scantron_warning_screen
5618:
5619: Interstitial screen to make sure the operator has selected the
5620: correct options before we start the validation phase.
5621:
5622: =cut
5623:
5624: sub scantron_warning_screen {
5625: my ($button_text)=@_;
5626: my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
5627: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
5628: my $CODElist;
5629: if ($scantron_config{'CODElocation'} &&
5630: $scantron_config{'CODEstart'} &&
5631: $scantron_config{'CODElength'}) {
5632: $CODElist=$env{'form.scantron_CODElist'};
5633: if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
5634: $CODElist=
5635: '<tr><td><b>List of CODES to validate against:</b></td><td><tt>'.
5636: $env{'form.scantron_CODElist'}.'</tt></td></tr>';
5637: }
5638: return (<<STUFF);
5639: <p>
5640: <span class="LC_warning">Please double check the information
5641: below before clicking on '$button_text'</span>
5642: </p>
5643: <table>
5644: <tr><td><b>Sequence to be Graded:</b></td><td>$title</td></tr>
5645: <tr><td><b>Data File that will be used:</b></td><td><tt>$env{'form.scantron_selectfile'}</tt></td></tr>
5646: $CODElist
5647: </table>
5648: <br />
5649: <p> If this information is correct, please click on '$button_text'.</p>
5650: <p> If something is incorrect, please click the 'Grading Menu' button to start over.</p>
5651:
5652: <br />
5653: STUFF
5654: }
5655:
5656: =pod
5657:
5658: =item scantron_do_warning
5659:
5660: Check if the operator has picked something for all required
5661: fields. Error out if something is missing.
5662:
5663: =cut
5664:
5665: sub scantron_do_warning {
5666: my ($r)=@_;
5667: my ($symb)=&get_symb($r);
5668: if (!$symb) {return '';}
5669: my $default_form_data=&defaultFormData($symb);
5670: $r->print(&scantron_form_start().$default_form_data);
5671: if ( $env{'form.selectpage'} eq '' ||
5672: $env{'form.scantron_selectfile'} eq '' ||
5673: $env{'form.scantron_format'} eq '' ) {
5674: $r->print("<p>You have forgetten to specify some information. Please go Back and try again.</p>");
5675: if ( $env{'form.selectpage'} eq '') {
5676: $r->print('<p><span class="LC_error">You have not selected a Sequence to grade</span></p>');
5677: }
5678: if ( $env{'form.scantron_selectfile'} eq '') {
5679: $r->print('<p><span class="LC_error">You have not selected a file that contains the student\'s response data.</span></p>');
5680: }
5681: if ( $env{'form.scantron_format'} eq '') {
5682: $r->print('<p><span class="LC_error">You have not selected a the format of the student\'s response data.</span></p>');
5683: }
5684: } else {
5685: my $warning=&scantron_warning_screen('Grading: Validate Records');
5686: $r->print(<<STUFF);
5687: $warning
5688: <input type="submit" name="submit" value="Grading: Validate Records" />
5689: <input type="hidden" name="command" value="scantron_validate" />
5690: STUFF
5691: }
5692: $r->print("</form><br />".&show_grading_menu_form($symb));
5693: return '';
5694: }
5695:
5696: =pod
5697:
5698: =item scantron_form_start
5699:
5700: html hidden input for remembering all selected grading options
5701:
5702: =cut
5703:
5704: sub scantron_form_start {
5705: my ($max_bubble)=@_;
5706: my $result= <<SCANTRONFORM;
5707: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
5708: <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
5709: <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
5710: <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
5711: <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
5712: <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
5713: <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
5714: <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
5715: <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
5716: <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
5717: SCANTRONFORM
5718:
5719: my $line = 0;
5720: while (defined($env{"form.scantron.bubblelines.$line"})) {
5721: &Apache::lonnet::logthis("Saving chunk for $line");
5722: my $chunk =
5723: '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
5724: $chunk .=
5725: '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
5726: $result .= $chunk;
5727: $line++;
5728: }
5729: return $result;
5730: }
5731:
5732: =pod
5733:
5734: =item scantron_validate_file
5735:
5736: Dispatch routine for doing validation of a bubble sheet data file.
5737:
5738: Also processes any necessary information resets that need to
5739: occur before validation begins (ignore previous corrections,
5740: restarting the skipped records processing)
5741:
5742: =cut
5743:
5744: sub scantron_validate_file {
5745: my ($r) = @_;
5746: my ($symb)=&get_symb($r);
5747: if (!$symb) {return '';}
5748: my $default_form_data=&defaultFormData($symb);
5749:
5750: # do the detection of only doing skipped records first befroe we delete
5751: # them when doing the corrections reset
5752: if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
5753: &reset_skipping_status();
5754: }
5755: if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
5756: &remember_current_skipped();
5757: $env{'form.scantron_options_redo'}='redo_skipped_ready';
5758: }
5759:
5760: if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
5761: &check_for_error($r,&scantron_remove_file('corrected'));
5762: &check_for_error($r,&scantron_remove_file('skipped'));
5763: &check_for_error($r,&scantron_remove_scan_data());
5764: $env{'form.scantron_options_ignore'}='done';
5765: }
5766:
5767: if ($env{'form.scantron_corrections'}) {
5768: &scantron_process_corrections($r);
5769: }
5770: $r->print("<p>Gathering necessary info.</p>");$r->rflush();
5771: #get the student pick code ready
5772: $r->print(&Apache::loncommon::studentbrowser_javascript());
5773: my $max_bubble=&scantron_get_maxbubble();
5774: my $result=&scantron_form_start($max_bubble).$default_form_data;
5775: $r->print($result);
5776:
5777: my @validate_phases=( 'sequence',
5778: 'ID',
5779: 'CODE',
5780: 'doublebubble',
5781: 'missingbubbles');
5782: if (!$env{'form.validatepass'}) {
5783: $env{'form.validatepass'} = 0;
5784: }
5785: my $currentphase=$env{'form.validatepass'};
5786:
5787: &Apache::lonnet::logthis("Phase: $currentphase");
5788:
5789: my $stop=0;
5790: while (!$stop && $currentphase < scalar(@validate_phases)) {
5791: $r->print("<p> Validating ".$validate_phases[$currentphase]."</p>");
5792: $r->rflush();
5793: my $which="scantron_validate_".$validate_phases[$currentphase];
5794: {
5795: no strict 'refs';
5796: ($stop,$currentphase)=&$which($r,$currentphase);
5797: }
5798: }
5799: if (!$stop) {
5800: my $warning=&scantron_warning_screen('Start Grading');
5801: $r->print(<<STUFF);
5802: Validation process complete.<br />
5803: $warning
5804: <input type="submit" name="submit" value="Start Grading" />
5805: <input type="hidden" name="command" value="scantron_process" />
5806: STUFF
5807:
5808: } else {
5809: $r->print('<input type="hidden" name="command" value="scantron_validate" />');
5810: $r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
5811: }
5812: if ($stop) {
5813: if ($validate_phases[$currentphase] eq 'sequence') {
5814: $r->print('<input type="submit" name="submit" value="Ignore -> " />');
5815: $r->print(' this error <br />');
5816:
5817: $r->print(" <p>Or click the 'Grading Menu' button to start over.</p>");
5818: } else {
5819: $r->print('<input type="submit" name="submit" value="Continue ->" />');
5820: $r->print(' using corrected info <br />');
5821: $r->print("<input type='submit' value='Skip' name='scantron_skip_record' />");
5822: $r->print(" this scanline saving it for later.");
5823: }
5824: }
5825: $r->print(" </form><br />".&show_grading_menu_form($symb));
5826: return '';
5827: }
5828:
5829:
5830: =pod
5831:
5832: =item scantron_remove_file
5833:
5834: Removes the requested bubble sheet data file, makes sure that
5835: scantron_original_<filename> is never removed
5836:
5837:
5838: =cut
5839:
5840: sub scantron_remove_file {
5841: my ($which)=@_;
5842: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5843: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5844: my $file='scantron_';
5845: if ($which eq 'corrected' || $which eq 'skipped') {
5846: $file.=$which.'_';
5847: } else {
5848: return 'refused';
5849: }
5850: $file.=$env{'form.scantron_selectfile'};
5851: return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
5852: }
5853:
5854:
5855: =pod
5856:
5857: =item scantron_remove_scan_data
5858:
5859: Removes all scan_data correction for the requested bubble sheet
5860: data file. (In the case that both the are doing skipped records we need
5861: to remember the old skipped lines for the time being so that element
5862: persists for a while.)
5863:
5864: =cut
5865:
5866: sub scantron_remove_scan_data {
5867: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5868: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5869: my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
5870: my @todelete;
5871: my $filename=$env{'form.scantron_selectfile'};
5872: foreach my $key (@keys) {
5873: if ($key=~/^\Q$filename\E_/) {
5874: if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
5875: $key=~/remember_skipping/) {
5876: next;
5877: }
5878: push(@todelete,$key);
5879: }
5880: }
5881: my $result;
5882: if (@todelete) {
5883: $result=&Apache::lonnet::del('nohist_scantrondata',\@todelete,$cdom,$cname);
5884: }
5885: return $result;
5886: }
5887:
5888:
5889: =pod
5890:
5891: =item scantron_getfile
5892:
5893: Fetches the requested bubble sheet data file (all 3 versions), and
5894: the scan_data hash
5895:
5896: Arguments:
5897: None
5898:
5899: Returns:
5900: 2 hash references
5901:
5902: - first one has
5903: orig -
5904: corrected -
5905: skipped - each of which points to an array ref of the specified
5906: file broken up into individual lines
5907: count - number of scanlines
5908:
5909: - second is the scan_data hash possible keys are
5910: ($number refers to scanline numbered $number and thus the key affects
5911: only that scanline
5912: $bubline refers to the specific bubble line element and the aspects
5913: refers to that specific bubble line element)
5914:
5915: $number.user - username:domain to use
5916: $number.CODE_ignore_dup
5917: - ignore the duplicate CODE error
5918: $number.useCODE
5919: - use the CODE in the scanline as is
5920: $number.no_bubble.$bubline
5921: - it is valid that there is no bubbled in bubble
5922: at $number $bubline
5923: remember_skipping
5924: - a frozen hash containing keys of $number and values
5925: of either
5926: 1 - we are on a 'do skipped records pass' and plan
5927: on processing this line
5928: 2 - we are on a 'do skipped records pass' and this
5929: scanline has been marked to skip yet again
5930:
5931: =cut
5932:
5933: sub scantron_getfile {
5934: #FIXME really would prefer a scantron directory
5935: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5936: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5937: my $lines;
5938: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
5939: 'scantron_orig_'.$env{'form.scantron_selectfile'});
5940: my %scanlines;
5941: $scanlines{'orig'}=[(split("\n",$lines,-1))];
5942: my $temp=$scanlines{'orig'};
5943: $scanlines{'count'}=$#$temp;
5944:
5945: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
5946: 'scantron_corrected_'.$env{'form.scantron_selectfile'});
5947: if ($lines eq '-1') {
5948: $scanlines{'corrected'}=[];
5949: } else {
5950: $scanlines{'corrected'}=[(split("\n",$lines,-1))];
5951: }
5952: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
5953: 'scantron_skipped_'.$env{'form.scantron_selectfile'});
5954: if ($lines eq '-1') {
5955: $scanlines{'skipped'}=[];
5956: } else {
5957: $scanlines{'skipped'}=[(split("\n",$lines,-1))];
5958: }
5959: my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
5960: if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
5961: my %scan_data = @tmp;
5962: return (\%scanlines,\%scan_data);
5963: }
5964:
5965: =pod
5966:
5967: =item lonnet_putfile
5968:
5969: Wrapper routine to call &Apache::lonnet::finishuserfileupload
5970:
5971: Arguments:
5972: $contents - data to store
5973: $filename - filename to store $contents into
5974:
5975: Returns:
5976: result value from &Apache::lonnet::finishuserfileupload
5977:
5978: =cut
5979:
5980: sub lonnet_putfile {
5981: my ($contents,$filename)=@_;
5982: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
5983: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5984: $env{'form.sillywaytopassafilearound'}=$contents;
5985: &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
5986:
5987: }
5988:
5989: =pod
5990:
5991: =item scantron_putfile
5992:
5993: Stores the current version of the bubble sheet data files, and the
5994: scan_data hash. (Does not modify the original version only the
5995: corrected and skipped versions.
5996:
5997: Arguments:
5998: $scanlines - hash ref that looks like the first return value from
5999: &scantron_getfile()
6000: $scan_data - hash ref that looks like the second return value from
6001: &scantron_getfile()
6002:
6003: =cut
6004:
6005: sub scantron_putfile {
6006: my ($scanlines,$scan_data) = @_;
6007: #FIXME really would prefer a scantron directory
6008: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6009: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6010: if ($scanlines) {
6011: my $prefix='scantron_';
6012: # no need to update orig, shouldn't change
6013: # &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
6014: # $env{'form.scantron_selectfile'});
6015: &lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
6016: $prefix.'corrected_'.
6017: $env{'form.scantron_selectfile'});
6018: &lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
6019: $prefix.'skipped_'.
6020: $env{'form.scantron_selectfile'});
6021: }
6022: &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
6023: }
6024:
6025: =pod
6026:
6027: =item scantron_get_line
6028:
6029: Returns the correct version of the scanline
6030:
6031: Arguments:
6032: $scanlines - hash ref that looks like the first return value from
6033: &scantron_getfile()
6034: $scan_data - hash ref that looks like the second return value from
6035: &scantron_getfile()
6036: $i - number of the requested line (starts at 0)
6037:
6038: Returns:
6039: A scanline, (either the original or the corrected one if it
6040: exists), or undef if the requested scanline should be
6041: skipped. (Either because it's an skipped scanline, or it's an
6042: unskipped scanline and we are not doing a 'do skipped scanlines'
6043: pass.
6044:
6045: =cut
6046:
6047: sub scantron_get_line {
6048: my ($scanlines,$scan_data,$i)=@_;
6049: if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
6050: #if ($scanlines->{'skipped'}[$i]) { return undef; }
6051: if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
6052: return $scanlines->{'orig'}[$i];
6053: }
6054:
6055: =pod
6056:
6057: =item scantron_todo_count
6058:
6059: Counts the number of scanlines that need processing.
6060:
6061: Arguments:
6062: $scanlines - hash ref that looks like the first return value from
6063: &scantron_getfile()
6064: $scan_data - hash ref that looks like the second return value from
6065: &scantron_getfile()
6066:
6067: Returns:
6068: $count - number of scanlines to process
6069:
6070: =cut
6071:
6072: sub get_todo_count {
6073: my ($scanlines,$scan_data)=@_;
6074: my $count=0;
6075: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6076: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6077: if ($line=~/^[\s\cz]*$/) { next; }
6078: $count++;
6079: }
6080: return $count;
6081: }
6082:
6083: =pod
6084:
6085: =item scantron_put_line
6086:
6087: Updates the 'corrected' or 'skipped' versions of the bubble sheet
6088: data file.
6089:
6090: Arguments:
6091: $scanlines - hash ref that looks like the first return value from
6092: &scantron_getfile()
6093: $scan_data - hash ref that looks like the second return value from
6094: &scantron_getfile()
6095: $i - line number to update
6096: $newline - contents of the updated scanline
6097: $skip - if true make the line for skipping and update the
6098: 'skipped' file
6099:
6100: =cut
6101:
6102: sub scantron_put_line {
6103: my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
6104: if ($skip) {
6105: $scanlines->{'skipped'}[$i]=$newline;
6106: &start_skipping($scan_data,$i);
6107: return;
6108: }
6109: $scanlines->{'corrected'}[$i]=$newline;
6110: }
6111:
6112: =pod
6113:
6114: =item scantron_clear_skip
6115:
6116: Remove a line from the 'skipped' file
6117:
6118: Arguments:
6119: $scanlines - hash ref that looks like the first return value from
6120: &scantron_getfile()
6121: $scan_data - hash ref that looks like the second return value from
6122: &scantron_getfile()
6123: $i - line number to update
6124:
6125: =cut
6126:
6127: sub scantron_clear_skip {
6128: my ($scanlines,$scan_data,$i)=@_;
6129: if (exists($scanlines->{'skipped'}[$i])) {
6130: undef($scanlines->{'skipped'}[$i]);
6131: return 1;
6132: }
6133: return 0;
6134: }
6135:
6136: =pod
6137:
6138: =item scantron_filter_not_exam
6139:
6140: Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
6141: filter out resources that are not marked as 'exam' mode
6142:
6143: =cut
6144:
6145: sub scantron_filter_not_exam {
6146: my ($curres)=@_;
6147:
6148: if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
6149: # if the user has asked to not have either hidden
6150: # or 'randomout' controlled resources to be graded
6151: # don't include them
6152: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
6153: && $curres->randomout) {
6154: return 0;
6155: }
6156: return 1;
6157: }
6158: return 0;
6159: }
6160:
6161: =pod
6162:
6163: =item scantron_validate_sequence
6164:
6165: Validates the selected sequence, checking for resource that are
6166: not set to exam mode.
6167:
6168: =cut
6169:
6170: sub scantron_validate_sequence {
6171: my ($r,$currentphase) = @_;
6172:
6173: my $navmap=Apache::lonnavmaps::navmap->new();
6174: my (undef,undef,$sequence)=
6175: &Apache::lonnet::decode_symb($env{'form.selectpage'});
6176:
6177: my $map=$navmap->getResourceByUrl($sequence);
6178:
6179: $r->print('<input type="hidden" name="validate_sequence_exam"
6180: value="ignore" />');
6181: if ($env{'form.validate_sequence_exam'} ne 'ignore') {
6182: my @resources=
6183: $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
6184: if (@resources) {
6185: $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>");
6186: return (1,$currentphase);
6187: }
6188: }
6189:
6190: return (0,$currentphase+1);
6191: }
6192:
6193: =pod
6194:
6195: =item scantron_validate_ID
6196:
6197: Validates all scanlines in the selected file to not have any
6198: invalid or underspecified student IDs
6199:
6200: =cut
6201:
6202: sub scantron_validate_ID {
6203: my ($r,$currentphase) = @_;
6204:
6205: #get student info
6206: my $classlist=&Apache::loncoursedata::get_classlist();
6207: my %idmap=&username_to_idmap($classlist);
6208:
6209: #get scantron line setup
6210: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6211: my ($scanlines,$scan_data)=&scantron_getfile();
6212:
6213: &scantron_get_maxbubble(); # parse needs the bubble_lines.. array.
6214:
6215: my %found=('ids'=>{},'usernames'=>{});
6216: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6217: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6218: if ($line=~/^[\s\cz]*$/) { next; }
6219: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6220: $scan_data);
6221: my $id=$$scan_record{'scantron.ID'};
6222: my $found;
6223: foreach my $checkid (keys(%idmap)) {
6224: if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
6225: }
6226: if ($found) {
6227: my $username=$idmap{$found};
6228: if ($found{'ids'}{$found}) {
6229: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6230: $line,'duplicateID',$found);
6231: return(1,$currentphase);
6232: } elsif ($found{'usernames'}{$username}) {
6233: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6234: $line,'duplicateID',$username);
6235: return(1,$currentphase);
6236: }
6237: #FIXME store away line we previously saw the ID on to use above
6238: $found{'ids'}{$found}++;
6239: $found{'usernames'}{$username}++;
6240: } else {
6241: if ($id =~ /^\s*$/) {
6242: my $username=&scan_data($scan_data,"$i.user");
6243: if (defined($username) && $found{'usernames'}{$username}) {
6244: &scantron_get_correction($r,$i,$scan_record,
6245: \%scantron_config,
6246: $line,'duplicateID',$username);
6247: return(1,$currentphase);
6248: } elsif (!defined($username)) {
6249: &scantron_get_correction($r,$i,$scan_record,
6250: \%scantron_config,
6251: $line,'incorrectID');
6252: return(1,$currentphase);
6253: }
6254: $found{'usernames'}{$username}++;
6255: } else {
6256: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6257: $line,'incorrectID');
6258: return(1,$currentphase);
6259: }
6260: }
6261: }
6262:
6263: return (0,$currentphase+1);
6264: }
6265:
6266: =pod
6267:
6268: =item scantron_get_correction
6269:
6270: Builds the interface screen to interact with the operator to fix a
6271: specific error condition in a specific scanline
6272:
6273: Arguments:
6274: $r - Apache request object
6275: $i - number of the current scanline
6276: $scan_record - hash ref as returned from &scantron_parse_scanline()
6277: $scan_config - hash ref as returned from &get_scantron_config()
6278: $line - full contents of the current scanline
6279: $error - error condition, valid values are
6280: 'incorrectCODE', 'duplicateCODE',
6281: 'doublebubble', 'missingbubble',
6282: 'duplicateID', 'incorrectID'
6283: $arg - extra information needed
6284: For errors:
6285: - duplicateID - paper number that this studentID was seen before on
6286: - duplicateCODE - array ref of the paper numbers this CODE was
6287: seen on before
6288: - incorrectCODE - current incorrect CODE
6289: - doublebubble - array ref of the bubble lines that have double
6290: bubble errors
6291: - missingbubble - array ref of the bubble lines that have missing
6292: bubble errors
6293:
6294: =cut
6295:
6296: sub scantron_get_correction {
6297: my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
6298:
6299: #FIXME in the case of a duplicated ID the previous line, probaly need
6300: #to show both the current line and the previous one and allow skipping
6301: #the previous one or the current one
6302:
6303: $r->print("<p><b>An error was detected ($error)</b>");
6304: if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
6305: $r->print(" for PaperID <tt>".
6306: $$scan_record{'scantron.PaperID'}."</tt> \n");
6307: } else {
6308: $r->print(" in scanline $i <pre>".
6309: $line."</pre> \n");
6310: }
6311: my $message="<p>The ID on the form is <tt>".
6312: $$scan_record{'scantron.ID'}."</tt><br />\n".
6313: "The name on the paper is ".
6314: $$scan_record{'scantron.LastName'}.",".
6315: $$scan_record{'scantron.FirstName'}."</p>";
6316:
6317: $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
6318: $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
6319: if ($error =~ /ID$/) {
6320: if ($error eq 'incorrectID') {
6321: $r->print("The encoded ID is not in the classlist</p>\n");
6322: } elsif ($error eq 'duplicateID') {
6323: $r->print("The encoded ID has also been used by a previous paper $arg</p>\n");
6324: }
6325: $r->print($message);
6326: $r->print("<p>How should I handle this? <br /> \n");
6327: $r->print("\n<ul><li> ");
6328: #FIXME it would be nice if this sent back the user ID and
6329: #could do partial userID matches
6330: $r->print(&Apache::loncommon::selectstudent_link('scantronupload',
6331: 'scantron_username','scantron_domain'));
6332: $r->print(": <input type='text' name='scantron_username' value='' />");
6333: $r->print("\n@".
6334: &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
6335:
6336: $r->print('</li>');
6337: } elsif ($error =~ /CODE$/) {
6338: if ($error eq 'incorrectCODE') {
6339: $r->print("</p><p>The encoded CODE is not in the list of possible CODEs</p>\n");
6340: } elsif ($error eq 'duplicateCODE') {
6341: $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");
6342: }
6343: $r->print("<p>The CODE on the form is <tt>'".
6344: $$scan_record{'scantron.CODE'}."'</tt><br />\n");
6345: $r->print($message);
6346: $r->print("<p>How should I handle this? <br /> \n");
6347: $r->print("\n<br /> ");
6348: my $i=0;
6349: if ($error eq 'incorrectCODE'
6350: && $$scan_record{'scantron.CODE'}=~/\S/ ) {
6351: my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
6352: if ($closest > 0) {
6353: foreach my $testcode (@{$closest}) {
6354: my $checked='';
6355: if (!$i) { $checked=' checked="checked" '; }
6356: $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' />");
6357: $r->print("\n<br />");
6358: $i++;
6359: }
6360: }
6361: }
6362: if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
6363: my $checked; if (!$i) { $checked=' checked="checked" '; }
6364: $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>");
6365: $r->print("\n<br />");
6366: }
6367:
6368: $r->print(<<ENDSCRIPT);
6369: <script type="text/javascript">
6370: function change_radio(field) {
6371: var slct=document.scantronupload.scantron_CODE_resolution;
6372: var i;
6373: for (i=0;i<slct.length;i++) {
6374: if (slct[i].value==field) { slct[i].checked=true; }
6375: }
6376: }
6377: </script>
6378: ENDSCRIPT
6379: my $href="/adm/pickcode?".
6380: "form=".&escape("scantronupload").
6381: "&scantron_format=".&escape($env{'form.scantron_format'}).
6382: "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
6383: "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
6384: "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
6385: if ($env{'form.scantron_CODElist'} =~ /\S/) {
6386: $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')\" />");
6387: $r->print("\n<br />");
6388: }
6389: $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.");
6390: $r->print("\n<br /><br />");
6391: } elsif ($error eq 'doublebubble') {
6392: $r->print("<p>There have been multiple bubbles scanned for a some question(s)</p>\n");
6393: $r->print('<input type="hidden" name="scantron_questions" value="'.
6394: join(',',@{$arg}).'" />');
6395: $r->print($message);
6396: $r->print("<p>Please indicate which bubble should be used for grading</p>");
6397: foreach my $question (@{$arg}) {
6398:
6399: my $selected = &get_response_bubbles($scan_record, $question);
6400: &scantron_bubble_selector($r,$scan_config,$question,
6401: split('',$selected));
6402: }
6403: } elsif ($error eq 'missingbubble') {
6404: $r->print("<p>There have been <b>no</b> bubbles scanned for some question(s)</p>\n");
6405: $r->print($message);
6406: $r->print("<p>Please indicate which bubble should be used for grading</p>");
6407: $r->print("Some questions have no scanned bubbles\n");
6408: $r->print('<input type="hidden" name="scantron_questions" value="'.
6409: join(',',@{$arg}).'" />');
6410: foreach my $question (@{$arg}) {
6411: my $selected = &get_response_bubbles($scan_record, $question);
6412: &scantron_bubble_selector($r,$scan_config,$question);
6413: }
6414: } else {
6415: $r->print("\n<ul>");
6416: }
6417: $r->print("\n</li></ul>");
6418:
6419: }
6420:
6421: =pod
6422:
6423: =item scantron_bubble_selector
6424:
6425: Generates the html radiobuttons to correct a single bubble line
6426: possibly showing the existing the selected bubbles if known
6427:
6428: Arguments:
6429: $r - Apache request object
6430: $scan_config - hash from &get_scantron_config()
6431: $quest - number of the bubble line to make a corrector for
6432: $selected - array of letters of previously selected bubbles
6433:
6434: =cut
6435:
6436: sub scantron_bubble_selector {
6437: my ($r,$scan_config,$quest,@selected)=@_;
6438: my $max=$$scan_config{'Qlength'};
6439:
6440: my $scmode=$$scan_config{'Qon'};
6441:
6442:
6443: if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }
6444:
6445: my $response = $quest-1;
6446: my $lines = $bubble_lines_per_response{$response};
6447: &Apache::lonnet::logthis("Question $quest, lines: $lines");
6448:
6449: my $total_lines = $lines*2;
6450: my @alphabet=('A'..'Z');
6451: $r->print("<table border='1'><tr><td rowspan='".$total_lines."'>$quest</td>");
6452:
6453: for (my $l = 0; $l < $lines; $l++) {
6454: if ($l != 0) {
6455: $r->print('<tr>');
6456: }
6457:
6458: # FIXME: This loop probably has to be considerably more clever for
6459: # multiline bubbles: User can multibubble by having bubbles in
6460: # several lines. User can skip lines legitimately etc. etc.
6461:
6462: for (my $i=0;$i<$max;$i++) {
6463: $r->print("\n".'<td align="center">');
6464: if ($selected[0] eq $alphabet[$i]) {
6465: $r->print('X');
6466: shift(@selected) ;
6467: } else {
6468: $r->print(' ');
6469: }
6470: $r->print('</td>');
6471:
6472: }
6473:
6474: if ($l == 0) {
6475: my $lspan = $total_lines * 2; # 2 table rows per bubble line.
6476:
6477: $r->print('<td rowspan='.$lspan.'><label><input type="radio" name="scantron_correct_Q_'.
6478: $quest.'" value="none" /> No bubble </label></td>');
6479:
6480: }
6481:
6482: $r->print('</tr><tr>');
6483:
6484: # FIXME: This may have to be a bit more clever for
6485: # multiline questions (different values e.g..).
6486:
6487: for (my $i=0;$i<$max;$i++) {
6488: $r->print("\n".
6489: '<td><label><input type="radio" name="scantron_correct_Q_'.
6490: $quest.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
6491: }
6492: $r->print('</tr>');
6493:
6494:
6495: }
6496: $r->print('</table>');
6497: }
6498:
6499: =pod
6500:
6501: =item num_matches
6502:
6503: Counts the number of characters that are the same between the two arguments.
6504:
6505: Arguments:
6506: $orig - CODE from the scanline
6507: $code - CODE to match against
6508:
6509: Returns:
6510: $count - integer count of the number of same characters between the
6511: two arguments
6512:
6513: =cut
6514:
6515: sub num_matches {
6516: my ($orig,$code) = @_;
6517: my @code=split(//,$code);
6518: my @orig=split(//,$orig);
6519: my $same=0;
6520: for (my $i=0;$i<scalar(@code);$i++) {
6521: if ($code[$i] eq $orig[$i]) { $same++; }
6522: }
6523: return $same;
6524: }
6525:
6526: =pod
6527:
6528: =item scantron_get_closely_matching_CODEs
6529:
6530: Cycles through all CODEs and finds the set that has the greatest
6531: number of same characters as the provided CODE
6532:
6533: Arguments:
6534: $allcodes - hash ref returned by &get_codes()
6535: $CODE - CODE from the current scanline
6536:
6537: Returns:
6538: 2 element list
6539: - first elements is number of how closely matching the best fit is
6540: (5 means best set has 5 matching characters)
6541: - second element is an arrary ref containing the set of valid CODEs
6542: that best fit the passed in CODE
6543:
6544: =cut
6545:
6546: sub scantron_get_closely_matching_CODEs {
6547: my ($allcodes,$CODE)=@_;
6548: my @CODEs;
6549: foreach my $testcode (sort(keys(%{$allcodes}))) {
6550: push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
6551: }
6552:
6553: return ($#CODEs,$CODEs[-1]);
6554: }
6555:
6556: =pod
6557:
6558: =item get_codes
6559:
6560: Builds a hash which has keys of all of the valid CODEs from the selected
6561: set of remembered CODEs.
6562:
6563: Arguments:
6564: $old_name - name of the set of remembered CODEs
6565: $cdom - domain of the course
6566: $cnum - internal course name
6567:
6568: Returns:
6569: %allcodes - keys are the valid CODEs, values are all 1
6570:
6571: =cut
6572:
6573: sub get_codes {
6574: my ($old_name, $cdom, $cnum) = @_;
6575: if (!$old_name) {
6576: $old_name=$env{'form.scantron_CODElist'};
6577: }
6578: if (!$cdom) {
6579: $cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
6580: }
6581: if (!$cnum) {
6582: $cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
6583: }
6584: my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
6585: $cdom,$cnum);
6586: my %allcodes;
6587: if ($result{"type\0$old_name"} eq 'number') {
6588: %allcodes=map {($_,1)} split(',',$result{$old_name});
6589: } else {
6590: %allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
6591: }
6592: return %allcodes;
6593: }
6594:
6595: =pod
6596:
6597: =item scantron_validate_CODE
6598:
6599: Validates all scanlines in the selected file to not have any
6600: invalid or underspecified CODEs and that none of the codes are
6601: duplicated if this was requested.
6602:
6603: =cut
6604:
6605: sub scantron_validate_CODE {
6606: my ($r,$currentphase) = @_;
6607: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6608: if ($scantron_config{'CODElocation'} &&
6609: $scantron_config{'CODEstart'} &&
6610: $scantron_config{'CODElength'}) {
6611: if (!defined($env{'form.scantron_CODElist'})) {
6612: &FIXME_blow_up()
6613: }
6614: } else {
6615: return (0,$currentphase+1);
6616: }
6617:
6618: my %usedCODEs;
6619:
6620: my %allcodes=&get_codes();
6621:
6622: &scantron_get_maxbubble(); # parse needs the lines per response array.
6623:
6624: my ($scanlines,$scan_data)=&scantron_getfile();
6625: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6626: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6627: if ($line=~/^[\s\cz]*$/) { next; }
6628: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6629: $scan_data);
6630: my $CODE=$$scan_record{'scantron.CODE'};
6631: my $error=0;
6632: if (!&Apache::lonnet::validCODE($CODE)) {
6633: &scantron_get_correction($r,$i,$scan_record,
6634: \%scantron_config,
6635: $line,'incorrectCODE',\%allcodes);
6636: return(1,$currentphase);
6637: }
6638: if (%allcodes && !exists($allcodes{$CODE})
6639: && !$$scan_record{'scantron.useCODE'}) {
6640: &scantron_get_correction($r,$i,$scan_record,
6641: \%scantron_config,
6642: $line,'incorrectCODE',\%allcodes);
6643: return(1,$currentphase);
6644: }
6645: if (exists($usedCODEs{$CODE})
6646: && $env{'form.scantron_CODEunique'} eq 'yes'
6647: && !$$scan_record{'scantron.CODE_ignore_dup'}) {
6648: &scantron_get_correction($r,$i,$scan_record,
6649: \%scantron_config,
6650: $line,'duplicateCODE',$usedCODEs{$CODE});
6651: return(1,$currentphase);
6652: }
6653: push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
6654: }
6655: return (0,$currentphase+1);
6656: }
6657:
6658: =pod
6659:
6660: =item scantron_validate_doublebubble
6661:
6662: Validates all scanlines in the selected file to not have any
6663: bubble lines with multiple bubbles marked.
6664:
6665: =cut
6666:
6667: sub scantron_validate_doublebubble {
6668: my ($r,$currentphase) = @_;
6669: #get student info
6670: my $classlist=&Apache::loncoursedata::get_classlist();
6671: my %idmap=&username_to_idmap($classlist);
6672:
6673: #get scantron line setup
6674: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6675: my ($scanlines,$scan_data)=&scantron_getfile();
6676:
6677: &scantron_get_maxbubble(); # parse needs the bubble line array.
6678:
6679: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6680: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6681: if ($line=~/^[\s\cz]*$/) { next; }
6682: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6683: $scan_data);
6684: if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
6685: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
6686: 'doublebubble',
6687: $$scan_record{'scantron.doubleerror'});
6688: return (1,$currentphase);
6689: }
6690: return (0,$currentphase+1);
6691: }
6692:
6693: =pod
6694:
6695: =item scantron_get_maxbubble
6696:
6697: Returns the maximum number of bubble lines that are expected to
6698: occur. Does this by walking the selected sequence rendering the
6699: resource and then checking &Apache::lonxml::get_problem_counter()
6700: for what the current value of the problem counter is.
6701:
6702: Caches the results to $env{'form.scantron_maxbubble'},
6703: $env{'form.scantron.bubble_lines.n'} and
6704: $env{'form.scantron.first_bubble_line.n'}
6705: which are the total number of bubble, lines, the number of bubble
6706: lines for reponse n and number of the first bubble line for response n.
6707:
6708: =cut
6709:
6710: sub scantron_get_maxbubble {
6711: &Apache::lonnet::logthis("get_max_bubble");
6712: if (defined($env{'form.scantron_maxbubble'}) &&
6713: $env{'form.scantron_maxbubble'}) {
6714: &Apache::lonnet::logthis("cached");
6715: &restore_bubble_lines();
6716: return $env{'form.scantron_maxbubble'};
6717: }
6718: &Apache::lonnet::logthis("computing");
6719:
6720: my (undef, undef, $sequence) =
6721: &Apache::lonnet::decode_symb($env{'form.selectpage'});
6722:
6723: my $navmap=Apache::lonnavmaps::navmap->new();
6724: my $map=$navmap->getResourceByUrl($sequence);
6725: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
6726:
6727: &Apache::lonxml::clear_problem_counter();
6728:
6729: my $uname = $env{'form.student'};
6730: my $udom = $env{'form.userdom'};
6731: my $cid = $env{'request.course.id'};
6732: my $total_lines = 0;
6733: %bubble_lines_per_response = ();
6734: %first_bubble_line = ();
6735:
6736:
6737: my $response_number = 0;
6738: my $bubble_line = 0;
6739: foreach my $resource (@resources) {
6740: my $symb = $resource->symb();
6741: &Apache::lonxml::clear_bubble_lines_for_part();
6742: my $result=&Apache::lonnet::ssi($resource->src(),
6743: ('symb' => $resource->symb()),
6744: ('grade_target' => 'analyze'),
6745: ('grade_courseid' => $cid),
6746: ('grade_domain' => $udom),
6747: ('grade_username' => $uname));
6748: my (undef, $an) =
6749: split(/_HASH_REF__/,$result, 2);
6750:
6751: my %analysis = &Apache::lonnet::str2hash($an);
6752:
6753:
6754:
6755: foreach my $part_id (@{$analysis{'parts'}}) {
6756: my ($trash, $part) = split(/\./, $part_id);
6757:
6758: my $lines = $analysis{"$part_id.bubble_lines"}[0];
6759:
6760: # TODO - make this a persistent hash not an array.
6761:
6762:
6763: $first_bubble_line{$response_number} = $bubble_line;
6764: $bubble_lines_per_response{$response_number} = $lines;
6765: $response_number++;
6766:
6767: $bubble_line += $lines;
6768: $total_lines += $lines;
6769: }
6770:
6771: }
6772: &Apache::lonnet::delenv('scantron\.');
6773:
6774: &save_bubble_lines();
6775: $env{'form.scantron_maxbubble'} =
6776: $total_lines;
6777: return $env{'form.scantron_maxbubble'};
6778: }
6779:
6780: =pod
6781:
6782: =item scantron_validate_missingbubbles
6783:
6784: Validates all scanlines in the selected file to not have any
6785: answers that don't have bubbles that have not been verified
6786: to be bubble free.
6787:
6788: =cut
6789:
6790: sub scantron_validate_missingbubbles {
6791: my ($r,$currentphase) = @_;
6792: #get student info
6793: my $classlist=&Apache::loncoursedata::get_classlist();
6794: my %idmap=&username_to_idmap($classlist);
6795:
6796: #get scantron line setup
6797: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6798: my ($scanlines,$scan_data)=&scantron_getfile();
6799: my $max_bubble=&scantron_get_maxbubble();
6800: if (!$max_bubble) { $max_bubble=2**31; }
6801: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6802: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6803: if ($line=~/^[\s\cz]*$/) { next; }
6804: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6805: $scan_data);
6806: if (!defined($$scan_record{'scantron.missingerror'})) { next; }
6807: my @to_correct;
6808: foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
6809: if ($missing > $max_bubble) { next; }
6810: push(@to_correct,$missing);
6811: }
6812: if (@to_correct) {
6813: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6814: $line,'missingbubble',\@to_correct);
6815: return (1,$currentphase);
6816: }
6817:
6818: }
6819: return (0,$currentphase+1);
6820: }
6821:
6822: =pod
6823:
6824: =item scantron_process_students
6825:
6826: Routine that does the actual grading of the bubble sheet information.
6827:
6828: The parsed scanline hash is added to %env
6829:
6830: Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
6831: foreach resource , with the form data of
6832:
6833: 'submitted' =>'scantron'
6834: 'grade_target' =>'grade',
6835: 'grade_username'=> username of student
6836: 'grade_domain' => domain of student
6837: 'grade_courseid'=> of course
6838: 'grade_symb' => symb of resource to grade
6839:
6840: This triggers a grading pass. The problem grading code takes care
6841: of converting the bubbled letter information (now in %env) into a
6842: valid submission.
6843:
6844: =cut
6845:
6846: sub scantron_process_students {
6847: my ($r) = @_;
6848: my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
6849: my ($symb)=&get_symb($r);
6850: if (!$symb) {return '';}
6851: my $default_form_data=&defaultFormData($symb);
6852:
6853: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6854: my ($scanlines,$scan_data)=&scantron_getfile();
6855: my $classlist=&Apache::loncoursedata::get_classlist();
6856: my %idmap=&username_to_idmap($classlist);
6857: my $navmap=Apache::lonnavmaps::navmap->new();
6858: my $map=$navmap->getResourceByUrl($sequence);
6859: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
6860: # $r->print("geto ".scalar(@resources)."<br />");
6861: my $result= <<SCANTRONFORM;
6862: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
6863: <input type="hidden" name="command" value="scantron_configphase" />
6864: $default_form_data
6865: SCANTRONFORM
6866: $r->print($result);
6867:
6868: my @delayqueue;
6869: my %completedstudents;
6870:
6871: my $count=&get_todo_count($scanlines,$scan_data);
6872: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
6873: 'Scantron Progress',$count,
6874: 'inline',undef,'scantronupload');
6875: &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
6876: 'Processing first student');
6877: my $start=&Time::HiRes::time();
6878: my $i=-1;
6879: my ($uname,$udom,$started);
6880:
6881: &scantron_get_maxbubble(); # Need the bubble lines array to parse.
6882:
6883: while ($i<$scanlines->{'count'}) {
6884: ($uname,$udom)=('','');
6885: $i++;
6886: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6887: if ($line=~/^[\s\cz]*$/) { next; }
6888: if ($started) {
6889: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
6890: 'last student');
6891: }
6892: $started=1;
6893: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6894: $scan_data);
6895: unless ($uname=&scantron_find_student($scan_record,$scan_data,
6896: \%idmap,$i)) {
6897: &scantron_add_delay(\@delayqueue,$line,
6898: 'Unable to find a student that matches',1);
6899: next;
6900: }
6901: if (exists $completedstudents{$uname}) {
6902: &scantron_add_delay(\@delayqueue,$line,
6903: 'Student '.$uname.' has multiple sheets',2);
6904: next;
6905: }
6906: ($uname,$udom)=split(/:/,$uname);
6907:
6908: &Apache::lonxml::clear_problem_counter();
6909: &Apache::lonnet::appenv(%$scan_record);
6910:
6911: if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
6912: &scantron_putfile($scanlines,$scan_data);
6913: }
6914:
6915: my $i=0;
6916: foreach my $resource (@resources) {
6917: $i++;
6918: my %form=('submitted' =>'scantron',
6919: 'grade_target' =>'grade',
6920: 'grade_username'=>$uname,
6921: 'grade_domain' =>$udom,
6922: 'grade_courseid'=>$env{'request.course.id'},
6923: 'grade_symb' =>$resource->symb());
6924: if (exists($scan_record->{'scantron.CODE'})
6925: &&
6926: &Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
6927: $form{'CODE'}=$scan_record->{'scantron.CODE'};
6928: } else {
6929: $form{'CODE'}='';
6930: }
6931: my $result=&Apache::lonnet::ssi($resource->src(),%form);
6932: if ($result ne '') {
6933: }
6934: if (&Apache::loncommon::connection_aborted($r)) { last; }
6935: }
6936: $completedstudents{$uname}={'line'=>$line};
6937: if (&Apache::loncommon::connection_aborted($r)) { last; }
6938: } continue {
6939: &Apache::lonxml::clear_problem_counter();
6940: &Apache::lonnet::delenv('scantron\.');
6941: }
6942: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
6943: # my $lasttime = &Time::HiRes::time()-$start;
6944: # $r->print("<p>took $lasttime</p>");
6945:
6946: $r->print("</form>");
6947: $r->print(&show_grading_menu_form($symb));
6948: return '';
6949: }
6950:
6951: =pod
6952:
6953: =item scantron_upload_scantron_data
6954:
6955: Creates the screen for adding a new bubble sheet data file to a course.
6956:
6957: =cut
6958:
6959: sub scantron_upload_scantron_data {
6960: my ($r)=@_;
6961: $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
6962: my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
6963: 'domainid',
6964: 'coursename');
6965: my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
6966: 'domainid');
6967: my $default_form_data=&defaultFormData(&get_symb($r,1));
6968: $r->print(<<UPLOAD);
6969: <script type="text/javascript" language="javascript">
6970: function checkUpload(formname) {
6971: if (formname.upfile.value == "") {
6972: alert("Please use the browse button to select a file from your local directory.");
6973: return false;
6974: }
6975: formname.submit();
6976: }
6977: </script>
6978:
6979: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
6980: $default_form_data
6981: <table>
6982: <tr><td>$select_link </td></tr>
6983: <tr><td>Course ID: </td><td><input name='courseid' type='text' /> </td></tr>
6984: <tr><td>Course Name: </td><td><input name='coursename' type='text' /></td></tr>
6985: <tr><td>Domain: </td><td>$domsel </td></tr>
6986: <tr><td>File to upload:</td><td><input type="file" name="upfile" size="50" /></td></tr>
6987: </table>
6988: <input name='command' value='scantronupload_save' type='hidden' />
6989: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
6990: </form>
6991: UPLOAD
6992: return '';
6993: }
6994:
6995: =pod
6996:
6997: =item scantron_upload_scantron_data_save
6998:
6999: Adds a provided bubble information data file to the course if user
7000: has the correct privileges to do so.
7001:
7002: =cut
7003:
7004: sub scantron_upload_scantron_data_save {
7005: my($r)=@_;
7006: my ($symb)=&get_symb($r,1);
7007: my $doanotherupload=
7008: '<br /><form action="/adm/grades" method="post">'."\n".
7009: '<input type="hidden" name="command" value="scantronupload" />'."\n".
7010: '<input type="submit" name="submit" value="Do Another Upload" />'."\n".
7011: '</form>'."\n";
7012: if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
7013: !&Apache::lonnet::allowed('usc',
7014: $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
7015: $r->print("You are not allowed to upload Scantron data to the requested course.<br />");
7016: if ($symb) {
7017: $r->print(&show_grading_menu_form($symb));
7018: } else {
7019: $r->print($doanotherupload);
7020: }
7021: return '';
7022: }
7023: my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
7024: $r->print("Doing upload to ".$coursedata{'description'}." <br />");
7025: my $fname=$env{'form.upfile.filename'};
7026: #FIXME
7027: #copied from lonnet::userfileupload()
7028: #make that function able to target a specified course
7029: # Replace Windows backslashes by forward slashes
7030: $fname=~s/\\/\//g;
7031: # Get rid of everything but the actual filename
7032: $fname=~s/^.*\/([^\/]+)$/$1/;
7033: # Replace spaces by underscores
7034: $fname=~s/\s+/\_/g;
7035: # Replace all other weird characters by nothing
7036: $fname=~s/[^\w\.\-]//g;
7037: # See if there is anything left
7038: unless ($fname) { return 'error: no uploaded file'; }
7039: my $uploadedfile=$fname;
7040: $fname='scantron_orig_'.$fname;
7041: if (length($env{'form.upfile'}) < 2) {
7042: $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.");
7043: } else {
7044: my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
7045: if ($result =~ m|^/uploaded/|) {
7046: $r->print("<span class=\"LC_success\">Success:</span> Successfully uploaded ".(length($env{'form.upfile'})-1)." bytes of data into location <tt>".$result."</tt>");
7047: } else {
7048: $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>");
7049: }
7050: }
7051: if ($symb) {
7052: $r->print(&scantron_selectphase($r,$uploadedfile));
7053: } else {
7054: $r->print($doanotherupload);
7055: }
7056: return '';
7057: }
7058:
7059: =pod
7060:
7061: =item valid_file
7062:
7063: Validates that the requested bubble data file exists in the course.
7064:
7065: =cut
7066:
7067: sub valid_file {
7068: my ($requested_file)=@_;
7069: foreach my $filename (sort(&scantron_filenames())) {
7070: if ($requested_file eq $filename) { return 1; }
7071: }
7072: return 0;
7073: }
7074:
7075: =pod
7076:
7077: =item scantron_download_scantron_data
7078:
7079: Shows a list of the three internal files (original, corrected,
7080: skipped) for a specific bubble sheet data file that exists in the
7081: course.
7082:
7083: =cut
7084:
7085: sub scantron_download_scantron_data {
7086: my ($r)=@_;
7087: my $default_form_data=&defaultFormData(&get_symb($r,1));
7088: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7089: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7090: my $file=$env{'form.scantron_selectfile'};
7091: if (! &valid_file($file)) {
7092: $r->print(<<ERROR);
7093: <p>
7094: The requested file name was invalid.
7095: </p>
7096: ERROR
7097: $r->print(&show_grading_menu_form(&get_symb($r,1)));
7098: return;
7099: }
7100: my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
7101: my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
7102: my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
7103: &Apache::lonnet::allowuploaded('/adm/grades',$orig);
7104: &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
7105: &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
7106: $r->print(<<DOWNLOAD);
7107: <p>
7108: <a href="$orig">Original</a> file as uploaded by the scantron office.
7109: </p>
7110: <p>
7111: <a href="$corrected">Corrections</a>, a file of corrected records that were used in grading.
7112: </p>
7113: <p>
7114: <a href="$skipped">Skipped</a>, a file of records that were skipped.
7115: </p>
7116: DOWNLOAD
7117: $r->print(&show_grading_menu_form(&get_symb($r,1)));
7118: return '';
7119: }
7120:
7121: =pod
7122:
7123: =back
7124:
7125: =cut
7126:
7127: #-------- end of section for handling grading scantron forms -------
7128: #
7129: #-------------------------------------------------------------------
7130:
7131: #-------------------------- Menu interface -------------------------
7132: #
7133: #--- Show a Grading Menu button - Calls the next routine ---
7134: sub show_grading_menu_form {
7135: my ($symb)=@_;
7136: my $result.='<br /><form action="/adm/grades" method="post">'."\n".
7137: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
7138: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
7139: '<input type="hidden" name="command" value="gradingmenu" />'."\n".
7140: '<input type="submit" name="submit" value="Grading Menu" />'."\n".
7141: '</form>'."\n";
7142: return $result;
7143: }
7144:
7145: # -- Retrieve choices for grading form
7146: sub savedState {
7147: my %savedState = ();
7148: if ($env{'form.saveState'}) {
7149: foreach (split(/:/,$env{'form.saveState'})) {
7150: my ($key,$value) = split(/=/,$_,2);
7151: $savedState{$key} = $value;
7152: }
7153: }
7154: return \%savedState;
7155: }
7156:
7157: sub grading_menu {
7158: my ($request) = @_;
7159: my ($symb)=&get_symb($request);
7160: if (!$symb) {return '';}
7161: my $probTitle = &Apache::lonnet::gettitle($symb);
7162: my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
7163:
7164: #
7165: # Define menu data
7166: $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
7167: my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
7168: $request->print($table);
7169: my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
7170: 'handgrade'=>$hdgrade,
7171: 'probTitle'=>$probTitle,
7172: 'command'=>'submit_options',
7173: 'saveState'=>"",
7174: 'gradingMenu'=>1,
7175: 'showgrading'=>"yes");
7176: my $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
7177: my @menu = ({ url => $url,
7178: name => &mt('Manual Grading/View Submissions'),
7179: short_description =>
7180: &mt('Start the process of hand grading submissions.'),
7181: });
7182: $fields{'command'} = 'csvform';
7183: $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
7184: push (@menu, { url => $url,
7185: name => &mt('Upload Scores'),
7186: short_description =>
7187: &mt('Specify a file containing the class scores for current resource.')});
7188: $fields{'command'} = 'processclicker';
7189: $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
7190: push (@menu, { url => $url,
7191: name => &mt('Process Clicker'),
7192: short_description =>
7193: &mt('Specify a file containing the clicker information for this resource.')});
7194: $fields{'command'} = 'scantron_selectphase';
7195: $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
7196: push (@menu, { url => $url,
7197: name => &mt('Grade Scantron Forms'),
7198: short_description =>
7199: &mt('')});
7200: $fields{'command'} = 'verify';
7201: $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
7202: push (@menu, { url => "",
7203: jscript => ' onClick="javascript:checkChoice2(document.forms.gradingMenu,\'5\',\'verify\')" ',
7204: name => &mt('Verify Receipt'),
7205: short_description =>
7206: &mt('')});
7207: $fields{'command'} = 'manage';
7208: $url = &Apache::lonhtmlcommon::build_url('/adm/helper/resettimes.helper',\%fields);
7209: push (@menu, { url => $url,
7210: name => &mt('Manage Access Times'),
7211: short_description =>
7212: &mt('')});
7213: $fields{'command'} = 'view';
7214: $url = &Apache::lonhtmlcommon::build_url('/adm/pickcode',\%fields);
7215: push (@menu, { url => $url,
7216: name => &mt('View Saved CODEs'),
7217: short_description =>
7218: &mt('')});
7219:
7220: #
7221: # Create the menu
7222: my $Str;
7223: # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
7224: $Str .= '<form method="post" action="" name="gradingMenu">';
7225: $Str .= '<input type="hidden" name="command" value="" />'.
7226: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
7227: '<input type="hidden" name="handgrade" value="'.$hdgrade.'" />'."\n".
7228: '<input type="hidden" name="probTitle" value="'.$probTitle.'" ue="" />'."\n".
7229: '<input type="hidden" name="saveState" value="" />'."\n".
7230: '<input type="hidden" name="gradingMenu" value="1" />'."\n".
7231: '<input type="hidden" name="showgrading" value="yes" />'."\n";
7232:
7233: foreach my $menudata (@menu) {
7234: if ($menudata->{'name'} ne &mt('Verify Receipt')) {
7235: $Str .=' <h3><a '.
7236: $menudata->{'jscript'}.
7237: ' href="'.
7238: $menudata->{'url'}.'" >'.
7239: $menudata->{'name'}."</a></h3>\n";
7240: } else {
7241: $Str .=' <h3><a '.
7242: $menudata->{'jscript'}.
7243: ' href="javascript:checkChoice2(document.forms.gradingMenu,\'5\',\'verify\')" >'.
7244: $menudata->{'name'}."</a></h3>\n";
7245: $Str .= (' 'x8).
7246: ' receipt: '.&Apache::lonnet::recprefix($env{'request.course.id'}).
7247: '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
7248: }
7249: $Str .= ' '.(' 'x8).$menudata->{'short_description'}.
7250: "\n";
7251: }
7252: $Str .="</dl>\n";
7253: $Str .="</form>\n";
7254: $request->print(<<GRADINGMENUJS);
7255: <script type="text/javascript" language="javascript">
7256: function checkChoice(formname,val,cmdx) {
7257: if (val <= 2) {
7258: var cmd = radioSelection(formname.radioChoice);
7259: var cmdsave = cmd;
7260: } else {
7261: cmd = cmdx;
7262: cmdsave = 'submission';
7263: }
7264: formname.command.value = cmd;
7265: formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
7266: ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
7267: if (val < 5) formname.submit();
7268: if (val == 5) {
7269: if (!checkReceiptNo(formname,'notOK')) { return false;}
7270: formname.submit();
7271: }
7272: if (val < 7) formname.submit();
7273: }
7274: function checkChoice2(formname,val,cmdx) {
7275: if (val <= 2) {
7276: var cmd = radioSelection(formname.radioChoice);
7277: var cmdsave = cmd;
7278: } else {
7279: cmd = cmdx;
7280: cmdsave = 'submission';
7281: }
7282: formname.command.value = cmd;
7283: if (val < 5) formname.submit();
7284: if (val == 5) {
7285: if (!checkReceiptNo(formname,'notOK')) { return false;}
7286: formname.submit();
7287: }
7288: if (val < 7) formname.submit();
7289: }
7290:
7291: function checkReceiptNo(formname,nospace) {
7292: var receiptNo = formname.receipt.value;
7293: var checkOpt = false;
7294: if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
7295: if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
7296: if (checkOpt) {
7297: alert("Please enter a receipt number given by a student in the receipt box.");
7298: formname.receipt.value = "";
7299: formname.receipt.focus();
7300: return false;
7301: }
7302: return true;
7303: }
7304: </script>
7305: GRADINGMENUJS
7306: &commonJSfunctions($request);
7307: my $result='<h3> <span class="LC_info">Manual Grading/View Submission</span></h3>';
7308: $result.=$table;
7309: my (undef,$sections) = &getclasslist('all','0');
7310: my $savedState = &savedState();
7311: my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
7312: my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
7313: my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
7314: my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
7315:
7316: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
7317: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
7318: '<input type="hidden" name="handgrade" value="'.$hdgrade.'" />'."\n".
7319: '<input type="hidden" name="probTitle" value="'.$probTitle.'" ue="" />'."\n".
7320: '<input type="hidden" name="saveState" value="" />'."\n".
7321: '<input type="hidden" name="gradingMenu" value="1" />'."\n".
7322: '<input type="hidden" name="showgrading" value="yes" />'."\n";
7323:
7324: $result.='<table width="100%" border="0"><tr><td bgcolor=#777777>'."\n".
7325: '<table width="100%" border="0"><tr bgcolor="#e6ffff"><td colspan="2">'."\n".
7326: ' <b>Select a Grading/Viewing Option</b></td></tr>'."\n".
7327: '<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
7328:
7329: $result.='<table width="100%" border="0">';
7330: $result.='<tr bgcolor="#ffffe6" valign="top">'."\n";
7331: $result.='<td><b>'.&mt('Sections').'</b></td>';
7332: # $result.='<td>Groups</td>';
7333: $result.='<td><b>'.&mt('Access Status').'</td>'."\n";
7334: $result.='</tr>';
7335: $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
7336: ' <select name="section" multiple="multiple" size="3">'."\n";
7337: if (ref($sections)) {
7338: foreach (sort (@$sections)) {
7339: $result.='<option value="'.$_.'" '.
7340: ($saveSec eq $_ ? 'selected="selected"':'').'>'.$_.'</option>'."\n";
7341: }
7342: }
7343: $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> ';
7344: return $Str;
7345: }
7346:
7347:
7348: #--- Displays the submissions first page -------
7349: sub submit_options {
7350: my ($request) = @_;
7351: my ($symb)=&get_symb($request);
7352: if (!$symb) {return '';}
7353: my $probTitle = &Apache::lonnet::gettitle($symb);
7354:
7355: $request->print(<<GRADINGMENUJS);
7356: <script type="text/javascript" language="javascript">
7357: function checkChoice(formname,val,cmdx) {
7358: if (val <= 2) {
7359: var cmd = radioSelection(formname.radioChoice);
7360: var cmdsave = cmd;
7361: } else {
7362: cmd = cmdx;
7363: cmdsave = 'submission';
7364: }
7365: formname.command.value = cmd;
7366: formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
7367: ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
7368: if (val < 5) formname.submit();
7369: if (val == 5) {
7370: if (!checkReceiptNo(formname,'notOK')) { return false;}
7371: formname.submit();
7372: }
7373: if (val < 7) formname.submit();
7374: }
7375:
7376: function checkReceiptNo(formname,nospace) {
7377: var receiptNo = formname.receipt.value;
7378: var checkOpt = false;
7379: if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
7380: if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
7381: if (checkOpt) {
7382: alert("Please enter a receipt number given by a student in the receipt box.");
7383: formname.receipt.value = "";
7384: formname.receipt.focus();
7385: return false;
7386: }
7387: return true;
7388: }
7389: </script>
7390: GRADINGMENUJS
7391: &commonJSfunctions($request);
7392: my $result='<h3> <span class="LC_info">Manual Grading/View Submission</span></h3>';
7393: my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
7394: $result.=$table;
7395: my (undef,$sections) = &getclasslist('all','0');
7396: my $savedState = &savedState();
7397: my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
7398: my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
7399: my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
7400: my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
7401:
7402: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
7403: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
7404: '<input type="hidden" name="handgrade" value="'.$hdgrade.'" />'."\n".
7405: '<input type="hidden" name="probTitle" value="'.$probTitle.'" />'."\n".
7406: '<input type="hidden" name="command" value="" />'."\n".
7407: '<input type="hidden" name="saveState" value="" />'."\n".
7408: '<input type="hidden" name="gradingMenu" value="1" />'."\n".
7409: '<input type="hidden" name="showgrading" value="yes" />'."\n";
7410:
7411: $result.='<table border="0"><tr><td bgcolor=#777777>'."\n".
7412: '<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n".
7413: ' <b>Select a Grading/Viewing Option</b></td></tr>'."\n".
7414: '<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
7415:
7416: $result.='<table width="100%" border="0">';
7417: $result.='<tr bgcolor="#ffffe6" valign="top">'."\n";
7418: $result.='<td><b>'.&mt('Sections').'</b></td>';
7419: $result.='<td><b>'.&mt('Groups').'</b></td>';
7420: $result.='<td><b>'.&mt('Access Status').'</td>'."\n";
7421: $result.='</tr>';
7422: $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
7423: ' <select name="section" multiple="multiple" size="3">'."\n";
7424: if (ref($sections)) {
7425: foreach (sort (@$sections)) {
7426: $result.='<option value="'.$_.'" '.
7427: ($saveSec eq $_ ? 'selected="selected"':'').'>'.$_.'</option>'."\n";
7428: }
7429: }
7430: $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> ';
7431: $result.= '</td><td>'."\n";
7432: $result.= &Apache::lonstatistics::GroupSelect('group','multiple',3);
7433: $result.='</td><td>'."\n";
7434: $result.=&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,3,undef,'mult');
7435:
7436: $result.='</td></tr>';
7437:
7438: $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="3"><label>'.
7439: '<input type="radio" name="radioChoice" value="submission" '.
7440: ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.'<b>'.&mt('Current Resource').':</b> '.&mt('For one or more students').
7441: '</label> <select name="submitonly">'.
7442: '<option value="yes" '.
7443: ($saveSub eq 'yes' ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>'.
7444: '<option value="queued" '.
7445: ($saveSub eq 'queued' ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>'.
7446: '<option value="graded" '.
7447: ($saveSub eq 'graded' ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>'.
7448: '<option value="incorrect" '.
7449: ($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>'.
7450: '<option value="all" '.
7451: ($saveSub eq 'all' ? 'selected="selected"' : '').'>'.&mt('with any status').'</option></select></td></tr>'."\n";
7452:
7453: $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
7454: '<label><input type="radio" name="radioChoice" value="viewgrades" '.
7455: ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
7456: '<b>Current Resource:</b> For all students in selected section or course</label></td></tr>'."\n";
7457:
7458: $result.='<tr bgcolor="#ffffe6" valign="top"><td colspan="2">'.
7459: '<label><input type="radio" name="radioChoice" value="pickStudentPage" '.
7460: ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
7461: 'The <b>complete</b> set/page/sequence: For one student</label></td></tr>'."\n";
7462:
7463: $result.='<tr bgcolor="#ffffe6"><td colspan="2"><br />'.
7464: '<input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="Next->" />'.
7465: '</td></tr></table>'."\n";
7466:
7467: $result.='</td>'; #<td valign="top">';
7468:
7469: # $result.='<table width="100%" border="0">';
7470: # $result.='<tr bgcolor="#ffffe6"><td>'.
7471: # '<input type="button" onClick="javascript:checkChoice(this.form,\'3\',\'csvform\');" value="'.&mt('Upload').'" />'.
7472: # ' '.&mt('scores from file').' </td></tr>'."\n";
7473: #
7474: # $result.='<tr bgcolor="#ffffe6"><td>'.
7475: # '<input type="button" onClick="javascript:checkChoice(this.form,\'6\',\'processclicker\');" value="'.&mt('Process').'" />'.
7476: # ' '.&mt('clicker file').' </td></tr>'."\n";
7477: #
7478: # $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
7479: # '<input type="button" onClick="javascript:checkChoice(this.form,\'4\',\'scantron_selectphase\');'.
7480: # '" value="'.&mt('Grade').'" /> scantron forms</td></tr>'."\n";
7481: #
7482: # if ((&Apache::lonnet::allowed('mgr',$env{'request.course.id'})) && ($symb)) {
7483: # $result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
7484: # '<input type="button" onClick="javascript:checkChoice(this.form,\'5\',\'verify\');" value="'.&mt('Verify').'" />'.
7485: # ' '.&mt('receipt').': '.
7486: # &Apache::lonnet::recprefix($env{'request.course.id'}).
7487: # '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />'.
7488: # '</td></tr>'."\n";
7489: # }
7490: # $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
7491: # '<input type="button" onClick="javascript:this.form.action=\'/adm/helper/resettimes.helper\';this.form.submit();'.
7492: # '" value="'.&mt('Manage').'" /> access times.</td></tr>'."\n";
7493: # $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
7494: # '<input type="button" onClick="javascript:this.form.command.value=\'codelist\';this.form.action=\'/adm/pickcode\';this.form.submit();'.
7495: # '" value="'.&mt('View').'" /> saved CODEs.</td></tr>'."\n";
7496: #
7497: # $result.='</table>'."\n".'</td>';
7498: $result.= '</tr></table>'."\n".
7499: '</td></tr></table></form>'."\n";
7500: return $result;
7501: }
7502:
7503: sub reset_perm {
7504: undef(%perm);
7505: }
7506:
7507: sub init_perm {
7508: &reset_perm();
7509: foreach my $test_perm ('vgr','mgr','opa') {
7510:
7511: my $scope = $env{'request.course.id'};
7512: if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
7513:
7514: $scope .= '/'.$env{'request.course.sec'};
7515: if ( $perm{$test_perm}=
7516: &Apache::lonnet::allowed($test_perm,$scope)) {
7517: $perm{$test_perm.'_section'}=$env{'request.course.sec'};
7518: } else {
7519: delete($perm{$test_perm});
7520: }
7521: }
7522: }
7523: }
7524:
7525: sub gather_clicker_ids {
7526: my %clicker_ids;
7527:
7528: my $classlist = &Apache::loncoursedata::get_classlist();
7529:
7530: # Set up a couple variables.
7531: my $username_idx = &Apache::loncoursedata::CL_SNAME();
7532: my $domain_idx = &Apache::loncoursedata::CL_SDOM();
7533: my $status_idx = &Apache::loncoursedata::CL_STATUS();
7534:
7535: foreach my $student (keys(%$classlist)) {
7536: if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
7537: my $username = $classlist->{$student}->[$username_idx];
7538: my $domain = $classlist->{$student}->[$domain_idx];
7539: my $clickers =
7540: (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
7541: foreach my $id (split(/\,/,$clickers)) {
7542: $id=~s/^[\#0]+//;
7543: $id=~s/[\-\:]//g;
7544: if (exists($clicker_ids{$id})) {
7545: $clicker_ids{$id}.=','.$username.':'.$domain;
7546: } else {
7547: $clicker_ids{$id}=$username.':'.$domain;
7548: }
7549: }
7550: }
7551: return %clicker_ids;
7552: }
7553:
7554: sub gather_adv_clicker_ids {
7555: my %clicker_ids;
7556: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
7557: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7558: my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
7559: foreach my $element (sort(keys(%coursepersonnel))) {
7560: foreach my $person (split(/\,/,$coursepersonnel{$element})) {
7561: my ($puname,$pudom)=split(/\:/,$person);
7562: my $clickers =
7563: (&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
7564: foreach my $id (split(/\,/,$clickers)) {
7565: $id=~s/^[\#0]+//;
7566: $id=~s/[\-\:]//g;
7567: if (exists($clicker_ids{$id})) {
7568: $clicker_ids{$id}.=','.$puname.':'.$pudom;
7569: } else {
7570: $clicker_ids{$id}=$puname.':'.$pudom;
7571: }
7572: }
7573: }
7574: }
7575: return %clicker_ids;
7576: }
7577:
7578: sub clicker_grading_parameters {
7579: return ('gradingmechanism' => 'scalar',
7580: 'upfiletype' => 'scalar',
7581: 'specificid' => 'scalar',
7582: 'pcorrect' => 'scalar',
7583: 'pincorrect' => 'scalar');
7584: }
7585:
7586: sub process_clicker {
7587: my ($r)=@_;
7588: my ($symb)=&get_symb($r);
7589: if (!$symb) {return '';}
7590: my $result=&checkforfile_js();
7591: $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
7592: my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
7593: $result.=$table;
7594: $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
7595: $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
7596: $result.=' <b>'.&mt('Specify a file containing the clicker information for this resource').
7597: '.</b></td></tr>'."\n";
7598: $result.='<tr bgcolor=#ffffe6><td>'."\n";
7599: # Attempt to restore parameters from last session, set defaults if not present
7600: my %Saveable_Parameters=&clicker_grading_parameters();
7601: &Apache::loncommon::restore_course_settings('grades_clicker',
7602: \%Saveable_Parameters);
7603: if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
7604: if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
7605: if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
7606: if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
7607:
7608: my %checked;
7609: foreach my $gradingmechanism ('attendance','personnel','specific') {
7610: if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
7611: $checked{$gradingmechanism}="checked='checked'";
7612: }
7613: }
7614:
7615: my $upload=&mt("Upload File");
7616: my $type=&mt("Type");
7617: my $attendance=&mt("Award points just for participation");
7618: my $personnel=&mt("Correctness determined from response by course personnel");
7619: my $specific=&mt("Correctness determined from response with clicker ID(s)");
7620: my $pcorrect=&mt("Percentage points for correct solution");
7621: my $pincorrect=&mt("Percentage points for incorrect solution");
7622: my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
7623: ('iclicker' => 'i>clicker',
7624: 'interwrite' => 'interwrite PRS'));
7625: $symb = &Apache::lonenc::check_encrypt($symb);
7626: $result.=<<ENDUPFORM;
7627: <script type="text/javascript">
7628: function sanitycheck() {
7629: // Accept only integer percentages
7630: document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
7631: document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
7632: // Find out grading choice
7633: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
7634: if (document.forms.gradesupload.gradingmechanism[i].checked) {
7635: gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
7636: }
7637: }
7638: // By default, new choice equals user selection
7639: newgradingchoice=gradingchoice;
7640: // Not good to give more points for false answers than correct ones
7641: if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
7642: document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
7643: }
7644: // If new choice is attendance only, and old choice was correctness-based, restore defaults
7645: if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
7646: document.forms.gradesupload.pcorrect.value=100;
7647: document.forms.gradesupload.pincorrect.value=100;
7648: }
7649: // If the values are different, cannot be attendance only
7650: if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
7651: (gradingchoice=='attendance')) {
7652: newgradingchoice='personnel';
7653: }
7654: // Change grading choice to new one
7655: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
7656: if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
7657: document.forms.gradesupload.gradingmechanism[i].checked=true;
7658: } else {
7659: document.forms.gradesupload.gradingmechanism[i].checked=false;
7660: }
7661: }
7662: // Remember the old state
7663: document.forms.gradesupload.waschecked.value=newgradingchoice;
7664: }
7665: </script>
7666: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
7667: <input type="hidden" name="symb" value="$symb" />
7668: <input type="hidden" name="command" value="processclickerfile" />
7669: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
7670: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
7671: <input type="file" name="upfile" size="50" />
7672: <br /><label>$type: $selectform</label>
7673: <br /><label>$attendance: <input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" /></label>
7674: <br /><label>$personnel: <input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" /></label>
7675: <br /><label>$specific: <input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" /></label>
7676: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
7677: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
7678: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
7679: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
7680: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
7681: </form>
7682: ENDUPFORM
7683: $result.='</td></tr></table>'."\n".
7684: '</td></tr></table><br /><br />'."\n";
7685: $result.=&show_grading_menu_form($symb);
7686: return $result;
7687: }
7688:
7689: sub process_clicker_file {
7690: my ($r)=@_;
7691: my ($symb)=&get_symb($r);
7692: if (!$symb) {return '';}
7693:
7694: my %Saveable_Parameters=&clicker_grading_parameters();
7695: &Apache::loncommon::store_course_settings('grades_clicker',
7696: \%Saveable_Parameters);
7697:
7698: my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
7699: if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
7700: $result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
7701: return $result.&show_grading_menu_form($symb);
7702: }
7703: my %clicker_ids=&gather_clicker_ids();
7704: my %correct_ids;
7705: if ($env{'form.gradingmechanism'} eq 'personnel') {
7706: %correct_ids=&gather_adv_clicker_ids();
7707: }
7708: if ($env{'form.gradingmechanism'} eq 'specific') {
7709: foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
7710: $correct_id=~tr/a-z/A-Z/;
7711: $correct_id=~s/\s//gs;
7712: $correct_id=~s/^[\#0]+//;
7713: $correct_id=~s/[\-\:]//g;
7714: if ($correct_id) {
7715: $correct_ids{$correct_id}='specified';
7716: }
7717: }
7718: }
7719: if ($env{'form.gradingmechanism'} eq 'attendance') {
7720: $result.=&mt('Score based on attendance only');
7721: } else {
7722: my $number=0;
7723: $result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
7724: foreach my $id (sort(keys(%correct_ids))) {
7725: $result.='<br /><tt>'.$id.'</tt> - ';
7726: if ($correct_ids{$id} eq 'specified') {
7727: $result.=&mt('specified');
7728: } else {
7729: my ($uname,$udom)=split(/\:/,$correct_ids{$id});
7730: $result.=&Apache::loncommon::plainname($uname,$udom);
7731: }
7732: $number++;
7733: }
7734: $result.="</p>\n";
7735: if ($number==0) {
7736: $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
7737: return $result.&show_grading_menu_form($symb);
7738: }
7739: }
7740: if (length($env{'form.upfile'}) < 2) {
7741: $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
7742: '<span class="LC_error">',
7743: '</span>',
7744: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
7745: return $result.&show_grading_menu_form($symb);
7746: }
7747:
7748: # Were able to get all the info needed, now analyze the file
7749:
7750: $result.=&Apache::loncommon::studentbrowser_javascript();
7751: $symb = &Apache::lonenc::check_encrypt($symb);
7752: my $heading=&mt('Scanning clicker file');
7753: $result.=(<<ENDHEADER);
7754: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
7755: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
7756: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
7757: <form method="post" action="/adm/grades" name="clickeranalysis">
7758: <input type="hidden" name="symb" value="$symb" />
7759: <input type="hidden" name="command" value="assignclickergrades" />
7760: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
7761: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
7762: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
7763: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
7764: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
7765: ENDHEADER
7766: my %responses;
7767: my @questiontitles;
7768: my $errormsg='';
7769: my $number=0;
7770: if ($env{'form.upfiletype'} eq 'iclicker') {
7771: ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
7772: }
7773: if ($env{'form.upfiletype'} eq 'interwrite') {
7774: ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
7775: }
7776: $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
7777: '<input type="hidden" name="number" value="'.$number.'" />'.
7778: &mt('Awarding [_1] percent for corrion(s)',$number).'<br />'.
7779: '<input type="hidden" name="number" value="'.$number.'" />'.
7780: &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
7781: $env{'form.pcorrect'},$env{'form.pincorrect'}).
7782: '<br />';
7783: # Remember Question Titles
7784: # FIXME: Possibly need delimiter other than ":"
7785: for (my $i=0;$i<$number;$i++) {
7786: $result.='<input type="hidden" name="question:'.$i.'" value="'.
7787: &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
7788: }
7789: my $correct_count=0;
7790: my $student_count=0;
7791: my $unknown_count=0;
7792: # Match answers with usernames
7793: # FIXME: Possibly need delimiter other than ":"
7794: foreach my $id (keys(%responses)) {
7795: if ($correct_ids{$id}) {
7796: $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
7797: $correct_count++;
7798: } elsif ($clicker_ids{$id}) {
7799: if ($clicker_ids{$id}=~/\,/) {
7800: # More than one user with the same clicker!
7801: $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
7802: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
7803: "<select name='multi".$id."'>";
7804: foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
7805: $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
7806: }
7807: $result.='</select>';
7808: $unknown_count++;
7809: } else {
7810: # Good: found one and only one user with the right clicker
7811: $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
7812: $student_count++;
7813: }
7814: } else {
7815: $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
7816: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
7817: "\n".&mt("Username").": <input type='text' name='uname".$id."' /> ".
7818: "\n".&mt("Domain").": ".
7819: &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).' '.
7820: &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
7821: $unknown_count++;
7822: }
7823: }
7824: $result.='<hr />'.
7825: &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
7826: if ($env{'form.gradingmechanism'} ne 'attendance') {
7827: if ($correct_count==0) {
7828: $errormsg.="Found no correct answers answers for grading!";
7829: } elsif ($correct_count>1) {
7830: $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
7831: }
7832: }
7833: if ($number<1) {
7834: $errormsg.="Found no questions.";
7835: }
7836: if ($errormsg) {
7837: $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
7838: } else {
7839: $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
7840: }
7841: $result.='</form></td></tr></table>'."\n".
7842: '</td></tr></table><br /><br />'."\n";
7843: return $result.&show_grading_menu_form($symb);
7844: }
7845:
7846: sub iclicker_eval {
7847: my ($questiontitles,$responses)=@_;
7848: my $number=0;
7849: my $errormsg='';
7850: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
7851: my %components=&Apache::loncommon::record_sep($line);
7852: my @entries=map {$components{$_}} (sort(keys(%components)));
7853: if ($entries[0] eq 'Question') {
7854: for (my $i=3;$i<$#entries;$i+=6) {
7855: $$questiontitles[$number]=$entries[$i];
7856: $number++;
7857: }
7858: }
7859: if ($entries[0]=~/^\#/) {
7860: my $id=$entries[0];
7861: my @idresponses;
7862: $id=~s/^[\#0]+//;
7863: for (my $i=0;$i<$number;$i++) {
7864: my $idx=3+$i*6;
7865: push(@idresponses,$entries[$idx]);
7866: }
7867: $$responses{$id}=join(',',@idresponses);
7868: }
7869: }
7870: return ($errormsg,$number);
7871: }
7872:
7873: sub interwrite_eval {
7874: my ($questiontitles,$responses)=@_;
7875: my $number=0;
7876: my $errormsg='';
7877: my $skipline=1;
7878: my $questionnumber=0;
7879: my %idresponses=();
7880: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
7881: my %components=&Apache::loncommon::record_sep($line);
7882: my @entries=map {$components{$_}} (sort(keys(%components)));
7883: if ($entries[1] eq 'Time') { $skipline=0; next; }
7884: if ($entries[1] eq 'Response') { $skipline=1; }
7885: next if $skipline;
7886: if ($entries[0]!=$questionnumber) {
7887: $questionnumber=$entries[0];
7888: $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
7889: $number++;
7890: }
7891: my $id=$entries[4];
7892: $id=~s/^[\#0]+//;
7893: $id=~s/^v\d*\://i;
7894: $id=~s/[\-\:]//g;
7895: $idresponses{$id}[$number]=$entries[6];
7896: }
7897: foreach my $id (keys %idresponses) {
7898: $$responses{$id}=join(',',@{$idresponses{$id}});
7899: $$responses{$id}=~s/^\s*\,//;
7900: }
7901: return ($errormsg,$number);
7902: }
7903:
7904: sub assign_clicker_grades {
7905: my ($r)=@_;
7906: my ($symb)=&get_symb($r);
7907: if (!$symb) {return '';}
7908: # See which part we are saving to
7909: my ($partlist,$handgrade,$responseType) = &response_type($symb);
7910: # FIXME: This should probably look for the first handgradeable part
7911: my $part=$$partlist[0];
7912: # Start screen output
7913: my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
7914:
7915: my $heading=&mt('Assigning grades based on clicker file');
7916: $result.=(<<ENDHEADER);
7917: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
7918: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
7919: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
7920: ENDHEADER
7921: # Get correct result
7922: # FIXME: Possibly need delimiter other than ":"
7923: my @correct=();
7924: my $gradingmechanism=$env{'form.gradingmechanism'};
7925: my $number=$env{'form.number'};
7926: if ($gradingmechanism ne 'attendance') {
7927: foreach my $key (keys(%env)) {
7928: if ($key=~/^form\.correct\:/) {
7929: my @input=split(/\,/,$env{$key});
7930: for (my $i=0;$i<=$#input;$i++) {
7931: if (($correct[$i]) && ($input[$i]) &&
7932: ($correct[$i] ne $input[$i])) {
7933: $result.='<br /><span class="LC_warning">'.
7934: &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
7935: $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
7936: } elsif ($input[$i]) {
7937: $correct[$i]=$input[$i];
7938: }
7939: }
7940: }
7941: }
7942: for (my $i=0;$i<$number;$i++) {
7943: if (!$correct[$i]) {
7944: $result.='<br /><span class="LC_error">'.
7945: &mt('No correct result given for question "[_1]"!',
7946: $env{'form.question:'.$i}).'</span>';
7947: }
7948: }
7949: $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
7950: }
7951: # Start grading
7952: my $pcorrect=$env{'form.pcorrect'};
7953: my $pincorrect=$env{'form.pincorrect'};
7954: my $storecount=0;
7955: foreach my $key (keys(%env)) {
7956: my $user='';
7957: if ($key=~/^form\.student\:(.*)$/) {
7958: $user=$1;
7959: }
7960: if ($key=~/^form\.unknown\:(.*)$/) {
7961: my $id=$1;
7962: if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
7963: $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
7964: } elsif ($env{'form.multi'.$id}) {
7965: $user=$env{'form.multi'.$id};
7966: }
7967: }
7968: if ($user) {
7969: my @answer=split(/\,/,$env{$key});
7970: my $sum=0;
7971: for (my $i=0;$i<$number;$i++) {
7972: if ($answer[$i]) {
7973: if ($gradingmechanism eq 'attendance') {
7974: $sum+=$pcorrect;
7975: } else {
7976: if ($answer[$i] eq $correct[$i]) {
7977: $sum+=$pcorrect;
7978: } else {
7979: $sum+=$pincorrect;
7980: }
7981: }
7982: }
7983: }
7984: my $ave=$sum/(100*$number);
7985: # Store
7986: my ($username,$domain)=split(/\:/,$user);
7987: my %grades=();
7988: $grades{"resource.$part.solved"}='correct_by_override';
7989: $grades{"resource.$part.awarded"}=$ave;
7990: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
7991: my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
7992: $env{'request.course.id'},
7993: $domain,$username);
7994: if ($returncode ne 'ok') {
7995: $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
7996: } else {
7997: $storecount++;
7998: }
7999: }
8000: }
8001: # We are done
8002: $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
8003: '</td></tr></table>'."\n".
8004: '</td></tr></table><br /><br />'."\n";
8005: return $result.&show_grading_menu_form($symb);
8006: }
8007:
8008: sub handler {
8009: my $request=$_[0];
8010:
8011: &reset_caches();
8012: if ($env{'browser.mathml'}) {
8013: &Apache::loncommon::content_type($request,'text/xml');
8014: } else {
8015: &Apache::loncommon::content_type($request,'text/html');
8016: }
8017: $request->send_http_header;
8018: return '' if $request->header_only;
8019: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
8020: my $symb=&get_symb($request,1);
8021: my @commands=&Apache::loncommon::get_env_multiple('form.command');
8022: my $command=$commands[0];
8023:
8024: if ($#commands > 0) {
8025: &Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
8026: }
8027:
8028:
8029: $request->print(&Apache::loncommon::start_page('Grading'));
8030: if ($symb eq '' && $command eq '') {
8031: if ($env{'user.adv'}) {
8032: if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
8033: ($env{'form.codethree'})) {
8034: my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
8035: $env{'form.codethree'};
8036: my ($tsymb,$tuname,$tudom,$tcrsid)=
8037: &Apache::lonnet::checkin($token);
8038: if ($tsymb) {
8039: my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
8040: if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
8041: $request->print(&Apache::lonnet::ssi_body('/res/'.$url,
8042: ('grade_username' => $tuname,
8043: 'grade_domain' => $tudom,
8044: 'grade_courseid' => $tcrsid,
8045: 'grade_symb' => $tsymb)));
8046: } else {
8047: $request->print('<h3>Not authorized: '.$token.'</h3>');
8048: }
8049: } else {
8050: $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
8051: }
8052: } else {
8053: $request->print(&Apache::lonxml::tokeninputfield());
8054: }
8055: }
8056: } else {
8057: &init_perm();
8058: if ($command eq 'submission' && $perm{'vgr'}) {
8059: ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
8060: } elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
8061: &pickStudentPage($request);
8062: } elsif ($command eq 'displayPage' && $perm{'vgr'}) {
8063: &displayPage($request);
8064: } elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
8065: &updateGradeByPage($request);
8066: } elsif ($command eq 'processGroup' && $perm{'vgr'}) {
8067: &processGroup($request);
8068: } elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
8069: $request->print(&grading_menu($request));
8070: } elsif ($command eq 'submit_options' && $perm{'vgr'}) {
8071: $request->print(&submit_options($request));
8072: } elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
8073: $request->print(&viewgrades($request));
8074: } elsif ($command eq 'handgrade' && $perm{'mgr'}) {
8075: $request->print(&processHandGrade($request));
8076: } elsif ($command eq 'editgrades' && $perm{'mgr'}) {
8077: $request->print(&editgrades($request));
8078: } elsif ($command eq 'verify' && $perm{'vgr'}) {
8079: $request->print(&verifyreceipt($request));
8080: } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
8081: $request->print(&process_clicker($request));
8082: } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
8083: $request->print(&process_clicker_file($request));
8084: } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
8085: $request->print(&assign_clicker_grades($request));
8086: } elsif ($command eq 'csvform' && $perm{'mgr'}) {
8087: $request->print(&upcsvScores_form($request));
8088: } elsif ($command eq 'csvupload' && $perm{'mgr'}) {
8089: $request->print(&csvupload($request));
8090: } elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
8091: $request->print(&csvuploadmap($request));
8092: } elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
8093: if ($env{'form.associate'} ne 'Reverse Association') {
8094: $request->print(&csvuploadoptions($request));
8095: } else {
8096: if ( $env{'form.upfile_associate'} ne 'reverse' ) {
8097: $env{'form.upfile_associate'} = 'reverse';
8098: } else {
8099: $env{'form.upfile_associate'} = 'forward';
8100: }
8101: $request->print(&csvuploadmap($request));
8102: }
8103: } elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
8104: $request->print(&csvuploadassign($request));
8105: } elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
8106: &Apache::lonnet::logthis("Selecting pyhase");
8107: $request->print(&scantron_selectphase($request));
8108: } elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
8109: $request->print(&scantron_do_warning($request));
8110: } elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
8111: $request->print(&scantron_validate_file($request));
8112: } elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
8113: $request->print(&scantron_process_students($request));
8114: } elsif ($command eq 'scantronupload' &&
8115: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
8116: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
8117: $request->print(&scantron_upload_scantron_data($request));
8118: } elsif ($command eq 'scantronupload_save' &&
8119: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
8120: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
8121: $request->print(&scantron_upload_scantron_data_save($request));
8122: } elsif ($command eq 'scantron_download' &&
8123: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
8124: $request->print(&scantron_download_scantron_data($request));
8125: } elsif ($command) {
8126: $request->print("Access Denied ($command)");
8127: }
8128: }
8129: $request->print(&Apache::loncommon::end_page());
8130: &reset_caches();
8131: return '';
8132: }
8133:
8134: 1;
8135:
8136: __END__;
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>