1: # The LearningOnline Network with CAPA
2: # The LON-CAPA Grading handler
3: #
4: # $Id: grades.pm,v 1.448 2007/10/09 10:31:21 foxr Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28:
29: package Apache::grades;
30: use strict;
31: use Apache::style;
32: use Apache::lonxml;
33: use Apache::lonnet;
34: use Apache::loncommon;
35: use Apache::lonhtmlcommon;
36: use Apache::lonnavmaps;
37: use Apache::lonhomework;
38: use Apache::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) = @_;
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=&Apache::loncoursedata::get_classlist();
491: # Bail out if we were unable to get the classlist
492: return if (! defined($classlist));
493: #
494: my %sections;
495: my %fullnames;
496: foreach my $student (keys(%$classlist)) {
497: my $end =
498: $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
499: my $start =
500: $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
501: my $id =
502: $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
503: my $section =
504: $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
505: my $fullname =
506: $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
507: my $status =
508: $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
509: # filter students according to status selected
510: if ($filterlist && (!($stu_status =~ /Any/))) {
511: if (!($stu_status =~ $status)) {
512: delete ($classlist->{$student});
513: next;
514: }
515: }
516: $section = ($section ne '' ? $section : 'none');
517: if (&canview($section)) {
518: if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
519: $sections{$section}++;
520: $fullnames{$student}=$fullname;
521: } else {
522: delete($classlist->{$student});
523: }
524: } else {
525: delete($classlist->{$student});
526: }
527: }
528: my %seen = ();
529: my @sections = sort(keys(%sections));
530: return ($classlist,\@sections,\%fullnames);
531: }
532:
533: sub canmodify {
534: my ($sec)=@_;
535: if ($perm{'mgr'}) {
536: if (!defined($perm{'mgr_section'})) {
537: # can modify whole class
538: return 1;
539: } else {
540: if ($sec eq $perm{'mgr_section'}) {
541: #can modify the requested section
542: return 1;
543: } else {
544: # can't modify the request section
545: return 0;
546: }
547: }
548: }
549: #can't modify
550: return 0;
551: }
552:
553: sub canview {
554: my ($sec)=@_;
555: if ($perm{'vgr'}) {
556: if (!defined($perm{'vgr_section'})) {
557: # can modify whole class
558: return 1;
559: } else {
560: if ($sec eq $perm{'vgr_section'}) {
561: #can modify the requested section
562: return 1;
563: } else {
564: # can't modify the request section
565: return 0;
566: }
567: }
568: }
569: #can't modify
570: return 0;
571: }
572:
573: #--- Retrieve the grade status of a student for all the parts
574: sub student_gradeStatus {
575: my ($symb,$udom,$uname,$partlist) = @_;
576: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
577: my %partstatus = ();
578: foreach (@$partlist) {
579: my ($status,undef) = split(/_/,$record{"resource.$_.solved"},2);
580: $status = 'nothing' if ($status eq '');
581: $partstatus{$_} = $status;
582: my $subkey = "resource.$_.submitted_by";
583: $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
584: }
585: return %partstatus;
586: }
587:
588: # hidden form and javascript that calls the form
589: # Use by verifyscript and viewgrades
590: # Shows a student's view of problem and submission
591: sub jscriptNform {
592: my ($symb) = @_;
593: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
594: my $jscript='<script type="text/javascript" language="javascript">'."\n".
595: ' function viewOneStudent(user,domain) {'."\n".
596: ' document.onestudent.student.value = user;'."\n".
597: ' document.onestudent.userdom.value = domain;'."\n".
598: ' document.onestudent.submit();'."\n".
599: ' }'."\n".
600: '</script>'."\n";
601: $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
602: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
603: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
604: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
605: '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
606: '<input type="hidden" name="command" value="submission" />'."\n".
607: '<input type="hidden" name="student" value="" />'."\n".
608: '<input type="hidden" name="userdom" value="" />'."\n".
609: '</form>'."\n";
610: return $jscript;
611: }
612:
613:
614:
615: # Given the score (as a number [0-1] and the weight) what is the final
616: # point value? This function will round to the nearest tenth, third,
617: # or quarter if one of those is within the tolerance of .00001.
618: sub compute_points {
619: my ($score, $weight) = @_;
620:
621: my $tolerance = .00001;
622: my $points = $score * $weight;
623:
624: # Check for nearness to 1/x.
625: my $check_for_nearness = sub {
626: my ($factor) = @_;
627: my $num = ($points * $factor) + $tolerance;
628: my $floored_num = floor($num);
629: if ($num - $floored_num < 2 * $tolerance * $factor) {
630: return $floored_num / $factor;
631: }
632: return $points;
633: };
634:
635: $points = $check_for_nearness->(10);
636: $points = $check_for_nearness->(3);
637: $points = $check_for_nearness->(4);
638:
639: return $points;
640: }
641:
642: #------------------ End of general use routines --------------------
643:
644: #
645: # Find most similar essay
646: #
647:
648: sub most_similar {
649: my ($uname,$udom,$uessay,$old_essays)=@_;
650:
651: # ignore spaces and punctuation
652:
653: $uessay=~s/\W+/ /gs;
654:
655: # ignore empty submissions (occuring when only files are sent)
656:
657: unless ($uessay=~/\w+/) { return ''; }
658:
659: # these will be returned. Do not care if not at least 50 percent similar
660: my $limit=0.6;
661: my $sname='';
662: my $sdom='';
663: my $scrsid='';
664: my $sessay='';
665: # go through all essays ...
666: foreach my $tkey (keys(%$old_essays)) {
667: my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
668: # ... except the same student
669: next if (($tname eq $uname) && ($tdom eq $udom));
670: my $tessay=$old_essays->{$tkey};
671: $tessay=~s/\W+/ /gs;
672: # String similarity gives up if not even limit
673: my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
674: # Found one
675: if ($tsimilar>$limit) {
676: $limit=$tsimilar;
677: $sname=$tname;
678: $sdom=$tdom;
679: $scrsid=$tcrsid;
680: $sessay=$old_essays->{$tkey};
681: }
682: }
683: if ($limit>0.6) {
684: return ($sname,$sdom,$scrsid,$sessay,$limit);
685: } else {
686: return ('','','','',0);
687: }
688: }
689:
690: #-------------------------------------------------------------------
691:
692: #------------------------------------ Receipt Verification Routines
693: #
694: #--- Check whether a receipt number is valid.---
695: sub verifyreceipt {
696: my $request = shift;
697:
698: my $courseid = $env{'request.course.id'};
699: my $receipt = &Apache::lonnet::recprefix($courseid).'-'.
700: $env{'form.receipt'};
701: $receipt =~ s/[^\-\d]//g;
702: my ($symb) = &get_symb($request);
703:
704: my $title.='<h3><span class="LC_info">Verifying Submission Receipt '.
705: $receipt.'</h3></span>'."\n".
706: '<h4><b>Resource: </b>'.$env{'form.probTitle'}.'</h4><br /><br />'."\n";
707:
708: my ($string,$contents,$matches) = ('','',0);
709: my (undef,undef,$fullname) = &getclasslist('all','0');
710:
711: my $receiptparts=0;
712: if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
713: $env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
714: my $parts=['0'];
715: if ($receiptparts) { ($parts)=&response_type($symb); }
716: foreach (sort
717: {
718: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
719: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
720: }
721: return $a cmp $b;
722: } (keys(%$fullname))) {
723: my ($uname,$udom)=split(/\:/);
724: foreach my $part (@$parts) {
725: if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
726: $contents.='<tr bgcolor="#ffffe6"><td> '."\n".
727: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
728: '\');" target="_self">'.$$fullname{$_}.'</a> </td>'."\n".
729: '<td> '.$uname.' </td>'.
730: '<td> '.$udom.' </td>';
731: if ($receiptparts) {
732: $contents.='<td> '.$part.' </td>';
733: }
734: $contents.='</tr>'."\n";
735:
736: $matches++;
737: }
738: }
739: }
740: if ($matches == 0) {
741: $string = $title.'No match found for the above receipt.';
742: } else {
743: $string = &jscriptNform($symb).$title.
744: 'The above receipt matches the following student'.
745: ($matches <= 1 ? '.' : 's.')."\n".
746: '<table border="0"><tr><td bgcolor="#777777">'."\n".
747: '<table border="0"><tr bgcolor="#e6ffff">'."\n".
748: '<td><b> Fullname </b></td>'."\n".
749: '<td><b> Username </b></td>'."\n".
750: '<td><b> Domain </b></td>';
751: if ($receiptparts) {
752: $string.='<td> Problem Part </td>';
753: }
754: $string.='</tr>'."\n".$contents.
755: '</table></td></tr></table>'."\n";
756: }
757: return $string.&show_grading_menu_form($symb);
758: }
759:
760: #--- This is called by a number of programs.
761: #--- Called from the Grading Menu - View/Grade an individual student
762: #--- Also called directly when one clicks on the subm button
763: # on the problem page.
764: sub listStudents {
765: my ($request) = shift;
766:
767: my ($symb) = &get_symb($request);
768: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
769: my $cnum = $env{"course.$env{'request.course.id'}.num"};
770: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
771: my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
772:
773: my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
774: $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ?
775: &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
776:
777: my $result='<h3><span class="LC_info"> '.$viewgrade.
778: ' Submissions for a Student or a Group of Students</span></h3>';
779:
780: my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
781:
782: $request->print(<<LISTJAVASCRIPT);
783: <script type="text/javascript" language="javascript">
784: function checkSelect(checkBox) {
785: var ctr=0;
786: var sense="";
787: if (checkBox.length > 1) {
788: for (var i=0; i<checkBox.length; i++) {
789: if (checkBox[i].checked) {
790: ctr++;
791: }
792: }
793: sense = "a student or group of students";
794: } else {
795: if (checkBox.checked) {
796: ctr = 1;
797: }
798: sense = "the student";
799: }
800: if (ctr == 0) {
801: alert("Please select "+sense+" before clicking on the Next button.");
802: return false;
803: }
804: document.gradesub.submit();
805: }
806:
807: function reLoadList(formname) {
808: if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
809: formname.command.value = 'submission';
810: formname.submit();
811: }
812: </script>
813: LISTJAVASCRIPT
814:
815: &commonJSfunctions($request);
816: $request->print($result);
817:
818: my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
819: my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
820: my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
821: "\n".$table.
822: ' <b>View Problem Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
823: '<label><input type="radio" name="vProb" value="yes" /> one student </label>'."\n".
824: '<label><input type="radio" name="vProb" value="all" /> all students </label><br />'."\n".
825: ' <b>View Answer: </b><label><input type="radio" name="vAns" value="no" /> no </label>'."\n".
826: '<label><input type="radio" name="vAns" value="yes" /> one student </label>'."\n".
827: '<label><input type="radio" name="vAns" value="all" checked="checked" /> all students </label><br />'."\n".
828: ' <b>Submissions: </b>'."\n";
829: if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
830: $gradeTable.='<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> essay part only </label>'."\n";
831: }
832: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
833: my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
834: $env{'form.Status'} = $saveStatus;
835: $gradeTable.='<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> last submission only </label>'."\n".
836: '<label><input type="radio" name="lastSub" value="last" /> last submission & parts info </label>'."\n".
837: '<label><input type="radio" name="lastSub" value="datesub" /> by dates and submissions </label>'."\n".
838: '<label><input type="radio" name="lastSub" value="all" /> all details</label><br />'."\n".
839: ' <b>Grading Increments:</b> <select name="increment">'.
840: '<option value="1">Whole Points</option>'.
841: '<option value=".5">Half Points</option>'.
842: '<option value=".25">Quarter Points</option>'.
843: '<option value=".1">Tenths of a Point</option>'.
844: '</select>'.
845: &build_section_inputs().
846: '<input type="hidden" name="submitonly" value="'.$submitonly.'" />'."\n".
847: '<input type="hidden" name="handgrade" value="'.$env{'form.handgrade'}.'" /><br />'."\n".
848: '<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
849: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
850: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
851: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
852: '<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
853:
854: if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
855: $gradeTable.='<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
856: } else {
857: $gradeTable.='<b>Student Status:</b> '.
858: &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);').'<br />';
859: }
860:
861: $gradeTable.='To '.lc($viewgrade).' a submission or a group of submissions, click on the check box(es) '.
862: 'next to the student\'s name(s). Then click on the Next button.<br />'."\n".
863: '<input type="hidden" name="command" value="processGroup" />'."\n";
864:
865: # checkall buttons
866: $gradeTable.=&check_script('gradesub', 'stuinfo');
867: $gradeTable.='<input type="button" '."\n".
868: 'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
869: 'value="Next->" /> <br />'."\n";
870: $gradeTable.=&check_buttons();
871: $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />Check For Plagiarism</label>';
872: my ($classlist, undef, $fullname) = &getclasslist($getsec,'1');
873: $gradeTable.='<table border="0"><tr><td bgcolor="#777777">'.
874: '<table border="0"><tr bgcolor="#e6ffff">';
875: my $loop = 0;
876: while ($loop < 2) {
877: $gradeTable.='<td><b> No.</b> </td><td><b> Select </b></td>'.
878: '<td>'.&nameUserString('header').' Section/Group</td>';
879: if ($env{'form.showgrading'} eq 'yes'
880: && $submitonly ne 'queued'
881: && $submitonly ne 'all') {
882: foreach (sort(@$partlist)) {
883: my $display_part=&get_display_part((split(/_/))[0],$symb);
884: $gradeTable.='<td><b> Part: '.$display_part.
885: ' Status </b></td>';
886: }
887: } elsif ($submitonly eq 'queued') {
888: $gradeTable.='<td><b> '.&mt('Queue Status').' </b></td>';
889: }
890: $loop++;
891: # $gradeTable.='<td></td>' if ($loop%2 ==1);
892: }
893: $gradeTable.='</tr>'."\n";
894:
895: my $ctr = 0;
896: foreach my $student (sort
897: {
898: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
899: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
900: }
901: return $a cmp $b;
902: }
903: (keys(%$fullname))) {
904: my ($uname,$udom) = split(/:/,$student);
905:
906: my %status = ();
907:
908: if ($submitonly eq 'queued') {
909: my %queue_status =
910: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
911: $udom,$uname);
912: next if (!defined($queue_status{'gradingqueue'}));
913: $status{'gradingqueue'} = $queue_status{'gradingqueue'};
914: }
915:
916: if ($env{'form.showgrading'} eq 'yes'
917: && $submitonly ne 'queued'
918: && $submitonly ne 'all') {
919: (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
920: my $submitted = 0;
921: my $graded = 0;
922: my $incorrect = 0;
923: foreach (keys(%status)) {
924: $submitted = 1 if ($status{$_} ne 'nothing');
925: $graded = 1 if ($status{$_} =~ /^ungraded/);
926: $incorrect = 1 if ($status{$_} =~ /^incorrect/);
927:
928: my ($foo,$partid,$foo1) = split(/\./,$_);
929: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
930: $submitted = 0;
931: my ($part)=split(/\./,$partid);
932: $gradeTable.='<input type="hidden" name="'.
933: $student.':'.$part.':submitted_by" value="'.
934: $status{'resource.'.$partid.'.submitted_by'}.'" />';
935: }
936: }
937:
938: next if (!$submitted && ($submitonly eq 'yes' ||
939: $submitonly eq 'incorrect' ||
940: $submitonly eq 'graded'));
941: next if (!$graded && ($submitonly eq 'graded'));
942: next if (!$incorrect && $submitonly eq 'incorrect');
943: }
944:
945: $ctr++;
946: my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
947:
948: if ( $perm{'vgr'} eq 'F' ) {
949: $gradeTable.='<tr bgcolor="#ffffe6">' if ($ctr%2 ==1);
950: $gradeTable.='<td align="right">'.$ctr.' </td>'.
951: '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
952: $student.':'.$$fullname{$student}.':::SECTION'.$section.
953: ') " /> </label></td>'."\n".'<td>'.
954: &nameUserString(undef,$$fullname{$student},$uname,$udom).
955: ' '.$section.'</td>'."\n";
956:
957: if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
958: foreach (sort keys(%status)) {
959: next if (/^resource.*?submitted_by$/);
960: $gradeTable.='<td align="center"> '.$status{$_}.' </td>'."\n";
961: }
962: }
963: # $gradeTable.='<td></td>' if ($ctr%2 ==1);
964: $gradeTable.='</tr>'."\n" if ($ctr%2 ==0);
965: }
966: }
967: if ($ctr%2 ==1) {
968: $gradeTable.='<td> </td><td> </td><td> </td>';
969: if ($env{'form.showgrading'} eq 'yes'
970: && $submitonly ne 'queued'
971: && $submitonly ne 'all') {
972: foreach (@$partlist) {
973: $gradeTable.='<td> </td>';
974: }
975: } elsif ($submitonly eq 'queued') {
976: $gradeTable.='<td> </td>';
977: }
978: $gradeTable.='</tr>';
979: }
980:
981: $gradeTable.='</table></td></tr></table>'."\n".
982: '<input type="button" '.
983: 'onClick="javascript:checkSelect(this.form.stuinfo);" '.
984: 'value="Next->" /></form>'."\n";
985: if ($ctr == 0) {
986: my $num_students=(scalar(keys(%$fullname)));
987: if ($num_students eq 0) {
988: $gradeTable='<br /> <span class="LC_warning">There are no students currently enrolled.</span>';
989: } else {
990: my $submissions='submissions';
991: if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
992: if ($submitonly eq 'graded' ) { $submissions = 'ungraded submissions'; }
993: if ($submitonly eq 'queued' ) { $submissions = 'queued submissions'; }
994: $gradeTable='<br /> <span class="LC_warning">'.
995: 'No '.$submissions.' found for this resource for any students. ('.$num_students.
996: ' students checked for '.$submissions.')</span><br />';
997: }
998: } elsif ($ctr == 1) {
999: $gradeTable =~ s/type=checkbox/type=checkbox checked/;
1000: }
1001: $gradeTable.=&show_grading_menu_form($symb);
1002: $request->print($gradeTable);
1003: return '';
1004: }
1005:
1006: #---- Called from the listStudents routine
1007:
1008: sub check_script {
1009: my ($form, $type)=@_;
1010: my $chkallscript='<script type="text/javascript">
1011: function checkall() {
1012: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1013: ele = document.forms.'.$form.'.elements[i];
1014: if (ele.name == "'.$type.'") {
1015: document.forms.'.$form.'.elements[i].checked=true;
1016: }
1017: }
1018: }
1019:
1020: function checksec() {
1021: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1022: ele = document.forms.'.$form.'.elements[i];
1023: string = document.forms.'.$form.'.chksec.value;
1024: if
1025: (ele.value.indexOf(":::SECTION"+string)>0) {
1026: document.forms.'.$form.'.elements[i].checked=true;
1027: }
1028: }
1029: }
1030:
1031:
1032: function uncheckall() {
1033: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1034: ele = document.forms.'.$form.'.elements[i];
1035: if (ele.name == "'.$type.'") {
1036: document.forms.'.$form.'.elements[i].checked=false;
1037: }
1038: }
1039: }
1040:
1041: </script>'."\n";
1042: return $chkallscript;
1043: }
1044:
1045: sub check_buttons {
1046: my $buttons.='<input type="button" onclick="checkall()" value="Check All" />';
1047: $buttons.='<input type="button" onclick="uncheckall()" value="Uncheck All" /> ';
1048: $buttons.='<input type="button" onclick="checksec()" value="Check Section/Group" />';
1049: $buttons.='<input type="text" size="5" name="chksec" /> ';
1050: return $buttons;
1051: }
1052:
1053: # Displays the submissions for one student or a group of students
1054: sub processGroup {
1055: my ($request) = shift;
1056: my $ctr = 0;
1057: my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1058: my $total = scalar(@stuchecked)-1;
1059:
1060: foreach my $student (@stuchecked) {
1061: my ($uname,$udom,$fullname) = split(/:/,$student);
1062: $env{'form.student'} = $uname;
1063: $env{'form.userdom'} = $udom;
1064: $env{'form.fullname'} = $fullname;
1065: &submission($request,$ctr,$total);
1066: $ctr++;
1067: }
1068: return '';
1069: }
1070:
1071: #------------------------------------------------------------------------------------
1072: #
1073: #-------------------------- Next few routines handles grading by student, essentially
1074: # handles essay response type problem/part
1075: #
1076: #--- Javascript to handle the submission page functionality ---
1077: sub sub_page_js {
1078: my $request = shift;
1079: $request->print(<<SUBJAVASCRIPT);
1080: <script type="text/javascript" language="javascript">
1081: function updateRadio(formname,id,weight) {
1082: var gradeBox = formname["GD_BOX"+id];
1083: var radioButton = formname["RADVAL"+id];
1084: var oldpts = formname["oldpts"+id].value;
1085: var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1086: gradeBox.value = pts;
1087: var resetbox = false;
1088: if (isNaN(pts) || pts < 0) {
1089: alert("A number equal or greater than 0 is expected. Entered value = "+pts);
1090: for (var i=0; i<radioButton.length; i++) {
1091: if (radioButton[i].checked) {
1092: gradeBox.value = i;
1093: resetbox = true;
1094: }
1095: }
1096: if (!resetbox) {
1097: formtextbox.value = "";
1098: }
1099: return;
1100: }
1101:
1102: if (pts > weight) {
1103: var resp = confirm("You entered a value ("+pts+
1104: ") greater than the weight for the part. Accept?");
1105: if (resp == false) {
1106: gradeBox.value = oldpts;
1107: return;
1108: }
1109: }
1110:
1111: for (var i=0; i<radioButton.length; i++) {
1112: radioButton[i].checked=false;
1113: if (pts == i && pts != "") {
1114: radioButton[i].checked=true;
1115: }
1116: }
1117: updateSelect(formname,id);
1118: formname["stores"+id].value = "0";
1119: }
1120:
1121: function writeBox(formname,id,pts) {
1122: var gradeBox = formname["GD_BOX"+id];
1123: if (checkSolved(formname,id) == 'update') {
1124: gradeBox.value = pts;
1125: } else {
1126: var oldpts = formname["oldpts"+id].value;
1127: gradeBox.value = oldpts;
1128: var radioButton = formname["RADVAL"+id];
1129: for (var i=0; i<radioButton.length; i++) {
1130: radioButton[i].checked=false;
1131: if (i == oldpts) {
1132: radioButton[i].checked=true;
1133: }
1134: }
1135: }
1136: formname["stores"+id].value = "0";
1137: updateSelect(formname,id);
1138: return;
1139: }
1140:
1141: function clearRadBox(formname,id) {
1142: if (checkSolved(formname,id) == 'noupdate') {
1143: updateSelect(formname,id);
1144: return;
1145: }
1146: gradeSelect = formname["GD_SEL"+id];
1147: for (var i=0; i<gradeSelect.length; i++) {
1148: if (gradeSelect[i].selected) {
1149: var selectx=i;
1150: }
1151: }
1152: var stores = formname["stores"+id];
1153: if (selectx == stores.value) { return };
1154: var gradeBox = formname["GD_BOX"+id];
1155: gradeBox.value = "";
1156: var radioButton = formname["RADVAL"+id];
1157: for (var i=0; i<radioButton.length; i++) {
1158: radioButton[i].checked=false;
1159: }
1160: stores.value = selectx;
1161: }
1162:
1163: function checkSolved(formname,id) {
1164: if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1165: var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
1166: if (!reply) {return "noupdate";}
1167: formname.overRideScore.value = 'yes';
1168: }
1169: return "update";
1170: }
1171:
1172: function updateSelect(formname,id) {
1173: formname["GD_SEL"+id][0].selected = true;
1174: return;
1175: }
1176:
1177: //=========== Check that a point is assigned for all the parts ============
1178: function checksubmit(formname,val,total,parttot) {
1179: formname.gradeOpt.value = val;
1180: if (val == "Save & Next") {
1181: for (i=0;i<=total;i++) {
1182: for (j=0;j<parttot;j++) {
1183: var partid = formname["partid"+i+"_"+j].value;
1184: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1185: var points = formname["GD_BOX"+i+"_"+partid].value;
1186: if (points == "") {
1187: var name = formname["name"+i].value;
1188: var studentID = (name != '' ? name : formname["unamedom"+i].value);
1189: var resp = confirm("You did not assign a score for "+studentID+
1190: ", part "+partid+". Continue?");
1191: if (resp == false) {
1192: formname["GD_BOX"+i+"_"+partid].focus();
1193: return false;
1194: }
1195: }
1196: }
1197:
1198: }
1199: }
1200:
1201: }
1202: if (val == "Grade Student") {
1203: formname.showgrading.value = "yes";
1204: if (formname.Status.value == "") {
1205: formname.Status.value = "Active";
1206: }
1207: formname.studentNo.value = total;
1208: }
1209: formname.submit();
1210: }
1211:
1212: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
1213: function checkSubmitPage(formname,total) {
1214: noscore = new Array(100);
1215: var ptr = 0;
1216: for (i=1;i<total;i++) {
1217: var partid = formname["q_"+i].value;
1218: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1219: var points = formname["GD_BOX"+i+"_"+partid].value;
1220: var status = formname["solved"+i+"_"+partid].value;
1221: if (points == "" && status != "correct_by_student") {
1222: noscore[ptr] = i;
1223: ptr++;
1224: }
1225: }
1226: }
1227: if (ptr != 0) {
1228: var sense = ptr == 1 ? ": " : "s: ";
1229: var prolist = "";
1230: if (ptr == 1) {
1231: prolist = noscore[0];
1232: } else {
1233: var i = 0;
1234: while (i < ptr-1) {
1235: prolist += noscore[i]+", ";
1236: i++;
1237: }
1238: prolist += "and "+noscore[i];
1239: }
1240: var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
1241: if (resp == false) {
1242: return false;
1243: }
1244: }
1245:
1246: formname.submit();
1247: }
1248: </script>
1249: SUBJAVASCRIPT
1250: }
1251:
1252: #--- javascript for essay type problem --
1253: sub sub_page_kw_js {
1254: my $request = shift;
1255: my $iconpath = $request->dir_config('lonIconsURL');
1256: &commonJSfunctions($request);
1257:
1258: my $inner_js_msg_central=<<INNERJS;
1259: <script text="text/javascript">
1260: function checkInput() {
1261: opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
1262: var nmsg = opener.document.SCORE.savemsgN.value;
1263: var usrctr = document.msgcenter.usrctr.value;
1264: var newval = opener.document.SCORE["newmsg"+usrctr];
1265: newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
1266:
1267: var msgchk = "";
1268: if (document.msgcenter.subchk.checked) {
1269: msgchk = "msgsub,";
1270: }
1271: var includemsg = 0;
1272: for (var i=1; i<=nmsg; i++) {
1273: var opnmsg = opener.document.SCORE["savemsg"+i];
1274: var frmmsg = document.msgcenter["msg"+i];
1275: opnmsg.value = opener.checkEntities(frmmsg.value);
1276: var showflg = opener.document.SCORE["shownOnce"+i];
1277: showflg.value = "1";
1278: var chkbox = document.msgcenter["msgn"+i];
1279: if (chkbox.checked) {
1280: msgchk += "savemsg"+i+",";
1281: includemsg = 1;
1282: }
1283: }
1284: if (document.msgcenter.newmsgchk.checked) {
1285: msgchk += "newmsg"+usrctr;
1286: includemsg = 1;
1287: }
1288: imgformname = opener.document.SCORE["mailicon"+usrctr];
1289: imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
1290: var includemsg = opener.document.SCORE["includemsg"+usrctr];
1291: includemsg.value = msgchk;
1292:
1293: self.close()
1294:
1295: }
1296: </script>
1297: INNERJS
1298:
1299: my $inner_js_highlight_central=<<INNERJS;
1300: <script type="text/javascript">
1301: function updateChoice(flag) {
1302: opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
1303: opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
1304: opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
1305: opener.document.SCORE.refresh.value = "on";
1306: if (opener.document.SCORE.keywords.value!=""){
1307: opener.document.SCORE.submit();
1308: }
1309: self.close()
1310: }
1311: </script>
1312: INNERJS
1313:
1314: my $start_page_msg_central =
1315: &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
1316: {'js_ready' => 1,
1317: 'only_body' => 1,
1318: 'bgcolor' =>'#FFFFFF',});
1319: my $end_page_msg_central =
1320: &Apache::loncommon::end_page({'js_ready' => 1});
1321:
1322:
1323: my $start_page_highlight_central =
1324: &Apache::loncommon::start_page('Highlight Central',
1325: $inner_js_highlight_central,
1326: {'js_ready' => 1,
1327: 'only_body' => 1,
1328: 'bgcolor' =>'#FFFFFF',});
1329: my $end_page_highlight_central =
1330: &Apache::loncommon::end_page({'js_ready' => 1});
1331:
1332: my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1333: $docopen=~s/^document\.//;
1334: $request->print(<<SUBJAVASCRIPT);
1335: <script type="text/javascript" language="javascript">
1336:
1337: //===================== Show list of keywords ====================
1338: function keywords(formname) {
1339: var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1340: if (nret==null) return;
1341: formname.keywords.value = nret;
1342:
1343: if (formname.keywords.value != "") {
1344: formname.refresh.value = "on";
1345: formname.submit();
1346: }
1347: return;
1348: }
1349:
1350: //===================== Script to view submitted by ==================
1351: function viewSubmitter(submitter) {
1352: document.SCORE.refresh.value = "on";
1353: document.SCORE.NCT.value = "1";
1354: document.SCORE.unamedom0.value = submitter;
1355: document.SCORE.submit();
1356: return;
1357: }
1358:
1359: //===================== Script to add keyword(s) ==================
1360: function getSel() {
1361: if (document.getSelection) txt = document.getSelection();
1362: else if (document.selection) txt = document.selection.createRange().text;
1363: else return;
1364: var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
1365: if (cleantxt=="") {
1366: alert("Please select a word or group of words from document and then click this link.");
1367: return;
1368: }
1369: var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
1370: if (nret==null) return;
1371: document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1372: if (document.SCORE.keywords.value != "") {
1373: document.SCORE.refresh.value = "on";
1374: document.SCORE.submit();
1375: }
1376: return;
1377: }
1378:
1379: //====================== Script for composing message ==============
1380: // preload images
1381: img1 = new Image();
1382: img1.src = "$iconpath/mailbkgrd.gif";
1383: img2 = new Image();
1384: img2.src = "$iconpath/mailto.gif";
1385:
1386: function msgCenter(msgform,usrctr,fullname) {
1387: var Nmsg = msgform.savemsgN.value;
1388: savedMsgHeader(Nmsg,usrctr,fullname);
1389: var subject = msgform.msgsub.value;
1390: var msgchk = document.SCORE["includemsg"+usrctr].value;
1391: re = /msgsub/;
1392: var shwsel = "";
1393: if (re.test(msgchk)) { shwsel = "checked" }
1394: subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
1395: displaySubject(checkEntities(subject),shwsel);
1396: for (var i=1; i<=Nmsg; i++) {
1397: var testmsg = "savemsg"+i+",";
1398: re = new RegExp(testmsg,"g");
1399: shwsel = "";
1400: if (re.test(msgchk)) { shwsel = "checked" }
1401: var message = document.SCORE["savemsg"+i].value;
1402: message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1403: displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
1404: //any < is already converted to <, etc. However, only once!!
1405: }
1406: newmsg = document.SCORE["newmsg"+usrctr].value;
1407: shwsel = "";
1408: re = /newmsg/;
1409: if (re.test(msgchk)) { shwsel = "checked" }
1410: newMsg(newmsg,shwsel);
1411: msgTail();
1412: return;
1413: }
1414:
1415: function checkEntities(strx) {
1416: if (strx.length == 0) return strx;
1417: var orgStr = ["&", "<", ">", '"'];
1418: var newStr = ["&", "<", ">", """];
1419: var counter = 0;
1420: while (counter < 4) {
1421: strx = strReplace(strx,orgStr[counter],newStr[counter]);
1422: counter++;
1423: }
1424: return strx;
1425: }
1426:
1427: function strReplace(strx, orgStr, newStr) {
1428: return strx.split(orgStr).join(newStr);
1429: }
1430:
1431: function savedMsgHeader(Nmsg,usrctr,fullname) {
1432: var height = 70*Nmsg+250;
1433: var scrollbar = "no";
1434: if (height > 600) {
1435: height = 600;
1436: scrollbar = "yes";
1437: }
1438: var xpos = (screen.width-600)/2;
1439: xpos = (xpos < 0) ? '0' : xpos;
1440: var ypos = (screen.height-height)/2-30;
1441: ypos = (ypos < 0) ? '0' : ypos;
1442:
1443: pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1444: pWin.focus();
1445: pDoc = pWin.document;
1446: pDoc.$docopen;
1447: pDoc.write('$start_page_msg_central');
1448:
1449: pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
1450: pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1451: pDoc.write("<h3><span class=\\"LC_info\\"> Compose Message for \"+fullname+\"</span></h3><br /><br />");
1452:
1453: pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
1454: pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
1455: pDoc.write("<td><b>Type</b></td><td><b>Include</b></td><td><b>Message</td></tr>");
1456: }
1457: function displaySubject(msg,shwsel) {
1458: pDoc = pWin.document;
1459: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1460: pDoc.write("<td>Subject</td>");
1461: pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
1462: pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"></td></tr>");
1463: }
1464:
1465: function displaySavedMsg(ctr,msg,shwsel) {
1466: pDoc = pWin.document;
1467: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1468: pDoc.write("<td align=\\"center\\">"+ctr+"</td>");
1469: pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"></td>");
1470: pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"</textarea></td></tr>");
1471: }
1472:
1473: function newMsg(newmsg,shwsel) {
1474: pDoc = pWin.document;
1475: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1476: pDoc.write("<td align=\\"center\\">New</td>");
1477: pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
1478: pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"</textarea></td></tr>");
1479: }
1480:
1481: function msgTail() {
1482: pDoc = pWin.document;
1483: pDoc.write("</table>");
1484: pDoc.write("</td></tr></table> ");
1485: pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\"> ");
1486: pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1487: pDoc.write("</form>");
1488: pDoc.write('$end_page_msg_central');
1489: pDoc.close();
1490: }
1491:
1492: //====================== Script for keyword highlight options ==============
1493: function kwhighlight() {
1494: var kwclr = document.SCORE.kwclr.value;
1495: var kwsize = document.SCORE.kwsize.value;
1496: var kwstyle = document.SCORE.kwstyle.value;
1497: var redsel = "";
1498: var grnsel = "";
1499: var blusel = "";
1500: if (kwclr=="red") {var redsel="checked"};
1501: if (kwclr=="green") {var grnsel="checked"};
1502: if (kwclr=="blue") {var blusel="checked"};
1503: var sznsel = "";
1504: var sz1sel = "";
1505: var sz2sel = "";
1506: if (kwsize=="0") {var sznsel="checked"};
1507: if (kwsize=="+1") {var sz1sel="checked"};
1508: if (kwsize=="+2") {var sz2sel="checked"};
1509: var synsel = "";
1510: var syisel = "";
1511: var sybsel = "";
1512: if (kwstyle=="") {var synsel="checked"};
1513: if (kwstyle=="<i>") {var syisel="checked"};
1514: if (kwstyle=="<b>") {var sybsel="checked"};
1515: highlightCentral();
1516: highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
1517: highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
1518: highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
1519: highlightend();
1520: return;
1521: }
1522:
1523: function highlightCentral() {
1524: // if (window.hwdWin) window.hwdWin.close();
1525: var xpos = (screen.width-400)/2;
1526: xpos = (xpos < 0) ? '0' : xpos;
1527: var ypos = (screen.height-330)/2-30;
1528: ypos = (ypos < 0) ? '0' : ypos;
1529:
1530: hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1531: hwdWin.focus();
1532: var hDoc = hwdWin.document;
1533: hDoc.$docopen;
1534: hDoc.write('$start_page_highlight_central');
1535: hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1536: hDoc.write("<h3><span class=\\"LC_info\\"> Keyword Highlight Options</span></h3><br /><br />");
1537:
1538: hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
1539: hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
1540: hDoc.write("<td><b>Text Color</b></td><td><b>Font Size</b></td><td><b>Font Style</td></tr>");
1541: }
1542:
1543: function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) {
1544: var hDoc = hwdWin.document;
1545: hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1546: hDoc.write("<td align=\\"left\\">");
1547: hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+"> "+clrtxt+"</td>");
1548: hDoc.write("<td align=\\"left\\">");
1549: hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+"> "+sztxt+"</td>");
1550: hDoc.write("<td align=\\"left\\">");
1551: hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+"> "+sytxt+"</td>");
1552: hDoc.write("</tr>");
1553: }
1554:
1555: function highlightend() {
1556: var hDoc = hwdWin.document;
1557: hDoc.write("</table>");
1558: hDoc.write("</td></tr></table> ");
1559: hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\"> ");
1560: hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1561: hDoc.write("</form>");
1562: hDoc.write('$end_page_highlight_central');
1563: hDoc.close();
1564: }
1565:
1566: </script>
1567: SUBJAVASCRIPT
1568: }
1569:
1570: sub get_increment {
1571: my $increment = $env{'form.increment'};
1572: if ($increment != 1 && $increment != .5 && $increment != .25 &&
1573: $increment != .1) {
1574: $increment = 1;
1575: }
1576: return $increment;
1577: }
1578:
1579: #--- displays the grading box, used in essay type problem and grading by page/sequence
1580: sub gradeBox {
1581: my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1582: my $checkIcon = '<img alt="'.&mt('Check Mark').
1583: '" src="'.$request->dir_config('lonIconsURL').
1584: '/check.gif" height="16" border="0" />';
1585: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1586: my $wgtmsg = ($wgt > 0 ? '(problem weight)' :
1587: '<span class="LC_info">problem weight assigned by computer</span>');
1588: $wgt = ($wgt > 0 ? $wgt : '1');
1589: my $score = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1590: '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1591: my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1592: my $display_part=&get_display_part($partid,$symb);
1593: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
1594: [$partid]);
1595: my $aggtries = $$record{'resource.'.$partid.'.tries'};
1596: if ($last_resets{$partid}) {
1597: $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
1598: }
1599: $result.='<table border="0"><tr><td>'.
1600: '<b>Part: </b>'.$display_part.' <b>Points: </b></td><td>'."\n";
1601: my $ctr = 0;
1602: my $thisweight = 0;
1603: my $increment = &get_increment();
1604: $result.='<table border="0"><tr>'."\n"; # display radio buttons in a nice table 10 across
1605: while ($thisweight<=$wgt) {
1606: $result.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1607: 'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1608: $thisweight.')" value="'.$thisweight.'" '.
1609: ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1610: $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1611: $thisweight += $increment;
1612: $ctr++;
1613: }
1614: $result.='</tr></table>';
1615: $result.='</td><td> <b>or</b> </td>'."\n";
1616: $result.='<td><input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1617: ($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1618: 'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1619: $wgt.')" /></td>'."\n";
1620: $result.='<td>/'.$wgt.' '.$wgtmsg.
1621: ($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? ' '.$checkIcon : '').
1622: ' </td><td>'."\n";
1623: $result.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
1624: 'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1625: if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1626: $result.='<option></option>'.
1627: '<option selected="selected">excused</option>';
1628: } else {
1629: $result.='<option selected="selected"></option>'.
1630: '<option>excused</option>';
1631: }
1632: $result.='<option>reset status</option></select>'."\n";
1633: $result.=" \n";
1634: $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
1635: '<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
1636: '<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1637: $$record{'resource.'.$partid.'.solved'}.'" />'."\n".
1638: '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
1639: $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
1640: '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
1641: $aggtries.'" />'."\n";
1642: $result.='</td></tr></table>'."\n";
1643: $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
1644: return $result;
1645: }
1646:
1647: sub handback_box {
1648: my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
1649: my ($partlist,$handgrade,$responseType) = &response_type($symb);
1650: my (@respids);
1651: my @part_response_id = &flatten_responseType($responseType);
1652: foreach my $part_response_id (@part_response_id) {
1653: my ($part,$resp) = @{ $part_response_id };
1654: if ($part eq $partid) {
1655: push(@respids,$resp);
1656: }
1657: }
1658: my $result;
1659: foreach my $respid (@respids) {
1660: my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
1661: my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
1662: next if (!@$files);
1663: my $file_counter = 1;
1664: foreach my $file (@$files) {
1665: if ($file =~ /\/portfolio\//) {
1666: my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1667: my ($name,$version,$ext) = &file_name_version_ext($file_disp);
1668: $file_disp = "$name.$ext";
1669: $file = $file_path.$file_disp;
1670: $result.=&mt('Return commented version of [_1] to student.',
1671: '<span class="LC_filename">'.$file_disp.'</span>');
1672: $result.='<input type="file" name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1673: $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1674: $result.='(File will be uploaded when you click on Save & Next below.)<br />';
1675: $file_counter++;
1676: }
1677: }
1678: }
1679: return $result;
1680: }
1681:
1682: sub show_problem {
1683: my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1684: my $rendered;
1685: my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1686: &Apache::lonxml::remember_problem_counter();
1687: if ($mode eq 'both' or $mode eq 'text') {
1688: $rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1689: $env{'request.course.id'},
1690: undef,\%form);
1691: }
1692: if ($removeform) {
1693: $rendered=~s|<form(.*?)>||g;
1694: $rendered=~s|</form>||g;
1695: $rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1696: }
1697: my $companswer;
1698: if ($mode eq 'both' or $mode eq 'answer') {
1699: &Apache::lonxml::restore_problem_counter();
1700: $companswer=
1701: &Apache::loncommon::get_student_answers($symb,$uname,$udom,
1702: $env{'request.course.id'},
1703: %form);
1704: }
1705: if ($removeform) {
1706: $companswer=~s|<form(.*?)>||g;
1707: $companswer=~s|</form>||g;
1708: $companswer=~s|name="submit"|name="would_have_been_submit"|g;
1709: }
1710: my $result.='<table border="0" width="100%"><tr><td bgcolor="#777777">';
1711: $result.='<table border="0" width="100%">';
1712: if ($viewon) {
1713: $result.='<tr><td bgcolor="#e6ffff"><b> ';
1714: if ($mode eq 'both' or $mode eq 'text') {
1715: $result.='View of the problem - ';
1716: } else {
1717: $result.='Correct answer: ';
1718: }
1719: $result.=$env{'form.fullname'}.'</b></td></tr>';
1720: }
1721: if ($mode eq 'both') {
1722: $result.='<tr><td bgcolor="#ffffff">'.$rendered.'<br />';
1723: $result.='<b>Correct answer:</b><br />'.$companswer;
1724: } elsif ($mode eq 'text') {
1725: $result.='<tr><td bgcolor="#ffffff">'.$rendered;
1726: } elsif ($mode eq 'answer') {
1727: $result.='<tr><td bgcolor="#ffffff">'.$companswer;
1728: }
1729: $result.='</td></tr></table>';
1730: $result.='</td></tr></table><br />';
1731: return $result;
1732: }
1733:
1734: sub files_exist {
1735: my ($r, $symb) = @_;
1736: my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1737:
1738: foreach my $student (@students) {
1739: my ($uname,$udom,$fullname) = split(/:/,$student);
1740: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
1741: $udom,$uname);
1742: my ($string,$timestamp)= &get_last_submission(\%record);
1743: foreach my $submission (@$string) {
1744: my ($partid,$respid) =
1745: ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1746: my $files=&get_submitted_files($udom,$uname,$partid,$respid,
1747: \%record);
1748: return 1 if (@$files);
1749: }
1750: }
1751: return 0;
1752: }
1753:
1754: sub download_all_link {
1755: my ($r,$symb) = @_;
1756: my $all_students =
1757: join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
1758:
1759: my $parts =
1760: join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
1761:
1762: my $identifier = &Apache::loncommon::get_cgi_id();
1763: &Apache::lonnet::appenv('cgi.'.$identifier.'.students' => $all_students,
1764: 'cgi.'.$identifier.'.symb' => $symb,
1765: 'cgi.'.$identifier.'.parts' => $parts,);
1766: $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
1767: &mt('Download All Submitted Documents').'</a>');
1768: return
1769: }
1770:
1771: sub build_section_inputs {
1772: my $section_inputs;
1773: if ($env{'form.section'} eq '') {
1774: $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
1775: } else {
1776: my @sections = &Apache::loncommon::get_env_multiple('form.section');
1777: foreach my $section (@sections) {
1778: $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
1779: }
1780: }
1781: return $section_inputs;
1782: }
1783:
1784: # --------------------------- show submissions of a student, option to grade
1785: sub submission {
1786: my ($request,$counter,$total) = @_;
1787:
1788: my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
1789: $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
1790: my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
1791: $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1792: my $symb = &get_symb($request);
1793: if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1794:
1795: if (!&canview($usec)) {
1796: $request->print('<span class="LC_warning">Unable to view requested student.('.
1797: $uname.':'.$udom.' in section '.$usec.' in course id '.
1798: $env{'request.course.id'}.')</span>');
1799: $request->print(&show_grading_menu_form($symb));
1800: return;
1801: }
1802:
1803: if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
1804: if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
1805: if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
1806: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1807: my $checkIcon = '<img alt="'.&mt('Check Mark').
1808: '" src="'.$request->dir_config('lonIconsURL').
1809: '/check.gif" height="16" border="0" />';
1810:
1811: my %old_essays;
1812: # header info
1813: if ($counter == 0) {
1814: &sub_page_js($request);
1815: &sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
1816: $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ?
1817: &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1818: if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1819: &download_all_link($request, $symb);
1820: }
1821: $request->print('<h3> <span class="LC_info">Submission Record</span></h3>'."\n".
1822: '<h4> <b>Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n");
1823:
1824: if ($env{'form.handgrade'} eq 'no') {
1825: my $checkMark='<br /><br /> <b>Note:</b> Part(s) graded correct by the computer is marked with a '.
1826: $checkIcon.' symbol.'."\n";
1827: $request->print($checkMark);
1828: }
1829:
1830: # option to display problem, only once else it cause problems
1831: # with the form later since the problem has a form.
1832: if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1833: my $mode;
1834: if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1835: $mode='both';
1836: } elsif ($env{'form.vProb'} eq 'yes') {
1837: $mode='text';
1838: } elsif ($env{'form.vAns'} eq 'yes') {
1839: $mode='answer';
1840: }
1841: &Apache::lonxml::clear_problem_counter();
1842: $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1843: }
1844:
1845: # kwclr is the only variable that is guaranteed to be non blank
1846: # if this subroutine has been called once.
1847: my %keyhash = ();
1848: if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1849: %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1850: $env{'course.'.$env{'request.course.id'}.'.domain'},
1851: $env{'course.'.$env{'request.course.id'}.'.num'});
1852:
1853: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1854: $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
1855: $env{'form.kwclr'} = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
1856: $env{'form.kwsize'} = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
1857: $env{'form.kwstyle'} = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
1858: $env{'form.msgsub'} = $keyhash{$symb.'_subject'} ne '' ?
1859: $keyhash{$symb.'_subject'} : $env{'form.probTitle'};
1860: $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1861: }
1862: my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1863: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1864: $request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1865: '<input type="hidden" name="command" value="handgrade" />'."\n".
1866: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1867: '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
1868: '<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1869: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
1870: '<input type="hidden" name="refresh" value="off" />'."\n".
1871: '<input type="hidden" name="studentNo" value="" />'."\n".
1872: '<input type="hidden" name="gradeOpt" value="" />'."\n".
1873: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1874: '<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
1875: '<input type="hidden" name="vProb" value="'.$env{'form.vProb'}.'" />'."\n".
1876: '<input type="hidden" name="vAns" value="'.$env{'form.vAns'}.'" />'."\n".
1877: '<input type="hidden" name="lastSub" value="'.$env{'form.lastSub'}.'" />'."\n".
1878: &build_section_inputs().
1879: '<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1880: '<input type="hidden" name="handgrade" value="'.$env{'form.handgrade'}.'" />'."\n".
1881: '<input type="hidden" name="NCT"'.
1882: ' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1883: if ($env{'form.handgrade'} eq 'yes') {
1884: $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
1885: '<input type="hidden" name="kwclr" value="'.$env{'form.kwclr'}.'" />'."\n".
1886: '<input type="hidden" name="kwsize" value="'.$env{'form.kwsize'}.'" />'."\n".
1887: '<input type="hidden" name="kwstyle" value="'.$env{'form.kwstyle'}.'" />'."\n".
1888: '<input type="hidden" name="msgsub" value="'.$env{'form.msgsub'}.'" />'."\n".
1889: '<input type="hidden" name="shownSub" value="0" />'."\n".
1890: '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1891: foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
1892: $request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
1893: }
1894: }
1895:
1896: my ($cts,$prnmsg) = (1,'');
1897: while ($cts <= $env{'form.savemsgN'}) {
1898: $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1899: (!exists($keyhash{$symb.'_savemsg'.$cts}) ?
1900: &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1901: &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1902: '" />'."\n".
1903: '<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1904: $cts++;
1905: }
1906: $request->print($prnmsg);
1907:
1908: if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1909: #
1910: # Print out the keyword options line
1911: #
1912: $request->print(<<KEYWORDS);
1913: <b>Keyword Options:</b>
1914: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>
1915: <a href="#" onMouseDown="javascript:getSel(); return false"
1916: CLASS="page">Paste Selection to List</a>
1917: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1918: KEYWORDS
1919: #
1920: # Load the other essays for similarity check
1921: #
1922: my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1923: my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1924: $apath=&escape($apath);
1925: $apath=~s/\W/\_/gs;
1926: %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1927: }
1928: }
1929:
1930: # This is where output for one specific student would start
1931: my $bgcolor='#DDEEDD';
1932: if (int($counter/2) eq $counter) { $bgcolor='#DDDDEE'; }
1933: $request->print("\n\n".
1934: '<p><table border="2"><tr><th bgcolor="'.$bgcolor.'">'.$env{'form.fullname'}.'</th></tr><tr><td bgcolor="'.$bgcolor.'">');
1935:
1936: if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1937: my $mode;
1938: if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1939: $mode='both';
1940: } elsif ($env{'form.vProb'} eq 'all' ) {
1941: $mode='text';
1942: } elsif ($env{'form.vAns'} eq 'all') {
1943: $mode='answer';
1944: }
1945: &Apache::lonxml::clear_problem_counter();
1946: $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode));
1947: }
1948:
1949: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1950: my ($partlist,$handgrade,$responseType) = &response_type($symb);
1951:
1952: # Display student info
1953: $request->print(($counter == 0 ? '' : '<br />'));
1954: my $result='<table border="0" width="100%"><tr><td bgcolor="#777777">'."\n".
1955: '<table border="0" width="100%"><tr bgcolor="#edffff"><td>'."\n";
1956:
1957: $result.='<b>Fullname: </b>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'<br />'."\n";
1958: $result.='<input type="hidden" name="name'.$counter.
1959: '" value="'.$env{'form.fullname'}.'" />'."\n";
1960:
1961: # If any part of the problem is an essay-response (handgraded), then check for collaborators
1962: my @col_fullnames;
1963: my ($classlist,$fullname);
1964: if ($env{'form.handgrade'} eq 'yes') {
1965: ($classlist,undef,$fullname) = &getclasslist('all','0');
1966: for (keys (%$handgrade)) {
1967: my $ncol = &Apache::lonnet::EXT('resource.'.$_.
1968: '.maxcollaborators',
1969: $symb,$udom,$uname);
1970: next if ($ncol <= 0);
1971: s/\_/\./g;
1972: next if ($record{'resource.'.$_.'.collaborators'} eq '');
1973: my @goodcollaborators = ();
1974: my @badcollaborators = ();
1975: foreach (split(/,?\s+/,$record{'resource.'.$_.'.collaborators'})) {
1976: $_ =~ s/[\$\^\(\)]//g;
1977: next if ($_ eq '');
1978: my ($co_name,$co_dom) = split /\@|:/,$_;
1979: $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
1980: next if ($co_name eq $uname && $co_dom eq $udom);
1981: # Doing this grep allows 'fuzzy' specification
1982: my @Matches = grep /^$co_name:$co_dom$/i,keys %$classlist;
1983: if (! scalar(@Matches)) {
1984: push @badcollaborators,$_;
1985: } else {
1986: push @goodcollaborators, @Matches;
1987: }
1988: }
1989: if (scalar(@goodcollaborators) != 0) {
1990: $result.='<b>Collaborators: </b>';
1991: foreach (@goodcollaborators) {
1992: my ($lastname,$givenn) = split(/,/,$$fullname{$_});
1993: push @col_fullnames, $givenn.' '.$lastname;
1994: $result.=$$fullname{$_}.' ';
1995: }
1996: $result.='<br />'."\n";
1997: my ($part)=split(/\./,$_);
1998: $result.='<input type="hidden" name="collaborator'.$counter.
1999: '" value="'.$part.':'.(join ':',@goodcollaborators).'" />'.
2000: "\n";
2001: }
2002: if (scalar(@badcollaborators) > 0) {
2003: $result.='<table border="0"><tr bgcolor="#ffbbbb"><td>';
2004: $result.='This student has submitted ';
2005: $result.=(scalar(@badcollaborators) == 1) ? 'an invalid collaborator' : 'invalid collaborators';
2006: $result .= ': '.join(', ',@badcollaborators);
2007: $result .= '</td></tr></table>';
2008: }
2009: if (scalar(@badcollaborators > $ncol)) {
2010: $result .= '<table border="0"><tr bgcolor="#ffbbbb"><td>';
2011: $result .= 'This student has submitted too many '.
2012: 'collaborators. Maximum is '.$ncol.'.';
2013: $result .= '</td></tr></table>';
2014: }
2015: }
2016: }
2017: $request->print($result."\n");
2018:
2019: # print student answer/submission
2020: # Options are (1) Handgaded submission only
2021: # (2) Last submission, includes submission that is not handgraded
2022: # (for multi-response type part)
2023: # (3) Last submission plus the parts info
2024: # (4) The whole record for this student
2025: if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
2026: my ($string,$timestamp)= &get_last_submission(\%record);
2027: my $lastsubonly=''.
2028: ($$timestamp eq '' ? '' : '<b>Date Submitted:</b> '.
2029: $$timestamp)."</td></tr>\n";
2030: if ($$timestamp eq '') {
2031: $lastsubonly.='<tr><td bgcolor="#ffffe6">'.$$string[0];
2032: } else {
2033: my %seenparts;
2034: my @part_response_id = &flatten_responseType($responseType);
2035: foreach my $part (@part_response_id) {
2036: next if ($env{'form.lastSub'} eq 'hdgrade'
2037: && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
2038:
2039: my ($partid,$respid) = @{ $part };
2040: my $display_part=&get_display_part($partid,$symb);
2041: if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
2042: if (exists($seenparts{$partid})) { next; }
2043: $seenparts{$partid}=1;
2044: my $submitby='<b>Part:</b> '.$display_part.
2045: ' <b>Collaborative submission by:</b> '.
2046: '<a href="javascript:viewSubmitter(\''.
2047: $env{"form.$uname:$udom:$partid:submitted_by"}.
2048: '\');" target="_self">'.
2049: $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
2050: $request->print($submitby);
2051: next;
2052: }
2053: my $responsetype = $responseType->{$partid}->{$respid};
2054: if (!exists($record{"resource.$partid.$respid.submission"})) {
2055: $lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
2056: $display_part.' <span class="LC_internal_info">( ID '.$respid.
2057: ' )</span> '.
2058: '<span class="LC_warning">Nothing submitted - no attempts</span><br /><br />';
2059: next;
2060: }
2061: foreach (@$string) {
2062: my ($partid,$respid) = /^resource\.([^\.]*)\.([^\.]*)\.submission/;
2063: if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
2064: my ($ressub,$subval) = split(/:/,$_,2);
2065: # Similarity check
2066: my $similar='';
2067: if($env{'form.checkPlag'}){
2068: my ($oname,$odom,$ocrsid,$oessay,$osim)=
2069: &most_similar($uname,$udom,$subval,\%old_essays);
2070: if ($osim) {
2071: $osim=int($osim*100.0);
2072: my %old_course_desc =
2073: &Apache::lonnet::coursedescription($ocrsid,
2074: {'one_time' => 1});
2075:
2076: $similar="<hr /><h3><span class=\"LC_warning\">".
2077: &mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
2078: $osim,
2079: &Apache::loncommon::plainname($oname,$odom),
2080: $oname,$odom,
2081: $old_course_desc{'description'},
2082: $old_course_desc{'num'},
2083: $old_course_desc{'domain'}).
2084: '</span></h3><blockquote><i>'.
2085: &keywords_highlight($oessay).
2086: '</i></blockquote><hr />';
2087: }
2088: }
2089: my $order=&get_order($partid,$respid,$symb,$uname,$udom);
2090: if ($env{'form.lastSub'} eq 'lastonly' ||
2091: ($env{'form.lastSub'} eq 'hdgrade' &&
2092: $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
2093: my $display_part=&get_display_part($partid,$symb);
2094: $lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
2095: $display_part.' <span class="LC_internal_info">( ID '.$respid.
2096: ' )</span> ';
2097: my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
2098: if (@$files) {
2099: $lastsubonly.='<br /><span class="LC_warning">Like all files provided by users, this file may contain virusses</span><br />';
2100: my $file_counter = 0;
2101: foreach my $file (@$files) {
2102: $file_counter ++;
2103: &Apache::lonnet::allowuploaded('/adm/grades',$file);
2104: $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
2105: }
2106: $lastsubonly.='<br />';
2107: }
2108: $lastsubonly.='<b>Submitted Answer: </b>'.
2109: &cleanRecord($subval,$responsetype,$symb,$partid,
2110: $respid,\%record,$order);
2111: if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
2112: }
2113: }
2114: }
2115: }
2116: $lastsubonly.='</td></tr><tr bgcolor="#ffffff"><td>'."\n";
2117: $request->print($lastsubonly);
2118: } elsif ($env{'form.lastSub'} eq 'datesub') {
2119: my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
2120: $request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
2121: } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
2122: $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
2123: $env{'request.course.id'},
2124: $last,'.submission',
2125: 'Apache::grades::keywords_highlight'));
2126: }
2127:
2128: $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
2129: .$udom.'" />'."\n");
2130:
2131: # return if view submission with no grading option
2132: if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
2133: my $toGrade.='<input type="button" value="Grade Student" '.
2134: 'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
2135: .$counter.'\');" target="_self" /> '."\n" if (&canmodify($usec));
2136: $toGrade.='</td></tr></table></td></tr></table>'."\n";
2137: if (($env{'form.command'} eq 'submission') ||
2138: ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
2139: $toGrade.='</form>'.&show_grading_menu_form($symb);
2140: }
2141: $request->print($toGrade);
2142: return;
2143: } else {
2144: $request->print('</td></tr></table></td></tr></table>'."\n");
2145: }
2146:
2147: # essay grading message center
2148: if ($env{'form.handgrade'} eq 'yes') {
2149: my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
2150: my $msgfor = $givenn.' '.$lastname;
2151: if (scalar(@col_fullnames) > 0) {
2152: my $lastone = pop @col_fullnames;
2153: $msgfor .= ', '.(join ', ',@col_fullnames).' and '.$lastone.'.';
2154: }
2155: $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
2156: $result='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
2157: '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
2158: $result.=' <a href="javascript:msgCenter(document.SCORE,'.$counter.
2159: ',\''.$msgfor.'\');" target="_self">'.
2160: &mt('Compose message to student').(scalar(@col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
2161: &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
2162: '<img src="'.$request->dir_config('lonIconsURL').
2163: '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
2164: '<br /> ('.
2165: &mt('Message will be sent when you click on Save & Next below.').")\n";
2166: $request->print($result);
2167: }
2168: if ($perm{'vgr'}) {
2169: $request->print('<br />'.
2170: &Apache::loncommon::track_student_link(&mt('View recent activity'),
2171: $uname,$udom,'check'));
2172: }
2173: if ($perm{'opa'}) {
2174: $request->print('<br />'.
2175: &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
2176: $uname,$udom,$symb,'check'));
2177: }
2178:
2179: my %seen = ();
2180: my @partlist;
2181: my @gradePartRespid;
2182: my @part_response_id = &flatten_responseType($responseType);
2183: foreach my $part_response_id (@part_response_id) {
2184: my ($partid,$respid) = @{ $part_response_id };
2185: my $part_resp = join('_',@{ $part_response_id });
2186: next if ($seen{$partid} > 0);
2187: $seen{$partid}++;
2188: next if ($$handgrade{$part_resp} ne 'yes'
2189: && $env{'form.lastSub'} eq 'hdgrade');
2190: push @partlist,$partid;
2191: push @gradePartRespid,$partid.'.'.$respid;
2192: $request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
2193: }
2194: $result='<input type="hidden" name="partlist'.$counter.
2195: '" value="'.(join ":",@partlist).'" />'."\n";
2196: $result.='<input type="hidden" name="gradePartRespid'.
2197: '" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
2198: my $ctr = 0;
2199: while ($ctr < scalar(@partlist)) {
2200: $result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
2201: $partlist[$ctr].'" />'."\n";
2202: $ctr++;
2203: }
2204: $request->print($result.'</td></tr></table></td></tr></table>'."\n");
2205:
2206: # Done with printing info for one student
2207:
2208: $request->print('</td></tr></table></p>');
2209:
2210:
2211: # print end of form
2212: if ($counter == $total) {
2213: my $endform='<table border="0"><tr><td>'."\n";
2214: $endform.='<input type="button" value="Save & Next" '.
2215: 'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
2216: $total.','.scalar(@partlist).');" target="_self" /> '."\n";
2217: my $ntstu ='<select name="NTSTU">'.
2218: '<option>1</option><option>2</option>'.
2219: '<option>3</option><option>5</option>'.
2220: '<option>7</option><option>10</option></select>'."\n";
2221: my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
2222: $ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
2223: $endform.=$ntstu.'student(s) ';
2224: $endform.='<input type="button" value="Previous" '.
2225: 'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> '."\n".
2226: '<input type="button" value="Next" '.
2227: 'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> ';
2228: $endform.='(Next and Previous (student) do not save the scores.)'."\n" ;
2229: $endform.="<input type='hidden' value='".&get_increment().
2230: "' name='increment' />";
2231: $endform.='</td><tr></table></form>';
2232: $endform.=&show_grading_menu_form($symb);
2233: $request->print($endform);
2234: }
2235: return '';
2236: }
2237:
2238: #--- Retrieve the last submission for all the parts
2239: sub get_last_submission {
2240: my ($returnhash)=@_;
2241: my (@string,$timestamp);
2242: if ($$returnhash{'version'}) {
2243: my %lasthash=();
2244: my ($version);
2245: for ($version=1;$version<=$$returnhash{'version'};$version++) {
2246: foreach my $key (sort(split(/\:/,
2247: $$returnhash{$version.':keys'}))) {
2248: $lasthash{$key}=$$returnhash{$version.':'.$key};
2249: $timestamp =
2250: scalar(localtime($$returnhash{$version.':timestamp'}));
2251: }
2252: }
2253: foreach my $key (keys(%lasthash)) {
2254: next if ($key !~ /\.submission$/);
2255:
2256: my ($partid,$foo) = split(/submission$/,$key);
2257: my $draft = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
2258: '<span class="LC_warning">Draft Copy</span> ' : '';
2259: push(@string, join(':', $key, $draft.$lasthash{$key}));
2260: }
2261: }
2262: if (!@string) {
2263: $string[0] =
2264: '<span class="LC_warning">Nothing submitted - no attempts.</span>';
2265: }
2266: return (\@string,\$timestamp);
2267: }
2268:
2269: #--- High light keywords, with style choosen by user.
2270: sub keywords_highlight {
2271: my $string = shift;
2272: my $size = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
2273: my $styleon = $env{'form.kwstyle'} eq '' ? '' : $env{'form.kwstyle'};
2274: (my $styleoff = $styleon) =~ s/\</\<\//;
2275: my @keylist = split(/[,\s+]/,$env{'form.keywords'});
2276: foreach my $keyword (@keylist) {
2277: $string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
2278: }
2279: return $string;
2280: }
2281:
2282: #--- Called from submission routine
2283: sub processHandGrade {
2284: my ($request) = shift;
2285: my $symb = &get_symb($request);
2286: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
2287: my $button = $env{'form.gradeOpt'};
2288: my $ngrade = $env{'form.NCT'};
2289: my $ntstu = $env{'form.NTSTU'};
2290: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2291: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2292:
2293: if ($button eq 'Save & Next') {
2294: my $ctr = 0;
2295: while ($ctr < $ngrade) {
2296: my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
2297: my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
2298: if ($errorflag eq 'no_score') {
2299: $ctr++;
2300: next;
2301: }
2302: if ($errorflag eq 'not_allowed') {
2303: $request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
2304: $ctr++;
2305: next;
2306: }
2307: my $includemsg = $env{'form.includemsg'.$ctr};
2308: my ($subject,$message,$msgstatus) = ('','','');
2309: my $restitle = &Apache::lonnet::gettitle($symb);
2310: my ($feedurl,$showsymb) =
2311: &get_feedurl_and_symb($symb,$uname,$udom);
2312: my $messagetail;
2313: if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
2314: $subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
2315: unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
2316: $subject.=' ['.$restitle.']';
2317: my (@msgnum) = split(/,/,$includemsg);
2318: foreach (@msgnum) {
2319: $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
2320: }
2321: $message =&Apache::lonfeedback::clear_out_html($message);
2322: if ($env{'form.withgrades'.$ctr}) {
2323: $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
2324: $messagetail = " for <a href=\"".
2325: $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
2326: }
2327: $msgstatus =
2328: &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
2329: $message.$messagetail,
2330: undef,$feedurl,undef,
2331: undef,undef,$showsymb,
2332: $restitle);
2333: $request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
2334: $msgstatus);
2335: }
2336: if ($env{'form.collaborator'.$ctr}) {
2337: my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
2338: foreach my $collabstr (@collabstrs) {
2339: my ($part,@collaborators) = split(/:/,$collabstr);
2340: foreach my $collaborator (@collaborators) {
2341: my ($errorflag,$pts,$wgt) =
2342: &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
2343: $env{'form.unamedom'.$ctr},$part);
2344: if ($errorflag eq 'not_allowed') {
2345: $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
2346: next;
2347: } elsif ($message ne '') {
2348: my ($baseurl,$showsymb) =
2349: &get_feedurl_and_symb($symb,$collaborator,
2350: $udom);
2351: if ($env{'form.withgrades'.$ctr}) {
2352: $messagetail = " for <a href=\"".
2353: $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
2354: }
2355: $msgstatus =
2356: &Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
2357: }
2358: }
2359: }
2360: }
2361: $ctr++;
2362: }
2363: }
2364:
2365: if ($env{'form.handgrade'} eq 'yes') {
2366: # Keywords sorted in alphabatical order
2367: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
2368: my %keyhash = ();
2369: $env{'form.keywords'} =~ s/,\s{0,}|\s+/ /g;
2370: $env{'form.keywords'} =~ s/^\s+|\s+$//;
2371: my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
2372: $env{'form.keywords'} = join(' ',@keywords);
2373: $keyhash{$symb.'_keywords'} = $env{'form.keywords'};
2374: $keyhash{$symb.'_subject'} = $env{'form.msgsub'};
2375: $keyhash{$loginuser.'_kwclr'} = $env{'form.kwclr'};
2376: $keyhash{$loginuser.'_kwsize'} = $env{'form.kwsize'};
2377: $keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
2378:
2379: # message center - Order of message gets changed. Blank line is eliminated.
2380: # New messages are saved in env for the next student.
2381: # All messages are saved in nohist_handgrade.db
2382: my ($ctr,$idx) = (1,1);
2383: while ($ctr <= $env{'form.savemsgN'}) {
2384: if ($env{'form.savemsg'.$ctr} ne '') {
2385: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
2386: $idx++;
2387: }
2388: $ctr++;
2389: }
2390: $ctr = 0;
2391: while ($ctr < $ngrade) {
2392: if ($env{'form.newmsg'.$ctr} ne '') {
2393: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2394: $env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2395: $idx++;
2396: }
2397: $ctr++;
2398: }
2399: $env{'form.savemsgN'} = --$idx;
2400: $keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
2401: my $putresult = &Apache::lonnet::put
2402: ('nohist_handgrade',\%keyhash,$cdom,$cnum);
2403: }
2404: # Called by Save & Refresh from Highlight Attribute Window
2405: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
2406: if ($env{'form.refresh'} eq 'on') {
2407: my ($ctr,$total) = (0,0);
2408: while ($ctr < $ngrade) {
2409: $total++ if $env{'form.unamedom'.$ctr} ne '';
2410: $ctr++;
2411: }
2412: $env{'form.NTSTU'}=$ngrade;
2413: $ctr = 0;
2414: while ($ctr < $total) {
2415: my $processUser = $env{'form.unamedom'.$ctr};
2416: ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
2417: $env{'form.fullname'} = $$fullname{$processUser};
2418: &submission($request,$ctr,$total-1);
2419: $ctr++;
2420: }
2421: return '';
2422: }
2423:
2424: # Go directly to grade student - from submission or link from chart page
2425: if ($button eq 'Grade Student') {
2426: (undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
2427: my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
2428: ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
2429: $env{'form.fullname'} = $$fullname{$processUser};
2430: &submission($request,0,0);
2431: return '';
2432: }
2433:
2434: # Get the next/previous one or group of students
2435: my $firststu = $env{'form.unamedom0'};
2436: my $laststu = $env{'form.unamedom'.($ngrade-1)};
2437: my $ctr = 2;
2438: while ($laststu eq '') {
2439: $laststu = $env{'form.unamedom'.($ngrade-$ctr)};
2440: $ctr++;
2441: $laststu = $firststu if ($ctr > $ngrade);
2442: }
2443:
2444: my (@parsedlist,@nextlist);
2445: my ($nextflg) = 0;
2446: foreach (sort
2447: {
2448: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
2449: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
2450: }
2451: return $a cmp $b;
2452: } (keys(%$fullname))) {
2453: if ($nextflg == 1 && $button =~ /Next$/) {
2454: push @parsedlist,$_;
2455: }
2456: $nextflg = 1 if ($_ eq $laststu);
2457: if ($button eq 'Previous') {
2458: last if ($_ eq $firststu);
2459: push @parsedlist,$_;
2460: }
2461: }
2462: $ctr = 0;
2463: @parsedlist = reverse @parsedlist if ($button eq 'Previous');
2464: my ($partlist) = &response_type($symb);
2465: foreach my $student (@parsedlist) {
2466: my $submitonly=$env{'form.submitonly'};
2467: my ($uname,$udom) = split(/:/,$student);
2468:
2469: if ($submitonly eq 'queued') {
2470: my %queue_status =
2471: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
2472: $udom,$uname);
2473: next if (!defined($queue_status{'gradingqueue'}));
2474: }
2475:
2476: if ($submitonly =~ /^(yes|graded|incorrect)$/) {
2477: # my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
2478: my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
2479: my $submitted = 0;
2480: my $ungraded = 0;
2481: my $incorrect = 0;
2482: foreach (keys(%status)) {
2483: $submitted = 1 if ($status{$_} ne 'nothing');
2484: $ungraded = 1 if ($status{$_} =~ /^ungraded/);
2485: $incorrect = 1 if ($status{$_} =~ /^incorrect/);
2486: my ($foo,$partid,$foo1) = split(/\./,$_);
2487: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
2488: $submitted = 0;
2489: }
2490: }
2491: next if (!$submitted && ($submitonly eq 'yes' ||
2492: $submitonly eq 'incorrect' ||
2493: $submitonly eq 'graded'));
2494: next if (!$ungraded && ($submitonly eq 'graded'));
2495: next if (!$incorrect && $submitonly eq 'incorrect');
2496: }
2497: push @nextlist,$student if ($ctr < $ntstu);
2498: last if ($ctr == $ntstu);
2499: $ctr++;
2500: }
2501:
2502: $ctr = 0;
2503: my $total = scalar(@nextlist)-1;
2504:
2505: foreach (sort @nextlist) {
2506: my ($uname,$udom,$submitter) = split(/:/);
2507: $env{'form.student'} = $uname;
2508: $env{'form.userdom'} = $udom;
2509: $env{'form.fullname'} = $$fullname{$_};
2510: &submission($request,$ctr,$total);
2511: $ctr++;
2512: }
2513: if ($total < 0) {
2514: my $the_end = '<h3><span class="LC_info">LON-CAPA User Message</span></h3><br />'."\n";
2515: $the_end.='<b>Message: </b> No more students for this section or class.<br /><br />'."\n";
2516: $the_end.='Click on the button below to return to the grading menu.<br /><br />'."\n";
2517: $the_end.=&show_grading_menu_form($symb);
2518: $request->print($the_end);
2519: }
2520: return '';
2521: }
2522:
2523: #---- Save the score and award for each student, if changed
2524: sub saveHandGrade {
2525: my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
2526: my @version_parts;
2527: my $usec = &Apache::lonnet::getsection($domain,$stuname,
2528: $env{'request.course.id'});
2529: if (!&canmodify($usec)) { return('not_allowed'); }
2530: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
2531: my @parts_graded;
2532: my %newrecord = ();
2533: my ($pts,$wgt) = ('','');
2534: my %aggregate = ();
2535: my $aggregateflag = 0;
2536: my @parts = split(/:/,$env{'form.partlist'.$newflg});
2537: foreach my $new_part (@parts) {
2538: #collaborator ($submi may vary for different parts
2539: if ($submitter && $new_part ne $part) { next; }
2540: my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
2541: if ($dropMenu eq 'excused') {
2542: if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
2543: $newrecord{'resource.'.$new_part.'.solved'} = 'excused';
2544: if (exists($record{'resource.'.$new_part.'.awarded'})) {
2545: $newrecord{'resource.'.$new_part.'.awarded'} = '';
2546: }
2547: $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
2548: }
2549: } elsif ($dropMenu eq 'reset status'
2550: && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
2551: foreach my $key (keys (%record)) {
2552: if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
2553: }
2554: $newrecord{'resource.'.$new_part.'.regrader'}=
2555: "$env{'user.name'}:$env{'user.domain'}";
2556: my $totaltries = $record{'resource.'.$part.'.tries'};
2557:
2558: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
2559: [$new_part]);
2560: my $aggtries =$totaltries;
2561: if ($last_resets{$new_part}) {
2562: $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
2563: $new_part);
2564: }
2565:
2566: my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
2567: if ($aggtries > 0) {
2568: &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
2569: $aggregateflag = 1;
2570: }
2571: } elsif ($dropMenu eq '') {
2572: $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ?
2573: $env{'form.GD_BOX'.$newflg.'_'.$new_part} :
2574: $env{'form.RADVAL'.$newflg.'_'.$new_part});
2575: if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
2576: next;
2577: }
2578: $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 :
2579: $env{'form.WGT'.$newflg.'_'.$new_part};
2580: my $partial= $pts/$wgt;
2581: if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
2582: #do not update score for part if not changed.
2583: &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
2584: next;
2585: } else {
2586: push @parts_graded, $new_part;
2587: }
2588: if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
2589: $newrecord{'resource.'.$new_part.'.awarded'} = $partial;
2590: }
2591: my $reckey = 'resource.'.$new_part.'.solved';
2592: if ($partial == 0) {
2593: if ($record{$reckey} ne 'incorrect_by_override') {
2594: $newrecord{$reckey} = 'incorrect_by_override';
2595: }
2596: } else {
2597: if ($record{$reckey} ne 'correct_by_override') {
2598: $newrecord{$reckey} = 'correct_by_override';
2599: }
2600: }
2601: if ($submitter &&
2602: ($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
2603: $newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
2604: }
2605: $newrecord{'resource.'.$new_part.'.regrader'}=
2606: "$env{'user.name'}:$env{'user.domain'}";
2607: }
2608: # unless problem has been graded, set flag to version the submitted files
2609: unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/ ||
2610: $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
2611: $dropMenu eq 'reset status')
2612: {
2613: push (@version_parts,$new_part);
2614: }
2615: }
2616: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2617: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2618:
2619: if (%newrecord) {
2620: if (@version_parts) {
2621: my @changed_keys = &version_portfiles(\%record, \@parts_graded,
2622: $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
2623: @newrecord{@changed_keys} = @record{@changed_keys};
2624: foreach my $new_part (@version_parts) {
2625: &handback_files($request,$symb,$stuname,$domain,$newflg,
2626: $new_part,\%newrecord);
2627: }
2628: }
2629: &Apache::lonnet::cstore(\%newrecord,$symb,
2630: $env{'request.course.id'},$domain,$stuname);
2631: &check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
2632: $cdom,$cnum,$domain,$stuname);
2633: }
2634: if ($aggregateflag) {
2635: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
2636: $cdom,$cnum);
2637: }
2638: return ('',$pts,$wgt);
2639: }
2640:
2641: sub check_and_remove_from_queue {
2642: my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
2643: my @ungraded_parts;
2644: foreach my $part (@{$parts}) {
2645: if ( $record->{ 'resource.'.$part.'.awarded'} eq ''
2646: && $record->{ 'resource.'.$part.'.solved' } ne 'excused'
2647: && $newrecord->{'resource.'.$part.'.awarded'} eq ''
2648: && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
2649: ) {
2650: push(@ungraded_parts, $part);
2651: }
2652: }
2653: if ( !@ungraded_parts ) {
2654: &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
2655: $cnum,$domain,$stuname);
2656: }
2657: }
2658:
2659: sub handback_files {
2660: my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
2661: my $portfolio_root = &propath($domain,$stuname).'/userfiles/portfolio';
2662: my ($partlist,$handgrade,$responseType) = &response_type($symb);
2663:
2664: my @part_response_id = &flatten_responseType($responseType);
2665: foreach my $part_response_id (@part_response_id) {
2666: my ($part_id,$resp_id) = @{ $part_response_id };
2667: my $part_resp = join('_',@{ $part_response_id });
2668: if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
2669: # if multiple files are uploaded names will be 'returndoc2','returndoc3'
2670: my $file_counter = 1;
2671: my $file_msg;
2672: while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
2673: my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
2674: my ($directory,$answer_file) =
2675: ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
2676: my ($answer_name,$answer_ver,$answer_ext) =
2677: &file_name_version_ext($answer_file);
2678: my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
2679: my @dir_list = &Apache::lonnet::dirlist($portfolio_path,$domain,$stuname,$portfolio_root);
2680: my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
2681: # fix file name
2682: my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
2683: my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
2684: $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
2685: $save_file_name);
2686: if ($result !~ m|^/uploaded/|) {
2687: $request->print('<span class="LC_error">An error occurred ('.$result.
2688: ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</span><br />');
2689: } else {
2690: # mark the file as read only
2691: my @files = ($save_file_name);
2692: my @what = ($symb,$env{'request.course.id'},'handback');
2693: &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
2694: if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
2695: $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
2696: }
2697: $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
2698: $file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
2699:
2700: }
2701: $request->print("<br />".$fname." will be the uploaded file name");
2702: $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
2703: $file_counter++;
2704: }
2705: my $subject = "File Handed Back by Instructor ";
2706: my $message = "A file has been returned that was originally submitted in reponse to: <br />";
2707: $message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
2708: $message .= ' The returned file(s) are named: '. $file_msg;
2709: $message .= " and can be found in your portfolio space.";
2710: my ($feedurl,$showsymb) =
2711: &get_feedurl_and_symb($symb,$domain,$stuname);
2712: my $restitle = &Apache::lonnet::gettitle($symb);
2713: my $msgstatus =
2714: &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
2715: ' (File Returned) ['.$restitle.']',$message,undef,
2716: $feedurl,undef,undef,undef,$showsymb,$restitle);
2717: }
2718: }
2719: return;
2720: }
2721:
2722: sub get_feedurl_and_symb {
2723: my ($symb,$uname,$udom) = @_;
2724: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
2725: $url = &Apache::lonnet::clutter($url);
2726: my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
2727: $symb,$udom,$uname);
2728: if ($encrypturl =~ /^yes$/i) {
2729: &Apache::lonenc::encrypted(\$url,1);
2730: &Apache::lonenc::encrypted(\$symb,1);
2731: }
2732: return ($url,$symb);
2733: }
2734:
2735: sub get_submitted_files {
2736: my ($udom,$uname,$partid,$respid,$record) = @_;
2737: my @files;
2738: if ($$record{"resource.$partid.$respid.portfiles"}) {
2739: my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
2740: foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
2741: push(@files,$file_url.$file);
2742: }
2743: }
2744: if ($$record{"resource.$partid.$respid.uploadedurl"}) {
2745: push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
2746: }
2747: return (\@files);
2748: }
2749:
2750: # ----------- Provides number of tries since last reset.
2751: sub get_num_tries {
2752: my ($record,$last_reset,$part) = @_;
2753: my $timestamp = '';
2754: my $num_tries = 0;
2755: if ($$record{'version'}) {
2756: for (my $version=$$record{'version'};$version>=1;$version--) {
2757: if (exists($$record{$version.':resource.'.$part.'.solved'})) {
2758: $timestamp = $$record{$version.':timestamp'};
2759: if ($timestamp > $last_reset) {
2760: $num_tries ++;
2761: } else {
2762: last;
2763: }
2764: }
2765: }
2766: }
2767: return $num_tries;
2768: }
2769:
2770: # ----------- Determine decrements required in aggregate totals
2771: sub decrement_aggs {
2772: my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
2773: my %decrement = (
2774: attempts => 0,
2775: users => 0,
2776: correct => 0
2777: );
2778: $decrement{'attempts'} = $aggtries;
2779: if ($solvedstatus =~ /^correct/) {
2780: $decrement{'correct'} = 1;
2781: }
2782: if ($aggtries == $totaltries) {
2783: $decrement{'users'} = 1;
2784: }
2785: foreach my $type (keys (%decrement)) {
2786: $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
2787: }
2788: return;
2789: }
2790:
2791: # ----------- Determine timestamps for last reset of aggregate totals for parts
2792: sub get_last_resets {
2793: my ($symb,$courseid,$partids) =@_;
2794: my %last_resets;
2795: my $cdom = $env{'course.'.$courseid.'.domain'};
2796: my $cname = $env{'course.'.$courseid.'.num'};
2797: my @keys;
2798: foreach my $part (@{$partids}) {
2799: push(@keys,"$symb\0$part\0resettime");
2800: }
2801: my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
2802: $cdom,$cname);
2803: foreach my $part (@{$partids}) {
2804: $last_resets{$part}=$results{"$symb\0$part\0resettime"};
2805: }
2806: return %last_resets;
2807: }
2808:
2809: # ----------- Handles creating versions for portfolio files as answers
2810: sub version_portfiles {
2811: my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
2812: my $version_parts = join('|',@$v_flag);
2813: my @returned_keys;
2814: my $parts = join('|', @$parts_graded);
2815: my $portfolio_root = &propath($domain,$stu_name).
2816: '/userfiles/portfolio';
2817: foreach my $key (keys(%$record)) {
2818: my $new_portfiles;
2819: if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
2820: my @versioned_portfiles;
2821: my @portfiles = split(/\s*,\s*/,$$record{$key});
2822: foreach my $file (@portfiles) {
2823: &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
2824: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
2825: my ($answer_name,$answer_ver,$answer_ext) =
2826: &file_name_version_ext($answer_file);
2827: my @dir_list = &Apache::lonnet::dirlist($directory,$domain,$stu_name,$portfolio_root);
2828: my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
2829: my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
2830: if ($new_answer ne 'problem getting file') {
2831: push(@versioned_portfiles, $directory.$new_answer);
2832: &Apache::lonnet::mark_as_readonly($domain,$stu_name,
2833: [$directory.$new_answer],
2834: [$symb,$env{'request.course.id'},'graded']);
2835: }
2836: }
2837: $$record{$key} = join(',',@versioned_portfiles);
2838: push(@returned_keys,$key);
2839: }
2840: }
2841: return (@returned_keys);
2842: }
2843:
2844: sub get_next_version {
2845: my ($answer_name, $answer_ext, $dir_list) = @_;
2846: my $version;
2847: foreach my $row (@$dir_list) {
2848: my ($file) = split(/\&/,$row,2);
2849: my ($file_name,$file_version,$file_ext) =
2850: &file_name_version_ext($file);
2851: if (($file_name eq $answer_name) &&
2852: ($file_ext eq $answer_ext)) {
2853: # gets here if filename and extension match, regardless of version
2854: if ($file_version ne '') {
2855: # a versioned file is found so save it for later
2856: if ($file_version > $version) {
2857: $version = $file_version;
2858: }
2859: }
2860: }
2861: }
2862: $version ++;
2863: return($version);
2864: }
2865:
2866: sub version_selected_portfile {
2867: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
2868: my ($answer_name,$answer_ver,$answer_ext) =
2869: &file_name_version_ext($file_name);
2870: my $new_answer;
2871: $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
2872: if($env{'form.copy'} eq '-1') {
2873: $new_answer = 'problem getting file';
2874: } else {
2875: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
2876: my $copy_result = &Apache::lonnet::finishuserfileupload(
2877: $stu_name,$domain,'copy',
2878: '/portfolio'.$directory.$new_answer);
2879: }
2880: return ($new_answer);
2881: }
2882:
2883: sub file_name_version_ext {
2884: my ($file)=@_;
2885: my @file_parts = split(/\./, $file);
2886: my ($name,$version,$ext);
2887: if (@file_parts > 1) {
2888: $ext=pop(@file_parts);
2889: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
2890: $version=pop(@file_parts);
2891: }
2892: $name=join('.',@file_parts);
2893: } else {
2894: $name=join('.',@file_parts);
2895: }
2896: return($name,$version,$ext);
2897: }
2898:
2899: #--------------------------------------------------------------------------------------
2900: #
2901: #-------------------------- Next few routines handles grading by section or whole class
2902: #
2903: #--- Javascript to handle grading by section or whole class
2904: sub viewgrades_js {
2905: my ($request) = shift;
2906:
2907: $request->print(<<VIEWJAVASCRIPT);
2908: <script type="text/javascript" language="javascript">
2909: function writePoint(partid,weight,point) {
2910: var radioButton = document.classgrade["RADVAL_"+partid];
2911: var textbox = document.classgrade["TEXTVAL_"+partid];
2912: if (point == "textval") {
2913: point = document.classgrade["TEXTVAL_"+partid].value;
2914: if (isNaN(point) || parseFloat(point) < 0) {
2915: alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
2916: var resetbox = false;
2917: for (var i=0; i<radioButton.length; i++) {
2918: if (radioButton[i].checked) {
2919: textbox.value = i;
2920: resetbox = true;
2921: }
2922: }
2923: if (!resetbox) {
2924: textbox.value = "";
2925: }
2926: return;
2927: }
2928: if (parseFloat(point) > parseFloat(weight)) {
2929: var resp = confirm("You entered a value ("+parseFloat(point)+
2930: ") greater than the weight for the part. Accept?");
2931: if (resp == false) {
2932: textbox.value = "";
2933: return;
2934: }
2935: }
2936: for (var i=0; i<radioButton.length; i++) {
2937: radioButton[i].checked=false;
2938: if (parseFloat(point) == i) {
2939: radioButton[i].checked=true;
2940: }
2941: }
2942:
2943: } else {
2944: textbox.value = parseFloat(point);
2945: }
2946: for (i=0;i<document.classgrade.total.value;i++) {
2947: var user = document.classgrade["ctr"+i].value;
2948: user = user.replace(new RegExp(':', 'g'),"_");
2949: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
2950: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
2951: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
2952: if (saveval != "correct") {
2953: scorename.value = point;
2954: if (selname[0].selected != true) {
2955: selname[0].selected = true;
2956: }
2957: }
2958: }
2959: document.classgrade["SELVAL_"+partid][0].selected = true;
2960: }
2961:
2962: function writeRadText(partid,weight) {
2963: var selval = document.classgrade["SELVAL_"+partid];
2964: var radioButton = document.classgrade["RADVAL_"+partid];
2965: var override = document.classgrade["FORCE_"+partid].checked;
2966: var textbox = document.classgrade["TEXTVAL_"+partid];
2967: if (selval[1].selected || selval[2].selected) {
2968: for (var i=0; i<radioButton.length; i++) {
2969: radioButton[i].checked=false;
2970:
2971: }
2972: textbox.value = "";
2973:
2974: for (i=0;i<document.classgrade.total.value;i++) {
2975: var user = document.classgrade["ctr"+i].value;
2976: user = user.replace(new RegExp(':', 'g'),"_");
2977: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
2978: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
2979: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
2980: if ((saveval != "correct") || override) {
2981: scorename.value = "";
2982: if (selval[1].selected) {
2983: selname[1].selected = true;
2984: } else {
2985: selname[2].selected = true;
2986: if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value))
2987: {document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
2988: }
2989: }
2990: }
2991: } else {
2992: for (i=0;i<document.classgrade.total.value;i++) {
2993: var user = document.classgrade["ctr"+i].value;
2994: user = user.replace(new RegExp(':', 'g'),"_");
2995: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
2996: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
2997: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
2998: if ((saveval != "correct") || override) {
2999: scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
3000: selname[0].selected = true;
3001: }
3002: }
3003: }
3004: }
3005:
3006: function changeSelect(partid,user) {
3007: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
3008: var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
3009: var point = textbox.value;
3010: var weight = document.classgrade["weight_"+partid].value;
3011:
3012: if (isNaN(point) || parseFloat(point) < 0) {
3013: alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
3014: textbox.value = "";
3015: return;
3016: }
3017: if (parseFloat(point) > parseFloat(weight)) {
3018: var resp = confirm("You entered a value ("+parseFloat(point)+
3019: ") greater than the weight of the part. Accept?");
3020: if (resp == false) {
3021: textbox.value = "";
3022: return;
3023: }
3024: }
3025: selval[0].selected = true;
3026: }
3027:
3028: function changeOneScore(partid,user) {
3029: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
3030: if (selval[1].selected || selval[2].selected) {
3031: document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
3032: if (selval[2].selected) {
3033: document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
3034: }
3035: }
3036: }
3037:
3038: function resetEntry(numpart) {
3039: for (ctpart=0;ctpart<numpart;ctpart++) {
3040: var partid = document.classgrade["partid_"+ctpart].value;
3041: var radioButton = document.classgrade["RADVAL_"+partid];
3042: var textbox = document.classgrade["TEXTVAL_"+partid];
3043: var selval = document.classgrade["SELVAL_"+partid];
3044: for (var i=0; i<radioButton.length; i++) {
3045: radioButton[i].checked=false;
3046:
3047: }
3048: textbox.value = "";
3049: selval[0].selected = true;
3050:
3051: for (i=0;i<document.classgrade.total.value;i++) {
3052: var user = document.classgrade["ctr"+i].value;
3053: user = user.replace(new RegExp(':', 'g'),"_");
3054: var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3055: resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
3056: var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
3057: resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
3058: var saveselval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3059: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3060: if (saveselval == "excused") {
3061: if (selname[1].selected == false) { selname[1].selected = true;}
3062: } else {
3063: if (selname[0].selected == false) {selname[0].selected = true};
3064: }
3065: }
3066: }
3067: }
3068:
3069: </script>
3070: VIEWJAVASCRIPT
3071: }
3072:
3073: #--- show scores for a section or whole class w/ option to change/update a score
3074: sub viewgrades {
3075: my ($request) = shift;
3076: &viewgrades_js($request);
3077:
3078: my ($symb) = &get_symb($request);
3079: #need to make sure we have the correct data for later EXT calls,
3080: #thus invalidate the cache
3081: &Apache::lonnet::devalidatecourseresdata(
3082: $env{'course.'.$env{'request.course.id'}.'.num'},
3083: $env{'course.'.$env{'request.course.id'}.'.domain'});
3084: &Apache::lonnet::clear_EXT_cache_status();
3085:
3086: my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
3087: $result.='<h4><b>Current Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n";
3088:
3089: #view individual student submission form - called using Javascript viewOneStudent
3090: $result.=&jscriptNform($symb);
3091:
3092: #beginning of class grading form
3093: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
3094: $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
3095: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
3096: '<input type="hidden" name="command" value="editgrades" />'."\n".
3097: &build_section_inputs().
3098: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
3099: '<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
3100: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
3101:
3102: my $sectionClass;
3103: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3104: if ($env{'form.section'} eq 'all') {
3105: $sectionClass='Class </h3>';
3106: } elsif ($env{'form.section'} eq 'none') {
3107: $sectionClass=&mt('Students in no Section').'</h3>';
3108: } else {
3109: $sectionClass=&mt('Students in Section(s) [_1]',$section_display).'</h3>';
3110: }
3111: $result.='<h3>'.&mt('Assign Common Grade To [_1]',$sectionClass);
3112: $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
3113: '<table border=0><tr bgcolor="#ffffdd"><td>';
3114: #radio buttons/text box for assigning points for a section or class.
3115: #handles different parts of a problem
3116: my ($partlist,$handgrade,$responseType) = &response_type($symb);
3117: my %weight = ();
3118: my $ctsparts = 0;
3119: $result.='<table border="0">';
3120: my %seen = ();
3121: my @part_response_id = &flatten_responseType($responseType);
3122: foreach my $part_response_id (@part_response_id) {
3123: my ($partid,$respid) = @{ $part_response_id };
3124: my $part_resp = join('_',@{ $part_response_id });
3125: next if $seen{$partid};
3126: $seen{$partid}++;
3127: my $handgrade=$$handgrade{$part_resp};
3128: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
3129: $weight{$partid} = $wgt eq '' ? '1' : $wgt;
3130:
3131: $result.='<input type="hidden" name="partid_'.
3132: $ctsparts.'" value="'.$partid.'" />'."\n";
3133: $result.='<input type="hidden" name="weight_'.
3134: $partid.'" value="'.$weight{$partid}.'" />'."\n";
3135: my $display_part=&get_display_part($partid,$symb);
3136: $result.='<tr><td><b>Part:</b> '.$display_part.' <b>Point:</b> </td><td>';
3137: $result.='<table border="0"><tr>';
3138: my $ctr = 0;
3139: while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
3140: $result.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
3141: 'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
3142: ','.$ctr.')" />'.$ctr."</label></td>\n";
3143: $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
3144: $ctr++;
3145: }
3146: $result.='</tr></table>';
3147: $result.= '</td><td><b> or </b><input type="text" name="TEXTVAL_'.
3148: $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
3149: $partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
3150: $weight{$partid}.' (problem weight)</td>'."\n";
3151: $result.= '</td><td><select name="SELVAL_'.$partid.'"'.
3152: 'onChange="javascript:writeRadText(\''.$partid.'\','.
3153: $weight{$partid}.')"> '.
3154: '<option selected="selected"> </option>'.
3155: '<option>excused</option>'.
3156: '<option>reset status</option></select></td>'.
3157: '<td><label><input type="checkbox" name="FORCE_'.$partid.'" /> Override "Correct"</label></td></tr>'."\n";
3158: $ctsparts++;
3159: }
3160: $result.='</table>'.'</td></tr></table>'.'</td></tr></table>'."\n".
3161: '<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
3162: $result.='<input type="button" value="Revert to Default" '.
3163: 'onClick="javascript:resetEntry('.$ctsparts.');" target="_self" />';
3164:
3165: #table listing all the students in a section/class
3166: #header of table
3167: $result.= '<h3>Assign Grade to Specific Students in '.$sectionClass;
3168: $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
3169: '<table border=0><tr bgcolor="#deffff"><td> <b>No.</b> </td>'.
3170: '<td>'.&nameUserString('header')."</td>\n";
3171: my (@parts) = sort(&getpartlist($symb));
3172: my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
3173: my @partids = ();
3174: foreach my $part (@parts) {
3175: my $display=&Apache::lonnet::metadata($url,$part.'.display');
3176: $display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
3177: if (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
3178: my ($partid) = &split_part_type($part);
3179: push(@partids, $partid);
3180: my $display_part=&get_display_part($partid,$symb);
3181: if ($display =~ /^Partial Credit Factor/) {
3182: $result.='<td><b>Score Part:</b> '.$display_part.
3183: ' <br /><b>(weight = '.$weight{$partid}.')</b></td>'."\n";
3184: next;
3185: } else {
3186: $display =~s/\[Part: \Q$partid\E\]/Part:<\/b> $display_part/;
3187: }
3188: $display =~ s|Problem Status|Grade Status<br />|;
3189: $result.='<td><b>'.$display.'</td>'."\n";
3190: }
3191: $result.='</tr>';
3192:
3193: my %last_resets =
3194: &get_last_resets($symb,$env{'request.course.id'},\@partids);
3195:
3196: #get info for each student
3197: #list all the students - with points and grade status
3198: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
3199: my $ctr = 0;
3200: foreach (sort
3201: {
3202: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
3203: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
3204: }
3205: return $a cmp $b;
3206: } (keys(%$fullname))) {
3207: $ctr++;
3208: $result.=&viewstudentgrade($symb,$env{'request.course.id'},
3209: $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
3210: }
3211: $result.='</table></td></tr></table>';
3212: $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
3213: $result.='<input type="button" value="Save" '.
3214: 'onClick="javascript:submit();" target="_self" /></form>'."\n";
3215: if (scalar(%$fullname) eq 0) {
3216: my $colspan=3+scalar(@parts);
3217: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3218: my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
3219: $result='<span class="LC_warning">'.
3220: &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade',
3221: $section_display, $stu_status).
3222: '</span>';
3223: }
3224: $result.=&show_grading_menu_form($symb);
3225: return $result;
3226: }
3227:
3228: #--- call by previous routine to display each student
3229: sub viewstudentgrade {
3230: my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
3231: my ($uname,$udom) = split(/:/,$student);
3232: my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
3233: my %aggregates = ();
3234: my $result='<tr bgcolor="#ffffdd"><td align="right">'.
3235: '<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
3236: "\n".$ctr.' </td><td> '.
3237: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
3238: '\');" target="_self">'.$fullname.'</a> '.
3239: '<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
3240: $student=~s/:/_/; # colon doen't work in javascript for names
3241: foreach my $apart (@$parts) {
3242: my ($part,$type) = &split_part_type($apart);
3243: my $score=$record{"resource.$part.$type"};
3244: $result.='<td align="center">';
3245: my ($aggtries,$totaltries);
3246: unless (exists($aggregates{$part})) {
3247: $totaltries = $record{'resource.'.$part.'.tries'};
3248:
3249: $aggtries = $totaltries;
3250: if ($$last_resets{$part}) {
3251: $aggtries = &get_num_tries(\%record,$$last_resets{$part},
3252: $part);
3253: }
3254: $result.='<input type="hidden" name="'.
3255: 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
3256: $result.='<input type="hidden" name="'.
3257: 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
3258: $aggregates{$part} = 1;
3259: }
3260: if ($type eq 'awarded') {
3261: my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
3262: $result.='<input type="hidden" name="'.
3263: 'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
3264: $result.='<input type="text" name="'.
3265: 'GD_'.$student.'_'.$part.'_awarded" '.
3266: 'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
3267: '\')" value="'.$pts.'" size="4" /></td>'."\n";
3268: } elsif ($type eq 'solved') {
3269: my ($status,$foo)=split(/_/,$score,2);
3270: $status = 'nothing' if ($status eq '');
3271: $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
3272: $part.'_solved_s" value="'.$status.'" />'."\n";
3273: $result.=' <select name="'.
3274: 'GD_'.$student.'_'.$part.'_solved" '.
3275: 'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
3276: $result.= (($status eq 'excused') ? '<option> </option><option selected="selected">excused</option>'
3277: : '<option selected="selected"> </option><option>excused</option>')."\n";
3278: $result.='<option>reset status</option>';
3279: $result.="</select> </td>\n";
3280: } else {
3281: $result.='<input type="hidden" name="'.
3282: 'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
3283: "\n";
3284: $result.='<input type="text" name="'.
3285: 'GD_'.$student.'_'.$part.'_'.$type.'" '.
3286: 'value="'.$score.'" size="4" /></td>'."\n";
3287: }
3288: }
3289: $result.='</tr>';
3290: return $result;
3291: }
3292:
3293: #--- change scores for all the students in a section/class
3294: # record does not get update if unchanged
3295: sub editgrades {
3296: my ($request) = @_;
3297:
3298: my $symb=&get_symb($request);
3299: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3300: my $title='<h3><span class="LC_info">'.&mt('Current Grade Status').'</span></h3>';
3301: $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4><br />'."\n";
3302: $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
3303:
3304: my $result= '<table border="0"><tr><td bgcolor="#777777">'."\n";
3305: $result.= '<table border="0"><tr bgcolor="#deffff">'.
3306: '<td rowspan=2 valign="center"> <b>No.</b> </td>'.
3307: '<td rowspan=2 valign="center">'.&nameUserString('header')."</td>\n";
3308:
3309: my %scoreptr = (
3310: 'correct' =>'correct_by_override',
3311: 'incorrect'=>'incorrect_by_override',
3312: 'excused' =>'excused',
3313: 'ungraded' =>'ungraded_attempted',
3314: 'nothing' => '',
3315: );
3316: my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
3317:
3318: my (@partid);
3319: my %weight = ();
3320: my %columns = ();
3321: my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
3322:
3323: my (@parts) = sort(&getpartlist($symb));
3324: my $header;
3325: while ($ctr < $env{'form.totalparts'}) {
3326: my $partid = $env{'form.partid_'.$ctr};
3327: push @partid,$partid;
3328: $weight{$partid} = $env{'form.weight_'.$partid};
3329: $ctr++;
3330: }
3331: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3332: foreach my $partid (@partid) {
3333: $header .= '<td align="center"> <b>Old Score</b> </td>'.
3334: '<td align="center"> <b>New Score</b> </td>';
3335: $columns{$partid}=2;
3336: foreach my $stores (@parts) {
3337: my ($part,$type) = &split_part_type($stores);
3338: if ($part !~ m/^\Q$partid\E/) { next;}
3339: if ($type eq 'awarded' || $type eq 'solved') { next; }
3340: my $display=&Apache::lonnet::metadata($url,$stores.'.display');
3341: $display =~ s/\[Part: (\w)+\]//;
3342: $display =~ s/Number of Attempts/Tries/;
3343: $header .= '<td align="center"> <b>Old '.$display.'</b> </td>'.
3344: '<td align="center"> <b>New '.$display.'</b> </td>';
3345: $columns{$partid}+=2;
3346: }
3347: }
3348: foreach my $partid (@partid) {
3349: my $display_part=&get_display_part($partid,$symb);
3350: $result .= '<td colspan="'.$columns{$partid}.
3351: '" align="center"><b>Part:</b> '.$display_part.
3352: ' (Weight = '.$weight{$partid}.')</td>';
3353:
3354: }
3355: $result .= '</tr><tr bgcolor="#deffff">';
3356: $result .= $header;
3357: $result .= '</tr>'."\n";
3358: my $noupdate;
3359: my ($updateCtr,$noupdateCtr) = (1,1);
3360: for ($i=0; $i<$env{'form.total'}; $i++) {
3361: my $line;
3362: my $user = $env{'form.ctr'.$i};
3363: my ($uname,$udom)=split(/:/,$user);
3364: my %newrecord;
3365: my $updateflag = 0;
3366: $line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
3367: my $usec=$classlist->{"$uname:$udom"}[5];
3368: if (!&canmodify($usec)) {
3369: my $numcols=scalar(@partid)*4+2;
3370: $noupdate.=$line."<td colspan=\"$numcols\"><span class=\"LC_warning\">Not allowed to modify student</span></td></tr>";
3371: next;
3372: }
3373: my %aggregate = ();
3374: my $aggregateflag = 0;
3375: $user=~s/:/_/; # colon doen't work in javascript for names
3376: foreach (@partid) {
3377: my $old_aw = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
3378: my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
3379: my $old_part = $old_aw eq '' ? '' : $old_part_pcr;
3380: my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
3381: my $awarded = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
3382: my $pcr = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
3383: my $partial = $awarded eq '' ? '' : $pcr;
3384: my $score;
3385: if ($partial eq '') {
3386: $score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
3387: } elsif ($partial > 0) {
3388: $score = 'correct_by_override';
3389: } elsif ($partial == 0) {
3390: $score = 'incorrect_by_override';
3391: }
3392: my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
3393: $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
3394:
3395: $newrecord{'resource.'.$_.'.regrader'}=
3396: "$env{'user.name'}:$env{'user.domain'}";
3397: if ($dropMenu eq 'reset status' &&
3398: $old_score ne '') { # ignore if no previous attempts => nothing to reset
3399: $newrecord{'resource.'.$_.'.tries'} = '';
3400: $newrecord{'resource.'.$_.'.solved'} = '';
3401: $newrecord{'resource.'.$_.'.award'} = '';
3402: $newrecord{'resource.'.$_.'.awarded'} = '';
3403: $updateflag = 1;
3404: if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
3405: my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
3406: my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
3407: my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
3408: &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
3409: $aggregateflag = 1;
3410: }
3411: } elsif (!($old_part eq $partial && $old_score eq $score)) {
3412: $updateflag = 1;
3413: $newrecord{'resource.'.$_.'.awarded'} = $partial if $partial ne '';
3414: $newrecord{'resource.'.$_.'.solved'} = $score;
3415: $rec_update++;
3416: }
3417:
3418: $line .= '<td align="center">'.$old_aw.' </td>'.
3419: '<td align="center">'.$awarded.
3420: ($score eq 'excused' ? $score : '').' </td>';
3421:
3422:
3423: my $partid=$_;
3424: foreach my $stores (@parts) {
3425: my ($part,$type) = &split_part_type($stores);
3426: if ($part !~ m/^\Q$partid\E/) { next;}
3427: if ($type eq 'awarded' || $type eq 'solved') { next; }
3428: my $old_aw = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
3429: my $awarded = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
3430: if ($awarded ne '' && $awarded ne $old_aw) {
3431: $newrecord{'resource.'.$part.'.'.$type}= $awarded;
3432: $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
3433: $updateflag=1;
3434: }
3435: $line .= '<td align="center">'.$old_aw.' </td>'.
3436: '<td align="center">'.$awarded.' </td>';
3437: }
3438: }
3439: $line.='</tr>'."\n";
3440:
3441: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3442: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3443:
3444: if ($updateflag) {
3445: $count++;
3446: &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
3447: $udom,$uname);
3448:
3449: if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
3450: $cnum,$udom,$uname)) {
3451: # need to figure out if should be in queue.
3452: my %record =
3453: &Apache::lonnet::restore($symb,$env{'request.course.id'},
3454: $udom,$uname);
3455: my $all_graded = 1;
3456: my $none_graded = 1;
3457: foreach my $part (@parts) {
3458: if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
3459: $all_graded = 0;
3460: } else {
3461: $none_graded = 0;
3462: }
3463: }
3464:
3465: if ($all_graded || $none_graded) {
3466: &Apache::bridgetask::remove_from_queue('gradingqueue',
3467: $symb,$cdom,$cnum,
3468: $udom,$uname);
3469: }
3470: }
3471:
3472: $result.='<tr bgcolor="#ffffde"><td align="right"> '.$updateCtr.' </td>'.$line;
3473: $updateCtr++;
3474: } else {
3475: $noupdate.='<tr bgcolor="#ffffde"><td align="right"> '.$noupdateCtr.' </td>'.$line;
3476: $noupdateCtr++;
3477: }
3478: if ($aggregateflag) {
3479: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
3480: $cdom,$cnum);
3481: }
3482: }
3483: if ($noupdate) {
3484: # my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
3485: my $numcols=scalar(@partid)*4+2;
3486: $result .= '<tr bgcolor="#ffffff"><td align="center" colspan="'.$numcols.'">No Changes Occurred For the Students Below</td></tr><tr bgcolor="#ffffde">'.$noupdate;
3487: }
3488: $result .= '</table></td></tr></table>'."\n".
3489: &show_grading_menu_form ($symb);
3490: my $msg = '<br /><b>Number of records updated = '.$rec_update.
3491: ' for '.$count.' student'.($count <= 1 ? '' : 's').'.</b><br />'.
3492: '<b>Total number of students = '.$env{'form.total'}.'</b><br />';
3493: return $title.$msg.$result;
3494: }
3495:
3496: sub split_part_type {
3497: my ($partstr) = @_;
3498: my ($temp,@allparts)=split(/_/,$partstr);
3499: my $type=pop(@allparts);
3500: my $part=join('_',@allparts);
3501: return ($part,$type);
3502: }
3503:
3504: #------------- end of section for handling grading by section/class ---------
3505: #
3506: #----------------------------------------------------------------------------
3507:
3508:
3509: #----------------------------------------------------------------------------
3510: #
3511: #-------------------------- Next few routines handles grading by csv upload
3512: #
3513: #--- Javascript to handle csv upload
3514: sub csvupload_javascript_reverse_associate {
3515: my $error1=&mt('You need to specify the username or ID');
3516: my $error2=&mt('You need to specify at least one grading field');
3517: return(<<ENDPICK);
3518: function verify(vf) {
3519: var foundsomething=0;
3520: var founduname=0;
3521: var foundID=0;
3522: for (i=0;i<=vf.nfields.value;i++) {
3523: tw=eval('vf.f'+i+'.selectedIndex');
3524: if (i==0 && tw!=0) { foundID=1; }
3525: if (i==1 && tw!=0) { founduname=1; }
3526: if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
3527: }
3528: if (founduname==0 && foundID==0) {
3529: alert('$error1');
3530: return;
3531: }
3532: if (foundsomething==0) {
3533: alert('$error2');
3534: return;
3535: }
3536: vf.submit();
3537: }
3538: function flip(vf,tf) {
3539: var nw=eval('vf.f'+tf+'.selectedIndex');
3540: var i;
3541: for (i=0;i<=vf.nfields.value;i++) {
3542: //can not pick the same destination field for both name and domain
3543: if (((i ==0)||(i ==1)) &&
3544: ((tf==0)||(tf==1)) &&
3545: (i!=tf) &&
3546: (eval('vf.f'+i+'.selectedIndex')==nw)) {
3547: eval('vf.f'+i+'.selectedIndex=0;')
3548: }
3549: }
3550: }
3551: ENDPICK
3552: }
3553:
3554: sub csvupload_javascript_forward_associate {
3555: my $error1=&mt('You need to specify the username or ID');
3556: my $error2=&mt('You need to specify at least one grading field');
3557: return(<<ENDPICK);
3558: function verify(vf) {
3559: var foundsomething=0;
3560: var founduname=0;
3561: var foundID=0;
3562: for (i=0;i<=vf.nfields.value;i++) {
3563: tw=eval('vf.f'+i+'.selectedIndex');
3564: if (tw==1) { foundID=1; }
3565: if (tw==2) { founduname=1; }
3566: if (tw>3) { foundsomething=1; }
3567: }
3568: if (founduname==0 && foundID==0) {
3569: alert('$error1');
3570: return;
3571: }
3572: if (foundsomething==0) {
3573: alert('$error2');
3574: return;
3575: }
3576: vf.submit();
3577: }
3578: function flip(vf,tf) {
3579: var nw=eval('vf.f'+tf+'.selectedIndex');
3580: var i;
3581: //can not pick the same destination field twice
3582: for (i=0;i<=vf.nfields.value;i++) {
3583: if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
3584: eval('vf.f'+i+'.selectedIndex=0;')
3585: }
3586: }
3587: }
3588: ENDPICK
3589: }
3590:
3591: sub csvuploadmap_header {
3592: my ($request,$symb,$datatoken,$distotal)= @_;
3593: my $javascript;
3594: if ($env{'form.upfile_associate'} eq 'reverse') {
3595: $javascript=&csvupload_javascript_reverse_associate();
3596: } else {
3597: $javascript=&csvupload_javascript_forward_associate();
3598: }
3599:
3600: my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
3601: my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
3602: my $ignore=&mt('Ignore First Line');
3603: $symb = &Apache::lonenc::check_encrypt($symb);
3604: $request->print(<<ENDPICK);
3605: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3606: <h3><span class="LC_info">Uploading Class Grades</span></h3>
3607: $result
3608: <hr />
3609: <h3>Identify fields</h3>
3610: Total number of records found in file: $distotal <hr />
3611: Enter as many fields as you can. The system will inform you and bring you back
3612: to this page if the data selected is insufficient to run your class.<hr />
3613: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
3614: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
3615: <input type="hidden" name="associate" value="" />
3616: <input type="hidden" name="phase" value="three" />
3617: <input type="hidden" name="datatoken" value="$datatoken" />
3618: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
3619: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
3620: <input type="hidden" name="upfile_associate"
3621: value="$env{'form.upfile_associate'}" />
3622: <input type="hidden" name="symb" value="$symb" />
3623: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
3624: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
3625: <input type="hidden" name="command" value="csvuploadoptions" />
3626: <hr />
3627: <script type="text/javascript" language="Javascript">
3628: $javascript
3629: </script>
3630: ENDPICK
3631: return '';
3632:
3633: }
3634:
3635: sub csvupload_fields {
3636: my ($symb) = @_;
3637: my (@parts) = &getpartlist($symb);
3638: my @fields=(['ID','Student ID'],
3639: ['username','Student Username'],
3640: ['domain','Student Domain']);
3641: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3642: foreach my $part (sort(@parts)) {
3643: my @datum;
3644: my $display=&Apache::lonnet::metadata($url,$part.'.display');
3645: my $name=$part;
3646: if (!$display) { $display = $name; }
3647: @datum=($name,$display);
3648: if ($name=~/^stores_(.*)_awarded/) {
3649: push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
3650: }
3651: push(@fields,\@datum);
3652: }
3653: return (@fields);
3654: }
3655:
3656: sub csvuploadmap_footer {
3657: my ($request,$i,$keyfields) =@_;
3658: $request->print(<<ENDPICK);
3659: </table>
3660: <input type="hidden" name="nfields" value="$i" />
3661: <input type="hidden" name="keyfields" value="$keyfields" />
3662: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
3663: </form>
3664: ENDPICK
3665: }
3666:
3667: sub checkforfile_js {
3668: my $result =<<CSVFORMJS;
3669: <script type="text/javascript" language="javascript">
3670: function checkUpload(formname) {
3671: if (formname.upfile.value == "") {
3672: alert("Please use the browse button to select a file from your local directory.");
3673: return false;
3674: }
3675: formname.submit();
3676: }
3677: </script>
3678: CSVFORMJS
3679: return $result;
3680: }
3681:
3682: sub upcsvScores_form {
3683: my ($request) = shift;
3684: my ($symb)=&get_symb($request);
3685: if (!$symb) {return '';}
3686: my $result=&checkforfile_js();
3687: $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
3688: my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
3689: $result.=$table;
3690: $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
3691: $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
3692: $result.=' <b>'.&mt('Specify a file containing the class scores for current resource').
3693: '.</b></td></tr>'."\n";
3694: $result.='<tr bgcolor=#ffffe6><td>'."\n";
3695: my $upload=&mt("Upload Scores");
3696: my $upfile_select=&Apache::loncommon::upfile_select_html();
3697: my $ignore=&mt('Ignore First Line');
3698: $symb = &Apache::lonenc::check_encrypt($symb);
3699: $result.=<<ENDUPFORM;
3700: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3701: <input type="hidden" name="symb" value="$symb" />
3702: <input type="hidden" name="command" value="csvuploadmap" />
3703: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
3704: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
3705: $upfile_select
3706: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
3707: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
3708: </form>
3709: ENDUPFORM
3710: $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
3711: &mt("How do I create a CSV file from a spreadsheet"))
3712: .'</td></tr></table>'."\n";
3713: $result.='</td></tr></table><br /><br />'."\n";
3714: $result.=&show_grading_menu_form($symb);
3715: return $result;
3716: }
3717:
3718:
3719: sub csvuploadmap {
3720: my ($request)= @_;
3721: my ($symb)=&get_symb($request);
3722: if (!$symb) {return '';}
3723:
3724: my $datatoken;
3725: if (!$env{'form.datatoken'}) {
3726: $datatoken=&Apache::loncommon::upfile_store($request);
3727: } else {
3728: $datatoken=$env{'form.datatoken'};
3729: &Apache::loncommon::load_tmp_file($request);
3730: }
3731: my @records=&Apache::loncommon::upfile_record_sep();
3732: if ($env{'form.noFirstLine'}) { shift(@records); }
3733: &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
3734: my ($i,$keyfields);
3735: if (@records) {
3736: my @fields=&csvupload_fields($symb);
3737:
3738: if ($env{'form.upfile_associate'} eq 'reverse') {
3739: &Apache::loncommon::csv_print_samples($request,\@records);
3740: $i=&Apache::loncommon::csv_print_select_table($request,\@records,
3741: \@fields);
3742: foreach (@fields) { $keyfields.=$_->[0].','; }
3743: chop($keyfields);
3744: } else {
3745: unshift(@fields,['none','']);
3746: $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
3747: \@fields);
3748: foreach my $rec (@records) {
3749: my %temp = &Apache::loncommon::record_sep($rec);
3750: if (%temp) {
3751: $keyfields=join(',',sort(keys(%temp)));
3752: last;
3753: }
3754: }
3755: }
3756: }
3757: &csvuploadmap_footer($request,$i,$keyfields);
3758: $request->print(&show_grading_menu_form($symb));
3759:
3760: return '';
3761: }
3762:
3763: sub csvuploadoptions {
3764: my ($request)= @_;
3765: my ($symb)=&get_symb($request);
3766: my $checked=(($env{'form.noFirstLine'})?'1':'0');
3767: my $ignore=&mt('Ignore First Line');
3768: $request->print(<<ENDPICK);
3769: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3770: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
3771: <input type="hidden" name="command" value="csvuploadassign" />
3772: <!--
3773: <p>
3774: <label>
3775: <input type="checkbox" name="show_full_results" />
3776: Show a table of all changes
3777: </label>
3778: </p>
3779: -->
3780: <p>
3781: <label>
3782: <input type="checkbox" name="overwite_scores" checked="checked" />
3783: Overwrite any existing score
3784: </label>
3785: </p>
3786: ENDPICK
3787: my %fields=&get_fields();
3788: if (!defined($fields{'domain'})) {
3789: my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
3790: $request->print("\n<p> Users are in domain: ".$domform."</p>\n");
3791: }
3792: foreach my $key (sort(keys(%env))) {
3793: if ($key !~ /^form\.(.*)$/) { next; }
3794: my $cleankey=$1;
3795: if ($cleankey eq 'command') { next; }
3796: $request->print('<input type="hidden" name="'.$cleankey.
3797: '" value="'.$env{$key}.'" />'."\n");
3798: }
3799: # FIXME do a check for any duplicated user ids...
3800: # FIXME do a check for any invalid user ids?...
3801: $request->print('<input type="submit" value="Assign Grades" /><br />
3802: <hr /></form>'."\n");
3803: $request->print(&show_grading_menu_form($symb));
3804: return '';
3805: }
3806:
3807: sub get_fields {
3808: my %fields;
3809: my @keyfields = split(/\,/,$env{'form.keyfields'});
3810: for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
3811: if ($env{'form.upfile_associate'} eq 'reverse') {
3812: if ($env{'form.f'.$i} ne 'none') {
3813: $fields{$keyfields[$i]}=$env{'form.f'.$i};
3814: }
3815: } else {
3816: if ($env{'form.f'.$i} ne 'none') {
3817: $fields{$env{'form.f'.$i}}=$keyfields[$i];
3818: }
3819: }
3820: }
3821: return %fields;
3822: }
3823:
3824: sub csvuploadassign {
3825: my ($request)= @_;
3826: my ($symb)=&get_symb($request);
3827: if (!$symb) {return '';}
3828: my $error_msg = '';
3829: &Apache::loncommon::load_tmp_file($request);
3830: my @gradedata = &Apache::loncommon::upfile_record_sep();
3831: if ($env{'form.noFirstLine'}) { shift(@gradedata); }
3832: my %fields=&get_fields();
3833: $request->print('<h3>Assigning Grades</h3>');
3834: my $courseid=$env{'request.course.id'};
3835: my ($classlist) = &getclasslist('all',0);
3836: my @notallowed;
3837: my @skipped;
3838: my $countdone=0;
3839: foreach my $grade (@gradedata) {
3840: my %entries=&Apache::loncommon::record_sep($grade);
3841: my $domain;
3842: if ($entries{$fields{'domain'}}) {
3843: $domain=$entries{$fields{'domain'}};
3844: } else {
3845: $domain=$env{'form.default_domain'};
3846: }
3847: $domain=~s/\s//g;
3848: my $username=$entries{$fields{'username'}};
3849: $username=~s/\s//g;
3850: if (!$username) {
3851: my $id=$entries{$fields{'ID'}};
3852: $id=~s/\s//g;
3853: my %ids=&Apache::lonnet::idget($domain,$id);
3854: $username=$ids{$id};
3855: }
3856: if (!exists($$classlist{"$username:$domain"})) {
3857: my $id=$entries{$fields{'ID'}};
3858: $id=~s/\s//g;
3859: if ($id) {
3860: push(@skipped,"$id:$domain");
3861: } else {
3862: push(@skipped,"$username:$domain");
3863: }
3864: next;
3865: }
3866: my $usec=$classlist->{"$username:$domain"}[5];
3867: if (!&canmodify($usec)) {
3868: push(@notallowed,"$username:$domain");
3869: next;
3870: }
3871: my %points;
3872: my %grades;
3873: foreach my $dest (keys(%fields)) {
3874: if ($dest eq 'ID' || $dest eq 'username' ||
3875: $dest eq 'domain') { next; }
3876: if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
3877: if ($dest=~/stores_(.*)_points/) {
3878: my $part=$1;
3879: my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
3880: $symb,$domain,$username);
3881: if ($wgt) {
3882: $entries{$fields{$dest}}=~s/\s//g;
3883: my $pcr=$entries{$fields{$dest}} / $wgt;
3884: my $award='correct_by_override';
3885: $grades{"resource.$part.awarded"}=$pcr;
3886: $grades{"resource.$part.solved"}=$award;
3887: $points{$part}=1;
3888: } else {
3889: $error_msg = "<br />" .
3890: &mt("Some point values were assigned"
3891: ." for problems with a weight "
3892: ."of zero. These values were "
3893: ."ignored.");
3894: }
3895: } else {
3896: if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
3897: if ($dest=~/stores_(.*)_solved/) { if ($points{$1}) {next;} }
3898: my $store_key=$dest;
3899: $store_key=~s/^stores/resource/;
3900: $store_key=~s/_/\./g;
3901: $grades{$store_key}=$entries{$fields{$dest}};
3902: }
3903: }
3904: if (! %grades) { push(@skipped,"$username:$domain no data to save"); }
3905: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
3906: my $result=&Apache::lonnet::cstore(\%grades,$symb,
3907: $env{'request.course.id'},
3908: $domain,$username);
3909: if ($result eq 'ok') {
3910: $request->print('.');
3911: } else {
3912: $request->print("<p>
3913: <span class=\"LC_error\">
3914: Failed to save student $username:$domain.
3915: Message when trying to save was ($result)
3916: </span>
3917: </p>" );
3918: }
3919: $request->rflush();
3920: $countdone++;
3921: }
3922: $request->print("<br />Saved $countdone students\n");
3923: if (@skipped) {
3924: $request->print('<p><h4><b>Skipped Students</b></h4></p>');
3925: foreach my $student (@skipped) { $request->print("$student<br />\n"); }
3926: }
3927: if (@notallowed) {
3928: $request->print('<p><span class="LC_error">Students Not Allowed to Modify</span></p>');
3929: foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
3930: }
3931: $request->print("<br />\n");
3932: $request->print(&show_grading_menu_form($symb));
3933: return $error_msg;
3934: }
3935: #------------- end of section for handling csv file upload ---------
3936: #
3937: #-------------------------------------------------------------------
3938: #
3939: #-------------- Next few routines handle grading by page/sequence
3940: #
3941: #--- Select a page/sequence and a student to grade
3942: sub pickStudentPage {
3943: my ($request) = shift;
3944:
3945: $request->print(<<LISTJAVASCRIPT);
3946: <script type="text/javascript" language="javascript">
3947:
3948: function checkPickOne(formname) {
3949: if (radioSelection(formname.student) == null) {
3950: alert("Please select the student you wish to grade.");
3951: return;
3952: }
3953: ptr = pullDownSelection(formname.selectpage);
3954: formname.page.value = formname["page"+ptr].value;
3955: formname.title.value = formname["title"+ptr].value;
3956: formname.submit();
3957: }
3958:
3959: </script>
3960: LISTJAVASCRIPT
3961: &commonJSfunctions($request);
3962: my ($symb) = &get_symb($request);
3963: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
3964: my $cnum = $env{"course.$env{'request.course.id'}.num"};
3965: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
3966:
3967: my $result='<h3><span class="LC_info"> '.
3968: 'Manual Grading by Page or Sequence</span></h3>';
3969:
3970: $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
3971: $result.=' <b>Problems from:</b> <select name="selectpage">'."\n";
3972: my ($titles,$symbx) = &getSymbMap();
3973: my ($curpage) =&Apache::lonnet::decode_symb($symb);
3974: # my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb);
3975: # my $type=($curpage =~ /\.(page|sequence)/);
3976: my $ctr=0;
3977: foreach (@$titles) {
3978: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
3979: $result.='<option value="'.$ctr.'" '.
3980: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
3981: '>'.$showtitle.'</option>'."\n";
3982: $ctr++;
3983: }
3984: $result.= '</select>'."<br />\n";
3985: $ctr=0;
3986: foreach (@$titles) {
3987: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
3988: $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
3989: $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
3990: $ctr++;
3991: }
3992: $result.='<input type="hidden" name="page" />'."\n".
3993: '<input type="hidden" name="title" />'."\n";
3994:
3995: $result.=' <b>View Problems Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
3996: '<label><input type="radio" name="vProb" value="yes" /> yes </label>'."<br />\n";
3997:
3998: $result.=' <b>Submission Details: </b>'.
3999: '<label><input type="radio" name="lastSub" value="none" /> none</label>'."\n".
4000: '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> by dates and submissions</label>'."\n".
4001: '<label><input type="radio" name="lastSub" value="all" /> all details</label>'."\n";
4002:
4003: $result.=&build_section_inputs();
4004: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
4005: $result.='<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
4006: '<input type="hidden" name="command" value="displayPage" />'."\n".
4007: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
4008: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
4009:
4010: $result.=' <b>'.&mt('Use CODE:').' </b>'.
4011: '<input type="text" name="CODE" value="" /><br />'."\n";
4012:
4013: $result.=' <input type="button" '.
4014: 'onClick="javascript:checkPickOne(this.form);"value="Next->" /><br />'."\n";
4015:
4016: $request->print($result);
4017:
4018: my $studentTable.=' <b>Select a student you wish to grade and then click on the Next button.</b><br />'.
4019: '<table border="0"><tr><td bgcolor="#777777">'.
4020: '<table border="0"><tr bgcolor="#e6ffff">'.
4021: '<td align="right"> <b>No.</b></td>'.
4022: '<td>'.&nameUserString('header').'</td>'.
4023: '<td align="right"> <b>No.</b></td>'.
4024: '<td>'.&nameUserString('header').'</td></tr>';
4025:
4026: my (undef,undef,$fullname) = &getclasslist($getsec,'1');
4027: my $ptr = 1;
4028: foreach my $student (sort
4029: {
4030: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
4031: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
4032: }
4033: return $a cmp $b;
4034: } (keys(%$fullname))) {
4035: my ($uname,$udom) = split(/:/,$student);
4036: $studentTable.=($ptr%2 == 1 ? '<tr bgcolor="#ffffe6">' : '</td>');
4037: $studentTable.='<td align="right">'.$ptr.' </td>';
4038: $studentTable.='<td> <label><input type="radio" name="student" value="'.$student.'" /> '
4039: .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
4040: $studentTable.=($ptr%2 == 0 ? '</td></tr>' : '');
4041: $ptr++;
4042: }
4043: $studentTable.='</td><td> </td><td> </td></tr>' if ($ptr%2 == 0);
4044: $studentTable.='</table></td></tr></table>'."\n";
4045: $studentTable.='<input type="button" '.
4046: 'onClick="javascript:checkPickOne(this.form);"value="Next->" /></form>'."\n";
4047:
4048: $studentTable.=&show_grading_menu_form($symb);
4049: $request->print($studentTable);
4050:
4051: return '';
4052: }
4053:
4054: sub getSymbMap {
4055: my $navmap = Apache::lonnavmaps::navmap->new();
4056:
4057: my %symbx = ();
4058: my @titles = ();
4059: my $minder = 0;
4060:
4061: # Gather every sequence that has problems.
4062: my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
4063: 1,0,1);
4064: for my $sequence ($navmap->getById('0.0'), @sequences) {
4065: if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
4066: my $title = $minder.'.'.
4067: &HTML::Entities::encode($sequence->compTitle(),'"\'&');
4068: push(@titles, $title); # minder in case two titles are identical
4069: $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
4070: $minder++;
4071: }
4072: }
4073: return \@titles,\%symbx;
4074: }
4075:
4076: #
4077: #--- Displays a page/sequence w/wo problems, w/wo submissions
4078: sub displayPage {
4079: my ($request) = shift;
4080:
4081: my ($symb) = &get_symb($request);
4082: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4083: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4084: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4085: my $pageTitle = $env{'form.page'};
4086: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
4087: my ($uname,$udom) = split(/:/,$env{'form.student'});
4088: my $usec=$classlist->{$env{'form.student'}}[5];
4089:
4090: #need to make sure we have the correct data for later EXT calls,
4091: #thus invalidate the cache
4092: &Apache::lonnet::devalidatecourseresdata(
4093: $env{'course.'.$env{'request.course.id'}.'.num'},
4094: $env{'course.'.$env{'request.course.id'}.'.domain'});
4095: &Apache::lonnet::clear_EXT_cache_status();
4096:
4097: if (!&canview($usec)) {
4098: $request->print('<span class="LC_warning">Unable to view requested student.('.$env{'form.student'}.')</span>');
4099: $request->print(&show_grading_menu_form($symb));
4100: return;
4101: }
4102: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
4103: $result.='<h3> Student: '.&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom).
4104: '</h3>'."\n";
4105: if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
4106: $result.='<h3> CODE: '.$env{'form.CODE'}.'</h3>'."\n";
4107: } else {
4108: delete($env{'form.CODE'});
4109: }
4110: &sub_page_js($request);
4111: $request->print($result);
4112:
4113: my $navmap = Apache::lonnavmaps::navmap->new();
4114: my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
4115: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
4116: if (!$map) {
4117: $request->print('<span class="LC_warning">Unable to view requested sequence. ('.$resUrl.')</span>');
4118: $request->print(&show_grading_menu_form($symb));
4119: return;
4120: }
4121: my $iterator = $navmap->getIterator($map->map_start(),
4122: $map->map_finish());
4123:
4124: my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
4125: '<input type="hidden" name="command" value="gradeByPage" />'."\n".
4126: '<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
4127: '<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
4128: '<input type="hidden" name="page" value="'.$pageTitle.'" />'."\n".
4129: '<input type="hidden" name="title" value="'.$env{'form.title'}.'" />'."\n".
4130: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
4131: '<input type="hidden" name="overRideScore" value="no" />'."\n".
4132: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
4133:
4134: if (defined($env{'form.CODE'})) {
4135: $studentTable.=
4136: '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
4137: }
4138: my $checkIcon = '<img alt="'.&mt('Check Mark').
4139: '" src="'.$request->dir_config('lonIconsURL').
4140: '/check.gif" height="16" border="0" />';
4141:
4142: $studentTable.=' <b>Note:</b> Problems graded correct by the computer are marked with a '.$checkIcon.
4143: ' symbol.'."\n".
4144: '<table border="0"><tr><td bgcolor="#777777">'.
4145: '<table border="0"><tr bgcolor="#e6ffff">'.
4146: '<td align="center"><b> Prob. </b></td>'.
4147: '<td><b> '.($env{'form.vProb'} eq 'no' ? 'Title' : 'Problem Text').'/Grade</b></td></tr>';
4148:
4149: &Apache::lonxml::clear_problem_counter();
4150: my ($depth,$question,$prob) = (1,1,1);
4151: $iterator->next(); # skip the first BEGIN_MAP
4152: my $curRes = $iterator->next(); # for "current resource"
4153: while ($depth > 0) {
4154: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
4155: if($curRes == $iterator->END_MAP) { $depth--; }
4156:
4157: if (ref($curRes) && $curRes->is_problem()) {
4158: my $parts = $curRes->parts();
4159: my $title = $curRes->compTitle();
4160: my $symbx = $curRes->symb();
4161: $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
4162: (scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).' parts)').'</td>';
4163: $studentTable.='<td valign="top">';
4164: my %form = ('CODE' => $env{'form.CODE'},);
4165: if ($env{'form.vProb'} eq 'yes' ) {
4166: $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
4167: undef,'both',\%form);
4168: } else {
4169: my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
4170: $companswer =~ s|<form(.*?)>||g;
4171: $companswer =~ s|</form>||g;
4172: # while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
4173: # $companswer =~ s/$1/ /ms;
4174: # $request->print('match='.$1."<br />\n");
4175: # }
4176: # $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
4177: $studentTable.=' <b>'.$title.'</b> <br /> <b>Correct answer:</b><br />'.$companswer;
4178: }
4179:
4180: my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
4181:
4182: if ($env{'form.lastSub'} eq 'datesub') {
4183: if ($record{'version'} eq '') {
4184: $studentTable.='<br /> <span class="LC_warning">No recorded submission for this problem</span><br />';
4185: } else {
4186: my %responseType = ();
4187: foreach my $partid (@{$parts}) {
4188: my @responseIds =$curRes->responseIds($partid);
4189: my @responseType =$curRes->responseType($partid);
4190: my %responseIds;
4191: for (my $i=0;$i<=$#responseIds;$i++) {
4192: $responseIds{$responseIds[$i]}=$responseType[$i];
4193: }
4194: $responseType{$partid} = \%responseIds;
4195: }
4196: $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
4197:
4198: }
4199: } elsif ($env{'form.lastSub'} eq 'all') {
4200: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
4201: $studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
4202: $env{'request.course.id'},
4203: '','.submission');
4204:
4205: }
4206: if (&canmodify($usec)) {
4207: foreach my $partid (@{$parts}) {
4208: $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
4209: $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
4210: $question++;
4211: }
4212: $prob++;
4213: }
4214: $studentTable.='</td></tr>';
4215:
4216: }
4217: $curRes = $iterator->next();
4218: }
4219:
4220: $studentTable.='</table></td></tr></table>'."\n".
4221: '<input type="button" value="Save" '.
4222: 'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
4223: '</form>'."\n";
4224: $studentTable.=&show_grading_menu_form($symb);
4225: $request->print($studentTable);
4226:
4227: return '';
4228: }
4229:
4230: sub displaySubByDates {
4231: my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
4232: my $isCODE=0;
4233: my $isTask = ($symb =~/\.task$/);
4234: if (exists($record->{'resource.CODE'})) { $isCODE=1; }
4235: my $studentTable='<table border="0" width="100%"><tr><td bgcolor="#777777">'.
4236: '<table border="0" width="100%"><tr bgcolor="#e6ffff">'.
4237: '<td><b>Date/Time</b></td>'.
4238: ($isCODE?'<td><b>CODE</b></td>':'').
4239: '<td><b>Submission</b></td>'.
4240: '<td><b>Status </b></td></tr>';
4241: my ($version);
4242: my %mark;
4243: my %orders;
4244: $mark{'correct_by_student'} = $checkIcon;
4245: if (!exists($$record{'1:timestamp'})) {
4246: return '<br /> <span class="LC_warning">Nothing submitted - no attempts</span><br />';
4247: }
4248:
4249: my $interaction;
4250: for ($version=1;$version<=$$record{'version'};$version++) {
4251: my $timestamp = scalar(localtime($$record{$version.':timestamp'}));
4252: if (exists($$record{$version.':resource.0.version'})) {
4253: $interaction = $$record{$version.':resource.0.version'};
4254: }
4255:
4256: my $where = ($isTask ? "$version:resource.$interaction"
4257: : "$version:resource");
4258: $studentTable.='<tr bgcolor="#ffffff" valign="top"><td>'.$timestamp.'</td>';
4259: if ($isCODE) {
4260: $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
4261: }
4262: my @versionKeys = split(/\:/,$$record{$version.':keys'});
4263: my @displaySub = ();
4264: foreach my $partid (@{$parts}) {
4265: my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
4266: : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
4267:
4268:
4269: # next if ($$record{"$version:resource.$partid.solved"} eq '');
4270: my $display_part=&get_display_part($partid,$symb);
4271: foreach my $matchKey (@matchKey) {
4272: if (exists($$record{$version.':'.$matchKey}) &&
4273: $$record{$version.':'.$matchKey} ne '') {
4274:
4275: my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
4276: : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
4277: $displaySub[0].='<b>Part:</b> '.$display_part.' ';
4278: $displaySub[0].='<span class="LC_internal_info">(ID '.
4279: $responseId.')</span> <b>';
4280: if ($$record{"$where.$partid.tries"} eq '') {
4281: $displaySub[0].='Trial not counted';
4282: } else {
4283: $displaySub[0].='Trial '.
4284: $$record{"$where.$partid.tries"};
4285: }
4286: my $responseType=($isTask ? 'Task'
4287: : $responseType->{$partid}->{$responseId});
4288: if (!exists($orders{$partid})) { $orders{$partid}={}; }
4289: if (!exists($orders{$partid}->{$responseId})) {
4290: $orders{$partid}->{$responseId}=
4291: &get_order($partid,$responseId,$symb,$uname,$udom);
4292: }
4293: $displaySub[0].='</b> '.
4294: &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
4295: }
4296: }
4297: if (exists($$record{"$where.$partid.checkedin"})) {
4298: $displaySub[1].='Checked in by '.
4299: $$record{"$where.$partid.checkedin"}.' into slot '.
4300: $$record{"$where.$partid.checkedin.slot"}.
4301: '<br />';
4302: }
4303: if (exists $$record{"$where.$partid.award"}) {
4304: $displaySub[1].='<b>Part:</b> '.$display_part.' '.
4305: lc($$record{"$where.$partid.award"}).' '.
4306: $mark{$$record{"$where.$partid.solved"}}.
4307: '<br />';
4308: }
4309: if (exists $$record{"$where.$partid.regrader"}) {
4310: $displaySub[2].=$$record{"$where.$partid.regrader"}.
4311: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
4312: } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
4313: $displaySub[2].=
4314: $$record{"$version:resource.$partid.regrader"}.
4315: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
4316: }
4317: }
4318: # needed because old essay regrader has not parts info
4319: if (exists $$record{"$version:resource.regrader"}) {
4320: $displaySub[2].=$$record{"$version:resource.regrader"};
4321: }
4322: $studentTable.='<td>'.$displaySub[0].' </td><td>'.$displaySub[1];
4323: if ($displaySub[2]) {
4324: $studentTable.='Manually graded by '.$displaySub[2];
4325: }
4326: $studentTable.=' </td></tr>';
4327:
4328: }
4329: $studentTable.='</table></td></tr></table>';
4330: return $studentTable;
4331: }
4332:
4333: sub updateGradeByPage {
4334: my ($request) = shift;
4335:
4336: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4337: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4338: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4339: my $pageTitle = $env{'form.page'};
4340: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
4341: my ($uname,$udom) = split(/:/,$env{'form.student'});
4342: my $usec=$classlist->{$env{'form.student'}}[5];
4343: if (!&canmodify($usec)) {
4344: $request->print('<span class="LC_warning">Unable to modify requested student.('.$env{'form.student'}.'</span>');
4345: $request->print(&show_grading_menu_form($env{'form.symb'}));
4346: return;
4347: }
4348: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
4349: $result.='<h3> Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
4350: '</h3>'."\n";
4351:
4352: $request->print($result);
4353:
4354: my $navmap = Apache::lonnavmaps::navmap->new();
4355: my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
4356: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
4357: if (!$map) {
4358: $request->print('<span class="LC_warning">Unable to grade requested sequence. ('.$resUrl.')</span>');
4359: my ($symb)=&get_symb($request);
4360: $request->print(&show_grading_menu_form($symb));
4361: return;
4362: }
4363: my $iterator = $navmap->getIterator($map->map_start(),
4364: $map->map_finish());
4365:
4366: my $studentTable='<table border="0"><tr><td bgcolor="#777777">'.
4367: '<table border="0"><tr bgcolor="#e6ffff">'.
4368: '<td align="center"><b> Prob. </b></td>'.
4369: '<td><b> Title </b></td>'.
4370: '<td><b> Previous Score </b></td>'.
4371: '<td><b> New Score </b></td></tr>';
4372:
4373: $iterator->next(); # skip the first BEGIN_MAP
4374: my $curRes = $iterator->next(); # for "current resource"
4375: my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
4376: while ($depth > 0) {
4377: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
4378: if($curRes == $iterator->END_MAP) { $depth--; }
4379:
4380: if (ref($curRes) && $curRes->is_problem()) {
4381: my $parts = $curRes->parts();
4382: my $title = $curRes->compTitle();
4383: my $symbx = $curRes->symb();
4384: $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
4385: (scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).' parts)').'</td>';
4386: $studentTable.='<td valign="top"> <b>'.$title.'</b> </td>';
4387:
4388: my %newrecord=();
4389: my @displayPts=();
4390: my %aggregate = ();
4391: my $aggregateflag = 0;
4392: foreach my $partid (@{$parts}) {
4393: my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
4394: my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
4395:
4396: my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ?
4397: $env{'form.WGT'.$question.'_'.$partid} : 1;
4398: my $partial = $newpts/$wgt;
4399: my $score;
4400: if ($partial > 0) {
4401: $score = 'correct_by_override';
4402: } elsif ($newpts ne '') { #empty is taken as 0
4403: $score = 'incorrect_by_override';
4404: }
4405: my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
4406: if ($dropMenu eq 'excused') {
4407: $partial = '';
4408: $score = 'excused';
4409: } elsif ($dropMenu eq 'reset status'
4410: && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
4411: $newrecord{'resource.'.$partid.'.tries'} = 0;
4412: $newrecord{'resource.'.$partid.'.solved'} = '';
4413: $newrecord{'resource.'.$partid.'.award'} = '';
4414: $newrecord{'resource.'.$partid.'.awarded'} = 0;
4415: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
4416: $changeflag++;
4417: $newpts = '';
4418:
4419: my $aggtries = $env{'form.aggtries'.$question.'_'.$partid};
4420: my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
4421: my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
4422: if ($aggtries > 0) {
4423: &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
4424: $aggregateflag = 1;
4425: }
4426: }
4427: my $display_part=&get_display_part($partid,$curRes->symb());
4428: my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
4429: $displayPts[0].=' <b>Part:</b> '.$display_part.' = '.
4430: (($oldstatus eq 'excused') ? 'excused' : $oldpts).
4431: ' <br />';
4432: $displayPts[1].=' <b>Part:</b> '.$display_part.' = '.
4433: (($score eq 'excused') ? 'excused' : $newpts).
4434: ' <br />';
4435: $question++;
4436: next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
4437:
4438: $newrecord{'resource.'.$partid.'.awarded'} = $partial if $partial ne '';
4439: $newrecord{'resource.'.$partid.'.solved'} = $score if $score ne '';
4440: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
4441: if (scalar(keys(%newrecord)) > 0);
4442:
4443: $changeflag++;
4444: }
4445: if (scalar(keys(%newrecord)) > 0) {
4446: my %record =
4447: &Apache::lonnet::restore($symbx,$env{'request.course.id'},
4448: $udom,$uname);
4449:
4450: if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
4451: $newrecord{'resource.CODE'} = $env{'form.CODE'};
4452: } elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
4453: $newrecord{'resource.CODE'} = '';
4454: }
4455: &Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
4456: $udom,$uname);
4457: %record = &Apache::lonnet::restore($symbx,
4458: $env{'request.course.id'},
4459: $udom,$uname);
4460: &check_and_remove_from_queue($parts,\%record,undef,$symbx,
4461: $cdom,$cnum,$udom,$uname);
4462: }
4463:
4464: if ($aggregateflag) {
4465: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
4466: $env{'course.'.$env{'request.course.id'}.'.domain'},
4467: $env{'course.'.$env{'request.course.id'}.'.num'});
4468: }
4469:
4470: $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
4471: '<td valign="top">'.$displayPts[1].'</td>'.
4472: '</tr>';
4473:
4474: $prob++;
4475: }
4476: $curRes = $iterator->next();
4477: }
4478:
4479: $studentTable.='</td></tr></table></td></tr></table>';
4480: $studentTable.=&show_grading_menu_form($env{'form.symb'});
4481: my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
4482: 'The scores were changed for '.
4483: $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
4484: $request->print($grademsg.$studentTable);
4485:
4486: return '';
4487: }
4488:
4489: #-------- end of section for handling grading by page/sequence ---------
4490: #
4491: #-------------------------------------------------------------------
4492:
4493: #--------------------Scantron Grading-----------------------------------
4494: #
4495: #------ start of section for handling grading by page/sequence ---------
4496:
4497: =pod
4498:
4499: =head1 Bubble sheet grading routines
4500:
4501: For this documentation:
4502:
4503: 'scanline' refers to the full line of characters
4504: from the file that we are parsing that represents one entire sheet
4505:
4506: 'bubble line' refers to the data
4507: representing the line of bubbles that are on the physical bubble sheet
4508:
4509:
4510: The overall process is that a scanned in bubble sheet data is uploaded
4511: into a course. When a user wants to grade, they select a
4512: sequence/folder of resources, a file of bubble sheet info, and pick
4513: one of the predefined configurations for what each scanline looks
4514: like.
4515:
4516: Next each scanline is checked for any errors of either 'missing
4517: bubbles' (it's an error because it may have been mis-scanned
4518: because too light bubbling), 'double bubble' (each bubble line should
4519: have no more that one letter picked), invalid or duplicated CODE,
4520: invalid student ID
4521:
4522: If the CODE option is used that determines the randomization of the
4523: homework problems, either way the student ID is looked up into a
4524: username:domain.
4525:
4526: During the validation phase the instructor can choose to skip scanlines.
4527:
4528: After the validation phase, there are now 3 bubble sheet files
4529:
4530: scantron_original_filename (unmodified original file)
4531: scantron_corrected_filename (file where the corrected information has replaced the original information)
4532: scantron_skipped_filename (contains the exact text of scanlines that where skipped)
4533:
4534: Also there is a separate hash nohist_scantrondata that contains extra
4535: correction information that isn't representable in the bubble sheet
4536: file (see &scantron_getfile() for more information)
4537:
4538: After all scanlines are either valid, marked as valid or skipped, then
4539: foreach line foreach problem in the picked sequence, an ssi request is
4540: made that simulates a user submitting their selected letter(s) against
4541: the homework problem.
4542:
4543: =over 4
4544:
4545:
4546:
4547: =item defaultFormData
4548:
4549: Returns html hidden inputs used to hold context/default values.
4550:
4551: Arguments:
4552: $symb - $symb of the current resource
4553:
4554: =cut
4555:
4556: sub defaultFormData {
4557: my ($symb)=@_;
4558: return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
4559: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
4560: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
4561: }
4562:
4563:
4564: =pod
4565:
4566: =item getSequenceDropDown
4567:
4568: Return html dropdown of possible sequences to grade
4569:
4570: Arguments:
4571: $symb - $symb of the current resource
4572:
4573: =cut
4574:
4575: sub getSequenceDropDown {
4576: my ($symb)=@_;
4577: my $result='<select name="selectpage">'."\n";
4578: my ($titles,$symbx) = &getSymbMap();
4579: my ($curpage)=&Apache::lonnet::decode_symb($symb);
4580: my $ctr=0;
4581: foreach (@$titles) {
4582: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4583: $result.='<option value="'.$$symbx{$_}.'" '.
4584: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
4585: '>'.$showtitle.'</option>'."\n";
4586: $ctr++;
4587: }
4588: $result.= '</select>';
4589: return $result;
4590: }
4591:
4592:
4593: =pod
4594:
4595: =item scantron_filenames
4596:
4597: Returns a list of the scantron files in the current course
4598:
4599: =cut
4600:
4601: sub scantron_filenames {
4602: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4603: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
4604: my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
4605: &propath($cdom,$cname));
4606: my @possiblenames;
4607: foreach my $filename (sort(@files)) {
4608: ($filename)=split(/&/,$filename);
4609: if ($filename!~/^scantron_orig_/) { next ; }
4610: $filename=~s/^scantron_orig_//;
4611: push(@possiblenames,$filename);
4612: }
4613: return @possiblenames;
4614: }
4615:
4616: =pod
4617:
4618: =item scantron_uploads
4619:
4620: Returns html drop-down list of scantron files in current course.
4621:
4622: Arguments:
4623: $file2grade - filename to set as selected in the dropdown
4624:
4625: =cut
4626:
4627: sub scantron_uploads {
4628: my ($file2grade) = @_;
4629: my $result= '<select name="scantron_selectfile">';
4630: $result.="<option></option>";
4631: foreach my $filename (sort(&scantron_filenames())) {
4632: $result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
4633: }
4634: $result.="</select>";
4635: return $result;
4636: }
4637:
4638: =pod
4639:
4640: =item scantron_scantab
4641:
4642: Returns html drop down of the scantron formats in the scantronformat.tab
4643: file.
4644:
4645: =cut
4646:
4647: sub scantron_scantab {
4648: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
4649: my $result='<select name="scantron_format">'."\n";
4650: $result.='<option></option>'."\n";
4651: foreach my $line (<$fh>) {
4652: my ($name,$descrip)=split(/:/,$line);
4653: if ($name =~ /^\#/) { next; }
4654: $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
4655: }
4656: $result.='</select>'."\n";
4657:
4658: return $result;
4659: }
4660:
4661: =pod
4662:
4663: =item scantron_CODElist
4664:
4665: Returns html drop down of the saved CODE lists from current course,
4666: generated from earlier printings.
4667:
4668: =cut
4669:
4670: sub scantron_CODElist {
4671: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4672: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4673: my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
4674: my $namechoice='<option></option>';
4675: foreach my $name (sort {uc($a) cmp uc($b)} @names) {
4676: if ($name =~ /^error: 2 /) { next; }
4677: if ($name =~ /^type\0/) { next; }
4678: $namechoice.='<option value="'.$name.'">'.$name.'</option>';
4679: }
4680: $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
4681: return $namechoice;
4682: }
4683:
4684: =pod
4685:
4686: =item scantron_CODEunique
4687:
4688: Returns the html for "Each CODE to be used once" radio.
4689:
4690: =cut
4691:
4692: sub scantron_CODEunique {
4693: my $result='<span style="white-space: nowrap;">
4694: <label><input type="radio" name="scantron_CODEunique"
4695: value="yes" checked="checked" />'.&mt('Yes').' </label>
4696: </span>
4697: <span style="white-space: nowrap;">
4698: <label><input type="radio" name="scantron_CODEunique"
4699: value="no" />'.&mt('No').' </label>
4700: </span>';
4701: return $result;
4702: }
4703:
4704: =pod
4705:
4706: =item scantron_selectphase
4707:
4708: Generates the initial screen to start the bubble sheet process.
4709: Allows for - starting a grading run.
4710: - downloading existing scan data (original, corrected
4711: or skipped info)
4712:
4713: - uploading new scan data
4714:
4715: Arguments:
4716: $r - The Apache request object
4717: $file2grade - name of the file that contain the scanned data to score
4718:
4719: =cut
4720:
4721: sub scantron_selectphase {
4722: my ($r,$file2grade) = @_;
4723: my ($symb)=&get_symb($r);
4724: if (!$symb) {return '';}
4725: my $sequence_selector=&getSequenceDropDown($symb);
4726: my $default_form_data=&defaultFormData($symb);
4727: my $grading_menu_button=&show_grading_menu_form($symb);
4728: my $file_selector=&scantron_uploads($file2grade);
4729: my $format_selector=&scantron_scantab();
4730: my $CODE_selector=&scantron_CODElist();
4731: my $CODE_unique=&scantron_CODEunique();
4732: my $result;
4733:
4734: # Chunk of form to prompt for a file to grade and how:
4735:
4736: $result.= <<SCANTRONFORM;
4737: <table width="100%" border="0">
4738: <tr>
4739: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
4740: <td bgcolor="#777777">
4741: <input type="hidden" name="command" value="scantron_warning" />
4742: $default_form_data
4743: <table width="100%" border="0">
4744: <tr bgcolor="#e6ffff">
4745: <td colspan="2">
4746: <b>Specify file and which Folder/Sequence to grade</b>
4747: </td>
4748: </tr>
4749: <tr bgcolor="#ffffe6">
4750: <td> Sequence to grade: </td><td> $sequence_selector </td>
4751: </tr>
4752: <tr bgcolor="#ffffe6">
4753: <td> Filename of scoring office file: </td><td> $file_selector </td>
4754: </tr>
4755: <tr bgcolor="#ffffe6">
4756: <td> Format of data file: </td><td> $format_selector </td>
4757: </tr>
4758: <tr bgcolor="#ffffe6">
4759: <td> Saved CODEs to validate against: </td><td> $CODE_selector</td>
4760: </tr>
4761: <tr bgcolor="#ffffe6">
4762: <td> Each CODE is only to be used once:</td><td> $CODE_unique </td>
4763: </tr>
4764: <tr bgcolor="#ffffe6">
4765: <td> Options: </td>
4766: <td>
4767: <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> Do only previously skipped records</label> <br />
4768: <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> Remove all existing corrections</label> <br />
4769: <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> Skip hidden resources when grading</label>
4770: </td>
4771: </tr>
4772: <tr bgcolor="#ffffe6">
4773: <td colspan="2">
4774: <input type="submit" value="Grading: Validate Scantron Records" />
4775: </td>
4776: </tr>
4777: </table>
4778: </td>
4779: </form>
4780: </tr>
4781: SCANTRONFORM
4782:
4783: $r->print($result);
4784:
4785: if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
4786: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
4787:
4788: # Chunk of form to prompt for a scantron file upload.
4789:
4790: $r->print(<<SCANTRONFORM);
4791: <tr>
4792: <td bgcolor="#777777">
4793: <table width="100%" border="0">
4794: <tr bgcolor="#e6ffff">
4795: <td>
4796: <b>Specify a Scantron data file to upload.</b>
4797: </td>
4798: </tr>
4799: <tr bgcolor="#ffffe6">
4800: <td>
4801: SCANTRONFORM
4802: my $default_form_data=&defaultFormData(&get_symb($r,1));
4803: my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
4804: my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
4805: $r->print(<<UPLOAD);
4806: <script type="text/javascript" language="javascript">
4807: function checkUpload(formname) {
4808: if (formname.upfile.value == "") {
4809: alert("Please use the browse button to select a file from your local directory.");
4810: return false;
4811: }
4812: formname.submit();
4813: }
4814: </script>
4815:
4816: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
4817: $default_form_data
4818: <input name='courseid' type='hidden' value='$cnum' />
4819: <input name='domainid' type='hidden' value='$cdom' />
4820: <input name='command' value='scantronupload_save' type='hidden' />
4821: File to upload:<input type="file" name="upfile" size="50" />
4822: <br />
4823: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
4824: </form>
4825: UPLOAD
4826:
4827: $r->print(<<SCANTRONFORM);
4828: </td>
4829: </tr>
4830: </table>
4831: </td>
4832: </tr>
4833: SCANTRONFORM
4834: }
4835:
4836: # Chunk of the form that prompts to view a scoring office file,
4837: # corrected file, skipped records in a file.
4838:
4839: $r->print(<<SCANTRONFORM);
4840: <tr>
4841: <form action='/adm/grades' name='scantron_download'>
4842: <td bgcolor="#777777">
4843: $default_form_data
4844: <input type="hidden" name="command" value="scantron_download" />
4845: <table width="100%" border="0">
4846: <tr bgcolor="#e6ffff">
4847: <td colspan="2">
4848: <b>Download a scoring office file</b>
4849: </td>
4850: </tr>
4851: <tr bgcolor="#ffffe6">
4852: <td> Filename of scoring office file: </td><td> $file_selector </td>
4853: </tr>
4854: <tr bgcolor="#ffffe6">
4855: <td colspan="2">
4856: <input type="submit" value="Download: Show List of Associated Files" />
4857: </td>
4858: </tr>
4859: </table>
4860: </td>
4861: </form>
4862: </tr>
4863: SCANTRONFORM
4864:
4865: $r->print(<<SCANTRONFORM);
4866: </table>
4867: $grading_menu_button
4868: SCANTRONFORM
4869:
4870: return
4871: }
4872:
4873: =pod
4874:
4875: =item get_scantron_config
4876:
4877: Parse and return the scantron configuration line selected as a
4878: hash of configuration file fields.
4879:
4880: Arguments:
4881: which - the name of the configuration to parse from the file.
4882:
4883:
4884: Returns:
4885: If the named configuration is not in the file, an empty
4886: hash is returned.
4887: a hash with the fields
4888: name - internal name for the this configuration setup
4889: description - text to display to operator that describes this config
4890: CODElocation - if 0 or the string 'none'
4891: - no CODE exists for this config
4892: if -1 || the string 'letter'
4893: - a CODE exists for this config and is
4894: a string of letters
4895: Unsupported value (but planned for future support)
4896: if a positive integer
4897: - The CODE exists as the first n items from
4898: the question section of the form
4899: if the string 'number'
4900: - The CODE exists for this config and is
4901: a string of numbers
4902: CODEstart - (only matter if a CODE exists) column in the line where
4903: the CODE starts
4904: CODElength - length of the CODE
4905: IDstart - column where the student ID number starts
4906: IDlength - length of the student ID info
4907: Qstart - column where the information from the bubbled
4908: 'questions' start
4909: Qlength - number of columns comprising a single bubble line from
4910: the sheet. (usually either 1 or 10)
4911: Qon - either a single character representing the character used
4912: to signal a bubble was chosen in the positional setup, or
4913: the string 'letter' if the letter of the chosen bubble is
4914: in the final, or 'number' if a number representing the
4915: chosen bubble is in the file (1->A 0->J)
4916: Qoff - the character used to represent that a bubble was
4917: left blank
4918: PaperID - if the scanning process generates a unique number for each
4919: sheet scanned the column that this ID number starts in
4920: PaperIDlength - number of columns that comprise the unique ID number
4921: for the sheet of paper
4922: FirstName - column that the first name starts in
4923: FirstNameLength - number of columns that the first name spans
4924:
4925: LastName - column that the last name starts in
4926: LastNameLength - number of columns that the last name spans
4927:
4928: =cut
4929:
4930: sub get_scantron_config {
4931: my ($which) = @_;
4932: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
4933: my %config;
4934: #FIXME probably should move to XML it has already gotten a bit much now
4935: foreach my $line (<$fh>) {
4936: my ($name,$descrip)=split(/:/,$line);
4937: if ($name ne $which ) { next; }
4938: chomp($line);
4939: my @config=split(/:/,$line);
4940: $config{'name'}=$config[0];
4941: $config{'description'}=$config[1];
4942: $config{'CODElocation'}=$config[2];
4943: $config{'CODEstart'}=$config[3];
4944: $config{'CODElength'}=$config[4];
4945: $config{'IDstart'}=$config[5];
4946: $config{'IDlength'}=$config[6];
4947: $config{'Qstart'}=$config[7];
4948: $config{'Qlength'}=$config[8];
4949: $config{'Qoff'}=$config[9];
4950: $config{'Qon'}=$config[10];
4951: $config{'PaperID'}=$config[11];
4952: $config{'PaperIDlength'}=$config[12];
4953: $config{'FirstName'}=$config[13];
4954: $config{'FirstNamelength'}=$config[14];
4955: $config{'LastName'}=$config[15];
4956: $config{'LastNamelength'}=$config[16];
4957: last;
4958: }
4959: return %config;
4960: }
4961:
4962: =pod
4963:
4964: =item username_to_idmap
4965:
4966: creates a hash keyed by student id with values of the corresponding
4967: student username:domain.
4968:
4969: Arguments:
4970:
4971: $classlist - reference to the class list hash. This is a hash
4972: keyed by student name:domain whose elements are references
4973: to arrays containing various chunks of information
4974: about the student. (See loncoursedata for more info).
4975:
4976: Returns
4977: %idmap - the constructed hash
4978:
4979: =cut
4980:
4981: sub username_to_idmap {
4982: my ($classlist)= @_;
4983: my %idmap;
4984: foreach my $student (keys(%$classlist)) {
4985: $idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
4986: $student;
4987: }
4988: return %idmap;
4989: }
4990:
4991: =pod
4992:
4993: =item scantron_fixup_scanline
4994:
4995: Process a requested correction to a scanline.
4996:
4997: Arguments:
4998: $scantron_config - hash from &get_scantron_config()
4999: $scan_data - hash of correction information
5000: (see &scantron_getfile())
5001: $line - existing scanline
5002: $whichline - line number of the passed in scanline
5003: $field - type of change to process
5004: (either
5005: 'ID' -> correct the student ID number
5006: 'CODE' -> correct the CODE
5007: 'answer' -> fixup the submitted answers)
5008:
5009: $args - hash of additional info,
5010: - 'ID'
5011: 'newid' -> studentID to use in replacement
5012: of existing one
5013: - 'CODE'
5014: 'CODE_ignore_dup' - set to true if duplicates
5015: should be ignored.
5016: 'CODE' - is new code or 'use_unfound'
5017: if the existing unfound code should
5018: be used as is
5019: - 'answer'
5020: 'response' - new answer or 'none' if blank
5021: 'question' - the bubble line to change
5022:
5023: Returns:
5024: $line - the modified scanline
5025:
5026: Side effects:
5027: $scan_data - may be updated
5028:
5029: =cut
5030:
5031:
5032: sub scantron_fixup_scanline {
5033: my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
5034:
5035: if ($field eq 'ID') {
5036: if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
5037: return ($line,1,'New value too large');
5038: }
5039: if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
5040: $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
5041: $args->{'newid'});
5042: }
5043: substr($line,$$scantron_config{'IDstart'}-1,
5044: $$scantron_config{'IDlength'})=$args->{'newid'};
5045: if ($args->{'newid'}=~/^\s*$/) {
5046: &scan_data($scan_data,"$whichline.user",
5047: $args->{'username'}.':'.$args->{'domain'});
5048: }
5049: } elsif ($field eq 'CODE') {
5050: if ($args->{'CODE_ignore_dup'}) {
5051: &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
5052: }
5053: &scan_data($scan_data,"$whichline.useCODE",'1');
5054: if ($args->{'CODE'} ne 'use_unfound') {
5055: if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
5056: return ($line,1,'New CODE value too large');
5057: }
5058: if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
5059: $args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
5060: }
5061: substr($line,$$scantron_config{'CODEstart'}-1,
5062: $$scantron_config{'CODElength'})=$args->{'CODE'};
5063: }
5064: } elsif ($field eq 'answer') {
5065: my $length=$scantron_config->{'Qlength'};
5066: my $off=$scantron_config->{'Qoff'};
5067: my $on=$scantron_config->{'Qon'};
5068: my $answer=${off}x$length;
5069: if ($args->{'response'} eq 'none') {
5070: &scan_data($scan_data,
5071: "$whichline.no_bubble.".$args->{'question'},'1');
5072: } else {
5073: if ($on eq 'letter') {
5074: my @alphabet=('A'..'Z');
5075: $answer=$alphabet[$args->{'response'}];
5076: } elsif ($on eq 'number') {
5077: $answer=$args->{'response'}+1;
5078: if ($answer == 10) { $answer = '0'; }
5079: } else {
5080: substr($answer,$args->{'response'},1)=$on;
5081: }
5082: &scan_data($scan_data,
5083: "$whichline.no_bubble.".$args->{'question'},undef,'1');
5084: }
5085: my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
5086: substr($line,$where-1,$length)=$answer;
5087: }
5088: return $line;
5089: }
5090:
5091: =pod
5092:
5093: =item scan_data
5094:
5095: Edit or look up an item in the scan_data hash.
5096:
5097: Arguments:
5098: $scan_data - The hash (see scantron_getfile)
5099: $key - shorthand of the key to edit (actual key is
5100: scantronfilename_key).
5101: $data - New value of the hash entry.
5102: $delete - If true, the entry is removed from the hash.
5103:
5104: Returns:
5105: The new value of the hash table field (undefined if deleted).
5106:
5107: =cut
5108:
5109:
5110: sub scan_data {
5111: my ($scan_data,$key,$value,$delete)=@_;
5112: my $filename=$env{'form.scantron_selectfile'};
5113: if (defined($value)) {
5114: $scan_data->{$filename.'_'.$key} = $value;
5115: }
5116: if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
5117: return $scan_data->{$filename.'_'.$key};
5118: }
5119:
5120: =pod
5121:
5122: =item scantron_parse_scanline
5123:
5124: Decodes a scanline from the selected scantron file
5125:
5126: Arguments:
5127: line - The text of the scantron file line to process
5128: whichline - Line number
5129: scantron_config - Hash describing the format of the scantron lines.
5130: scan_data - Hash of extra information about the scanline
5131: (see scantron_getfile for more information)
5132: just_header - True if should not process question answers but only
5133: the stuff to the left of the answers.
5134: Returns:
5135: Hash containing the result of parsing the scanline
5136:
5137: Keys are all proceeded by the string 'scantron.'
5138:
5139: CODE - the CODE in use for this scanline
5140: useCODE - 1 if the CODE is invalid but it usage has been forced
5141: by the operator
5142: CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
5143: CODEs were selected, but the usage has been
5144: forced by the operator
5145: ID - student ID
5146: PaperID - if used, the ID number printed on the sheet when the
5147: paper was scanned
5148: FirstName - first name from the sheet
5149: LastName - last name from the sheet
5150:
5151: if just_header was not true these key may also exist
5152:
5153: missingerror - a list of bubble ranges that are considered to be answers
5154: to a single question that don't have any bubbles filled in.
5155: Of the form questionnumber:firstbubblenumber:count.
5156: doubleerror - a list of bubble ranges that are considered to be answers
5157: to a single question that have more than one bubble filled in.
5158: Of the form questionnumber::firstbubblenumber:count
5159:
5160: In the above, count is the number of bubble responses in the
5161: input line needed to represent the possible answers to the question.
5162: e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
5163: per line would have count = 2.
5164:
5165: maxquest - the number of the last bubble line that was parsed
5166:
5167: (<number> starts at 1)
5168: <number>.answer - zero or more letters representing the selected
5169: letters from the scanline for the bubble line
5170: <number>.
5171: if blank there was either no bubble or there where
5172: multiple bubbles, (consult the keys missingerror and
5173: doubleerror if this is an error condition)
5174:
5175: =cut
5176:
5177: sub scantron_parse_scanline {
5178: my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
5179: my %record;
5180: my $questions=substr($line,$$scantron_config{'Qstart'}-1); # Answers
5181: my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # earlier stuff
5182: if (!($$scantron_config{'CODElocation'} eq 0 ||
5183: $$scantron_config{'CODElocation'} eq 'none')) {
5184: if ($$scantron_config{'CODElocation'} < 0 ||
5185: $$scantron_config{'CODElocation'} eq 'letter' ||
5186: $$scantron_config{'CODElocation'} eq 'number') {
5187: $record{'scantron.CODE'}=substr($data,
5188: $$scantron_config{'CODEstart'}-1,
5189: $$scantron_config{'CODElength'});
5190: if (&scan_data($scan_data,"$whichline.useCODE")) {
5191: $record{'scantron.useCODE'}=1;
5192: }
5193: if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
5194: $record{'scantron.CODE_ignore_dup'}=1;
5195: }
5196: } else {
5197: #FIXME interpret first N questions
5198: }
5199: }
5200: $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
5201: $$scantron_config{'IDlength'});
5202: $record{'scantron.PaperID'}=
5203: substr($data,$$scantron_config{'PaperID'}-1,
5204: $$scantron_config{'PaperIDlength'});
5205: $record{'scantron.FirstName'}=
5206: substr($data,$$scantron_config{'FirstName'}-1,
5207: $$scantron_config{'FirstNamelength'});
5208: $record{'scantron.LastName'}=
5209: substr($data,$$scantron_config{'LastName'}-1,
5210: $$scantron_config{'LastNamelength'});
5211: if ($just_header) { return \%record; }
5212:
5213: my @alphabet=('A'..'Z');
5214: my $questnum=0;
5215: my $ansnum =1; # Multiple 'answer lines'/question.
5216:
5217: while ($questions) {
5218: my $answers_needed = $bubble_lines_per_response{$questnum};
5219: my $answer_length = $$scantron_config{'Qlength'} * $answers_needed;
5220:
5221:
5222:
5223: $questnum++;
5224: my $currentquest = substr($questions,0,$answer_length);
5225: $questions = substr($questions,0,$answer_length)='';
5226: if (length($currentquest) < $answer_length) { next; }
5227:
5228: # Qon letter implies for each slot in currentquest we have:
5229: # ? or * for doubles a letter in A-Z for a bubble and
5230: # about anything else (esp. a value of Qoff for missing
5231: # bubbles.
5232:
5233:
5234: if ($$scantron_config{'Qon'} eq 'letter') {
5235:
5236: if ($currentquest =~ /\?/
5237: || $currentquest =~ /\*/
5238: || (&occurence_count($currentquest, "[A-Z]") > 1)) {
5239: push(@{$record{'scantron.doubleerror'}},$questnum);
5240: for (my $ans = 0; $ans < $answers_needed; $ans++) {
5241: $record{"scantron.$ansnum.answer"}='';
5242: $ansnum++;
5243: }
5244:
5245: } elsif (!defined($currentquest)
5246: || (&occurence_count($currentquest, $$scantron_config{'Qoff'}) == length($currentquest))
5247: || (&occurence_count($currentquest, "[A-Z]") == 0)) {
5248: for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
5249: $record{"scantron.$ansnum.answer"}='';
5250: $ansnum++;
5251:
5252: }
5253: if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
5254: push(@{$record{"scantron.missingerror"}},$questnum);
5255: $ansnum += $answers_needed;
5256: }
5257:
5258: } else {
5259: for (my $ans = 0; $ans < $answers_needed; $ans++) {
5260: $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
5261: $ansnum++;
5262: }
5263: }
5264:
5265: # Qon 'number' implies each slot gives a digit that indexes the
5266: # the bubbles filled or Qoff or a non number for unbubbled lines.
5267: # and *? for double bubbles on a line.
5268: # these answers are also stored as letters.
5269:
5270: } elsif ($$scantron_config{'Qon'} eq 'number') {
5271: if ($currentquest =~ /\?/
5272: || $currentquest =~ /\*/
5273: || (&occurence_count($currentquest, '\d') > 1)) {
5274: push(@{$record{'scantron.doubleerror'}},$questnum);
5275: for (my $ans = 0; $ans < $answers_needed; $ans++) {
5276: $record{"scantron.$ansnum.answer"}='';
5277: $ansnum++;
5278: }
5279:
5280: } elsif (!defined($currentquest)
5281: || (&occurence_count($currentquest,$$scantron_config{'Qoff'}) == length($currentquest))
5282: || (&occurence_count($currentquest, '\d') == 0)) {
5283: for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
5284: $record{"scantron.$ansnum.answer"}='';
5285: $ansnum++;
5286:
5287: }
5288: if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
5289: push(@{$record{"scantron.missingerror"}},$questnum);
5290: $ansnum += $answers_needed;
5291: }
5292:
5293: } else {
5294: $currentquest = &digits_to_letters($currentquest);
5295: for (my $ans =0; $ans < $answers_needed; $ans++) {
5296: $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
5297: $ansnum++;
5298: }
5299: }
5300: } else {
5301:
5302: # Otherwise there's a positional notation;
5303: # each bubble line requires Qlength items, and there are filled in
5304: # bubbles for each case where there 'Qon' characters.
5305: #
5306:
5307: my @array=split($$scantron_config{'Qon'},$currentquest,-1);
5308:
5309: # If the split only giveas us one element.. the full length of the
5310: # answser string, no bubbles are filled in:
5311:
5312: if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
5313: for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
5314: $record{"scantron.$ansnum.answer"}='';
5315: $ansnum++;
5316:
5317: }
5318: if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
5319: push(@{$record{"scantron.missingerror"}},$questnum);
5320: }
5321: } elsif (scalar(@array) lt 2) {
5322:
5323: my $location = [length($array[0])];
5324: my $line_num = $location / $$scantron_config{'Qlength'};
5325: my $bubble = $alphabet[$location % $$scantron_config{'Qlength'}];
5326:
5327: for (my $ans = 0; $ans < $answers_needed; $ans++) {
5328: if ($ans eq $line_num) {
5329: $record{"scantron.$ansnum.answer"} = $bubble;
5330: } else {
5331: $record{"scantron.$ansnum.answer"} = ' ';
5332: }
5333: $ansnum++;
5334: }
5335: }
5336: # If there's more than one instance of a bubble character
5337: # That's a double bubble; with positional notation we can
5338: # record all the bubbles filled in as well as the
5339: # fact this response consists of multiple bubbles.
5340: #
5341: else {
5342: push(@{$record{'scantron.doubleerror'}},$questnum);
5343:
5344: my $first_answer = $ansnum;
5345: for (my $ans =0; $ans < $answers_needed; $ans++) {
5346: $record{"scantron.$ansnum.answer"} = '';
5347: $ans++;
5348: }
5349:
5350: my @ans=@array;
5351: my $i=length($ans[0]);shift(@ans);
5352: while ($#ans) {
5353: $i+=length($ans[0])+1;
5354: my $line = $i/$$scantron_config{'Qlength'} + $first_answer;
5355: my $bubble = $i%$$scantron_config{'Qlength'};
5356:
5357: $record{"scantron.$line.answer"}.=$alphabet[$bubble];
5358: shift(@ans);
5359: }
5360: }
5361: }
5362: }
5363: $record{'scantron.maxquest'}=$questnum;
5364: return \%record;
5365: }
5366:
5367: =pod
5368:
5369: =item scantron_add_delay
5370:
5371: Adds an error message that occurred during the grading phase to a
5372: queue of messages to be shown after grading pass is complete
5373:
5374: Arguments:
5375: $delayqueue - arrary ref of hash ref of error messages
5376: $scanline - the scanline that caused the error
5377: $errormesage - the error message
5378: $errorcode - a numeric code for the error
5379:
5380: Side Effects:
5381: updates the $delayqueue to have a new hash ref of the error
5382:
5383: =cut
5384:
5385: sub scantron_add_delay {
5386: my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
5387: push(@$delayqueue,
5388: {'line' => $scanline, 'emsg' => $errormessage,
5389: 'ecode' => $errorcode }
5390: );
5391: }
5392:
5393: =pod
5394:
5395: =item scantron_find_student
5396:
5397: Finds the username for the current scanline
5398:
5399: Arguments:
5400: $scantron_record - hash result from scantron_parse_scanline
5401: $scan_data - hash of correction information
5402: (see &scantron_getfile() form more information)
5403: $idmap - hash from &username_to_idmap()
5404: $line - number of current scanline
5405:
5406: Returns:
5407: Either 'username:domain' or undef if unknown
5408:
5409: =cut
5410:
5411: sub scantron_find_student {
5412: my ($scantron_record,$scan_data,$idmap,$line)=@_;
5413: my $scanID=$$scantron_record{'scantron.ID'};
5414: if ($scanID =~ /^\s*$/) {
5415: return &scan_data($scan_data,"$line.user");
5416: }
5417: foreach my $id (keys(%$idmap)) {
5418: if (lc($id) eq lc($scanID)) {
5419: return $$idmap{$id};
5420: }
5421: }
5422: return undef;
5423: }
5424:
5425: =pod
5426:
5427: =item scantron_filter
5428:
5429: Filter sub for lonnavmaps, filters out hidden resources if ignore
5430: hidden resources was selected
5431:
5432: =cut
5433:
5434: sub scantron_filter {
5435: my ($curres)=@_;
5436:
5437: if (ref($curres) && $curres->is_problem()) {
5438: # if the user has asked to not have either hidden
5439: # or 'randomout' controlled resources to be graded
5440: # don't include them
5441: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
5442: && $curres->randomout) {
5443: return 0;
5444: }
5445: return 1;
5446: }
5447: return 0;
5448: }
5449:
5450: =pod
5451:
5452: =item scantron_process_corrections
5453:
5454: Gets correction information out of submitted form data and corrects
5455: the scanline
5456:
5457: =cut
5458:
5459: sub scantron_process_corrections {
5460: my ($r) = @_;
5461: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
5462: my ($scanlines,$scan_data)=&scantron_getfile();
5463: my $classlist=&Apache::loncoursedata::get_classlist();
5464: my $which=$env{'form.scantron_line'};
5465: my $line=&scantron_get_line($scanlines,$scan_data,$which);
5466: my ($skip,$err,$errmsg);
5467: if ($env{'form.scantron_skip_record'}) {
5468: $skip=1;
5469: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
5470: my $newstudent=$env{'form.scantron_username'}.':'.
5471: $env{'form.scantron_domain'};
5472: my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
5473: ($line,$err,$errmsg)=
5474: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
5475: 'ID',{'newid'=>$newid,
5476: 'username'=>$env{'form.scantron_username'},
5477: 'domain'=>$env{'form.scantron_domain'}});
5478: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
5479: my $resolution=$env{'form.scantron_CODE_resolution'};
5480: my $newCODE;
5481: my %args;
5482: if ($resolution eq 'use_unfound') {
5483: $newCODE='use_unfound';
5484: } elsif ($resolution eq 'use_found') {
5485: $newCODE=$env{'form.scantron_CODE_selectedvalue'};
5486: } elsif ($resolution eq 'use_typed') {
5487: $newCODE=$env{'form.scantron_CODE_newvalue'};
5488: } elsif ($resolution =~ /^use_closest_(\d+)/) {
5489: $newCODE=$env{"form.scantron_CODE_closest_$1"};
5490: }
5491: if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
5492: $args{'CODE_ignore_dup'}=1;
5493: }
5494: $args{'CODE'}=$newCODE;
5495: ($line,$err,$errmsg)=
5496: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
5497: 'CODE',\%args);
5498: } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
5499: foreach my $question (split(',',$env{'form.scantron_questions'})) {
5500: ($line,$err,$errmsg)=
5501: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
5502: $which,'answer',
5503: { 'question'=>$question,
5504: 'response'=>$env{"form.scantron_correct_Q_$question"}});
5505: if ($err) { last; }
5506: }
5507: }
5508: if ($err) {
5509: $r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
5510: } else {
5511: &scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
5512: &scantron_putfile($scanlines,$scan_data);
5513: }
5514: }
5515:
5516: =pod
5517:
5518: =item reset_skipping_status
5519:
5520: Forgets the current set of remember skipped scanlines (and thus
5521: reverts back to considering all lines in the
5522: scantron_skipped_<filename> file)
5523:
5524: =cut
5525:
5526: sub reset_skipping_status {
5527: my ($scanlines,$scan_data)=&scantron_getfile();
5528: &scan_data($scan_data,'remember_skipping',undef,1);
5529: &scantron_putfile(undef,$scan_data);
5530: }
5531:
5532: =pod
5533:
5534: =item start_skipping
5535:
5536: Marks a scanline to be skipped.
5537:
5538: =cut
5539:
5540: sub start_skipping {
5541: my ($scan_data,$i)=@_;
5542: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
5543: if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
5544: $remembered{$i}=2;
5545: } else {
5546: $remembered{$i}=1;
5547: }
5548: &scan_data($scan_data,'remember_skipping',join(':',%remembered));
5549: }
5550:
5551: =pod
5552:
5553: =item should_be_skipped
5554:
5555: Checks whether a scanline should be skipped.
5556:
5557: =cut
5558:
5559: sub should_be_skipped {
5560: my ($scanlines,$scan_data,$i)=@_;
5561: if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
5562: # not redoing old skips
5563: if ($scanlines->{'skipped'}[$i]) { return 1; }
5564: return 0;
5565: }
5566: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
5567:
5568: if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
5569: return 0;
5570: }
5571: return 1;
5572: }
5573:
5574: =pod
5575:
5576: =item remember_current_skipped
5577:
5578: Discovers what scanlines are in the scantron_skipped_<filename>
5579: file and remembers them into scan_data for later use.
5580:
5581: =cut
5582:
5583: sub remember_current_skipped {
5584: my ($scanlines,$scan_data)=&scantron_getfile();
5585: my %to_remember;
5586: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
5587: if ($scanlines->{'skipped'}[$i]) {
5588: $to_remember{$i}=1;
5589: }
5590: }
5591:
5592: &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
5593: &scantron_putfile(undef,$scan_data);
5594: }
5595:
5596: =pod
5597:
5598: =item check_for_error
5599:
5600: Checks if there was an error when attempting to remove a specific
5601: scantron_.. bubble sheet data file. Prints out an error if
5602: something went wrong.
5603:
5604: =cut
5605:
5606: sub check_for_error {
5607: my ($r,$result)=@_;
5608: if ($result ne 'ok' && $result ne 'not_found' ) {
5609: $r->print("An error occurred ($result) when trying to Remove the existing corrections.");
5610: }
5611: }
5612:
5613: =pod
5614:
5615: =item scantron_warning_screen
5616:
5617: Interstitial screen to make sure the operator has selected the
5618: correct options before we start the validation phase.
5619:
5620: =cut
5621:
5622: sub scantron_warning_screen {
5623: my ($button_text)=@_;
5624: my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
5625: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
5626: my $CODElist;
5627: if ($scantron_config{'CODElocation'} &&
5628: $scantron_config{'CODEstart'} &&
5629: $scantron_config{'CODElength'}) {
5630: $CODElist=$env{'form.scantron_CODElist'};
5631: if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
5632: $CODElist=
5633: '<tr><td><b>List of CODES to validate against:</b></td><td><tt>'.
5634: $env{'form.scantron_CODElist'}.'</tt></td></tr>';
5635: }
5636: return (<<STUFF);
5637: <p>
5638: <span class="LC_warning">Please double check the information
5639: below before clicking on '$button_text'</span>
5640: </p>
5641: <table>
5642: <tr><td><b>Sequence to be Graded:</b></td><td>$title</td></tr>
5643: <tr><td><b>Data File that will be used:</b></td><td><tt>$env{'form.scantron_selectfile'}</tt></td></tr>
5644: $CODElist
5645: </table>
5646: <br />
5647: <p> If this information is correct, please click on '$button_text'.</p>
5648: <p> If something is incorrect, please click the 'Grading Menu' button to start over.</p>
5649:
5650: <br />
5651: STUFF
5652: }
5653:
5654: =pod
5655:
5656: =item scantron_do_warning
5657:
5658: Check if the operator has picked something for all required
5659: fields. Error out if something is missing.
5660:
5661: =cut
5662:
5663: sub scantron_do_warning {
5664: my ($r)=@_;
5665: my ($symb)=&get_symb($r);
5666: if (!$symb) {return '';}
5667: my $default_form_data=&defaultFormData($symb);
5668: $r->print(&scantron_form_start().$default_form_data);
5669: if ( $env{'form.selectpage'} eq '' ||
5670: $env{'form.scantron_selectfile'} eq '' ||
5671: $env{'form.scantron_format'} eq '' ) {
5672: $r->print("<p>You have forgetten to specify some information. Please go Back and try again.</p>");
5673: if ( $env{'form.selectpage'} eq '') {
5674: $r->print('<p><span class="LC_error">You have not selected a Sequence to grade</span></p>');
5675: }
5676: if ( $env{'form.scantron_selectfile'} eq '') {
5677: $r->print('<p><span class="LC_error">You have not selected a file that contains the student\'s response data.</span></p>');
5678: }
5679: if ( $env{'form.scantron_format'} eq '') {
5680: $r->print('<p><span class="LC_error">You have not selected a the format of the student\'s response data.</span></p>');
5681: }
5682: } else {
5683: my $warning=&scantron_warning_screen('Grading: Validate Records');
5684: $r->print(<<STUFF);
5685: $warning
5686: <input type="submit" name="submit" value="Grading: Validate Records" />
5687: <input type="hidden" name="command" value="scantron_validate" />
5688: STUFF
5689: }
5690: $r->print("</form><br />".&show_grading_menu_form($symb));
5691: return '';
5692: }
5693:
5694: =pod
5695:
5696: =item scantron_form_start
5697:
5698: html hidden input for remembering all selected grading options
5699:
5700: =cut
5701:
5702: sub scantron_form_start {
5703: my ($max_bubble)=@_;
5704: my $result= <<SCANTRONFORM;
5705: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
5706: <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
5707: <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
5708: <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
5709: <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
5710: <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
5711: <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
5712: <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
5713: <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
5714: <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
5715: SCANTRONFORM
5716:
5717: my $line = 0;
5718: while (defined($env{"form.scantron.bubblelines.$line"})) {
5719: &Apache::lonnet::logthis("Saving chunk for $line");
5720: my $chunk =
5721: '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
5722: $chunk .=
5723: '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
5724: $result .= $chunk;
5725: $line++;
5726: }
5727: return $result;
5728: }
5729:
5730: =pod
5731:
5732: =item scantron_validate_file
5733:
5734: Dispatch routine for doing validation of a bubble sheet data file.
5735:
5736: Also processes any necessary information resets that need to
5737: occur before validation begins (ignore previous corrections,
5738: restarting the skipped records processing)
5739:
5740: =cut
5741:
5742: sub scantron_validate_file {
5743: my ($r) = @_;
5744: my ($symb)=&get_symb($r);
5745: if (!$symb) {return '';}
5746: my $default_form_data=&defaultFormData($symb);
5747:
5748: # do the detection of only doing skipped records first befroe we delete
5749: # them when doing the corrections reset
5750: if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
5751: &reset_skipping_status();
5752: }
5753: if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
5754: &remember_current_skipped();
5755: $env{'form.scantron_options_redo'}='redo_skipped_ready';
5756: }
5757:
5758: if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
5759: &check_for_error($r,&scantron_remove_file('corrected'));
5760: &check_for_error($r,&scantron_remove_file('skipped'));
5761: &check_for_error($r,&scantron_remove_scan_data());
5762: $env{'form.scantron_options_ignore'}='done';
5763: }
5764:
5765: if ($env{'form.scantron_corrections'}) {
5766: &scantron_process_corrections($r);
5767: }
5768: $r->print("<p>Gathering necessary info.</p>");$r->rflush();
5769: #get the student pick code ready
5770: $r->print(&Apache::loncommon::studentbrowser_javascript());
5771: my $max_bubble=&scantron_get_maxbubble();
5772: my $result=&scantron_form_start($max_bubble).$default_form_data;
5773: $r->print($result);
5774:
5775: my @validate_phases=( 'sequence',
5776: 'ID',
5777: 'CODE',
5778: 'doublebubble',
5779: 'missingbubbles');
5780: if (!$env{'form.validatepass'}) {
5781: $env{'form.validatepass'} = 0;
5782: }
5783: my $currentphase=$env{'form.validatepass'};
5784:
5785: &Apache::lonnet::logthis("Phase: $currentphase");
5786:
5787: my $stop=0;
5788: while (!$stop && $currentphase < scalar(@validate_phases)) {
5789: $r->print("<p> Validating ".$validate_phases[$currentphase]."</p>");
5790: $r->rflush();
5791: my $which="scantron_validate_".$validate_phases[$currentphase];
5792: {
5793: no strict 'refs';
5794: ($stop,$currentphase)=&$which($r,$currentphase);
5795: }
5796: }
5797: if (!$stop) {
5798: my $warning=&scantron_warning_screen('Start Grading');
5799: $r->print(<<STUFF);
5800: Validation process complete.<br />
5801: $warning
5802: <input type="submit" name="submit" value="Start Grading" />
5803: <input type="hidden" name="command" value="scantron_process" />
5804: STUFF
5805:
5806: } else {
5807: $r->print('<input type="hidden" name="command" value="scantron_validate" />');
5808: $r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
5809: }
5810: if ($stop) {
5811: if ($validate_phases[$currentphase] eq 'sequence') {
5812: $r->print('<input type="submit" name="submit" value="Ignore -> " />');
5813: $r->print(' this error <br />');
5814:
5815: $r->print(" <p>Or click the 'Grading Menu' button to start over.</p>");
5816: } else {
5817: $r->print('<input type="submit" name="submit" value="Continue ->" />');
5818: $r->print(' using corrected info <br />');
5819: $r->print("<input type='submit' value='Skip' name='scantron_skip_record' />");
5820: $r->print(" this scanline saving it for later.");
5821: }
5822: }
5823: $r->print(" </form><br />".&show_grading_menu_form($symb));
5824: return '';
5825: }
5826:
5827:
5828: =pod
5829:
5830: =item scantron_remove_file
5831:
5832: Removes the requested bubble sheet data file, makes sure that
5833: scantron_original_<filename> is never removed
5834:
5835:
5836: =cut
5837:
5838: sub scantron_remove_file {
5839: my ($which)=@_;
5840: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5841: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5842: my $file='scantron_';
5843: if ($which eq 'corrected' || $which eq 'skipped') {
5844: $file.=$which.'_';
5845: } else {
5846: return 'refused';
5847: }
5848: $file.=$env{'form.scantron_selectfile'};
5849: return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
5850: }
5851:
5852:
5853: =pod
5854:
5855: =item scantron_remove_scan_data
5856:
5857: Removes all scan_data correction for the requested bubble sheet
5858: data file. (In the case that both the are doing skipped records we need
5859: to remember the old skipped lines for the time being so that element
5860: persists for a while.)
5861:
5862: =cut
5863:
5864: sub scantron_remove_scan_data {
5865: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5866: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5867: my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
5868: my @todelete;
5869: my $filename=$env{'form.scantron_selectfile'};
5870: foreach my $key (@keys) {
5871: if ($key=~/^\Q$filename\E_/) {
5872: if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
5873: $key=~/remember_skipping/) {
5874: next;
5875: }
5876: push(@todelete,$key);
5877: }
5878: }
5879: my $result;
5880: if (@todelete) {
5881: $result=&Apache::lonnet::del('nohist_scantrondata',\@todelete,$cdom,$cname);
5882: }
5883: return $result;
5884: }
5885:
5886:
5887: =pod
5888:
5889: =item scantron_getfile
5890:
5891: Fetches the requested bubble sheet data file (all 3 versions), and
5892: the scan_data hash
5893:
5894: Arguments:
5895: None
5896:
5897: Returns:
5898: 2 hash references
5899:
5900: - first one has
5901: orig -
5902: corrected -
5903: skipped - each of which points to an array ref of the specified
5904: file broken up into individual lines
5905: count - number of scanlines
5906:
5907: - second is the scan_data hash possible keys are
5908: ($number refers to scanline numbered $number and thus the key affects
5909: only that scanline
5910: $bubline refers to the specific bubble line element and the aspects
5911: refers to that specific bubble line element)
5912:
5913: $number.user - username:domain to use
5914: $number.CODE_ignore_dup
5915: - ignore the duplicate CODE error
5916: $number.useCODE
5917: - use the CODE in the scanline as is
5918: $number.no_bubble.$bubline
5919: - it is valid that there is no bubbled in bubble
5920: at $number $bubline
5921: remember_skipping
5922: - a frozen hash containing keys of $number and values
5923: of either
5924: 1 - we are on a 'do skipped records pass' and plan
5925: on processing this line
5926: 2 - we are on a 'do skipped records pass' and this
5927: scanline has been marked to skip yet again
5928:
5929: =cut
5930:
5931: sub scantron_getfile {
5932: #FIXME really would prefer a scantron directory
5933: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5934: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5935: my $lines;
5936: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
5937: 'scantron_orig_'.$env{'form.scantron_selectfile'});
5938: my %scanlines;
5939: $scanlines{'orig'}=[(split("\n",$lines,-1))];
5940: my $temp=$scanlines{'orig'};
5941: $scanlines{'count'}=$#$temp;
5942:
5943: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
5944: 'scantron_corrected_'.$env{'form.scantron_selectfile'});
5945: if ($lines eq '-1') {
5946: $scanlines{'corrected'}=[];
5947: } else {
5948: $scanlines{'corrected'}=[(split("\n",$lines,-1))];
5949: }
5950: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
5951: 'scantron_skipped_'.$env{'form.scantron_selectfile'});
5952: if ($lines eq '-1') {
5953: $scanlines{'skipped'}=[];
5954: } else {
5955: $scanlines{'skipped'}=[(split("\n",$lines,-1))];
5956: }
5957: my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
5958: if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
5959: my %scan_data = @tmp;
5960: return (\%scanlines,\%scan_data);
5961: }
5962:
5963: =pod
5964:
5965: =item lonnet_putfile
5966:
5967: Wrapper routine to call &Apache::lonnet::finishuserfileupload
5968:
5969: Arguments:
5970: $contents - data to store
5971: $filename - filename to store $contents into
5972:
5973: Returns:
5974: result value from &Apache::lonnet::finishuserfileupload
5975:
5976: =cut
5977:
5978: sub lonnet_putfile {
5979: my ($contents,$filename)=@_;
5980: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
5981: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5982: $env{'form.sillywaytopassafilearound'}=$contents;
5983: &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
5984:
5985: }
5986:
5987: =pod
5988:
5989: =item scantron_putfile
5990:
5991: Stores the current version of the bubble sheet data files, and the
5992: scan_data hash. (Does not modify the original version only the
5993: corrected and skipped versions.
5994:
5995: Arguments:
5996: $scanlines - hash ref that looks like the first return value from
5997: &scantron_getfile()
5998: $scan_data - hash ref that looks like the second return value from
5999: &scantron_getfile()
6000:
6001: =cut
6002:
6003: sub scantron_putfile {
6004: my ($scanlines,$scan_data) = @_;
6005: #FIXME really would prefer a scantron directory
6006: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6007: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6008: if ($scanlines) {
6009: my $prefix='scantron_';
6010: # no need to update orig, shouldn't change
6011: # &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
6012: # $env{'form.scantron_selectfile'});
6013: &lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
6014: $prefix.'corrected_'.
6015: $env{'form.scantron_selectfile'});
6016: &lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
6017: $prefix.'skipped_'.
6018: $env{'form.scantron_selectfile'});
6019: }
6020: &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
6021: }
6022:
6023: =pod
6024:
6025: =item scantron_get_line
6026:
6027: Returns the correct version of the scanline
6028:
6029: Arguments:
6030: $scanlines - hash ref that looks like the first return value from
6031: &scantron_getfile()
6032: $scan_data - hash ref that looks like the second return value from
6033: &scantron_getfile()
6034: $i - number of the requested line (starts at 0)
6035:
6036: Returns:
6037: A scanline, (either the original or the corrected one if it
6038: exists), or undef if the requested scanline should be
6039: skipped. (Either because it's an skipped scanline, or it's an
6040: unskipped scanline and we are not doing a 'do skipped scanlines'
6041: pass.
6042:
6043: =cut
6044:
6045: sub scantron_get_line {
6046: my ($scanlines,$scan_data,$i)=@_;
6047: if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
6048: #if ($scanlines->{'skipped'}[$i]) { return undef; }
6049: if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
6050: return $scanlines->{'orig'}[$i];
6051: }
6052:
6053: =pod
6054:
6055: =item scantron_todo_count
6056:
6057: Counts the number of scanlines that need processing.
6058:
6059: Arguments:
6060: $scanlines - hash ref that looks like the first return value from
6061: &scantron_getfile()
6062: $scan_data - hash ref that looks like the second return value from
6063: &scantron_getfile()
6064:
6065: Returns:
6066: $count - number of scanlines to process
6067:
6068: =cut
6069:
6070: sub get_todo_count {
6071: my ($scanlines,$scan_data)=@_;
6072: my $count=0;
6073: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6074: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6075: if ($line=~/^[\s\cz]*$/) { next; }
6076: $count++;
6077: }
6078: return $count;
6079: }
6080:
6081: =pod
6082:
6083: =item scantron_put_line
6084:
6085: Updates the 'corrected' or 'skipped' versions of the bubble sheet
6086: data file.
6087:
6088: Arguments:
6089: $scanlines - hash ref that looks like the first return value from
6090: &scantron_getfile()
6091: $scan_data - hash ref that looks like the second return value from
6092: &scantron_getfile()
6093: $i - line number to update
6094: $newline - contents of the updated scanline
6095: $skip - if true make the line for skipping and update the
6096: 'skipped' file
6097:
6098: =cut
6099:
6100: sub scantron_put_line {
6101: my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
6102: if ($skip) {
6103: $scanlines->{'skipped'}[$i]=$newline;
6104: &start_skipping($scan_data,$i);
6105: return;
6106: }
6107: $scanlines->{'corrected'}[$i]=$newline;
6108: }
6109:
6110: =pod
6111:
6112: =item scantron_clear_skip
6113:
6114: Remove a line from the 'skipped' file
6115:
6116: Arguments:
6117: $scanlines - hash ref that looks like the first return value from
6118: &scantron_getfile()
6119: $scan_data - hash ref that looks like the second return value from
6120: &scantron_getfile()
6121: $i - line number to update
6122:
6123: =cut
6124:
6125: sub scantron_clear_skip {
6126: my ($scanlines,$scan_data,$i)=@_;
6127: if (exists($scanlines->{'skipped'}[$i])) {
6128: undef($scanlines->{'skipped'}[$i]);
6129: return 1;
6130: }
6131: return 0;
6132: }
6133:
6134: =pod
6135:
6136: =item scantron_filter_not_exam
6137:
6138: Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
6139: filter out resources that are not marked as 'exam' mode
6140:
6141: =cut
6142:
6143: sub scantron_filter_not_exam {
6144: my ($curres)=@_;
6145:
6146: if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
6147: # if the user has asked to not have either hidden
6148: # or 'randomout' controlled resources to be graded
6149: # don't include them
6150: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
6151: && $curres->randomout) {
6152: return 0;
6153: }
6154: return 1;
6155: }
6156: return 0;
6157: }
6158:
6159: =pod
6160:
6161: =item scantron_validate_sequence
6162:
6163: Validates the selected sequence, checking for resource that are
6164: not set to exam mode.
6165:
6166: =cut
6167:
6168: sub scantron_validate_sequence {
6169: my ($r,$currentphase) = @_;
6170:
6171: my $navmap=Apache::lonnavmaps::navmap->new();
6172: my (undef,undef,$sequence)=
6173: &Apache::lonnet::decode_symb($env{'form.selectpage'});
6174:
6175: my $map=$navmap->getResourceByUrl($sequence);
6176:
6177: $r->print('<input type="hidden" name="validate_sequence_exam"
6178: value="ignore" />');
6179: if ($env{'form.validate_sequence_exam'} ne 'ignore') {
6180: my @resources=
6181: $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
6182: if (@resources) {
6183: $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>");
6184: return (1,$currentphase);
6185: }
6186: }
6187:
6188: return (0,$currentphase+1);
6189: }
6190:
6191: =pod
6192:
6193: =item scantron_validate_ID
6194:
6195: Validates all scanlines in the selected file to not have any
6196: invalid or underspecified student IDs
6197:
6198: =cut
6199:
6200: sub scantron_validate_ID {
6201: my ($r,$currentphase) = @_;
6202:
6203: #get student info
6204: my $classlist=&Apache::loncoursedata::get_classlist();
6205: my %idmap=&username_to_idmap($classlist);
6206:
6207: #get scantron line setup
6208: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6209: my ($scanlines,$scan_data)=&scantron_getfile();
6210:
6211: &scantron_get_maxbubble(); # parse needs the bubble_lines.. array.
6212:
6213: my %found=('ids'=>{},'usernames'=>{});
6214: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6215: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6216: if ($line=~/^[\s\cz]*$/) { next; }
6217: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6218: $scan_data);
6219: my $id=$$scan_record{'scantron.ID'};
6220: my $found;
6221: foreach my $checkid (keys(%idmap)) {
6222: if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
6223: }
6224: if ($found) {
6225: my $username=$idmap{$found};
6226: if ($found{'ids'}{$found}) {
6227: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6228: $line,'duplicateID',$found);
6229: return(1,$currentphase);
6230: } elsif ($found{'usernames'}{$username}) {
6231: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6232: $line,'duplicateID',$username);
6233: return(1,$currentphase);
6234: }
6235: #FIXME store away line we previously saw the ID on to use above
6236: $found{'ids'}{$found}++;
6237: $found{'usernames'}{$username}++;
6238: } else {
6239: if ($id =~ /^\s*$/) {
6240: my $username=&scan_data($scan_data,"$i.user");
6241: if (defined($username) && $found{'usernames'}{$username}) {
6242: &scantron_get_correction($r,$i,$scan_record,
6243: \%scantron_config,
6244: $line,'duplicateID',$username);
6245: return(1,$currentphase);
6246: } elsif (!defined($username)) {
6247: &scantron_get_correction($r,$i,$scan_record,
6248: \%scantron_config,
6249: $line,'incorrectID');
6250: return(1,$currentphase);
6251: }
6252: $found{'usernames'}{$username}++;
6253: } else {
6254: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6255: $line,'incorrectID');
6256: return(1,$currentphase);
6257: }
6258: }
6259: }
6260:
6261: return (0,$currentphase+1);
6262: }
6263:
6264: =pod
6265:
6266: =item scantron_get_correction
6267:
6268: Builds the interface screen to interact with the operator to fix a
6269: specific error condition in a specific scanline
6270:
6271: Arguments:
6272: $r - Apache request object
6273: $i - number of the current scanline
6274: $scan_record - hash ref as returned from &scantron_parse_scanline()
6275: $scan_config - hash ref as returned from &get_scantron_config()
6276: $line - full contents of the current scanline
6277: $error - error condition, valid values are
6278: 'incorrectCODE', 'duplicateCODE',
6279: 'doublebubble', 'missingbubble',
6280: 'duplicateID', 'incorrectID'
6281: $arg - extra information needed
6282: For errors:
6283: - duplicateID - paper number that this studentID was seen before on
6284: - duplicateCODE - array ref of the paper numbers this CODE was
6285: seen on before
6286: - incorrectCODE - current incorrect CODE
6287: - doublebubble - array ref of the bubble lines that have double
6288: bubble errors
6289: - missingbubble - array ref of the bubble lines that have missing
6290: bubble errors
6291:
6292: =cut
6293:
6294: sub scantron_get_correction {
6295: my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
6296:
6297: #FIXME in the case of a duplicated ID the previous line, probaly need
6298: #to show both the current line and the previous one and allow skipping
6299: #the previous one or the current one
6300:
6301: $r->print("<p><b>An error was detected ($error)</b>");
6302: if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
6303: $r->print(" for PaperID <tt>".
6304: $$scan_record{'scantron.PaperID'}."</tt> \n");
6305: } else {
6306: $r->print(" in scanline $i <pre>".
6307: $line."</pre> \n");
6308: }
6309: my $message="<p>The ID on the form is <tt>".
6310: $$scan_record{'scantron.ID'}."</tt><br />\n".
6311: "The name on the paper is ".
6312: $$scan_record{'scantron.LastName'}.",".
6313: $$scan_record{'scantron.FirstName'}."</p>";
6314:
6315: $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
6316: $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
6317: if ($error =~ /ID$/) {
6318: if ($error eq 'incorrectID') {
6319: $r->print("The encoded ID is not in the classlist</p>\n");
6320: } elsif ($error eq 'duplicateID') {
6321: $r->print("The encoded ID has also been used by a previous paper $arg</p>\n");
6322: }
6323: $r->print($message);
6324: $r->print("<p>How should I handle this? <br /> \n");
6325: $r->print("\n<ul><li> ");
6326: #FIXME it would be nice if this sent back the user ID and
6327: #could do partial userID matches
6328: $r->print(&Apache::loncommon::selectstudent_link('scantronupload',
6329: 'scantron_username','scantron_domain'));
6330: $r->print(": <input type='text' name='scantron_username' value='' />");
6331: $r->print("\n@".
6332: &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
6333:
6334: $r->print('</li>');
6335: } elsif ($error =~ /CODE$/) {
6336: if ($error eq 'incorrectCODE') {
6337: $r->print("</p><p>The encoded CODE is not in the list of possible CODEs</p>\n");
6338: } elsif ($error eq 'duplicateCODE') {
6339: $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");
6340: }
6341: $r->print("<p>The CODE on the form is <tt>'".
6342: $$scan_record{'scantron.CODE'}."'</tt><br />\n");
6343: $r->print($message);
6344: $r->print("<p>How should I handle this? <br /> \n");
6345: $r->print("\n<br /> ");
6346: my $i=0;
6347: if ($error eq 'incorrectCODE'
6348: && $$scan_record{'scantron.CODE'}=~/\S/ ) {
6349: my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
6350: if ($closest > 0) {
6351: foreach my $testcode (@{$closest}) {
6352: my $checked='';
6353: if (!$i) { $checked=' checked="checked" '; }
6354: $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' />");
6355: $r->print("\n<br />");
6356: $i++;
6357: }
6358: }
6359: }
6360: if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
6361: my $checked; if (!$i) { $checked=' checked="checked" '; }
6362: $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>");
6363: $r->print("\n<br />");
6364: }
6365:
6366: $r->print(<<ENDSCRIPT);
6367: <script type="text/javascript">
6368: function change_radio(field) {
6369: var slct=document.scantronupload.scantron_CODE_resolution;
6370: var i;
6371: for (i=0;i<slct.length;i++) {
6372: if (slct[i].value==field) { slct[i].checked=true; }
6373: }
6374: }
6375: </script>
6376: ENDSCRIPT
6377: my $href="/adm/pickcode?".
6378: "form=".&escape("scantronupload").
6379: "&scantron_format=".&escape($env{'form.scantron_format'}).
6380: "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
6381: "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
6382: "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
6383: if ($env{'form.scantron_CODElist'} =~ /\S/) {
6384: $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')\" />");
6385: $r->print("\n<br />");
6386: }
6387: $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.");
6388: $r->print("\n<br /><br />");
6389: } elsif ($error eq 'doublebubble') {
6390: $r->print("<p>There have been multiple bubbles scanned for a some question(s)</p>\n");
6391: $r->print('<input type="hidden" name="scantron_questions" value="'.
6392: join(',',@{$arg}).'" />');
6393: $r->print($message);
6394: $r->print("<p>Please indicate which bubble should be used for grading</p>");
6395: foreach my $question (@{$arg}) {
6396:
6397: my $selected = &get_response_bubbles($scan_record, $question);
6398: &scantron_bubble_selector($r,$scan_config,$question,
6399: split('',$selected));
6400: }
6401: } elsif ($error eq 'missingbubble') {
6402: $r->print("<p>There have been <b>no</b> bubbles scanned for some question(s)</p>\n");
6403: $r->print($message);
6404: $r->print("<p>Please indicate which bubble should be used for grading</p>");
6405: $r->print("Some questions have no scanned bubbles\n");
6406: $r->print('<input type="hidden" name="scantron_questions" value="'.
6407: join(',',@{$arg}).'" />');
6408: foreach my $question (@{$arg}) {
6409: my $selected = &get_response_bubbles($scan_record, $question);
6410: &scantron_bubble_selector($r,$scan_config,$question);
6411: }
6412: } else {
6413: $r->print("\n<ul>");
6414: }
6415: $r->print("\n</li></ul>");
6416:
6417: }
6418:
6419: =pod
6420:
6421: =item scantron_bubble_selector
6422:
6423: Generates the html radiobuttons to correct a single bubble line
6424: possibly showing the existing the selected bubbles if known
6425:
6426: Arguments:
6427: $r - Apache request object
6428: $scan_config - hash from &get_scantron_config()
6429: $quest - number of the bubble line to make a corrector for
6430: $selected - array of letters of previously selected bubbles
6431:
6432: =cut
6433:
6434: sub scantron_bubble_selector {
6435: my ($r,$scan_config,$quest,@selected)=@_;
6436: my $max=$$scan_config{'Qlength'};
6437:
6438: my $scmode=$$scan_config{'Qon'};
6439:
6440:
6441: if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }
6442:
6443: my $response = $quest-1;
6444: my $lines = $bubble_lines_per_response{$response};
6445: &Apache::lonnet::logthis("Question $quest, lines: $lines");
6446:
6447: my $total_lines = $lines*2;
6448: my @alphabet=('A'..'Z');
6449: $r->print("<table border='1'><tr><td rowspan='".$total_lines."'>$quest</td>");
6450:
6451: for (my $l = 0; $l < $lines; $l++) {
6452: if ($l != 0) {
6453: $r->print('<tr>');
6454: }
6455:
6456: # FIXME: This loop probably has to be considerably more clever for
6457: # multiline bubbles: User can multibubble by having bubbles in
6458: # several lines. User can skip lines legitimately etc. etc.
6459:
6460: for (my $i=0;$i<$max;$i++) {
6461: $r->print("\n".'<td align="center">');
6462: if ($selected[0] eq $alphabet[$i]) {
6463: $r->print('X');
6464: shift(@selected) ;
6465: } else {
6466: $r->print(' ');
6467: }
6468: $r->print('</td>');
6469:
6470: }
6471:
6472: if ($l == 0) {
6473: my $lspan = $total_lines * 2; # 2 table rows per bubble line.
6474:
6475: $r->print('<td rowspan='.$lspan.'><label><input type="radio" name="scantron_correct_Q_'.
6476: $quest.'" value="none" /> No bubble </label></td>');
6477:
6478: }
6479:
6480: $r->print('</tr><tr>');
6481:
6482: # FIXME: This may have to be a bit more clever for
6483: # multiline questions (different values e.g..).
6484:
6485: for (my $i=0;$i<$max;$i++) {
6486: $r->print("\n".
6487: '<td><label><input type="radio" name="scantron_correct_Q_'.
6488: $quest.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
6489: }
6490: $r->print('</tr>');
6491:
6492:
6493: }
6494: $r->print('</table>');
6495: }
6496:
6497: =pod
6498:
6499: =item num_matches
6500:
6501: Counts the number of characters that are the same between the two arguments.
6502:
6503: Arguments:
6504: $orig - CODE from the scanline
6505: $code - CODE to match against
6506:
6507: Returns:
6508: $count - integer count of the number of same characters between the
6509: two arguments
6510:
6511: =cut
6512:
6513: sub num_matches {
6514: my ($orig,$code) = @_;
6515: my @code=split(//,$code);
6516: my @orig=split(//,$orig);
6517: my $same=0;
6518: for (my $i=0;$i<scalar(@code);$i++) {
6519: if ($code[$i] eq $orig[$i]) { $same++; }
6520: }
6521: return $same;
6522: }
6523:
6524: =pod
6525:
6526: =item scantron_get_closely_matching_CODEs
6527:
6528: Cycles through all CODEs and finds the set that has the greatest
6529: number of same characters as the provided CODE
6530:
6531: Arguments:
6532: $allcodes - hash ref returned by &get_codes()
6533: $CODE - CODE from the current scanline
6534:
6535: Returns:
6536: 2 element list
6537: - first elements is number of how closely matching the best fit is
6538: (5 means best set has 5 matching characters)
6539: - second element is an arrary ref containing the set of valid CODEs
6540: that best fit the passed in CODE
6541:
6542: =cut
6543:
6544: sub scantron_get_closely_matching_CODEs {
6545: my ($allcodes,$CODE)=@_;
6546: my @CODEs;
6547: foreach my $testcode (sort(keys(%{$allcodes}))) {
6548: push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
6549: }
6550:
6551: return ($#CODEs,$CODEs[-1]);
6552: }
6553:
6554: =pod
6555:
6556: =item get_codes
6557:
6558: Builds a hash which has keys of all of the valid CODEs from the selected
6559: set of remembered CODEs.
6560:
6561: Arguments:
6562: $old_name - name of the set of remembered CODEs
6563: $cdom - domain of the course
6564: $cnum - internal course name
6565:
6566: Returns:
6567: %allcodes - keys are the valid CODEs, values are all 1
6568:
6569: =cut
6570:
6571: sub get_codes {
6572: my ($old_name, $cdom, $cnum) = @_;
6573: if (!$old_name) {
6574: $old_name=$env{'form.scantron_CODElist'};
6575: }
6576: if (!$cdom) {
6577: $cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
6578: }
6579: if (!$cnum) {
6580: $cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
6581: }
6582: my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
6583: $cdom,$cnum);
6584: my %allcodes;
6585: if ($result{"type\0$old_name"} eq 'number') {
6586: %allcodes=map {($_,1)} split(',',$result{$old_name});
6587: } else {
6588: %allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
6589: }
6590: return %allcodes;
6591: }
6592:
6593: =pod
6594:
6595: =item scantron_validate_CODE
6596:
6597: Validates all scanlines in the selected file to not have any
6598: invalid or underspecified CODEs and that none of the codes are
6599: duplicated if this was requested.
6600:
6601: =cut
6602:
6603: sub scantron_validate_CODE {
6604: my ($r,$currentphase) = @_;
6605: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6606: if ($scantron_config{'CODElocation'} &&
6607: $scantron_config{'CODEstart'} &&
6608: $scantron_config{'CODElength'}) {
6609: if (!defined($env{'form.scantron_CODElist'})) {
6610: &FIXME_blow_up()
6611: }
6612: } else {
6613: return (0,$currentphase+1);
6614: }
6615:
6616: my %usedCODEs;
6617:
6618: my %allcodes=&get_codes();
6619:
6620: &scantron_get_maxbubble(); # parse needs the lines per response array.
6621:
6622: my ($scanlines,$scan_data)=&scantron_getfile();
6623: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6624: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6625: if ($line=~/^[\s\cz]*$/) { next; }
6626: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6627: $scan_data);
6628: my $CODE=$$scan_record{'scantron.CODE'};
6629: my $error=0;
6630: if (!&Apache::lonnet::validCODE($CODE)) {
6631: &scantron_get_correction($r,$i,$scan_record,
6632: \%scantron_config,
6633: $line,'incorrectCODE',\%allcodes);
6634: return(1,$currentphase);
6635: }
6636: if (%allcodes && !exists($allcodes{$CODE})
6637: && !$$scan_record{'scantron.useCODE'}) {
6638: &scantron_get_correction($r,$i,$scan_record,
6639: \%scantron_config,
6640: $line,'incorrectCODE',\%allcodes);
6641: return(1,$currentphase);
6642: }
6643: if (exists($usedCODEs{$CODE})
6644: && $env{'form.scantron_CODEunique'} eq 'yes'
6645: && !$$scan_record{'scantron.CODE_ignore_dup'}) {
6646: &scantron_get_correction($r,$i,$scan_record,
6647: \%scantron_config,
6648: $line,'duplicateCODE',$usedCODEs{$CODE});
6649: return(1,$currentphase);
6650: }
6651: push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
6652: }
6653: return (0,$currentphase+1);
6654: }
6655:
6656: =pod
6657:
6658: =item scantron_validate_doublebubble
6659:
6660: Validates all scanlines in the selected file to not have any
6661: bubble lines with multiple bubbles marked.
6662:
6663: =cut
6664:
6665: sub scantron_validate_doublebubble {
6666: my ($r,$currentphase) = @_;
6667: #get student info
6668: my $classlist=&Apache::loncoursedata::get_classlist();
6669: my %idmap=&username_to_idmap($classlist);
6670:
6671: #get scantron line setup
6672: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6673: my ($scanlines,$scan_data)=&scantron_getfile();
6674:
6675: &scantron_get_maxbubble(); # parse needs the bubble line array.
6676:
6677: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6678: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6679: if ($line=~/^[\s\cz]*$/) { next; }
6680: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6681: $scan_data);
6682: if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
6683: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
6684: 'doublebubble',
6685: $$scan_record{'scantron.doubleerror'});
6686: return (1,$currentphase);
6687: }
6688: return (0,$currentphase+1);
6689: }
6690:
6691: =pod
6692:
6693: =item scantron_get_maxbubble
6694:
6695: Returns the maximum number of bubble lines that are expected to
6696: occur. Does this by walking the selected sequence rendering the
6697: resource and then checking &Apache::lonxml::get_problem_counter()
6698: for what the current value of the problem counter is.
6699:
6700: Caches the results to $env{'form.scantron_maxbubble'},
6701: $env{'form.scantron.bubble_lines.n'} and
6702: $env{'form.scantron.first_bubble_line.n'}
6703: which are the total number of bubble, lines, the number of bubble
6704: lines for reponse n and number of the first bubble line for response n.
6705:
6706: =cut
6707:
6708: sub scantron_get_maxbubble {
6709: &Apache::lonnet::logthis("get_max_bubble");
6710: if (defined($env{'form.scantron_maxbubble'}) &&
6711: $env{'form.scantron_maxbubble'}) {
6712: &Apache::lonnet::logthis("cached");
6713: &restore_bubble_lines();
6714: return $env{'form.scantron_maxbubble'};
6715: }
6716: &Apache::lonnet::logthis("computing");
6717:
6718: my (undef, undef, $sequence) =
6719: &Apache::lonnet::decode_symb($env{'form.selectpage'});
6720:
6721: my $navmap=Apache::lonnavmaps::navmap->new();
6722: my $map=$navmap->getResourceByUrl($sequence);
6723: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
6724:
6725: &Apache::lonxml::clear_problem_counter();
6726:
6727: my $uname = $env{'form.student'};
6728: my $udom = $env{'form.userdom'};
6729: my $cid = $env{'request.course.id'};
6730: my $total_lines = 0;
6731: %bubble_lines_per_response = ();
6732: %first_bubble_line = ();
6733:
6734:
6735: my $response_number = 0;
6736: my $bubble_line = 0;
6737: foreach my $resource (@resources) {
6738: my $symb = $resource->symb();
6739: &Apache::lonxml::clear_bubble_lines_for_part();
6740: my $result=&Apache::lonnet::ssi($resource->src(),
6741: ('symb' => $resource->symb()),
6742: ('grade_target' => 'analyze'),
6743: ('grade_courseid' => $cid),
6744: ('grade_domain' => $udom),
6745: ('grade_username' => $uname));
6746: my (undef, $an) =
6747: split(/_HASH_REF__/,$result, 2);
6748:
6749: my %analysis = &Apache::lonnet::str2hash($an);
6750:
6751:
6752:
6753: foreach my $part_id (@{$analysis{'parts'}}) {
6754: my ($trash, $part) = split(/\./, $part_id);
6755:
6756: my $lines = $analysis{"$part_id.bubble_lines"}[0];
6757:
6758: # TODO - make this a persistent hash not an array.
6759:
6760:
6761: $first_bubble_line{$response_number} = $bubble_line;
6762: $bubble_lines_per_response{$response_number} = $lines;
6763: $response_number++;
6764:
6765: $bubble_line += $lines;
6766: $total_lines += $lines;
6767: }
6768:
6769: }
6770: &Apache::lonnet::delenv('scantron\.');
6771:
6772: &save_bubble_lines();
6773: $env{'form.scantron_maxbubble'} =
6774: $total_lines;
6775: return $env{'form.scantron_maxbubble'};
6776: }
6777:
6778: =pod
6779:
6780: =item scantron_validate_missingbubbles
6781:
6782: Validates all scanlines in the selected file to not have any
6783: answers that don't have bubbles that have not been verified
6784: to be bubble free.
6785:
6786: =cut
6787:
6788: sub scantron_validate_missingbubbles {
6789: my ($r,$currentphase) = @_;
6790: #get student info
6791: my $classlist=&Apache::loncoursedata::get_classlist();
6792: my %idmap=&username_to_idmap($classlist);
6793:
6794: #get scantron line setup
6795: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6796: my ($scanlines,$scan_data)=&scantron_getfile();
6797: my $max_bubble=&scantron_get_maxbubble();
6798: if (!$max_bubble) { $max_bubble=2**31; }
6799: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6800: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6801: if ($line=~/^[\s\cz]*$/) { next; }
6802: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6803: $scan_data);
6804: if (!defined($$scan_record{'scantron.missingerror'})) { next; }
6805: my @to_correct;
6806: foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
6807: if ($missing > $max_bubble) { next; }
6808: push(@to_correct,$missing);
6809: }
6810: if (@to_correct) {
6811: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6812: $line,'missingbubble',\@to_correct);
6813: return (1,$currentphase);
6814: }
6815:
6816: }
6817: return (0,$currentphase+1);
6818: }
6819:
6820: =pod
6821:
6822: =item scantron_process_students
6823:
6824: Routine that does the actual grading of the bubble sheet information.
6825:
6826: The parsed scanline hash is added to %env
6827:
6828: Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
6829: foreach resource , with the form data of
6830:
6831: 'submitted' =>'scantron'
6832: 'grade_target' =>'grade',
6833: 'grade_username'=> username of student
6834: 'grade_domain' => domain of student
6835: 'grade_courseid'=> of course
6836: 'grade_symb' => symb of resource to grade
6837:
6838: This triggers a grading pass. The problem grading code takes care
6839: of converting the bubbled letter information (now in %env) into a
6840: valid submission.
6841:
6842: =cut
6843:
6844: sub scantron_process_students {
6845: my ($r) = @_;
6846: my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
6847: my ($symb)=&get_symb($r);
6848: if (!$symb) {return '';}
6849: my $default_form_data=&defaultFormData($symb);
6850:
6851: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6852: my ($scanlines,$scan_data)=&scantron_getfile();
6853: my $classlist=&Apache::loncoursedata::get_classlist();
6854: my %idmap=&username_to_idmap($classlist);
6855: my $navmap=Apache::lonnavmaps::navmap->new();
6856: my $map=$navmap->getResourceByUrl($sequence);
6857: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
6858: # $r->print("geto ".scalar(@resources)."<br />");
6859: my $result= <<SCANTRONFORM;
6860: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
6861: <input type="hidden" name="command" value="scantron_configphase" />
6862: $default_form_data
6863: SCANTRONFORM
6864: $r->print($result);
6865:
6866: my @delayqueue;
6867: my %completedstudents;
6868:
6869: my $count=&get_todo_count($scanlines,$scan_data);
6870: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
6871: 'Scantron Progress',$count,
6872: 'inline',undef,'scantronupload');
6873: &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
6874: 'Processing first student');
6875: my $start=&Time::HiRes::time();
6876: my $i=-1;
6877: my ($uname,$udom,$started);
6878:
6879: &scantron_get_maxbubble(); # Need the bubble lines array to parse.
6880:
6881: while ($i<$scanlines->{'count'}) {
6882: ($uname,$udom)=('','');
6883: $i++;
6884: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6885: if ($line=~/^[\s\cz]*$/) { next; }
6886: if ($started) {
6887: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
6888: 'last student');
6889: }
6890: $started=1;
6891: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6892: $scan_data);
6893: unless ($uname=&scantron_find_student($scan_record,$scan_data,
6894: \%idmap,$i)) {
6895: &scantron_add_delay(\@delayqueue,$line,
6896: 'Unable to find a student that matches',1);
6897: next;
6898: }
6899: if (exists $completedstudents{$uname}) {
6900: &scantron_add_delay(\@delayqueue,$line,
6901: 'Student '.$uname.' has multiple sheets',2);
6902: next;
6903: }
6904: ($uname,$udom)=split(/:/,$uname);
6905:
6906: &Apache::lonxml::clear_problem_counter();
6907: &Apache::lonnet::appenv(%$scan_record);
6908:
6909: if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
6910: &scantron_putfile($scanlines,$scan_data);
6911: }
6912:
6913: my $i=0;
6914: foreach my $resource (@resources) {
6915: $i++;
6916: my %form=('submitted' =>'scantron',
6917: 'grade_target' =>'grade',
6918: 'grade_username'=>$uname,
6919: 'grade_domain' =>$udom,
6920: 'grade_courseid'=>$env{'request.course.id'},
6921: 'grade_symb' =>$resource->symb());
6922: if (exists($scan_record->{'scantron.CODE'})
6923: &&
6924: &Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
6925: $form{'CODE'}=$scan_record->{'scantron.CODE'};
6926: } else {
6927: $form{'CODE'}='';
6928: }
6929: my $result=&Apache::lonnet::ssi($resource->src(),%form);
6930: if ($result ne '') {
6931: }
6932: if (&Apache::loncommon::connection_aborted($r)) { last; }
6933: }
6934: $completedstudents{$uname}={'line'=>$line};
6935: if (&Apache::loncommon::connection_aborted($r)) { last; }
6936: } continue {
6937: &Apache::lonxml::clear_problem_counter();
6938: &Apache::lonnet::delenv('scantron\.');
6939: }
6940: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
6941: # my $lasttime = &Time::HiRes::time()-$start;
6942: # $r->print("<p>took $lasttime</p>");
6943:
6944: $r->print("</form>");
6945: $r->print(&show_grading_menu_form($symb));
6946: return '';
6947: }
6948:
6949: =pod
6950:
6951: =item scantron_upload_scantron_data
6952:
6953: Creates the screen for adding a new bubble sheet data file to a course.
6954:
6955: =cut
6956:
6957: sub scantron_upload_scantron_data {
6958: my ($r)=@_;
6959: $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
6960: my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
6961: 'domainid',
6962: 'coursename');
6963: my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
6964: 'domainid');
6965: my $default_form_data=&defaultFormData(&get_symb($r,1));
6966: $r->print(<<UPLOAD);
6967: <script type="text/javascript" language="javascript">
6968: function checkUpload(formname) {
6969: if (formname.upfile.value == "") {
6970: alert("Please use the browse button to select a file from your local directory.");
6971: return false;
6972: }
6973: formname.submit();
6974: }
6975: </script>
6976:
6977: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
6978: $default_form_data
6979: <table>
6980: <tr><td>$select_link </td></tr>
6981: <tr><td>Course ID: </td><td><input name='courseid' type='text' /> </td></tr>
6982: <tr><td>Course Name: </td><td><input name='coursename' type='text' /></td></tr>
6983: <tr><td>Domain: </td><td>$domsel </td></tr>
6984: <tr><td>File to upload:</td><td><input type="file" name="upfile" size="50" /></td></tr>
6985: </table>
6986: <input name='command' value='scantronupload_save' type='hidden' />
6987: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
6988: </form>
6989: UPLOAD
6990: return '';
6991: }
6992:
6993: =pod
6994:
6995: =item scantron_upload_scantron_data_save
6996:
6997: Adds a provided bubble information data file to the course if user
6998: has the correct privileges to do so.
6999:
7000: =cut
7001:
7002: sub scantron_upload_scantron_data_save {
7003: my($r)=@_;
7004: my ($symb)=&get_symb($r,1);
7005: my $doanotherupload=
7006: '<br /><form action="/adm/grades" method="post">'."\n".
7007: '<input type="hidden" name="command" value="scantronupload" />'."\n".
7008: '<input type="submit" name="submit" value="Do Another Upload" />'."\n".
7009: '</form>'."\n";
7010: if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
7011: !&Apache::lonnet::allowed('usc',
7012: $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
7013: $r->print("You are not allowed to upload Scantron data to the requested course.<br />");
7014: if ($symb) {
7015: $r->print(&show_grading_menu_form($symb));
7016: } else {
7017: $r->print($doanotherupload);
7018: }
7019: return '';
7020: }
7021: my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
7022: $r->print("Doing upload to ".$coursedata{'description'}." <br />");
7023: my $fname=$env{'form.upfile.filename'};
7024: #FIXME
7025: #copied from lonnet::userfileupload()
7026: #make that function able to target a specified course
7027: # Replace Windows backslashes by forward slashes
7028: $fname=~s/\\/\//g;
7029: # Get rid of everything but the actual filename
7030: $fname=~s/^.*\/([^\/]+)$/$1/;
7031: # Replace spaces by underscores
7032: $fname=~s/\s+/\_/g;
7033: # Replace all other weird characters by nothing
7034: $fname=~s/[^\w\.\-]//g;
7035: # See if there is anything left
7036: unless ($fname) { return 'error: no uploaded file'; }
7037: my $uploadedfile=$fname;
7038: $fname='scantron_orig_'.$fname;
7039: if (length($env{'form.upfile'}) < 2) {
7040: $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.");
7041: } else {
7042: my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
7043: if ($result =~ m|^/uploaded/|) {
7044: $r->print("<span class=\"LC_success\">Success:</span> Successfully uploaded ".(length($env{'form.upfile'})-1)." bytes of data into location <tt>".$result."</tt>");
7045: } else {
7046: $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>");
7047: }
7048: }
7049: if ($symb) {
7050: $r->print(&scantron_selectphase($r,$uploadedfile));
7051: } else {
7052: $r->print($doanotherupload);
7053: }
7054: return '';
7055: }
7056:
7057: =pod
7058:
7059: =item valid_file
7060:
7061: Validates that the requested bubble data file exists in the course.
7062:
7063: =cut
7064:
7065: sub valid_file {
7066: my ($requested_file)=@_;
7067: foreach my $filename (sort(&scantron_filenames())) {
7068: if ($requested_file eq $filename) { return 1; }
7069: }
7070: return 0;
7071: }
7072:
7073: =pod
7074:
7075: =item scantron_download_scantron_data
7076:
7077: Shows a list of the three internal files (original, corrected,
7078: skipped) for a specific bubble sheet data file that exists in the
7079: course.
7080:
7081: =cut
7082:
7083: sub scantron_download_scantron_data {
7084: my ($r)=@_;
7085: my $default_form_data=&defaultFormData(&get_symb($r,1));
7086: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7087: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7088: my $file=$env{'form.scantron_selectfile'};
7089: if (! &valid_file($file)) {
7090: $r->print(<<ERROR);
7091: <p>
7092: The requested file name was invalid.
7093: </p>
7094: ERROR
7095: $r->print(&show_grading_menu_form(&get_symb($r,1)));
7096: return;
7097: }
7098: my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
7099: my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
7100: my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
7101: &Apache::lonnet::allowuploaded('/adm/grades',$orig);
7102: &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
7103: &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
7104: $r->print(<<DOWNLOAD);
7105: <p>
7106: <a href="$orig">Original</a> file as uploaded by the scantron office.
7107: </p>
7108: <p>
7109: <a href="$corrected">Corrections</a>, a file of corrected records that were used in grading.
7110: </p>
7111: <p>
7112: <a href="$skipped">Skipped</a>, a file of records that were skipped.
7113: </p>
7114: DOWNLOAD
7115: $r->print(&show_grading_menu_form(&get_symb($r,1)));
7116: return '';
7117: }
7118:
7119: =pod
7120:
7121: =back
7122:
7123: =cut
7124:
7125: #-------- end of section for handling grading scantron forms -------
7126: #
7127: #-------------------------------------------------------------------
7128:
7129: #-------------------------- Menu interface -------------------------
7130: #
7131: #--- Show a Grading Menu button - Calls the next routine ---
7132: sub show_grading_menu_form {
7133: my ($symb)=@_;
7134: my $result.='<br /><form action="/adm/grades" method="post">'."\n".
7135: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
7136: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
7137: '<input type="hidden" name="command" value="gradingmenu" />'."\n".
7138: '<input type="submit" name="submit" value="Grading Menu" />'."\n".
7139: '</form>'."\n";
7140: return $result;
7141: }
7142:
7143: # -- Retrieve choices for grading form
7144: sub savedState {
7145: my %savedState = ();
7146: if ($env{'form.saveState'}) {
7147: foreach (split(/:/,$env{'form.saveState'})) {
7148: my ($key,$value) = split(/=/,$_,2);
7149: $savedState{$key} = $value;
7150: }
7151: }
7152: return \%savedState;
7153: }
7154:
7155: sub grading_menu {
7156: my ($request) = @_;
7157: my ($symb)=&get_symb($request);
7158: if (!$symb) {return '';}
7159: my $probTitle = &Apache::lonnet::gettitle($symb);
7160: my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
7161:
7162: #
7163: # Define menu data
7164: $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
7165: my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
7166: $request->print($table);
7167: my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
7168: 'handgrade'=>$hdgrade,
7169: 'probTitle'=>$probTitle,
7170: 'command'=>'submit_options',
7171: 'saveState'=>"",
7172: 'gradingMenu'=>1,
7173: 'showgrading'=>"yes");
7174: my $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
7175: my @menu = ({ url => $url,
7176: name => &mt('Manual Grading/View Submissions'),
7177: short_description =>
7178: &mt('Start the process of hand grading submissions.'),
7179: });
7180: $fields{'command'} = 'csvform';
7181: $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
7182: push (@menu, { url => $url,
7183: name => &mt('Upload Scores'),
7184: short_description =>
7185: &mt('Specify a file containing the class scores for current resource.')});
7186: $fields{'command'} = 'processclicker';
7187: $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
7188: push (@menu, { url => $url,
7189: name => &mt('Process Clicker'),
7190: short_description =>
7191: &mt('Specify a file containing the clicker information for this resource.')});
7192: $fields{'command'} = 'scantron_selectphase';
7193: $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
7194: push (@menu, { url => $url,
7195: name => &mt('Grade Scantron Forms'),
7196: short_description =>
7197: &mt('')});
7198: $fields{'command'} = 'verify';
7199: $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
7200: push (@menu, { url => "",
7201: jscript => ' onClick="javascript:checkChoice2(document.forms.gradingMenu,\'5\',\'verify\')" ',
7202: name => &mt('Verify Receipt'),
7203: short_description =>
7204: &mt('')});
7205: $fields{'command'} = 'manage';
7206: $url = &Apache::lonhtmlcommon::build_url('/adm/helper/resettimes.helper',\%fields);
7207: push (@menu, { url => $url,
7208: name => &mt('Manage Access Times'),
7209: short_description =>
7210: &mt('')});
7211: $fields{'command'} = 'view';
7212: $url = &Apache::lonhtmlcommon::build_url('/adm/pickcode',\%fields);
7213: push (@menu, { url => $url,
7214: name => &mt('View Saved CODEs'),
7215: short_description =>
7216: &mt('')});
7217:
7218: #
7219: # Create the menu
7220: my $Str;
7221: # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
7222: $Str .= '<form method="post" action="" name="gradingMenu">';
7223: $Str .= '<input type="hidden" name="command" value="" />'.
7224: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
7225: '<input type="hidden" name="handgrade" value="'.$hdgrade.'" />'."\n".
7226: '<input type="hidden" name="probTitle" value="'.$probTitle.'" ue="" />'."\n".
7227: '<input type="hidden" name="saveState" value="" />'."\n".
7228: '<input type="hidden" name="gradingMenu" value="1" />'."\n".
7229: '<input type="hidden" name="showgrading" value="yes" />'."\n";
7230:
7231: foreach my $menudata (@menu) {
7232: if ($menudata->{'name'} ne &mt('Verify Receipt')) {
7233: $Str .=' <h3><a '.
7234: $menudata->{'jscript'}.
7235: ' href="'.
7236: $menudata->{'url'}.'" >'.
7237: $menudata->{'name'}."</a></h3>\n";
7238: } else {
7239: $Str .=' <h3><a '.
7240: $menudata->{'jscript'}.
7241: ' href="javascript:checkChoice2(document.forms.gradingMenu,\'5\',\'verify\')" >'.
7242: $menudata->{'name'}."</a></h3>\n";
7243: $Str .= (' 'x8).
7244: ' receipt: '.&Apache::lonnet::recprefix($env{'request.course.id'}).
7245: '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
7246: }
7247: $Str .= ' '.(' 'x8).$menudata->{'short_description'}.
7248: "\n";
7249: }
7250: $Str .="</dl>\n";
7251: $Str .="</form>\n";
7252: $request->print(<<GRADINGMENUJS);
7253: <script type="text/javascript" language="javascript">
7254: function checkChoice(formname,val,cmdx) {
7255: if (val <= 2) {
7256: var cmd = radioSelection(formname.radioChoice);
7257: var cmdsave = cmd;
7258: } else {
7259: cmd = cmdx;
7260: cmdsave = 'submission';
7261: }
7262: formname.command.value = cmd;
7263: formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
7264: ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
7265: if (val < 5) formname.submit();
7266: if (val == 5) {
7267: if (!checkReceiptNo(formname,'notOK')) { return false;}
7268: formname.submit();
7269: }
7270: if (val < 7) formname.submit();
7271: }
7272: function checkChoice2(formname,val,cmdx) {
7273: if (val <= 2) {
7274: var cmd = radioSelection(formname.radioChoice);
7275: var cmdsave = cmd;
7276: } else {
7277: cmd = cmdx;
7278: cmdsave = 'submission';
7279: }
7280: formname.command.value = cmd;
7281: if (val < 5) formname.submit();
7282: if (val == 5) {
7283: if (!checkReceiptNo(formname,'notOK')) { return false;}
7284: formname.submit();
7285: }
7286: if (val < 7) formname.submit();
7287: }
7288:
7289: function checkReceiptNo(formname,nospace) {
7290: var receiptNo = formname.receipt.value;
7291: var checkOpt = false;
7292: if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
7293: if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
7294: if (checkOpt) {
7295: alert("Please enter a receipt number given by a student in the receipt box.");
7296: formname.receipt.value = "";
7297: formname.receipt.focus();
7298: return false;
7299: }
7300: return true;
7301: }
7302: </script>
7303: GRADINGMENUJS
7304: &commonJSfunctions($request);
7305: my $result='<h3> <span class="LC_info">Manual Grading/View Submission</span></h3>';
7306: $result.=$table;
7307: my (undef,$sections) = &getclasslist('all','0');
7308: my $savedState = &savedState();
7309: my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
7310: my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
7311: my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
7312: my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
7313:
7314: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
7315: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
7316: '<input type="hidden" name="handgrade" value="'.$hdgrade.'" />'."\n".
7317: '<input type="hidden" name="probTitle" value="'.$probTitle.'" ue="" />'."\n".
7318: '<input type="hidden" name="saveState" value="" />'."\n".
7319: '<input type="hidden" name="gradingMenu" value="1" />'."\n".
7320: '<input type="hidden" name="showgrading" value="yes" />'."\n";
7321:
7322: $result.='<table width="100%" border="0"><tr><td bgcolor=#777777>'."\n".
7323: '<table width="100%" border="0"><tr bgcolor="#e6ffff"><td colspan="2">'."\n".
7324: ' <b>Select a Grading/Viewing Option</b></td></tr>'."\n".
7325: '<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
7326:
7327: $result.='<table width="100%" border="0">';
7328: $result.='<tr bgcolor="#ffffe6" valign="top">'."\n";
7329: $result.='<td><b>'.&mt('Sections').'</b></td>';
7330: # $result.='<td>Groups</td>';
7331: $result.='<td><b>'.&mt('Access Status').'</td>'."\n";
7332: $result.='</tr>';
7333: $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
7334: ' <select name="section" multiple="multiple" size="3">'."\n";
7335: if (ref($sections)) {
7336: foreach (sort (@$sections)) {
7337: $result.='<option value="'.$_.'" '.
7338: ($saveSec eq $_ ? 'selected="selected"':'').'>'.$_.'</option>'."\n";
7339: }
7340: }
7341: $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> ';
7342: return $Str;
7343: }
7344:
7345:
7346: #--- Displays the submissions first page -------
7347: sub submit_options {
7348: my ($request) = @_;
7349: my ($symb)=&get_symb($request);
7350: if (!$symb) {return '';}
7351: my $probTitle = &Apache::lonnet::gettitle($symb);
7352:
7353: $request->print(<<GRADINGMENUJS);
7354: <script type="text/javascript" language="javascript">
7355: function checkChoice(formname,val,cmdx) {
7356: if (val <= 2) {
7357: var cmd = radioSelection(formname.radioChoice);
7358: var cmdsave = cmd;
7359: } else {
7360: cmd = cmdx;
7361: cmdsave = 'submission';
7362: }
7363: formname.command.value = cmd;
7364: formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
7365: ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
7366: if (val < 5) formname.submit();
7367: if (val == 5) {
7368: if (!checkReceiptNo(formname,'notOK')) { return false;}
7369: formname.submit();
7370: }
7371: if (val < 7) formname.submit();
7372: }
7373:
7374: function checkReceiptNo(formname,nospace) {
7375: var receiptNo = formname.receipt.value;
7376: var checkOpt = false;
7377: if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
7378: if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
7379: if (checkOpt) {
7380: alert("Please enter a receipt number given by a student in the receipt box.");
7381: formname.receipt.value = "";
7382: formname.receipt.focus();
7383: return false;
7384: }
7385: return true;
7386: }
7387: </script>
7388: GRADINGMENUJS
7389: &commonJSfunctions($request);
7390: my $result='<h3> <span class="LC_info">Manual Grading/View Submission</span></h3>';
7391: my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
7392: $result.=$table;
7393: my (undef,$sections) = &getclasslist('all','0');
7394: my $savedState = &savedState();
7395: my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
7396: my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
7397: my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
7398: my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
7399:
7400: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
7401: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
7402: '<input type="hidden" name="handgrade" value="'.$hdgrade.'" />'."\n".
7403: '<input type="hidden" name="probTitle" value="'.$probTitle.'" />'."\n".
7404: '<input type="hidden" name="command" value="" />'."\n".
7405: '<input type="hidden" name="saveState" value="" />'."\n".
7406: '<input type="hidden" name="gradingMenu" value="1" />'."\n".
7407: '<input type="hidden" name="showgrading" value="yes" />'."\n";
7408:
7409: $result.='<table border="0"><tr><td bgcolor=#777777>'."\n".
7410: '<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n".
7411: ' <b>Select a Grading/Viewing Option</b></td></tr>'."\n".
7412: '<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
7413:
7414: $result.='<table width="100%" border="0">';
7415: $result.='<tr bgcolor="#ffffe6" valign="top">'."\n";
7416: $result.='<td><b>'.&mt('Sections').'</b></td>';
7417: $result.='<td><b>'.&mt('Groups').'</b></td>';
7418: $result.='<td><b>'.&mt('Access Status').'</td>'."\n";
7419: $result.='</tr>';
7420: $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
7421: ' <select name="section" multiple="multiple" size="3">'."\n";
7422: if (ref($sections)) {
7423: foreach (sort (@$sections)) {
7424: $result.='<option value="'.$_.'" '.
7425: ($saveSec eq $_ ? 'selected="selected"':'').'>'.$_.'</option>'."\n";
7426: }
7427: }
7428: $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> ';
7429: $result.= '</td><td>'."\n";
7430: $result.= &Apache::lonstatistics::GroupSelect('group','multiple',3);
7431: $result.='</td><td>'."\n";
7432: $result.=&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,3,undef,'mult');
7433:
7434: $result.='</td></tr>';
7435:
7436: $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="3"><label>'.
7437: '<input type="radio" name="radioChoice" value="submission" '.
7438: ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.'<b>'.&mt('Current Resource').':</b> '.&mt('For one or more students').
7439: '</label> <select name="submitonly">'.
7440: '<option value="yes" '.
7441: ($saveSub eq 'yes' ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>'.
7442: '<option value="queued" '.
7443: ($saveSub eq 'queued' ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>'.
7444: '<option value="graded" '.
7445: ($saveSub eq 'graded' ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>'.
7446: '<option value="incorrect" '.
7447: ($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>'.
7448: '<option value="all" '.
7449: ($saveSub eq 'all' ? 'selected="selected"' : '').'>'.&mt('with any status').'</option></select></td></tr>'."\n";
7450:
7451: $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
7452: '<label><input type="radio" name="radioChoice" value="viewgrades" '.
7453: ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
7454: '<b>Current Resource:</b> For all students in selected section or course</label></td></tr>'."\n";
7455:
7456: $result.='<tr bgcolor="#ffffe6" valign="top"><td colspan="2">'.
7457: '<label><input type="radio" name="radioChoice" value="pickStudentPage" '.
7458: ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
7459: 'The <b>complete</b> set/page/sequence: For one student</label></td></tr>'."\n";
7460:
7461: $result.='<tr bgcolor="#ffffe6"><td colspan="2"><br />'.
7462: '<input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="Next->" />'.
7463: '</td></tr></table>'."\n";
7464:
7465: $result.='</td>'; #<td valign="top">';
7466:
7467: # $result.='<table width="100%" border="0">';
7468: # $result.='<tr bgcolor="#ffffe6"><td>'.
7469: # '<input type="button" onClick="javascript:checkChoice(this.form,\'3\',\'csvform\');" value="'.&mt('Upload').'" />'.
7470: # ' '.&mt('scores from file').' </td></tr>'."\n";
7471: #
7472: # $result.='<tr bgcolor="#ffffe6"><td>'.
7473: # '<input type="button" onClick="javascript:checkChoice(this.form,\'6\',\'processclicker\');" value="'.&mt('Process').'" />'.
7474: # ' '.&mt('clicker file').' </td></tr>'."\n";
7475: #
7476: # $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
7477: # '<input type="button" onClick="javascript:checkChoice(this.form,\'4\',\'scantron_selectphase\');'.
7478: # '" value="'.&mt('Grade').'" /> scantron forms</td></tr>'."\n";
7479: #
7480: # if ((&Apache::lonnet::allowed('mgr',$env{'request.course.id'})) && ($symb)) {
7481: # $result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
7482: # '<input type="button" onClick="javascript:checkChoice(this.form,\'5\',\'verify\');" value="'.&mt('Verify').'" />'.
7483: # ' '.&mt('receipt').': '.
7484: # &Apache::lonnet::recprefix($env{'request.course.id'}).
7485: # '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />'.
7486: # '</td></tr>'."\n";
7487: # }
7488: # $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
7489: # '<input type="button" onClick="javascript:this.form.action=\'/adm/helper/resettimes.helper\';this.form.submit();'.
7490: # '" value="'.&mt('Manage').'" /> access times.</td></tr>'."\n";
7491: # $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
7492: # '<input type="button" onClick="javascript:this.form.command.value=\'codelist\';this.form.action=\'/adm/pickcode\';this.form.submit();'.
7493: # '" value="'.&mt('View').'" /> saved CODEs.</td></tr>'."\n";
7494: #
7495: # $result.='</table>'."\n".'</td>';
7496: $result.= '</tr></table>'."\n".
7497: '</td></tr></table></form>'."\n";
7498: return $result;
7499: }
7500:
7501: sub reset_perm {
7502: undef(%perm);
7503: }
7504:
7505: sub init_perm {
7506: &reset_perm();
7507: foreach my $test_perm ('vgr','mgr','opa') {
7508:
7509: my $scope = $env{'request.course.id'};
7510: if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
7511:
7512: $scope .= '/'.$env{'request.course.sec'};
7513: if ( $perm{$test_perm}=
7514: &Apache::lonnet::allowed($test_perm,$scope)) {
7515: $perm{$test_perm.'_section'}=$env{'request.course.sec'};
7516: } else {
7517: delete($perm{$test_perm});
7518: }
7519: }
7520: }
7521: }
7522:
7523: sub gather_clicker_ids {
7524: my %clicker_ids;
7525:
7526: my $classlist = &Apache::loncoursedata::get_classlist();
7527:
7528: # Set up a couple variables.
7529: my $username_idx = &Apache::loncoursedata::CL_SNAME();
7530: my $domain_idx = &Apache::loncoursedata::CL_SDOM();
7531: my $status_idx = &Apache::loncoursedata::CL_STATUS();
7532:
7533: foreach my $student (keys(%$classlist)) {
7534: if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
7535: my $username = $classlist->{$student}->[$username_idx];
7536: my $domain = $classlist->{$student}->[$domain_idx];
7537: my $clickers =
7538: (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
7539: foreach my $id (split(/\,/,$clickers)) {
7540: $id=~s/^[\#0]+//;
7541: $id=~s/[\-\:]//g;
7542: if (exists($clicker_ids{$id})) {
7543: $clicker_ids{$id}.=','.$username.':'.$domain;
7544: } else {
7545: $clicker_ids{$id}=$username.':'.$domain;
7546: }
7547: }
7548: }
7549: return %clicker_ids;
7550: }
7551:
7552: sub gather_adv_clicker_ids {
7553: my %clicker_ids;
7554: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
7555: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7556: my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
7557: foreach my $element (sort(keys(%coursepersonnel))) {
7558: foreach my $person (split(/\,/,$coursepersonnel{$element})) {
7559: my ($puname,$pudom)=split(/\:/,$person);
7560: my $clickers =
7561: (&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
7562: foreach my $id (split(/\,/,$clickers)) {
7563: $id=~s/^[\#0]+//;
7564: $id=~s/[\-\:]//g;
7565: if (exists($clicker_ids{$id})) {
7566: $clicker_ids{$id}.=','.$puname.':'.$pudom;
7567: } else {
7568: $clicker_ids{$id}=$puname.':'.$pudom;
7569: }
7570: }
7571: }
7572: }
7573: return %clicker_ids;
7574: }
7575:
7576: sub clicker_grading_parameters {
7577: return ('gradingmechanism' => 'scalar',
7578: 'upfiletype' => 'scalar',
7579: 'specificid' => 'scalar',
7580: 'pcorrect' => 'scalar',
7581: 'pincorrect' => 'scalar');
7582: }
7583:
7584: sub process_clicker {
7585: my ($r)=@_;
7586: my ($symb)=&get_symb($r);
7587: if (!$symb) {return '';}
7588: my $result=&checkforfile_js();
7589: $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
7590: my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
7591: $result.=$table;
7592: $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
7593: $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
7594: $result.=' <b>'.&mt('Specify a file containing the clicker information for this resource').
7595: '.</b></td></tr>'."\n";
7596: $result.='<tr bgcolor=#ffffe6><td>'."\n";
7597: # Attempt to restore parameters from last session, set defaults if not present
7598: my %Saveable_Parameters=&clicker_grading_parameters();
7599: &Apache::loncommon::restore_course_settings('grades_clicker',
7600: \%Saveable_Parameters);
7601: if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
7602: if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
7603: if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
7604: if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
7605:
7606: my %checked;
7607: foreach my $gradingmechanism ('attendance','personnel','specific') {
7608: if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
7609: $checked{$gradingmechanism}="checked='checked'";
7610: }
7611: }
7612:
7613: my $upload=&mt("Upload File");
7614: my $type=&mt("Type");
7615: my $attendance=&mt("Award points just for participation");
7616: my $personnel=&mt("Correctness determined from response by course personnel");
7617: my $specific=&mt("Correctness determined from response with clicker ID(s)");
7618: my $pcorrect=&mt("Percentage points for correct solution");
7619: my $pincorrect=&mt("Percentage points for incorrect solution");
7620: my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
7621: ('iclicker' => 'i>clicker',
7622: 'interwrite' => 'interwrite PRS'));
7623: $symb = &Apache::lonenc::check_encrypt($symb);
7624: $result.=<<ENDUPFORM;
7625: <script type="text/javascript">
7626: function sanitycheck() {
7627: // Accept only integer percentages
7628: document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
7629: document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
7630: // Find out grading choice
7631: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
7632: if (document.forms.gradesupload.gradingmechanism[i].checked) {
7633: gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
7634: }
7635: }
7636: // By default, new choice equals user selection
7637: newgradingchoice=gradingchoice;
7638: // Not good to give more points for false answers than correct ones
7639: if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
7640: document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
7641: }
7642: // If new choice is attendance only, and old choice was correctness-based, restore defaults
7643: if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
7644: document.forms.gradesupload.pcorrect.value=100;
7645: document.forms.gradesupload.pincorrect.value=100;
7646: }
7647: // If the values are different, cannot be attendance only
7648: if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
7649: (gradingchoice=='attendance')) {
7650: newgradingchoice='personnel';
7651: }
7652: // Change grading choice to new one
7653: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
7654: if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
7655: document.forms.gradesupload.gradingmechanism[i].checked=true;
7656: } else {
7657: document.forms.gradesupload.gradingmechanism[i].checked=false;
7658: }
7659: }
7660: // Remember the old state
7661: document.forms.gradesupload.waschecked.value=newgradingchoice;
7662: }
7663: </script>
7664: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
7665: <input type="hidden" name="symb" value="$symb" />
7666: <input type="hidden" name="command" value="processclickerfile" />
7667: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
7668: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
7669: <input type="file" name="upfile" size="50" />
7670: <br /><label>$type: $selectform</label>
7671: <br /><label>$attendance: <input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" /></label>
7672: <br /><label>$personnel: <input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" /></label>
7673: <br /><label>$specific: <input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" /></label>
7674: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
7675: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
7676: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
7677: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
7678: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
7679: </form>
7680: ENDUPFORM
7681: $result.='</td></tr></table>'."\n".
7682: '</td></tr></table><br /><br />'."\n";
7683: $result.=&show_grading_menu_form($symb);
7684: return $result;
7685: }
7686:
7687: sub process_clicker_file {
7688: my ($r)=@_;
7689: my ($symb)=&get_symb($r);
7690: if (!$symb) {return '';}
7691:
7692: my %Saveable_Parameters=&clicker_grading_parameters();
7693: &Apache::loncommon::store_course_settings('grades_clicker',
7694: \%Saveable_Parameters);
7695:
7696: my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
7697: if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
7698: $result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
7699: return $result.&show_grading_menu_form($symb);
7700: }
7701: my %clicker_ids=&gather_clicker_ids();
7702: my %correct_ids;
7703: if ($env{'form.gradingmechanism'} eq 'personnel') {
7704: %correct_ids=&gather_adv_clicker_ids();
7705: }
7706: if ($env{'form.gradingmechanism'} eq 'specific') {
7707: foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
7708: $correct_id=~tr/a-z/A-Z/;
7709: $correct_id=~s/\s//gs;
7710: $correct_id=~s/^[\#0]+//;
7711: $correct_id=~s/[\-\:]//g;
7712: if ($correct_id) {
7713: $correct_ids{$correct_id}='specified';
7714: }
7715: }
7716: }
7717: if ($env{'form.gradingmechanism'} eq 'attendance') {
7718: $result.=&mt('Score based on attendance only');
7719: } else {
7720: my $number=0;
7721: $result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
7722: foreach my $id (sort(keys(%correct_ids))) {
7723: $result.='<br /><tt>'.$id.'</tt> - ';
7724: if ($correct_ids{$id} eq 'specified') {
7725: $result.=&mt('specified');
7726: } else {
7727: my ($uname,$udom)=split(/\:/,$correct_ids{$id});
7728: $result.=&Apache::loncommon::plainname($uname,$udom);
7729: }
7730: $number++;
7731: }
7732: $result.="</p>\n";
7733: if ($number==0) {
7734: $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
7735: return $result.&show_grading_menu_form($symb);
7736: }
7737: }
7738: if (length($env{'form.upfile'}) < 2) {
7739: $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
7740: '<span class="LC_error">',
7741: '</span>',
7742: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
7743: return $result.&show_grading_menu_form($symb);
7744: }
7745:
7746: # Were able to get all the info needed, now analyze the file
7747:
7748: $result.=&Apache::loncommon::studentbrowser_javascript();
7749: $symb = &Apache::lonenc::check_encrypt($symb);
7750: my $heading=&mt('Scanning clicker file');
7751: $result.=(<<ENDHEADER);
7752: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
7753: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
7754: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
7755: <form method="post" action="/adm/grades" name="clickeranalysis">
7756: <input type="hidden" name="symb" value="$symb" />
7757: <input type="hidden" name="command" value="assignclickergrades" />
7758: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
7759: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
7760: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
7761: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
7762: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
7763: ENDHEADER
7764: my %responses;
7765: my @questiontitles;
7766: my $errormsg='';
7767: my $number=0;
7768: if ($env{'form.upfiletype'} eq 'iclicker') {
7769: ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
7770: }
7771: if ($env{'form.upfiletype'} eq 'interwrite') {
7772: ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
7773: }
7774: $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
7775: '<input type="hidden" name="number" value="'.$number.'" />'.
7776: &mt('Awarding [_1] percent for corrion(s)',$number).'<br />'.
7777: '<input type="hidden" name="number" value="'.$number.'" />'.
7778: &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
7779: $env{'form.pcorrect'},$env{'form.pincorrect'}).
7780: '<br />';
7781: # Remember Question Titles
7782: # FIXME: Possibly need delimiter other than ":"
7783: for (my $i=0;$i<$number;$i++) {
7784: $result.='<input type="hidden" name="question:'.$i.'" value="'.
7785: &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
7786: }
7787: my $correct_count=0;
7788: my $student_count=0;
7789: my $unknown_count=0;
7790: # Match answers with usernames
7791: # FIXME: Possibly need delimiter other than ":"
7792: foreach my $id (keys(%responses)) {
7793: if ($correct_ids{$id}) {
7794: $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
7795: $correct_count++;
7796: } elsif ($clicker_ids{$id}) {
7797: if ($clicker_ids{$id}=~/\,/) {
7798: # More than one user with the same clicker!
7799: $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
7800: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
7801: "<select name='multi".$id."'>";
7802: foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
7803: $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
7804: }
7805: $result.='</select>';
7806: $unknown_count++;
7807: } else {
7808: # Good: found one and only one user with the right clicker
7809: $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
7810: $student_count++;
7811: }
7812: } else {
7813: $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
7814: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
7815: "\n".&mt("Username").": <input type='text' name='uname".$id."' /> ".
7816: "\n".&mt("Domain").": ".
7817: &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).' '.
7818: &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
7819: $unknown_count++;
7820: }
7821: }
7822: $result.='<hr />'.
7823: &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
7824: if ($env{'form.gradingmechanism'} ne 'attendance') {
7825: if ($correct_count==0) {
7826: $errormsg.="Found no correct answers answers for grading!";
7827: } elsif ($correct_count>1) {
7828: $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
7829: }
7830: }
7831: if ($number<1) {
7832: $errormsg.="Found no questions.";
7833: }
7834: if ($errormsg) {
7835: $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
7836: } else {
7837: $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
7838: }
7839: $result.='</form></td></tr></table>'."\n".
7840: '</td></tr></table><br /><br />'."\n";
7841: return $result.&show_grading_menu_form($symb);
7842: }
7843:
7844: sub iclicker_eval {
7845: my ($questiontitles,$responses)=@_;
7846: my $number=0;
7847: my $errormsg='';
7848: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
7849: my %components=&Apache::loncommon::record_sep($line);
7850: my @entries=map {$components{$_}} (sort(keys(%components)));
7851: if ($entries[0] eq 'Question') {
7852: for (my $i=3;$i<$#entries;$i+=6) {
7853: $$questiontitles[$number]=$entries[$i];
7854: $number++;
7855: }
7856: }
7857: if ($entries[0]=~/^\#/) {
7858: my $id=$entries[0];
7859: my @idresponses;
7860: $id=~s/^[\#0]+//;
7861: for (my $i=0;$i<$number;$i++) {
7862: my $idx=3+$i*6;
7863: push(@idresponses,$entries[$idx]);
7864: }
7865: $$responses{$id}=join(',',@idresponses);
7866: }
7867: }
7868: return ($errormsg,$number);
7869: }
7870:
7871: sub interwrite_eval {
7872: my ($questiontitles,$responses)=@_;
7873: my $number=0;
7874: my $errormsg='';
7875: my $skipline=1;
7876: my $questionnumber=0;
7877: my %idresponses=();
7878: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
7879: my %components=&Apache::loncommon::record_sep($line);
7880: my @entries=map {$components{$_}} (sort(keys(%components)));
7881: if ($entries[1] eq 'Time') { $skipline=0; next; }
7882: if ($entries[1] eq 'Response') { $skipline=1; }
7883: next if $skipline;
7884: if ($entries[0]!=$questionnumber) {
7885: $questionnumber=$entries[0];
7886: $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
7887: $number++;
7888: }
7889: my $id=$entries[4];
7890: $id=~s/^[\#0]+//;
7891: $id=~s/^v\d*\://i;
7892: $id=~s/[\-\:]//g;
7893: $idresponses{$id}[$number]=$entries[6];
7894: }
7895: foreach my $id (keys %idresponses) {
7896: $$responses{$id}=join(',',@{$idresponses{$id}});
7897: $$responses{$id}=~s/^\s*\,//;
7898: }
7899: return ($errormsg,$number);
7900: }
7901:
7902: sub assign_clicker_grades {
7903: my ($r)=@_;
7904: my ($symb)=&get_symb($r);
7905: if (!$symb) {return '';}
7906: # See which part we are saving to
7907: my ($partlist,$handgrade,$responseType) = &response_type($symb);
7908: # FIXME: This should probably look for the first handgradeable part
7909: my $part=$$partlist[0];
7910: # Start screen output
7911: my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
7912:
7913: my $heading=&mt('Assigning grades based on clicker file');
7914: $result.=(<<ENDHEADER);
7915: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
7916: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
7917: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
7918: ENDHEADER
7919: # Get correct result
7920: # FIXME: Possibly need delimiter other than ":"
7921: my @correct=();
7922: my $gradingmechanism=$env{'form.gradingmechanism'};
7923: my $number=$env{'form.number'};
7924: if ($gradingmechanism ne 'attendance') {
7925: foreach my $key (keys(%env)) {
7926: if ($key=~/^form\.correct\:/) {
7927: my @input=split(/\,/,$env{$key});
7928: for (my $i=0;$i<=$#input;$i++) {
7929: if (($correct[$i]) && ($input[$i]) &&
7930: ($correct[$i] ne $input[$i])) {
7931: $result.='<br /><span class="LC_warning">'.
7932: &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
7933: $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
7934: } elsif ($input[$i]) {
7935: $correct[$i]=$input[$i];
7936: }
7937: }
7938: }
7939: }
7940: for (my $i=0;$i<$number;$i++) {
7941: if (!$correct[$i]) {
7942: $result.='<br /><span class="LC_error">'.
7943: &mt('No correct result given for question "[_1]"!',
7944: $env{'form.question:'.$i}).'</span>';
7945: }
7946: }
7947: $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
7948: }
7949: # Start grading
7950: my $pcorrect=$env{'form.pcorrect'};
7951: my $pincorrect=$env{'form.pincorrect'};
7952: my $storecount=0;
7953: foreach my $key (keys(%env)) {
7954: my $user='';
7955: if ($key=~/^form\.student\:(.*)$/) {
7956: $user=$1;
7957: }
7958: if ($key=~/^form\.unknown\:(.*)$/) {
7959: my $id=$1;
7960: if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
7961: $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
7962: } elsif ($env{'form.multi'.$id}) {
7963: $user=$env{'form.multi'.$id};
7964: }
7965: }
7966: if ($user) {
7967: my @answer=split(/\,/,$env{$key});
7968: my $sum=0;
7969: for (my $i=0;$i<$number;$i++) {
7970: if ($answer[$i]) {
7971: if ($gradingmechanism eq 'attendance') {
7972: $sum+=$pcorrect;
7973: } else {
7974: if ($answer[$i] eq $correct[$i]) {
7975: $sum+=$pcorrect;
7976: } else {
7977: $sum+=$pincorrect;
7978: }
7979: }
7980: }
7981: }
7982: my $ave=$sum/(100*$number);
7983: # Store
7984: my ($username,$domain)=split(/\:/,$user);
7985: my %grades=();
7986: $grades{"resource.$part.solved"}='correct_by_override';
7987: $grades{"resource.$part.awarded"}=$ave;
7988: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
7989: my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
7990: $env{'request.course.id'},
7991: $domain,$username);
7992: if ($returncode ne 'ok') {
7993: $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
7994: } else {
7995: $storecount++;
7996: }
7997: }
7998: }
7999: # We are done
8000: $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
8001: '</td></tr></table>'."\n".
8002: '</td></tr></table><br /><br />'."\n";
8003: return $result.&show_grading_menu_form($symb);
8004: }
8005:
8006: sub handler {
8007: my $request=$_[0];
8008:
8009: &reset_caches();
8010: if ($env{'browser.mathml'}) {
8011: &Apache::loncommon::content_type($request,'text/xml');
8012: } else {
8013: &Apache::loncommon::content_type($request,'text/html');
8014: }
8015: $request->send_http_header;
8016: return '' if $request->header_only;
8017: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
8018: my $symb=&get_symb($request,1);
8019: my @commands=&Apache::loncommon::get_env_multiple('form.command');
8020: my $command=$commands[0];
8021:
8022: if ($#commands > 0) {
8023: &Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
8024: }
8025:
8026:
8027: $request->print(&Apache::loncommon::start_page('Grading'));
8028: if ($symb eq '' && $command eq '') {
8029: if ($env{'user.adv'}) {
8030: if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
8031: ($env{'form.codethree'})) {
8032: my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
8033: $env{'form.codethree'};
8034: my ($tsymb,$tuname,$tudom,$tcrsid)=
8035: &Apache::lonnet::checkin($token);
8036: if ($tsymb) {
8037: my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
8038: if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
8039: $request->print(&Apache::lonnet::ssi_body('/res/'.$url,
8040: ('grade_username' => $tuname,
8041: 'grade_domain' => $tudom,
8042: 'grade_courseid' => $tcrsid,
8043: 'grade_symb' => $tsymb)));
8044: } else {
8045: $request->print('<h3>Not authorized: '.$token.'</h3>');
8046: }
8047: } else {
8048: $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
8049: }
8050: } else {
8051: $request->print(&Apache::lonxml::tokeninputfield());
8052: }
8053: }
8054: } else {
8055: &init_perm();
8056: if ($command eq 'submission' && $perm{'vgr'}) {
8057: ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
8058: } elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
8059: &pickStudentPage($request);
8060: } elsif ($command eq 'displayPage' && $perm{'vgr'}) {
8061: &displayPage($request);
8062: } elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
8063: &updateGradeByPage($request);
8064: } elsif ($command eq 'processGroup' && $perm{'vgr'}) {
8065: &processGroup($request);
8066: } elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
8067: $request->print(&grading_menu($request));
8068: } elsif ($command eq 'submit_options' && $perm{'vgr'}) {
8069: $request->print(&submit_options($request));
8070: } elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
8071: $request->print(&viewgrades($request));
8072: } elsif ($command eq 'handgrade' && $perm{'mgr'}) {
8073: $request->print(&processHandGrade($request));
8074: } elsif ($command eq 'editgrades' && $perm{'mgr'}) {
8075: $request->print(&editgrades($request));
8076: } elsif ($command eq 'verify' && $perm{'vgr'}) {
8077: $request->print(&verifyreceipt($request));
8078: } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
8079: $request->print(&process_clicker($request));
8080: } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
8081: $request->print(&process_clicker_file($request));
8082: } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
8083: $request->print(&assign_clicker_grades($request));
8084: } elsif ($command eq 'csvform' && $perm{'mgr'}) {
8085: $request->print(&upcsvScores_form($request));
8086: } elsif ($command eq 'csvupload' && $perm{'mgr'}) {
8087: $request->print(&csvupload($request));
8088: } elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
8089: $request->print(&csvuploadmap($request));
8090: } elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
8091: if ($env{'form.associate'} ne 'Reverse Association') {
8092: $request->print(&csvuploadoptions($request));
8093: } else {
8094: if ( $env{'form.upfile_associate'} ne 'reverse' ) {
8095: $env{'form.upfile_associate'} = 'reverse';
8096: } else {
8097: $env{'form.upfile_associate'} = 'forward';
8098: }
8099: $request->print(&csvuploadmap($request));
8100: }
8101: } elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
8102: $request->print(&csvuploadassign($request));
8103: } elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
8104: &Apache::lonnet::logthis("Selecting pyhase");
8105: $request->print(&scantron_selectphase($request));
8106: } elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
8107: $request->print(&scantron_do_warning($request));
8108: } elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
8109: $request->print(&scantron_validate_file($request));
8110: } elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
8111: $request->print(&scantron_process_students($request));
8112: } elsif ($command eq 'scantronupload' &&
8113: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
8114: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
8115: $request->print(&scantron_upload_scantron_data($request));
8116: } elsif ($command eq 'scantronupload_save' &&
8117: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
8118: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
8119: $request->print(&scantron_upload_scantron_data_save($request));
8120: } elsif ($command eq 'scantron_download' &&
8121: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
8122: $request->print(&scantron_download_scantron_data($request));
8123: } elsif ($command) {
8124: $request->print("Access Denied ($command)");
8125: }
8126: }
8127: $request->print(&Apache::loncommon::end_page());
8128: &reset_caches();
8129: return '';
8130: }
8131:
8132: 1;
8133:
8134: __END__;
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>