1: # The LearningOnline Network with CAPA
2: # The LON-CAPA Grading handler
3: #
4: # $Id: grades.pm,v 1.485 2007/11/08 01:48:18 albertel Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28:
29: package Apache::grades;
30: use strict;
31: use Apache::style;
32: use Apache::lonxml;
33: use Apache::lonnet;
34: use Apache::loncommon;
35: use Apache::lonhtmlcommon;
36: use Apache::lonnavmaps;
37: use Apache::lonhomework;
38: use Apache::lonpickcode;
39: use Apache::loncoursedata;
40: use Apache::lonmsg();
41: use Apache::Constants qw(:common);
42: use Apache::lonlocal;
43: use Apache::lonenc;
44: use String::Similarity;
45: use LONCAPA;
46:
47: use POSIX qw(floor);
48:
49:
50: my %perm=();
51: my %bubble_lines_per_response = (); # no. bubble lines for each response.
52: # index is "symb.part_id"
53:
54: my %first_bubble_line = (); # First bubble line no. for each bubble.
55:
56: # Save and restore the bubble lines array to the form env.
57:
58:
59: sub save_bubble_lines {
60: foreach my $line (keys(%bubble_lines_per_response)) {
61: $env{"form.scantron.bubblelines.$line"} = $bubble_lines_per_response{$line};
62: $env{"form.scantron.first_bubble_line.$line"} =
63: $first_bubble_line{$line};
64: }
65: }
66:
67:
68: sub restore_bubble_lines {
69: my $line = 0;
70: %bubble_lines_per_response = ();
71: while ($env{"form.scantron.bubblelines.$line"}) {
72: my $value = $env{"form.scantron.bubblelines.$line"};
73: $bubble_lines_per_response{$line} = $value;
74: $first_bubble_line{$line} =
75: $env{"form.scantron.first_bubble_line.$line"};
76: $line++;
77: }
78:
79: }
80:
81: # Given the parsed scanline, get the response for
82: # 'answer' number n:
83:
84: sub get_response_bubbles {
85: my ($parsed_line, $response) = @_;
86:
87:
88: my $bubble_line = $first_bubble_line{$response-1} +1;
89: my $bubble_lines= $bubble_lines_per_response{$response-1};
90:
91: my $selected = "";
92:
93: for (my $bline = 0; $bline < $bubble_lines; $bline++) {
94: $selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
95: $bubble_line++;
96: }
97: return $selected;
98: }
99:
100:
101: # ----- These first few routines are general use routines.----
102:
103: # Return the number of occurences of a pattern in a string.
104:
105: sub occurence_count {
106: my ($string, $pattern) = @_;
107:
108: my @matches = ($string =~ /$pattern/g);
109:
110: return scalar(@matches);
111: }
112:
113:
114: # Take a string known to have digits and convert all the
115: # digits into letters in the range J,A..I.
116:
117: sub digits_to_letters {
118: my ($input) = @_;
119:
120: my @alphabet = ('J', 'A'..'I');
121:
122: my @input = split(//, $input);
123: my $output ='';
124: for (my $i = 0; $i < scalar(@input); $i++) {
125: if ($input[$i] =~ /\d/) {
126: $output .= $alphabet[$input[$i]];
127: } else {
128: $output .= $input[$i];
129: }
130: }
131: return $output;
132: }
133:
134: #
135: # --- Retrieve the parts from the metadata file.---
136: sub getpartlist {
137: my ($symb) = @_;
138:
139: my $navmap = Apache::lonnavmaps::navmap->new();
140: my $res = $navmap->getBySymb($symb);
141: my $partlist = $res->parts();
142: my $url = $res->src();
143: my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
144:
145: my @stores;
146: foreach my $part (@{ $partlist }) {
147: foreach my $key (@metakeys) {
148: if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
149: }
150: }
151: return @stores;
152: }
153:
154: # --- Get the symbolic name of a problem and the url
155: sub get_symb {
156: my ($request,$silent) = @_;
157: (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
158: my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
159: if ($symb eq '') {
160: if (!$silent) {
161: $request->print("Unable to handle ambiguous references:$url:.");
162: return ();
163: }
164: }
165: &Apache::lonenc::check_decrypt(\$symb);
166: return ($symb);
167: }
168:
169: #--- Format fullname, username:domain if different for display
170: #--- Use anywhere where the student names are listed
171: sub nameUserString {
172: my ($type,$fullname,$uname,$udom) = @_;
173: if ($type eq 'header') {
174: return '<b> '.&mt('Fullname').' </b><span class="LC_internal_info">('.&mt('Username').')</span>';
175: } else {
176: return ' '.$fullname.'<span class="LC_internal_info"> ('.$uname.
177: ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
178: }
179: }
180:
181: #--- Get the partlist and the response type for a given problem. ---
182: #--- Indicate if a response type is coded handgraded or not. ---
183: sub response_type {
184: my ($symb) = shift;
185:
186: my $navmap = Apache::lonnavmaps::navmap->new();
187: my $res = $navmap->getBySymb($symb);
188: my $partlist = $res->parts();
189: my %vPart =
190: map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
191: my (%response_types,%handgrade);
192: foreach my $part (@{ $partlist }) {
193: next if (%vPart && !exists($vPart{$part}));
194:
195: my @types = $res->responseType($part);
196: my @ids = $res->responseIds($part);
197: for (my $i=0; $i < scalar(@ids); $i++) {
198: $response_types{$part}{$ids[$i]} = $types[$i];
199: $handgrade{$part.'_'.$ids[$i]} =
200: &Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
201: '.handgrade',$symb);
202: }
203: }
204: return ($partlist,\%handgrade,\%response_types);
205: }
206:
207: sub flatten_responseType {
208: my ($responseType) = @_;
209: my @part_response_id =
210: map {
211: my $part = $_;
212: map {
213: [$part,$_]
214: } sort(keys(%{ $responseType->{$part} }));
215: } sort(keys(%$responseType));
216: return @part_response_id;
217: }
218:
219: sub get_display_part {
220: my ($partID,$symb)=@_;
221: my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
222: if (defined($display) and $display ne '') {
223: $display.= " (<span class=\"LC_internal_info\">id $partID</span>)";
224: } else {
225: $display=$partID;
226: }
227: return $display;
228: }
229:
230: #--- Show resource title
231: #--- and parts and response type
232: sub showResourceInfo {
233: my ($symb,$probTitle,$checkboxes) = @_;
234: my $col=3;
235: if ($checkboxes) { $col=4; }
236: my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
237: $result .='<table border="0">';
238: my ($partlist,$handgrade,$responseType) = &response_type($symb);
239: my %resptype = ();
240: my $hdgrade='no';
241: my %partsseen;
242: foreach my $partID (sort keys(%$responseType)) {
243: foreach my $resID (sort keys(%{ $responseType->{$partID} })) {
244: my $handgrade=$$handgrade{$partID.'_'.$resID};
245: my $responsetype = $responseType->{$partID}->{$resID};
246: $hdgrade = $handgrade if ($handgrade eq 'yes');
247: $result.='<tr>';
248: if ($checkboxes) {
249: if (exists($partsseen{$partID})) {
250: $result.="<td> </td>";
251: } else {
252: $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
253: }
254: $partsseen{$partID}=1;
255: }
256: my $display_part=&get_display_part($partID,$symb);
257: $result.='<td>'.&mt('<b>Part: </b>[_1]',$display_part).' <span class="LC_internal_info">'.
258: $resID.'</span></td>'.
259: '<td>'.&mt('<b>Type: </b>[_1]',$responsetype).'</td></tr>';
260: # '<td>'.&mt('<b>Handgrade: </b>[_1]',$handgrade).'</td></tr>';
261: }
262: }
263: $result.='</table>'."\n";
264: return $result,$responseType,$hdgrade,$partlist,$handgrade;
265: }
266:
267: sub reset_caches {
268: &reset_analyze_cache();
269: &reset_perm();
270: }
271:
272: {
273: my %analyze_cache;
274:
275: sub reset_analyze_cache {
276: undef(%analyze_cache);
277: }
278:
279: sub get_analyze {
280: my ($symb,$uname,$udom)=@_;
281: my $key = "$symb\0$uname\0$udom";
282: return $analyze_cache{$key} if (exists($analyze_cache{$key}));
283:
284: my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
285: $url=&Apache::lonnet::clutter($url);
286: my $subresult=&Apache::lonnet::ssi($url,
287: ('grade_target' => 'analyze'),
288: ('grade_domain' => $udom),
289: ('grade_symb' => $symb),
290: ('grade_courseid' =>
291: $env{'request.course.id'}),
292: ('grade_username' => $uname));
293: (undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
294: my %analyze=&Apache::lonnet::str2hash($subresult);
295: return $analyze_cache{$key} = \%analyze;
296: }
297:
298: sub get_order {
299: my ($partid,$respid,$symb,$uname,$udom)=@_;
300: my $analyze = &get_analyze($symb,$uname,$udom);
301: return $analyze->{"$partid.$respid.shown"};
302: }
303:
304: sub get_radiobutton_correct_foil {
305: my ($partid,$respid,$symb,$uname,$udom)=@_;
306: my $analyze = &get_analyze($symb,$uname,$udom);
307: foreach my $foil (@{&get_order($partid,$respid,$symb,$uname,$udom)}) {
308: if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
309: return $foil;
310: }
311: }
312: }
313: }
314:
315: #--- Clean response type for display
316: #--- Currently filters option/rank/radiobutton/match/essay/Task
317: # response types only.
318: sub cleanRecord {
319: my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
320: $uname,$udom) = @_;
321: my $grayFont = '<span class="LC_internal_info">';
322: if ($response =~ /^(option|rank)$/) {
323: my %answer=&Apache::lonnet::str2hash($answer);
324: my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
325: my ($toprow,$bottomrow);
326: foreach my $foil (@$order) {
327: if ($grading{$foil} == 1) {
328: $toprow.='<td><b>'.$answer{$foil}.' </b></td>';
329: } else {
330: $toprow.='<td><i>'.$answer{$foil}.' </i></td>';
331: }
332: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
333: }
334: return '<blockquote><table border="1">'.
335: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
336: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
337: $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
338: } elsif ($response eq 'match') {
339: my %answer=&Apache::lonnet::str2hash($answer);
340: my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
341: my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
342: my ($toprow,$middlerow,$bottomrow);
343: foreach my $foil (@$order) {
344: my $item=shift(@items);
345: if ($grading{$foil} == 1) {
346: $toprow.='<td><b>'.$item.' </b></td>';
347: $middlerow.='<td><b>'.$grayFont.$answer{$foil}.' </span></b></td>';
348: } else {
349: $toprow.='<td><i>'.$item.' </i></td>';
350: $middlerow.='<td><i>'.$grayFont.$answer{$foil}.' </span></i></td>';
351: }
352: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
353: }
354: return '<blockquote><table border="1">'.
355: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
356: '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
357: $middlerow.'</tr>'.
358: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
359: $bottomrow.'</tr>'.'</table></blockquote>';
360: } elsif ($response eq 'radiobutton') {
361: my %answer=&Apache::lonnet::str2hash($answer);
362: my ($toprow,$bottomrow);
363: my $correct =
364: &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
365: foreach my $foil (@$order) {
366: if (exists($answer{$foil})) {
367: if ($foil eq $correct) {
368: $toprow.='<td><b>'.&mt('true').'</b></td>';
369: } else {
370: $toprow.='<td><i>'.&mt('true').'</i></td>';
371: }
372: } else {
373: $toprow.='<td>'.&mt('false').'</td>';
374: }
375: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
376: }
377: return '<blockquote><table border="1">'.
378: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
379: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
380: $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
381: } elsif ($response eq 'essay') {
382: if (! exists ($env{'form.'.$symb})) {
383: my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
384: $env{'course.'.$env{'request.course.id'}.'.domain'},
385: $env{'course.'.$env{'request.course.id'}.'.num'});
386:
387: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
388: $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
389: $env{'form.kwclr'} = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
390: $env{'form.kwsize'} = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
391: $env{'form.kwstyle'} = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
392: $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
393: }
394: $answer =~ s-\n-<br />-g;
395: return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
396: } elsif ( $response eq 'organic') {
397: my $result='Smile representation: "<tt>'.$answer.'</tt>"';
398: my $jme=$record->{$version."resource.$partid.$respid.molecule"};
399: $result.=&Apache::chemresponse::jme_img($jme,$answer,400);
400: return $result;
401: } elsif ( $response eq 'Task') {
402: if ( $answer eq 'SUBMITTED') {
403: my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
404: my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
405: return $result;
406: } elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
407: my @matches = grep(/^\Q$version\E.*?\.instance$/,
408: keys(%{$record}));
409: return join('<br />',($version,@matches));
410:
411:
412: } else {
413: my $result =
414: '<p>'
415: .&mt('Overall result: [_1]',
416: $record->{$version."resource.$respid.$partid.status"})
417: .'</p>';
418:
419: $result .= '<ul>';
420: my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
421: keys(%{$record}));
422: foreach my $grade (sort(@grade)) {
423: my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
424: $result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
425: $dim, $record->{$grade}).
426: '</li>';
427: }
428: $result.='</ul>';
429: return $result;
430: }
431: } elsif ( $response =~ m/(?:numerical|formula)/) {
432: $answer =
433: &Apache::loncommon::format_previous_attempt_value('submission',
434: $answer);
435: }
436: return $answer;
437: }
438:
439: #-- A couple of common js functions
440: sub commonJSfunctions {
441: my $request = shift;
442: $request->print(<<COMMONJSFUNCTIONS);
443: <script type="text/javascript" language="javascript">
444: function radioSelection(radioButton) {
445: var selection=null;
446: if (radioButton.length > 1) {
447: for (var i=0; i<radioButton.length; i++) {
448: if (radioButton[i].checked) {
449: return radioButton[i].value;
450: }
451: }
452: } else {
453: if (radioButton.checked) return radioButton.value;
454: }
455: return selection;
456: }
457:
458: function pullDownSelection(selectOne) {
459: var selection="";
460: if (selectOne.length > 1) {
461: for (var i=0; i<selectOne.length; i++) {
462: if (selectOne[i].selected) {
463: return selectOne[i].value;
464: }
465: }
466: } else {
467: // only one value it must be the selected one
468: return selectOne.value;
469: }
470: }
471: </script>
472: COMMONJSFUNCTIONS
473: }
474:
475: #--- Dumps the class list with usernames,list of sections,
476: #--- section, ids and fullnames for each user.
477: sub getclasslist {
478: my ($getsec,$filterlist,$getgroup) = @_;
479: my @getsec;
480: my @getgroup;
481: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
482: if (!ref($getsec)) {
483: if ($getsec ne '' && $getsec ne 'all') {
484: @getsec=($getsec);
485: }
486: } else {
487: @getsec=@{$getsec};
488: }
489: if (grep(/^all$/,@getsec)) { undef(@getsec); }
490: if (!ref($getgroup)) {
491: if ($getgroup ne '' && $getgroup ne 'all') {
492: @getgroup=($getgroup);
493: }
494: } else {
495: @getgroup=@{$getgroup};
496: }
497: if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
498:
499: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
500: # Bail out if we were unable to get the classlist
501: return if (! defined($classlist));
502: &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
503: #
504: my %sections;
505: my %fullnames;
506: foreach my $student (keys(%$classlist)) {
507: my $end =
508: $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
509: my $start =
510: $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
511: my $id =
512: $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
513: my $section =
514: $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
515: my $fullname =
516: $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
517: my $status =
518: $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
519: my $group =
520: $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
521: # filter students according to status selected
522: if ($filterlist && (!($stu_status =~ /Any/))) {
523: if (!($stu_status =~ $status)) {
524: delete($classlist->{$student});
525: next;
526: }
527: }
528: # filter students according to groups selected
529: my @stu_groups = split(/,/,$group);
530: if (@getgroup) {
531: my $exclude = 1;
532: foreach my $grp (@getgroup) {
533: foreach my $stu_group (@stu_groups) {
534: if ($stu_group eq $grp) {
535: $exclude = 0;
536: }
537: }
538: if (($grp eq 'none') && !$group) {
539: $exclude = 0;
540: }
541: }
542: if ($exclude) {
543: delete($classlist->{$student});
544: }
545: }
546: $section = ($section ne '' ? $section : 'none');
547: if (&canview($section)) {
548: if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
549: $sections{$section}++;
550: if ($classlist->{$student}) {
551: $fullnames{$student}=$fullname;
552: }
553: } else {
554: delete($classlist->{$student});
555: }
556: } else {
557: delete($classlist->{$student});
558: }
559: }
560: my %seen = ();
561: my @sections = sort(keys(%sections));
562: return ($classlist,\@sections,\%fullnames);
563: }
564:
565: sub canmodify {
566: my ($sec)=@_;
567: if ($perm{'mgr'}) {
568: if (!defined($perm{'mgr_section'})) {
569: # can modify whole class
570: return 1;
571: } else {
572: if ($sec eq $perm{'mgr_section'}) {
573: #can modify the requested section
574: return 1;
575: } else {
576: # can't modify the request section
577: return 0;
578: }
579: }
580: }
581: #can't modify
582: return 0;
583: }
584:
585: sub canview {
586: my ($sec)=@_;
587: if ($perm{'vgr'}) {
588: if (!defined($perm{'vgr_section'})) {
589: # can modify whole class
590: return 1;
591: } else {
592: if ($sec eq $perm{'vgr_section'}) {
593: #can modify the requested section
594: return 1;
595: } else {
596: # can't modify the request section
597: return 0;
598: }
599: }
600: }
601: #can't modify
602: return 0;
603: }
604:
605: #--- Retrieve the grade status of a student for all the parts
606: sub student_gradeStatus {
607: my ($symb,$udom,$uname,$partlist) = @_;
608: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
609: my %partstatus = ();
610: foreach (@$partlist) {
611: my ($status,undef) = split(/_/,$record{"resource.$_.solved"},2);
612: $status = 'nothing' if ($status eq '');
613: $partstatus{$_} = $status;
614: my $subkey = "resource.$_.submitted_by";
615: $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
616: }
617: return %partstatus;
618: }
619:
620: # hidden form and javascript that calls the form
621: # Use by verifyscript and viewgrades
622: # Shows a student's view of problem and submission
623: sub jscriptNform {
624: my ($symb) = @_;
625: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
626: my $jscript='<script type="text/javascript" language="javascript">'."\n".
627: ' function viewOneStudent(user,domain) {'."\n".
628: ' document.onestudent.student.value = user;'."\n".
629: ' document.onestudent.userdom.value = domain;'."\n".
630: ' document.onestudent.submit();'."\n".
631: ' }'."\n".
632: '</script>'."\n";
633: $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
634: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
635: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
636: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
637: '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
638: '<input type="hidden" name="command" value="submission" />'."\n".
639: '<input type="hidden" name="student" value="" />'."\n".
640: '<input type="hidden" name="userdom" value="" />'."\n".
641: '</form>'."\n";
642: return $jscript;
643: }
644:
645:
646:
647: # Given the score (as a number [0-1] and the weight) what is the final
648: # point value? This function will round to the nearest tenth, third,
649: # or quarter if one of those is within the tolerance of .00001.
650: sub compute_points {
651: my ($score, $weight) = @_;
652:
653: my $tolerance = .00001;
654: my $points = $score * $weight;
655:
656: # Check for nearness to 1/x.
657: my $check_for_nearness = sub {
658: my ($factor) = @_;
659: my $num = ($points * $factor) + $tolerance;
660: my $floored_num = floor($num);
661: if ($num - $floored_num < 2 * $tolerance * $factor) {
662: return $floored_num / $factor;
663: }
664: return $points;
665: };
666:
667: $points = $check_for_nearness->(10);
668: $points = $check_for_nearness->(3);
669: $points = $check_for_nearness->(4);
670:
671: return $points;
672: }
673:
674: #------------------ End of general use routines --------------------
675:
676: #
677: # Find most similar essay
678: #
679:
680: sub most_similar {
681: my ($uname,$udom,$uessay,$old_essays)=@_;
682:
683: # ignore spaces and punctuation
684:
685: $uessay=~s/\W+/ /gs;
686:
687: # ignore empty submissions (occuring when only files are sent)
688:
689: unless ($uessay=~/\w+/) { return ''; }
690:
691: # these will be returned. Do not care if not at least 50 percent similar
692: my $limit=0.6;
693: my $sname='';
694: my $sdom='';
695: my $scrsid='';
696: my $sessay='';
697: # go through all essays ...
698: foreach my $tkey (keys(%$old_essays)) {
699: my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
700: # ... except the same student
701: next if (($tname eq $uname) && ($tdom eq $udom));
702: my $tessay=$old_essays->{$tkey};
703: $tessay=~s/\W+/ /gs;
704: # String similarity gives up if not even limit
705: my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
706: # Found one
707: if ($tsimilar>$limit) {
708: $limit=$tsimilar;
709: $sname=$tname;
710: $sdom=$tdom;
711: $scrsid=$tcrsid;
712: $sessay=$old_essays->{$tkey};
713: }
714: }
715: if ($limit>0.6) {
716: return ($sname,$sdom,$scrsid,$sessay,$limit);
717: } else {
718: return ('','','','',0);
719: }
720: }
721:
722: #-------------------------------------------------------------------
723:
724: #------------------------------------ Receipt Verification Routines
725: #
726: #--- Check whether a receipt number is valid.---
727: sub verifyreceipt {
728: my $request = shift;
729:
730: my $courseid = $env{'request.course.id'};
731: my $receipt = &Apache::lonnet::recprefix($courseid).'-'.
732: $env{'form.receipt'};
733: $receipt =~ s/[^\-\d]//g;
734: my ($symb) = &get_symb($request);
735:
736: my $title.='<h3><span class="LC_info">Verifying Submission Receipt '.
737: $receipt.'</h3></span>'."\n".
738: '<h4><b>Resource: </b>'.$env{'form.probTitle'}.'</h4><br /><br />'."\n";
739:
740: my ($string,$contents,$matches) = ('','',0);
741: my (undef,undef,$fullname) = &getclasslist('all','0');
742:
743: my $receiptparts=0;
744: if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
745: $env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
746: my $parts=['0'];
747: if ($receiptparts) { ($parts)=&response_type($symb); }
748: foreach (sort
749: {
750: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
751: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
752: }
753: return $a cmp $b;
754: } (keys(%$fullname))) {
755: my ($uname,$udom)=split(/\:/);
756: foreach my $part (@$parts) {
757: if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
758: $contents.='<tr bgcolor="#ffffe6"><td> '."\n".
759: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
760: '\');" target="_self">'.$$fullname{$_}.'</a> </td>'."\n".
761: '<td> '.$uname.' </td>'.
762: '<td> '.$udom.' </td>';
763: if ($receiptparts) {
764: $contents.='<td> '.$part.' </td>';
765: }
766: $contents.='</tr>'."\n";
767:
768: $matches++;
769: }
770: }
771: }
772: if ($matches == 0) {
773: $string = $title.'No match found for the above receipt.';
774: } else {
775: $string = &jscriptNform($symb).$title.
776: 'The above receipt matches the following student'.
777: ($matches <= 1 ? '.' : 's.')."\n".
778: '<table border="0"><tr><td bgcolor="#777777">'."\n".
779: '<table border="0"><tr bgcolor="#e6ffff">'."\n".
780: '<td><b> Fullname </b></td>'."\n".
781: '<td><b> Username </b></td>'."\n".
782: '<td><b> Domain </b></td>';
783: if ($receiptparts) {
784: $string.='<td> Problem Part </td>';
785: }
786: $string.='</tr>'."\n".$contents.
787: '</table></td></tr></table>'."\n";
788: }
789: return $string.&show_grading_menu_form($symb);
790: }
791:
792: #--- This is called by a number of programs.
793: #--- Called from the Grading Menu - View/Grade an individual student
794: #--- Also called directly when one clicks on the subm button
795: # on the problem page.
796: sub listStudents {
797: my ($request) = shift;
798:
799: my ($symb) = &get_symb($request);
800: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
801: my $cnum = $env{"course.$env{'request.course.id'}.num"};
802: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
803: my $getgroup = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
804: my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
805: my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
806: $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ?
807: &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
808:
809: my $result='<h3><span class="LC_info"> '.
810: &mt($viewgrade.' Submissions for a Student or a Group of Students')
811: .'</span></h3>';
812:
813: my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
814:
815: my %lt = ( 'multiple' =>
816: "Please select a student or group of students before clicking on the Next button.",
817: 'single' =>
818: "Please select the student before clicking on the Next button.",
819: );
820: %lt = &Apache::lonlocal::texthash(%lt);
821: $request->print(<<LISTJAVASCRIPT);
822: <script type="text/javascript" language="javascript">
823: function checkSelect(checkBox) {
824: var ctr=0;
825: var sense="";
826: if (checkBox.length > 1) {
827: for (var i=0; i<checkBox.length; i++) {
828: if (checkBox[i].checked) {
829: ctr++;
830: }
831: }
832: sense = '$lt{'multiple'}';
833: } else {
834: if (checkBox.checked) {
835: ctr = 1;
836: }
837: sense = '$lt{'single'}';
838: }
839: if (ctr == 0) {
840: alert(sense);
841: return false;
842: }
843: document.gradesub.submit();
844: }
845:
846: function reLoadList(formname) {
847: if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
848: formname.command.value = 'submission';
849: formname.submit();
850: }
851: </script>
852: LISTJAVASCRIPT
853:
854: &commonJSfunctions($request);
855: $request->print($result);
856:
857: my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
858: my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
859: my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
860: "\n".$table;
861:
862: $gradeTable .=
863: ' '.
864: &mt('<b>View Problem Text: </b>[_1]',
865: '<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
866: '<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n".
867: '<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label>').'<br />'."\n";
868: $gradeTable .=
869: ' '.
870: &mt('<b>View Answer: </b>[_1]',
871: '<label><input type="radio" name="vAns" value="no" /> '.&mt('no').' </label>'."\n".
872: '<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n".
873: '<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label>').'<br />'."\n";
874:
875: my $submission_options;
876: if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
877: $submission_options.=
878: '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
879: }
880: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
881: my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
882: $env{'form.Status'} = $saveStatus;
883: $submission_options.=
884: '<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.&mt('last submission only').' </label>'."\n".
885: '<label><input type="radio" name="lastSub" value="last" /> '.&mt('last submission & parts info').' </label>'."\n".
886: '<label><input type="radio" name="lastSub" value="datesub" /> '.&mt('by dates and submissions').' </label>'."\n".
887: '<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').'</label>';
888: $gradeTable .=
889: ' '.
890: &mt('<b>Submissions: </b>[_1]',$submission_options).'<br />'."\n";
891:
892: $gradeTable .=
893: ' '.
894: &mt('<b>Grading Increments:</b> [_1]',
895: '<select name="increment">'.
896: '<option value="1">'.&mt('Whole Points').'</option>'.
897: '<option value=".5">'.&mt('Half Points').'</option>'.
898: '<option value=".25">'.&mt('Quarter Points').'</option>'.
899: '<option value=".1">'.&mt('Tenths of a Point').'</option>'.
900: '</select>');
901:
902: $gradeTable .=
903: &build_section_inputs().
904: '<input type="hidden" name="submitonly" value="'.$submitonly.'" />'."\n".
905: '<input type="hidden" name="handgrade" value="'.$env{'form.handgrade'}.'" /><br />'."\n".
906: '<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
907: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
908: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
909: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
910: '<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
911:
912: if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
913: $gradeTable.='<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
914: } else {
915: $gradeTable.=&mt('<b>Student Status:</b> [_1]',
916: &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);')).'<br />';
917: }
918:
919: $gradeTable.=&mt('To '.lc($viewgrade).' a submission or a group of submissions, click on the check box(es) '.
920: 'next to the student\'s name(s). Then click on the Next button.').'<br />'."\n".
921: '<input type="hidden" name="command" value="processGroup" />'."\n";
922:
923: # checkall buttons
924: $gradeTable.=&check_script('gradesub', 'stuinfo');
925: $gradeTable.='<input type="button" '."\n".
926: 'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
927: 'value="'.&mt('Next->').'" /> <br />'."\n";
928: $gradeTable.=&check_buttons();
929: $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />'.&mt('Check For Plagiarism').'</label>';
930: my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
931: $gradeTable.= &Apache::loncommon::start_data_table().
932: &Apache::loncommon::start_data_table_header_row();
933: my $loop = 0;
934: while ($loop < 2) {
935: $gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
936: '<th>'.&nameUserString('header').' '.&mt('Section/Group').'</th>';
937: if ($env{'form.showgrading'} eq 'yes'
938: && $submitonly ne 'queued'
939: && $submitonly ne 'all') {
940: foreach my $part (sort(@$partlist)) {
941: my $display_part=
942: &get_display_part((split(/_/,$part))[0],$symb);
943: $gradeTable.=
944: '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
945: }
946: } elsif ($submitonly eq 'queued') {
947: $gradeTable.='<th>'.&mt('Queue Status').' </th>';
948: }
949: $loop++;
950: # $gradeTable.='<td></td>' if ($loop%2 ==1);
951: }
952: $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
953:
954: my $ctr = 0;
955: foreach my $student (sort
956: {
957: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
958: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
959: }
960: return $a cmp $b;
961: }
962: (keys(%$fullname))) {
963: my ($uname,$udom) = split(/:/,$student);
964:
965: my %status = ();
966:
967: if ($submitonly eq 'queued') {
968: my %queue_status =
969: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
970: $udom,$uname);
971: next if (!defined($queue_status{'gradingqueue'}));
972: $status{'gradingqueue'} = $queue_status{'gradingqueue'};
973: }
974:
975: if ($env{'form.showgrading'} eq 'yes'
976: && $submitonly ne 'queued'
977: && $submitonly ne 'all') {
978: (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
979: my $submitted = 0;
980: my $graded = 0;
981: my $incorrect = 0;
982: foreach (keys(%status)) {
983: $submitted = 1 if ($status{$_} ne 'nothing');
984: $graded = 1 if ($status{$_} =~ /^ungraded/);
985: $incorrect = 1 if ($status{$_} =~ /^incorrect/);
986:
987: my ($foo,$partid,$foo1) = split(/\./,$_);
988: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
989: $submitted = 0;
990: my ($part)=split(/\./,$partid);
991: $gradeTable.='<input type="hidden" name="'.
992: $student.':'.$part.':submitted_by" value="'.
993: $status{'resource.'.$partid.'.submitted_by'}.'" />';
994: }
995: }
996:
997: next if (!$submitted && ($submitonly eq 'yes' ||
998: $submitonly eq 'incorrect' ||
999: $submitonly eq 'graded'));
1000: next if (!$graded && ($submitonly eq 'graded'));
1001: next if (!$incorrect && $submitonly eq 'incorrect');
1002: }
1003:
1004: $ctr++;
1005: my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1006: my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1007: if ( $perm{'vgr'} eq 'F' ) {
1008: if ($ctr%2 ==1) {
1009: $gradeTable.= &Apache::loncommon::start_data_table_row();
1010: }
1011: $gradeTable.='<td align="right">'.$ctr.' </td>'.
1012: '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
1013: $student.':'.$$fullname{$student}.':::SECTION'.$section.
1014: ') " /> </label></td>'."\n".'<td>'.
1015: &nameUserString(undef,$$fullname{$student},$uname,$udom).
1016: ' '.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1017:
1018: if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1019: foreach (sort keys(%status)) {
1020: next if ($_ =~ /^resource.*?submitted_by$/);
1021: $gradeTable.='<td align="center"> '.&mt($status{$_}).' </td>'."\n";
1022: }
1023: }
1024: # $gradeTable.='<td></td>' if ($ctr%2 ==1);
1025: if ($ctr%2 ==0) {
1026: $gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
1027: }
1028: }
1029: }
1030: if ($ctr%2 ==1) {
1031: $gradeTable.='<td> </td><td> </td><td> </td>';
1032: if ($env{'form.showgrading'} eq 'yes'
1033: && $submitonly ne 'queued'
1034: && $submitonly ne 'all') {
1035: foreach (@$partlist) {
1036: $gradeTable.='<td> </td>';
1037: }
1038: } elsif ($submitonly eq 'queued') {
1039: $gradeTable.='<td> </td>';
1040: }
1041: $gradeTable.=&Apache::loncommon::end_data_table_row();
1042: }
1043:
1044: $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1045: '<input type="button" '.
1046: 'onClick="javascript:checkSelect(this.form.stuinfo);" '.
1047: 'value="'.&mt('Next->').'" /></form>'."\n";
1048: if ($ctr == 0) {
1049: my $num_students=(scalar(keys(%$fullname)));
1050: if ($num_students eq 0) {
1051: $gradeTable='<br /> <span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1052: } else {
1053: my $submissions='submissions';
1054: if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
1055: if ($submitonly eq 'graded' ) { $submissions = 'ungraded submissions'; }
1056: if ($submitonly eq 'queued' ) { $submissions = 'queued submissions'; }
1057: $gradeTable='<br /> <span class="LC_warning">'.
1058: &mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
1059: $num_students).
1060: '</span><br />';
1061: }
1062: } elsif ($ctr == 1) {
1063: $gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1064: }
1065: $gradeTable.=&show_grading_menu_form($symb);
1066: $request->print($gradeTable);
1067: return '';
1068: }
1069:
1070: #---- Called from the listStudents routine
1071:
1072: sub check_script {
1073: my ($form, $type)=@_;
1074: my $chkallscript='<script type="text/javascript">
1075: function checkall() {
1076: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1077: ele = document.forms.'.$form.'.elements[i];
1078: if (ele.name == "'.$type.'") {
1079: document.forms.'.$form.'.elements[i].checked=true;
1080: }
1081: }
1082: }
1083:
1084: function checksec() {
1085: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1086: ele = document.forms.'.$form.'.elements[i];
1087: string = document.forms.'.$form.'.chksec.value;
1088: if
1089: (ele.value.indexOf(":::SECTION"+string)>0) {
1090: document.forms.'.$form.'.elements[i].checked=true;
1091: }
1092: }
1093: }
1094:
1095:
1096: function uncheckall() {
1097: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1098: ele = document.forms.'.$form.'.elements[i];
1099: if (ele.name == "'.$type.'") {
1100: document.forms.'.$form.'.elements[i].checked=false;
1101: }
1102: }
1103: }
1104:
1105: </script>'."\n";
1106: return $chkallscript;
1107: }
1108:
1109: sub check_buttons {
1110: my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
1111: $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" /> ';
1112: $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1113: $buttons.='<input type="text" size="5" name="chksec" /> ';
1114: return $buttons;
1115: }
1116:
1117: # Displays the submissions for one student or a group of students
1118: sub processGroup {
1119: my ($request) = shift;
1120: my $ctr = 0;
1121: my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1122: my $total = scalar(@stuchecked)-1;
1123:
1124: foreach my $student (@stuchecked) {
1125: my ($uname,$udom,$fullname) = split(/:/,$student);
1126: $env{'form.student'} = $uname;
1127: $env{'form.userdom'} = $udom;
1128: $env{'form.fullname'} = $fullname;
1129: &submission($request,$ctr,$total);
1130: $ctr++;
1131: }
1132: return '';
1133: }
1134:
1135: #------------------------------------------------------------------------------------
1136: #
1137: #-------------------------- Next few routines handles grading by student, essentially
1138: # handles essay response type problem/part
1139: #
1140: #--- Javascript to handle the submission page functionality ---
1141: sub sub_page_js {
1142: my $request = shift;
1143: $request->print(<<SUBJAVASCRIPT);
1144: <script type="text/javascript" language="javascript">
1145: function updateRadio(formname,id,weight) {
1146: var gradeBox = formname["GD_BOX"+id];
1147: var radioButton = formname["RADVAL"+id];
1148: var oldpts = formname["oldpts"+id].value;
1149: var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1150: gradeBox.value = pts;
1151: var resetbox = false;
1152: if (isNaN(pts) || pts < 0) {
1153: alert("A number equal or greater than 0 is expected. Entered value = "+pts);
1154: for (var i=0; i<radioButton.length; i++) {
1155: if (radioButton[i].checked) {
1156: gradeBox.value = i;
1157: resetbox = true;
1158: }
1159: }
1160: if (!resetbox) {
1161: formtextbox.value = "";
1162: }
1163: return;
1164: }
1165:
1166: if (pts > weight) {
1167: var resp = confirm("You entered a value ("+pts+
1168: ") greater than the weight for the part. Accept?");
1169: if (resp == false) {
1170: gradeBox.value = oldpts;
1171: return;
1172: }
1173: }
1174:
1175: for (var i=0; i<radioButton.length; i++) {
1176: radioButton[i].checked=false;
1177: if (pts == i && pts != "") {
1178: radioButton[i].checked=true;
1179: }
1180: }
1181: updateSelect(formname,id);
1182: formname["stores"+id].value = "0";
1183: }
1184:
1185: function writeBox(formname,id,pts) {
1186: var gradeBox = formname["GD_BOX"+id];
1187: if (checkSolved(formname,id) == 'update') {
1188: gradeBox.value = pts;
1189: } else {
1190: var oldpts = formname["oldpts"+id].value;
1191: gradeBox.value = oldpts;
1192: var radioButton = formname["RADVAL"+id];
1193: for (var i=0; i<radioButton.length; i++) {
1194: radioButton[i].checked=false;
1195: if (i == oldpts) {
1196: radioButton[i].checked=true;
1197: }
1198: }
1199: }
1200: formname["stores"+id].value = "0";
1201: updateSelect(formname,id);
1202: return;
1203: }
1204:
1205: function clearRadBox(formname,id) {
1206: if (checkSolved(formname,id) == 'noupdate') {
1207: updateSelect(formname,id);
1208: return;
1209: }
1210: gradeSelect = formname["GD_SEL"+id];
1211: for (var i=0; i<gradeSelect.length; i++) {
1212: if (gradeSelect[i].selected) {
1213: var selectx=i;
1214: }
1215: }
1216: var stores = formname["stores"+id];
1217: if (selectx == stores.value) { return };
1218: var gradeBox = formname["GD_BOX"+id];
1219: gradeBox.value = "";
1220: var radioButton = formname["RADVAL"+id];
1221: for (var i=0; i<radioButton.length; i++) {
1222: radioButton[i].checked=false;
1223: }
1224: stores.value = selectx;
1225: }
1226:
1227: function checkSolved(formname,id) {
1228: if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1229: var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
1230: if (!reply) {return "noupdate";}
1231: formname.overRideScore.value = 'yes';
1232: }
1233: return "update";
1234: }
1235:
1236: function updateSelect(formname,id) {
1237: formname["GD_SEL"+id][0].selected = true;
1238: return;
1239: }
1240:
1241: //=========== Check that a point is assigned for all the parts ============
1242: function checksubmit(formname,val,total,parttot) {
1243: formname.gradeOpt.value = val;
1244: if (val == "Save & Next") {
1245: for (i=0;i<=total;i++) {
1246: for (j=0;j<parttot;j++) {
1247: var partid = formname["partid"+i+"_"+j].value;
1248: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1249: var points = formname["GD_BOX"+i+"_"+partid].value;
1250: if (points == "") {
1251: var name = formname["name"+i].value;
1252: var studentID = (name != '' ? name : formname["unamedom"+i].value);
1253: var resp = confirm("You did not assign a score for "+studentID+
1254: ", part "+partid+". Continue?");
1255: if (resp == false) {
1256: formname["GD_BOX"+i+"_"+partid].focus();
1257: return false;
1258: }
1259: }
1260: }
1261:
1262: }
1263: }
1264:
1265: }
1266: if (val == "Grade Student") {
1267: formname.showgrading.value = "yes";
1268: if (formname.Status.value == "") {
1269: formname.Status.value = "Active";
1270: }
1271: formname.studentNo.value = total;
1272: }
1273: formname.submit();
1274: }
1275:
1276: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
1277: function checkSubmitPage(formname,total) {
1278: noscore = new Array(100);
1279: var ptr = 0;
1280: for (i=1;i<total;i++) {
1281: var partid = formname["q_"+i].value;
1282: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1283: var points = formname["GD_BOX"+i+"_"+partid].value;
1284: var status = formname["solved"+i+"_"+partid].value;
1285: if (points == "" && status != "correct_by_student") {
1286: noscore[ptr] = i;
1287: ptr++;
1288: }
1289: }
1290: }
1291: if (ptr != 0) {
1292: var sense = ptr == 1 ? ": " : "s: ";
1293: var prolist = "";
1294: if (ptr == 1) {
1295: prolist = noscore[0];
1296: } else {
1297: var i = 0;
1298: while (i < ptr-1) {
1299: prolist += noscore[i]+", ";
1300: i++;
1301: }
1302: prolist += "and "+noscore[i];
1303: }
1304: var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
1305: if (resp == false) {
1306: return false;
1307: }
1308: }
1309:
1310: formname.submit();
1311: }
1312: </script>
1313: SUBJAVASCRIPT
1314: }
1315:
1316: #--- javascript for essay type problem --
1317: sub sub_page_kw_js {
1318: my $request = shift;
1319: my $iconpath = $request->dir_config('lonIconsURL');
1320: &commonJSfunctions($request);
1321:
1322: my $inner_js_msg_central=<<INNERJS;
1323: <script text="text/javascript">
1324: function checkInput() {
1325: opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
1326: var nmsg = opener.document.SCORE.savemsgN.value;
1327: var usrctr = document.msgcenter.usrctr.value;
1328: var newval = opener.document.SCORE["newmsg"+usrctr];
1329: newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
1330:
1331: var msgchk = "";
1332: if (document.msgcenter.subchk.checked) {
1333: msgchk = "msgsub,";
1334: }
1335: var includemsg = 0;
1336: for (var i=1; i<=nmsg; i++) {
1337: var opnmsg = opener.document.SCORE["savemsg"+i];
1338: var frmmsg = document.msgcenter["msg"+i];
1339: opnmsg.value = opener.checkEntities(frmmsg.value);
1340: var showflg = opener.document.SCORE["shownOnce"+i];
1341: showflg.value = "1";
1342: var chkbox = document.msgcenter["msgn"+i];
1343: if (chkbox.checked) {
1344: msgchk += "savemsg"+i+",";
1345: includemsg = 1;
1346: }
1347: }
1348: if (document.msgcenter.newmsgchk.checked) {
1349: msgchk += "newmsg"+usrctr;
1350: includemsg = 1;
1351: }
1352: imgformname = opener.document.SCORE["mailicon"+usrctr];
1353: imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
1354: var includemsg = opener.document.SCORE["includemsg"+usrctr];
1355: includemsg.value = msgchk;
1356:
1357: self.close()
1358:
1359: }
1360: </script>
1361: INNERJS
1362:
1363: my $inner_js_highlight_central=<<INNERJS;
1364: <script type="text/javascript">
1365: function updateChoice(flag) {
1366: opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
1367: opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
1368: opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
1369: opener.document.SCORE.refresh.value = "on";
1370: if (opener.document.SCORE.keywords.value!=""){
1371: opener.document.SCORE.submit();
1372: }
1373: self.close()
1374: }
1375: </script>
1376: INNERJS
1377:
1378: my $start_page_msg_central =
1379: &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
1380: {'js_ready' => 1,
1381: 'only_body' => 1,
1382: 'bgcolor' =>'#FFFFFF',});
1383: my $end_page_msg_central =
1384: &Apache::loncommon::end_page({'js_ready' => 1});
1385:
1386:
1387: my $start_page_highlight_central =
1388: &Apache::loncommon::start_page('Highlight Central',
1389: $inner_js_highlight_central,
1390: {'js_ready' => 1,
1391: 'only_body' => 1,
1392: 'bgcolor' =>'#FFFFFF',});
1393: my $end_page_highlight_central =
1394: &Apache::loncommon::end_page({'js_ready' => 1});
1395:
1396: my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1397: $docopen=~s/^document\.//;
1398: $request->print(<<SUBJAVASCRIPT);
1399: <script type="text/javascript" language="javascript">
1400:
1401: //===================== Show list of keywords ====================
1402: function keywords(formname) {
1403: var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1404: if (nret==null) return;
1405: formname.keywords.value = nret;
1406:
1407: if (formname.keywords.value != "") {
1408: formname.refresh.value = "on";
1409: formname.submit();
1410: }
1411: return;
1412: }
1413:
1414: //===================== Script to view submitted by ==================
1415: function viewSubmitter(submitter) {
1416: document.SCORE.refresh.value = "on";
1417: document.SCORE.NCT.value = "1";
1418: document.SCORE.unamedom0.value = submitter;
1419: document.SCORE.submit();
1420: return;
1421: }
1422:
1423: //===================== Script to add keyword(s) ==================
1424: function getSel() {
1425: if (document.getSelection) txt = document.getSelection();
1426: else if (document.selection) txt = document.selection.createRange().text;
1427: else return;
1428: var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
1429: if (cleantxt=="") {
1430: alert("Please select a word or group of words from document and then click this link.");
1431: return;
1432: }
1433: var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
1434: if (nret==null) return;
1435: document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1436: if (document.SCORE.keywords.value != "") {
1437: document.SCORE.refresh.value = "on";
1438: document.SCORE.submit();
1439: }
1440: return;
1441: }
1442:
1443: //====================== Script for composing message ==============
1444: // preload images
1445: img1 = new Image();
1446: img1.src = "$iconpath/mailbkgrd.gif";
1447: img2 = new Image();
1448: img2.src = "$iconpath/mailto.gif";
1449:
1450: function msgCenter(msgform,usrctr,fullname) {
1451: var Nmsg = msgform.savemsgN.value;
1452: savedMsgHeader(Nmsg,usrctr,fullname);
1453: var subject = msgform.msgsub.value;
1454: var msgchk = document.SCORE["includemsg"+usrctr].value;
1455: re = /msgsub/;
1456: var shwsel = "";
1457: if (re.test(msgchk)) { shwsel = "checked" }
1458: subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
1459: displaySubject(checkEntities(subject),shwsel);
1460: for (var i=1; i<=Nmsg; i++) {
1461: var testmsg = "savemsg"+i+",";
1462: re = new RegExp(testmsg,"g");
1463: shwsel = "";
1464: if (re.test(msgchk)) { shwsel = "checked" }
1465: var message = document.SCORE["savemsg"+i].value;
1466: message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1467: displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
1468: //any < is already converted to <, etc. However, only once!!
1469: }
1470: newmsg = document.SCORE["newmsg"+usrctr].value;
1471: shwsel = "";
1472: re = /newmsg/;
1473: if (re.test(msgchk)) { shwsel = "checked" }
1474: newMsg(newmsg,shwsel);
1475: msgTail();
1476: return;
1477: }
1478:
1479: function checkEntities(strx) {
1480: if (strx.length == 0) return strx;
1481: var orgStr = ["&", "<", ">", '"'];
1482: var newStr = ["&", "<", ">", """];
1483: var counter = 0;
1484: while (counter < 4) {
1485: strx = strReplace(strx,orgStr[counter],newStr[counter]);
1486: counter++;
1487: }
1488: return strx;
1489: }
1490:
1491: function strReplace(strx, orgStr, newStr) {
1492: return strx.split(orgStr).join(newStr);
1493: }
1494:
1495: function savedMsgHeader(Nmsg,usrctr,fullname) {
1496: var height = 70*Nmsg+250;
1497: var scrollbar = "no";
1498: if (height > 600) {
1499: height = 600;
1500: scrollbar = "yes";
1501: }
1502: var xpos = (screen.width-600)/2;
1503: xpos = (xpos < 0) ? '0' : xpos;
1504: var ypos = (screen.height-height)/2-30;
1505: ypos = (ypos < 0) ? '0' : ypos;
1506:
1507: pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1508: pWin.focus();
1509: pDoc = pWin.document;
1510: pDoc.$docopen;
1511: pDoc.write('$start_page_msg_central');
1512:
1513: pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
1514: pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1515: pDoc.write("<h3><span class=\\"LC_info\\"> Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
1516:
1517: pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
1518: pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
1519: pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
1520: }
1521: function displaySubject(msg,shwsel) {
1522: pDoc = pWin.document;
1523: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1524: pDoc.write("<td>Subject<\\/td>");
1525: pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1526: pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1527: }
1528:
1529: function displaySavedMsg(ctr,msg,shwsel) {
1530: pDoc = pWin.document;
1531: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1532: pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
1533: pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1534: pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1535: }
1536:
1537: function newMsg(newmsg,shwsel) {
1538: pDoc = pWin.document;
1539: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1540: pDoc.write("<td align=\\"center\\">New<\\/td>");
1541: pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1542: pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1543: }
1544:
1545: function msgTail() {
1546: pDoc = pWin.document;
1547: pDoc.write("<\\/table>");
1548: pDoc.write("<\\/td><\\/tr><\\/table> ");
1549: pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\"> ");
1550: pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1551: pDoc.write("<\\/form>");
1552: pDoc.write('$end_page_msg_central');
1553: pDoc.close();
1554: }
1555:
1556: //====================== Script for keyword highlight options ==============
1557: function kwhighlight() {
1558: var kwclr = document.SCORE.kwclr.value;
1559: var kwsize = document.SCORE.kwsize.value;
1560: var kwstyle = document.SCORE.kwstyle.value;
1561: var redsel = "";
1562: var grnsel = "";
1563: var blusel = "";
1564: if (kwclr=="red") {var redsel="checked"};
1565: if (kwclr=="green") {var grnsel="checked"};
1566: if (kwclr=="blue") {var blusel="checked"};
1567: var sznsel = "";
1568: var sz1sel = "";
1569: var sz2sel = "";
1570: if (kwsize=="0") {var sznsel="checked"};
1571: if (kwsize=="+1") {var sz1sel="checked"};
1572: if (kwsize=="+2") {var sz2sel="checked"};
1573: var synsel = "";
1574: var syisel = "";
1575: var sybsel = "";
1576: if (kwstyle=="") {var synsel="checked"};
1577: if (kwstyle=="<i>") {var syisel="checked"};
1578: if (kwstyle=="<b>") {var sybsel="checked"};
1579: highlightCentral();
1580: highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
1581: highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
1582: highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
1583: highlightend();
1584: return;
1585: }
1586:
1587: function highlightCentral() {
1588: // if (window.hwdWin) window.hwdWin.close();
1589: var xpos = (screen.width-400)/2;
1590: xpos = (xpos < 0) ? '0' : xpos;
1591: var ypos = (screen.height-330)/2-30;
1592: ypos = (ypos < 0) ? '0' : ypos;
1593:
1594: hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1595: hwdWin.focus();
1596: var hDoc = hwdWin.document;
1597: hDoc.$docopen;
1598: hDoc.write('$start_page_highlight_central');
1599: hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1600: hDoc.write("<h3><span class=\\"LC_info\\"> Keyword Highlight Options<\\/span><\\/h3><br /><br />");
1601:
1602: hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
1603: hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
1604: hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
1605: }
1606:
1607: function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) {
1608: var hDoc = hwdWin.document;
1609: hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1610: hDoc.write("<td align=\\"left\\">");
1611: hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+"> "+clrtxt+"<\\/td>");
1612: hDoc.write("<td align=\\"left\\">");
1613: hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+"> "+sztxt+"<\\/td>");
1614: hDoc.write("<td align=\\"left\\">");
1615: hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+"> "+sytxt+"<\\/td>");
1616: hDoc.write("<\\/tr>");
1617: }
1618:
1619: function highlightend() {
1620: var hDoc = hwdWin.document;
1621: hDoc.write("<\\/table>");
1622: hDoc.write("<\\/td><\\/tr><\\/table> ");
1623: hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\"> ");
1624: hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1625: hDoc.write("<\\/form>");
1626: hDoc.write('$end_page_highlight_central');
1627: hDoc.close();
1628: }
1629:
1630: </script>
1631: SUBJAVASCRIPT
1632: }
1633:
1634: sub get_increment {
1635: my $increment = $env{'form.increment'};
1636: if ($increment != 1 && $increment != .5 && $increment != .25 &&
1637: $increment != .1) {
1638: $increment = 1;
1639: }
1640: return $increment;
1641: }
1642:
1643: #--- displays the grading box, used in essay type problem and grading by page/sequence
1644: sub gradeBox {
1645: my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1646: my $checkIcon = '<img alt="'.&mt('Check Mark').
1647: '" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1648: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1649: my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)')
1650: : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1651: $wgt = ($wgt > 0 ? $wgt : '1');
1652: my $score = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1653: '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1654: my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1655: my $display_part= &get_display_part($partid,$symb);
1656: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
1657: [$partid]);
1658: my $aggtries = $$record{'resource.'.$partid.'.tries'};
1659: if ($last_resets{$partid}) {
1660: $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
1661: }
1662: $result.='<table border="0"><tr>';
1663: my $ctr = 0;
1664: my $thisweight = 0;
1665: my $increment = &get_increment();
1666:
1667: my $radio.='<table border="0"><tr>'."\n"; # display radio buttons in a nice table 10 across
1668: while ($thisweight<=$wgt) {
1669: $radio.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1670: 'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1671: $thisweight.')" value="'.$thisweight.'" '.
1672: ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1673: $radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1674: $thisweight += $increment;
1675: $ctr++;
1676: }
1677: $radio.='</tr></table>';
1678:
1679: my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1680: ($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1681: 'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1682: $wgt.')" /></td>'."\n";
1683: $line.='<td>/'.$wgt.' '.$wgtmsg.
1684: ($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? ' '.$checkIcon : '').
1685: ' </td><td>'."\n";
1686: $line.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
1687: 'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1688: if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1689: $line.='<option></option>'.
1690: '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1691: } else {
1692: $line.='<option selected="selected"></option>'.
1693: '<option value="excused" >'.&mt('excused').'</option>';
1694: }
1695: $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
1696:
1697:
1698: $result .=
1699: &mt('<td><b>Part:</b></td><td>[_1]</td><td><b>Points:</b></td><td>[_2]</td><td>or</td><td>[_3]</td>',$display_part,$radio,$line);
1700:
1701:
1702: $result.='</tr></table>'."\n";
1703: $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
1704: '<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
1705: '<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1706: $$record{'resource.'.$partid.'.solved'}.'" />'."\n".
1707: '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
1708: $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
1709: '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
1710: $aggtries.'" />'."\n";
1711: $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
1712: return $result;
1713: }
1714:
1715: sub handback_box {
1716: my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
1717: my ($partlist,$handgrade,$responseType) = &response_type($symb);
1718: my (@respids);
1719: my @part_response_id = &flatten_responseType($responseType);
1720: foreach my $part_response_id (@part_response_id) {
1721: my ($part,$resp) = @{ $part_response_id };
1722: if ($part eq $partid) {
1723: push(@respids,$resp);
1724: }
1725: }
1726: my $result;
1727: foreach my $respid (@respids) {
1728: my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
1729: my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
1730: next if (!@$files);
1731: my $file_counter = 1;
1732: foreach my $file (@$files) {
1733: if ($file =~ /\/portfolio\//) {
1734: my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1735: my ($name,$version,$ext) = &file_name_version_ext($file_disp);
1736: $file_disp = "$name.$ext";
1737: $file = $file_path.$file_disp;
1738: $result.=&mt('Return commented version of [_1] to student.',
1739: '<span class="LC_filename">'.$file_disp.'</span>');
1740: $result.='<input type="file" name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1741: $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1742: $result.='('.&mt('File will be uploaded when you click on Save & Next below.').')<br />';
1743: $file_counter++;
1744: }
1745: }
1746: }
1747: return $result;
1748: }
1749:
1750: sub show_problem {
1751: my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1752: my $rendered;
1753: my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1754: &Apache::lonxml::remember_problem_counter();
1755: if ($mode eq 'both' or $mode eq 'text') {
1756: $rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1757: $env{'request.course.id'},
1758: undef,\%form);
1759: }
1760: if ($removeform) {
1761: $rendered=~s|<form(.*?)>||g;
1762: $rendered=~s|</form>||g;
1763: $rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1764: }
1765: my $companswer;
1766: if ($mode eq 'both' or $mode eq 'answer') {
1767: &Apache::lonxml::restore_problem_counter();
1768: $companswer=
1769: &Apache::loncommon::get_student_answers($symb,$uname,$udom,
1770: $env{'request.course.id'},
1771: %form);
1772: }
1773: if ($removeform) {
1774: $companswer=~s|<form(.*?)>||g;
1775: $companswer=~s|</form>||g;
1776: $companswer=~s|name="submit"|name="would_have_been_submit"|g;
1777: }
1778: $rendered=
1779: '<div class="LC_grade_show_problem_header">'.
1780: &mt('View of the problem').
1781: '</div><div class="LC_grade_show_problem_problem">'.
1782: $rendered.
1783: '</div>';
1784: $companswer=
1785: '<div class="LC_grade_show_problem_header">'.
1786: &mt('Correct answer').
1787: '</div><div class="LC_grade_show_problem_problem">'.
1788: $companswer.
1789: '</div>';
1790: my $result;
1791: if ($mode eq 'both') {
1792: $result=$rendered.$companswer;
1793: } elsif ($mode eq 'text') {
1794: $result=$rendered;
1795: } elsif ($mode eq 'answer') {
1796: $result=$companswer;
1797: }
1798: $result='<div class="LC_grade_show_problem">'.$result.'</div>';
1799: return $result;
1800: }
1801:
1802: sub files_exist {
1803: my ($r, $symb) = @_;
1804: my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1805:
1806: foreach my $student (@students) {
1807: my ($uname,$udom,$fullname) = split(/:/,$student);
1808: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
1809: $udom,$uname);
1810: my ($string,$timestamp)= &get_last_submission(\%record);
1811: foreach my $submission (@$string) {
1812: my ($partid,$respid) =
1813: ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1814: my $files=&get_submitted_files($udom,$uname,$partid,$respid,
1815: \%record);
1816: return 1 if (@$files);
1817: }
1818: }
1819: return 0;
1820: }
1821:
1822: sub download_all_link {
1823: my ($r,$symb) = @_;
1824: my $all_students =
1825: join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
1826:
1827: my $parts =
1828: join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
1829:
1830: my $identifier = &Apache::loncommon::get_cgi_id();
1831: &Apache::lonnet::appenv('cgi.'.$identifier.'.students' => $all_students,
1832: 'cgi.'.$identifier.'.symb' => $symb,
1833: 'cgi.'.$identifier.'.parts' => $parts,);
1834: $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
1835: &mt('Download All Submitted Documents').'</a>');
1836: return
1837: }
1838:
1839: sub build_section_inputs {
1840: my $section_inputs;
1841: if ($env{'form.section'} eq '') {
1842: $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
1843: } else {
1844: my @sections = &Apache::loncommon::get_env_multiple('form.section');
1845: foreach my $section (@sections) {
1846: $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
1847: }
1848: }
1849: return $section_inputs;
1850: }
1851:
1852: # --------------------------- show submissions of a student, option to grade
1853: sub submission {
1854: my ($request,$counter,$total) = @_;
1855: my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
1856: $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
1857: my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
1858: $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1859: my $symb = &get_symb($request);
1860: if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1861:
1862: if (!&canview($usec)) {
1863: $request->print('<span class="LC_warning">Unable to view requested student.('.
1864: $uname.':'.$udom.' in section '.$usec.' in course id '.
1865: $env{'request.course.id'}.')</span>');
1866: $request->print(&show_grading_menu_form($symb));
1867: return;
1868: }
1869:
1870: if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
1871: if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
1872: if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
1873: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1874: my $checkIcon = '<img alt="'.&mt('Check Mark').
1875: '" src="'.$request->dir_config('lonIconsURL').
1876: '/check.gif" height="16" border="0" />';
1877:
1878: my %old_essays;
1879: # header info
1880: if ($counter == 0) {
1881: &sub_page_js($request);
1882: &sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
1883: $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ?
1884: &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1885: if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1886: &download_all_link($request, $symb);
1887: }
1888: $request->print('<h3> <span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
1889: '<h4> '.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
1890:
1891: # option to display problem, only once else it cause problems
1892: # with the form later since the problem has a form.
1893: if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1894: my $mode;
1895: if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1896: $mode='both';
1897: } elsif ($env{'form.vProb'} eq 'yes') {
1898: $mode='text';
1899: } elsif ($env{'form.vAns'} eq 'yes') {
1900: $mode='answer';
1901: }
1902: &Apache::lonxml::clear_problem_counter();
1903: $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1904: }
1905:
1906: # kwclr is the only variable that is guaranteed to be non blank
1907: # if this subroutine has been called once.
1908: my %keyhash = ();
1909: if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1910: %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1911: $env{'course.'.$env{'request.course.id'}.'.domain'},
1912: $env{'course.'.$env{'request.course.id'}.'.num'});
1913:
1914: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1915: $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
1916: $env{'form.kwclr'} = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
1917: $env{'form.kwsize'} = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
1918: $env{'form.kwstyle'} = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
1919: $env{'form.msgsub'} = $keyhash{$symb.'_subject'} ne '' ?
1920: $keyhash{$symb.'_subject'} : $env{'form.probTitle'};
1921: $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1922: }
1923: my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1924: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1925: $request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1926: '<input type="hidden" name="command" value="handgrade" />'."\n".
1927: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1928: '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
1929: '<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1930: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
1931: '<input type="hidden" name="refresh" value="off" />'."\n".
1932: '<input type="hidden" name="studentNo" value="" />'."\n".
1933: '<input type="hidden" name="gradeOpt" value="" />'."\n".
1934: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1935: '<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
1936: '<input type="hidden" name="vProb" value="'.$env{'form.vProb'}.'" />'."\n".
1937: '<input type="hidden" name="vAns" value="'.$env{'form.vAns'}.'" />'."\n".
1938: '<input type="hidden" name="lastSub" value="'.$env{'form.lastSub'}.'" />'."\n".
1939: &build_section_inputs().
1940: '<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1941: '<input type="hidden" name="handgrade" value="'.$env{'form.handgrade'}.'" />'."\n".
1942: '<input type="hidden" name="NCT"'.
1943: ' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1944: if ($env{'form.handgrade'} eq 'yes') {
1945: $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
1946: '<input type="hidden" name="kwclr" value="'.$env{'form.kwclr'}.'" />'."\n".
1947: '<input type="hidden" name="kwsize" value="'.$env{'form.kwsize'}.'" />'."\n".
1948: '<input type="hidden" name="kwstyle" value="'.$env{'form.kwstyle'}.'" />'."\n".
1949: '<input type="hidden" name="msgsub" value="'.$env{'form.msgsub'}.'" />'."\n".
1950: '<input type="hidden" name="shownSub" value="0" />'."\n".
1951: '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1952: foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
1953: $request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
1954: }
1955: }
1956:
1957: my ($cts,$prnmsg) = (1,'');
1958: while ($cts <= $env{'form.savemsgN'}) {
1959: $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1960: (!exists($keyhash{$symb.'_savemsg'.$cts}) ?
1961: &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1962: &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1963: '" />'."\n".
1964: '<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1965: $cts++;
1966: }
1967: $request->print($prnmsg);
1968:
1969: if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1970: #
1971: # Print out the keyword options line
1972: #
1973: $request->print(<<KEYWORDS);
1974: <b>Keyword Options:</b>
1975: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>
1976: <a href="#" onMouseDown="javascript:getSel(); return false"
1977: CLASS="page">Paste Selection to List</a>
1978: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1979: KEYWORDS
1980: #
1981: # Load the other essays for similarity check
1982: #
1983: my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1984: my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1985: $apath=&escape($apath);
1986: $apath=~s/\W/\_/gs;
1987: %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1988: }
1989: }
1990:
1991: # This is where output for one specific student would start
1992: my $add_class = ($counter%2) ? 'LC_grade_show_user_odd_row' : '';
1993: $request->print("\n\n".
1994: '<div class="LC_grade_show_user '.$add_class.'">'.
1995: '<div class="LC_grade_user_name">'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</div>'.
1996: '<div class="LC_grade_show_user_body">'."\n");
1997:
1998: if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1999: my $mode;
2000: if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
2001: $mode='both';
2002: } elsif ($env{'form.vProb'} eq 'all' ) {
2003: $mode='text';
2004: } elsif ($env{'form.vAns'} eq 'all') {
2005: $mode='answer';
2006: }
2007: &Apache::lonxml::clear_problem_counter();
2008: $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
2009: }
2010:
2011: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
2012: my ($partlist,$handgrade,$responseType) = &response_type($symb);
2013:
2014: # Display student info
2015: $request->print(($counter == 0 ? '' : '<br />'));
2016: my $result='<div class="LC_grade_submissions">';
2017:
2018: $result.='<div class="LC_grade_submissions_header">';
2019: $result.= &mt('Submissions');
2020: $result.='<input type="hidden" name="name'.$counter.
2021: '" value="'.$env{'form.fullname'}.'" />'."\n";
2022: if ($env{'form.handgrade'} eq 'no') {
2023: $result.='<span class="LC_grade_check_note">'.
2024: &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)."</span>\n";
2025:
2026: }
2027:
2028:
2029:
2030: # If any part of the problem is an essay-response (handgraded), then check for collaborators
2031: my $fullname;
2032: my $col_fullnames = [];
2033: if ($env{'form.handgrade'} eq 'yes') {
2034: (my $sub_result,$fullname,$col_fullnames)=
2035: &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
2036: $counter);
2037: $result.=$sub_result;
2038: }
2039: $request->print($result."\n");
2040: $request->print('</div>'."\n");
2041: # print student answer/submission
2042: # Options are (1) Handgaded submission only
2043: # (2) Last submission, includes submission that is not handgraded
2044: # (for multi-response type part)
2045: # (3) Last submission plus the parts info
2046: # (4) The whole record for this student
2047: if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
2048: my ($string,$timestamp)= &get_last_submission(\%record);
2049:
2050: my $lastsubonly;
2051:
2052: if ($$timestamp eq '') {
2053: $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>';
2054: } else {
2055: $lastsubonly = '<div class="LC_grade_submissions_body"> <b>Date Submitted:</b> '.$$timestamp."\n";
2056:
2057: my %seenparts;
2058: my @part_response_id = &flatten_responseType($responseType);
2059: foreach my $part (@part_response_id) {
2060: next if ($env{'form.lastSub'} eq 'hdgrade'
2061: && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
2062:
2063: my ($partid,$respid) = @{ $part };
2064: my $display_part=&get_display_part($partid,$symb);
2065: if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
2066: if (exists($seenparts{$partid})) { next; }
2067: $seenparts{$partid}=1;
2068: my $submitby='<b>Part:</b> '.$display_part.
2069: ' <b>Collaborative submission by:</b> '.
2070: '<a href="javascript:viewSubmitter(\''.
2071: $env{"form.$uname:$udom:$partid:submitted_by"}.
2072: '\');" target="_self">'.
2073: $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
2074: $request->print($submitby);
2075: next;
2076: }
2077: my $responsetype = $responseType->{$partid}->{$respid};
2078: if (!exists($record{"resource.$partid.$respid.submission"})) {
2079: $lastsubonly.="\n".'<div class="LC_grade_submission_part"><b>Part:</b> '.
2080: $display_part.' <span class="LC_internal_info">( ID '.$respid.
2081: ' )</span> '.
2082: '<span class="LC_warning">'.&mt('Nothing submitted - no attempts').'</span><br /><br /></div>';
2083: next;
2084: }
2085: foreach my $submission (@$string) {
2086: my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
2087: if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
2088: my ($ressub,$subval) = split(/:/,$submission,2);
2089: # Similarity check
2090: my $similar='';
2091: if($env{'form.checkPlag'}){
2092: my ($oname,$odom,$ocrsid,$oessay,$osim)=
2093: &most_similar($uname,$udom,$subval,\%old_essays);
2094: if ($osim) {
2095: $osim=int($osim*100.0);
2096: my %old_course_desc =
2097: &Apache::lonnet::coursedescription($ocrsid,
2098: {'one_time' => 1});
2099:
2100: $similar="<hr /><h3><span class=\"LC_warning\">".
2101: &mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
2102: $osim,
2103: &Apache::loncommon::plainname($oname,$odom),
2104: $oname,$odom,
2105: $old_course_desc{'description'},
2106: $old_course_desc{'num'},
2107: $old_course_desc{'domain'}).
2108: '</span></h3><blockquote><i>'.
2109: &keywords_highlight($oessay).
2110: '</i></blockquote><hr />';
2111: }
2112: }
2113: my $order=&get_order($partid,$respid,$symb,$uname,$udom);
2114: if ($env{'form.lastSub'} eq 'lastonly' ||
2115: ($env{'form.lastSub'} eq 'hdgrade' &&
2116: $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
2117: my $display_part=&get_display_part($partid,$symb);
2118: $lastsubonly.='<div class="LC_grade_submission_part"><b>Part:</b> '.
2119: $display_part.' <span class="LC_internal_info">( ID '.$respid.
2120: ' )</span> ';
2121: my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
2122: if (@$files) {
2123: $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain virusses').'</span><br />';
2124: my $file_counter = 0;
2125: foreach my $file (@$files) {
2126: $file_counter++;
2127: &Apache::lonnet::allowuploaded('/adm/grades',$file);
2128: $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
2129: }
2130: $lastsubonly.='<br />';
2131: }
2132: $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
2133: &cleanRecord($subval,$responsetype,$symb,$partid,
2134: $respid,\%record,$order);
2135: if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
2136: $lastsubonly.='</div>';
2137: }
2138: }
2139: }
2140: $lastsubonly.='</div>'."\n";
2141: }
2142: $request->print($lastsubonly);
2143: } elsif ($env{'form.lastSub'} eq 'datesub') {
2144: my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
2145: $request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
2146: } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
2147: $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
2148: $env{'request.course.id'},
2149: $last,'.submission',
2150: 'Apache::grades::keywords_highlight'));
2151: }
2152:
2153: $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
2154: .$udom.'" />'."\n");
2155: # return if view submission with no grading option
2156: if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
2157: my $toGrade.='<input type="button" value="Grade Student" '.
2158: 'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
2159: .$counter.'\');" target="_self" /> '."\n" if (&canmodify($usec));
2160: $toGrade.='</div>'."\n";
2161: if (($env{'form.command'} eq 'submission') ||
2162: ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
2163: $toGrade.='</form>'.&show_grading_menu_form($symb);
2164: }
2165: $request->print($toGrade);
2166: return;
2167: } else {
2168: $request->print('</div>'."\n");
2169: }
2170:
2171: # essay grading message center
2172: if ($env{'form.handgrade'} eq 'yes') {
2173: my $result='<div class="LC_grade_message_center">';
2174:
2175: $result.='<div class="LC_grade_message_center_header">'.
2176: &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
2177: my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
2178: my $msgfor = $givenn.' '.$lastname;
2179: if (scalar(@$col_fullnames) > 0) {
2180: my $lastone = pop(@$col_fullnames);
2181: $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
2182: }
2183: $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
2184: $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
2185: '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
2186: $result.=' <a href="javascript:msgCenter(document.SCORE,'.$counter.
2187: ',\''.$msgfor.'\');" target="_self">'.
2188: &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
2189: &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
2190: '<img src="'.$request->dir_config('lonIconsURL').
2191: '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
2192: '<br /> ('.
2193: &mt('Message will be sent when you click on Save & Next below.').")\n";
2194: $result.='</div></div>';
2195: $request->print($result);
2196: }
2197:
2198: my %seen = ();
2199: my @partlist;
2200: my @gradePartRespid;
2201: my @part_response_id = &flatten_responseType($responseType);
2202: $request->print('<div class="LC_grade_assign">'.
2203:
2204: '<div class="LC_grade_assign_header">'.
2205: &mt('Assign Grades').'</div>'.
2206: '<div class="LC_grade_assign_body">');
2207: foreach my $part_response_id (@part_response_id) {
2208: my ($partid,$respid) = @{ $part_response_id };
2209: my $part_resp = join('_',@{ $part_response_id });
2210: next if ($seen{$partid} > 0);
2211: $seen{$partid}++;
2212: next if ($$handgrade{$part_resp} ne 'yes'
2213: && $env{'form.lastSub'} eq 'hdgrade');
2214: push @partlist,$partid;
2215: push @gradePartRespid,$partid.'.'.$respid;
2216: $request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
2217: }
2218: $request->print('</div></div>');
2219:
2220: $request->print('<div class="LC_grade_info_links">');
2221: if ($perm{'vgr'}) {
2222: $request->print(
2223: &Apache::loncommon::track_student_link(&mt('View recent activity'),
2224: $uname,$udom,'check'));
2225: }
2226: if ($perm{'opa'}) {
2227: $request->print(
2228: &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
2229: $uname,$udom,$symb,'check'));
2230: }
2231: $request->print('</div>');
2232:
2233: $result='<input type="hidden" name="partlist'.$counter.
2234: '" value="'.(join ":",@partlist).'" />'."\n";
2235: $result.='<input type="hidden" name="gradePartRespid'.
2236: '" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
2237: my $ctr = 0;
2238: while ($ctr < scalar(@partlist)) {
2239: $result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
2240: $partlist[$ctr].'" />'."\n";
2241: $ctr++;
2242: }
2243: $request->print($result.''."\n");
2244:
2245: # Done with printing info for one student
2246:
2247: $request->print('</div>');#LC_grade_show_user_body
2248: $request->print('</div>');#LC_grade_show_user
2249:
2250:
2251: # print end of form
2252: if ($counter == $total) {
2253: my $endform='<table border="0"><tr><td>'."\n";
2254: $endform.='<input type="button" value="'.&mt('Save & Next').'" '.
2255: 'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
2256: $total.','.scalar(@partlist).');" target="_self" /> '."\n";
2257: my $ntstu ='<select name="NTSTU">'.
2258: '<option>1</option><option>2</option>'.
2259: '<option>3</option><option>5</option>'.
2260: '<option>7</option><option>10</option></select>'."\n";
2261: my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
2262: $ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
2263: $endform.=&mt('[_1]student(s)',$ntstu);
2264: $endform.=' <input type="button" value="'.&mt('Previous').'" '.
2265: 'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> '."\n".
2266: '<input type="button" value="'.&mt('Next').'" '.
2267: 'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> ';
2268: $endform.=&mt('(Next and Previous (student) do not save the scores.)')."\n" ;
2269: $endform.="<input type='hidden' value='".&get_increment().
2270: "' name='increment' />";
2271: $endform.='</td></tr></table></form>';
2272: $endform.=&show_grading_menu_form($symb);
2273: $request->print($endform);
2274: }
2275: return '';
2276: }
2277:
2278: sub check_collaborators {
2279: my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
2280: my ($result,@col_fullnames);
2281: my ($classlist,undef,$fullname) = &getclasslist('all','0');
2282: foreach my $part (keys(%$handgrade)) {
2283: my $ncol = &Apache::lonnet::EXT('resource.'.$part.
2284: '.maxcollaborators',
2285: $symb,$udom,$uname);
2286: next if ($ncol <= 0);
2287: $part =~ s/\_/\./g;
2288: next if ($record->{'resource.'.$part.'.collaborators'} eq '');
2289: my (@good_collaborators, @bad_collaborators);
2290: foreach my $possible_collaborator
2291: (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) {
2292: $possible_collaborator =~ s/[\$\^\(\)]//g;
2293: next if ($possible_collaborator eq '');
2294: my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
2295: $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
2296: next if ($co_name eq $uname && $co_dom eq $udom);
2297: # Doing this grep allows 'fuzzy' specification
2298: my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i,
2299: keys(%$classlist));
2300: if (! scalar(@matches)) {
2301: push(@bad_collaborators, $possible_collaborator);
2302: } else {
2303: push(@good_collaborators, @matches);
2304: }
2305: }
2306: if (scalar(@good_collaborators) != 0) {
2307: $result.='<br />'.&mt('Collaborators: ');
2308: foreach my $name (@good_collaborators) {
2309: my ($lastname,$givenn) = split(/,/,$$fullname{$name});
2310: push(@col_fullnames, $givenn.' '.$lastname);
2311: $result.=$fullname->{$name}.' ';
2312: }
2313: $result.='<br />'."\n";
2314: my ($part)=split(/\./,$part);
2315: $result.='<input type="hidden" name="collaborator'.$counter.
2316: '" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
2317: "\n";
2318: }
2319: if (scalar(@bad_collaborators) > 0) {
2320: $result.='<div class="LC_warning">';
2321: $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
2322: $result .= '</div>';
2323: }
2324: if (scalar(@bad_collaborators > $ncol)) {
2325: $result .= '<div class="LC_warning">';
2326: $result .= &mt('This student has submitted too many '.
2327: 'collaborators. Maximum is [_1].',$ncol);
2328: $result .= '</div>';
2329: }
2330: }
2331: return ($result,$fullname,\@col_fullnames);
2332: }
2333:
2334: #--- Retrieve the last submission for all the parts
2335: sub get_last_submission {
2336: my ($returnhash)=@_;
2337: my (@string,$timestamp);
2338: if ($$returnhash{'version'}) {
2339: my %lasthash=();
2340: my ($version);
2341: for ($version=1;$version<=$$returnhash{'version'};$version++) {
2342: foreach my $key (sort(split(/\:/,
2343: $$returnhash{$version.':keys'}))) {
2344: $lasthash{$key}=$$returnhash{$version.':'.$key};
2345: $timestamp =
2346: scalar(localtime($$returnhash{$version.':timestamp'}));
2347: }
2348: }
2349: foreach my $key (keys(%lasthash)) {
2350: next if ($key !~ /\.submission$/);
2351:
2352: my ($partid,$foo) = split(/submission$/,$key);
2353: my $draft = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
2354: '<span class="LC_warning">Draft Copy</span> ' : '';
2355: push(@string, join(':', $key, $draft.$lasthash{$key}));
2356: }
2357: }
2358: if (!@string) {
2359: $string[0] =
2360: '<span class="LC_warning">Nothing submitted - no attempts.</span>';
2361: }
2362: return (\@string,\$timestamp);
2363: }
2364:
2365: #--- High light keywords, with style choosen by user.
2366: sub keywords_highlight {
2367: my $string = shift;
2368: my $size = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
2369: my $styleon = $env{'form.kwstyle'} eq '' ? '' : $env{'form.kwstyle'};
2370: (my $styleoff = $styleon) =~ s/\</\<\//;
2371: my @keylist = split(/[,\s+]/,$env{'form.keywords'});
2372: foreach my $keyword (@keylist) {
2373: $string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
2374: }
2375: return $string;
2376: }
2377:
2378: #--- Called from submission routine
2379: sub processHandGrade {
2380: my ($request) = shift;
2381: my $symb = &get_symb($request);
2382: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
2383: my $button = $env{'form.gradeOpt'};
2384: my $ngrade = $env{'form.NCT'};
2385: my $ntstu = $env{'form.NTSTU'};
2386: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2387: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2388:
2389: if ($button eq 'Save & Next') {
2390: my $ctr = 0;
2391: while ($ctr < $ngrade) {
2392: my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
2393: my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
2394: if ($errorflag eq 'no_score') {
2395: $ctr++;
2396: next;
2397: }
2398: if ($errorflag eq 'not_allowed') {
2399: $request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
2400: $ctr++;
2401: next;
2402: }
2403: my $includemsg = $env{'form.includemsg'.$ctr};
2404: my ($subject,$message,$msgstatus) = ('','','');
2405: my $restitle = &Apache::lonnet::gettitle($symb);
2406: my ($feedurl,$showsymb) =
2407: &get_feedurl_and_symb($symb,$uname,$udom);
2408: my $messagetail;
2409: if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
2410: $subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
2411: unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
2412: $subject.=' ['.$restitle.']';
2413: my (@msgnum) = split(/,/,$includemsg);
2414: foreach (@msgnum) {
2415: $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
2416: }
2417: $message =&Apache::lonfeedback::clear_out_html($message);
2418: if ($env{'form.withgrades'.$ctr}) {
2419: $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
2420: $messagetail = " for <a href=\"".
2421: $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
2422: }
2423: $msgstatus =
2424: &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
2425: $message.$messagetail,
2426: undef,$feedurl,undef,
2427: undef,undef,$showsymb,
2428: $restitle);
2429: $request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
2430: $msgstatus);
2431: }
2432: if ($env{'form.collaborator'.$ctr}) {
2433: my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
2434: foreach my $collabstr (@collabstrs) {
2435: my ($part,@collaborators) = split(/:/,$collabstr);
2436: foreach my $collaborator (@collaborators) {
2437: my ($errorflag,$pts,$wgt) =
2438: &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
2439: $env{'form.unamedom'.$ctr},$part);
2440: if ($errorflag eq 'not_allowed') {
2441: $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
2442: next;
2443: } elsif ($message ne '') {
2444: my ($baseurl,$showsymb) =
2445: &get_feedurl_and_symb($symb,$collaborator,
2446: $udom);
2447: if ($env{'form.withgrades'.$ctr}) {
2448: $messagetail = " for <a href=\"".
2449: $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
2450: }
2451: $msgstatus =
2452: &Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
2453: }
2454: }
2455: }
2456: }
2457: $ctr++;
2458: }
2459: }
2460:
2461: if ($env{'form.handgrade'} eq 'yes') {
2462: # Keywords sorted in alphabatical order
2463: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
2464: my %keyhash = ();
2465: $env{'form.keywords'} =~ s/,\s{0,}|\s+/ /g;
2466: $env{'form.keywords'} =~ s/^\s+|\s+$//;
2467: my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
2468: $env{'form.keywords'} = join(' ',@keywords);
2469: $keyhash{$symb.'_keywords'} = $env{'form.keywords'};
2470: $keyhash{$symb.'_subject'} = $env{'form.msgsub'};
2471: $keyhash{$loginuser.'_kwclr'} = $env{'form.kwclr'};
2472: $keyhash{$loginuser.'_kwsize'} = $env{'form.kwsize'};
2473: $keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
2474:
2475: # message center - Order of message gets changed. Blank line is eliminated.
2476: # New messages are saved in env for the next student.
2477: # All messages are saved in nohist_handgrade.db
2478: my ($ctr,$idx) = (1,1);
2479: while ($ctr <= $env{'form.savemsgN'}) {
2480: if ($env{'form.savemsg'.$ctr} ne '') {
2481: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
2482: $idx++;
2483: }
2484: $ctr++;
2485: }
2486: $ctr = 0;
2487: while ($ctr < $ngrade) {
2488: if ($env{'form.newmsg'.$ctr} ne '') {
2489: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2490: $env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2491: $idx++;
2492: }
2493: $ctr++;
2494: }
2495: $env{'form.savemsgN'} = --$idx;
2496: $keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
2497: my $putresult = &Apache::lonnet::put
2498: ('nohist_handgrade',\%keyhash,$cdom,$cnum);
2499: }
2500: # Called by Save & Refresh from Highlight Attribute Window
2501: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
2502: if ($env{'form.refresh'} eq 'on') {
2503: my ($ctr,$total) = (0,0);
2504: while ($ctr < $ngrade) {
2505: $total++ if $env{'form.unamedom'.$ctr} ne '';
2506: $ctr++;
2507: }
2508: $env{'form.NTSTU'}=$ngrade;
2509: $ctr = 0;
2510: while ($ctr < $total) {
2511: my $processUser = $env{'form.unamedom'.$ctr};
2512: ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
2513: $env{'form.fullname'} = $$fullname{$processUser};
2514: &submission($request,$ctr,$total-1);
2515: $ctr++;
2516: }
2517: return '';
2518: }
2519:
2520: # Go directly to grade student - from submission or link from chart page
2521: if ($button eq 'Grade Student') {
2522: (undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
2523: my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
2524: ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
2525: $env{'form.fullname'} = $$fullname{$processUser};
2526: &submission($request,0,0);
2527: return '';
2528: }
2529:
2530: # Get the next/previous one or group of students
2531: my $firststu = $env{'form.unamedom0'};
2532: my $laststu = $env{'form.unamedom'.($ngrade-1)};
2533: my $ctr = 2;
2534: while ($laststu eq '') {
2535: $laststu = $env{'form.unamedom'.($ngrade-$ctr)};
2536: $ctr++;
2537: $laststu = $firststu if ($ctr > $ngrade);
2538: }
2539:
2540: my (@parsedlist,@nextlist);
2541: my ($nextflg) = 0;
2542: foreach (sort
2543: {
2544: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
2545: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
2546: }
2547: return $a cmp $b;
2548: } (keys(%$fullname))) {
2549: if ($nextflg == 1 && $button =~ /Next$/) {
2550: push @parsedlist,$_;
2551: }
2552: $nextflg = 1 if ($_ eq $laststu);
2553: if ($button eq 'Previous') {
2554: last if ($_ eq $firststu);
2555: push @parsedlist,$_;
2556: }
2557: }
2558: $ctr = 0;
2559: @parsedlist = reverse @parsedlist if ($button eq 'Previous');
2560: my ($partlist) = &response_type($symb);
2561: foreach my $student (@parsedlist) {
2562: my $submitonly=$env{'form.submitonly'};
2563: my ($uname,$udom) = split(/:/,$student);
2564:
2565: if ($submitonly eq 'queued') {
2566: my %queue_status =
2567: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
2568: $udom,$uname);
2569: next if (!defined($queue_status{'gradingqueue'}));
2570: }
2571:
2572: if ($submitonly =~ /^(yes|graded|incorrect)$/) {
2573: # my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
2574: my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
2575: my $submitted = 0;
2576: my $ungraded = 0;
2577: my $incorrect = 0;
2578: foreach (keys(%status)) {
2579: $submitted = 1 if ($status{$_} ne 'nothing');
2580: $ungraded = 1 if ($status{$_} =~ /^ungraded/);
2581: $incorrect = 1 if ($status{$_} =~ /^incorrect/);
2582: my ($foo,$partid,$foo1) = split(/\./,$_);
2583: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
2584: $submitted = 0;
2585: }
2586: }
2587: next if (!$submitted && ($submitonly eq 'yes' ||
2588: $submitonly eq 'incorrect' ||
2589: $submitonly eq 'graded'));
2590: next if (!$ungraded && ($submitonly eq 'graded'));
2591: next if (!$incorrect && $submitonly eq 'incorrect');
2592: }
2593: push @nextlist,$student if ($ctr < $ntstu);
2594: last if ($ctr == $ntstu);
2595: $ctr++;
2596: }
2597:
2598: $ctr = 0;
2599: my $total = scalar(@nextlist)-1;
2600:
2601: foreach (sort @nextlist) {
2602: my ($uname,$udom,$submitter) = split(/:/);
2603: $env{'form.student'} = $uname;
2604: $env{'form.userdom'} = $udom;
2605: $env{'form.fullname'} = $$fullname{$_};
2606: &submission($request,$ctr,$total);
2607: $ctr++;
2608: }
2609: if ($total < 0) {
2610: my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
2611: $the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
2612: $the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
2613: $the_end.=&show_grading_menu_form($symb);
2614: $request->print($the_end);
2615: }
2616: return '';
2617: }
2618:
2619: #---- Save the score and award for each student, if changed
2620: sub saveHandGrade {
2621: my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
2622: my @version_parts;
2623: my $usec = &Apache::lonnet::getsection($domain,$stuname,
2624: $env{'request.course.id'});
2625: if (!&canmodify($usec)) { return('not_allowed'); }
2626: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
2627: my @parts_graded;
2628: my %newrecord = ();
2629: my ($pts,$wgt) = ('','');
2630: my %aggregate = ();
2631: my $aggregateflag = 0;
2632: my @parts = split(/:/,$env{'form.partlist'.$newflg});
2633: foreach my $new_part (@parts) {
2634: #collaborator ($submi may vary for different parts
2635: if ($submitter && $new_part ne $part) { next; }
2636: my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
2637: if ($dropMenu eq 'excused') {
2638: if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
2639: $newrecord{'resource.'.$new_part.'.solved'} = 'excused';
2640: if (exists($record{'resource.'.$new_part.'.awarded'})) {
2641: $newrecord{'resource.'.$new_part.'.awarded'} = '';
2642: }
2643: $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
2644: }
2645: } elsif ($dropMenu eq 'reset status'
2646: && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
2647: foreach my $key (keys (%record)) {
2648: if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
2649: }
2650: $newrecord{'resource.'.$new_part.'.regrader'}=
2651: "$env{'user.name'}:$env{'user.domain'}";
2652: my $totaltries = $record{'resource.'.$part.'.tries'};
2653:
2654: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
2655: [$new_part]);
2656: my $aggtries =$totaltries;
2657: if ($last_resets{$new_part}) {
2658: $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
2659: $new_part);
2660: }
2661:
2662: my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
2663: if ($aggtries > 0) {
2664: &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
2665: $aggregateflag = 1;
2666: }
2667: } elsif ($dropMenu eq '') {
2668: $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ?
2669: $env{'form.GD_BOX'.$newflg.'_'.$new_part} :
2670: $env{'form.RADVAL'.$newflg.'_'.$new_part});
2671: if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
2672: next;
2673: }
2674: $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 :
2675: $env{'form.WGT'.$newflg.'_'.$new_part};
2676: my $partial= $pts/$wgt;
2677: if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
2678: #do not update score for part if not changed.
2679: &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
2680: next;
2681: } else {
2682: push @parts_graded, $new_part;
2683: }
2684: if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
2685: $newrecord{'resource.'.$new_part.'.awarded'} = $partial;
2686: }
2687: my $reckey = 'resource.'.$new_part.'.solved';
2688: if ($partial == 0) {
2689: if ($record{$reckey} ne 'incorrect_by_override') {
2690: $newrecord{$reckey} = 'incorrect_by_override';
2691: }
2692: } else {
2693: if ($record{$reckey} ne 'correct_by_override') {
2694: $newrecord{$reckey} = 'correct_by_override';
2695: }
2696: }
2697: if ($submitter &&
2698: ($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
2699: $newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
2700: }
2701: $newrecord{'resource.'.$new_part.'.regrader'}=
2702: "$env{'user.name'}:$env{'user.domain'}";
2703: }
2704: # unless problem has been graded, set flag to version the submitted files
2705: unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/ ||
2706: $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
2707: $dropMenu eq 'reset status')
2708: {
2709: push (@version_parts,$new_part);
2710: }
2711: }
2712: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2713: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2714:
2715: if (%newrecord) {
2716: if (@version_parts) {
2717: my @changed_keys = &version_portfiles(\%record, \@parts_graded,
2718: $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
2719: @newrecord{@changed_keys} = @record{@changed_keys};
2720: foreach my $new_part (@version_parts) {
2721: &handback_files($request,$symb,$stuname,$domain,$newflg,
2722: $new_part,\%newrecord);
2723: }
2724: }
2725: &Apache::lonnet::cstore(\%newrecord,$symb,
2726: $env{'request.course.id'},$domain,$stuname);
2727: &check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
2728: $cdom,$cnum,$domain,$stuname);
2729: }
2730: if ($aggregateflag) {
2731: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
2732: $cdom,$cnum);
2733: }
2734: return ('',$pts,$wgt);
2735: }
2736:
2737: sub check_and_remove_from_queue {
2738: my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
2739: my @ungraded_parts;
2740: foreach my $part (@{$parts}) {
2741: if ( $record->{ 'resource.'.$part.'.awarded'} eq ''
2742: && $record->{ 'resource.'.$part.'.solved' } ne 'excused'
2743: && $newrecord->{'resource.'.$part.'.awarded'} eq ''
2744: && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
2745: ) {
2746: push(@ungraded_parts, $part);
2747: }
2748: }
2749: if ( !@ungraded_parts ) {
2750: &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
2751: $cnum,$domain,$stuname);
2752: }
2753: }
2754:
2755: sub handback_files {
2756: my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
2757: my $portfolio_root = &propath($domain,$stuname).'/userfiles/portfolio';
2758: my ($partlist,$handgrade,$responseType) = &response_type($symb);
2759:
2760: my @part_response_id = &flatten_responseType($responseType);
2761: foreach my $part_response_id (@part_response_id) {
2762: my ($part_id,$resp_id) = @{ $part_response_id };
2763: my $part_resp = join('_',@{ $part_response_id });
2764: if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
2765: # if multiple files are uploaded names will be 'returndoc2','returndoc3'
2766: my $file_counter = 1;
2767: my $file_msg;
2768: while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
2769: my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
2770: my ($directory,$answer_file) =
2771: ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
2772: my ($answer_name,$answer_ver,$answer_ext) =
2773: &file_name_version_ext($answer_file);
2774: my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
2775: my @dir_list = &Apache::lonnet::dirlist($portfolio_path,$domain,$stuname,$portfolio_root);
2776: my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
2777: # fix file name
2778: my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
2779: my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
2780: $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
2781: $save_file_name);
2782: if ($result !~ m|^/uploaded/|) {
2783: $request->print('<span class="LC_error">An error occurred ('.$result.
2784: ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</span><br />');
2785: } else {
2786: # mark the file as read only
2787: my @files = ($save_file_name);
2788: my @what = ($symb,$env{'request.course.id'},'handback');
2789: &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
2790: if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
2791: $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
2792: }
2793: $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
2794: $file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
2795:
2796: }
2797: $request->print("<br />".$fname." will be the uploaded file name");
2798: $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
2799: $file_counter++;
2800: }
2801: my $subject = "File Handed Back by Instructor ";
2802: my $message = "A file has been returned that was originally submitted in reponse to: <br />";
2803: $message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
2804: $message .= ' The returned file(s) are named: '. $file_msg;
2805: $message .= " and can be found in your portfolio space.";
2806: my ($feedurl,$showsymb) =
2807: &get_feedurl_and_symb($symb,$domain,$stuname);
2808: my $restitle = &Apache::lonnet::gettitle($symb);
2809: my $msgstatus =
2810: &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
2811: ' (File Returned) ['.$restitle.']',$message,undef,
2812: $feedurl,undef,undef,undef,$showsymb,$restitle);
2813: }
2814: }
2815: return;
2816: }
2817:
2818: sub get_feedurl_and_symb {
2819: my ($symb,$uname,$udom) = @_;
2820: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
2821: $url = &Apache::lonnet::clutter($url);
2822: my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
2823: $symb,$udom,$uname);
2824: if ($encrypturl =~ /^yes$/i) {
2825: &Apache::lonenc::encrypted(\$url,1);
2826: &Apache::lonenc::encrypted(\$symb,1);
2827: }
2828: return ($url,$symb);
2829: }
2830:
2831: sub get_submitted_files {
2832: my ($udom,$uname,$partid,$respid,$record) = @_;
2833: my @files;
2834: if ($$record{"resource.$partid.$respid.portfiles"}) {
2835: my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
2836: foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
2837: push(@files,$file_url.$file);
2838: }
2839: }
2840: if ($$record{"resource.$partid.$respid.uploadedurl"}) {
2841: push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
2842: }
2843: return (\@files);
2844: }
2845:
2846: # ----------- Provides number of tries since last reset.
2847: sub get_num_tries {
2848: my ($record,$last_reset,$part) = @_;
2849: my $timestamp = '';
2850: my $num_tries = 0;
2851: if ($$record{'version'}) {
2852: for (my $version=$$record{'version'};$version>=1;$version--) {
2853: if (exists($$record{$version.':resource.'.$part.'.solved'})) {
2854: $timestamp = $$record{$version.':timestamp'};
2855: if ($timestamp > $last_reset) {
2856: $num_tries ++;
2857: } else {
2858: last;
2859: }
2860: }
2861: }
2862: }
2863: return $num_tries;
2864: }
2865:
2866: # ----------- Determine decrements required in aggregate totals
2867: sub decrement_aggs {
2868: my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
2869: my %decrement = (
2870: attempts => 0,
2871: users => 0,
2872: correct => 0
2873: );
2874: $decrement{'attempts'} = $aggtries;
2875: if ($solvedstatus =~ /^correct/) {
2876: $decrement{'correct'} = 1;
2877: }
2878: if ($aggtries == $totaltries) {
2879: $decrement{'users'} = 1;
2880: }
2881: foreach my $type (keys (%decrement)) {
2882: $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
2883: }
2884: return;
2885: }
2886:
2887: # ----------- Determine timestamps for last reset of aggregate totals for parts
2888: sub get_last_resets {
2889: my ($symb,$courseid,$partids) =@_;
2890: my %last_resets;
2891: my $cdom = $env{'course.'.$courseid.'.domain'};
2892: my $cname = $env{'course.'.$courseid.'.num'};
2893: my @keys;
2894: foreach my $part (@{$partids}) {
2895: push(@keys,"$symb\0$part\0resettime");
2896: }
2897: my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
2898: $cdom,$cname);
2899: foreach my $part (@{$partids}) {
2900: $last_resets{$part}=$results{"$symb\0$part\0resettime"};
2901: }
2902: return %last_resets;
2903: }
2904:
2905: # ----------- Handles creating versions for portfolio files as answers
2906: sub version_portfiles {
2907: my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
2908: my $version_parts = join('|',@$v_flag);
2909: my @returned_keys;
2910: my $parts = join('|', @$parts_graded);
2911: my $portfolio_root = &propath($domain,$stu_name).
2912: '/userfiles/portfolio';
2913: foreach my $key (keys(%$record)) {
2914: my $new_portfiles;
2915: if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
2916: my @versioned_portfiles;
2917: my @portfiles = split(/\s*,\s*/,$$record{$key});
2918: foreach my $file (@portfiles) {
2919: &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
2920: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
2921: my ($answer_name,$answer_ver,$answer_ext) =
2922: &file_name_version_ext($answer_file);
2923: my @dir_list = &Apache::lonnet::dirlist($directory,$domain,$stu_name,$portfolio_root);
2924: my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
2925: my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
2926: if ($new_answer ne 'problem getting file') {
2927: push(@versioned_portfiles, $directory.$new_answer);
2928: &Apache::lonnet::mark_as_readonly($domain,$stu_name,
2929: [$directory.$new_answer],
2930: [$symb,$env{'request.course.id'},'graded']);
2931: }
2932: }
2933: $$record{$key} = join(',',@versioned_portfiles);
2934: push(@returned_keys,$key);
2935: }
2936: }
2937: return (@returned_keys);
2938: }
2939:
2940: sub get_next_version {
2941: my ($answer_name, $answer_ext, $dir_list) = @_;
2942: my $version;
2943: foreach my $row (@$dir_list) {
2944: my ($file) = split(/\&/,$row,2);
2945: my ($file_name,$file_version,$file_ext) =
2946: &file_name_version_ext($file);
2947: if (($file_name eq $answer_name) &&
2948: ($file_ext eq $answer_ext)) {
2949: # gets here if filename and extension match, regardless of version
2950: if ($file_version ne '') {
2951: # a versioned file is found so save it for later
2952: if ($file_version > $version) {
2953: $version = $file_version;
2954: }
2955: }
2956: }
2957: }
2958: $version ++;
2959: return($version);
2960: }
2961:
2962: sub version_selected_portfile {
2963: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
2964: my ($answer_name,$answer_ver,$answer_ext) =
2965: &file_name_version_ext($file_name);
2966: my $new_answer;
2967: $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
2968: if($env{'form.copy'} eq '-1') {
2969: $new_answer = 'problem getting file';
2970: } else {
2971: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
2972: my $copy_result = &Apache::lonnet::finishuserfileupload(
2973: $stu_name,$domain,'copy',
2974: '/portfolio'.$directory.$new_answer);
2975: }
2976: return ($new_answer);
2977: }
2978:
2979: sub file_name_version_ext {
2980: my ($file)=@_;
2981: my @file_parts = split(/\./, $file);
2982: my ($name,$version,$ext);
2983: if (@file_parts > 1) {
2984: $ext=pop(@file_parts);
2985: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
2986: $version=pop(@file_parts);
2987: }
2988: $name=join('.',@file_parts);
2989: } else {
2990: $name=join('.',@file_parts);
2991: }
2992: return($name,$version,$ext);
2993: }
2994:
2995: #--------------------------------------------------------------------------------------
2996: #
2997: #-------------------------- Next few routines handles grading by section or whole class
2998: #
2999: #--- Javascript to handle grading by section or whole class
3000: sub viewgrades_js {
3001: my ($request) = shift;
3002:
3003: $request->print(<<VIEWJAVASCRIPT);
3004: <script type="text/javascript" language="javascript">
3005: function writePoint(partid,weight,point) {
3006: var radioButton = document.classgrade["RADVAL_"+partid];
3007: var textbox = document.classgrade["TEXTVAL_"+partid];
3008: if (point == "textval") {
3009: point = document.classgrade["TEXTVAL_"+partid].value;
3010: if (isNaN(point) || parseFloat(point) < 0) {
3011: alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
3012: var resetbox = false;
3013: for (var i=0; i<radioButton.length; i++) {
3014: if (radioButton[i].checked) {
3015: textbox.value = i;
3016: resetbox = true;
3017: }
3018: }
3019: if (!resetbox) {
3020: textbox.value = "";
3021: }
3022: return;
3023: }
3024: if (parseFloat(point) > parseFloat(weight)) {
3025: var resp = confirm("You entered a value ("+parseFloat(point)+
3026: ") greater than the weight for the part. Accept?");
3027: if (resp == false) {
3028: textbox.value = "";
3029: return;
3030: }
3031: }
3032: for (var i=0; i<radioButton.length; i++) {
3033: radioButton[i].checked=false;
3034: if (parseFloat(point) == i) {
3035: radioButton[i].checked=true;
3036: }
3037: }
3038:
3039: } else {
3040: textbox.value = parseFloat(point);
3041: }
3042: for (i=0;i<document.classgrade.total.value;i++) {
3043: var user = document.classgrade["ctr"+i].value;
3044: user = user.replace(new RegExp(':', 'g'),"_");
3045: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3046: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3047: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3048: if (saveval != "correct") {
3049: scorename.value = point;
3050: if (selname[0].selected != true) {
3051: selname[0].selected = true;
3052: }
3053: }
3054: }
3055: document.classgrade["SELVAL_"+partid][0].selected = true;
3056: }
3057:
3058: function writeRadText(partid,weight) {
3059: var selval = document.classgrade["SELVAL_"+partid];
3060: var radioButton = document.classgrade["RADVAL_"+partid];
3061: var override = document.classgrade["FORCE_"+partid].checked;
3062: var textbox = document.classgrade["TEXTVAL_"+partid];
3063: if (selval[1].selected || selval[2].selected) {
3064: for (var i=0; i<radioButton.length; i++) {
3065: radioButton[i].checked=false;
3066:
3067: }
3068: textbox.value = "";
3069:
3070: for (i=0;i<document.classgrade.total.value;i++) {
3071: var user = document.classgrade["ctr"+i].value;
3072: user = user.replace(new RegExp(':', 'g'),"_");
3073: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3074: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3075: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3076: if ((saveval != "correct") || override) {
3077: scorename.value = "";
3078: if (selval[1].selected) {
3079: selname[1].selected = true;
3080: } else {
3081: selname[2].selected = true;
3082: if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value))
3083: {document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
3084: }
3085: }
3086: }
3087: } else {
3088: for (i=0;i<document.classgrade.total.value;i++) {
3089: var user = document.classgrade["ctr"+i].value;
3090: user = user.replace(new RegExp(':', 'g'),"_");
3091: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3092: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3093: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3094: if ((saveval != "correct") || override) {
3095: scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
3096: selname[0].selected = true;
3097: }
3098: }
3099: }
3100: }
3101:
3102: function changeSelect(partid,user) {
3103: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
3104: var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
3105: var point = textbox.value;
3106: var weight = document.classgrade["weight_"+partid].value;
3107:
3108: if (isNaN(point) || parseFloat(point) < 0) {
3109: alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
3110: textbox.value = "";
3111: return;
3112: }
3113: if (parseFloat(point) > parseFloat(weight)) {
3114: var resp = confirm("You entered a value ("+parseFloat(point)+
3115: ") greater than the weight of the part. Accept?");
3116: if (resp == false) {
3117: textbox.value = "";
3118: return;
3119: }
3120: }
3121: selval[0].selected = true;
3122: }
3123:
3124: function changeOneScore(partid,user) {
3125: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
3126: if (selval[1].selected || selval[2].selected) {
3127: document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
3128: if (selval[2].selected) {
3129: document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
3130: }
3131: }
3132: }
3133:
3134: function resetEntry(numpart) {
3135: for (ctpart=0;ctpart<numpart;ctpart++) {
3136: var partid = document.classgrade["partid_"+ctpart].value;
3137: var radioButton = document.classgrade["RADVAL_"+partid];
3138: var textbox = document.classgrade["TEXTVAL_"+partid];
3139: var selval = document.classgrade["SELVAL_"+partid];
3140: for (var i=0; i<radioButton.length; i++) {
3141: radioButton[i].checked=false;
3142:
3143: }
3144: textbox.value = "";
3145: selval[0].selected = true;
3146:
3147: for (i=0;i<document.classgrade.total.value;i++) {
3148: var user = document.classgrade["ctr"+i].value;
3149: user = user.replace(new RegExp(':', 'g'),"_");
3150: var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3151: resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
3152: var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
3153: resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
3154: var saveselval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3155: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3156: if (saveselval == "excused") {
3157: if (selname[1].selected == false) { selname[1].selected = true;}
3158: } else {
3159: if (selname[0].selected == false) {selname[0].selected = true};
3160: }
3161: }
3162: }
3163: }
3164:
3165: </script>
3166: VIEWJAVASCRIPT
3167: }
3168:
3169: #--- show scores for a section or whole class w/ option to change/update a score
3170: sub viewgrades {
3171: my ($request) = shift;
3172: &viewgrades_js($request);
3173:
3174: my ($symb) = &get_symb($request);
3175: #need to make sure we have the correct data for later EXT calls,
3176: #thus invalidate the cache
3177: &Apache::lonnet::devalidatecourseresdata(
3178: $env{'course.'.$env{'request.course.id'}.'.num'},
3179: $env{'course.'.$env{'request.course.id'}.'.domain'});
3180: &Apache::lonnet::clear_EXT_cache_status();
3181:
3182: my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
3183: $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
3184:
3185: #view individual student submission form - called using Javascript viewOneStudent
3186: $result.=&jscriptNform($symb);
3187:
3188: #beginning of class grading form
3189: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
3190: $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
3191: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
3192: '<input type="hidden" name="command" value="editgrades" />'."\n".
3193: &build_section_inputs().
3194: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
3195: '<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
3196: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
3197:
3198: my $sectionClass;
3199: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3200: if ($env{'form.section'} eq 'all') {
3201: $sectionClass='Class';
3202: } elsif ($env{'form.section'} eq 'none') {
3203: $sectionClass='Students in no Section';
3204: } else {
3205: $sectionClass='Students in Section(s) [_1]';
3206: }
3207: $result.=
3208: '<h3>'.
3209: &mt("Assign Common Grade To $sectionClass",$section_display).'</h3>';
3210: $result.= &Apache::loncommon::start_data_table();
3211: #radio buttons/text box for assigning points for a section or class.
3212: #handles different parts of a problem
3213: my ($partlist,$handgrade,$responseType) = &response_type($symb);
3214: my %weight = ();
3215: my $ctsparts = 0;
3216: my %seen = ();
3217: my @part_response_id = &flatten_responseType($responseType);
3218: foreach my $part_response_id (@part_response_id) {
3219: my ($partid,$respid) = @{ $part_response_id };
3220: my $part_resp = join('_',@{ $part_response_id });
3221: next if $seen{$partid};
3222: $seen{$partid}++;
3223: my $handgrade=$$handgrade{$part_resp};
3224: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
3225: $weight{$partid} = $wgt eq '' ? '1' : $wgt;
3226:
3227: my $display_part=&get_display_part($partid,$symb);
3228: my $radio.='<table border="0"><tr>';
3229: my $ctr = 0;
3230: while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
3231: $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
3232: 'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
3233: ','.$ctr.')" />'.$ctr."</label></td>\n";
3234: $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
3235: $ctr++;
3236: }
3237: $radio.='</tr></table>';
3238: my $line = '<input type="text" name="TEXTVAL_'.
3239: $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
3240: $partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
3241: $weight{$partid}.' (problem weight)</td>'."\n";
3242: $line.= '<td><select name="SELVAL_'.$partid.'"'.
3243: 'onChange="javascript:writeRadText(\''.$partid.'\','.
3244: $weight{$partid}.')"> '.
3245: '<option selected="selected"> </option>'.
3246: '<option value="excused">'.&mt('excused').'</option>'.
3247: '<option value="reset status">'.&mt('reset status').'</option>'.
3248: '</select></td>'.
3249: '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
3250: $line.='<input type="hidden" name="partid_'.
3251: $ctsparts.'" value="'.$partid.'" />'."\n";
3252: $line.='<input type="hidden" name="weight_'.
3253: $partid.'" value="'.$weight{$partid}.'" />'."\n";
3254:
3255: $result.=
3256: &Apache::loncommon::start_data_table_row()."\n".
3257: &mt('<td><b>Part:</b></td><td>[_1]</td><td><b>Points:</b></td><td>[_2]</td><td>or</td><td>[_3]</td>',$display_part,$radio,$line).
3258: &Apache::loncommon::end_data_table_row()."\n";
3259: $ctsparts++;
3260: }
3261: $result.=&Apache::loncommon::end_data_table()."\n".
3262: '<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
3263: $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
3264: 'onClick="javascript:resetEntry('.$ctsparts.');" />';
3265:
3266: #table listing all the students in a section/class
3267: #header of table
3268: $result.= '<h3>'.&mt('Assign Grade to Specific Students in '.$sectionClass,
3269: $section_display).'</h3>';
3270: $result.= &Apache::loncommon::start_data_table().
3271: &Apache::loncommon::start_data_table_header_row().
3272: '<th>'.&mt('No.').'</th>'.
3273: '<th>'.&nameUserString('header')."</th>\n";
3274: my (@parts) = sort(&getpartlist($symb));
3275: my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
3276: my @partids = ();
3277: foreach my $part (@parts) {
3278: my $display=&Apache::lonnet::metadata($url,$part.'.display');
3279: $display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
3280: if (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
3281: my ($partid) = &split_part_type($part);
3282: push(@partids, $partid);
3283: my $display_part=&get_display_part($partid,$symb);
3284: if ($display =~ /^Partial Credit Factor/) {
3285: $result.='<th>'.
3286: &mt('Score Part: [_1]<br /> (weight = [_2])',
3287: $display_part,$weight{$partid}).'</th>'."\n";
3288: next;
3289:
3290: } else {
3291: if ($display =~ /Problem Status/) {
3292: my $grade_status_mt = &mt('Grade Status');
3293: $display =~ s{Problem Status}{$grade_status_mt<br />};
3294: }
3295: my $part_mt = &mt('Part:');
3296: $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
3297: }
3298:
3299: $result.='<th>'.$display.'</th>'."\n";
3300: }
3301: $result.=&Apache::loncommon::end_data_table_header_row();
3302:
3303: my %last_resets =
3304: &get_last_resets($symb,$env{'request.course.id'},\@partids);
3305:
3306: #get info for each student
3307: #list all the students - with points and grade status
3308: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
3309: my $ctr = 0;
3310: foreach (sort
3311: {
3312: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
3313: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
3314: }
3315: return $a cmp $b;
3316: } (keys(%$fullname))) {
3317: $ctr++;
3318: $result.=&viewstudentgrade($symb,$env{'request.course.id'},
3319: $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
3320: }
3321: $result.=&Apache::loncommon::end_data_table();
3322: $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
3323: $result.='<input type="button" value="'.&mt('Save').'" '.
3324: 'onClick="javascript:submit();" target="_self" /></form>'."\n";
3325: if (scalar(%$fullname) eq 0) {
3326: my $colspan=3+scalar(@parts);
3327: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3328: my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
3329: $result='<span class="LC_warning">'.
3330: &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
3331: $section_display, $stu_status).
3332: '</span>';
3333: }
3334: $result.=&show_grading_menu_form($symb);
3335: return $result;
3336: }
3337:
3338: #--- call by previous routine to display each student
3339: sub viewstudentgrade {
3340: my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
3341: my ($uname,$udom) = split(/:/,$student);
3342: my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
3343: my %aggregates = ();
3344: my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
3345: '<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
3346: "\n".$ctr.' </td><td> '.
3347: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
3348: '\');" target="_self">'.$fullname.'</a> '.
3349: '<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
3350: $student=~s/:/_/; # colon doen't work in javascript for names
3351: foreach my $apart (@$parts) {
3352: my ($part,$type) = &split_part_type($apart);
3353: my $score=$record{"resource.$part.$type"};
3354: $result.='<td align="center">';
3355: my ($aggtries,$totaltries);
3356: unless (exists($aggregates{$part})) {
3357: $totaltries = $record{'resource.'.$part.'.tries'};
3358:
3359: $aggtries = $totaltries;
3360: if ($$last_resets{$part}) {
3361: $aggtries = &get_num_tries(\%record,$$last_resets{$part},
3362: $part);
3363: }
3364: $result.='<input type="hidden" name="'.
3365: 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
3366: $result.='<input type="hidden" name="'.
3367: 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
3368: $aggregates{$part} = 1;
3369: }
3370: if ($type eq 'awarded') {
3371: my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
3372: $result.='<input type="hidden" name="'.
3373: 'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
3374: $result.='<input type="text" name="'.
3375: 'GD_'.$student.'_'.$part.'_awarded" '.
3376: 'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
3377: '\')" value="'.$pts.'" size="4" /></td>'."\n";
3378: } elsif ($type eq 'solved') {
3379: my ($status,$foo)=split(/_/,$score,2);
3380: $status = 'nothing' if ($status eq '');
3381: $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
3382: $part.'_solved_s" value="'.$status.'" />'."\n";
3383: $result.=' <select name="'.
3384: 'GD_'.$student.'_'.$part.'_solved" '.
3385: 'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
3386: $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>'
3387: : '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
3388: $result.='<option value="reset status">'.&mt('reset status').'</option>';
3389: $result.="</select> </td>\n";
3390: } else {
3391: $result.='<input type="hidden" name="'.
3392: 'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
3393: "\n";
3394: $result.='<input type="text" name="'.
3395: 'GD_'.$student.'_'.$part.'_'.$type.'" '.
3396: 'value="'.$score.'" size="4" /></td>'."\n";
3397: }
3398: }
3399: $result.=&Apache::loncommon::end_data_table_row();
3400: return $result;
3401: }
3402:
3403: #--- change scores for all the students in a section/class
3404: # record does not get update if unchanged
3405: sub editgrades {
3406: my ($request) = @_;
3407:
3408: my $symb=&get_symb($request);
3409: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3410: my $title='<h2>'.&mt('Current Grade Status').'</h2>';
3411: $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
3412: $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
3413:
3414: my $result= &Apache::loncommon::start_data_table().
3415: &Apache::loncommon::start_data_table_header_row().
3416: '<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
3417: '<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
3418: my %scoreptr = (
3419: 'correct' =>'correct_by_override',
3420: 'incorrect'=>'incorrect_by_override',
3421: 'excused' =>'excused',
3422: 'ungraded' =>'ungraded_attempted',
3423: 'nothing' => '',
3424: );
3425: my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
3426:
3427: my (@partid);
3428: my %weight = ();
3429: my %columns = ();
3430: my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
3431:
3432: my (@parts) = sort(&getpartlist($symb));
3433: my $header;
3434: while ($ctr < $env{'form.totalparts'}) {
3435: my $partid = $env{'form.partid_'.$ctr};
3436: push @partid,$partid;
3437: $weight{$partid} = $env{'form.weight_'.$partid};
3438: $ctr++;
3439: }
3440: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3441: foreach my $partid (@partid) {
3442: $header .= '<th align="center">'.&mt('Old Score').'</th>'.
3443: '<th align="center">'.&mt('New Score').'</th>';
3444: $columns{$partid}=2;
3445: foreach my $stores (@parts) {
3446: my ($part,$type) = &split_part_type($stores);
3447: if ($part !~ m/^\Q$partid\E/) { next;}
3448: if ($type eq 'awarded' || $type eq 'solved') { next; }
3449: my $display=&Apache::lonnet::metadata($url,$stores.'.display');
3450: $display =~ s/\[Part: (\w)+\]//;
3451: $display =~ s/Number of Attempts/Tries/;
3452: $header .= '<th align="center">'.&mt('Old '.$display).'</th>'.
3453: '<th align="center">'.&mt('New '.$display).'</th>';
3454: $columns{$partid}+=2;
3455: }
3456: }
3457: foreach my $partid (@partid) {
3458: my $display_part=&get_display_part($partid,$symb);
3459: $result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
3460: &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
3461: '</th>';
3462:
3463: }
3464: $result .= &Apache::loncommon::end_data_table_header_row().
3465: &Apache::loncommon::start_data_table_header_row().
3466: $header.
3467: &Apache::loncommon::end_data_table_header_row();
3468: my @noupdate;
3469: my ($updateCtr,$noupdateCtr) = (1,1);
3470: for ($i=0; $i<$env{'form.total'}; $i++) {
3471: my $line;
3472: my $user = $env{'form.ctr'.$i};
3473: my ($uname,$udom)=split(/:/,$user);
3474: my %newrecord;
3475: my $updateflag = 0;
3476: $line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
3477: my $usec=$classlist->{"$uname:$udom"}[5];
3478: if (!&canmodify($usec)) {
3479: my $numcols=scalar(@partid)*4+2;
3480: push(@noupdate,
3481: $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
3482: &mt('Not allowed to modify student')."</span></td></tr>");
3483: next;
3484: }
3485: my %aggregate = ();
3486: my $aggregateflag = 0;
3487: $user=~s/:/_/; # colon doen't work in javascript for names
3488: foreach (@partid) {
3489: my $old_aw = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
3490: my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
3491: my $old_part = $old_aw eq '' ? '' : $old_part_pcr;
3492: my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
3493: my $awarded = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
3494: my $pcr = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
3495: my $partial = $awarded eq '' ? '' : $pcr;
3496: my $score;
3497: if ($partial eq '') {
3498: $score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
3499: } elsif ($partial > 0) {
3500: $score = 'correct_by_override';
3501: } elsif ($partial == 0) {
3502: $score = 'incorrect_by_override';
3503: }
3504: my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
3505: $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
3506:
3507: $newrecord{'resource.'.$_.'.regrader'}=
3508: "$env{'user.name'}:$env{'user.domain'}";
3509: if ($dropMenu eq 'reset status' &&
3510: $old_score ne '') { # ignore if no previous attempts => nothing to reset
3511: $newrecord{'resource.'.$_.'.tries'} = '';
3512: $newrecord{'resource.'.$_.'.solved'} = '';
3513: $newrecord{'resource.'.$_.'.award'} = '';
3514: $newrecord{'resource.'.$_.'.awarded'} = '';
3515: $updateflag = 1;
3516: if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
3517: my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
3518: my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
3519: my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
3520: &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
3521: $aggregateflag = 1;
3522: }
3523: } elsif (!($old_part eq $partial && $old_score eq $score)) {
3524: $updateflag = 1;
3525: $newrecord{'resource.'.$_.'.awarded'} = $partial if $partial ne '';
3526: $newrecord{'resource.'.$_.'.solved'} = $score;
3527: $rec_update++;
3528: }
3529:
3530: $line .= '<td align="center">'.$old_aw.' </td>'.
3531: '<td align="center">'.$awarded.
3532: ($score eq 'excused' ? $score : '').' </td>';
3533:
3534:
3535: my $partid=$_;
3536: foreach my $stores (@parts) {
3537: my ($part,$type) = &split_part_type($stores);
3538: if ($part !~ m/^\Q$partid\E/) { next;}
3539: if ($type eq 'awarded' || $type eq 'solved') { next; }
3540: my $old_aw = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
3541: my $awarded = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
3542: if ($awarded ne '' && $awarded ne $old_aw) {
3543: $newrecord{'resource.'.$part.'.'.$type}= $awarded;
3544: $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
3545: $updateflag=1;
3546: }
3547: $line .= '<td align="center">'.$old_aw.' </td>'.
3548: '<td align="center">'.$awarded.' </td>';
3549: }
3550: }
3551: $line.="\n";
3552:
3553: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3554: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3555:
3556: if ($updateflag) {
3557: $count++;
3558: &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
3559: $udom,$uname);
3560:
3561: if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
3562: $cnum,$udom,$uname)) {
3563: # need to figure out if should be in queue.
3564: my %record =
3565: &Apache::lonnet::restore($symb,$env{'request.course.id'},
3566: $udom,$uname);
3567: my $all_graded = 1;
3568: my $none_graded = 1;
3569: foreach my $part (@parts) {
3570: if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
3571: $all_graded = 0;
3572: } else {
3573: $none_graded = 0;
3574: }
3575: }
3576:
3577: if ($all_graded || $none_graded) {
3578: &Apache::bridgetask::remove_from_queue('gradingqueue',
3579: $symb,$cdom,$cnum,
3580: $udom,$uname);
3581: }
3582: }
3583:
3584: $result.=&Apache::loncommon::start_data_table_row().
3585: '<td align="right"> '.$updateCtr.' </td>'.$line.
3586: &Apache::loncommon::end_data_table_row();
3587: $updateCtr++;
3588: } else {
3589: push(@noupdate,
3590: '<td align="right"> '.$noupdateCtr.' </td>'.$line);
3591: $noupdateCtr++;
3592: }
3593: if ($aggregateflag) {
3594: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
3595: $cdom,$cnum);
3596: }
3597: }
3598: if (@noupdate) {
3599: # my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
3600: my $numcols=scalar(@partid)*4+2;
3601: $result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
3602: '<td align="center" colspan="'.$numcols.'">'.
3603: &mt('No Changes Occurred For the Students Below').
3604: '</td>'.
3605: &Apache::loncommon::end_data_table_row();
3606: foreach my $line (@noupdate) {
3607: $result.=
3608: &Apache::loncommon::start_data_table_row().
3609: $line.
3610: &Apache::loncommon::end_data_table_row();
3611: }
3612: }
3613: $result .= &Apache::loncommon::end_data_table().
3614: &show_grading_menu_form($symb);
3615: my $msg = '<p><b>'.
3616: &mt('Number of records updated = [_1] for [quant,_2,student].',
3617: $rec_update,$count).'</b><br />'.
3618: '<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
3619: '</b></p>';
3620: return $title.$msg.$result;
3621: }
3622:
3623: sub split_part_type {
3624: my ($partstr) = @_;
3625: my ($temp,@allparts)=split(/_/,$partstr);
3626: my $type=pop(@allparts);
3627: my $part=join('_',@allparts);
3628: return ($part,$type);
3629: }
3630:
3631: #------------- end of section for handling grading by section/class ---------
3632: #
3633: #----------------------------------------------------------------------------
3634:
3635:
3636: #----------------------------------------------------------------------------
3637: #
3638: #-------------------------- Next few routines handles grading by csv upload
3639: #
3640: #--- Javascript to handle csv upload
3641: sub csvupload_javascript_reverse_associate {
3642: my $error1=&mt('You need to specify the username or ID');
3643: my $error2=&mt('You need to specify at least one grading field');
3644: return(<<ENDPICK);
3645: function verify(vf) {
3646: var foundsomething=0;
3647: var founduname=0;
3648: var foundID=0;
3649: for (i=0;i<=vf.nfields.value;i++) {
3650: tw=eval('vf.f'+i+'.selectedIndex');
3651: if (i==0 && tw!=0) { foundID=1; }
3652: if (i==1 && tw!=0) { founduname=1; }
3653: if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
3654: }
3655: if (founduname==0 && foundID==0) {
3656: alert('$error1');
3657: return;
3658: }
3659: if (foundsomething==0) {
3660: alert('$error2');
3661: return;
3662: }
3663: vf.submit();
3664: }
3665: function flip(vf,tf) {
3666: var nw=eval('vf.f'+tf+'.selectedIndex');
3667: var i;
3668: for (i=0;i<=vf.nfields.value;i++) {
3669: //can not pick the same destination field for both name and domain
3670: if (((i ==0)||(i ==1)) &&
3671: ((tf==0)||(tf==1)) &&
3672: (i!=tf) &&
3673: (eval('vf.f'+i+'.selectedIndex')==nw)) {
3674: eval('vf.f'+i+'.selectedIndex=0;')
3675: }
3676: }
3677: }
3678: ENDPICK
3679: }
3680:
3681: sub csvupload_javascript_forward_associate {
3682: my $error1=&mt('You need to specify the username or ID');
3683: my $error2=&mt('You need to specify at least one grading field');
3684: return(<<ENDPICK);
3685: function verify(vf) {
3686: var foundsomething=0;
3687: var founduname=0;
3688: var foundID=0;
3689: for (i=0;i<=vf.nfields.value;i++) {
3690: tw=eval('vf.f'+i+'.selectedIndex');
3691: if (tw==1) { foundID=1; }
3692: if (tw==2) { founduname=1; }
3693: if (tw>3) { foundsomething=1; }
3694: }
3695: if (founduname==0 && foundID==0) {
3696: alert('$error1');
3697: return;
3698: }
3699: if (foundsomething==0) {
3700: alert('$error2');
3701: return;
3702: }
3703: vf.submit();
3704: }
3705: function flip(vf,tf) {
3706: var nw=eval('vf.f'+tf+'.selectedIndex');
3707: var i;
3708: //can not pick the same destination field twice
3709: for (i=0;i<=vf.nfields.value;i++) {
3710: if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
3711: eval('vf.f'+i+'.selectedIndex=0;')
3712: }
3713: }
3714: }
3715: ENDPICK
3716: }
3717:
3718: sub csvuploadmap_header {
3719: my ($request,$symb,$datatoken,$distotal)= @_;
3720: my $javascript;
3721: if ($env{'form.upfile_associate'} eq 'reverse') {
3722: $javascript=&csvupload_javascript_reverse_associate();
3723: } else {
3724: $javascript=&csvupload_javascript_forward_associate();
3725: }
3726:
3727: my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
3728: my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
3729: my $ignore=&mt('Ignore First Line');
3730: $symb = &Apache::lonenc::check_encrypt($symb);
3731: $request->print(<<ENDPICK);
3732: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3733: <h3><span class="LC_info">Uploading Class Grades</span></h3>
3734: $result
3735: <hr />
3736: <h3>Identify fields</h3>
3737: Total number of records found in file: $distotal <hr />
3738: Enter as many fields as you can. The system will inform you and bring you back
3739: to this page if the data selected is insufficient to run your class.<hr />
3740: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
3741: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
3742: <input type="hidden" name="associate" value="" />
3743: <input type="hidden" name="phase" value="three" />
3744: <input type="hidden" name="datatoken" value="$datatoken" />
3745: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
3746: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
3747: <input type="hidden" name="upfile_associate"
3748: value="$env{'form.upfile_associate'}" />
3749: <input type="hidden" name="symb" value="$symb" />
3750: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
3751: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
3752: <input type="hidden" name="command" value="csvuploadoptions" />
3753: <hr />
3754: <script type="text/javascript" language="Javascript">
3755: $javascript
3756: </script>
3757: ENDPICK
3758: return '';
3759:
3760: }
3761:
3762: sub csvupload_fields {
3763: my ($symb) = @_;
3764: my (@parts) = &getpartlist($symb);
3765: my @fields=(['ID','Student ID'],
3766: ['username','Student Username'],
3767: ['domain','Student Domain']);
3768: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3769: foreach my $part (sort(@parts)) {
3770: my @datum;
3771: my $display=&Apache::lonnet::metadata($url,$part.'.display');
3772: my $name=$part;
3773: if (!$display) { $display = $name; }
3774: @datum=($name,$display);
3775: if ($name=~/^stores_(.*)_awarded/) {
3776: push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
3777: }
3778: push(@fields,\@datum);
3779: }
3780: return (@fields);
3781: }
3782:
3783: sub csvuploadmap_footer {
3784: my ($request,$i,$keyfields) =@_;
3785: $request->print(<<ENDPICK);
3786: </table>
3787: <input type="hidden" name="nfields" value="$i" />
3788: <input type="hidden" name="keyfields" value="$keyfields" />
3789: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
3790: </form>
3791: ENDPICK
3792: }
3793:
3794: sub checkforfile_js {
3795: my $result =<<CSVFORMJS;
3796: <script type="text/javascript" language="javascript">
3797: function checkUpload(formname) {
3798: if (formname.upfile.value == "") {
3799: alert("Please use the browse button to select a file from your local directory.");
3800: return false;
3801: }
3802: formname.submit();
3803: }
3804: </script>
3805: CSVFORMJS
3806: return $result;
3807: }
3808:
3809: sub upcsvScores_form {
3810: my ($request) = shift;
3811: my ($symb)=&get_symb($request);
3812: if (!$symb) {return '';}
3813: my $result=&checkforfile_js();
3814: $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
3815: my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
3816: $result.=$table;
3817: $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
3818: $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
3819: $result.=' <b>'.&mt('Specify a file containing the class scores for current resource').
3820: '.</b></td></tr>'."\n";
3821: $result.='<tr bgcolor=#ffffe6><td>'."\n";
3822: my $upload=&mt("Upload Scores");
3823: my $upfile_select=&Apache::loncommon::upfile_select_html();
3824: my $ignore=&mt('Ignore First Line');
3825: $symb = &Apache::lonenc::check_encrypt($symb);
3826: $result.=<<ENDUPFORM;
3827: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3828: <input type="hidden" name="symb" value="$symb" />
3829: <input type="hidden" name="command" value="csvuploadmap" />
3830: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
3831: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
3832: $upfile_select
3833: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
3834: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
3835: </form>
3836: ENDUPFORM
3837: $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
3838: &mt("How do I create a CSV file from a spreadsheet"))
3839: .'</td></tr></table>'."\n";
3840: $result.='</td></tr></table><br /><br />'."\n";
3841: $result.=&show_grading_menu_form($symb);
3842: return $result;
3843: }
3844:
3845:
3846: sub csvuploadmap {
3847: my ($request)= @_;
3848: my ($symb)=&get_symb($request);
3849: if (!$symb) {return '';}
3850:
3851: my $datatoken;
3852: if (!$env{'form.datatoken'}) {
3853: $datatoken=&Apache::loncommon::upfile_store($request);
3854: } else {
3855: $datatoken=$env{'form.datatoken'};
3856: &Apache::loncommon::load_tmp_file($request);
3857: }
3858: my @records=&Apache::loncommon::upfile_record_sep();
3859: if ($env{'form.noFirstLine'}) { shift(@records); }
3860: &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
3861: my ($i,$keyfields);
3862: if (@records) {
3863: my @fields=&csvupload_fields($symb);
3864:
3865: if ($env{'form.upfile_associate'} eq 'reverse') {
3866: &Apache::loncommon::csv_print_samples($request,\@records);
3867: $i=&Apache::loncommon::csv_print_select_table($request,\@records,
3868: \@fields);
3869: foreach (@fields) { $keyfields.=$_->[0].','; }
3870: chop($keyfields);
3871: } else {
3872: unshift(@fields,['none','']);
3873: $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
3874: \@fields);
3875: foreach my $rec (@records) {
3876: my %temp = &Apache::loncommon::record_sep($rec);
3877: if (%temp) {
3878: $keyfields=join(',',sort(keys(%temp)));
3879: last;
3880: }
3881: }
3882: }
3883: }
3884: &csvuploadmap_footer($request,$i,$keyfields);
3885: $request->print(&show_grading_menu_form($symb));
3886:
3887: return '';
3888: }
3889:
3890: sub csvuploadoptions {
3891: my ($request)= @_;
3892: my ($symb)=&get_symb($request);
3893: my $checked=(($env{'form.noFirstLine'})?'1':'0');
3894: my $ignore=&mt('Ignore First Line');
3895: $request->print(<<ENDPICK);
3896: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3897: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
3898: <input type="hidden" name="command" value="csvuploadassign" />
3899: <!--
3900: <p>
3901: <label>
3902: <input type="checkbox" name="show_full_results" />
3903: Show a table of all changes
3904: </label>
3905: </p>
3906: -->
3907: <p>
3908: <label>
3909: <input type="checkbox" name="overwite_scores" checked="checked" />
3910: Overwrite any existing score
3911: </label>
3912: </p>
3913: ENDPICK
3914: my %fields=&get_fields();
3915: if (!defined($fields{'domain'})) {
3916: my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
3917: $request->print("\n<p> Users are in domain: ".$domform."</p>\n");
3918: }
3919: foreach my $key (sort(keys(%env))) {
3920: if ($key !~ /^form\.(.*)$/) { next; }
3921: my $cleankey=$1;
3922: if ($cleankey eq 'command') { next; }
3923: $request->print('<input type="hidden" name="'.$cleankey.
3924: '" value="'.$env{$key}.'" />'."\n");
3925: }
3926: # FIXME do a check for any duplicated user ids...
3927: # FIXME do a check for any invalid user ids?...
3928: $request->print('<input type="submit" value="Assign Grades" /><br />
3929: <hr /></form>'."\n");
3930: $request->print(&show_grading_menu_form($symb));
3931: return '';
3932: }
3933:
3934: sub get_fields {
3935: my %fields;
3936: my @keyfields = split(/\,/,$env{'form.keyfields'});
3937: for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
3938: if ($env{'form.upfile_associate'} eq 'reverse') {
3939: if ($env{'form.f'.$i} ne 'none') {
3940: $fields{$keyfields[$i]}=$env{'form.f'.$i};
3941: }
3942: } else {
3943: if ($env{'form.f'.$i} ne 'none') {
3944: $fields{$env{'form.f'.$i}}=$keyfields[$i];
3945: }
3946: }
3947: }
3948: return %fields;
3949: }
3950:
3951: sub csvuploadassign {
3952: my ($request)= @_;
3953: my ($symb)=&get_symb($request);
3954: if (!$symb) {return '';}
3955: my $error_msg = '';
3956: &Apache::loncommon::load_tmp_file($request);
3957: my @gradedata = &Apache::loncommon::upfile_record_sep();
3958: if ($env{'form.noFirstLine'}) { shift(@gradedata); }
3959: my %fields=&get_fields();
3960: $request->print('<h3>Assigning Grades</h3>');
3961: my $courseid=$env{'request.course.id'};
3962: my ($classlist) = &getclasslist('all',0);
3963: my @notallowed;
3964: my @skipped;
3965: my $countdone=0;
3966: foreach my $grade (@gradedata) {
3967: my %entries=&Apache::loncommon::record_sep($grade);
3968: my $domain;
3969: if ($entries{$fields{'domain'}}) {
3970: $domain=$entries{$fields{'domain'}};
3971: } else {
3972: $domain=$env{'form.default_domain'};
3973: }
3974: $domain=~s/\s//g;
3975: my $username=$entries{$fields{'username'}};
3976: $username=~s/\s//g;
3977: if (!$username) {
3978: my $id=$entries{$fields{'ID'}};
3979: $id=~s/\s//g;
3980: my %ids=&Apache::lonnet::idget($domain,$id);
3981: $username=$ids{$id};
3982: }
3983: if (!exists($$classlist{"$username:$domain"})) {
3984: my $id=$entries{$fields{'ID'}};
3985: $id=~s/\s//g;
3986: if ($id) {
3987: push(@skipped,"$id:$domain");
3988: } else {
3989: push(@skipped,"$username:$domain");
3990: }
3991: next;
3992: }
3993: my $usec=$classlist->{"$username:$domain"}[5];
3994: if (!&canmodify($usec)) {
3995: push(@notallowed,"$username:$domain");
3996: next;
3997: }
3998: my %points;
3999: my %grades;
4000: foreach my $dest (keys(%fields)) {
4001: if ($dest eq 'ID' || $dest eq 'username' ||
4002: $dest eq 'domain') { next; }
4003: if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
4004: if ($dest=~/stores_(.*)_points/) {
4005: my $part=$1;
4006: my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
4007: $symb,$domain,$username);
4008: if ($wgt) {
4009: $entries{$fields{$dest}}=~s/\s//g;
4010: my $pcr=$entries{$fields{$dest}} / $wgt;
4011: my $award=($pcr == 0) ? 'incorrect_by_override'
4012: : 'correct_by_override';
4013: $grades{"resource.$part.awarded"}=$pcr;
4014: $grades{"resource.$part.solved"}=$award;
4015: $points{$part}=1;
4016: } else {
4017: $error_msg = "<br />" .
4018: &mt("Some point values were assigned"
4019: ." for problems with a weight "
4020: ."of zero. These values were "
4021: ."ignored.");
4022: }
4023: } else {
4024: if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
4025: if ($dest=~/stores_(.*)_solved/) { if ($points{$1}) {next;} }
4026: my $store_key=$dest;
4027: $store_key=~s/^stores/resource/;
4028: $store_key=~s/_/\./g;
4029: $grades{$store_key}=$entries{$fields{$dest}};
4030: }
4031: }
4032: if (! %grades) { push(@skipped,"$username:$domain no data to save"); }
4033: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
4034: my $result=&Apache::lonnet::cstore(\%grades,$symb,
4035: $env{'request.course.id'},
4036: $domain,$username);
4037: if ($result eq 'ok') {
4038: $request->print('.');
4039: } else {
4040: $request->print("<p>
4041: <span class=\"LC_error\">
4042: Failed to save student $username:$domain.
4043: Message when trying to save was ($result)
4044: </span>
4045: </p>" );
4046: }
4047: $request->rflush();
4048: $countdone++;
4049: }
4050: $request->print("<br />Saved $countdone students\n");
4051: if (@skipped) {
4052: $request->print('<p><h4><b>Skipped Students</b></h4></p>');
4053: foreach my $student (@skipped) { $request->print("$student<br />\n"); }
4054: }
4055: if (@notallowed) {
4056: $request->print('<p><span class="LC_error">Students Not Allowed to Modify</span></p>');
4057: foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
4058: }
4059: $request->print("<br />\n");
4060: $request->print(&show_grading_menu_form($symb));
4061: return $error_msg;
4062: }
4063: #------------- end of section for handling csv file upload ---------
4064: #
4065: #-------------------------------------------------------------------
4066: #
4067: #-------------- Next few routines handle grading by page/sequence
4068: #
4069: #--- Select a page/sequence and a student to grade
4070: sub pickStudentPage {
4071: my ($request) = shift;
4072:
4073: $request->print(<<LISTJAVASCRIPT);
4074: <script type="text/javascript" language="javascript">
4075:
4076: function checkPickOne(formname) {
4077: if (radioSelection(formname.student) == null) {
4078: alert("Please select the student you wish to grade.");
4079: return;
4080: }
4081: ptr = pullDownSelection(formname.selectpage);
4082: formname.page.value = formname["page"+ptr].value;
4083: formname.title.value = formname["title"+ptr].value;
4084: formname.submit();
4085: }
4086:
4087: </script>
4088: LISTJAVASCRIPT
4089: &commonJSfunctions($request);
4090: my ($symb) = &get_symb($request);
4091: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4092: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4093: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4094:
4095: my $result='<h3><span class="LC_info"> '.
4096: &mt('Manual Grading by Page or Sequence').'</span></h3>';
4097:
4098: $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
4099: my ($titles,$symbx) = &getSymbMap();
4100: my ($curpage) =&Apache::lonnet::decode_symb($symb);
4101: # my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb);
4102: # my $type=($curpage =~ /\.(page|sequence)/);
4103: my $select = '<select name="selectpage">'."\n";
4104: my $ctr=0;
4105: foreach (@$titles) {
4106: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4107: $select.='<option value="'.$ctr.'" '.
4108: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
4109: '>'.$showtitle.'</option>'."\n";
4110: $ctr++;
4111: }
4112: $select.= '</select>';
4113: $result.=&mt(' <b>Problems from:</b> [_1]',$select)."<br />\n";
4114:
4115: $ctr=0;
4116: foreach (@$titles) {
4117: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4118: $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
4119: $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
4120: $ctr++;
4121: }
4122: $result.='<input type="hidden" name="page" />'."\n".
4123: '<input type="hidden" name="title" />'."\n";
4124:
4125: my $options =
4126: '<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
4127: '<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
4128: $result.=' '.&mt('<b>View Problems Text: </b> [_1]',$options);
4129:
4130: $options =
4131: '<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
4132: '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
4133: '<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
4134: $result.=' '.&mt('<b>Submission Details: </b>[_1]',$options);
4135:
4136: $result.=&build_section_inputs();
4137: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
4138: $result.='<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
4139: '<input type="hidden" name="command" value="displayPage" />'."\n".
4140: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
4141: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
4142:
4143: $result.=' '.&mt('<b>Use CODE: [_1] </b>',
4144: '<input type="text" name="CODE" value="" />').
4145: '<br />'."\n";
4146:
4147: $result.=' <input type="button" '.
4148: 'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next->').'" /><br />'."\n";
4149:
4150: $request->print($result);
4151:
4152: my $studentTable.=' <b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
4153: &Apache::loncommon::start_data_table().
4154: &Apache::loncommon::start_data_table_header_row().
4155: '<th align="right"> '.&mt('No.').'</th>'.
4156: '<th>'.&nameUserString('header').'</th>'.
4157: '<th align="right"> '.&mt('No.').'</th>'.
4158: '<th>'.&nameUserString('header').'</th>'.
4159: &Apache::loncommon::end_data_table_header_row();
4160:
4161: my (undef,undef,$fullname) = &getclasslist($getsec,'1');
4162: my $ptr = 1;
4163: foreach my $student (sort
4164: {
4165: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
4166: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
4167: }
4168: return $a cmp $b;
4169: } (keys(%$fullname))) {
4170: my ($uname,$udom) = split(/:/,$student);
4171: $studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
4172: : '</td>');
4173: $studentTable.='<td align="right">'.$ptr.' </td>';
4174: $studentTable.='<td> <label><input type="radio" name="student" value="'.$student.'" /> '
4175: .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
4176: $studentTable.=
4177: ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row()
4178: : '');
4179: $ptr++;
4180: }
4181: if ($ptr%2 == 0) {
4182: $studentTable.='</td><td> </td><td> </td>'.
4183: &Apache::loncommon::end_data_table_row();
4184: }
4185: $studentTable.=&Apache::loncommon::end_data_table()."\n";
4186: $studentTable.='<input type="button" '.
4187: 'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next->').'" /></form>'."\n";
4188:
4189: $studentTable.=&show_grading_menu_form($symb);
4190: $request->print($studentTable);
4191:
4192: return '';
4193: }
4194:
4195: sub getSymbMap {
4196: my $navmap = Apache::lonnavmaps::navmap->new();
4197:
4198: my %symbx = ();
4199: my @titles = ();
4200: my $minder = 0;
4201:
4202: # Gather every sequence that has problems.
4203: my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
4204: 1,0,1);
4205: for my $sequence ($navmap->getById('0.0'), @sequences) {
4206: if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
4207: my $title = $minder.'.'.
4208: &HTML::Entities::encode($sequence->compTitle(),'"\'&');
4209: push(@titles, $title); # minder in case two titles are identical
4210: $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
4211: $minder++;
4212: }
4213: }
4214: return \@titles,\%symbx;
4215: }
4216:
4217: #
4218: #--- Displays a page/sequence w/wo problems, w/wo submissions
4219: sub displayPage {
4220: my ($request) = shift;
4221:
4222: my ($symb) = &get_symb($request);
4223: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4224: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4225: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4226: my $pageTitle = $env{'form.page'};
4227: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
4228: my ($uname,$udom) = split(/:/,$env{'form.student'});
4229: my $usec=$classlist->{$env{'form.student'}}[5];
4230:
4231: #need to make sure we have the correct data for later EXT calls,
4232: #thus invalidate the cache
4233: &Apache::lonnet::devalidatecourseresdata(
4234: $env{'course.'.$env{'request.course.id'}.'.num'},
4235: $env{'course.'.$env{'request.course.id'}.'.domain'});
4236: &Apache::lonnet::clear_EXT_cache_status();
4237:
4238: if (!&canview($usec)) {
4239: $request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
4240: $request->print(&show_grading_menu_form($symb));
4241: return;
4242: }
4243: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
4244: $result.='<h3> '.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
4245: '</h3>'."\n";
4246: if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
4247: $result.='<h3> '.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
4248: } else {
4249: delete($env{'form.CODE'});
4250: }
4251: &sub_page_js($request);
4252: $request->print($result);
4253:
4254: my $navmap = Apache::lonnavmaps::navmap->new();
4255: my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
4256: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
4257: if (!$map) {
4258: $request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
4259: $request->print(&show_grading_menu_form($symb));
4260: return;
4261: }
4262: my $iterator = $navmap->getIterator($map->map_start(),
4263: $map->map_finish());
4264:
4265: my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
4266: '<input type="hidden" name="command" value="gradeByPage" />'."\n".
4267: '<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
4268: '<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
4269: '<input type="hidden" name="page" value="'.$pageTitle.'" />'."\n".
4270: '<input type="hidden" name="title" value="'.$env{'form.title'}.'" />'."\n".
4271: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
4272: '<input type="hidden" name="overRideScore" value="no" />'."\n".
4273: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
4274:
4275: if (defined($env{'form.CODE'})) {
4276: $studentTable.=
4277: '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
4278: }
4279: my $checkIcon = '<img alt="'.&mt('Check Mark').
4280: '" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
4281:
4282: $studentTable.=' '.&mt('<b>Note:</b> Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon)."\n".
4283: &Apache::loncommon::start_data_table().
4284: &Apache::loncommon::start_data_table_header_row().
4285: '<th align="center"> Prob. </th>'.
4286: '<th> '.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
4287: &Apache::loncommon::end_data_table_header_row();
4288:
4289: &Apache::lonxml::clear_problem_counter();
4290: my ($depth,$question,$prob) = (1,1,1);
4291: $iterator->next(); # skip the first BEGIN_MAP
4292: my $curRes = $iterator->next(); # for "current resource"
4293: while ($depth > 0) {
4294: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
4295: if($curRes == $iterator->END_MAP) { $depth--; }
4296:
4297: if (ref($curRes) && $curRes->is_problem()) {
4298: my $parts = $curRes->parts();
4299: my $title = $curRes->compTitle();
4300: my $symbx = $curRes->symb();
4301: $studentTable.=
4302: &Apache::loncommon::start_data_table_row().
4303: '<td align="center" valign="top" >'.$prob.
4304: (scalar(@{$parts}) == 1 ? ''
4305: : '<br />('.&mt('[_1] parts)',
4306: scalar(@{$parts}))
4307: ).
4308: '</td>';
4309: $studentTable.='<td valign="top">';
4310: my %form = ('CODE' => $env{'form.CODE'},);
4311: if ($env{'form.vProb'} eq 'yes' ) {
4312: $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
4313: undef,'both',\%form);
4314: } else {
4315: my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
4316: $companswer =~ s|<form(.*?)>||g;
4317: $companswer =~ s|</form>||g;
4318: # while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
4319: # $companswer =~ s/$1/ /ms;
4320: # $request->print('match='.$1."<br />\n");
4321: # }
4322: # $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
4323: $studentTable.=' <b>'.$title.'</b> <br /> '.&mt('<b>Correct answer:</b><br />[_1]',$companswer);
4324: }
4325:
4326: my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
4327:
4328: if ($env{'form.lastSub'} eq 'datesub') {
4329: if ($record{'version'} eq '') {
4330: $studentTable.='<br /> <span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
4331: } else {
4332: my %responseType = ();
4333: foreach my $partid (@{$parts}) {
4334: my @responseIds =$curRes->responseIds($partid);
4335: my @responseType =$curRes->responseType($partid);
4336: my %responseIds;
4337: for (my $i=0;$i<=$#responseIds;$i++) {
4338: $responseIds{$responseIds[$i]}=$responseType[$i];
4339: }
4340: $responseType{$partid} = \%responseIds;
4341: }
4342: $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
4343:
4344: }
4345: } elsif ($env{'form.lastSub'} eq 'all') {
4346: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
4347: $studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
4348: $env{'request.course.id'},
4349: '','.submission');
4350:
4351: }
4352: if (&canmodify($usec)) {
4353: foreach my $partid (@{$parts}) {
4354: $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
4355: $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
4356: $question++;
4357: }
4358: $prob++;
4359: }
4360: $studentTable.='</td></tr>';
4361:
4362: }
4363: $curRes = $iterator->next();
4364: }
4365:
4366: $studentTable.='</table>'."\n".
4367: '<input type="button" value="'.&mt('Save').'" '.
4368: 'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
4369: '</form>'."\n";
4370: $studentTable.=&show_grading_menu_form($symb);
4371: $request->print($studentTable);
4372:
4373: return '';
4374: }
4375:
4376: sub displaySubByDates {
4377: my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
4378: my $isCODE=0;
4379: my $isTask = ($symb =~/\.task$/);
4380: if (exists($record->{'resource.CODE'})) { $isCODE=1; }
4381: my $studentTable=&Apache::loncommon::start_data_table().
4382: &Apache::loncommon::start_data_table_header_row().
4383: '<th>'.&mt('Date/Time').'</th>'.
4384: ($isCODE?'<th>'.&mt('CODE').'</th>':'').
4385: '<th>'.&mt('Submission').'</th>'.
4386: '<th>'.&mt('Status').'</th>'.
4387: &Apache::loncommon::end_data_table_header_row();
4388: my ($version);
4389: my %mark;
4390: my %orders;
4391: $mark{'correct_by_student'} = $checkIcon;
4392: if (!exists($$record{'1:timestamp'})) {
4393: return '<br /> <span class="LC_warning">'.&mt('Nothing submitted - no attempts').'</span><br />';
4394: }
4395:
4396: my $interaction;
4397: for ($version=1;$version<=$$record{'version'};$version++) {
4398: my $timestamp =
4399: &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
4400: if (exists($$record{$version.':resource.0.version'})) {
4401: $interaction = $$record{$version.':resource.0.version'};
4402: }
4403:
4404: my $where = ($isTask ? "$version:resource.$interaction"
4405: : "$version:resource");
4406: $studentTable.=&Apache::loncommon::start_data_table_row().
4407: '<td>'.$timestamp.'</td>';
4408: if ($isCODE) {
4409: $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
4410: }
4411: my @versionKeys = split(/\:/,$$record{$version.':keys'});
4412: my @displaySub = ();
4413: foreach my $partid (@{$parts}) {
4414: my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
4415: : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
4416:
4417:
4418: # next if ($$record{"$version:resource.$partid.solved"} eq '');
4419: my $display_part=&get_display_part($partid,$symb);
4420: foreach my $matchKey (@matchKey) {
4421: if (exists($$record{$version.':'.$matchKey}) &&
4422: $$record{$version.':'.$matchKey} ne '') {
4423:
4424: my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
4425: : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
4426: $displaySub[0].='<b>'.&mt('Part:').'</b> '.$display_part.' ';
4427: $displaySub[0].='<span class="LC_internal_info">('.&mt('ID').' '.
4428: $responseId.')</span> <b>';
4429: if ($$record{"$where.$partid.tries"} eq '') {
4430: $displaySub[0].=&mt('Trial not counted');
4431: } else {
4432: $displaySub[0].=&mt('Trial [_1]',
4433: $$record{"$where.$partid.tries"});
4434: }
4435: my $responseType=($isTask ? 'Task'
4436: : $responseType->{$partid}->{$responseId});
4437: if (!exists($orders{$partid})) { $orders{$partid}={}; }
4438: if (!exists($orders{$partid}->{$responseId})) {
4439: $orders{$partid}->{$responseId}=
4440: &get_order($partid,$responseId,$symb,$uname,$udom);
4441: }
4442: $displaySub[0].='</b> '.
4443: &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
4444: }
4445: }
4446: if (exists($$record{"$where.$partid.checkedin"})) {
4447: $displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
4448: $$record{"$where.$partid.checkedin"},
4449: $$record{"$where.$partid.checkedin.slot"}).
4450: '<br />';
4451: }
4452: if (exists $$record{"$where.$partid.award"}) {
4453: $displaySub[1].='<b>'.&mt('Part:').'</b> '.$display_part.' '.
4454: lc($$record{"$where.$partid.award"}).' '.
4455: $mark{$$record{"$where.$partid.solved"}}.
4456: '<br />';
4457: }
4458: if (exists $$record{"$where.$partid.regrader"}) {
4459: $displaySub[2].=$$record{"$where.$partid.regrader"}.
4460: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
4461: } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
4462: $displaySub[2].=
4463: $$record{"$version:resource.$partid.regrader"}.
4464: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
4465: }
4466: }
4467: # needed because old essay regrader has not parts info
4468: if (exists $$record{"$version:resource.regrader"}) {
4469: $displaySub[2].=$$record{"$version:resource.regrader"};
4470: }
4471: $studentTable.='<td>'.$displaySub[0].' </td><td>'.$displaySub[1];
4472: if ($displaySub[2]) {
4473: $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
4474: }
4475: $studentTable.=' </td>'.
4476: &Apache::loncommon::end_data_table_row();
4477: }
4478: $studentTable.=&Apache::loncommon::end_data_table();
4479: return $studentTable;
4480: }
4481:
4482: sub updateGradeByPage {
4483: my ($request) = shift;
4484:
4485: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4486: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4487: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4488: my $pageTitle = $env{'form.page'};
4489: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
4490: my ($uname,$udom) = split(/:/,$env{'form.student'});
4491: my $usec=$classlist->{$env{'form.student'}}[5];
4492: if (!&canmodify($usec)) {
4493: $request->print('<span class="LC_warning">Unable to modify requested student.('.$env{'form.student'}.'</span>');
4494: $request->print(&show_grading_menu_form($env{'form.symb'}));
4495: return;
4496: }
4497: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
4498: $result.='<h3> Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
4499: '</h3>'."\n";
4500:
4501: $request->print($result);
4502:
4503: my $navmap = Apache::lonnavmaps::navmap->new();
4504: my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
4505: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
4506: if (!$map) {
4507: $request->print('<span class="LC_warning">Unable to grade requested sequence. ('.$resUrl.')</span>');
4508: my ($symb)=&get_symb($request);
4509: $request->print(&show_grading_menu_form($symb));
4510: return;
4511: }
4512: my $iterator = $navmap->getIterator($map->map_start(),
4513: $map->map_finish());
4514:
4515: my $studentTable=
4516: &Apache::loncommon::start_data_table().
4517: &Apache::loncommon::start_data_table_header_row().
4518: '<th align="center"> '.&mt('Prob.').' </th>'.
4519: '<th> '.&mt('Title').' </th>'.
4520: '<th> '.&mt('Previous Score').' </th>'.
4521: '<th> '.&mt('New Score').' </th>'.
4522: &Apache::loncommon::end_data_table_header_row();
4523:
4524: $iterator->next(); # skip the first BEGIN_MAP
4525: my $curRes = $iterator->next(); # for "current resource"
4526: my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
4527: while ($depth > 0) {
4528: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
4529: if($curRes == $iterator->END_MAP) { $depth--; }
4530:
4531: if (ref($curRes) && $curRes->is_problem()) {
4532: my $parts = $curRes->parts();
4533: my $title = $curRes->compTitle();
4534: my $symbx = $curRes->symb();
4535: $studentTable.=
4536: &Apache::loncommon::start_data_table_row().
4537: '<td align="center" valign="top" >'.$prob.
4538: (scalar(@{$parts}) == 1 ? ''
4539: : '<br />('.&mt('[quant,_1, parts]',scalar(@{$parts}))
4540: ).')</td>';
4541: $studentTable.='<td valign="top"> <b>'.$title.'</b> </td>';
4542:
4543: my %newrecord=();
4544: my @displayPts=();
4545: my %aggregate = ();
4546: my $aggregateflag = 0;
4547: foreach my $partid (@{$parts}) {
4548: my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
4549: my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
4550:
4551: my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ?
4552: $env{'form.WGT'.$question.'_'.$partid} : 1;
4553: my $partial = $newpts/$wgt;
4554: my $score;
4555: if ($partial > 0) {
4556: $score = 'correct_by_override';
4557: } elsif ($newpts ne '') { #empty is taken as 0
4558: $score = 'incorrect_by_override';
4559: }
4560: my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
4561: if ($dropMenu eq 'excused') {
4562: $partial = '';
4563: $score = 'excused';
4564: } elsif ($dropMenu eq 'reset status'
4565: && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
4566: $newrecord{'resource.'.$partid.'.tries'} = 0;
4567: $newrecord{'resource.'.$partid.'.solved'} = '';
4568: $newrecord{'resource.'.$partid.'.award'} = '';
4569: $newrecord{'resource.'.$partid.'.awarded'} = 0;
4570: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
4571: $changeflag++;
4572: $newpts = '';
4573:
4574: my $aggtries = $env{'form.aggtries'.$question.'_'.$partid};
4575: my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
4576: my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
4577: if ($aggtries > 0) {
4578: &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
4579: $aggregateflag = 1;
4580: }
4581: }
4582: my $display_part=&get_display_part($partid,$curRes->symb());
4583: my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
4584: $displayPts[0].=' <b>Part:</b> '.$display_part.' = '.
4585: (($oldstatus eq 'excused') ? 'excused' : $oldpts).
4586: ' <br />';
4587: $displayPts[1].=' <b>Part:</b> '.$display_part.' = '.
4588: (($score eq 'excused') ? 'excused' : $newpts).
4589: ' <br />';
4590: $question++;
4591: next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
4592:
4593: $newrecord{'resource.'.$partid.'.awarded'} = $partial if $partial ne '';
4594: $newrecord{'resource.'.$partid.'.solved'} = $score if $score ne '';
4595: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
4596: if (scalar(keys(%newrecord)) > 0);
4597:
4598: $changeflag++;
4599: }
4600: if (scalar(keys(%newrecord)) > 0) {
4601: my %record =
4602: &Apache::lonnet::restore($symbx,$env{'request.course.id'},
4603: $udom,$uname);
4604:
4605: if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
4606: $newrecord{'resource.CODE'} = $env{'form.CODE'};
4607: } elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
4608: $newrecord{'resource.CODE'} = '';
4609: }
4610: &Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
4611: $udom,$uname);
4612: %record = &Apache::lonnet::restore($symbx,
4613: $env{'request.course.id'},
4614: $udom,$uname);
4615: &check_and_remove_from_queue($parts,\%record,undef,$symbx,
4616: $cdom,$cnum,$udom,$uname);
4617: }
4618:
4619: if ($aggregateflag) {
4620: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
4621: $env{'course.'.$env{'request.course.id'}.'.domain'},
4622: $env{'course.'.$env{'request.course.id'}.'.num'});
4623: }
4624:
4625: $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
4626: '<td valign="top">'.$displayPts[1].'</td>'.
4627: &Apache::loncommon::end_data_table_row();
4628:
4629: $prob++;
4630: }
4631: $curRes = $iterator->next();
4632: }
4633:
4634: $studentTable.=&Apache::loncommon::end_data_table();
4635: $studentTable.=&show_grading_menu_form($env{'form.symb'});
4636: my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
4637: 'The scores were changed for '.
4638: $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
4639: $request->print($grademsg.$studentTable);
4640:
4641: return '';
4642: }
4643:
4644: #-------- end of section for handling grading by page/sequence ---------
4645: #
4646: #-------------------------------------------------------------------
4647:
4648: #--------------------Scantron Grading-----------------------------------
4649: #
4650: #------ start of section for handling grading by page/sequence ---------
4651:
4652: =pod
4653:
4654: =head1 Bubble sheet grading routines
4655:
4656: For this documentation:
4657:
4658: 'scanline' refers to the full line of characters
4659: from the file that we are parsing that represents one entire sheet
4660:
4661: 'bubble line' refers to the data
4662: representing the line of bubbles that are on the physical bubble sheet
4663:
4664:
4665: The overall process is that a scanned in bubble sheet data is uploaded
4666: into a course. When a user wants to grade, they select a
4667: sequence/folder of resources, a file of bubble sheet info, and pick
4668: one of the predefined configurations for what each scanline looks
4669: like.
4670:
4671: Next each scanline is checked for any errors of either 'missing
4672: bubbles' (it's an error because it may have been mis-scanned
4673: because too light bubbling), 'double bubble' (each bubble line should
4674: have no more that one letter picked), invalid or duplicated CODE,
4675: invalid student ID
4676:
4677: If the CODE option is used that determines the randomization of the
4678: homework problems, either way the student ID is looked up into a
4679: username:domain.
4680:
4681: During the validation phase the instructor can choose to skip scanlines.
4682:
4683: After the validation phase, there are now 3 bubble sheet files
4684:
4685: scantron_original_filename (unmodified original file)
4686: scantron_corrected_filename (file where the corrected information has replaced the original information)
4687: scantron_skipped_filename (contains the exact text of scanlines that where skipped)
4688:
4689: Also there is a separate hash nohist_scantrondata that contains extra
4690: correction information that isn't representable in the bubble sheet
4691: file (see &scantron_getfile() for more information)
4692:
4693: After all scanlines are either valid, marked as valid or skipped, then
4694: foreach line foreach problem in the picked sequence, an ssi request is
4695: made that simulates a user submitting their selected letter(s) against
4696: the homework problem.
4697:
4698: =over 4
4699:
4700:
4701:
4702: =item defaultFormData
4703:
4704: Returns html hidden inputs used to hold context/default values.
4705:
4706: Arguments:
4707: $symb - $symb of the current resource
4708:
4709: =cut
4710:
4711: sub defaultFormData {
4712: my ($symb)=@_;
4713: return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
4714: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
4715: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
4716: }
4717:
4718:
4719: =pod
4720:
4721: =item getSequenceDropDown
4722:
4723: Return html dropdown of possible sequences to grade
4724:
4725: Arguments:
4726: $symb - $symb of the current resource
4727:
4728: =cut
4729:
4730: sub getSequenceDropDown {
4731: my ($symb)=@_;
4732: my $result='<select name="selectpage">'."\n";
4733: my ($titles,$symbx) = &getSymbMap();
4734: my ($curpage)=&Apache::lonnet::decode_symb($symb);
4735: my $ctr=0;
4736: foreach (@$titles) {
4737: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4738: $result.='<option value="'.$$symbx{$_}.'" '.
4739: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
4740: '>'.$showtitle.'</option>'."\n";
4741: $ctr++;
4742: }
4743: $result.= '</select>';
4744: return $result;
4745: }
4746:
4747:
4748: =pod
4749:
4750: =item scantron_filenames
4751:
4752: Returns a list of the scantron files in the current course
4753:
4754: =cut
4755:
4756: sub scantron_filenames {
4757: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4758: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
4759: my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
4760: &propath($cdom,$cname));
4761: my @possiblenames;
4762: foreach my $filename (sort(@files)) {
4763: ($filename)=split(/&/,$filename);
4764: if ($filename!~/^scantron_orig_/) { next ; }
4765: $filename=~s/^scantron_orig_//;
4766: push(@possiblenames,$filename);
4767: }
4768: return @possiblenames;
4769: }
4770:
4771: =pod
4772:
4773: =item scantron_uploads
4774:
4775: Returns html drop-down list of scantron files in current course.
4776:
4777: Arguments:
4778: $file2grade - filename to set as selected in the dropdown
4779:
4780: =cut
4781:
4782: sub scantron_uploads {
4783: my ($file2grade) = @_;
4784: my $result= '<select name="scantron_selectfile">';
4785: $result.="<option></option>";
4786: foreach my $filename (sort(&scantron_filenames())) {
4787: $result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
4788: }
4789: $result.="</select>";
4790: return $result;
4791: }
4792:
4793: =pod
4794:
4795: =item scantron_scantab
4796:
4797: Returns html drop down of the scantron formats in the scantronformat.tab
4798: file.
4799:
4800: =cut
4801:
4802: sub scantron_scantab {
4803: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
4804: my $result='<select name="scantron_format">'."\n";
4805: $result.='<option></option>'."\n";
4806: foreach my $line (<$fh>) {
4807: my ($name,$descrip)=split(/:/,$line);
4808: if ($name =~ /^\#/) { next; }
4809: $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
4810: }
4811: $result.='</select>'."\n";
4812:
4813: return $result;
4814: }
4815:
4816: =pod
4817:
4818: =item scantron_CODElist
4819:
4820: Returns html drop down of the saved CODE lists from current course,
4821: generated from earlier printings.
4822:
4823: =cut
4824:
4825: sub scantron_CODElist {
4826: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4827: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4828: my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
4829: my $namechoice='<option></option>';
4830: foreach my $name (sort {uc($a) cmp uc($b)} @names) {
4831: if ($name =~ /^error: 2 /) { next; }
4832: if ($name =~ /^type\0/) { next; }
4833: $namechoice.='<option value="'.$name.'">'.$name.'</option>';
4834: }
4835: $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
4836: return $namechoice;
4837: }
4838:
4839: =pod
4840:
4841: =item scantron_CODEunique
4842:
4843: Returns the html for "Each CODE to be used once" radio.
4844:
4845: =cut
4846:
4847: sub scantron_CODEunique {
4848: my $result='<span style="white-space: nowrap;">
4849: <label><input type="radio" name="scantron_CODEunique"
4850: value="yes" checked="checked" />'.&mt('Yes').' </label>
4851: </span>
4852: <span style="white-space: nowrap;">
4853: <label><input type="radio" name="scantron_CODEunique"
4854: value="no" />'.&mt('No').' </label>
4855: </span>';
4856: return $result;
4857: }
4858:
4859: =pod
4860:
4861: =item scantron_selectphase
4862:
4863: Generates the initial screen to start the bubble sheet process.
4864: Allows for - starting a grading run.
4865: - downloading existing scan data (original, corrected
4866: or skipped info)
4867:
4868: - uploading new scan data
4869:
4870: Arguments:
4871: $r - The Apache request object
4872: $file2grade - name of the file that contain the scanned data to score
4873:
4874: =cut
4875:
4876: sub scantron_selectphase {
4877: my ($r,$file2grade) = @_;
4878: my ($symb)=&get_symb($r);
4879: if (!$symb) {return '';}
4880: my $sequence_selector=&getSequenceDropDown($symb);
4881: my $default_form_data=&defaultFormData($symb);
4882: my $grading_menu_button=&show_grading_menu_form($symb);
4883: my $file_selector=&scantron_uploads($file2grade);
4884: my $format_selector=&scantron_scantab();
4885: my $CODE_selector=&scantron_CODElist();
4886: my $CODE_unique=&scantron_CODEunique();
4887: my $result;
4888:
4889: # Chunk of form to prompt for a file to grade and how:
4890:
4891: $result.= <<SCANTRONFORM;
4892: <table width="100%" border="0">
4893: <tr>
4894: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
4895: <td bgcolor="#777777">
4896: <input type="hidden" name="command" value="scantron_warning" />
4897: $default_form_data
4898: <table width="100%" border="0">
4899: <tr bgcolor="#e6ffff">
4900: <td colspan="2">
4901: <b>Specify file and which Folder/Sequence to grade</b>
4902: </td>
4903: </tr>
4904: <tr bgcolor="#ffffe6">
4905: <td> Sequence to grade: </td><td> $sequence_selector </td>
4906: </tr>
4907: <tr bgcolor="#ffffe6">
4908: <td> Filename of scoring office file: </td><td> $file_selector </td>
4909: </tr>
4910: <tr bgcolor="#ffffe6">
4911: <td> Format of data file: </td><td> $format_selector </td>
4912: </tr>
4913: <tr bgcolor="#ffffe6">
4914: <td> Saved CODEs to validate against: </td><td> $CODE_selector</td>
4915: </tr>
4916: <tr bgcolor="#ffffe6">
4917: <td> Each CODE is only to be used once:</td><td> $CODE_unique </td>
4918: </tr>
4919: <tr bgcolor="#ffffe6">
4920: <td> Options: </td>
4921: <td>
4922: <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> Do only previously skipped records</label> <br />
4923: <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> Remove all existing corrections</label> <br />
4924: <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> Skip hidden resources when grading</label>
4925: </td>
4926: </tr>
4927: <tr bgcolor="#ffffe6">
4928: <td colspan="2">
4929: <input type="submit" value="Grading: Validate Scantron Records" />
4930: </td>
4931: </tr>
4932: </table>
4933: </td>
4934: </form>
4935: </tr>
4936: SCANTRONFORM
4937:
4938: $r->print($result);
4939:
4940: if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
4941: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
4942:
4943: # Chunk of form to prompt for a scantron file upload.
4944:
4945: $r->print(<<SCANTRONFORM);
4946: <tr>
4947: <td bgcolor="#777777">
4948: <table width="100%" border="0">
4949: <tr bgcolor="#e6ffff">
4950: <td>
4951: <b>Specify a Scantron data file to upload.</b>
4952: </td>
4953: </tr>
4954: <tr bgcolor="#ffffe6">
4955: <td>
4956: SCANTRONFORM
4957: my $default_form_data=&defaultFormData(&get_symb($r,1));
4958: my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
4959: my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
4960: $r->print(<<UPLOAD);
4961: <script type="text/javascript" language="javascript">
4962: function checkUpload(formname) {
4963: if (formname.upfile.value == "") {
4964: alert("Please use the browse button to select a file from your local directory.");
4965: return false;
4966: }
4967: formname.submit();
4968: }
4969: </script>
4970:
4971: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
4972: $default_form_data
4973: <input name='courseid' type='hidden' value='$cnum' />
4974: <input name='domainid' type='hidden' value='$cdom' />
4975: <input name='command' value='scantronupload_save' type='hidden' />
4976: File to upload:<input type="file" name="upfile" size="50" />
4977: <br />
4978: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
4979: </form>
4980: UPLOAD
4981:
4982: $r->print(<<SCANTRONFORM);
4983: </td>
4984: </tr>
4985: </table>
4986: </td>
4987: </tr>
4988: SCANTRONFORM
4989: }
4990:
4991: # Chunk of the form that prompts to view a scoring office file,
4992: # corrected file, skipped records in a file.
4993:
4994: $r->print(<<SCANTRONFORM);
4995: <tr>
4996: <form action='/adm/grades' name='scantron_download'>
4997: <td bgcolor="#777777">
4998: $default_form_data
4999: <input type="hidden" name="command" value="scantron_download" />
5000: <table width="100%" border="0">
5001: <tr bgcolor="#e6ffff">
5002: <td colspan="2">
5003: <b>Download a scoring office file</b>
5004: </td>
5005: </tr>
5006: <tr bgcolor="#ffffe6">
5007: <td> Filename of scoring office file: </td><td> $file_selector </td>
5008: </tr>
5009: <tr bgcolor="#ffffe6">
5010: <td colspan="2">
5011: <input type="submit" value="Download: Show List of Associated Files" />
5012: </td>
5013: </tr>
5014: </table>
5015: </td>
5016: </form>
5017: </tr>
5018: SCANTRONFORM
5019:
5020: $r->print('<tr><td bgcolor="#777777">');
5021: &Apache::lonpickcode::code_list($r,2);
5022: $r->print('</td></tr></table>');
5023: $r->print($grading_menu_button);
5024: return
5025: }
5026:
5027: =pod
5028:
5029: =item get_scantron_config
5030:
5031: Parse and return the scantron configuration line selected as a
5032: hash of configuration file fields.
5033:
5034: Arguments:
5035: which - the name of the configuration to parse from the file.
5036:
5037:
5038: Returns:
5039: If the named configuration is not in the file, an empty
5040: hash is returned.
5041: a hash with the fields
5042: name - internal name for the this configuration setup
5043: description - text to display to operator that describes this config
5044: CODElocation - if 0 or the string 'none'
5045: - no CODE exists for this config
5046: if -1 || the string 'letter'
5047: - a CODE exists for this config and is
5048: a string of letters
5049: Unsupported value (but planned for future support)
5050: if a positive integer
5051: - The CODE exists as the first n items from
5052: the question section of the form
5053: if the string 'number'
5054: - The CODE exists for this config and is
5055: a string of numbers
5056: CODEstart - (only matter if a CODE exists) column in the line where
5057: the CODE starts
5058: CODElength - length of the CODE
5059: IDstart - column where the student ID number starts
5060: IDlength - length of the student ID info
5061: Qstart - column where the information from the bubbled
5062: 'questions' start
5063: Qlength - number of columns comprising a single bubble line from
5064: the sheet. (usually either 1 or 10)
5065: Qon - either a single character representing the character used
5066: to signal a bubble was chosen in the positional setup, or
5067: the string 'letter' if the letter of the chosen bubble is
5068: in the final, or 'number' if a number representing the
5069: chosen bubble is in the file (1->A 0->J)
5070: Qoff - the character used to represent that a bubble was
5071: left blank
5072: PaperID - if the scanning process generates a unique number for each
5073: sheet scanned the column that this ID number starts in
5074: PaperIDlength - number of columns that comprise the unique ID number
5075: for the sheet of paper
5076: FirstName - column that the first name starts in
5077: FirstNameLength - number of columns that the first name spans
5078:
5079: LastName - column that the last name starts in
5080: LastNameLength - number of columns that the last name spans
5081:
5082: =cut
5083:
5084: sub get_scantron_config {
5085: my ($which) = @_;
5086: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
5087: my %config;
5088: #FIXME probably should move to XML it has already gotten a bit much now
5089: foreach my $line (<$fh>) {
5090: my ($name,$descrip)=split(/:/,$line);
5091: if ($name ne $which ) { next; }
5092: chomp($line);
5093: my @config=split(/:/,$line);
5094: $config{'name'}=$config[0];
5095: $config{'description'}=$config[1];
5096: $config{'CODElocation'}=$config[2];
5097: $config{'CODEstart'}=$config[3];
5098: $config{'CODElength'}=$config[4];
5099: $config{'IDstart'}=$config[5];
5100: $config{'IDlength'}=$config[6];
5101: $config{'Qstart'}=$config[7];
5102: $config{'Qlength'}=$config[8];
5103: $config{'Qoff'}=$config[9];
5104: $config{'Qon'}=$config[10];
5105: $config{'PaperID'}=$config[11];
5106: $config{'PaperIDlength'}=$config[12];
5107: $config{'FirstName'}=$config[13];
5108: $config{'FirstNamelength'}=$config[14];
5109: $config{'LastName'}=$config[15];
5110: $config{'LastNamelength'}=$config[16];
5111: last;
5112: }
5113: return %config;
5114: }
5115:
5116: =pod
5117:
5118: =item username_to_idmap
5119:
5120: creates a hash keyed by student id with values of the corresponding
5121: student username:domain.
5122:
5123: Arguments:
5124:
5125: $classlist - reference to the class list hash. This is a hash
5126: keyed by student name:domain whose elements are references
5127: to arrays containing various chunks of information
5128: about the student. (See loncoursedata for more info).
5129:
5130: Returns
5131: %idmap - the constructed hash
5132:
5133: =cut
5134:
5135: sub username_to_idmap {
5136: my ($classlist)= @_;
5137: my %idmap;
5138: foreach my $student (keys(%$classlist)) {
5139: $idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
5140: $student;
5141: }
5142: return %idmap;
5143: }
5144:
5145: =pod
5146:
5147: =item scantron_fixup_scanline
5148:
5149: Process a requested correction to a scanline.
5150:
5151: Arguments:
5152: $scantron_config - hash from &get_scantron_config()
5153: $scan_data - hash of correction information
5154: (see &scantron_getfile())
5155: $line - existing scanline
5156: $whichline - line number of the passed in scanline
5157: $field - type of change to process
5158: (either
5159: 'ID' -> correct the student ID number
5160: 'CODE' -> correct the CODE
5161: 'answer' -> fixup the submitted answers)
5162:
5163: $args - hash of additional info,
5164: - 'ID'
5165: 'newid' -> studentID to use in replacement
5166: of existing one
5167: - 'CODE'
5168: 'CODE_ignore_dup' - set to true if duplicates
5169: should be ignored.
5170: 'CODE' - is new code or 'use_unfound'
5171: if the existing unfound code should
5172: be used as is
5173: - 'answer'
5174: 'response' - new answer or 'none' if blank
5175: 'question' - the bubble line to change
5176:
5177: Returns:
5178: $line - the modified scanline
5179:
5180: Side effects:
5181: $scan_data - may be updated
5182:
5183: =cut
5184:
5185:
5186: sub scantron_fixup_scanline {
5187: my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
5188:
5189:
5190: if ($field eq 'ID') {
5191: if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
5192: return ($line,1,'New value too large');
5193: }
5194: if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
5195: $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
5196: $args->{'newid'});
5197: }
5198: substr($line,$$scantron_config{'IDstart'}-1,
5199: $$scantron_config{'IDlength'})=$args->{'newid'};
5200: if ($args->{'newid'}=~/^\s*$/) {
5201: &scan_data($scan_data,"$whichline.user",
5202: $args->{'username'}.':'.$args->{'domain'});
5203: }
5204: } elsif ($field eq 'CODE') {
5205: if ($args->{'CODE_ignore_dup'}) {
5206: &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
5207: }
5208: &scan_data($scan_data,"$whichline.useCODE",'1');
5209: if ($args->{'CODE'} ne 'use_unfound') {
5210: if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
5211: return ($line,1,'New CODE value too large');
5212: }
5213: if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
5214: $args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
5215: }
5216: substr($line,$$scantron_config{'CODEstart'}-1,
5217: $$scantron_config{'CODElength'})=$args->{'CODE'};
5218: }
5219: } elsif ($field eq 'answer') {
5220: &scantron_get_maxbubble(); # Need the bubble counter info.
5221: my $length =$scantron_config->{'Qlength'};
5222: my $off=$scantron_config->{'Qoff'};
5223: my $on=$scantron_config->{'Qon'};
5224: my $question_number = $args->{'question'} -1;
5225: my $first_position = $first_bubble_line{$question_number};
5226: my $bubble_count = $bubble_lines_per_response{$question_number};
5227: my $bubbles_per_line= $$scantron_config{'Qlength'};
5228: my $answer=${off}x($bubbles_per_line*$bubble_count);
5229: my $final_answer;
5230: if ($$scantron_config{'Qon'} eq 'letter' ||
5231: $$scantron_config{'Qon'} eq 'number') {
5232: $bubbles_per_line = 10;
5233: }
5234: if (defined $args->{'response'}) {
5235:
5236: if ($args->{'response'} eq 'none') {
5237: &scan_data($scan_data,
5238: "$whichline.no_bubble.".$args->{'question'},'1');
5239: } else {
5240: my ($bubble_line, $bubble_number) = split(/:/,$args->{'response'});
5241: if ($on eq 'letter') {
5242: my @alphabet=('A'..'Z');
5243: $answer=$alphabet[$bubble_number];
5244: } elsif ($on eq 'number') {
5245: $answer= $bubble_number+1;
5246: if ($answer == 10) { $answer = '0'; }
5247: } else {
5248: substr($answer,$bubble_number+$bubble_line*$bubbles_per_line,1)=$on;
5249: $final_answer = $answer;
5250: }
5251: &scan_data($scan_data,
5252: "$whichline.no_bubble.".$args->{'question'},undef,'1');
5253:
5254: # Positional notation already has the right final answer length..
5255:
5256: if (($on eq 'letter') || ($on eq 'number')) {
5257: for (my $l = 0; $l < $bubble_count; $l++) {
5258: if ($l eq $bubble_line) {
5259: $final_answer .= $answer;
5260: } else {
5261: $final_answer .= ' ';
5262: }
5263: }
5264: }
5265: }
5266: # $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
5267: #substr($line,$where-1,$length)=$answer;
5268: substr($line,
5269: $scantron_config->{'Qstart'}+$first_position-1,
5270: $bubbles_per_line*$length) = $final_answer;
5271: }
5272: }
5273: return $line;
5274: }
5275:
5276: =pod
5277:
5278: =item scan_data
5279:
5280: Edit or look up an item in the scan_data hash.
5281:
5282: Arguments:
5283: $scan_data - The hash (see scantron_getfile)
5284: $key - shorthand of the key to edit (actual key is
5285: scantronfilename_key).
5286: $data - New value of the hash entry.
5287: $delete - If true, the entry is removed from the hash.
5288:
5289: Returns:
5290: The new value of the hash table field (undefined if deleted).
5291:
5292: =cut
5293:
5294:
5295: sub scan_data {
5296: my ($scan_data,$key,$value,$delete)=@_;
5297: my $filename=$env{'form.scantron_selectfile'};
5298: if (defined($value)) {
5299: $scan_data->{$filename.'_'.$key} = $value;
5300: }
5301: if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
5302: return $scan_data->{$filename.'_'.$key};
5303: }
5304:
5305: =pod
5306:
5307: =item scantron_parse_scanline
5308:
5309: Decodes a scanline from the selected scantron file
5310:
5311: Arguments:
5312: line - The text of the scantron file line to process
5313: whichline - Line number
5314: scantron_config - Hash describing the format of the scantron lines.
5315: scan_data - Hash of extra information about the scanline
5316: (see scantron_getfile for more information)
5317: just_header - True if should not process question answers but only
5318: the stuff to the left of the answers.
5319: Returns:
5320: Hash containing the result of parsing the scanline
5321:
5322: Keys are all proceeded by the string 'scantron.'
5323:
5324: CODE - the CODE in use for this scanline
5325: useCODE - 1 if the CODE is invalid but it usage has been forced
5326: by the operator
5327: CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
5328: CODEs were selected, but the usage has been
5329: forced by the operator
5330: ID - student ID
5331: PaperID - if used, the ID number printed on the sheet when the
5332: paper was scanned
5333: FirstName - first name from the sheet
5334: LastName - last name from the sheet
5335:
5336: if just_header was not true these key may also exist
5337:
5338: missingerror - a list of bubble ranges that are considered to be answers
5339: to a single question that don't have any bubbles filled in.
5340: Of the form questionnumber:firstbubblenumber:count.
5341: doubleerror - a list of bubble ranges that are considered to be answers
5342: to a single question that have more than one bubble filled in.
5343: Of the form questionnumber::firstbubblenumber:count
5344:
5345: In the above, count is the number of bubble responses in the
5346: input line needed to represent the possible answers to the question.
5347: e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
5348: per line would have count = 2.
5349:
5350: maxquest - the number of the last bubble line that was parsed
5351:
5352: (<number> starts at 1)
5353: <number>.answer - zero or more letters representing the selected
5354: letters from the scanline for the bubble line
5355: <number>.
5356: if blank there was either no bubble or there where
5357: multiple bubbles, (consult the keys missingerror and
5358: doubleerror if this is an error condition)
5359:
5360: =cut
5361:
5362: sub scantron_parse_scanline {
5363: my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
5364:
5365: my %record;
5366: my $questions=substr($line,$$scantron_config{'Qstart'}-1); # Answers
5367: my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # earlier stuff
5368: if (!($$scantron_config{'CODElocation'} eq 0 ||
5369: $$scantron_config{'CODElocation'} eq 'none')) {
5370: if ($$scantron_config{'CODElocation'} < 0 ||
5371: $$scantron_config{'CODElocation'} eq 'letter' ||
5372: $$scantron_config{'CODElocation'} eq 'number') {
5373: $record{'scantron.CODE'}=substr($data,
5374: $$scantron_config{'CODEstart'}-1,
5375: $$scantron_config{'CODElength'});
5376: if (&scan_data($scan_data,"$whichline.useCODE")) {
5377: $record{'scantron.useCODE'}=1;
5378: }
5379: if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
5380: $record{'scantron.CODE_ignore_dup'}=1;
5381: }
5382: } else {
5383: #FIXME interpret first N questions
5384: }
5385: }
5386: $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
5387: $$scantron_config{'IDlength'});
5388: $record{'scantron.PaperID'}=
5389: substr($data,$$scantron_config{'PaperID'}-1,
5390: $$scantron_config{'PaperIDlength'});
5391: $record{'scantron.FirstName'}=
5392: substr($data,$$scantron_config{'FirstName'}-1,
5393: $$scantron_config{'FirstNamelength'});
5394: $record{'scantron.LastName'}=
5395: substr($data,$$scantron_config{'LastName'}-1,
5396: $$scantron_config{'LastNamelength'});
5397: if ($just_header) { return \%record; }
5398:
5399: my @alphabet=('A'..'Z');
5400: my $questnum=0;
5401: my $ansnum =1; # Multiple 'answer lines'/question.
5402:
5403: chomp($questions); # Get rid of any trailing \n.
5404: $questions =~ s/\r$//; # Get rid of trailing \r too (MAC or Win uploads).
5405: while (length($questions)) {
5406: my $answers_needed = $bubble_lines_per_response{$questnum};
5407: my $answer_length = $$scantron_config{'Qlength'} * $answers_needed;
5408:
5409:
5410:
5411: $questnum++;
5412: my $currentquest = substr($questions,0,$answer_length);
5413: $questions = substr($questions,0,$answer_length)='';
5414: if (length($currentquest) < $answer_length) { next; }
5415:
5416: # Qon letter implies for each slot in currentquest we have:
5417: # ? or * for doubles a letter in A-Z for a bubble and
5418: # about anything else (esp. a value of Qoff for missing
5419: # bubbles.
5420:
5421:
5422: if ($$scantron_config{'Qon'} eq 'letter') {
5423:
5424: if ($currentquest =~ /\?/
5425: || $currentquest =~ /\*/
5426: || (&occurence_count($currentquest, "[A-Z]") > 1)) {
5427: push(@{$record{'scantron.doubleerror'}},$questnum);
5428: for (my $ans = 0; $ans < $answers_needed; $ans++) {
5429: my $bubble = substr($currentquest, $ans, 1);
5430: if ($bubble =~ /[A-Z]/ ) {
5431: $record{"scantron.$ansnum.answer"} = $bubble;
5432: } else {
5433: $record{"scantron.$ansnum.answer"}='';
5434: }
5435: $ansnum++;
5436: }
5437:
5438: } elsif (!defined($currentquest)
5439: || (&occurence_count($currentquest, $$scantron_config{'Qoff'}) == length($currentquest))
5440: || (&occurence_count($currentquest, "[A-Z]") == 0)) {
5441: for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
5442: $record{"scantron.$ansnum.answer"}='';
5443: $ansnum++;
5444:
5445: }
5446: if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
5447: push(@{$record{"scantron.missingerror"}},$questnum);
5448: # $ansnum += $answers_needed;
5449: }
5450: } else {
5451: for (my $ans = 0; $ans < $answers_needed; $ans++) {
5452: $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
5453: $ansnum++;
5454: }
5455: }
5456:
5457: # Qon 'number' implies each slot gives a digit that indexes the
5458: # the bubbles filled or Qoff or a non number for unbubbled lines.
5459: # and *? for double bubbles on a line.
5460: # these answers are also stored as letters.
5461:
5462: } elsif ($$scantron_config{'Qon'} eq 'number') {
5463: if ($currentquest =~ /\?/
5464: || $currentquest =~ /\*/
5465: || (&occurence_count($currentquest, '\d') > 1)) {
5466: push(@{$record{'scantron.doubleerror'}},$questnum);
5467: for (my $ans = 0; $ans < $answers_needed; $ans++) {
5468: my $bubble = substr($currentquest, $ans, 1);
5469: if ($bubble =~ /\d/) {
5470: $record{"scantron.$ansnum.answer"} = $alphabet[$bubble];
5471: } else {
5472: $record{"scantron.$ansnum.answer"}=' ';
5473: }
5474: $ansnum++;
5475: }
5476:
5477: } elsif (!defined($currentquest)
5478: || (&occurence_count($currentquest,$$scantron_config{'Qoff'}) == length($currentquest))
5479: || (&occurence_count($currentquest, '\d') == 0)) {
5480: for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
5481: $record{"scantron.$ansnum.answer"}='';
5482: $ansnum++;
5483:
5484: }
5485: if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
5486: push(@{$record{"scantron.missingerror"}},$questnum);
5487: $ansnum += $answers_needed;
5488: }
5489:
5490: } else {
5491: $currentquest = &digits_to_letters($currentquest);
5492: for (my $ans =0; $ans < $answers_needed; $ans++) {
5493: $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
5494: $ansnum++;
5495: }
5496: }
5497: } else {
5498:
5499: # Otherwise there's a positional notation;
5500: # each bubble line requires Qlength items, and there are filled in
5501: # bubbles for each case where there 'Qon' characters.
5502: #
5503:
5504: my @array=split($$scantron_config{'Qon'},$currentquest,-1);
5505:
5506: # If the split only giveas us one element.. the full length of the
5507: # answser string, no bubbles are filled in:
5508:
5509: if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
5510: for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
5511: $record{"scantron.$ansnum.answer"}='';
5512: $ansnum++;
5513:
5514: }
5515: if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
5516: push(@{$record{"scantron.missingerror"}},$questnum);
5517: }
5518:
5519: # If the bubble is not the last position, there will be
5520: # 2 elements. If it is the last position, there will be 1 element.
5521:
5522: } elsif (scalar(@array) le 2) {
5523:
5524: my $location = length($array[0]);
5525: my $line_num = int($location / $$scantron_config{'Qlength'});
5526: my $bubble = $alphabet[$location % $$scantron_config{'Qlength'}];
5527:
5528:
5529: for (my $ans = 0; $ans < $answers_needed; $ans++) {
5530: if ($ans eq $line_num) {
5531: $record{"scantron.$ansnum.answer"} = $bubble;
5532: } else {
5533: $record{"scantron.$ansnum.answer"} = ' ';
5534: }
5535: $ansnum++;
5536: }
5537: }
5538: # If there's more than one instance of a bubble character
5539: # That's a double bubble; with positional notation we can
5540: # record all the bubbles filled in as well as the
5541: # fact this response consists of multiple bubbles.
5542: #
5543: else {
5544: push(@{$record{'scantron.doubleerror'}},$questnum);
5545:
5546: my $first_answer = $ansnum;
5547: for (my $ans =0; $ans < $answers_needed; $ans++) {
5548: my $item = $first_answer+$ans;
5549: $record{"scantron.$item.answer"} = '';
5550: }
5551:
5552: my @ans=@array;
5553: my $i=0;
5554: my $increment = 0;
5555: while ($#ans) {
5556: $i+=length($ans[0]) + $increment;
5557: my $line = int($i/$$scantron_config{'Qlength'} + $first_answer);
5558: my $bubble = $i%$$scantron_config{'Qlength'};
5559: $record{"scantron.$line.answer"}.=$alphabet[$bubble];
5560: shift(@ans);
5561: $increment = 1;
5562: }
5563: $ansnum += $answers_needed;
5564: }
5565: }
5566: }
5567: $record{'scantron.maxquest'}=$questnum;
5568: return \%record;
5569: }
5570:
5571: =pod
5572:
5573: =item scantron_add_delay
5574:
5575: Adds an error message that occurred during the grading phase to a
5576: queue of messages to be shown after grading pass is complete
5577:
5578: Arguments:
5579: $delayqueue - arrary ref of hash ref of error messages
5580: $scanline - the scanline that caused the error
5581: $errormesage - the error message
5582: $errorcode - a numeric code for the error
5583:
5584: Side Effects:
5585: updates the $delayqueue to have a new hash ref of the error
5586:
5587: =cut
5588:
5589: sub scantron_add_delay {
5590: my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
5591: push(@$delayqueue,
5592: {'line' => $scanline, 'emsg' => $errormessage,
5593: 'ecode' => $errorcode }
5594: );
5595: }
5596:
5597: =pod
5598:
5599: =item scantron_find_student
5600:
5601: Finds the username for the current scanline
5602:
5603: Arguments:
5604: $scantron_record - hash result from scantron_parse_scanline
5605: $scan_data - hash of correction information
5606: (see &scantron_getfile() form more information)
5607: $idmap - hash from &username_to_idmap()
5608: $line - number of current scanline
5609:
5610: Returns:
5611: Either 'username:domain' or undef if unknown
5612:
5613: =cut
5614:
5615: sub scantron_find_student {
5616: my ($scantron_record,$scan_data,$idmap,$line)=@_;
5617: my $scanID=$$scantron_record{'scantron.ID'};
5618: if ($scanID =~ /^\s*$/) {
5619: return &scan_data($scan_data,"$line.user");
5620: }
5621: foreach my $id (keys(%$idmap)) {
5622: if (lc($id) eq lc($scanID)) {
5623: return $$idmap{$id};
5624: }
5625: }
5626: return undef;
5627: }
5628:
5629: =pod
5630:
5631: =item scantron_filter
5632:
5633: Filter sub for lonnavmaps, filters out hidden resources if ignore
5634: hidden resources was selected
5635:
5636: =cut
5637:
5638: sub scantron_filter {
5639: my ($curres)=@_;
5640:
5641: if (ref($curres) && $curres->is_problem()) {
5642: # if the user has asked to not have either hidden
5643: # or 'randomout' controlled resources to be graded
5644: # don't include them
5645: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
5646: && $curres->randomout) {
5647: return 0;
5648: }
5649: return 1;
5650: }
5651: return 0;
5652: }
5653:
5654: =pod
5655:
5656: =item scantron_process_corrections
5657:
5658: Gets correction information out of submitted form data and corrects
5659: the scanline
5660:
5661: =cut
5662:
5663: sub scantron_process_corrections {
5664: my ($r) = @_;
5665: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
5666: my ($scanlines,$scan_data)=&scantron_getfile();
5667: my $classlist=&Apache::loncoursedata::get_classlist();
5668: my $which=$env{'form.scantron_line'};
5669: my $line=&scantron_get_line($scanlines,$scan_data,$which);
5670: my ($skip,$err,$errmsg);
5671: if ($env{'form.scantron_skip_record'}) {
5672: $skip=1;
5673: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
5674: my $newstudent=$env{'form.scantron_username'}.':'.
5675: $env{'form.scantron_domain'};
5676: my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
5677: ($line,$err,$errmsg)=
5678: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
5679: 'ID',{'newid'=>$newid,
5680: 'username'=>$env{'form.scantron_username'},
5681: 'domain'=>$env{'form.scantron_domain'}});
5682: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
5683: my $resolution=$env{'form.scantron_CODE_resolution'};
5684: my $newCODE;
5685: my %args;
5686: if ($resolution eq 'use_unfound') {
5687: $newCODE='use_unfound';
5688: } elsif ($resolution eq 'use_found') {
5689: $newCODE=$env{'form.scantron_CODE_selectedvalue'};
5690: } elsif ($resolution eq 'use_typed') {
5691: $newCODE=$env{'form.scantron_CODE_newvalue'};
5692: } elsif ($resolution =~ /^use_closest_(\d+)/) {
5693: $newCODE=$env{"form.scantron_CODE_closest_$1"};
5694: }
5695: if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
5696: $args{'CODE_ignore_dup'}=1;
5697: }
5698: $args{'CODE'}=$newCODE;
5699: ($line,$err,$errmsg)=
5700: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
5701: 'CODE',\%args);
5702: } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
5703: foreach my $question (split(',',$env{'form.scantron_questions'})) {
5704: ($line,$err,$errmsg)=
5705: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
5706: $which,'answer',
5707: { 'question'=>$question,
5708: 'response'=>$env{"form.scantron_correct_Q_$question"}});
5709: if ($err) { last; }
5710: }
5711: }
5712: if ($err) {
5713: $r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
5714: } else {
5715: &scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
5716: &scantron_putfile($scanlines,$scan_data);
5717: }
5718: }
5719:
5720: =pod
5721:
5722: =item reset_skipping_status
5723:
5724: Forgets the current set of remember skipped scanlines (and thus
5725: reverts back to considering all lines in the
5726: scantron_skipped_<filename> file)
5727:
5728: =cut
5729:
5730: sub reset_skipping_status {
5731: my ($scanlines,$scan_data)=&scantron_getfile();
5732: &scan_data($scan_data,'remember_skipping',undef,1);
5733: &scantron_putfile(undef,$scan_data);
5734: }
5735:
5736: =pod
5737:
5738: =item start_skipping
5739:
5740: Marks a scanline to be skipped.
5741:
5742: =cut
5743:
5744: sub start_skipping {
5745: my ($scan_data,$i)=@_;
5746: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
5747: if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
5748: $remembered{$i}=2;
5749: } else {
5750: $remembered{$i}=1;
5751: }
5752: &scan_data($scan_data,'remember_skipping',join(':',%remembered));
5753: }
5754:
5755: =pod
5756:
5757: =item should_be_skipped
5758:
5759: Checks whether a scanline should be skipped.
5760:
5761: =cut
5762:
5763: sub should_be_skipped {
5764: my ($scanlines,$scan_data,$i)=@_;
5765: if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
5766: # not redoing old skips
5767: if ($scanlines->{'skipped'}[$i]) { return 1; }
5768: return 0;
5769: }
5770: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
5771:
5772: if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
5773: return 0;
5774: }
5775: return 1;
5776: }
5777:
5778: =pod
5779:
5780: =item remember_current_skipped
5781:
5782: Discovers what scanlines are in the scantron_skipped_<filename>
5783: file and remembers them into scan_data for later use.
5784:
5785: =cut
5786:
5787: sub remember_current_skipped {
5788: my ($scanlines,$scan_data)=&scantron_getfile();
5789: my %to_remember;
5790: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
5791: if ($scanlines->{'skipped'}[$i]) {
5792: $to_remember{$i}=1;
5793: }
5794: }
5795:
5796: &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
5797: &scantron_putfile(undef,$scan_data);
5798: }
5799:
5800: =pod
5801:
5802: =item check_for_error
5803:
5804: Checks if there was an error when attempting to remove a specific
5805: scantron_.. bubble sheet data file. Prints out an error if
5806: something went wrong.
5807:
5808: =cut
5809:
5810: sub check_for_error {
5811: my ($r,$result)=@_;
5812: if ($result ne 'ok' && $result ne 'not_found' ) {
5813: $r->print("An error occurred ($result) when trying to Remove the existing corrections.");
5814: }
5815: }
5816:
5817: =pod
5818:
5819: =item scantron_warning_screen
5820:
5821: Interstitial screen to make sure the operator has selected the
5822: correct options before we start the validation phase.
5823:
5824: =cut
5825:
5826: sub scantron_warning_screen {
5827: my ($button_text)=@_;
5828: my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
5829: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
5830: my $CODElist;
5831: if ($scantron_config{'CODElocation'} &&
5832: $scantron_config{'CODEstart'} &&
5833: $scantron_config{'CODElength'}) {
5834: $CODElist=$env{'form.scantron_CODElist'};
5835: if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
5836: $CODElist=
5837: '<tr><td><b>List of CODES to validate against:</b></td><td><tt>'.
5838: $env{'form.scantron_CODElist'}.'</tt></td></tr>';
5839: }
5840: return (<<STUFF);
5841: <p>
5842: <span class="LC_warning">Please double check the information
5843: below before clicking on '$button_text'</span>
5844: </p>
5845: <table>
5846: <tr><td><b>Sequence to be Graded:</b></td><td>$title</td></tr>
5847: <tr><td><b>Data File that will be used:</b></td><td><tt>$env{'form.scantron_selectfile'}</tt></td></tr>
5848: $CODElist
5849: </table>
5850: <br />
5851: <p> If this information is correct, please click on '$button_text'.</p>
5852: <p> If something is incorrect, please click the 'Grading Menu' button to start over.</p>
5853:
5854: <br />
5855: STUFF
5856: }
5857:
5858: =pod
5859:
5860: =item scantron_do_warning
5861:
5862: Check if the operator has picked something for all required
5863: fields. Error out if something is missing.
5864:
5865: =cut
5866:
5867: sub scantron_do_warning {
5868: my ($r)=@_;
5869: my ($symb)=&get_symb($r);
5870: if (!$symb) {return '';}
5871: my $default_form_data=&defaultFormData($symb);
5872: $r->print(&scantron_form_start().$default_form_data);
5873: if ( $env{'form.selectpage'} eq '' ||
5874: $env{'form.scantron_selectfile'} eq '' ||
5875: $env{'form.scantron_format'} eq '' ) {
5876: $r->print("<p>You have forgetten to specify some information. Please go Back and try again.</p>");
5877: if ( $env{'form.selectpage'} eq '') {
5878: $r->print('<p><span class="LC_error">You have not selected a Sequence to grade</span></p>');
5879: }
5880: if ( $env{'form.scantron_selectfile'} eq '') {
5881: $r->print('<p><span class="LC_error">You have not selected a file that contains the student\'s response data.</span></p>');
5882: }
5883: if ( $env{'form.scantron_format'} eq '') {
5884: $r->print('<p><span class="LC_error">You have not selected a the format of the student\'s response data.</span></p>');
5885: }
5886: } else {
5887: my $warning=&scantron_warning_screen('Grading: Validate Records');
5888: $r->print(<<STUFF);
5889: $warning
5890: <input type="submit" name="submit" value="Grading: Validate Records" />
5891: <input type="hidden" name="command" value="scantron_validate" />
5892: STUFF
5893: }
5894: $r->print("</form><br />".&show_grading_menu_form($symb));
5895: return '';
5896: }
5897:
5898: =pod
5899:
5900: =item scantron_form_start
5901:
5902: html hidden input for remembering all selected grading options
5903:
5904: =cut
5905:
5906: sub scantron_form_start {
5907: my ($max_bubble)=@_;
5908: my $result= <<SCANTRONFORM;
5909: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
5910: <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
5911: <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
5912: <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
5913: <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
5914: <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
5915: <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
5916: <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
5917: <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
5918: <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
5919: SCANTRONFORM
5920:
5921: my $line = 0;
5922: while (defined($env{"form.scantron.bubblelines.$line"})) {
5923: my $chunk =
5924: '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
5925: $chunk .=
5926: '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
5927: $result .= $chunk;
5928: $line++;
5929: }
5930: return $result;
5931: }
5932:
5933: =pod
5934:
5935: =item scantron_validate_file
5936:
5937: Dispatch routine for doing validation of a bubble sheet data file.
5938:
5939: Also processes any necessary information resets that need to
5940: occur before validation begins (ignore previous corrections,
5941: restarting the skipped records processing)
5942:
5943: =cut
5944:
5945: sub scantron_validate_file {
5946: my ($r) = @_;
5947: my ($symb)=&get_symb($r);
5948: if (!$symb) {return '';}
5949: my $default_form_data=&defaultFormData($symb);
5950:
5951: # do the detection of only doing skipped records first befroe we delete
5952: # them when doing the corrections reset
5953: if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
5954: &reset_skipping_status();
5955: }
5956: if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
5957: &remember_current_skipped();
5958: $env{'form.scantron_options_redo'}='redo_skipped_ready';
5959: }
5960:
5961: if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
5962: &check_for_error($r,&scantron_remove_file('corrected'));
5963: &check_for_error($r,&scantron_remove_file('skipped'));
5964: &check_for_error($r,&scantron_remove_scan_data());
5965: $env{'form.scantron_options_ignore'}='done';
5966: }
5967:
5968: if ($env{'form.scantron_corrections'}) {
5969: &scantron_process_corrections($r);
5970: }
5971: $r->print("<p>Gathering necessary info.</p>");$r->rflush();
5972: #get the student pick code ready
5973: $r->print(&Apache::loncommon::studentbrowser_javascript());
5974: my $max_bubble=&scantron_get_maxbubble();
5975: my $result=&scantron_form_start($max_bubble).$default_form_data;
5976: $r->print($result);
5977:
5978: my @validate_phases=( 'sequence',
5979: 'ID',
5980: 'CODE',
5981: 'doublebubble',
5982: 'missingbubbles');
5983: if (!$env{'form.validatepass'}) {
5984: $env{'form.validatepass'} = 0;
5985: }
5986: my $currentphase=$env{'form.validatepass'};
5987:
5988:
5989: my $stop=0;
5990: while (!$stop && $currentphase < scalar(@validate_phases)) {
5991: $r->print("<p> Validating ".$validate_phases[$currentphase]."</p>");
5992: $r->rflush();
5993: my $which="scantron_validate_".$validate_phases[$currentphase];
5994: {
5995: no strict 'refs';
5996: ($stop,$currentphase)=&$which($r,$currentphase);
5997: }
5998: }
5999: if (!$stop) {
6000: my $warning=&scantron_warning_screen('Start Grading');
6001: $r->print(<<STUFF);
6002: Validation process complete.<br />
6003: $warning
6004: <input type="submit" name="submit" value="Start Grading" />
6005: <input type="hidden" name="command" value="scantron_process" />
6006: STUFF
6007:
6008: } else {
6009: $r->print('<input type="hidden" name="command" value="scantron_validate" />');
6010: $r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
6011: }
6012: if ($stop) {
6013: if ($validate_phases[$currentphase] eq 'sequence') {
6014: $r->print('<input type="submit" name="submit" value="Ignore -> " />');
6015: $r->print(' this error <br />');
6016:
6017: $r->print(" <p>Or click the 'Grading Menu' button to start over.</p>");
6018: } else {
6019: $r->print('<input type="submit" name="submit" value="Continue ->" />');
6020: $r->print(' using corrected info <br />');
6021: $r->print("<input type='submit' value='Skip' name='scantron_skip_record' />");
6022: $r->print(" this scanline saving it for later.");
6023: }
6024: }
6025: $r->print(" </form><br />".&show_grading_menu_form($symb));
6026: return '';
6027: }
6028:
6029:
6030: =pod
6031:
6032: =item scantron_remove_file
6033:
6034: Removes the requested bubble sheet data file, makes sure that
6035: scantron_original_<filename> is never removed
6036:
6037:
6038: =cut
6039:
6040: sub scantron_remove_file {
6041: my ($which)=@_;
6042: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6043: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6044: my $file='scantron_';
6045: if ($which eq 'corrected' || $which eq 'skipped') {
6046: $file.=$which.'_';
6047: } else {
6048: return 'refused';
6049: }
6050: $file.=$env{'form.scantron_selectfile'};
6051: return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
6052: }
6053:
6054:
6055: =pod
6056:
6057: =item scantron_remove_scan_data
6058:
6059: Removes all scan_data correction for the requested bubble sheet
6060: data file. (In the case that both the are doing skipped records we need
6061: to remember the old skipped lines for the time being so that element
6062: persists for a while.)
6063:
6064: =cut
6065:
6066: sub scantron_remove_scan_data {
6067: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6068: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6069: my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
6070: my @todelete;
6071: my $filename=$env{'form.scantron_selectfile'};
6072: foreach my $key (@keys) {
6073: if ($key=~/^\Q$filename\E_/) {
6074: if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
6075: $key=~/remember_skipping/) {
6076: next;
6077: }
6078: push(@todelete,$key);
6079: }
6080: }
6081: my $result;
6082: if (@todelete) {
6083: $result=&Apache::lonnet::del('nohist_scantrondata',\@todelete,$cdom,$cname);
6084: }
6085: return $result;
6086: }
6087:
6088:
6089: =pod
6090:
6091: =item scantron_getfile
6092:
6093: Fetches the requested bubble sheet data file (all 3 versions), and
6094: the scan_data hash
6095:
6096: Arguments:
6097: None
6098:
6099: Returns:
6100: 2 hash references
6101:
6102: - first one has
6103: orig -
6104: corrected -
6105: skipped - each of which points to an array ref of the specified
6106: file broken up into individual lines
6107: count - number of scanlines
6108:
6109: - second is the scan_data hash possible keys are
6110: ($number refers to scanline numbered $number and thus the key affects
6111: only that scanline
6112: $bubline refers to the specific bubble line element and the aspects
6113: refers to that specific bubble line element)
6114:
6115: $number.user - username:domain to use
6116: $number.CODE_ignore_dup
6117: - ignore the duplicate CODE error
6118: $number.useCODE
6119: - use the CODE in the scanline as is
6120: $number.no_bubble.$bubline
6121: - it is valid that there is no bubbled in bubble
6122: at $number $bubline
6123: remember_skipping
6124: - a frozen hash containing keys of $number and values
6125: of either
6126: 1 - we are on a 'do skipped records pass' and plan
6127: on processing this line
6128: 2 - we are on a 'do skipped records pass' and this
6129: scanline has been marked to skip yet again
6130:
6131: =cut
6132:
6133: sub scantron_getfile {
6134: #FIXME really would prefer a scantron directory
6135: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6136: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6137: my $lines;
6138: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
6139: 'scantron_orig_'.$env{'form.scantron_selectfile'});
6140: my %scanlines;
6141: $scanlines{'orig'}=[(split("\n",$lines,-1))];
6142: my $temp=$scanlines{'orig'};
6143: $scanlines{'count'}=$#$temp;
6144:
6145: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
6146: 'scantron_corrected_'.$env{'form.scantron_selectfile'});
6147: if ($lines eq '-1') {
6148: $scanlines{'corrected'}=[];
6149: } else {
6150: $scanlines{'corrected'}=[(split("\n",$lines,-1))];
6151: }
6152: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
6153: 'scantron_skipped_'.$env{'form.scantron_selectfile'});
6154: if ($lines eq '-1') {
6155: $scanlines{'skipped'}=[];
6156: } else {
6157: $scanlines{'skipped'}=[(split("\n",$lines,-1))];
6158: }
6159: my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
6160: if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
6161: my %scan_data = @tmp;
6162: return (\%scanlines,\%scan_data);
6163: }
6164:
6165: =pod
6166:
6167: =item lonnet_putfile
6168:
6169: Wrapper routine to call &Apache::lonnet::finishuserfileupload
6170:
6171: Arguments:
6172: $contents - data to store
6173: $filename - filename to store $contents into
6174:
6175: Returns:
6176: result value from &Apache::lonnet::finishuserfileupload
6177:
6178: =cut
6179:
6180: sub lonnet_putfile {
6181: my ($contents,$filename)=@_;
6182: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
6183: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6184: $env{'form.sillywaytopassafilearound'}=$contents;
6185: &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
6186:
6187: }
6188:
6189: =pod
6190:
6191: =item scantron_putfile
6192:
6193: Stores the current version of the bubble sheet data files, and the
6194: scan_data hash. (Does not modify the original version only the
6195: corrected and skipped versions.
6196:
6197: Arguments:
6198: $scanlines - hash ref that looks like the first return value from
6199: &scantron_getfile()
6200: $scan_data - hash ref that looks like the second return value from
6201: &scantron_getfile()
6202:
6203: =cut
6204:
6205: sub scantron_putfile {
6206: my ($scanlines,$scan_data) = @_;
6207: #FIXME really would prefer a scantron directory
6208: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6209: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6210: if ($scanlines) {
6211: my $prefix='scantron_';
6212: # no need to update orig, shouldn't change
6213: # &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
6214: # $env{'form.scantron_selectfile'});
6215: &lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
6216: $prefix.'corrected_'.
6217: $env{'form.scantron_selectfile'});
6218: &lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
6219: $prefix.'skipped_'.
6220: $env{'form.scantron_selectfile'});
6221: }
6222: &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
6223: }
6224:
6225: =pod
6226:
6227: =item scantron_get_line
6228:
6229: Returns the correct version of the scanline
6230:
6231: Arguments:
6232: $scanlines - hash ref that looks like the first return value from
6233: &scantron_getfile()
6234: $scan_data - hash ref that looks like the second return value from
6235: &scantron_getfile()
6236: $i - number of the requested line (starts at 0)
6237:
6238: Returns:
6239: A scanline, (either the original or the corrected one if it
6240: exists), or undef if the requested scanline should be
6241: skipped. (Either because it's an skipped scanline, or it's an
6242: unskipped scanline and we are not doing a 'do skipped scanlines'
6243: pass.
6244:
6245: =cut
6246:
6247: sub scantron_get_line {
6248: my ($scanlines,$scan_data,$i)=@_;
6249: if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
6250: #if ($scanlines->{'skipped'}[$i]) { return undef; }
6251: if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
6252: return $scanlines->{'orig'}[$i];
6253: }
6254:
6255: =pod
6256:
6257: =item scantron_todo_count
6258:
6259: Counts the number of scanlines that need processing.
6260:
6261: Arguments:
6262: $scanlines - hash ref that looks like the first return value from
6263: &scantron_getfile()
6264: $scan_data - hash ref that looks like the second return value from
6265: &scantron_getfile()
6266:
6267: Returns:
6268: $count - number of scanlines to process
6269:
6270: =cut
6271:
6272: sub get_todo_count {
6273: my ($scanlines,$scan_data)=@_;
6274: my $count=0;
6275: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6276: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6277: if ($line=~/^[\s\cz]*$/) { next; }
6278: $count++;
6279: }
6280: return $count;
6281: }
6282:
6283: =pod
6284:
6285: =item scantron_put_line
6286:
6287: Updates the 'corrected' or 'skipped' versions of the bubble sheet
6288: data file.
6289:
6290: Arguments:
6291: $scanlines - hash ref that looks like the first return value from
6292: &scantron_getfile()
6293: $scan_data - hash ref that looks like the second return value from
6294: &scantron_getfile()
6295: $i - line number to update
6296: $newline - contents of the updated scanline
6297: $skip - if true make the line for skipping and update the
6298: 'skipped' file
6299:
6300: =cut
6301:
6302: sub scantron_put_line {
6303: my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
6304: if ($skip) {
6305: $scanlines->{'skipped'}[$i]=$newline;
6306: &start_skipping($scan_data,$i);
6307: return;
6308: }
6309: $scanlines->{'corrected'}[$i]=$newline;
6310: }
6311:
6312: =pod
6313:
6314: =item scantron_clear_skip
6315:
6316: Remove a line from the 'skipped' file
6317:
6318: Arguments:
6319: $scanlines - hash ref that looks like the first return value from
6320: &scantron_getfile()
6321: $scan_data - hash ref that looks like the second return value from
6322: &scantron_getfile()
6323: $i - line number to update
6324:
6325: =cut
6326:
6327: sub scantron_clear_skip {
6328: my ($scanlines,$scan_data,$i)=@_;
6329: if (exists($scanlines->{'skipped'}[$i])) {
6330: undef($scanlines->{'skipped'}[$i]);
6331: return 1;
6332: }
6333: return 0;
6334: }
6335:
6336: =pod
6337:
6338: =item scantron_filter_not_exam
6339:
6340: Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
6341: filter out resources that are not marked as 'exam' mode
6342:
6343: =cut
6344:
6345: sub scantron_filter_not_exam {
6346: my ($curres)=@_;
6347:
6348: if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
6349: # if the user has asked to not have either hidden
6350: # or 'randomout' controlled resources to be graded
6351: # don't include them
6352: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
6353: && $curres->randomout) {
6354: return 0;
6355: }
6356: return 1;
6357: }
6358: return 0;
6359: }
6360:
6361: =pod
6362:
6363: =item scantron_validate_sequence
6364:
6365: Validates the selected sequence, checking for resource that are
6366: not set to exam mode.
6367:
6368: =cut
6369:
6370: sub scantron_validate_sequence {
6371: my ($r,$currentphase) = @_;
6372:
6373: my $navmap=Apache::lonnavmaps::navmap->new();
6374: my (undef,undef,$sequence)=
6375: &Apache::lonnet::decode_symb($env{'form.selectpage'});
6376:
6377: my $map=$navmap->getResourceByUrl($sequence);
6378:
6379: $r->print('<input type="hidden" name="validate_sequence_exam"
6380: value="ignore" />');
6381: if ($env{'form.validate_sequence_exam'} ne 'ignore') {
6382: my @resources=
6383: $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
6384: if (@resources) {
6385: $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>");
6386: return (1,$currentphase);
6387: }
6388: }
6389:
6390: return (0,$currentphase+1);
6391: }
6392:
6393: =pod
6394:
6395: =item scantron_validate_ID
6396:
6397: Validates all scanlines in the selected file to not have any
6398: invalid or underspecified student IDs
6399:
6400: =cut
6401:
6402: sub scantron_validate_ID {
6403: my ($r,$currentphase) = @_;
6404:
6405: #get student info
6406: my $classlist=&Apache::loncoursedata::get_classlist();
6407: my %idmap=&username_to_idmap($classlist);
6408:
6409: #get scantron line setup
6410: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6411: my ($scanlines,$scan_data)=&scantron_getfile();
6412:
6413: &scantron_get_maxbubble(); # parse needs the bubble_lines.. array.
6414:
6415: my %found=('ids'=>{},'usernames'=>{});
6416: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6417: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6418: if ($line=~/^[\s\cz]*$/) { next; }
6419: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6420: $scan_data);
6421: my $id=$$scan_record{'scantron.ID'};
6422: my $found;
6423: foreach my $checkid (keys(%idmap)) {
6424: if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
6425: }
6426: if ($found) {
6427: my $username=$idmap{$found};
6428: if ($found{'ids'}{$found}) {
6429: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6430: $line,'duplicateID',$found);
6431: return(1,$currentphase);
6432: } elsif ($found{'usernames'}{$username}) {
6433: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6434: $line,'duplicateID',$username);
6435: return(1,$currentphase);
6436: }
6437: #FIXME store away line we previously saw the ID on to use above
6438: $found{'ids'}{$found}++;
6439: $found{'usernames'}{$username}++;
6440: } else {
6441: if ($id =~ /^\s*$/) {
6442: my $username=&scan_data($scan_data,"$i.user");
6443: if (defined($username) && $found{'usernames'}{$username}) {
6444: &scantron_get_correction($r,$i,$scan_record,
6445: \%scantron_config,
6446: $line,'duplicateID',$username);
6447: return(1,$currentphase);
6448: } elsif (!defined($username)) {
6449: &scantron_get_correction($r,$i,$scan_record,
6450: \%scantron_config,
6451: $line,'incorrectID');
6452: return(1,$currentphase);
6453: }
6454: $found{'usernames'}{$username}++;
6455: } else {
6456: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6457: $line,'incorrectID');
6458: return(1,$currentphase);
6459: }
6460: }
6461: }
6462:
6463: return (0,$currentphase+1);
6464: }
6465:
6466: =pod
6467:
6468: =item scantron_get_correction
6469:
6470: Builds the interface screen to interact with the operator to fix a
6471: specific error condition in a specific scanline
6472:
6473: Arguments:
6474: $r - Apache request object
6475: $i - number of the current scanline
6476: $scan_record - hash ref as returned from &scantron_parse_scanline()
6477: $scan_config - hash ref as returned from &get_scantron_config()
6478: $line - full contents of the current scanline
6479: $error - error condition, valid values are
6480: 'incorrectCODE', 'duplicateCODE',
6481: 'doublebubble', 'missingbubble',
6482: 'duplicateID', 'incorrectID'
6483: $arg - extra information needed
6484: For errors:
6485: - duplicateID - paper number that this studentID was seen before on
6486: - duplicateCODE - array ref of the paper numbers this CODE was
6487: seen on before
6488: - incorrectCODE - current incorrect CODE
6489: - doublebubble - array ref of the bubble lines that have double
6490: bubble errors
6491: - missingbubble - array ref of the bubble lines that have missing
6492: bubble errors
6493:
6494: =cut
6495:
6496: sub scantron_get_correction {
6497: my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
6498:
6499: #FIXME in the case of a duplicated ID the previous line, probably need
6500: #to show both the current line and the previous one and allow skipping
6501: #the previous one or the current one
6502:
6503: $r->print("<p><b>An error was detected ($error)</b>");
6504: if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
6505: $r->print(" for PaperID <tt>".
6506: $$scan_record{'scantron.PaperID'}."</tt> \n");
6507: } else {
6508: $r->print(" in scanline $i <pre>".
6509: $line."</pre> \n");
6510: }
6511: my $message="<p>The ID on the form is <tt>".
6512: $$scan_record{'scantron.ID'}."</tt><br />\n".
6513: "The name on the paper is ".
6514: $$scan_record{'scantron.LastName'}.",".
6515: $$scan_record{'scantron.FirstName'}."</p>";
6516:
6517: $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
6518: $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
6519: if ($error =~ /ID$/) {
6520: if ($error eq 'incorrectID') {
6521: $r->print("The encoded ID is not in the classlist</p>\n");
6522: } elsif ($error eq 'duplicateID') {
6523: $r->print("The encoded ID has also been used by a previous paper $arg</p>\n");
6524: }
6525: $r->print($message);
6526: $r->print("<p>How should I handle this? <br /> \n");
6527: $r->print("\n<ul><li> ");
6528: #FIXME it would be nice if this sent back the user ID and
6529: #could do partial userID matches
6530: $r->print(&Apache::loncommon::selectstudent_link('scantronupload',
6531: 'scantron_username','scantron_domain'));
6532: $r->print(": <input type='text' name='scantron_username' value='' />");
6533: $r->print("\n@".
6534: &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
6535:
6536: $r->print('</li>');
6537: } elsif ($error =~ /CODE$/) {
6538: if ($error eq 'incorrectCODE') {
6539: $r->print("</p><p>The encoded CODE is not in the list of possible CODEs</p>\n");
6540: } elsif ($error eq 'duplicateCODE') {
6541: $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");
6542: }
6543: $r->print("<p>The CODE on the form is <tt>'".
6544: $$scan_record{'scantron.CODE'}."'</tt><br />\n");
6545: $r->print($message);
6546: $r->print("<p>How should I handle this? <br /> \n");
6547: $r->print("\n<br /> ");
6548: my $i=0;
6549: if ($error eq 'incorrectCODE'
6550: && $$scan_record{'scantron.CODE'}=~/\S/ ) {
6551: my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
6552: if ($closest > 0) {
6553: foreach my $testcode (@{$closest}) {
6554: my $checked='';
6555: if (!$i) { $checked=' checked="checked" '; }
6556: $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' />");
6557: $r->print("\n<br />");
6558: $i++;
6559: }
6560: }
6561: }
6562: if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
6563: my $checked; if (!$i) { $checked=' checked="checked" '; }
6564: $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>");
6565: $r->print("\n<br />");
6566: }
6567:
6568: $r->print(<<ENDSCRIPT);
6569: <script type="text/javascript">
6570: function change_radio(field) {
6571: var slct=document.scantronupload.scantron_CODE_resolution;
6572: var i;
6573: for (i=0;i<slct.length;i++) {
6574: if (slct[i].value==field) { slct[i].checked=true; }
6575: }
6576: }
6577: </script>
6578: ENDSCRIPT
6579: my $href="/adm/pickcode?".
6580: "form=".&escape("scantronupload").
6581: "&scantron_format=".&escape($env{'form.scantron_format'}).
6582: "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
6583: "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
6584: "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
6585: if ($env{'form.scantron_CODElist'} =~ /\S/) {
6586: $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')\" />");
6587: $r->print("\n<br />");
6588: }
6589: $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.");
6590: $r->print("\n<br /><br />");
6591: } elsif ($error eq 'doublebubble') {
6592: $r->print("<p>There have been multiple bubbles scanned for a some question(s)</p>\n");
6593: $r->print('<input type="hidden" name="scantron_questions" value="'.
6594: join(',',@{$arg}).'" />');
6595: $r->print($message);
6596: $r->print("<p>Please indicate which bubble should be used for grading</p>");
6597: foreach my $question (@{$arg}) {
6598: my $selected = &get_response_bubbles($scan_record, $question);
6599: my @select_array = split(/:/,$selected);
6600: &scantron_bubble_selector($r,$scan_config,$question,
6601: @select_array);
6602: }
6603: } elsif ($error eq 'missingbubble') {
6604: $r->print("<p>There have been <b>no</b> bubbles scanned for some question(s)</p>\n");
6605: $r->print($message);
6606: $r->print("<p>Please indicate which bubble should be used for grading</p>");
6607: $r->print("Some questions have no scanned bubbles\n");
6608: $r->print('<input type="hidden" name="scantron_questions" value="'.
6609: join(',',@{$arg}).'" />');
6610: foreach my $question (@{$arg}) {
6611: my $selected = &get_response_bubbles($scan_record, $question);
6612: my @select_array = split(/:/,$selected); # ought to be an array of empties.
6613: &scantron_bubble_selector($r,$scan_config,$question, @select_array);
6614: }
6615: } else {
6616: $r->print("\n<ul>");
6617: }
6618: $r->print("\n</li></ul>");
6619:
6620: }
6621:
6622: =pod
6623:
6624: =item scantron_bubble_selector
6625:
6626: Generates the html radiobuttons to correct a single bubble line
6627: possibly showing the existing the selected bubbles if known
6628:
6629: Arguments:
6630: $r - Apache request object
6631: $scan_config - hash from &get_scantron_config()
6632: $quest - number of the bubble line to make a corrector for
6633: @lines - array of answer lines.
6634:
6635: =cut
6636:
6637: sub scantron_bubble_selector {
6638: my ($r,$scan_config,$quest,@lines)=@_;
6639: my $max=$$scan_config{'Qlength'};
6640:
6641:
6642: my $scmode=$$scan_config{'Qon'};
6643:
6644: my $bubble_length = scalar(@lines);
6645:
6646:
6647: if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }
6648:
6649: my $response = $quest-1;
6650: my $lines = $bubble_lines_per_response{$response};
6651:
6652: my $total_lines = $lines*2;
6653: my @alphabet=('A'..'Z');
6654:
6655: $r->print("<table border='1'><tr><td rowspan='".$total_lines."'>$quest</td>");
6656:
6657: for (my $l = 0; $l < $lines; $l++) {
6658: if ($l != 0) {
6659: $r->print('<tr>');
6660: }
6661: my @selected = split(//,$lines[$l]);
6662: for (my $i=0;$i<$max;$i++) {
6663: $r->print("\n".'<td align="center">');
6664: if ($selected[0] eq $alphabet[$i]) {
6665: $r->print('X');
6666: shift(@selected) ;
6667: } else {
6668: $r->print(' ');
6669: }
6670: $r->print('</td>');
6671:
6672: }
6673:
6674: if ($l == 0) {
6675: my $lspan = $total_lines * 2; # 2 table rows per bubble line.
6676:
6677: $r->print('<td rowspan='.$lspan.'><label><input type="radio" name="scantron_correct_Q_'.
6678: $quest.'" value="none" /> No bubble </label></td>');
6679:
6680: }
6681:
6682: $r->print('</tr><tr>');
6683:
6684: # FIXME: This may have to be a bit more clever for
6685: # multiline questions (different values e.g..).
6686:
6687: for (my $i=0;$i<$max;$i++) {
6688: my $value = "$l:$i"; # Relative bubble line #: Bubble in line.
6689: $r->print("\n".
6690: '<td><label><input type="radio" name="scantron_correct_Q_'.
6691: $quest.'" value="'.$value.'" />'.$alphabet[$i]."</label></td>");
6692: }
6693: $r->print('</tr>');
6694:
6695:
6696: }
6697: $r->print('</table>');
6698: }
6699:
6700: =pod
6701:
6702: =item num_matches
6703:
6704: Counts the number of characters that are the same between the two arguments.
6705:
6706: Arguments:
6707: $orig - CODE from the scanline
6708: $code - CODE to match against
6709:
6710: Returns:
6711: $count - integer count of the number of same characters between the
6712: two arguments
6713:
6714: =cut
6715:
6716: sub num_matches {
6717: my ($orig,$code) = @_;
6718: my @code=split(//,$code);
6719: my @orig=split(//,$orig);
6720: my $same=0;
6721: for (my $i=0;$i<scalar(@code);$i++) {
6722: if ($code[$i] eq $orig[$i]) { $same++; }
6723: }
6724: return $same;
6725: }
6726:
6727: =pod
6728:
6729: =item scantron_get_closely_matching_CODEs
6730:
6731: Cycles through all CODEs and finds the set that has the greatest
6732: number of same characters as the provided CODE
6733:
6734: Arguments:
6735: $allcodes - hash ref returned by &get_codes()
6736: $CODE - CODE from the current scanline
6737:
6738: Returns:
6739: 2 element list
6740: - first elements is number of how closely matching the best fit is
6741: (5 means best set has 5 matching characters)
6742: - second element is an arrary ref containing the set of valid CODEs
6743: that best fit the passed in CODE
6744:
6745: =cut
6746:
6747: sub scantron_get_closely_matching_CODEs {
6748: my ($allcodes,$CODE)=@_;
6749: my @CODEs;
6750: foreach my $testcode (sort(keys(%{$allcodes}))) {
6751: push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
6752: }
6753:
6754: return ($#CODEs,$CODEs[-1]);
6755: }
6756:
6757: =pod
6758:
6759: =item get_codes
6760:
6761: Builds a hash which has keys of all of the valid CODEs from the selected
6762: set of remembered CODEs.
6763:
6764: Arguments:
6765: $old_name - name of the set of remembered CODEs
6766: $cdom - domain of the course
6767: $cnum - internal course name
6768:
6769: Returns:
6770: %allcodes - keys are the valid CODEs, values are all 1
6771:
6772: =cut
6773:
6774: sub get_codes {
6775: my ($old_name, $cdom, $cnum) = @_;
6776: if (!$old_name) {
6777: $old_name=$env{'form.scantron_CODElist'};
6778: }
6779: if (!$cdom) {
6780: $cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
6781: }
6782: if (!$cnum) {
6783: $cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
6784: }
6785: my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
6786: $cdom,$cnum);
6787: my %allcodes;
6788: if ($result{"type\0$old_name"} eq 'number') {
6789: %allcodes=map {($_,1)} split(',',$result{$old_name});
6790: } else {
6791: %allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
6792: }
6793: return %allcodes;
6794: }
6795:
6796: =pod
6797:
6798: =item scantron_validate_CODE
6799:
6800: Validates all scanlines in the selected file to not have any
6801: invalid or underspecified CODEs and that none of the codes are
6802: duplicated if this was requested.
6803:
6804: =cut
6805:
6806: sub scantron_validate_CODE {
6807: my ($r,$currentphase) = @_;
6808: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6809: if ($scantron_config{'CODElocation'} &&
6810: $scantron_config{'CODEstart'} &&
6811: $scantron_config{'CODElength'}) {
6812: if (!defined($env{'form.scantron_CODElist'})) {
6813: &FIXME_blow_up()
6814: }
6815: } else {
6816: return (0,$currentphase+1);
6817: }
6818:
6819: my %usedCODEs;
6820:
6821: my %allcodes=&get_codes();
6822:
6823: &scantron_get_maxbubble(); # parse needs the lines per response array.
6824:
6825: my ($scanlines,$scan_data)=&scantron_getfile();
6826: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6827: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6828: if ($line=~/^[\s\cz]*$/) { next; }
6829: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6830: $scan_data);
6831: my $CODE=$$scan_record{'scantron.CODE'};
6832: my $error=0;
6833: if (!&Apache::lonnet::validCODE($CODE)) {
6834: &scantron_get_correction($r,$i,$scan_record,
6835: \%scantron_config,
6836: $line,'incorrectCODE',\%allcodes);
6837: return(1,$currentphase);
6838: }
6839: if (%allcodes && !exists($allcodes{$CODE})
6840: && !$$scan_record{'scantron.useCODE'}) {
6841: &scantron_get_correction($r,$i,$scan_record,
6842: \%scantron_config,
6843: $line,'incorrectCODE',\%allcodes);
6844: return(1,$currentphase);
6845: }
6846: if (exists($usedCODEs{$CODE})
6847: && $env{'form.scantron_CODEunique'} eq 'yes'
6848: && !$$scan_record{'scantron.CODE_ignore_dup'}) {
6849: &scantron_get_correction($r,$i,$scan_record,
6850: \%scantron_config,
6851: $line,'duplicateCODE',$usedCODEs{$CODE});
6852: return(1,$currentphase);
6853: }
6854: push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
6855: }
6856: return (0,$currentphase+1);
6857: }
6858:
6859: =pod
6860:
6861: =item scantron_validate_doublebubble
6862:
6863: Validates all scanlines in the selected file to not have any
6864: bubble lines with multiple bubbles marked.
6865:
6866: =cut
6867:
6868: sub scantron_validate_doublebubble {
6869: my ($r,$currentphase) = @_;
6870: #get student info
6871: my $classlist=&Apache::loncoursedata::get_classlist();
6872: my %idmap=&username_to_idmap($classlist);
6873:
6874: #get scantron line setup
6875: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6876: my ($scanlines,$scan_data)=&scantron_getfile();
6877:
6878: &scantron_get_maxbubble(); # parse needs the bubble line array.
6879:
6880: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6881: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6882: if ($line=~/^[\s\cz]*$/) { next; }
6883: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6884: $scan_data);
6885: if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
6886: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
6887: 'doublebubble',
6888: $$scan_record{'scantron.doubleerror'});
6889: return (1,$currentphase);
6890: }
6891: return (0,$currentphase+1);
6892: }
6893:
6894: =pod
6895:
6896: =item scantron_get_maxbubble
6897:
6898: Returns the maximum number of bubble lines that are expected to
6899: occur. Does this by walking the selected sequence rendering the
6900: resource and then checking &Apache::lonxml::get_problem_counter()
6901: for what the current value of the problem counter is.
6902:
6903: Caches the results to $env{'form.scantron_maxbubble'},
6904: $env{'form.scantron.bubble_lines.n'} and
6905: $env{'form.scantron.first_bubble_line.n'}
6906: which are the total number of bubble, lines, the number of bubble
6907: lines for reponse n and number of the first bubble line for response n.
6908:
6909: =cut
6910:
6911: sub scantron_get_maxbubble {
6912: if (defined($env{'form.scantron_maxbubble'}) &&
6913: $env{'form.scantron_maxbubble'}) {
6914: &restore_bubble_lines();
6915: return $env{'form.scantron_maxbubble'};
6916: }
6917:
6918: my (undef, undef, $sequence) =
6919: &Apache::lonnet::decode_symb($env{'form.selectpage'});
6920:
6921: my $navmap=Apache::lonnavmaps::navmap->new();
6922: my $map=$navmap->getResourceByUrl($sequence);
6923: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
6924:
6925: &Apache::lonxml::clear_problem_counter();
6926:
6927: my $uname = $env{'form.student'};
6928: my $udom = $env{'form.userdom'};
6929: my $cid = $env{'request.course.id'};
6930: my $total_lines = 0;
6931: %bubble_lines_per_response = ();
6932: %first_bubble_line = ();
6933:
6934:
6935: my $response_number = 0;
6936: my $bubble_line = 0;
6937: foreach my $resource (@resources) {
6938: my $symb = $resource->symb();
6939: &Apache::lonxml::clear_bubble_lines_for_part();
6940: my $result=&Apache::lonnet::ssi($resource->src(),
6941: ('symb' => $resource->symb()),
6942: ('grade_target' => 'analyze'),
6943: ('grade_courseid' => $cid),
6944: ('grade_domain' => $udom),
6945: ('grade_username' => $uname));
6946: my (undef, $an) =
6947: split(/_HASH_REF__/,$result, 2);
6948:
6949: my %analysis = &Apache::lonnet::str2hash($an);
6950:
6951:
6952:
6953: foreach my $part_id (@{$analysis{'parts'}}) {
6954:
6955:
6956: my $lines = $analysis{"$part_id.bubble_lines"};;
6957:
6958: # TODO - make this a persistent hash not an array.
6959:
6960:
6961: $first_bubble_line{$response_number} = $bubble_line;
6962: $bubble_lines_per_response{$response_number} = $lines;
6963: $response_number++;
6964:
6965: $bubble_line += $lines;
6966: $total_lines += $lines;
6967: }
6968:
6969: }
6970: &Apache::lonnet::delenv('scantron\.');
6971:
6972: &save_bubble_lines();
6973: $env{'form.scantron_maxbubble'} =
6974: $total_lines;
6975: return $env{'form.scantron_maxbubble'};
6976: }
6977:
6978: =pod
6979:
6980: =item scantron_validate_missingbubbles
6981:
6982: Validates all scanlines in the selected file to not have any
6983: answers that don't have bubbles that have not been verified
6984: to be bubble free.
6985:
6986: =cut
6987:
6988: sub scantron_validate_missingbubbles {
6989: my ($r,$currentphase) = @_;
6990: #get student info
6991: my $classlist=&Apache::loncoursedata::get_classlist();
6992: my %idmap=&username_to_idmap($classlist);
6993:
6994: #get scantron line setup
6995: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6996: my ($scanlines,$scan_data)=&scantron_getfile();
6997: my $max_bubble=&scantron_get_maxbubble();
6998: if (!$max_bubble) { $max_bubble=2**31; }
6999: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7000: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7001: if ($line=~/^[\s\cz]*$/) { next; }
7002: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7003: $scan_data);
7004: if (!defined($$scan_record{'scantron.missingerror'})) { next; }
7005: my @to_correct;
7006:
7007: # Probably here's where the error is...
7008:
7009: foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
7010: if ($missing > $max_bubble) { next; }
7011: push(@to_correct,$missing);
7012: }
7013: if (@to_correct) {
7014: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
7015: $line,'missingbubble',\@to_correct);
7016: return (1,$currentphase);
7017: }
7018:
7019: }
7020: return (0,$currentphase+1);
7021: }
7022:
7023: =pod
7024:
7025: =item scantron_process_students
7026:
7027: Routine that does the actual grading of the bubble sheet information.
7028:
7029: The parsed scanline hash is added to %env
7030:
7031: Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
7032: foreach resource , with the form data of
7033:
7034: 'submitted' =>'scantron'
7035: 'grade_target' =>'grade',
7036: 'grade_username'=> username of student
7037: 'grade_domain' => domain of student
7038: 'grade_courseid'=> of course
7039: 'grade_symb' => symb of resource to grade
7040:
7041: This triggers a grading pass. The problem grading code takes care
7042: of converting the bubbled letter information (now in %env) into a
7043: valid submission.
7044:
7045: =cut
7046:
7047: sub scantron_process_students {
7048: my ($r) = @_;
7049: my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
7050: my ($symb)=&get_symb($r);
7051: if (!$symb) {return '';}
7052: my $default_form_data=&defaultFormData($symb);
7053:
7054: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7055: my ($scanlines,$scan_data)=&scantron_getfile();
7056: my $classlist=&Apache::loncoursedata::get_classlist();
7057: my %idmap=&username_to_idmap($classlist);
7058: my $navmap=Apache::lonnavmaps::navmap->new();
7059: my $map=$navmap->getResourceByUrl($sequence);
7060: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
7061: # $r->print("geto ".scalar(@resources)."<br />");
7062: my $result= <<SCANTRONFORM;
7063: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
7064: <input type="hidden" name="command" value="scantron_configphase" />
7065: $default_form_data
7066: SCANTRONFORM
7067: $r->print($result);
7068:
7069: my @delayqueue;
7070: my %completedstudents;
7071:
7072: my $count=&get_todo_count($scanlines,$scan_data);
7073: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
7074: 'Scantron Progress',$count,
7075: 'inline',undef,'scantronupload');
7076: &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
7077: 'Processing first student');
7078: my $start=&Time::HiRes::time();
7079: my $i=-1;
7080: my ($uname,$udom,$started);
7081:
7082: &scantron_get_maxbubble(); # Need the bubble lines array to parse.
7083:
7084: while ($i<$scanlines->{'count'}) {
7085: ($uname,$udom)=('','');
7086: $i++;
7087: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7088: if ($line=~/^[\s\cz]*$/) { next; }
7089: if ($started) {
7090: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
7091: 'last student');
7092: }
7093: $started=1;
7094: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7095: $scan_data);
7096: unless ($uname=&scantron_find_student($scan_record,$scan_data,
7097: \%idmap,$i)) {
7098: &scantron_add_delay(\@delayqueue,$line,
7099: 'Unable to find a student that matches',1);
7100: next;
7101: }
7102: if (exists $completedstudents{$uname}) {
7103: &scantron_add_delay(\@delayqueue,$line,
7104: 'Student '.$uname.' has multiple sheets',2);
7105: next;
7106: }
7107: ($uname,$udom)=split(/:/,$uname);
7108:
7109: &Apache::lonxml::clear_problem_counter();
7110: &Apache::lonnet::appenv(%$scan_record);
7111:
7112: if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
7113: &scantron_putfile($scanlines,$scan_data);
7114: }
7115:
7116: my $i=0;
7117: foreach my $resource (@resources) {
7118: $i++;
7119: my %form=('submitted' =>'scantron',
7120: 'grade_target' =>'grade',
7121: 'grade_username'=>$uname,
7122: 'grade_domain' =>$udom,
7123: 'grade_courseid'=>$env{'request.course.id'},
7124: 'grade_symb' =>$resource->symb());
7125: if (exists($scan_record->{'scantron.CODE'})
7126: &&
7127: &Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
7128: $form{'CODE'}=$scan_record->{'scantron.CODE'};
7129: } else {
7130: $form{'CODE'}='';
7131: }
7132: my $result=&Apache::lonnet::ssi($resource->src(),%form);
7133: if ($result ne '') {
7134: }
7135: if (&Apache::loncommon::connection_aborted($r)) { last; }
7136: }
7137: $completedstudents{$uname}={'line'=>$line};
7138: if (&Apache::loncommon::connection_aborted($r)) { last; }
7139: } continue {
7140: &Apache::lonxml::clear_problem_counter();
7141: &Apache::lonnet::delenv('scantron\.');
7142: }
7143: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
7144: # my $lasttime = &Time::HiRes::time()-$start;
7145: # $r->print("<p>took $lasttime</p>");
7146:
7147: $r->print("</form>");
7148: $r->print(&show_grading_menu_form($symb));
7149: return '';
7150: }
7151:
7152: =pod
7153:
7154: =item scantron_upload_scantron_data
7155:
7156: Creates the screen for adding a new bubble sheet data file to a course.
7157:
7158: =cut
7159:
7160: sub scantron_upload_scantron_data {
7161: my ($r)=@_;
7162: $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
7163: my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
7164: 'domainid',
7165: 'coursename');
7166: my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
7167: 'domainid');
7168: my $default_form_data=&defaultFormData(&get_symb($r,1));
7169: $r->print(<<UPLOAD);
7170: <script type="text/javascript" language="javascript">
7171: function checkUpload(formname) {
7172: if (formname.upfile.value == "") {
7173: alert("Please use the browse button to select a file from your local directory.");
7174: return false;
7175: }
7176: formname.submit();
7177: }
7178: </script>
7179:
7180: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
7181: $default_form_data
7182: <table>
7183: <tr><td>$select_link </td></tr>
7184: <tr><td>Course ID: </td><td><input name='courseid' type='text' /> </td></tr>
7185: <tr><td>Course Name: </td><td><input name='coursename' type='text' /></td></tr>
7186: <tr><td>Domain: </td><td>$domsel </td></tr>
7187: <tr><td>File to upload:</td><td><input type="file" name="upfile" size="50" /></td></tr>
7188: </table>
7189: <input name='command' value='scantronupload_save' type='hidden' />
7190: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
7191: </form>
7192: UPLOAD
7193: return '';
7194: }
7195:
7196: =pod
7197:
7198: =item scantron_upload_scantron_data_save
7199:
7200: Adds a provided bubble information data file to the course if user
7201: has the correct privileges to do so.
7202:
7203: =cut
7204:
7205: sub scantron_upload_scantron_data_save {
7206: my($r)=@_;
7207: my ($symb)=&get_symb($r,1);
7208: my $doanotherupload=
7209: '<br /><form action="/adm/grades" method="post">'."\n".
7210: '<input type="hidden" name="command" value="scantronupload" />'."\n".
7211: '<input type="submit" name="submit" value="Do Another Upload" />'."\n".
7212: '</form>'."\n";
7213: if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
7214: !&Apache::lonnet::allowed('usc',
7215: $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
7216: $r->print("You are not allowed to upload Scantron data to the requested course.<br />");
7217: if ($symb) {
7218: $r->print(&show_grading_menu_form($symb));
7219: } else {
7220: $r->print($doanotherupload);
7221: }
7222: return '';
7223: }
7224: my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
7225: $r->print("Doing upload to ".$coursedata{'description'}." <br />");
7226: my $fname=$env{'form.upfile.filename'};
7227: #FIXME
7228: #copied from lonnet::userfileupload()
7229: #make that function able to target a specified course
7230: # Replace Windows backslashes by forward slashes
7231: $fname=~s/\\/\//g;
7232: # Get rid of everything but the actual filename
7233: $fname=~s/^.*\/([^\/]+)$/$1/;
7234: # Replace spaces by underscores
7235: $fname=~s/\s+/\_/g;
7236: # Replace all other weird characters by nothing
7237: $fname=~s/[^\w\.\-]//g;
7238: # See if there is anything left
7239: unless ($fname) { return 'error: no uploaded file'; }
7240: my $uploadedfile=$fname;
7241: $fname='scantron_orig_'.$fname;
7242: if (length($env{'form.upfile'}) < 2) {
7243: $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.");
7244: } else {
7245: my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
7246: if ($result =~ m|^/uploaded/|) {
7247: $r->print("<span class=\"LC_success\">Success:</span> Successfully uploaded ".(length($env{'form.upfile'})-1)." bytes of data into location <tt>".$result."</tt>");
7248: } else {
7249: $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>");
7250: }
7251: }
7252: if ($symb) {
7253: $r->print(&scantron_selectphase($r,$uploadedfile));
7254: } else {
7255: $r->print($doanotherupload);
7256: }
7257: return '';
7258: }
7259:
7260: =pod
7261:
7262: =item valid_file
7263:
7264: Validates that the requested bubble data file exists in the course.
7265:
7266: =cut
7267:
7268: sub valid_file {
7269: my ($requested_file)=@_;
7270: foreach my $filename (sort(&scantron_filenames())) {
7271: if ($requested_file eq $filename) { return 1; }
7272: }
7273: return 0;
7274: }
7275:
7276: =pod
7277:
7278: =item scantron_download_scantron_data
7279:
7280: Shows a list of the three internal files (original, corrected,
7281: skipped) for a specific bubble sheet data file that exists in the
7282: course.
7283:
7284: =cut
7285:
7286: sub scantron_download_scantron_data {
7287: my ($r)=@_;
7288: my $default_form_data=&defaultFormData(&get_symb($r,1));
7289: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7290: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7291: my $file=$env{'form.scantron_selectfile'};
7292: if (! &valid_file($file)) {
7293: $r->print(<<ERROR);
7294: <p>
7295: The requested file name was invalid.
7296: </p>
7297: ERROR
7298: $r->print(&show_grading_menu_form(&get_symb($r,1)));
7299: return;
7300: }
7301: my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
7302: my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
7303: my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
7304: &Apache::lonnet::allowuploaded('/adm/grades',$orig);
7305: &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
7306: &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
7307: $r->print(<<DOWNLOAD);
7308: <p>
7309: <a href="$orig">Original</a> file as uploaded by the scantron office.
7310: </p>
7311: <p>
7312: <a href="$corrected">Corrections</a>, a file of corrected records that were used in grading.
7313: </p>
7314: <p>
7315: <a href="$skipped">Skipped</a>, a file of records that were skipped.
7316: </p>
7317: DOWNLOAD
7318: $r->print(&show_grading_menu_form(&get_symb($r,1)));
7319: return '';
7320: }
7321:
7322: =pod
7323:
7324: =back
7325:
7326: =cut
7327:
7328: #-------- end of section for handling grading scantron forms -------
7329: #
7330: #-------------------------------------------------------------------
7331:
7332: #-------------------------- Menu interface -------------------------
7333: #
7334: #--- Show a Grading Menu button - Calls the next routine ---
7335: sub show_grading_menu_form {
7336: my ($symb)=@_;
7337: my $result.='<br /><form action="/adm/grades" method="post">'."\n".
7338: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
7339: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
7340: '<input type="hidden" name="command" value="gradingmenu" />'."\n".
7341: '<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
7342: '</form>'."\n";
7343: return $result;
7344: }
7345:
7346: # -- Retrieve choices for grading form
7347: sub savedState {
7348: my %savedState = ();
7349: if ($env{'form.saveState'}) {
7350: foreach (split(/:/,$env{'form.saveState'})) {
7351: my ($key,$value) = split(/=/,$_,2);
7352: $savedState{$key} = $value;
7353: }
7354: }
7355: return \%savedState;
7356: }
7357:
7358: sub grading_menu {
7359: my ($request) = @_;
7360: my ($symb)=&get_symb($request);
7361: if (!$symb) {return '';}
7362: my $probTitle = &Apache::lonnet::gettitle($symb);
7363: my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
7364:
7365: $request->print($table);
7366: my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
7367: 'handgrade'=>$hdgrade,
7368: 'probTitle'=>$probTitle,
7369: 'command'=>'submit_options',
7370: 'saveState'=>"",
7371: 'gradingMenu'=>1,
7372: 'showgrading'=>"yes");
7373: my $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
7374: my @menu = ({ url => $url,
7375: name => &mt('Manual Grading/View Submissions'),
7376: short_description =>
7377: &mt('Start the process of hand grading submissions.'),
7378: });
7379: $fields{'command'} = 'csvform';
7380: $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
7381: push (@menu, { url => $url,
7382: name => &mt('Upload Scores'),
7383: short_description =>
7384: &mt('Specify a file containing the class scores for current resource.')});
7385: $fields{'command'} = 'processclicker';
7386: $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
7387: push (@menu, { url => $url,
7388: name => &mt('Process Clicker'),
7389: short_description =>
7390: &mt('Specify a file containing the clicker information for this resource.')});
7391: $fields{'command'} = 'scantron_selectphase';
7392: $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
7393: push (@menu, { url => $url,
7394: name => &mt('Grade/Manage Scantron Forms'),
7395: short_description =>
7396: &mt('')});
7397: $fields{'command'} = 'verify';
7398: $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
7399: push (@menu, { url => "",
7400: name => &mt('Verify Receipt'),
7401: short_description =>
7402: &mt('')});
7403: #
7404: # Create the menu
7405: my $Str;
7406: # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
7407: $Str .= '<form method="post" action="" name="gradingMenu">';
7408: $Str .= '<input type="hidden" name="command" value="" />'.
7409: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
7410: '<input type="hidden" name="handgrade" value="'.$hdgrade.'" />'."\n".
7411: '<input type="hidden" name="probTitle" value="'.$probTitle.'" />'."\n".
7412: '<input type="hidden" name="saveState" value="" />'."\n".
7413: '<input type="hidden" name="gradingMenu" value="1" />'."\n".
7414: '<input type="hidden" name="showgrading" value="yes" />'."\n";
7415:
7416: foreach my $menudata (@menu) {
7417: if ($menudata->{'name'} ne &mt('Verify Receipt')) {
7418: $Str .=' <h3><a '.
7419: $menudata->{'jscript'}.
7420: ' href="'.
7421: $menudata->{'url'}.'" >'.
7422: $menudata->{'name'}."</a></h3>\n";
7423: } else {
7424: $Str .=' <h3><input type="button" value="'.&mt('Verify Receipt').'" '.
7425: $menudata->{'jscript'}.
7426: ' onClick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
7427: ' /></h3>';
7428: $Str .= (' 'x8).
7429: &mt(' receipt: [_1]',
7430: &Apache::lonnet::recprefix($env{'request.course.id'}).
7431: '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />');
7432: }
7433: $Str .= ' '.(' 'x8).$menudata->{'short_description'}.
7434: "\n";
7435: }
7436: $Str .="</form>\n";
7437: $request->print(<<GRADINGMENUJS);
7438: <script type="text/javascript" language="javascript">
7439: function checkChoice(formname,val,cmdx) {
7440: if (val <= 2) {
7441: var cmd = radioSelection(formname.radioChoice);
7442: var cmdsave = cmd;
7443: } else {
7444: cmd = cmdx;
7445: cmdsave = 'submission';
7446: }
7447: formname.command.value = cmd;
7448: if (val < 5) formname.submit();
7449: if (val == 5) {
7450: if (!checkReceiptNo(formname,'notOK')) {
7451: return false;
7452: } else {
7453: formname.submit();
7454: }
7455: }
7456: }
7457:
7458: function checkReceiptNo(formname,nospace) {
7459: var receiptNo = formname.receipt.value;
7460: var checkOpt = false;
7461: if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
7462: if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
7463: if (checkOpt) {
7464: alert("Please enter a receipt number given by a student in the receipt box.");
7465: formname.receipt.value = "";
7466: formname.receipt.focus();
7467: return false;
7468: }
7469: return true;
7470: }
7471: </script>
7472: GRADINGMENUJS
7473: &commonJSfunctions($request);
7474: return $Str;
7475: }
7476:
7477:
7478: #--- Displays the submissions first page -------
7479: sub submit_options {
7480: my ($request) = @_;
7481: my ($symb)=&get_symb($request);
7482: if (!$symb) {return '';}
7483: my $probTitle = &Apache::lonnet::gettitle($symb);
7484:
7485: $request->print(<<GRADINGMENUJS);
7486: <script type="text/javascript" language="javascript">
7487: function checkChoice(formname,val,cmdx) {
7488: if (val <= 2) {
7489: var cmd = radioSelection(formname.radioChoice);
7490: var cmdsave = cmd;
7491: } else {
7492: cmd = cmdx;
7493: cmdsave = 'submission';
7494: }
7495: formname.command.value = cmd;
7496: formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
7497: ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
7498: if (val < 5) formname.submit();
7499: if (val == 5) {
7500: if (!checkReceiptNo(formname,'notOK')) { return false;}
7501: formname.submit();
7502: }
7503: if (val < 7) formname.submit();
7504: }
7505:
7506: function checkReceiptNo(formname,nospace) {
7507: var receiptNo = formname.receipt.value;
7508: var checkOpt = false;
7509: if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
7510: if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
7511: if (checkOpt) {
7512: alert("Please enter a receipt number given by a student in the receipt box.");
7513: formname.receipt.value = "";
7514: formname.receipt.focus();
7515: return false;
7516: }
7517: return true;
7518: }
7519: </script>
7520: GRADINGMENUJS
7521: &commonJSfunctions($request);
7522: my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
7523: my $result;
7524: my (undef,$sections) = &getclasslist('all','0');
7525: my $savedState = &savedState();
7526: my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
7527: my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
7528: my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
7529: my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
7530:
7531: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
7532: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
7533: '<input type="hidden" name="handgrade" value="'.$hdgrade.'" />'."\n".
7534: '<input type="hidden" name="probTitle" value="'.$probTitle.'" />'."\n".
7535: '<input type="hidden" name="command" value="" />'."\n".
7536: '<input type="hidden" name="saveState" value="" />'."\n".
7537: '<input type="hidden" name="gradingMenu" value="1" />'."\n".
7538: '<input type="hidden" name="showgrading" value="yes" />'."\n";
7539:
7540: $result.='
7541: <div class="LC_grade_select_mode">
7542: <div class="LC_grade_select_mode_current">
7543: <h2>
7544: '.&mt('Grade Current Resource').'
7545: </h2>
7546: <div class="LC_grade_select_mode_body">
7547: <div class="LC_grades_resource_info">
7548: '.$table.'
7549: </div>
7550: <div class="LC_grade_select_mode_selector">
7551: <div class="LC_grade_select_mode_selector_header">
7552: '.&mt('Sections').'
7553: </div>
7554: <div class="LC_grade_select_mode_selector_body">
7555: <select name="section" multiple="multiple" size="5">'."\n";
7556: if (ref($sections)) {
7557: foreach my $section (sort (@$sections)) {
7558: $result.='<option value="'.$section.'" '.
7559: ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
7560: }
7561: }
7562: $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> ';
7563: $result.='
7564: </div>
7565: </div>
7566: <div class="LC_grade_select_mode_selector">
7567: <div class="LC_grade_select_mode_selector_header">
7568: '.&mt('Groups').'
7569: </div>
7570: <div class="LC_grade_select_mode_selector_body">
7571: '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
7572: </div>
7573: </div>
7574: <div class="LC_grade_select_mode_selector">
7575: <div class="LC_grade_select_mode_selector_header">
7576: '.&mt('Access Status').'
7577: </div>
7578: <div class="LC_grade_select_mode_selector_body">
7579: '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
7580: </div>
7581: </div>
7582: <div class="LC_grade_select_mode_selector">
7583: <div class="LC_grade_select_mode_selector_header">
7584: '.&mt('Submission Status').'
7585: </div>
7586: <div class="LC_grade_select_mode_selector_body">
7587: <select name="submitonly" size="5">
7588: <option value="yes" '. ($saveSub eq 'yes' ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
7589: <option value="queued" '. ($saveSub eq 'queued' ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
7590: <option value="graded" '. ($saveSub eq 'graded' ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
7591: <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
7592: <option value="all" '. ($saveSub eq 'all' ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
7593: </select>
7594: </div>
7595: </div>
7596: <div class="LC_grade_select_mode_type_body">
7597: <div class="LC_grade_select_mode_type">
7598: <label>
7599: <input type="radio" name="radioChoice" value="submission" '.
7600: ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
7601: &mt('Select individual students to grade and view submissions.').'
7602: </label>
7603: </div>
7604: <div class="LC_grade_select_mode_type">
7605: <label>
7606: <input type="radio" name="radioChoice" value="viewgrades" '.
7607: ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
7608: &mt('Grade all selected students in a grading table.').'
7609: </label>
7610: </div>
7611: <div class="LC_grade_select_mode_type">
7612: <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next->').'" />
7613: </div>
7614: </div>
7615: </div>
7616: </div>
7617: <div class="LC_grade_select_mode_page">
7618: <h2>
7619: '.&mt('Grade Complete Folder for One Student').'
7620: </h2>
7621: <div class="LC_grades_select_mode_body">
7622: <div class="LC_grade_select_mode_type_body">
7623: <div class="LC_grade_select_mode_type">
7624: <label>
7625: <input type="radio" name="radioChoice" value="pickStudentPage" '.
7626: ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
7627: &mt('The <b>complete</b> page/sequence/folder: For one student').'
7628: </label>
7629: </div>
7630: <div class="LC_grade_select_mode_type">
7631: <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next->').'" />
7632: </div>
7633: </div>
7634: </div>
7635: </div>
7636: </div>
7637: </form>';
7638: return $result;
7639: }
7640:
7641: sub reset_perm {
7642: undef(%perm);
7643: }
7644:
7645: sub init_perm {
7646: &reset_perm();
7647: foreach my $test_perm ('vgr','mgr','opa') {
7648:
7649: my $scope = $env{'request.course.id'};
7650: if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
7651:
7652: $scope .= '/'.$env{'request.course.sec'};
7653: if ( $perm{$test_perm}=
7654: &Apache::lonnet::allowed($test_perm,$scope)) {
7655: $perm{$test_perm.'_section'}=$env{'request.course.sec'};
7656: } else {
7657: delete($perm{$test_perm});
7658: }
7659: }
7660: }
7661: }
7662:
7663: sub gather_clicker_ids {
7664: my %clicker_ids;
7665:
7666: my $classlist = &Apache::loncoursedata::get_classlist();
7667:
7668: # Set up a couple variables.
7669: my $username_idx = &Apache::loncoursedata::CL_SNAME();
7670: my $domain_idx = &Apache::loncoursedata::CL_SDOM();
7671: my $status_idx = &Apache::loncoursedata::CL_STATUS();
7672:
7673: foreach my $student (keys(%$classlist)) {
7674: if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
7675: my $username = $classlist->{$student}->[$username_idx];
7676: my $domain = $classlist->{$student}->[$domain_idx];
7677: my $clickers =
7678: (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
7679: foreach my $id (split(/\,/,$clickers)) {
7680: $id=~s/^[\#0]+//;
7681: $id=~s/[\-\:]//g;
7682: if (exists($clicker_ids{$id})) {
7683: $clicker_ids{$id}.=','.$username.':'.$domain;
7684: } else {
7685: $clicker_ids{$id}=$username.':'.$domain;
7686: }
7687: }
7688: }
7689: return %clicker_ids;
7690: }
7691:
7692: sub gather_adv_clicker_ids {
7693: my %clicker_ids;
7694: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
7695: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7696: my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
7697: foreach my $element (sort(keys(%coursepersonnel))) {
7698: foreach my $person (split(/\,/,$coursepersonnel{$element})) {
7699: my ($puname,$pudom)=split(/\:/,$person);
7700: my $clickers =
7701: (&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
7702: foreach my $id (split(/\,/,$clickers)) {
7703: $id=~s/^[\#0]+//;
7704: $id=~s/[\-\:]//g;
7705: if (exists($clicker_ids{$id})) {
7706: $clicker_ids{$id}.=','.$puname.':'.$pudom;
7707: } else {
7708: $clicker_ids{$id}=$puname.':'.$pudom;
7709: }
7710: }
7711: }
7712: }
7713: return %clicker_ids;
7714: }
7715:
7716: sub clicker_grading_parameters {
7717: return ('gradingmechanism' => 'scalar',
7718: 'upfiletype' => 'scalar',
7719: 'specificid' => 'scalar',
7720: 'pcorrect' => 'scalar',
7721: 'pincorrect' => 'scalar');
7722: }
7723:
7724: sub process_clicker {
7725: my ($r)=@_;
7726: my ($symb)=&get_symb($r);
7727: if (!$symb) {return '';}
7728: my $result=&checkforfile_js();
7729: $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
7730: my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
7731: $result.=$table;
7732: $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
7733: $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
7734: $result.=' <b>'.&mt('Specify a file containing the clicker information for this resource').
7735: '.</b></td></tr>'."\n";
7736: $result.='<tr bgcolor=#ffffe6><td>'."\n";
7737: # Attempt to restore parameters from last session, set defaults if not present
7738: my %Saveable_Parameters=&clicker_grading_parameters();
7739: &Apache::loncommon::restore_course_settings('grades_clicker',
7740: \%Saveable_Parameters);
7741: if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
7742: if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
7743: if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
7744: if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
7745:
7746: my %checked;
7747: foreach my $gradingmechanism ('attendance','personnel','specific') {
7748: if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
7749: $checked{$gradingmechanism}="checked='checked'";
7750: }
7751: }
7752:
7753: my $upload=&mt("Upload File");
7754: my $type=&mt("Type");
7755: my $attendance=&mt("Award points just for participation");
7756: my $personnel=&mt("Correctness determined from response by course personnel");
7757: my $specific=&mt("Correctness determined from response with clicker ID(s)");
7758: my $pcorrect=&mt("Percentage points for correct solution");
7759: my $pincorrect=&mt("Percentage points for incorrect solution");
7760: my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
7761: ('iclicker' => 'i>clicker',
7762: 'interwrite' => 'interwrite PRS'));
7763: $symb = &Apache::lonenc::check_encrypt($symb);
7764: $result.=<<ENDUPFORM;
7765: <script type="text/javascript">
7766: function sanitycheck() {
7767: // Accept only integer percentages
7768: document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
7769: document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
7770: // Find out grading choice
7771: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
7772: if (document.forms.gradesupload.gradingmechanism[i].checked) {
7773: gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
7774: }
7775: }
7776: // By default, new choice equals user selection
7777: newgradingchoice=gradingchoice;
7778: // Not good to give more points for false answers than correct ones
7779: if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
7780: document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
7781: }
7782: // If new choice is attendance only, and old choice was correctness-based, restore defaults
7783: if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
7784: document.forms.gradesupload.pcorrect.value=100;
7785: document.forms.gradesupload.pincorrect.value=100;
7786: }
7787: // If the values are different, cannot be attendance only
7788: if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
7789: (gradingchoice=='attendance')) {
7790: newgradingchoice='personnel';
7791: }
7792: // Change grading choice to new one
7793: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
7794: if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
7795: document.forms.gradesupload.gradingmechanism[i].checked=true;
7796: } else {
7797: document.forms.gradesupload.gradingmechanism[i].checked=false;
7798: }
7799: }
7800: // Remember the old state
7801: document.forms.gradesupload.waschecked.value=newgradingchoice;
7802: }
7803: </script>
7804: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
7805: <input type="hidden" name="symb" value="$symb" />
7806: <input type="hidden" name="command" value="processclickerfile" />
7807: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
7808: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
7809: <input type="file" name="upfile" size="50" />
7810: <br /><label>$type: $selectform</label>
7811: <br /><label><input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
7812: <br /><label><input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
7813: <br /><label><input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" />$specific </label>
7814: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
7815: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
7816: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
7817: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
7818: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
7819: </form>
7820: ENDUPFORM
7821: $result.='</td></tr></table>'."\n".
7822: '</td></tr></table><br /><br />'."\n";
7823: $result.=&show_grading_menu_form($symb);
7824: return $result;
7825: }
7826:
7827: sub process_clicker_file {
7828: my ($r)=@_;
7829: my ($symb)=&get_symb($r);
7830: if (!$symb) {return '';}
7831:
7832: my %Saveable_Parameters=&clicker_grading_parameters();
7833: &Apache::loncommon::store_course_settings('grades_clicker',
7834: \%Saveable_Parameters);
7835:
7836: my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
7837: if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
7838: $result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
7839: return $result.&show_grading_menu_form($symb);
7840: }
7841: my %clicker_ids=&gather_clicker_ids();
7842: my %correct_ids;
7843: if ($env{'form.gradingmechanism'} eq 'personnel') {
7844: %correct_ids=&gather_adv_clicker_ids();
7845: }
7846: if ($env{'form.gradingmechanism'} eq 'specific') {
7847: foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
7848: $correct_id=~tr/a-z/A-Z/;
7849: $correct_id=~s/\s//gs;
7850: $correct_id=~s/^[\#0]+//;
7851: $correct_id=~s/[\-\:]//g;
7852: if ($correct_id) {
7853: $correct_ids{$correct_id}='specified';
7854: }
7855: }
7856: }
7857: if ($env{'form.gradingmechanism'} eq 'attendance') {
7858: $result.=&mt('Score based on attendance only');
7859: } else {
7860: my $number=0;
7861: $result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
7862: foreach my $id (sort(keys(%correct_ids))) {
7863: $result.='<br /><tt>'.$id.'</tt> - ';
7864: if ($correct_ids{$id} eq 'specified') {
7865: $result.=&mt('specified');
7866: } else {
7867: my ($uname,$udom)=split(/\:/,$correct_ids{$id});
7868: $result.=&Apache::loncommon::plainname($uname,$udom);
7869: }
7870: $number++;
7871: }
7872: $result.="</p>\n";
7873: if ($number==0) {
7874: $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
7875: return $result.&show_grading_menu_form($symb);
7876: }
7877: }
7878: if (length($env{'form.upfile'}) < 2) {
7879: $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
7880: '<span class="LC_error">',
7881: '</span>',
7882: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
7883: return $result.&show_grading_menu_form($symb);
7884: }
7885:
7886: # Were able to get all the info needed, now analyze the file
7887:
7888: $result.=&Apache::loncommon::studentbrowser_javascript();
7889: $symb = &Apache::lonenc::check_encrypt($symb);
7890: my $heading=&mt('Scanning clicker file');
7891: $result.=(<<ENDHEADER);
7892: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
7893: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
7894: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
7895: <form method="post" action="/adm/grades" name="clickeranalysis">
7896: <input type="hidden" name="symb" value="$symb" />
7897: <input type="hidden" name="command" value="assignclickergrades" />
7898: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
7899: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
7900: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
7901: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
7902: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
7903: ENDHEADER
7904: my %responses;
7905: my @questiontitles;
7906: my $errormsg='';
7907: my $number=0;
7908: if ($env{'form.upfiletype'} eq 'iclicker') {
7909: ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
7910: }
7911: if ($env{'form.upfiletype'} eq 'interwrite') {
7912: ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
7913: }
7914: $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
7915: '<input type="hidden" name="number" value="'.$number.'" />'.
7916: &mt('Awarding [_1] percent for corrion(s)',$number).'<br />'.
7917: '<input type="hidden" name="number" value="'.$number.'" />'.
7918: &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
7919: $env{'form.pcorrect'},$env{'form.pincorrect'}).
7920: '<br />';
7921: # Remember Question Titles
7922: # FIXME: Possibly need delimiter other than ":"
7923: for (my $i=0;$i<$number;$i++) {
7924: $result.='<input type="hidden" name="question:'.$i.'" value="'.
7925: &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
7926: }
7927: my $correct_count=0;
7928: my $student_count=0;
7929: my $unknown_count=0;
7930: # Match answers with usernames
7931: # FIXME: Possibly need delimiter other than ":"
7932: foreach my $id (keys(%responses)) {
7933: if ($correct_ids{$id}) {
7934: $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
7935: $correct_count++;
7936: } elsif ($clicker_ids{$id}) {
7937: if ($clicker_ids{$id}=~/\,/) {
7938: # More than one user with the same clicker!
7939: $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
7940: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
7941: "<select name='multi".$id."'>";
7942: foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
7943: $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
7944: }
7945: $result.='</select>';
7946: $unknown_count++;
7947: } else {
7948: # Good: found one and only one user with the right clicker
7949: $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
7950: $student_count++;
7951: }
7952: } else {
7953: $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
7954: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
7955: "\n".&mt("Username").": <input type='text' name='uname".$id."' /> ".
7956: "\n".&mt("Domain").": ".
7957: &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).' '.
7958: &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
7959: $unknown_count++;
7960: }
7961: }
7962: $result.='<hr />'.
7963: &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
7964: if ($env{'form.gradingmechanism'} ne 'attendance') {
7965: if ($correct_count==0) {
7966: $errormsg.="Found no correct answers answers for grading!";
7967: } elsif ($correct_count>1) {
7968: $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
7969: }
7970: }
7971: if ($number<1) {
7972: $errormsg.="Found no questions.";
7973: }
7974: if ($errormsg) {
7975: $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
7976: } else {
7977: $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
7978: }
7979: $result.='</form></td></tr></table>'."\n".
7980: '</td></tr></table><br /><br />'."\n";
7981: return $result.&show_grading_menu_form($symb);
7982: }
7983:
7984: sub iclicker_eval {
7985: my ($questiontitles,$responses)=@_;
7986: my $number=0;
7987: my $errormsg='';
7988: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
7989: my %components=&Apache::loncommon::record_sep($line);
7990: my @entries=map {$components{$_}} (sort(keys(%components)));
7991: if ($entries[0] eq 'Question') {
7992: for (my $i=3;$i<$#entries;$i+=6) {
7993: $$questiontitles[$number]=$entries[$i];
7994: $number++;
7995: }
7996: }
7997: if ($entries[0]=~/^\#/) {
7998: my $id=$entries[0];
7999: my @idresponses;
8000: $id=~s/^[\#0]+//;
8001: for (my $i=0;$i<$number;$i++) {
8002: my $idx=3+$i*6;
8003: push(@idresponses,$entries[$idx]);
8004: }
8005: $$responses{$id}=join(',',@idresponses);
8006: }
8007: }
8008: return ($errormsg,$number);
8009: }
8010:
8011: sub interwrite_eval {
8012: my ($questiontitles,$responses)=@_;
8013: my $number=0;
8014: my $errormsg='';
8015: my $skipline=1;
8016: my $questionnumber=0;
8017: my %idresponses=();
8018: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
8019: my %components=&Apache::loncommon::record_sep($line);
8020: my @entries=map {$components{$_}} (sort(keys(%components)));
8021: if ($entries[1] eq 'Time') { $skipline=0; next; }
8022: if ($entries[1] eq 'Response') { $skipline=1; }
8023: next if $skipline;
8024: if ($entries[0]!=$questionnumber) {
8025: $questionnumber=$entries[0];
8026: $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
8027: $number++;
8028: }
8029: my $id=$entries[4];
8030: $id=~s/^[\#0]+//;
8031: $id=~s/^v\d*\://i;
8032: $id=~s/[\-\:]//g;
8033: $idresponses{$id}[$number]=$entries[6];
8034: }
8035: foreach my $id (keys %idresponses) {
8036: $$responses{$id}=join(',',@{$idresponses{$id}});
8037: $$responses{$id}=~s/^\s*\,//;
8038: }
8039: return ($errormsg,$number);
8040: }
8041:
8042: sub assign_clicker_grades {
8043: my ($r)=@_;
8044: my ($symb)=&get_symb($r);
8045: if (!$symb) {return '';}
8046: # See which part we are saving to
8047: my ($partlist,$handgrade,$responseType) = &response_type($symb);
8048: # FIXME: This should probably look for the first handgradeable part
8049: my $part=$$partlist[0];
8050: # Start screen output
8051: my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
8052:
8053: my $heading=&mt('Assigning grades based on clicker file');
8054: $result.=(<<ENDHEADER);
8055: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
8056: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
8057: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
8058: ENDHEADER
8059: # Get correct result
8060: # FIXME: Possibly need delimiter other than ":"
8061: my @correct=();
8062: my $gradingmechanism=$env{'form.gradingmechanism'};
8063: my $number=$env{'form.number'};
8064: if ($gradingmechanism ne 'attendance') {
8065: foreach my $key (keys(%env)) {
8066: if ($key=~/^form\.correct\:/) {
8067: my @input=split(/\,/,$env{$key});
8068: for (my $i=0;$i<=$#input;$i++) {
8069: if (($correct[$i]) && ($input[$i]) &&
8070: ($correct[$i] ne $input[$i])) {
8071: $result.='<br /><span class="LC_warning">'.
8072: &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
8073: $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
8074: } elsif ($input[$i]) {
8075: $correct[$i]=$input[$i];
8076: }
8077: }
8078: }
8079: }
8080: for (my $i=0;$i<$number;$i++) {
8081: if (!$correct[$i]) {
8082: $result.='<br /><span class="LC_error">'.
8083: &mt('No correct result given for question "[_1]"!',
8084: $env{'form.question:'.$i}).'</span>';
8085: }
8086: }
8087: $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
8088: }
8089: # Start grading
8090: my $pcorrect=$env{'form.pcorrect'};
8091: my $pincorrect=$env{'form.pincorrect'};
8092: my $storecount=0;
8093: foreach my $key (keys(%env)) {
8094: my $user='';
8095: if ($key=~/^form\.student\:(.*)$/) {
8096: $user=$1;
8097: }
8098: if ($key=~/^form\.unknown\:(.*)$/) {
8099: my $id=$1;
8100: if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
8101: $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
8102: } elsif ($env{'form.multi'.$id}) {
8103: $user=$env{'form.multi'.$id};
8104: }
8105: }
8106: if ($user) {
8107: my @answer=split(/\,/,$env{$key});
8108: my $sum=0;
8109: for (my $i=0;$i<$number;$i++) {
8110: if ($answer[$i]) {
8111: if ($gradingmechanism eq 'attendance') {
8112: $sum+=$pcorrect;
8113: } else {
8114: if ($answer[$i] eq $correct[$i]) {
8115: $sum+=$pcorrect;
8116: } else {
8117: $sum+=$pincorrect;
8118: }
8119: }
8120: }
8121: }
8122: my $ave=$sum/(100*$number);
8123: # Store
8124: my ($username,$domain)=split(/\:/,$user);
8125: my %grades=();
8126: $grades{"resource.$part.solved"}='correct_by_override';
8127: $grades{"resource.$part.awarded"}=$ave;
8128: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
8129: my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
8130: $env{'request.course.id'},
8131: $domain,$username);
8132: if ($returncode ne 'ok') {
8133: $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
8134: } else {
8135: $storecount++;
8136: }
8137: }
8138: }
8139: # We are done
8140: $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
8141: '</td></tr></table>'."\n".
8142: '</td></tr></table><br /><br />'."\n";
8143: return $result.&show_grading_menu_form($symb);
8144: }
8145:
8146: sub handler {
8147: my $request=$_[0];
8148: &reset_caches();
8149: if ($env{'browser.mathml'}) {
8150: &Apache::loncommon::content_type($request,'text/xml');
8151: } else {
8152: &Apache::loncommon::content_type($request,'text/html');
8153: }
8154: $request->send_http_header;
8155: return '' if $request->header_only;
8156: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
8157: my $symb=&get_symb($request,1);
8158: my @commands=&Apache::loncommon::get_env_multiple('form.command');
8159: my $command=$commands[0];
8160:
8161: if ($#commands > 0) {
8162: &Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
8163: }
8164:
8165:
8166: $request->print(&Apache::loncommon::start_page('Grading'));
8167: if ($symb eq '' && $command eq '') {
8168: if ($env{'user.adv'}) {
8169: if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
8170: ($env{'form.codethree'})) {
8171: my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
8172: $env{'form.codethree'};
8173: my ($tsymb,$tuname,$tudom,$tcrsid)=
8174: &Apache::lonnet::checkin($token);
8175: if ($tsymb) {
8176: my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
8177: if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
8178: $request->print(&Apache::lonnet::ssi_body('/res/'.$url,
8179: ('grade_username' => $tuname,
8180: 'grade_domain' => $tudom,
8181: 'grade_courseid' => $tcrsid,
8182: 'grade_symb' => $tsymb)));
8183: } else {
8184: $request->print('<h3>Not authorized: '.$token.'</h3>');
8185: }
8186: } else {
8187: $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
8188: }
8189: } else {
8190: $request->print(&Apache::lonxml::tokeninputfield());
8191: }
8192: }
8193: } else {
8194: &init_perm();
8195: if ($command eq 'submission' && $perm{'vgr'}) {
8196: ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
8197: } elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
8198: &pickStudentPage($request);
8199: } elsif ($command eq 'displayPage' && $perm{'vgr'}) {
8200: &displayPage($request);
8201: } elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
8202: &updateGradeByPage($request);
8203: } elsif ($command eq 'processGroup' && $perm{'vgr'}) {
8204: &processGroup($request);
8205: } elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
8206: $request->print(&grading_menu($request));
8207: } elsif ($command eq 'submit_options' && $perm{'vgr'}) {
8208: $request->print(&submit_options($request));
8209: } elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
8210: $request->print(&viewgrades($request));
8211: } elsif ($command eq 'handgrade' && $perm{'mgr'}) {
8212: $request->print(&processHandGrade($request));
8213: } elsif ($command eq 'editgrades' && $perm{'mgr'}) {
8214: $request->print(&editgrades($request));
8215: } elsif ($command eq 'verify' && $perm{'vgr'}) {
8216: $request->print(&verifyreceipt($request));
8217: } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
8218: $request->print(&process_clicker($request));
8219: } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
8220: $request->print(&process_clicker_file($request));
8221: } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
8222: $request->print(&assign_clicker_grades($request));
8223: } elsif ($command eq 'csvform' && $perm{'mgr'}) {
8224: $request->print(&upcsvScores_form($request));
8225: } elsif ($command eq 'csvupload' && $perm{'mgr'}) {
8226: $request->print(&csvupload($request));
8227: } elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
8228: $request->print(&csvuploadmap($request));
8229: } elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
8230: if ($env{'form.associate'} ne 'Reverse Association') {
8231: $request->print(&csvuploadoptions($request));
8232: } else {
8233: if ( $env{'form.upfile_associate'} ne 'reverse' ) {
8234: $env{'form.upfile_associate'} = 'reverse';
8235: } else {
8236: $env{'form.upfile_associate'} = 'forward';
8237: }
8238: $request->print(&csvuploadmap($request));
8239: }
8240: } elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
8241: $request->print(&csvuploadassign($request));
8242: } elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
8243: $request->print(&scantron_selectphase($request));
8244: } elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
8245: $request->print(&scantron_do_warning($request));
8246: } elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
8247: $request->print(&scantron_validate_file($request));
8248: } elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
8249: $request->print(&scantron_process_students($request));
8250: } elsif ($command eq 'scantronupload' &&
8251: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
8252: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
8253: $request->print(&scantron_upload_scantron_data($request));
8254: } elsif ($command eq 'scantronupload_save' &&
8255: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
8256: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
8257: $request->print(&scantron_upload_scantron_data_save($request));
8258: } elsif ($command eq 'scantron_download' &&
8259: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
8260: $request->print(&scantron_download_scantron_data($request));
8261: } elsif ($command) {
8262: $request->print("Access Denied ($command)");
8263: }
8264: }
8265: $request->print(&Apache::loncommon::end_page());
8266: &reset_caches();
8267: return '';
8268: }
8269:
8270: 1;
8271:
8272: __END__;
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>