1: # The LearningOnline Network with CAPA
2: # The LON-CAPA Grading handler
3: #
4: # $Id: grades.pm,v 1.484 2007/11/06 19:19:54 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> Fullname </b><span class="LC_internal_info">(Username)</span>';
175: } else {
176: return ' '.$fullname.'<span class="LC_internal_info"> ('.$uname.
177: ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
178: }
179: }
180:
181: #--- Get the partlist and the response type for a given problem. ---
182: #--- Indicate if a response type is coded handgraded or not. ---
183: sub response_type {
184: my ($symb) = shift;
185:
186: my $navmap = Apache::lonnavmaps::navmap->new();
187: my $res = $navmap->getBySymb($symb);
188: my $partlist = $res->parts();
189: my %vPart =
190: map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
191: my (%response_types,%handgrade);
192: foreach my $part (@{ $partlist }) {
193: next if (%vPart && !exists($vPart{$part}));
194:
195: my @types = $res->responseType($part);
196: my @ids = $res->responseIds($part);
197: for (my $i=0; $i < scalar(@ids); $i++) {
198: $response_types{$part}{$ids[$i]} = $types[$i];
199: $handgrade{$part.'_'.$ids[$i]} =
200: &Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
201: '.handgrade',$symb);
202: }
203: }
204: return ($partlist,\%handgrade,\%response_types);
205: }
206:
207: sub flatten_responseType {
208: my ($responseType) = @_;
209: my @part_response_id =
210: map {
211: my $part = $_;
212: map {
213: [$part,$_]
214: } sort(keys(%{ $responseType->{$part} }));
215: } sort(keys(%$responseType));
216: return @part_response_id;
217: }
218:
219: sub get_display_part {
220: my ($partID,$symb)=@_;
221: my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
222: if (defined($display) and $display ne '') {
223: $display.= " (<span class=\"LC_internal_info\">id $partID</span>)";
224: } else {
225: $display=$partID;
226: }
227: return $display;
228: }
229:
230: #--- Show resource title
231: #--- and parts and response type
232: sub showResourceInfo {
233: my ($symb,$probTitle,$checkboxes) = @_;
234: my $col=3;
235: if ($checkboxes) { $col=4; }
236: my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
237: $result .='<table border="0">';
238: my ($partlist,$handgrade,$responseType) = &response_type($symb);
239: my %resptype = ();
240: my $hdgrade='no';
241: my %partsseen;
242: foreach my $partID (sort keys(%$responseType)) {
243: foreach my $resID (sort keys(%{ $responseType->{$partID} })) {
244: my $handgrade=$$handgrade{$partID.'_'.$resID};
245: my $responsetype = $responseType->{$partID}->{$resID};
246: $hdgrade = $handgrade if ($handgrade eq 'yes');
247: $result.='<tr>';
248: if ($checkboxes) {
249: if (exists($partsseen{$partID})) {
250: $result.="<td> </td>";
251: } else {
252: $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
253: }
254: $partsseen{$partID}=1;
255: }
256: my $display_part=&get_display_part($partID,$symb);
257: $result.='<td><b>Part: </b>'.$display_part.' <span class="LC_internal_info">'.
258: $resID.'</span></td>'.
259: '<td><b>Type: </b>'.$responsetype.'</td></tr>';
260: # '<td><b>Handgrade: </b>'.$handgrade.'</td></tr>';
261: }
262: }
263: $result.='</table>'."\n";
264: return $result,$responseType,$hdgrade,$partlist,$handgrade;
265: }
266:
267: sub reset_caches {
268: &reset_analyze_cache();
269: &reset_perm();
270: }
271:
272: {
273: my %analyze_cache;
274:
275: sub reset_analyze_cache {
276: undef(%analyze_cache);
277: }
278:
279: sub get_analyze {
280: my ($symb,$uname,$udom)=@_;
281: my $key = "$symb\0$uname\0$udom";
282: return $analyze_cache{$key} if (exists($analyze_cache{$key}));
283:
284: my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
285: $url=&Apache::lonnet::clutter($url);
286: my $subresult=&Apache::lonnet::ssi($url,
287: ('grade_target' => 'analyze'),
288: ('grade_domain' => $udom),
289: ('grade_symb' => $symb),
290: ('grade_courseid' =>
291: $env{'request.course.id'}),
292: ('grade_username' => $uname));
293: (undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
294: my %analyze=&Apache::lonnet::str2hash($subresult);
295: return $analyze_cache{$key} = \%analyze;
296: }
297:
298: sub get_order {
299: my ($partid,$respid,$symb,$uname,$udom)=@_;
300: my $analyze = &get_analyze($symb,$uname,$udom);
301: return $analyze->{"$partid.$respid.shown"};
302: }
303:
304: sub get_radiobutton_correct_foil {
305: my ($partid,$respid,$symb,$uname,$udom)=@_;
306: my $analyze = &get_analyze($symb,$uname,$udom);
307: foreach my $foil (@{&get_order($partid,$respid,$symb,$uname,$udom)}) {
308: if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
309: return $foil;
310: }
311: }
312: }
313: }
314:
315: #--- Clean response type for display
316: #--- Currently filters option/rank/radiobutton/match/essay/Task
317: # response types only.
318: sub cleanRecord {
319: my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
320: $uname,$udom) = @_;
321: my $grayFont = '<span class="LC_internal_info">';
322: if ($response =~ /^(option|rank)$/) {
323: my %answer=&Apache::lonnet::str2hash($answer);
324: my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
325: my ($toprow,$bottomrow);
326: foreach my $foil (@$order) {
327: if ($grading{$foil} == 1) {
328: $toprow.='<td><b>'.$answer{$foil}.' </b></td>';
329: } else {
330: $toprow.='<td><i>'.$answer{$foil}.' </i></td>';
331: }
332: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
333: }
334: return '<blockquote><table border="1">'.
335: '<tr valign="top"><td>'.&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"> '.$viewgrade.
810: ' Submissions for a Student or a Group of Students</span></h3>';
811:
812: my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
813:
814: $request->print(<<LISTJAVASCRIPT);
815: <script type="text/javascript" language="javascript">
816: function checkSelect(checkBox) {
817: var ctr=0;
818: var sense="";
819: if (checkBox.length > 1) {
820: for (var i=0; i<checkBox.length; i++) {
821: if (checkBox[i].checked) {
822: ctr++;
823: }
824: }
825: sense = "a student or group of students";
826: } else {
827: if (checkBox.checked) {
828: ctr = 1;
829: }
830: sense = "the student";
831: }
832: if (ctr == 0) {
833: alert("Please select "+sense+" before clicking on the Next button.");
834: return false;
835: }
836: document.gradesub.submit();
837: }
838:
839: function reLoadList(formname) {
840: if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
841: formname.command.value = 'submission';
842: formname.submit();
843: }
844: </script>
845: LISTJAVASCRIPT
846:
847: &commonJSfunctions($request);
848: $request->print($result);
849:
850: my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
851: my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
852: my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
853: "\n".$table.
854: ' <b>View Problem Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
855: '<label><input type="radio" name="vProb" value="yes" /> one student </label>'."\n".
856: '<label><input type="radio" name="vProb" value="all" /> all students </label><br />'."\n".
857: ' <b>View Answer: </b><label><input type="radio" name="vAns" value="no" /> no </label>'."\n".
858: '<label><input type="radio" name="vAns" value="yes" /> one student </label>'."\n".
859: '<label><input type="radio" name="vAns" value="all" checked="checked" /> all students </label><br />'."\n".
860: ' <b>Submissions: </b>'."\n";
861: if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
862: $gradeTable.='<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> essay part only </label>'."\n";
863: }
864: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
865: my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
866: $env{'form.Status'} = $saveStatus;
867: $gradeTable.='<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> last submission only </label>'."\n".
868: '<label><input type="radio" name="lastSub" value="last" /> last submission & parts info </label>'."\n".
869: '<label><input type="radio" name="lastSub" value="datesub" /> by dates and submissions </label>'."\n".
870: '<label><input type="radio" name="lastSub" value="all" /> all details</label><br />'."\n".
871: ' <b>Grading Increments:</b> <select name="increment">'.
872: '<option value="1">Whole Points</option>'.
873: '<option value=".5">Half Points</option>'.
874: '<option value=".25">Quarter Points</option>'.
875: '<option value=".1">Tenths of a Point</option>'.
876: '</select>'.
877: &build_section_inputs().
878: '<input type="hidden" name="submitonly" value="'.$submitonly.'" />'."\n".
879: '<input type="hidden" name="handgrade" value="'.$env{'form.handgrade'}.'" /><br />'."\n".
880: '<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
881: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
882: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
883: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
884: '<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
885:
886: if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
887: $gradeTable.='<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
888: } else {
889: $gradeTable.='<b>Student Status:</b> '.
890: &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);').'<br />';
891: }
892:
893: $gradeTable.='To '.lc($viewgrade).' a submission or a group of submissions, click on the check box(es) '.
894: 'next to the student\'s name(s). Then click on the Next button.<br />'."\n".
895: '<input type="hidden" name="command" value="processGroup" />'."\n";
896:
897: # checkall buttons
898: $gradeTable.=&check_script('gradesub', 'stuinfo');
899: $gradeTable.='<input type="button" '."\n".
900: 'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
901: 'value="Next->" /> <br />'."\n";
902: $gradeTable.=&check_buttons();
903: $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />Check For Plagiarism</label>';
904: my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
905: $gradeTable.= &Apache::loncommon::start_data_table().
906: &Apache::loncommon::start_data_table_header_row();
907: my $loop = 0;
908: while ($loop < 2) {
909: $gradeTable.='<th>No.</th><th>Select</th>'.
910: '<th>'.&nameUserString('header').' '.'Section/Group</th>';
911: if ($env{'form.showgrading'} eq 'yes'
912: && $submitonly ne 'queued'
913: && $submitonly ne 'all') {
914: foreach (sort(@$partlist)) {
915: my $display_part=&get_display_part((split(/_/))[0],$symb);
916: $gradeTable.='<th>Part: '.$display_part.
917: ' Status</h>';
918: }
919: } elsif ($submitonly eq 'queued') {
920: $gradeTable.='<th>'.&mt('Queue Status').' </th>';
921: }
922: $loop++;
923: # $gradeTable.='<td></td>' if ($loop%2 ==1);
924: }
925: $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
926:
927: my $ctr = 0;
928: foreach my $student (sort
929: {
930: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
931: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
932: }
933: return $a cmp $b;
934: }
935: (keys(%$fullname))) {
936: my ($uname,$udom) = split(/:/,$student);
937:
938: my %status = ();
939:
940: if ($submitonly eq 'queued') {
941: my %queue_status =
942: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
943: $udom,$uname);
944: next if (!defined($queue_status{'gradingqueue'}));
945: $status{'gradingqueue'} = $queue_status{'gradingqueue'};
946: }
947:
948: if ($env{'form.showgrading'} eq 'yes'
949: && $submitonly ne 'queued'
950: && $submitonly ne 'all') {
951: (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
952: my $submitted = 0;
953: my $graded = 0;
954: my $incorrect = 0;
955: foreach (keys(%status)) {
956: $submitted = 1 if ($status{$_} ne 'nothing');
957: $graded = 1 if ($status{$_} =~ /^ungraded/);
958: $incorrect = 1 if ($status{$_} =~ /^incorrect/);
959:
960: my ($foo,$partid,$foo1) = split(/\./,$_);
961: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
962: $submitted = 0;
963: my ($part)=split(/\./,$partid);
964: $gradeTable.='<input type="hidden" name="'.
965: $student.':'.$part.':submitted_by" value="'.
966: $status{'resource.'.$partid.'.submitted_by'}.'" />';
967: }
968: }
969:
970: next if (!$submitted && ($submitonly eq 'yes' ||
971: $submitonly eq 'incorrect' ||
972: $submitonly eq 'graded'));
973: next if (!$graded && ($submitonly eq 'graded'));
974: next if (!$incorrect && $submitonly eq 'incorrect');
975: }
976:
977: $ctr++;
978: my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
979: my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
980: if ( $perm{'vgr'} eq 'F' ) {
981: if ($ctr%2 ==1) {
982: $gradeTable.= &Apache::loncommon::start_data_table_row();
983: }
984: $gradeTable.='<td align="right">'.$ctr.' </td>'.
985: '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
986: $student.':'.$$fullname{$student}.':::SECTION'.$section.
987: ') " /> </label></td>'."\n".'<td>'.
988: &nameUserString(undef,$$fullname{$student},$uname,$udom).
989: ' '.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
990:
991: if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
992: foreach (sort keys(%status)) {
993: next if (/^resource.*?submitted_by$/);
994: $gradeTable.='<td align="center"> '.$status{$_}.' </td>'."\n";
995: }
996: }
997: # $gradeTable.='<td></td>' if ($ctr%2 ==1);
998: if ($ctr%2 ==0) {
999: $gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
1000: }
1001: }
1002: }
1003: if ($ctr%2 ==1) {
1004: $gradeTable.='<td> </td><td> </td><td> </td>';
1005: if ($env{'form.showgrading'} eq 'yes'
1006: && $submitonly ne 'queued'
1007: && $submitonly ne 'all') {
1008: foreach (@$partlist) {
1009: $gradeTable.='<td> </td>';
1010: }
1011: } elsif ($submitonly eq 'queued') {
1012: $gradeTable.='<td> </td>';
1013: }
1014: $gradeTable.=&Apache::loncommon::end_data_table_row();
1015: }
1016:
1017: $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1018: '<input type="button" '.
1019: 'onClick="javascript:checkSelect(this.form.stuinfo);" '.
1020: 'value="Next->" /></form>'."\n";
1021: if ($ctr == 0) {
1022: my $num_students=(scalar(keys(%$fullname)));
1023: if ($num_students eq 0) {
1024: $gradeTable='<br /> <span class="LC_warning">There are no students currently enrolled.</span>';
1025: } else {
1026: my $submissions='submissions';
1027: if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
1028: if ($submitonly eq 'graded' ) { $submissions = 'ungraded submissions'; }
1029: if ($submitonly eq 'queued' ) { $submissions = 'queued submissions'; }
1030: $gradeTable='<br /> <span class="LC_warning">'.
1031: 'No '.$submissions.' found for this resource for any students. ('.$num_students.
1032: ' students checked for '.$submissions.')</span><br />';
1033: }
1034: } elsif ($ctr == 1) {
1035: $gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1036: }
1037: $gradeTable.=&show_grading_menu_form($symb);
1038: $request->print($gradeTable);
1039: return '';
1040: }
1041:
1042: #---- Called from the listStudents routine
1043:
1044: sub check_script {
1045: my ($form, $type)=@_;
1046: my $chkallscript='<script type="text/javascript">
1047: function checkall() {
1048: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1049: ele = document.forms.'.$form.'.elements[i];
1050: if (ele.name == "'.$type.'") {
1051: document.forms.'.$form.'.elements[i].checked=true;
1052: }
1053: }
1054: }
1055:
1056: function checksec() {
1057: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1058: ele = document.forms.'.$form.'.elements[i];
1059: string = document.forms.'.$form.'.chksec.value;
1060: if
1061: (ele.value.indexOf(":::SECTION"+string)>0) {
1062: document.forms.'.$form.'.elements[i].checked=true;
1063: }
1064: }
1065: }
1066:
1067:
1068: function uncheckall() {
1069: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1070: ele = document.forms.'.$form.'.elements[i];
1071: if (ele.name == "'.$type.'") {
1072: document.forms.'.$form.'.elements[i].checked=false;
1073: }
1074: }
1075: }
1076:
1077: </script>'."\n";
1078: return $chkallscript;
1079: }
1080:
1081: sub check_buttons {
1082: my $buttons.='<input type="button" onclick="checkall()" value="Check All" />';
1083: $buttons.='<input type="button" onclick="uncheckall()" value="Uncheck All" /> ';
1084: $buttons.='<input type="button" onclick="checksec()" value="Check Section/Group" />';
1085: $buttons.='<input type="text" size="5" name="chksec" /> ';
1086: return $buttons;
1087: }
1088:
1089: # Displays the submissions for one student or a group of students
1090: sub processGroup {
1091: my ($request) = shift;
1092: my $ctr = 0;
1093: my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1094: my $total = scalar(@stuchecked)-1;
1095:
1096: foreach my $student (@stuchecked) {
1097: my ($uname,$udom,$fullname) = split(/:/,$student);
1098: $env{'form.student'} = $uname;
1099: $env{'form.userdom'} = $udom;
1100: $env{'form.fullname'} = $fullname;
1101: &submission($request,$ctr,$total);
1102: $ctr++;
1103: }
1104: return '';
1105: }
1106:
1107: #------------------------------------------------------------------------------------
1108: #
1109: #-------------------------- Next few routines handles grading by student, essentially
1110: # handles essay response type problem/part
1111: #
1112: #--- Javascript to handle the submission page functionality ---
1113: sub sub_page_js {
1114: my $request = shift;
1115: $request->print(<<SUBJAVASCRIPT);
1116: <script type="text/javascript" language="javascript">
1117: function updateRadio(formname,id,weight) {
1118: var gradeBox = formname["GD_BOX"+id];
1119: var radioButton = formname["RADVAL"+id];
1120: var oldpts = formname["oldpts"+id].value;
1121: var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1122: gradeBox.value = pts;
1123: var resetbox = false;
1124: if (isNaN(pts) || pts < 0) {
1125: alert("A number equal or greater than 0 is expected. Entered value = "+pts);
1126: for (var i=0; i<radioButton.length; i++) {
1127: if (radioButton[i].checked) {
1128: gradeBox.value = i;
1129: resetbox = true;
1130: }
1131: }
1132: if (!resetbox) {
1133: formtextbox.value = "";
1134: }
1135: return;
1136: }
1137:
1138: if (pts > weight) {
1139: var resp = confirm("You entered a value ("+pts+
1140: ") greater than the weight for the part. Accept?");
1141: if (resp == false) {
1142: gradeBox.value = oldpts;
1143: return;
1144: }
1145: }
1146:
1147: for (var i=0; i<radioButton.length; i++) {
1148: radioButton[i].checked=false;
1149: if (pts == i && pts != "") {
1150: radioButton[i].checked=true;
1151: }
1152: }
1153: updateSelect(formname,id);
1154: formname["stores"+id].value = "0";
1155: }
1156:
1157: function writeBox(formname,id,pts) {
1158: var gradeBox = formname["GD_BOX"+id];
1159: if (checkSolved(formname,id) == 'update') {
1160: gradeBox.value = pts;
1161: } else {
1162: var oldpts = formname["oldpts"+id].value;
1163: gradeBox.value = oldpts;
1164: var radioButton = formname["RADVAL"+id];
1165: for (var i=0; i<radioButton.length; i++) {
1166: radioButton[i].checked=false;
1167: if (i == oldpts) {
1168: radioButton[i].checked=true;
1169: }
1170: }
1171: }
1172: formname["stores"+id].value = "0";
1173: updateSelect(formname,id);
1174: return;
1175: }
1176:
1177: function clearRadBox(formname,id) {
1178: if (checkSolved(formname,id) == 'noupdate') {
1179: updateSelect(formname,id);
1180: return;
1181: }
1182: gradeSelect = formname["GD_SEL"+id];
1183: for (var i=0; i<gradeSelect.length; i++) {
1184: if (gradeSelect[i].selected) {
1185: var selectx=i;
1186: }
1187: }
1188: var stores = formname["stores"+id];
1189: if (selectx == stores.value) { return };
1190: var gradeBox = formname["GD_BOX"+id];
1191: gradeBox.value = "";
1192: var radioButton = formname["RADVAL"+id];
1193: for (var i=0; i<radioButton.length; i++) {
1194: radioButton[i].checked=false;
1195: }
1196: stores.value = selectx;
1197: }
1198:
1199: function checkSolved(formname,id) {
1200: if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1201: var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
1202: if (!reply) {return "noupdate";}
1203: formname.overRideScore.value = 'yes';
1204: }
1205: return "update";
1206: }
1207:
1208: function updateSelect(formname,id) {
1209: formname["GD_SEL"+id][0].selected = true;
1210: return;
1211: }
1212:
1213: //=========== Check that a point is assigned for all the parts ============
1214: function checksubmit(formname,val,total,parttot) {
1215: formname.gradeOpt.value = val;
1216: if (val == "Save & Next") {
1217: for (i=0;i<=total;i++) {
1218: for (j=0;j<parttot;j++) {
1219: var partid = formname["partid"+i+"_"+j].value;
1220: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1221: var points = formname["GD_BOX"+i+"_"+partid].value;
1222: if (points == "") {
1223: var name = formname["name"+i].value;
1224: var studentID = (name != '' ? name : formname["unamedom"+i].value);
1225: var resp = confirm("You did not assign a score for "+studentID+
1226: ", part "+partid+". Continue?");
1227: if (resp == false) {
1228: formname["GD_BOX"+i+"_"+partid].focus();
1229: return false;
1230: }
1231: }
1232: }
1233:
1234: }
1235: }
1236:
1237: }
1238: if (val == "Grade Student") {
1239: formname.showgrading.value = "yes";
1240: if (formname.Status.value == "") {
1241: formname.Status.value = "Active";
1242: }
1243: formname.studentNo.value = total;
1244: }
1245: formname.submit();
1246: }
1247:
1248: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
1249: function checkSubmitPage(formname,total) {
1250: noscore = new Array(100);
1251: var ptr = 0;
1252: for (i=1;i<total;i++) {
1253: var partid = formname["q_"+i].value;
1254: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1255: var points = formname["GD_BOX"+i+"_"+partid].value;
1256: var status = formname["solved"+i+"_"+partid].value;
1257: if (points == "" && status != "correct_by_student") {
1258: noscore[ptr] = i;
1259: ptr++;
1260: }
1261: }
1262: }
1263: if (ptr != 0) {
1264: var sense = ptr == 1 ? ": " : "s: ";
1265: var prolist = "";
1266: if (ptr == 1) {
1267: prolist = noscore[0];
1268: } else {
1269: var i = 0;
1270: while (i < ptr-1) {
1271: prolist += noscore[i]+", ";
1272: i++;
1273: }
1274: prolist += "and "+noscore[i];
1275: }
1276: var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
1277: if (resp == false) {
1278: return false;
1279: }
1280: }
1281:
1282: formname.submit();
1283: }
1284: </script>
1285: SUBJAVASCRIPT
1286: }
1287:
1288: #--- javascript for essay type problem --
1289: sub sub_page_kw_js {
1290: my $request = shift;
1291: my $iconpath = $request->dir_config('lonIconsURL');
1292: &commonJSfunctions($request);
1293:
1294: my $inner_js_msg_central=<<INNERJS;
1295: <script text="text/javascript">
1296: function checkInput() {
1297: opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
1298: var nmsg = opener.document.SCORE.savemsgN.value;
1299: var usrctr = document.msgcenter.usrctr.value;
1300: var newval = opener.document.SCORE["newmsg"+usrctr];
1301: newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
1302:
1303: var msgchk = "";
1304: if (document.msgcenter.subchk.checked) {
1305: msgchk = "msgsub,";
1306: }
1307: var includemsg = 0;
1308: for (var i=1; i<=nmsg; i++) {
1309: var opnmsg = opener.document.SCORE["savemsg"+i];
1310: var frmmsg = document.msgcenter["msg"+i];
1311: opnmsg.value = opener.checkEntities(frmmsg.value);
1312: var showflg = opener.document.SCORE["shownOnce"+i];
1313: showflg.value = "1";
1314: var chkbox = document.msgcenter["msgn"+i];
1315: if (chkbox.checked) {
1316: msgchk += "savemsg"+i+",";
1317: includemsg = 1;
1318: }
1319: }
1320: if (document.msgcenter.newmsgchk.checked) {
1321: msgchk += "newmsg"+usrctr;
1322: includemsg = 1;
1323: }
1324: imgformname = opener.document.SCORE["mailicon"+usrctr];
1325: imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
1326: var includemsg = opener.document.SCORE["includemsg"+usrctr];
1327: includemsg.value = msgchk;
1328:
1329: self.close()
1330:
1331: }
1332: </script>
1333: INNERJS
1334:
1335: my $inner_js_highlight_central=<<INNERJS;
1336: <script type="text/javascript">
1337: function updateChoice(flag) {
1338: opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
1339: opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
1340: opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
1341: opener.document.SCORE.refresh.value = "on";
1342: if (opener.document.SCORE.keywords.value!=""){
1343: opener.document.SCORE.submit();
1344: }
1345: self.close()
1346: }
1347: </script>
1348: INNERJS
1349:
1350: my $start_page_msg_central =
1351: &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
1352: {'js_ready' => 1,
1353: 'only_body' => 1,
1354: 'bgcolor' =>'#FFFFFF',});
1355: my $end_page_msg_central =
1356: &Apache::loncommon::end_page({'js_ready' => 1});
1357:
1358:
1359: my $start_page_highlight_central =
1360: &Apache::loncommon::start_page('Highlight Central',
1361: $inner_js_highlight_central,
1362: {'js_ready' => 1,
1363: 'only_body' => 1,
1364: 'bgcolor' =>'#FFFFFF',});
1365: my $end_page_highlight_central =
1366: &Apache::loncommon::end_page({'js_ready' => 1});
1367:
1368: my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1369: $docopen=~s/^document\.//;
1370: $request->print(<<SUBJAVASCRIPT);
1371: <script type="text/javascript" language="javascript">
1372:
1373: //===================== Show list of keywords ====================
1374: function keywords(formname) {
1375: var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1376: if (nret==null) return;
1377: formname.keywords.value = nret;
1378:
1379: if (formname.keywords.value != "") {
1380: formname.refresh.value = "on";
1381: formname.submit();
1382: }
1383: return;
1384: }
1385:
1386: //===================== Script to view submitted by ==================
1387: function viewSubmitter(submitter) {
1388: document.SCORE.refresh.value = "on";
1389: document.SCORE.NCT.value = "1";
1390: document.SCORE.unamedom0.value = submitter;
1391: document.SCORE.submit();
1392: return;
1393: }
1394:
1395: //===================== Script to add keyword(s) ==================
1396: function getSel() {
1397: if (document.getSelection) txt = document.getSelection();
1398: else if (document.selection) txt = document.selection.createRange().text;
1399: else return;
1400: var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
1401: if (cleantxt=="") {
1402: alert("Please select a word or group of words from document and then click this link.");
1403: return;
1404: }
1405: var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
1406: if (nret==null) return;
1407: document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1408: if (document.SCORE.keywords.value != "") {
1409: document.SCORE.refresh.value = "on";
1410: document.SCORE.submit();
1411: }
1412: return;
1413: }
1414:
1415: //====================== Script for composing message ==============
1416: // preload images
1417: img1 = new Image();
1418: img1.src = "$iconpath/mailbkgrd.gif";
1419: img2 = new Image();
1420: img2.src = "$iconpath/mailto.gif";
1421:
1422: function msgCenter(msgform,usrctr,fullname) {
1423: var Nmsg = msgform.savemsgN.value;
1424: savedMsgHeader(Nmsg,usrctr,fullname);
1425: var subject = msgform.msgsub.value;
1426: var msgchk = document.SCORE["includemsg"+usrctr].value;
1427: re = /msgsub/;
1428: var shwsel = "";
1429: if (re.test(msgchk)) { shwsel = "checked" }
1430: subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
1431: displaySubject(checkEntities(subject),shwsel);
1432: for (var i=1; i<=Nmsg; i++) {
1433: var testmsg = "savemsg"+i+",";
1434: re = new RegExp(testmsg,"g");
1435: shwsel = "";
1436: if (re.test(msgchk)) { shwsel = "checked" }
1437: var message = document.SCORE["savemsg"+i].value;
1438: message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1439: displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
1440: //any < is already converted to <, etc. However, only once!!
1441: }
1442: newmsg = document.SCORE["newmsg"+usrctr].value;
1443: shwsel = "";
1444: re = /newmsg/;
1445: if (re.test(msgchk)) { shwsel = "checked" }
1446: newMsg(newmsg,shwsel);
1447: msgTail();
1448: return;
1449: }
1450:
1451: function checkEntities(strx) {
1452: if (strx.length == 0) return strx;
1453: var orgStr = ["&", "<", ">", '"'];
1454: var newStr = ["&", "<", ">", """];
1455: var counter = 0;
1456: while (counter < 4) {
1457: strx = strReplace(strx,orgStr[counter],newStr[counter]);
1458: counter++;
1459: }
1460: return strx;
1461: }
1462:
1463: function strReplace(strx, orgStr, newStr) {
1464: return strx.split(orgStr).join(newStr);
1465: }
1466:
1467: function savedMsgHeader(Nmsg,usrctr,fullname) {
1468: var height = 70*Nmsg+250;
1469: var scrollbar = "no";
1470: if (height > 600) {
1471: height = 600;
1472: scrollbar = "yes";
1473: }
1474: var xpos = (screen.width-600)/2;
1475: xpos = (xpos < 0) ? '0' : xpos;
1476: var ypos = (screen.height-height)/2-30;
1477: ypos = (ypos < 0) ? '0' : ypos;
1478:
1479: pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1480: pWin.focus();
1481: pDoc = pWin.document;
1482: pDoc.$docopen;
1483: pDoc.write('$start_page_msg_central');
1484:
1485: pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
1486: pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1487: pDoc.write("<h3><span class=\\"LC_info\\"> Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
1488:
1489: pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
1490: pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
1491: pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
1492: }
1493: function displaySubject(msg,shwsel) {
1494: pDoc = pWin.document;
1495: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1496: pDoc.write("<td>Subject<\\/td>");
1497: pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1498: pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1499: }
1500:
1501: function displaySavedMsg(ctr,msg,shwsel) {
1502: pDoc = pWin.document;
1503: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1504: pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
1505: pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1506: pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1507: }
1508:
1509: function newMsg(newmsg,shwsel) {
1510: pDoc = pWin.document;
1511: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1512: pDoc.write("<td align=\\"center\\">New<\\/td>");
1513: pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1514: pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1515: }
1516:
1517: function msgTail() {
1518: pDoc = pWin.document;
1519: pDoc.write("<\\/table>");
1520: pDoc.write("<\\/td><\\/tr><\\/table> ");
1521: pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\"> ");
1522: pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1523: pDoc.write("<\\/form>");
1524: pDoc.write('$end_page_msg_central');
1525: pDoc.close();
1526: }
1527:
1528: //====================== Script for keyword highlight options ==============
1529: function kwhighlight() {
1530: var kwclr = document.SCORE.kwclr.value;
1531: var kwsize = document.SCORE.kwsize.value;
1532: var kwstyle = document.SCORE.kwstyle.value;
1533: var redsel = "";
1534: var grnsel = "";
1535: var blusel = "";
1536: if (kwclr=="red") {var redsel="checked"};
1537: if (kwclr=="green") {var grnsel="checked"};
1538: if (kwclr=="blue") {var blusel="checked"};
1539: var sznsel = "";
1540: var sz1sel = "";
1541: var sz2sel = "";
1542: if (kwsize=="0") {var sznsel="checked"};
1543: if (kwsize=="+1") {var sz1sel="checked"};
1544: if (kwsize=="+2") {var sz2sel="checked"};
1545: var synsel = "";
1546: var syisel = "";
1547: var sybsel = "";
1548: if (kwstyle=="") {var synsel="checked"};
1549: if (kwstyle=="<i>") {var syisel="checked"};
1550: if (kwstyle=="<b>") {var sybsel="checked"};
1551: highlightCentral();
1552: highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
1553: highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
1554: highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
1555: highlightend();
1556: return;
1557: }
1558:
1559: function highlightCentral() {
1560: // if (window.hwdWin) window.hwdWin.close();
1561: var xpos = (screen.width-400)/2;
1562: xpos = (xpos < 0) ? '0' : xpos;
1563: var ypos = (screen.height-330)/2-30;
1564: ypos = (ypos < 0) ? '0' : ypos;
1565:
1566: hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1567: hwdWin.focus();
1568: var hDoc = hwdWin.document;
1569: hDoc.$docopen;
1570: hDoc.write('$start_page_highlight_central');
1571: hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1572: hDoc.write("<h3><span class=\\"LC_info\\"> Keyword Highlight Options<\\/span><\\/h3><br /><br />");
1573:
1574: hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
1575: hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
1576: hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
1577: }
1578:
1579: function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) {
1580: var hDoc = hwdWin.document;
1581: hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1582: hDoc.write("<td align=\\"left\\">");
1583: hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+"> "+clrtxt+"<\\/td>");
1584: hDoc.write("<td align=\\"left\\">");
1585: hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+"> "+sztxt+"<\\/td>");
1586: hDoc.write("<td align=\\"left\\">");
1587: hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+"> "+sytxt+"<\\/td>");
1588: hDoc.write("<\\/tr>");
1589: }
1590:
1591: function highlightend() {
1592: var hDoc = hwdWin.document;
1593: hDoc.write("<\\/table>");
1594: hDoc.write("<\\/td><\\/tr><\\/table> ");
1595: hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\"> ");
1596: hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1597: hDoc.write("<\\/form>");
1598: hDoc.write('$end_page_highlight_central');
1599: hDoc.close();
1600: }
1601:
1602: </script>
1603: SUBJAVASCRIPT
1604: }
1605:
1606: sub get_increment {
1607: my $increment = $env{'form.increment'};
1608: if ($increment != 1 && $increment != .5 && $increment != .25 &&
1609: $increment != .1) {
1610: $increment = 1;
1611: }
1612: return $increment;
1613: }
1614:
1615: #--- displays the grading box, used in essay type problem and grading by page/sequence
1616: sub gradeBox {
1617: my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1618: my $checkIcon = '<img alt="'.&mt('Check Mark').
1619: '" src="'.$request->dir_config('lonIconsURL').
1620: '/check.gif" height="16" border="0" />';
1621: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1622: my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)')
1623: : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1624: $wgt = ($wgt > 0 ? $wgt : '1');
1625: my $score = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1626: '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1627: my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1628: my $display_part= &get_display_part($partid,$symb);
1629: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
1630: [$partid]);
1631: my $aggtries = $$record{'resource.'.$partid.'.tries'};
1632: if ($last_resets{$partid}) {
1633: $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
1634: }
1635: $result.='<table border="0"><tr><td>'.
1636: '<b>Part: </b>'.$display_part.' <b>Points: </b></td><td>'."\n";
1637: my $ctr = 0;
1638: my $thisweight = 0;
1639: my $increment = &get_increment();
1640: $result.='<table border="0"><tr>'."\n"; # display radio buttons in a nice table 10 across
1641: while ($thisweight<=$wgt) {
1642: $result.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1643: 'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1644: $thisweight.')" value="'.$thisweight.'" '.
1645: ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1646: $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1647: $thisweight += $increment;
1648: $ctr++;
1649: }
1650: $result.='</tr></table>';
1651: $result.='</td><td> <b>or</b> </td>'."\n";
1652: $result.='<td><input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1653: ($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1654: 'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1655: $wgt.')" /></td>'."\n";
1656: $result.='<td>/'.$wgt.' '.$wgtmsg.
1657: ($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? ' '.$checkIcon : '').
1658: ' </td><td>'."\n";
1659: $result.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
1660: 'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1661: if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1662: $result.='<option></option>'.
1663: '<option selected="selected">excused</option>';
1664: } else {
1665: $result.='<option selected="selected"></option>'.
1666: '<option>excused</option>';
1667: }
1668: $result.='<option>reset status</option></select>'."\n";
1669: $result.=" \n";
1670: $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
1671: '<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
1672: '<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1673: $$record{'resource.'.$partid.'.solved'}.'" />'."\n".
1674: '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
1675: $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
1676: '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
1677: $aggtries.'" />'."\n";
1678: $result.='</td></tr></table>'."\n";
1679: $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
1680: return $result;
1681: }
1682:
1683: sub handback_box {
1684: my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
1685: my ($partlist,$handgrade,$responseType) = &response_type($symb);
1686: my (@respids);
1687: my @part_response_id = &flatten_responseType($responseType);
1688: foreach my $part_response_id (@part_response_id) {
1689: my ($part,$resp) = @{ $part_response_id };
1690: if ($part eq $partid) {
1691: push(@respids,$resp);
1692: }
1693: }
1694: my $result;
1695: foreach my $respid (@respids) {
1696: my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
1697: my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
1698: next if (!@$files);
1699: my $file_counter = 1;
1700: foreach my $file (@$files) {
1701: if ($file =~ /\/portfolio\//) {
1702: my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1703: my ($name,$version,$ext) = &file_name_version_ext($file_disp);
1704: $file_disp = "$name.$ext";
1705: $file = $file_path.$file_disp;
1706: $result.=&mt('Return commented version of [_1] to student.',
1707: '<span class="LC_filename">'.$file_disp.'</span>');
1708: $result.='<input type="file" name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1709: $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1710: $result.='(File will be uploaded when you click on Save & Next below.)<br />';
1711: $file_counter++;
1712: }
1713: }
1714: }
1715: return $result;
1716: }
1717:
1718: sub show_problem {
1719: my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1720: my $rendered;
1721: my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1722: &Apache::lonxml::remember_problem_counter();
1723: if ($mode eq 'both' or $mode eq 'text') {
1724: $rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1725: $env{'request.course.id'},
1726: undef,\%form);
1727: }
1728: if ($removeform) {
1729: $rendered=~s|<form(.*?)>||g;
1730: $rendered=~s|</form>||g;
1731: $rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1732: }
1733: my $companswer;
1734: if ($mode eq 'both' or $mode eq 'answer') {
1735: &Apache::lonxml::restore_problem_counter();
1736: $companswer=
1737: &Apache::loncommon::get_student_answers($symb,$uname,$udom,
1738: $env{'request.course.id'},
1739: %form);
1740: }
1741: if ($removeform) {
1742: $companswer=~s|<form(.*?)>||g;
1743: $companswer=~s|</form>||g;
1744: $companswer=~s|name="submit"|name="would_have_been_submit"|g;
1745: }
1746: $rendered=
1747: '<div class="LC_grade_show_problem_header">'.
1748: &mt('View of the problem').
1749: '</div><div class="LC_grade_show_problem_problem">'.
1750: $rendered.
1751: '</div>';
1752: $companswer=
1753: '<div class="LC_grade_show_problem_header">'.
1754: &mt('Correct answer').
1755: '</div><div class="LC_grade_show_problem_problem">'.
1756: $companswer.
1757: '</div>';
1758: my $result;
1759: if ($mode eq 'both') {
1760: $result=$rendered.$companswer;
1761: } elsif ($mode eq 'text') {
1762: $result=$rendered;
1763: } elsif ($mode eq 'answer') {
1764: $result=$companswer;
1765: }
1766: $result='<div class="LC_grade_show_problem">'.$result.'</div>';
1767: return $result;
1768: }
1769:
1770: sub files_exist {
1771: my ($r, $symb) = @_;
1772: my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1773:
1774: foreach my $student (@students) {
1775: my ($uname,$udom,$fullname) = split(/:/,$student);
1776: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
1777: $udom,$uname);
1778: my ($string,$timestamp)= &get_last_submission(\%record);
1779: foreach my $submission (@$string) {
1780: my ($partid,$respid) =
1781: ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1782: my $files=&get_submitted_files($udom,$uname,$partid,$respid,
1783: \%record);
1784: return 1 if (@$files);
1785: }
1786: }
1787: return 0;
1788: }
1789:
1790: sub download_all_link {
1791: my ($r,$symb) = @_;
1792: my $all_students =
1793: join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
1794:
1795: my $parts =
1796: join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
1797:
1798: my $identifier = &Apache::loncommon::get_cgi_id();
1799: &Apache::lonnet::appenv('cgi.'.$identifier.'.students' => $all_students,
1800: 'cgi.'.$identifier.'.symb' => $symb,
1801: 'cgi.'.$identifier.'.parts' => $parts,);
1802: $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
1803: &mt('Download All Submitted Documents').'</a>');
1804: return
1805: }
1806:
1807: sub build_section_inputs {
1808: my $section_inputs;
1809: if ($env{'form.section'} eq '') {
1810: $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
1811: } else {
1812: my @sections = &Apache::loncommon::get_env_multiple('form.section');
1813: foreach my $section (@sections) {
1814: $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
1815: }
1816: }
1817: return $section_inputs;
1818: }
1819:
1820: # --------------------------- show submissions of a student, option to grade
1821: sub submission {
1822: my ($request,$counter,$total) = @_;
1823: my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
1824: $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
1825: my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
1826: $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1827: my $symb = &get_symb($request);
1828: if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1829:
1830: if (!&canview($usec)) {
1831: $request->print('<span class="LC_warning">Unable to view requested student.('.
1832: $uname.':'.$udom.' in section '.$usec.' in course id '.
1833: $env{'request.course.id'}.')</span>');
1834: $request->print(&show_grading_menu_form($symb));
1835: return;
1836: }
1837:
1838: if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
1839: if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
1840: if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
1841: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1842: my $checkIcon = '<img alt="'.&mt('Check Mark').
1843: '" src="'.$request->dir_config('lonIconsURL').
1844: '/check.gif" height="16" border="0" />';
1845:
1846: my %old_essays;
1847: # header info
1848: if ($counter == 0) {
1849: &sub_page_js($request);
1850: &sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
1851: $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ?
1852: &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1853: if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1854: &download_all_link($request, $symb);
1855: }
1856: $request->print('<h3> <span class="LC_info">Submission Record</span></h3>'."\n".
1857: '<h4> <b>Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n");
1858:
1859: # option to display problem, only once else it cause problems
1860: # with the form later since the problem has a form.
1861: if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1862: my $mode;
1863: if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1864: $mode='both';
1865: } elsif ($env{'form.vProb'} eq 'yes') {
1866: $mode='text';
1867: } elsif ($env{'form.vAns'} eq 'yes') {
1868: $mode='answer';
1869: }
1870: &Apache::lonxml::clear_problem_counter();
1871: $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1872: }
1873:
1874: # kwclr is the only variable that is guaranteed to be non blank
1875: # if this subroutine has been called once.
1876: my %keyhash = ();
1877: if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1878: %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1879: $env{'course.'.$env{'request.course.id'}.'.domain'},
1880: $env{'course.'.$env{'request.course.id'}.'.num'});
1881:
1882: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1883: $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
1884: $env{'form.kwclr'} = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
1885: $env{'form.kwsize'} = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
1886: $env{'form.kwstyle'} = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
1887: $env{'form.msgsub'} = $keyhash{$symb.'_subject'} ne '' ?
1888: $keyhash{$symb.'_subject'} : $env{'form.probTitle'};
1889: $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1890: }
1891: my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1892: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1893: $request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1894: '<input type="hidden" name="command" value="handgrade" />'."\n".
1895: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1896: '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
1897: '<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1898: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
1899: '<input type="hidden" name="refresh" value="off" />'."\n".
1900: '<input type="hidden" name="studentNo" value="" />'."\n".
1901: '<input type="hidden" name="gradeOpt" value="" />'."\n".
1902: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1903: '<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
1904: '<input type="hidden" name="vProb" value="'.$env{'form.vProb'}.'" />'."\n".
1905: '<input type="hidden" name="vAns" value="'.$env{'form.vAns'}.'" />'."\n".
1906: '<input type="hidden" name="lastSub" value="'.$env{'form.lastSub'}.'" />'."\n".
1907: &build_section_inputs().
1908: '<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1909: '<input type="hidden" name="handgrade" value="'.$env{'form.handgrade'}.'" />'."\n".
1910: '<input type="hidden" name="NCT"'.
1911: ' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1912: if ($env{'form.handgrade'} eq 'yes') {
1913: $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
1914: '<input type="hidden" name="kwclr" value="'.$env{'form.kwclr'}.'" />'."\n".
1915: '<input type="hidden" name="kwsize" value="'.$env{'form.kwsize'}.'" />'."\n".
1916: '<input type="hidden" name="kwstyle" value="'.$env{'form.kwstyle'}.'" />'."\n".
1917: '<input type="hidden" name="msgsub" value="'.$env{'form.msgsub'}.'" />'."\n".
1918: '<input type="hidden" name="shownSub" value="0" />'."\n".
1919: '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1920: foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
1921: $request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
1922: }
1923: }
1924:
1925: my ($cts,$prnmsg) = (1,'');
1926: while ($cts <= $env{'form.savemsgN'}) {
1927: $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1928: (!exists($keyhash{$symb.'_savemsg'.$cts}) ?
1929: &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1930: &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1931: '" />'."\n".
1932: '<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1933: $cts++;
1934: }
1935: $request->print($prnmsg);
1936:
1937: if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1938: #
1939: # Print out the keyword options line
1940: #
1941: $request->print(<<KEYWORDS);
1942: <b>Keyword Options:</b>
1943: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>
1944: <a href="#" onMouseDown="javascript:getSel(); return false"
1945: CLASS="page">Paste Selection to List</a>
1946: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1947: KEYWORDS
1948: #
1949: # Load the other essays for similarity check
1950: #
1951: my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1952: my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1953: $apath=&escape($apath);
1954: $apath=~s/\W/\_/gs;
1955: %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1956: }
1957: }
1958:
1959: # This is where output for one specific student would start
1960: my $add_class = ($counter%2) ? 'LC_grade_show_user_odd_row' : '';
1961: $request->print("\n\n".
1962: '<div class="LC_grade_show_user '.$add_class.'">'.
1963: '<div class="LC_grade_user_name">'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</div>'.
1964: '<div class="LC_grade_show_user_body">'."\n");
1965:
1966: if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1967: my $mode;
1968: if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1969: $mode='both';
1970: } elsif ($env{'form.vProb'} eq 'all' ) {
1971: $mode='text';
1972: } elsif ($env{'form.vAns'} eq 'all') {
1973: $mode='answer';
1974: }
1975: &Apache::lonxml::clear_problem_counter();
1976: $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1977: }
1978:
1979: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1980: my ($partlist,$handgrade,$responseType) = &response_type($symb);
1981:
1982: # Display student info
1983: $request->print(($counter == 0 ? '' : '<br />'));
1984: my $result='<div class="LC_grade_submissions">';
1985:
1986: $result.='<div class="LC_grade_submissions_header">';
1987: $result.= &mt('Submissions');
1988: $result.='<input type="hidden" name="name'.$counter.
1989: '" value="'.$env{'form.fullname'}.'" />'."\n";
1990: if ($env{'form.handgrade'} eq 'no') {
1991: $result.='<span class="LC_grade_check_note">'.
1992: &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)."</span>\n";
1993:
1994: }
1995:
1996:
1997:
1998: # If any part of the problem is an essay-response (handgraded), then check for collaborators
1999: my $fullname;
2000: my $col_fullnames = [];
2001: if ($env{'form.handgrade'} eq 'yes') {
2002: (my $sub_result,$fullname,$col_fullnames)=
2003: &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
2004: $counter);
2005: $result.=$sub_result;
2006: }
2007: $request->print($result."\n");
2008: $request->print('</div>'."\n");
2009: # print student answer/submission
2010: # Options are (1) Handgaded submission only
2011: # (2) Last submission, includes submission that is not handgraded
2012: # (for multi-response type part)
2013: # (3) Last submission plus the parts info
2014: # (4) The whole record for this student
2015: if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
2016: my ($string,$timestamp)= &get_last_submission(\%record);
2017:
2018: my $lastsubonly;
2019:
2020: if ($$timestamp eq '') {
2021: $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>';
2022: } else {
2023: $lastsubonly = '<div class="LC_grade_submissions_body"> <b>Date Submitted:</b> '.$$timestamp."\n";
2024:
2025: my %seenparts;
2026: my @part_response_id = &flatten_responseType($responseType);
2027: foreach my $part (@part_response_id) {
2028: next if ($env{'form.lastSub'} eq 'hdgrade'
2029: && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
2030:
2031: my ($partid,$respid) = @{ $part };
2032: my $display_part=&get_display_part($partid,$symb);
2033: if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
2034: if (exists($seenparts{$partid})) { next; }
2035: $seenparts{$partid}=1;
2036: my $submitby='<b>Part:</b> '.$display_part.
2037: ' <b>Collaborative submission by:</b> '.
2038: '<a href="javascript:viewSubmitter(\''.
2039: $env{"form.$uname:$udom:$partid:submitted_by"}.
2040: '\');" target="_self">'.
2041: $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
2042: $request->print($submitby);
2043: next;
2044: }
2045: my $responsetype = $responseType->{$partid}->{$respid};
2046: if (!exists($record{"resource.$partid.$respid.submission"})) {
2047: $lastsubonly.="\n".'<div class="LC_grade_submission_part"><b>Part:</b> '.
2048: $display_part.' <span class="LC_internal_info">( ID '.$respid.
2049: ' )</span> '.
2050: '<span class="LC_warning">'.&mt('Nothing submitted - no attempts').'</span><br /><br /></div>';
2051: next;
2052: }
2053: foreach my $submission (@$string) {
2054: my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
2055: if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
2056: my ($ressub,$subval) = split(/:/,$submission,2);
2057: # Similarity check
2058: my $similar='';
2059: if($env{'form.checkPlag'}){
2060: my ($oname,$odom,$ocrsid,$oessay,$osim)=
2061: &most_similar($uname,$udom,$subval,\%old_essays);
2062: if ($osim) {
2063: $osim=int($osim*100.0);
2064: my %old_course_desc =
2065: &Apache::lonnet::coursedescription($ocrsid,
2066: {'one_time' => 1});
2067:
2068: $similar="<hr /><h3><span class=\"LC_warning\">".
2069: &mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
2070: $osim,
2071: &Apache::loncommon::plainname($oname,$odom),
2072: $oname,$odom,
2073: $old_course_desc{'description'},
2074: $old_course_desc{'num'},
2075: $old_course_desc{'domain'}).
2076: '</span></h3><blockquote><i>'.
2077: &keywords_highlight($oessay).
2078: '</i></blockquote><hr />';
2079: }
2080: }
2081: my $order=&get_order($partid,$respid,$symb,$uname,$udom);
2082: if ($env{'form.lastSub'} eq 'lastonly' ||
2083: ($env{'form.lastSub'} eq 'hdgrade' &&
2084: $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
2085: my $display_part=&get_display_part($partid,$symb);
2086: $lastsubonly.='<div class="LC_grade_submission_part"><b>Part:</b> '.
2087: $display_part.' <span class="LC_internal_info">( ID '.$respid.
2088: ' )</span> ';
2089: my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
2090: if (@$files) {
2091: $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain virusses').'</span><br />';
2092: my $file_counter = 0;
2093: foreach my $file (@$files) {
2094: $file_counter++;
2095: &Apache::lonnet::allowuploaded('/adm/grades',$file);
2096: $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
2097: }
2098: $lastsubonly.='<br />';
2099: }
2100: $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
2101: &cleanRecord($subval,$responsetype,$symb,$partid,
2102: $respid,\%record,$order);
2103: if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
2104: $lastsubonly.='</div>';
2105: }
2106: }
2107: }
2108: $lastsubonly.='</div>'."\n";
2109: }
2110: $request->print($lastsubonly);
2111: } elsif ($env{'form.lastSub'} eq 'datesub') {
2112: my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
2113: $request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
2114: } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
2115: $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
2116: $env{'request.course.id'},
2117: $last,'.submission',
2118: 'Apache::grades::keywords_highlight'));
2119: }
2120:
2121: $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
2122: .$udom.'" />'."\n");
2123: # return if view submission with no grading option
2124: if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
2125: my $toGrade.='<input type="button" value="Grade Student" '.
2126: 'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
2127: .$counter.'\');" target="_self" /> '."\n" if (&canmodify($usec));
2128: $toGrade.='</div>'."\n";
2129: if (($env{'form.command'} eq 'submission') ||
2130: ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
2131: $toGrade.='</form>'.&show_grading_menu_form($symb);
2132: }
2133: $request->print($toGrade);
2134: return;
2135: } else {
2136: $request->print('</div>'."\n");
2137: }
2138:
2139: # essay grading message center
2140: if ($env{'form.handgrade'} eq 'yes') {
2141: my $result='<div class="LC_grade_message_center">';
2142:
2143: $result.='<div class="LC_grade_message_center_header">'.
2144: &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
2145: my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
2146: my $msgfor = $givenn.' '.$lastname;
2147: if (scalar(@$col_fullnames) > 0) {
2148: my $lastone = pop(@$col_fullnames);
2149: $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
2150: }
2151: $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
2152: $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
2153: '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
2154: $result.=' <a href="javascript:msgCenter(document.SCORE,'.$counter.
2155: ',\''.$msgfor.'\');" target="_self">'.
2156: &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
2157: &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
2158: '<img src="'.$request->dir_config('lonIconsURL').
2159: '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
2160: '<br /> ('.
2161: &mt('Message will be sent when you click on Save & Next below.').")\n";
2162: $result.='</div></div>';
2163: $request->print($result);
2164: }
2165:
2166: my %seen = ();
2167: my @partlist;
2168: my @gradePartRespid;
2169: my @part_response_id = &flatten_responseType($responseType);
2170: $request->print('<div class="LC_grade_assign">'.
2171:
2172: '<div class="LC_grade_assign_header">'.
2173: &mt('Assign Grades').'</div>'.
2174: '<div class="LC_grade_assign_body">');
2175: foreach my $part_response_id (@part_response_id) {
2176: my ($partid,$respid) = @{ $part_response_id };
2177: my $part_resp = join('_',@{ $part_response_id });
2178: next if ($seen{$partid} > 0);
2179: $seen{$partid}++;
2180: next if ($$handgrade{$part_resp} ne 'yes'
2181: && $env{'form.lastSub'} eq 'hdgrade');
2182: push @partlist,$partid;
2183: push @gradePartRespid,$partid.'.'.$respid;
2184: $request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
2185: }
2186: $request->print('</div></div>');
2187:
2188: $request->print('<div class="LC_grade_info_links">');
2189: if ($perm{'vgr'}) {
2190: $request->print(
2191: &Apache::loncommon::track_student_link(&mt('View recent activity'),
2192: $uname,$udom,'check'));
2193: }
2194: if ($perm{'opa'}) {
2195: $request->print(
2196: &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
2197: $uname,$udom,$symb,'check'));
2198: }
2199: $request->print('</div>');
2200:
2201: $result='<input type="hidden" name="partlist'.$counter.
2202: '" value="'.(join ":",@partlist).'" />'."\n";
2203: $result.='<input type="hidden" name="gradePartRespid'.
2204: '" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
2205: my $ctr = 0;
2206: while ($ctr < scalar(@partlist)) {
2207: $result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
2208: $partlist[$ctr].'" />'."\n";
2209: $ctr++;
2210: }
2211: $request->print($result.''."\n");
2212:
2213: # Done with printing info for one student
2214:
2215: $request->print('</div>');#LC_grade_show_user_body
2216: $request->print('</div>');#LC_grade_show_user
2217:
2218:
2219: # print end of form
2220: if ($counter == $total) {
2221: my $endform='<table border="0"><tr><td>'."\n";
2222: $endform.='<input type="button" value="Save & Next" '.
2223: 'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
2224: $total.','.scalar(@partlist).');" target="_self" /> '."\n";
2225: my $ntstu ='<select name="NTSTU">'.
2226: '<option>1</option><option>2</option>'.
2227: '<option>3</option><option>5</option>'.
2228: '<option>7</option><option>10</option></select>'."\n";
2229: my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
2230: $ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
2231: $endform.=$ntstu.'student(s) ';
2232: $endform.='<input type="button" value="Previous" '.
2233: 'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> '."\n".
2234: '<input type="button" value="Next" '.
2235: 'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> ';
2236: $endform.='(Next and Previous (student) do not save the scores.)'."\n" ;
2237: $endform.="<input type='hidden' value='".&get_increment().
2238: "' name='increment' />";
2239: $endform.='</td><tr></table></form>';
2240: $endform.=&show_grading_menu_form($symb);
2241: $request->print($endform);
2242: }
2243: return '';
2244: }
2245:
2246: sub check_collaborators {
2247: my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
2248: my ($result,@col_fullnames);
2249: my ($classlist,undef,$fullname) = &getclasslist('all','0');
2250: foreach my $part (keys(%$handgrade)) {
2251: my $ncol = &Apache::lonnet::EXT('resource.'.$part.
2252: '.maxcollaborators',
2253: $symb,$udom,$uname);
2254: next if ($ncol <= 0);
2255: $part =~ s/\_/\./g;
2256: next if ($record->{'resource.'.$part.'.collaborators'} eq '');
2257: my (@good_collaborators, @bad_collaborators);
2258: foreach my $possible_collaborator
2259: (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) {
2260: $possible_collaborator =~ s/[\$\^\(\)]//g;
2261: next if ($possible_collaborator eq '');
2262: my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
2263: $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
2264: next if ($co_name eq $uname && $co_dom eq $udom);
2265: # Doing this grep allows 'fuzzy' specification
2266: my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i,
2267: keys(%$classlist));
2268: if (! scalar(@matches)) {
2269: push(@bad_collaborators, $possible_collaborator);
2270: } else {
2271: push(@good_collaborators, @matches);
2272: }
2273: }
2274: if (scalar(@good_collaborators) != 0) {
2275: $result.='<br />'.&mt('Collaborators: ');
2276: foreach my $name (@good_collaborators) {
2277: my ($lastname,$givenn) = split(/,/,$$fullname{$name});
2278: push(@col_fullnames, $givenn.' '.$lastname);
2279: $result.=$fullname->{$name}.' ';
2280: }
2281: $result.='<br />'."\n";
2282: my ($part)=split(/\./,$part);
2283: $result.='<input type="hidden" name="collaborator'.$counter.
2284: '" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
2285: "\n";
2286: }
2287: if (scalar(@bad_collaborators) > 0) {
2288: $result.='<div class="LC_warning">';
2289: $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
2290: $result .= '</div>';
2291: }
2292: if (scalar(@bad_collaborators > $ncol)) {
2293: $result .= '<div class="LC_warning">';
2294: $result .= &mt('This student has submitted too many '.
2295: 'collaborators. Maximum is [_1].',$ncol);
2296: $result .= '</div>';
2297: }
2298: }
2299: return ($result,$fullname,\@col_fullnames);
2300: }
2301:
2302: #--- Retrieve the last submission for all the parts
2303: sub get_last_submission {
2304: my ($returnhash)=@_;
2305: my (@string,$timestamp);
2306: if ($$returnhash{'version'}) {
2307: my %lasthash=();
2308: my ($version);
2309: for ($version=1;$version<=$$returnhash{'version'};$version++) {
2310: foreach my $key (sort(split(/\:/,
2311: $$returnhash{$version.':keys'}))) {
2312: $lasthash{$key}=$$returnhash{$version.':'.$key};
2313: $timestamp =
2314: scalar(localtime($$returnhash{$version.':timestamp'}));
2315: }
2316: }
2317: foreach my $key (keys(%lasthash)) {
2318: next if ($key !~ /\.submission$/);
2319:
2320: my ($partid,$foo) = split(/submission$/,$key);
2321: my $draft = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
2322: '<span class="LC_warning">Draft Copy</span> ' : '';
2323: push(@string, join(':', $key, $draft.$lasthash{$key}));
2324: }
2325: }
2326: if (!@string) {
2327: $string[0] =
2328: '<span class="LC_warning">Nothing submitted - no attempts.</span>';
2329: }
2330: return (\@string,\$timestamp);
2331: }
2332:
2333: #--- High light keywords, with style choosen by user.
2334: sub keywords_highlight {
2335: my $string = shift;
2336: my $size = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
2337: my $styleon = $env{'form.kwstyle'} eq '' ? '' : $env{'form.kwstyle'};
2338: (my $styleoff = $styleon) =~ s/\</\<\//;
2339: my @keylist = split(/[,\s+]/,$env{'form.keywords'});
2340: foreach my $keyword (@keylist) {
2341: $string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
2342: }
2343: return $string;
2344: }
2345:
2346: #--- Called from submission routine
2347: sub processHandGrade {
2348: my ($request) = shift;
2349: my $symb = &get_symb($request);
2350: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
2351: my $button = $env{'form.gradeOpt'};
2352: my $ngrade = $env{'form.NCT'};
2353: my $ntstu = $env{'form.NTSTU'};
2354: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2355: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2356:
2357: if ($button eq 'Save & Next') {
2358: my $ctr = 0;
2359: while ($ctr < $ngrade) {
2360: my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
2361: my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
2362: if ($errorflag eq 'no_score') {
2363: $ctr++;
2364: next;
2365: }
2366: if ($errorflag eq 'not_allowed') {
2367: $request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
2368: $ctr++;
2369: next;
2370: }
2371: my $includemsg = $env{'form.includemsg'.$ctr};
2372: my ($subject,$message,$msgstatus) = ('','','');
2373: my $restitle = &Apache::lonnet::gettitle($symb);
2374: my ($feedurl,$showsymb) =
2375: &get_feedurl_and_symb($symb,$uname,$udom);
2376: my $messagetail;
2377: if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
2378: $subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
2379: unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
2380: $subject.=' ['.$restitle.']';
2381: my (@msgnum) = split(/,/,$includemsg);
2382: foreach (@msgnum) {
2383: $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
2384: }
2385: $message =&Apache::lonfeedback::clear_out_html($message);
2386: if ($env{'form.withgrades'.$ctr}) {
2387: $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
2388: $messagetail = " for <a href=\"".
2389: $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
2390: }
2391: $msgstatus =
2392: &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
2393: $message.$messagetail,
2394: undef,$feedurl,undef,
2395: undef,undef,$showsymb,
2396: $restitle);
2397: $request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
2398: $msgstatus);
2399: }
2400: if ($env{'form.collaborator'.$ctr}) {
2401: my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
2402: foreach my $collabstr (@collabstrs) {
2403: my ($part,@collaborators) = split(/:/,$collabstr);
2404: foreach my $collaborator (@collaborators) {
2405: my ($errorflag,$pts,$wgt) =
2406: &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
2407: $env{'form.unamedom'.$ctr},$part);
2408: if ($errorflag eq 'not_allowed') {
2409: $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
2410: next;
2411: } elsif ($message ne '') {
2412: my ($baseurl,$showsymb) =
2413: &get_feedurl_and_symb($symb,$collaborator,
2414: $udom);
2415: if ($env{'form.withgrades'.$ctr}) {
2416: $messagetail = " for <a href=\"".
2417: $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
2418: }
2419: $msgstatus =
2420: &Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
2421: }
2422: }
2423: }
2424: }
2425: $ctr++;
2426: }
2427: }
2428:
2429: if ($env{'form.handgrade'} eq 'yes') {
2430: # Keywords sorted in alphabatical order
2431: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
2432: my %keyhash = ();
2433: $env{'form.keywords'} =~ s/,\s{0,}|\s+/ /g;
2434: $env{'form.keywords'} =~ s/^\s+|\s+$//;
2435: my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
2436: $env{'form.keywords'} = join(' ',@keywords);
2437: $keyhash{$symb.'_keywords'} = $env{'form.keywords'};
2438: $keyhash{$symb.'_subject'} = $env{'form.msgsub'};
2439: $keyhash{$loginuser.'_kwclr'} = $env{'form.kwclr'};
2440: $keyhash{$loginuser.'_kwsize'} = $env{'form.kwsize'};
2441: $keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
2442:
2443: # message center - Order of message gets changed. Blank line is eliminated.
2444: # New messages are saved in env for the next student.
2445: # All messages are saved in nohist_handgrade.db
2446: my ($ctr,$idx) = (1,1);
2447: while ($ctr <= $env{'form.savemsgN'}) {
2448: if ($env{'form.savemsg'.$ctr} ne '') {
2449: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
2450: $idx++;
2451: }
2452: $ctr++;
2453: }
2454: $ctr = 0;
2455: while ($ctr < $ngrade) {
2456: if ($env{'form.newmsg'.$ctr} ne '') {
2457: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2458: $env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2459: $idx++;
2460: }
2461: $ctr++;
2462: }
2463: $env{'form.savemsgN'} = --$idx;
2464: $keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
2465: my $putresult = &Apache::lonnet::put
2466: ('nohist_handgrade',\%keyhash,$cdom,$cnum);
2467: }
2468: # Called by Save & Refresh from Highlight Attribute Window
2469: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
2470: if ($env{'form.refresh'} eq 'on') {
2471: my ($ctr,$total) = (0,0);
2472: while ($ctr < $ngrade) {
2473: $total++ if $env{'form.unamedom'.$ctr} ne '';
2474: $ctr++;
2475: }
2476: $env{'form.NTSTU'}=$ngrade;
2477: $ctr = 0;
2478: while ($ctr < $total) {
2479: my $processUser = $env{'form.unamedom'.$ctr};
2480: ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
2481: $env{'form.fullname'} = $$fullname{$processUser};
2482: &submission($request,$ctr,$total-1);
2483: $ctr++;
2484: }
2485: return '';
2486: }
2487:
2488: # Go directly to grade student - from submission or link from chart page
2489: if ($button eq 'Grade Student') {
2490: (undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
2491: my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
2492: ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
2493: $env{'form.fullname'} = $$fullname{$processUser};
2494: &submission($request,0,0);
2495: return '';
2496: }
2497:
2498: # Get the next/previous one or group of students
2499: my $firststu = $env{'form.unamedom0'};
2500: my $laststu = $env{'form.unamedom'.($ngrade-1)};
2501: my $ctr = 2;
2502: while ($laststu eq '') {
2503: $laststu = $env{'form.unamedom'.($ngrade-$ctr)};
2504: $ctr++;
2505: $laststu = $firststu if ($ctr > $ngrade);
2506: }
2507:
2508: my (@parsedlist,@nextlist);
2509: my ($nextflg) = 0;
2510: foreach (sort
2511: {
2512: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
2513: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
2514: }
2515: return $a cmp $b;
2516: } (keys(%$fullname))) {
2517: if ($nextflg == 1 && $button =~ /Next$/) {
2518: push @parsedlist,$_;
2519: }
2520: $nextflg = 1 if ($_ eq $laststu);
2521: if ($button eq 'Previous') {
2522: last if ($_ eq $firststu);
2523: push @parsedlist,$_;
2524: }
2525: }
2526: $ctr = 0;
2527: @parsedlist = reverse @parsedlist if ($button eq 'Previous');
2528: my ($partlist) = &response_type($symb);
2529: foreach my $student (@parsedlist) {
2530: my $submitonly=$env{'form.submitonly'};
2531: my ($uname,$udom) = split(/:/,$student);
2532:
2533: if ($submitonly eq 'queued') {
2534: my %queue_status =
2535: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
2536: $udom,$uname);
2537: next if (!defined($queue_status{'gradingqueue'}));
2538: }
2539:
2540: if ($submitonly =~ /^(yes|graded|incorrect)$/) {
2541: # my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
2542: my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
2543: my $submitted = 0;
2544: my $ungraded = 0;
2545: my $incorrect = 0;
2546: foreach (keys(%status)) {
2547: $submitted = 1 if ($status{$_} ne 'nothing');
2548: $ungraded = 1 if ($status{$_} =~ /^ungraded/);
2549: $incorrect = 1 if ($status{$_} =~ /^incorrect/);
2550: my ($foo,$partid,$foo1) = split(/\./,$_);
2551: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
2552: $submitted = 0;
2553: }
2554: }
2555: next if (!$submitted && ($submitonly eq 'yes' ||
2556: $submitonly eq 'incorrect' ||
2557: $submitonly eq 'graded'));
2558: next if (!$ungraded && ($submitonly eq 'graded'));
2559: next if (!$incorrect && $submitonly eq 'incorrect');
2560: }
2561: push @nextlist,$student if ($ctr < $ntstu);
2562: last if ($ctr == $ntstu);
2563: $ctr++;
2564: }
2565:
2566: $ctr = 0;
2567: my $total = scalar(@nextlist)-1;
2568:
2569: foreach (sort @nextlist) {
2570: my ($uname,$udom,$submitter) = split(/:/);
2571: $env{'form.student'} = $uname;
2572: $env{'form.userdom'} = $udom;
2573: $env{'form.fullname'} = $$fullname{$_};
2574: &submission($request,$ctr,$total);
2575: $ctr++;
2576: }
2577: if ($total < 0) {
2578: my $the_end = '<h3><span class="LC_info">LON-CAPA User Message</span></h3><br />'."\n";
2579: $the_end.='<b>Message: </b> No more students for this section or class.<br /><br />'."\n";
2580: $the_end.='Click on the button below to return to the grading menu.<br /><br />'."\n";
2581: $the_end.=&show_grading_menu_form($symb);
2582: $request->print($the_end);
2583: }
2584: return '';
2585: }
2586:
2587: #---- Save the score and award for each student, if changed
2588: sub saveHandGrade {
2589: my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
2590: my @version_parts;
2591: my $usec = &Apache::lonnet::getsection($domain,$stuname,
2592: $env{'request.course.id'});
2593: if (!&canmodify($usec)) { return('not_allowed'); }
2594: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
2595: my @parts_graded;
2596: my %newrecord = ();
2597: my ($pts,$wgt) = ('','');
2598: my %aggregate = ();
2599: my $aggregateflag = 0;
2600: my @parts = split(/:/,$env{'form.partlist'.$newflg});
2601: foreach my $new_part (@parts) {
2602: #collaborator ($submi may vary for different parts
2603: if ($submitter && $new_part ne $part) { next; }
2604: my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
2605: if ($dropMenu eq 'excused') {
2606: if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
2607: $newrecord{'resource.'.$new_part.'.solved'} = 'excused';
2608: if (exists($record{'resource.'.$new_part.'.awarded'})) {
2609: $newrecord{'resource.'.$new_part.'.awarded'} = '';
2610: }
2611: $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
2612: }
2613: } elsif ($dropMenu eq 'reset status'
2614: && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
2615: foreach my $key (keys (%record)) {
2616: if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
2617: }
2618: $newrecord{'resource.'.$new_part.'.regrader'}=
2619: "$env{'user.name'}:$env{'user.domain'}";
2620: my $totaltries = $record{'resource.'.$part.'.tries'};
2621:
2622: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
2623: [$new_part]);
2624: my $aggtries =$totaltries;
2625: if ($last_resets{$new_part}) {
2626: $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
2627: $new_part);
2628: }
2629:
2630: my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
2631: if ($aggtries > 0) {
2632: &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
2633: $aggregateflag = 1;
2634: }
2635: } elsif ($dropMenu eq '') {
2636: $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ?
2637: $env{'form.GD_BOX'.$newflg.'_'.$new_part} :
2638: $env{'form.RADVAL'.$newflg.'_'.$new_part});
2639: if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
2640: next;
2641: }
2642: $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 :
2643: $env{'form.WGT'.$newflg.'_'.$new_part};
2644: my $partial= $pts/$wgt;
2645: if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
2646: #do not update score for part if not changed.
2647: &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
2648: next;
2649: } else {
2650: push @parts_graded, $new_part;
2651: }
2652: if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
2653: $newrecord{'resource.'.$new_part.'.awarded'} = $partial;
2654: }
2655: my $reckey = 'resource.'.$new_part.'.solved';
2656: if ($partial == 0) {
2657: if ($record{$reckey} ne 'incorrect_by_override') {
2658: $newrecord{$reckey} = 'incorrect_by_override';
2659: }
2660: } else {
2661: if ($record{$reckey} ne 'correct_by_override') {
2662: $newrecord{$reckey} = 'correct_by_override';
2663: }
2664: }
2665: if ($submitter &&
2666: ($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
2667: $newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
2668: }
2669: $newrecord{'resource.'.$new_part.'.regrader'}=
2670: "$env{'user.name'}:$env{'user.domain'}";
2671: }
2672: # unless problem has been graded, set flag to version the submitted files
2673: unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/ ||
2674: $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
2675: $dropMenu eq 'reset status')
2676: {
2677: push (@version_parts,$new_part);
2678: }
2679: }
2680: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2681: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2682:
2683: if (%newrecord) {
2684: if (@version_parts) {
2685: my @changed_keys = &version_portfiles(\%record, \@parts_graded,
2686: $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
2687: @newrecord{@changed_keys} = @record{@changed_keys};
2688: foreach my $new_part (@version_parts) {
2689: &handback_files($request,$symb,$stuname,$domain,$newflg,
2690: $new_part,\%newrecord);
2691: }
2692: }
2693: &Apache::lonnet::cstore(\%newrecord,$symb,
2694: $env{'request.course.id'},$domain,$stuname);
2695: &check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
2696: $cdom,$cnum,$domain,$stuname);
2697: }
2698: if ($aggregateflag) {
2699: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
2700: $cdom,$cnum);
2701: }
2702: return ('',$pts,$wgt);
2703: }
2704:
2705: sub check_and_remove_from_queue {
2706: my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
2707: my @ungraded_parts;
2708: foreach my $part (@{$parts}) {
2709: if ( $record->{ 'resource.'.$part.'.awarded'} eq ''
2710: && $record->{ 'resource.'.$part.'.solved' } ne 'excused'
2711: && $newrecord->{'resource.'.$part.'.awarded'} eq ''
2712: && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
2713: ) {
2714: push(@ungraded_parts, $part);
2715: }
2716: }
2717: if ( !@ungraded_parts ) {
2718: &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
2719: $cnum,$domain,$stuname);
2720: }
2721: }
2722:
2723: sub handback_files {
2724: my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
2725: my $portfolio_root = &propath($domain,$stuname).'/userfiles/portfolio';
2726: my ($partlist,$handgrade,$responseType) = &response_type($symb);
2727:
2728: my @part_response_id = &flatten_responseType($responseType);
2729: foreach my $part_response_id (@part_response_id) {
2730: my ($part_id,$resp_id) = @{ $part_response_id };
2731: my $part_resp = join('_',@{ $part_response_id });
2732: if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
2733: # if multiple files are uploaded names will be 'returndoc2','returndoc3'
2734: my $file_counter = 1;
2735: my $file_msg;
2736: while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
2737: my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
2738: my ($directory,$answer_file) =
2739: ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
2740: my ($answer_name,$answer_ver,$answer_ext) =
2741: &file_name_version_ext($answer_file);
2742: my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
2743: my @dir_list = &Apache::lonnet::dirlist($portfolio_path,$domain,$stuname,$portfolio_root);
2744: my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
2745: # fix file name
2746: my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
2747: my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
2748: $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
2749: $save_file_name);
2750: if ($result !~ m|^/uploaded/|) {
2751: $request->print('<span class="LC_error">An error occurred ('.$result.
2752: ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</span><br />');
2753: } else {
2754: # mark the file as read only
2755: my @files = ($save_file_name);
2756: my @what = ($symb,$env{'request.course.id'},'handback');
2757: &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
2758: if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
2759: $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
2760: }
2761: $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
2762: $file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
2763:
2764: }
2765: $request->print("<br />".$fname." will be the uploaded file name");
2766: $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
2767: $file_counter++;
2768: }
2769: my $subject = "File Handed Back by Instructor ";
2770: my $message = "A file has been returned that was originally submitted in reponse to: <br />";
2771: $message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
2772: $message .= ' The returned file(s) are named: '. $file_msg;
2773: $message .= " and can be found in your portfolio space.";
2774: my ($feedurl,$showsymb) =
2775: &get_feedurl_and_symb($symb,$domain,$stuname);
2776: my $restitle = &Apache::lonnet::gettitle($symb);
2777: my $msgstatus =
2778: &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
2779: ' (File Returned) ['.$restitle.']',$message,undef,
2780: $feedurl,undef,undef,undef,$showsymb,$restitle);
2781: }
2782: }
2783: return;
2784: }
2785:
2786: sub get_feedurl_and_symb {
2787: my ($symb,$uname,$udom) = @_;
2788: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
2789: $url = &Apache::lonnet::clutter($url);
2790: my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
2791: $symb,$udom,$uname);
2792: if ($encrypturl =~ /^yes$/i) {
2793: &Apache::lonenc::encrypted(\$url,1);
2794: &Apache::lonenc::encrypted(\$symb,1);
2795: }
2796: return ($url,$symb);
2797: }
2798:
2799: sub get_submitted_files {
2800: my ($udom,$uname,$partid,$respid,$record) = @_;
2801: my @files;
2802: if ($$record{"resource.$partid.$respid.portfiles"}) {
2803: my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
2804: foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
2805: push(@files,$file_url.$file);
2806: }
2807: }
2808: if ($$record{"resource.$partid.$respid.uploadedurl"}) {
2809: push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
2810: }
2811: return (\@files);
2812: }
2813:
2814: # ----------- Provides number of tries since last reset.
2815: sub get_num_tries {
2816: my ($record,$last_reset,$part) = @_;
2817: my $timestamp = '';
2818: my $num_tries = 0;
2819: if ($$record{'version'}) {
2820: for (my $version=$$record{'version'};$version>=1;$version--) {
2821: if (exists($$record{$version.':resource.'.$part.'.solved'})) {
2822: $timestamp = $$record{$version.':timestamp'};
2823: if ($timestamp > $last_reset) {
2824: $num_tries ++;
2825: } else {
2826: last;
2827: }
2828: }
2829: }
2830: }
2831: return $num_tries;
2832: }
2833:
2834: # ----------- Determine decrements required in aggregate totals
2835: sub decrement_aggs {
2836: my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
2837: my %decrement = (
2838: attempts => 0,
2839: users => 0,
2840: correct => 0
2841: );
2842: $decrement{'attempts'} = $aggtries;
2843: if ($solvedstatus =~ /^correct/) {
2844: $decrement{'correct'} = 1;
2845: }
2846: if ($aggtries == $totaltries) {
2847: $decrement{'users'} = 1;
2848: }
2849: foreach my $type (keys (%decrement)) {
2850: $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
2851: }
2852: return;
2853: }
2854:
2855: # ----------- Determine timestamps for last reset of aggregate totals for parts
2856: sub get_last_resets {
2857: my ($symb,$courseid,$partids) =@_;
2858: my %last_resets;
2859: my $cdom = $env{'course.'.$courseid.'.domain'};
2860: my $cname = $env{'course.'.$courseid.'.num'};
2861: my @keys;
2862: foreach my $part (@{$partids}) {
2863: push(@keys,"$symb\0$part\0resettime");
2864: }
2865: my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
2866: $cdom,$cname);
2867: foreach my $part (@{$partids}) {
2868: $last_resets{$part}=$results{"$symb\0$part\0resettime"};
2869: }
2870: return %last_resets;
2871: }
2872:
2873: # ----------- Handles creating versions for portfolio files as answers
2874: sub version_portfiles {
2875: my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
2876: my $version_parts = join('|',@$v_flag);
2877: my @returned_keys;
2878: my $parts = join('|', @$parts_graded);
2879: my $portfolio_root = &propath($domain,$stu_name).
2880: '/userfiles/portfolio';
2881: foreach my $key (keys(%$record)) {
2882: my $new_portfiles;
2883: if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
2884: my @versioned_portfiles;
2885: my @portfiles = split(/\s*,\s*/,$$record{$key});
2886: foreach my $file (@portfiles) {
2887: &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
2888: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
2889: my ($answer_name,$answer_ver,$answer_ext) =
2890: &file_name_version_ext($answer_file);
2891: my @dir_list = &Apache::lonnet::dirlist($directory,$domain,$stu_name,$portfolio_root);
2892: my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
2893: my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
2894: if ($new_answer ne 'problem getting file') {
2895: push(@versioned_portfiles, $directory.$new_answer);
2896: &Apache::lonnet::mark_as_readonly($domain,$stu_name,
2897: [$directory.$new_answer],
2898: [$symb,$env{'request.course.id'},'graded']);
2899: }
2900: }
2901: $$record{$key} = join(',',@versioned_portfiles);
2902: push(@returned_keys,$key);
2903: }
2904: }
2905: return (@returned_keys);
2906: }
2907:
2908: sub get_next_version {
2909: my ($answer_name, $answer_ext, $dir_list) = @_;
2910: my $version;
2911: foreach my $row (@$dir_list) {
2912: my ($file) = split(/\&/,$row,2);
2913: my ($file_name,$file_version,$file_ext) =
2914: &file_name_version_ext($file);
2915: if (($file_name eq $answer_name) &&
2916: ($file_ext eq $answer_ext)) {
2917: # gets here if filename and extension match, regardless of version
2918: if ($file_version ne '') {
2919: # a versioned file is found so save it for later
2920: if ($file_version > $version) {
2921: $version = $file_version;
2922: }
2923: }
2924: }
2925: }
2926: $version ++;
2927: return($version);
2928: }
2929:
2930: sub version_selected_portfile {
2931: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
2932: my ($answer_name,$answer_ver,$answer_ext) =
2933: &file_name_version_ext($file_name);
2934: my $new_answer;
2935: $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
2936: if($env{'form.copy'} eq '-1') {
2937: $new_answer = 'problem getting file';
2938: } else {
2939: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
2940: my $copy_result = &Apache::lonnet::finishuserfileupload(
2941: $stu_name,$domain,'copy',
2942: '/portfolio'.$directory.$new_answer);
2943: }
2944: return ($new_answer);
2945: }
2946:
2947: sub file_name_version_ext {
2948: my ($file)=@_;
2949: my @file_parts = split(/\./, $file);
2950: my ($name,$version,$ext);
2951: if (@file_parts > 1) {
2952: $ext=pop(@file_parts);
2953: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
2954: $version=pop(@file_parts);
2955: }
2956: $name=join('.',@file_parts);
2957: } else {
2958: $name=join('.',@file_parts);
2959: }
2960: return($name,$version,$ext);
2961: }
2962:
2963: #--------------------------------------------------------------------------------------
2964: #
2965: #-------------------------- Next few routines handles grading by section or whole class
2966: #
2967: #--- Javascript to handle grading by section or whole class
2968: sub viewgrades_js {
2969: my ($request) = shift;
2970:
2971: $request->print(<<VIEWJAVASCRIPT);
2972: <script type="text/javascript" language="javascript">
2973: function writePoint(partid,weight,point) {
2974: var radioButton = document.classgrade["RADVAL_"+partid];
2975: var textbox = document.classgrade["TEXTVAL_"+partid];
2976: if (point == "textval") {
2977: point = document.classgrade["TEXTVAL_"+partid].value;
2978: if (isNaN(point) || parseFloat(point) < 0) {
2979: alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
2980: var resetbox = false;
2981: for (var i=0; i<radioButton.length; i++) {
2982: if (radioButton[i].checked) {
2983: textbox.value = i;
2984: resetbox = true;
2985: }
2986: }
2987: if (!resetbox) {
2988: textbox.value = "";
2989: }
2990: return;
2991: }
2992: if (parseFloat(point) > parseFloat(weight)) {
2993: var resp = confirm("You entered a value ("+parseFloat(point)+
2994: ") greater than the weight for the part. Accept?");
2995: if (resp == false) {
2996: textbox.value = "";
2997: return;
2998: }
2999: }
3000: for (var i=0; i<radioButton.length; i++) {
3001: radioButton[i].checked=false;
3002: if (parseFloat(point) == i) {
3003: radioButton[i].checked=true;
3004: }
3005: }
3006:
3007: } else {
3008: textbox.value = parseFloat(point);
3009: }
3010: for (i=0;i<document.classgrade.total.value;i++) {
3011: var user = document.classgrade["ctr"+i].value;
3012: user = user.replace(new RegExp(':', 'g'),"_");
3013: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3014: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3015: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3016: if (saveval != "correct") {
3017: scorename.value = point;
3018: if (selname[0].selected != true) {
3019: selname[0].selected = true;
3020: }
3021: }
3022: }
3023: document.classgrade["SELVAL_"+partid][0].selected = true;
3024: }
3025:
3026: function writeRadText(partid,weight) {
3027: var selval = document.classgrade["SELVAL_"+partid];
3028: var radioButton = document.classgrade["RADVAL_"+partid];
3029: var override = document.classgrade["FORCE_"+partid].checked;
3030: var textbox = document.classgrade["TEXTVAL_"+partid];
3031: if (selval[1].selected || selval[2].selected) {
3032: for (var i=0; i<radioButton.length; i++) {
3033: radioButton[i].checked=false;
3034:
3035: }
3036: textbox.value = "";
3037:
3038: for (i=0;i<document.classgrade.total.value;i++) {
3039: var user = document.classgrade["ctr"+i].value;
3040: user = user.replace(new RegExp(':', 'g'),"_");
3041: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3042: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3043: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3044: if ((saveval != "correct") || override) {
3045: scorename.value = "";
3046: if (selval[1].selected) {
3047: selname[1].selected = true;
3048: } else {
3049: selname[2].selected = true;
3050: if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value))
3051: {document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
3052: }
3053: }
3054: }
3055: } else {
3056: for (i=0;i<document.classgrade.total.value;i++) {
3057: var user = document.classgrade["ctr"+i].value;
3058: user = user.replace(new RegExp(':', 'g'),"_");
3059: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3060: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3061: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3062: if ((saveval != "correct") || override) {
3063: scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
3064: selname[0].selected = true;
3065: }
3066: }
3067: }
3068: }
3069:
3070: function changeSelect(partid,user) {
3071: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
3072: var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
3073: var point = textbox.value;
3074: var weight = document.classgrade["weight_"+partid].value;
3075:
3076: if (isNaN(point) || parseFloat(point) < 0) {
3077: alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
3078: textbox.value = "";
3079: return;
3080: }
3081: if (parseFloat(point) > parseFloat(weight)) {
3082: var resp = confirm("You entered a value ("+parseFloat(point)+
3083: ") greater than the weight of the part. Accept?");
3084: if (resp == false) {
3085: textbox.value = "";
3086: return;
3087: }
3088: }
3089: selval[0].selected = true;
3090: }
3091:
3092: function changeOneScore(partid,user) {
3093: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
3094: if (selval[1].selected || selval[2].selected) {
3095: document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
3096: if (selval[2].selected) {
3097: document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
3098: }
3099: }
3100: }
3101:
3102: function resetEntry(numpart) {
3103: for (ctpart=0;ctpart<numpart;ctpart++) {
3104: var partid = document.classgrade["partid_"+ctpart].value;
3105: var radioButton = document.classgrade["RADVAL_"+partid];
3106: var textbox = document.classgrade["TEXTVAL_"+partid];
3107: var selval = document.classgrade["SELVAL_"+partid];
3108: for (var i=0; i<radioButton.length; i++) {
3109: radioButton[i].checked=false;
3110:
3111: }
3112: textbox.value = "";
3113: selval[0].selected = true;
3114:
3115: for (i=0;i<document.classgrade.total.value;i++) {
3116: var user = document.classgrade["ctr"+i].value;
3117: user = user.replace(new RegExp(':', 'g'),"_");
3118: var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3119: resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
3120: var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
3121: resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
3122: var saveselval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3123: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3124: if (saveselval == "excused") {
3125: if (selname[1].selected == false) { selname[1].selected = true;}
3126: } else {
3127: if (selname[0].selected == false) {selname[0].selected = true};
3128: }
3129: }
3130: }
3131: }
3132:
3133: </script>
3134: VIEWJAVASCRIPT
3135: }
3136:
3137: #--- show scores for a section or whole class w/ option to change/update a score
3138: sub viewgrades {
3139: my ($request) = shift;
3140: &viewgrades_js($request);
3141:
3142: my ($symb) = &get_symb($request);
3143: #need to make sure we have the correct data for later EXT calls,
3144: #thus invalidate the cache
3145: &Apache::lonnet::devalidatecourseresdata(
3146: $env{'course.'.$env{'request.course.id'}.'.num'},
3147: $env{'course.'.$env{'request.course.id'}.'.domain'});
3148: &Apache::lonnet::clear_EXT_cache_status();
3149:
3150: my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
3151: $result.='<h4><b>Current Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n";
3152:
3153: #view individual student submission form - called using Javascript viewOneStudent
3154: $result.=&jscriptNform($symb);
3155:
3156: #beginning of class grading form
3157: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
3158: $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
3159: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
3160: '<input type="hidden" name="command" value="editgrades" />'."\n".
3161: &build_section_inputs().
3162: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
3163: '<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
3164: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
3165:
3166: my $sectionClass;
3167: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3168: if ($env{'form.section'} eq 'all') {
3169: $sectionClass='Class </h3>';
3170: } elsif ($env{'form.section'} eq 'none') {
3171: $sectionClass=&mt('Students in no Section').'</h3>';
3172: } else {
3173: $sectionClass=&mt('Students in Section(s) [_1]',$section_display).'</h3>';
3174: }
3175: $result.='<h3>'.&mt('Assign Common Grade To [_1]',$sectionClass);
3176: $result.= &Apache::loncommon::start_data_table();
3177: #radio buttons/text box for assigning points for a section or class.
3178: #handles different parts of a problem
3179: my ($partlist,$handgrade,$responseType) = &response_type($symb);
3180: my %weight = ();
3181: my $ctsparts = 0;
3182: my %seen = ();
3183: my @part_response_id = &flatten_responseType($responseType);
3184: foreach my $part_response_id (@part_response_id) {
3185: my ($partid,$respid) = @{ $part_response_id };
3186: my $part_resp = join('_',@{ $part_response_id });
3187: next if $seen{$partid};
3188: $seen{$partid}++;
3189: my $handgrade=$$handgrade{$part_resp};
3190: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
3191: $weight{$partid} = $wgt eq '' ? '1' : $wgt;
3192:
3193: $result.=&Apache::loncommon::start_data_table_row().'<td>';
3194: $result.='<input type="hidden" name="partid_'.
3195: $ctsparts.'" value="'.$partid.'" />'."\n";
3196: $result.='<input type="hidden" name="weight_'.
3197: $partid.'" value="'.$weight{$partid}.'" />'."\n";
3198: my $display_part=&get_display_part($partid,$symb);
3199: $result.=
3200: '<b>Part:</b> '.$display_part.' <b>Point:</b> </td><td>';
3201: $result.='<table border="0"><tr>';
3202: my $ctr = 0;
3203: while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
3204: $result.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
3205: 'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
3206: ','.$ctr.')" />'.$ctr."</label></td>\n";
3207: $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
3208: $ctr++;
3209: }
3210: $result.='</tr></table>';
3211: $result.= '</td><td><b> or </b><input type="text" name="TEXTVAL_'.
3212: $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
3213: $partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
3214: $weight{$partid}.' (problem weight)</td>'."\n";
3215: $result.= '<td><select name="SELVAL_'.$partid.'"'.
3216: 'onChange="javascript:writeRadText(\''.$partid.'\','.
3217: $weight{$partid}.')"> '.
3218: '<option selected="selected"> </option>'.
3219: '<option>excused</option>'.
3220: '<option>reset status</option></select></td>'.
3221: '<td><label><input type="checkbox" name="FORCE_'.$partid.'" /> Override "Correct"</label></td>'.&Apache::loncommon::end_data_table_row()."\n";
3222: $ctsparts++;
3223: }
3224: $result.=&Apache::loncommon::end_data_table()."\n".
3225: '<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
3226: $result.='<input type="button" value="Revert to Default" '.
3227: 'onClick="javascript:resetEntry('.$ctsparts.');" />';
3228:
3229: #table listing all the students in a section/class
3230: #header of table
3231: $result.= '<h3>Assign Grade to Specific Students in '.$sectionClass;
3232: $result.= &Apache::loncommon::start_data_table().
3233: &Apache::loncommon::start_data_table_header_row().
3234: '<th>No.</th>'.
3235: '<th>'.&nameUserString('header')."</th>\n";
3236: my (@parts) = sort(&getpartlist($symb));
3237: my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
3238: my @partids = ();
3239: foreach my $part (@parts) {
3240: my $display=&Apache::lonnet::metadata($url,$part.'.display');
3241: $display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
3242: if (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
3243: my ($partid) = &split_part_type($part);
3244: push(@partids, $partid);
3245: my $display_part=&get_display_part($partid,$symb);
3246: if ($display =~ /^Partial Credit Factor/) {
3247: $result.='<th>Score Part: '.$display_part.
3248: ' <br />(weight = '.$weight{$partid}.')</th>'."\n";
3249: next;
3250: } else {
3251: $display =~s/\[Part: \Q$partid\E\]/Part:<\/b> $display_part/;
3252: }
3253: $display =~ s|Problem Status|Grade Status<br />|;
3254: $result.='<th>'.$display.'</th>'."\n";
3255: }
3256: $result.=&Apache::loncommon::end_data_table_header_row();
3257:
3258: my %last_resets =
3259: &get_last_resets($symb,$env{'request.course.id'},\@partids);
3260:
3261: #get info for each student
3262: #list all the students - with points and grade status
3263: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
3264: my $ctr = 0;
3265: foreach (sort
3266: {
3267: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
3268: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
3269: }
3270: return $a cmp $b;
3271: } (keys(%$fullname))) {
3272: $ctr++;
3273: $result.=&viewstudentgrade($symb,$env{'request.course.id'},
3274: $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
3275: }
3276: $result.=&Apache::loncommon::end_data_table();
3277: $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
3278: $result.='<input type="button" value="Save" '.
3279: 'onClick="javascript:submit();" target="_self" /></form>'."\n";
3280: if (scalar(%$fullname) eq 0) {
3281: my $colspan=3+scalar(@parts);
3282: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3283: my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
3284: $result='<span class="LC_warning">'.
3285: &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade',
3286: $section_display, $stu_status).
3287: '</span>';
3288: }
3289: $result.=&show_grading_menu_form($symb);
3290: return $result;
3291: }
3292:
3293: #--- call by previous routine to display each student
3294: sub viewstudentgrade {
3295: my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
3296: my ($uname,$udom) = split(/:/,$student);
3297: my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
3298: my %aggregates = ();
3299: my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
3300: '<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
3301: "\n".$ctr.' </td><td> '.
3302: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
3303: '\');" target="_self">'.$fullname.'</a> '.
3304: '<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
3305: $student=~s/:/_/; # colon doen't work in javascript for names
3306: foreach my $apart (@$parts) {
3307: my ($part,$type) = &split_part_type($apart);
3308: my $score=$record{"resource.$part.$type"};
3309: $result.='<td align="center">';
3310: my ($aggtries,$totaltries);
3311: unless (exists($aggregates{$part})) {
3312: $totaltries = $record{'resource.'.$part.'.tries'};
3313:
3314: $aggtries = $totaltries;
3315: if ($$last_resets{$part}) {
3316: $aggtries = &get_num_tries(\%record,$$last_resets{$part},
3317: $part);
3318: }
3319: $result.='<input type="hidden" name="'.
3320: 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
3321: $result.='<input type="hidden" name="'.
3322: 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
3323: $aggregates{$part} = 1;
3324: }
3325: if ($type eq 'awarded') {
3326: my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
3327: $result.='<input type="hidden" name="'.
3328: 'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
3329: $result.='<input type="text" name="'.
3330: 'GD_'.$student.'_'.$part.'_awarded" '.
3331: 'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
3332: '\')" value="'.$pts.'" size="4" /></td>'."\n";
3333: } elsif ($type eq 'solved') {
3334: my ($status,$foo)=split(/_/,$score,2);
3335: $status = 'nothing' if ($status eq '');
3336: $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
3337: $part.'_solved_s" value="'.$status.'" />'."\n";
3338: $result.=' <select name="'.
3339: 'GD_'.$student.'_'.$part.'_solved" '.
3340: 'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
3341: $result.= (($status eq 'excused') ? '<option> </option><option selected="selected">excused</option>'
3342: : '<option selected="selected"> </option><option>excused</option>')."\n";
3343: $result.='<option>reset status</option>';
3344: $result.="</select> </td>\n";
3345: } else {
3346: $result.='<input type="hidden" name="'.
3347: 'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
3348: "\n";
3349: $result.='<input type="text" name="'.
3350: 'GD_'.$student.'_'.$part.'_'.$type.'" '.
3351: 'value="'.$score.'" size="4" /></td>'."\n";
3352: }
3353: }
3354: $result.=&Apache::loncommon::end_data_table_row();
3355: return $result;
3356: }
3357:
3358: #--- change scores for all the students in a section/class
3359: # record does not get update if unchanged
3360: sub editgrades {
3361: my ($request) = @_;
3362:
3363: my $symb=&get_symb($request);
3364: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3365: my $title='<h2>'.&mt('Current Grade Status').'</h2>';
3366: $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
3367: $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
3368:
3369: my $result= &Apache::loncommon::start_data_table().
3370: &Apache::loncommon::start_data_table_header_row().
3371: '<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
3372: '<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
3373: my %scoreptr = (
3374: 'correct' =>'correct_by_override',
3375: 'incorrect'=>'incorrect_by_override',
3376: 'excused' =>'excused',
3377: 'ungraded' =>'ungraded_attempted',
3378: 'nothing' => '',
3379: );
3380: my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
3381:
3382: my (@partid);
3383: my %weight = ();
3384: my %columns = ();
3385: my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
3386:
3387: my (@parts) = sort(&getpartlist($symb));
3388: my $header;
3389: while ($ctr < $env{'form.totalparts'}) {
3390: my $partid = $env{'form.partid_'.$ctr};
3391: push @partid,$partid;
3392: $weight{$partid} = $env{'form.weight_'.$partid};
3393: $ctr++;
3394: }
3395: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3396: foreach my $partid (@partid) {
3397: $header .= '<th align="center">'.&mt('Old Score').'</th>'.
3398: '<th align="center">'.&mt('New Score').'</th>';
3399: $columns{$partid}=2;
3400: foreach my $stores (@parts) {
3401: my ($part,$type) = &split_part_type($stores);
3402: if ($part !~ m/^\Q$partid\E/) { next;}
3403: if ($type eq 'awarded' || $type eq 'solved') { next; }
3404: my $display=&Apache::lonnet::metadata($url,$stores.'.display');
3405: $display =~ s/\[Part: (\w)+\]//;
3406: $display =~ s/Number of Attempts/Tries/;
3407: $header .= '<th align="center">'.&mt('Old '.$display).'</th>'.
3408: '<th align="center">'.&mt('New '.$display).'</th>';
3409: $columns{$partid}+=2;
3410: }
3411: }
3412: foreach my $partid (@partid) {
3413: my $display_part=&get_display_part($partid,$symb);
3414: $result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
3415: &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
3416: '</th>';
3417:
3418: }
3419: $result .= &Apache::loncommon::end_data_table_header_row().
3420: &Apache::loncommon::start_data_table_header_row().
3421: $header.
3422: &Apache::loncommon::end_data_table_header_row();
3423: my @noupdate;
3424: my ($updateCtr,$noupdateCtr) = (1,1);
3425: for ($i=0; $i<$env{'form.total'}; $i++) {
3426: my $line;
3427: my $user = $env{'form.ctr'.$i};
3428: my ($uname,$udom)=split(/:/,$user);
3429: my %newrecord;
3430: my $updateflag = 0;
3431: $line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
3432: my $usec=$classlist->{"$uname:$udom"}[5];
3433: if (!&canmodify($usec)) {
3434: my $numcols=scalar(@partid)*4+2;
3435: push(@noupdate,
3436: $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
3437: &mt('Not allowed to modify student')."</span></td></tr>");
3438: next;
3439: }
3440: my %aggregate = ();
3441: my $aggregateflag = 0;
3442: $user=~s/:/_/; # colon doen't work in javascript for names
3443: foreach (@partid) {
3444: my $old_aw = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
3445: my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
3446: my $old_part = $old_aw eq '' ? '' : $old_part_pcr;
3447: my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
3448: my $awarded = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
3449: my $pcr = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
3450: my $partial = $awarded eq '' ? '' : $pcr;
3451: my $score;
3452: if ($partial eq '') {
3453: $score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
3454: } elsif ($partial > 0) {
3455: $score = 'correct_by_override';
3456: } elsif ($partial == 0) {
3457: $score = 'incorrect_by_override';
3458: }
3459: my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
3460: $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
3461:
3462: $newrecord{'resource.'.$_.'.regrader'}=
3463: "$env{'user.name'}:$env{'user.domain'}";
3464: if ($dropMenu eq 'reset status' &&
3465: $old_score ne '') { # ignore if no previous attempts => nothing to reset
3466: $newrecord{'resource.'.$_.'.tries'} = '';
3467: $newrecord{'resource.'.$_.'.solved'} = '';
3468: $newrecord{'resource.'.$_.'.award'} = '';
3469: $newrecord{'resource.'.$_.'.awarded'} = '';
3470: $updateflag = 1;
3471: if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
3472: my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
3473: my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
3474: my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
3475: &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
3476: $aggregateflag = 1;
3477: }
3478: } elsif (!($old_part eq $partial && $old_score eq $score)) {
3479: $updateflag = 1;
3480: $newrecord{'resource.'.$_.'.awarded'} = $partial if $partial ne '';
3481: $newrecord{'resource.'.$_.'.solved'} = $score;
3482: $rec_update++;
3483: }
3484:
3485: $line .= '<td align="center">'.$old_aw.' </td>'.
3486: '<td align="center">'.$awarded.
3487: ($score eq 'excused' ? $score : '').' </td>';
3488:
3489:
3490: my $partid=$_;
3491: foreach my $stores (@parts) {
3492: my ($part,$type) = &split_part_type($stores);
3493: if ($part !~ m/^\Q$partid\E/) { next;}
3494: if ($type eq 'awarded' || $type eq 'solved') { next; }
3495: my $old_aw = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
3496: my $awarded = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
3497: if ($awarded ne '' && $awarded ne $old_aw) {
3498: $newrecord{'resource.'.$part.'.'.$type}= $awarded;
3499: $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
3500: $updateflag=1;
3501: }
3502: $line .= '<td align="center">'.$old_aw.' </td>'.
3503: '<td align="center">'.$awarded.' </td>';
3504: }
3505: }
3506: $line.="\n";
3507:
3508: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3509: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3510:
3511: if ($updateflag) {
3512: $count++;
3513: &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
3514: $udom,$uname);
3515:
3516: if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
3517: $cnum,$udom,$uname)) {
3518: # need to figure out if should be in queue.
3519: my %record =
3520: &Apache::lonnet::restore($symb,$env{'request.course.id'},
3521: $udom,$uname);
3522: my $all_graded = 1;
3523: my $none_graded = 1;
3524: foreach my $part (@parts) {
3525: if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
3526: $all_graded = 0;
3527: } else {
3528: $none_graded = 0;
3529: }
3530: }
3531:
3532: if ($all_graded || $none_graded) {
3533: &Apache::bridgetask::remove_from_queue('gradingqueue',
3534: $symb,$cdom,$cnum,
3535: $udom,$uname);
3536: }
3537: }
3538:
3539: $result.=&Apache::loncommon::start_data_table_row().
3540: '<td align="right"> '.$updateCtr.' </td>'.$line.
3541: &Apache::loncommon::end_data_table_row();
3542: $updateCtr++;
3543: } else {
3544: push(@noupdate,
3545: '<td align="right"> '.$noupdateCtr.' </td>'.$line);
3546: $noupdateCtr++;
3547: }
3548: if ($aggregateflag) {
3549: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
3550: $cdom,$cnum);
3551: }
3552: }
3553: if (@noupdate) {
3554: # my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
3555: my $numcols=scalar(@partid)*4+2;
3556: $result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
3557: '<td align="center" colspan="'.$numcols.'">'.
3558: &mt('No Changes Occurred For the Students Below').
3559: '</td>'.
3560: &Apache::loncommon::end_data_table_row();
3561: foreach my $line (@noupdate) {
3562: $result.=
3563: &Apache::loncommon::start_data_table_row().
3564: $line.
3565: &Apache::loncommon::end_data_table_row();
3566: }
3567: }
3568: $result .= &Apache::loncommon::end_data_table().
3569: &show_grading_menu_form($symb);
3570: my $msg = '<p><b>'.
3571: &mt('Number of records updated = [_1] for [quant,_2,student].',
3572: $rec_update,$count).'</b><br />'.
3573: '<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
3574: '</b></p>';
3575: return $title.$msg.$result;
3576: }
3577:
3578: sub split_part_type {
3579: my ($partstr) = @_;
3580: my ($temp,@allparts)=split(/_/,$partstr);
3581: my $type=pop(@allparts);
3582: my $part=join('_',@allparts);
3583: return ($part,$type);
3584: }
3585:
3586: #------------- end of section for handling grading by section/class ---------
3587: #
3588: #----------------------------------------------------------------------------
3589:
3590:
3591: #----------------------------------------------------------------------------
3592: #
3593: #-------------------------- Next few routines handles grading by csv upload
3594: #
3595: #--- Javascript to handle csv upload
3596: sub csvupload_javascript_reverse_associate {
3597: my $error1=&mt('You need to specify the username or ID');
3598: my $error2=&mt('You need to specify at least one grading field');
3599: return(<<ENDPICK);
3600: function verify(vf) {
3601: var foundsomething=0;
3602: var founduname=0;
3603: var foundID=0;
3604: for (i=0;i<=vf.nfields.value;i++) {
3605: tw=eval('vf.f'+i+'.selectedIndex');
3606: if (i==0 && tw!=0) { foundID=1; }
3607: if (i==1 && tw!=0) { founduname=1; }
3608: if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
3609: }
3610: if (founduname==0 && foundID==0) {
3611: alert('$error1');
3612: return;
3613: }
3614: if (foundsomething==0) {
3615: alert('$error2');
3616: return;
3617: }
3618: vf.submit();
3619: }
3620: function flip(vf,tf) {
3621: var nw=eval('vf.f'+tf+'.selectedIndex');
3622: var i;
3623: for (i=0;i<=vf.nfields.value;i++) {
3624: //can not pick the same destination field for both name and domain
3625: if (((i ==0)||(i ==1)) &&
3626: ((tf==0)||(tf==1)) &&
3627: (i!=tf) &&
3628: (eval('vf.f'+i+'.selectedIndex')==nw)) {
3629: eval('vf.f'+i+'.selectedIndex=0;')
3630: }
3631: }
3632: }
3633: ENDPICK
3634: }
3635:
3636: sub csvupload_javascript_forward_associate {
3637: my $error1=&mt('You need to specify the username or ID');
3638: my $error2=&mt('You need to specify at least one grading field');
3639: return(<<ENDPICK);
3640: function verify(vf) {
3641: var foundsomething=0;
3642: var founduname=0;
3643: var foundID=0;
3644: for (i=0;i<=vf.nfields.value;i++) {
3645: tw=eval('vf.f'+i+'.selectedIndex');
3646: if (tw==1) { foundID=1; }
3647: if (tw==2) { founduname=1; }
3648: if (tw>3) { foundsomething=1; }
3649: }
3650: if (founduname==0 && foundID==0) {
3651: alert('$error1');
3652: return;
3653: }
3654: if (foundsomething==0) {
3655: alert('$error2');
3656: return;
3657: }
3658: vf.submit();
3659: }
3660: function flip(vf,tf) {
3661: var nw=eval('vf.f'+tf+'.selectedIndex');
3662: var i;
3663: //can not pick the same destination field twice
3664: for (i=0;i<=vf.nfields.value;i++) {
3665: if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
3666: eval('vf.f'+i+'.selectedIndex=0;')
3667: }
3668: }
3669: }
3670: ENDPICK
3671: }
3672:
3673: sub csvuploadmap_header {
3674: my ($request,$symb,$datatoken,$distotal)= @_;
3675: my $javascript;
3676: if ($env{'form.upfile_associate'} eq 'reverse') {
3677: $javascript=&csvupload_javascript_reverse_associate();
3678: } else {
3679: $javascript=&csvupload_javascript_forward_associate();
3680: }
3681:
3682: my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
3683: my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
3684: my $ignore=&mt('Ignore First Line');
3685: $symb = &Apache::lonenc::check_encrypt($symb);
3686: $request->print(<<ENDPICK);
3687: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3688: <h3><span class="LC_info">Uploading Class Grades</span></h3>
3689: $result
3690: <hr />
3691: <h3>Identify fields</h3>
3692: Total number of records found in file: $distotal <hr />
3693: Enter as many fields as you can. The system will inform you and bring you back
3694: to this page if the data selected is insufficient to run your class.<hr />
3695: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
3696: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
3697: <input type="hidden" name="associate" value="" />
3698: <input type="hidden" name="phase" value="three" />
3699: <input type="hidden" name="datatoken" value="$datatoken" />
3700: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
3701: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
3702: <input type="hidden" name="upfile_associate"
3703: value="$env{'form.upfile_associate'}" />
3704: <input type="hidden" name="symb" value="$symb" />
3705: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
3706: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
3707: <input type="hidden" name="command" value="csvuploadoptions" />
3708: <hr />
3709: <script type="text/javascript" language="Javascript">
3710: $javascript
3711: </script>
3712: ENDPICK
3713: return '';
3714:
3715: }
3716:
3717: sub csvupload_fields {
3718: my ($symb) = @_;
3719: my (@parts) = &getpartlist($symb);
3720: my @fields=(['ID','Student ID'],
3721: ['username','Student Username'],
3722: ['domain','Student Domain']);
3723: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3724: foreach my $part (sort(@parts)) {
3725: my @datum;
3726: my $display=&Apache::lonnet::metadata($url,$part.'.display');
3727: my $name=$part;
3728: if (!$display) { $display = $name; }
3729: @datum=($name,$display);
3730: if ($name=~/^stores_(.*)_awarded/) {
3731: push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
3732: }
3733: push(@fields,\@datum);
3734: }
3735: return (@fields);
3736: }
3737:
3738: sub csvuploadmap_footer {
3739: my ($request,$i,$keyfields) =@_;
3740: $request->print(<<ENDPICK);
3741: </table>
3742: <input type="hidden" name="nfields" value="$i" />
3743: <input type="hidden" name="keyfields" value="$keyfields" />
3744: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
3745: </form>
3746: ENDPICK
3747: }
3748:
3749: sub checkforfile_js {
3750: my $result =<<CSVFORMJS;
3751: <script type="text/javascript" language="javascript">
3752: function checkUpload(formname) {
3753: if (formname.upfile.value == "") {
3754: alert("Please use the browse button to select a file from your local directory.");
3755: return false;
3756: }
3757: formname.submit();
3758: }
3759: </script>
3760: CSVFORMJS
3761: return $result;
3762: }
3763:
3764: sub upcsvScores_form {
3765: my ($request) = shift;
3766: my ($symb)=&get_symb($request);
3767: if (!$symb) {return '';}
3768: my $result=&checkforfile_js();
3769: $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
3770: my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
3771: $result.=$table;
3772: $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
3773: $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
3774: $result.=' <b>'.&mt('Specify a file containing the class scores for current resource').
3775: '.</b></td></tr>'."\n";
3776: $result.='<tr bgcolor=#ffffe6><td>'."\n";
3777: my $upload=&mt("Upload Scores");
3778: my $upfile_select=&Apache::loncommon::upfile_select_html();
3779: my $ignore=&mt('Ignore First Line');
3780: $symb = &Apache::lonenc::check_encrypt($symb);
3781: $result.=<<ENDUPFORM;
3782: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3783: <input type="hidden" name="symb" value="$symb" />
3784: <input type="hidden" name="command" value="csvuploadmap" />
3785: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
3786: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
3787: $upfile_select
3788: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
3789: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
3790: </form>
3791: ENDUPFORM
3792: $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
3793: &mt("How do I create a CSV file from a spreadsheet"))
3794: .'</td></tr></table>'."\n";
3795: $result.='</td></tr></table><br /><br />'."\n";
3796: $result.=&show_grading_menu_form($symb);
3797: return $result;
3798: }
3799:
3800:
3801: sub csvuploadmap {
3802: my ($request)= @_;
3803: my ($symb)=&get_symb($request);
3804: if (!$symb) {return '';}
3805:
3806: my $datatoken;
3807: if (!$env{'form.datatoken'}) {
3808: $datatoken=&Apache::loncommon::upfile_store($request);
3809: } else {
3810: $datatoken=$env{'form.datatoken'};
3811: &Apache::loncommon::load_tmp_file($request);
3812: }
3813: my @records=&Apache::loncommon::upfile_record_sep();
3814: if ($env{'form.noFirstLine'}) { shift(@records); }
3815: &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
3816: my ($i,$keyfields);
3817: if (@records) {
3818: my @fields=&csvupload_fields($symb);
3819:
3820: if ($env{'form.upfile_associate'} eq 'reverse') {
3821: &Apache::loncommon::csv_print_samples($request,\@records);
3822: $i=&Apache::loncommon::csv_print_select_table($request,\@records,
3823: \@fields);
3824: foreach (@fields) { $keyfields.=$_->[0].','; }
3825: chop($keyfields);
3826: } else {
3827: unshift(@fields,['none','']);
3828: $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
3829: \@fields);
3830: foreach my $rec (@records) {
3831: my %temp = &Apache::loncommon::record_sep($rec);
3832: if (%temp) {
3833: $keyfields=join(',',sort(keys(%temp)));
3834: last;
3835: }
3836: }
3837: }
3838: }
3839: &csvuploadmap_footer($request,$i,$keyfields);
3840: $request->print(&show_grading_menu_form($symb));
3841:
3842: return '';
3843: }
3844:
3845: sub csvuploadoptions {
3846: my ($request)= @_;
3847: my ($symb)=&get_symb($request);
3848: my $checked=(($env{'form.noFirstLine'})?'1':'0');
3849: my $ignore=&mt('Ignore First Line');
3850: $request->print(<<ENDPICK);
3851: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3852: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
3853: <input type="hidden" name="command" value="csvuploadassign" />
3854: <!--
3855: <p>
3856: <label>
3857: <input type="checkbox" name="show_full_results" />
3858: Show a table of all changes
3859: </label>
3860: </p>
3861: -->
3862: <p>
3863: <label>
3864: <input type="checkbox" name="overwite_scores" checked="checked" />
3865: Overwrite any existing score
3866: </label>
3867: </p>
3868: ENDPICK
3869: my %fields=&get_fields();
3870: if (!defined($fields{'domain'})) {
3871: my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
3872: $request->print("\n<p> Users are in domain: ".$domform."</p>\n");
3873: }
3874: foreach my $key (sort(keys(%env))) {
3875: if ($key !~ /^form\.(.*)$/) { next; }
3876: my $cleankey=$1;
3877: if ($cleankey eq 'command') { next; }
3878: $request->print('<input type="hidden" name="'.$cleankey.
3879: '" value="'.$env{$key}.'" />'."\n");
3880: }
3881: # FIXME do a check for any duplicated user ids...
3882: # FIXME do a check for any invalid user ids?...
3883: $request->print('<input type="submit" value="Assign Grades" /><br />
3884: <hr /></form>'."\n");
3885: $request->print(&show_grading_menu_form($symb));
3886: return '';
3887: }
3888:
3889: sub get_fields {
3890: my %fields;
3891: my @keyfields = split(/\,/,$env{'form.keyfields'});
3892: for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
3893: if ($env{'form.upfile_associate'} eq 'reverse') {
3894: if ($env{'form.f'.$i} ne 'none') {
3895: $fields{$keyfields[$i]}=$env{'form.f'.$i};
3896: }
3897: } else {
3898: if ($env{'form.f'.$i} ne 'none') {
3899: $fields{$env{'form.f'.$i}}=$keyfields[$i];
3900: }
3901: }
3902: }
3903: return %fields;
3904: }
3905:
3906: sub csvuploadassign {
3907: my ($request)= @_;
3908: my ($symb)=&get_symb($request);
3909: if (!$symb) {return '';}
3910: my $error_msg = '';
3911: &Apache::loncommon::load_tmp_file($request);
3912: my @gradedata = &Apache::loncommon::upfile_record_sep();
3913: if ($env{'form.noFirstLine'}) { shift(@gradedata); }
3914: my %fields=&get_fields();
3915: $request->print('<h3>Assigning Grades</h3>');
3916: my $courseid=$env{'request.course.id'};
3917: my ($classlist) = &getclasslist('all',0);
3918: my @notallowed;
3919: my @skipped;
3920: my $countdone=0;
3921: foreach my $grade (@gradedata) {
3922: my %entries=&Apache::loncommon::record_sep($grade);
3923: my $domain;
3924: if ($entries{$fields{'domain'}}) {
3925: $domain=$entries{$fields{'domain'}};
3926: } else {
3927: $domain=$env{'form.default_domain'};
3928: }
3929: $domain=~s/\s//g;
3930: my $username=$entries{$fields{'username'}};
3931: $username=~s/\s//g;
3932: if (!$username) {
3933: my $id=$entries{$fields{'ID'}};
3934: $id=~s/\s//g;
3935: my %ids=&Apache::lonnet::idget($domain,$id);
3936: $username=$ids{$id};
3937: }
3938: if (!exists($$classlist{"$username:$domain"})) {
3939: my $id=$entries{$fields{'ID'}};
3940: $id=~s/\s//g;
3941: if ($id) {
3942: push(@skipped,"$id:$domain");
3943: } else {
3944: push(@skipped,"$username:$domain");
3945: }
3946: next;
3947: }
3948: my $usec=$classlist->{"$username:$domain"}[5];
3949: if (!&canmodify($usec)) {
3950: push(@notallowed,"$username:$domain");
3951: next;
3952: }
3953: my %points;
3954: my %grades;
3955: foreach my $dest (keys(%fields)) {
3956: if ($dest eq 'ID' || $dest eq 'username' ||
3957: $dest eq 'domain') { next; }
3958: if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
3959: if ($dest=~/stores_(.*)_points/) {
3960: my $part=$1;
3961: my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
3962: $symb,$domain,$username);
3963: if ($wgt) {
3964: $entries{$fields{$dest}}=~s/\s//g;
3965: my $pcr=$entries{$fields{$dest}} / $wgt;
3966: my $award=($pcr == 0) ? 'incorrect_by_override'
3967: : 'correct_by_override';
3968: $grades{"resource.$part.awarded"}=$pcr;
3969: $grades{"resource.$part.solved"}=$award;
3970: $points{$part}=1;
3971: } else {
3972: $error_msg = "<br />" .
3973: &mt("Some point values were assigned"
3974: ." for problems with a weight "
3975: ."of zero. These values were "
3976: ."ignored.");
3977: }
3978: } else {
3979: if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
3980: if ($dest=~/stores_(.*)_solved/) { if ($points{$1}) {next;} }
3981: my $store_key=$dest;
3982: $store_key=~s/^stores/resource/;
3983: $store_key=~s/_/\./g;
3984: $grades{$store_key}=$entries{$fields{$dest}};
3985: }
3986: }
3987: if (! %grades) { push(@skipped,"$username:$domain no data to save"); }
3988: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
3989: my $result=&Apache::lonnet::cstore(\%grades,$symb,
3990: $env{'request.course.id'},
3991: $domain,$username);
3992: if ($result eq 'ok') {
3993: $request->print('.');
3994: } else {
3995: $request->print("<p>
3996: <span class=\"LC_error\">
3997: Failed to save student $username:$domain.
3998: Message when trying to save was ($result)
3999: </span>
4000: </p>" );
4001: }
4002: $request->rflush();
4003: $countdone++;
4004: }
4005: $request->print("<br />Saved $countdone students\n");
4006: if (@skipped) {
4007: $request->print('<p><h4><b>Skipped Students</b></h4></p>');
4008: foreach my $student (@skipped) { $request->print("$student<br />\n"); }
4009: }
4010: if (@notallowed) {
4011: $request->print('<p><span class="LC_error">Students Not Allowed to Modify</span></p>');
4012: foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
4013: }
4014: $request->print("<br />\n");
4015: $request->print(&show_grading_menu_form($symb));
4016: return $error_msg;
4017: }
4018: #------------- end of section for handling csv file upload ---------
4019: #
4020: #-------------------------------------------------------------------
4021: #
4022: #-------------- Next few routines handle grading by page/sequence
4023: #
4024: #--- Select a page/sequence and a student to grade
4025: sub pickStudentPage {
4026: my ($request) = shift;
4027:
4028: $request->print(<<LISTJAVASCRIPT);
4029: <script type="text/javascript" language="javascript">
4030:
4031: function checkPickOne(formname) {
4032: if (radioSelection(formname.student) == null) {
4033: alert("Please select the student you wish to grade.");
4034: return;
4035: }
4036: ptr = pullDownSelection(formname.selectpage);
4037: formname.page.value = formname["page"+ptr].value;
4038: formname.title.value = formname["title"+ptr].value;
4039: formname.submit();
4040: }
4041:
4042: </script>
4043: LISTJAVASCRIPT
4044: &commonJSfunctions($request);
4045: my ($symb) = &get_symb($request);
4046: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4047: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4048: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4049:
4050: my $result='<h3><span class="LC_info"> '.
4051: 'Manual Grading by Page or Sequence</span></h3>';
4052:
4053: $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
4054: $result.=' <b>Problems from:</b> <select name="selectpage">'."\n";
4055: my ($titles,$symbx) = &getSymbMap();
4056: my ($curpage) =&Apache::lonnet::decode_symb($symb);
4057: # my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb);
4058: # my $type=($curpage =~ /\.(page|sequence)/);
4059: my $ctr=0;
4060: foreach (@$titles) {
4061: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4062: $result.='<option value="'.$ctr.'" '.
4063: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
4064: '>'.$showtitle.'</option>'."\n";
4065: $ctr++;
4066: }
4067: $result.= '</select>'."<br />\n";
4068: $ctr=0;
4069: foreach (@$titles) {
4070: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4071: $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
4072: $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
4073: $ctr++;
4074: }
4075: $result.='<input type="hidden" name="page" />'."\n".
4076: '<input type="hidden" name="title" />'."\n";
4077:
4078: $result.=' <b>View Problems Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
4079: '<label><input type="radio" name="vProb" value="yes" /> yes </label>'."<br />\n";
4080:
4081: $result.=' <b>Submission Details: </b>'.
4082: '<label><input type="radio" name="lastSub" value="none" /> none</label>'."\n".
4083: '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> by dates and submissions</label>'."\n".
4084: '<label><input type="radio" name="lastSub" value="all" /> all details</label>'."\n";
4085:
4086: $result.=&build_section_inputs();
4087: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
4088: $result.='<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
4089: '<input type="hidden" name="command" value="displayPage" />'."\n".
4090: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
4091: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
4092:
4093: $result.=' <b>'.&mt('Use CODE:').' </b>'.
4094: '<input type="text" name="CODE" value="" /><br />'."\n";
4095:
4096: $result.=' <input type="button" '.
4097: 'onClick="javascript:checkPickOne(this.form);"value="Next->" /><br />'."\n";
4098:
4099: $request->print($result);
4100:
4101: my $studentTable.=' <b>Select a student you wish to grade and then click on the Next button.</b><br />'.
4102: &Apache::loncommon::start_data_table().
4103: &Apache::loncommon::start_data_table_header_row().
4104: '<th align="right"> No.</th>'.
4105: '<th>'.&nameUserString('header').'</th>'.
4106: '<th align="right"> No.</th>'.
4107: '<th>'.&nameUserString('header').'</th>'.
4108: &Apache::loncommon::end_data_table_header_row();
4109:
4110: my (undef,undef,$fullname) = &getclasslist($getsec,'1');
4111: my $ptr = 1;
4112: foreach my $student (sort
4113: {
4114: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
4115: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
4116: }
4117: return $a cmp $b;
4118: } (keys(%$fullname))) {
4119: my ($uname,$udom) = split(/:/,$student);
4120: $studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
4121: : '</td>');
4122: $studentTable.='<td align="right">'.$ptr.' </td>';
4123: $studentTable.='<td> <label><input type="radio" name="student" value="'.$student.'" /> '
4124: .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
4125: $studentTable.=
4126: ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row()
4127: : '');
4128: $ptr++;
4129: }
4130: if ($ptr%2 == 0) {
4131: $studentTable.='</td><td> </td><td> </td>'.
4132: &Apache::loncommon::end_data_table_row();
4133: }
4134: $studentTable.=&Apache::loncommon::end_data_table()."\n";
4135: $studentTable.='<input type="button" '.
4136: 'onClick="javascript:checkPickOne(this.form);"value="Next->" /></form>'."\n";
4137:
4138: $studentTable.=&show_grading_menu_form($symb);
4139: $request->print($studentTable);
4140:
4141: return '';
4142: }
4143:
4144: sub getSymbMap {
4145: my $navmap = Apache::lonnavmaps::navmap->new();
4146:
4147: my %symbx = ();
4148: my @titles = ();
4149: my $minder = 0;
4150:
4151: # Gather every sequence that has problems.
4152: my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
4153: 1,0,1);
4154: for my $sequence ($navmap->getById('0.0'), @sequences) {
4155: if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
4156: my $title = $minder.'.'.
4157: &HTML::Entities::encode($sequence->compTitle(),'"\'&');
4158: push(@titles, $title); # minder in case two titles are identical
4159: $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
4160: $minder++;
4161: }
4162: }
4163: return \@titles,\%symbx;
4164: }
4165:
4166: #
4167: #--- Displays a page/sequence w/wo problems, w/wo submissions
4168: sub displayPage {
4169: my ($request) = shift;
4170:
4171: my ($symb) = &get_symb($request);
4172: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4173: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4174: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4175: my $pageTitle = $env{'form.page'};
4176: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
4177: my ($uname,$udom) = split(/:/,$env{'form.student'});
4178: my $usec=$classlist->{$env{'form.student'}}[5];
4179:
4180: #need to make sure we have the correct data for later EXT calls,
4181: #thus invalidate the cache
4182: &Apache::lonnet::devalidatecourseresdata(
4183: $env{'course.'.$env{'request.course.id'}.'.num'},
4184: $env{'course.'.$env{'request.course.id'}.'.domain'});
4185: &Apache::lonnet::clear_EXT_cache_status();
4186:
4187: if (!&canview($usec)) {
4188: $request->print('<span class="LC_warning">Unable to view requested student.('.$env{'form.student'}.')</span>');
4189: $request->print(&show_grading_menu_form($symb));
4190: return;
4191: }
4192: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
4193: $result.='<h3> Student: '.&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom).
4194: '</h3>'."\n";
4195: if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
4196: $result.='<h3> CODE: '.$env{'form.CODE'}.'</h3>'."\n";
4197: } else {
4198: delete($env{'form.CODE'});
4199: }
4200: &sub_page_js($request);
4201: $request->print($result);
4202:
4203: my $navmap = Apache::lonnavmaps::navmap->new();
4204: my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
4205: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
4206: if (!$map) {
4207: $request->print('<span class="LC_warning">Unable to view requested sequence. ('.$resUrl.')</span>');
4208: $request->print(&show_grading_menu_form($symb));
4209: return;
4210: }
4211: my $iterator = $navmap->getIterator($map->map_start(),
4212: $map->map_finish());
4213:
4214: my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
4215: '<input type="hidden" name="command" value="gradeByPage" />'."\n".
4216: '<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
4217: '<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
4218: '<input type="hidden" name="page" value="'.$pageTitle.'" />'."\n".
4219: '<input type="hidden" name="title" value="'.$env{'form.title'}.'" />'."\n".
4220: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
4221: '<input type="hidden" name="overRideScore" value="no" />'."\n".
4222: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
4223:
4224: if (defined($env{'form.CODE'})) {
4225: $studentTable.=
4226: '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
4227: }
4228: my $checkIcon = '<img alt="'.&mt('Check Mark').
4229: '" src="'.$request->dir_config('lonIconsURL').
4230: '/check.gif" height="16" border="0" />';
4231:
4232: $studentTable.=' <b>Note:</b> Problems graded correct by the computer are marked with a '.$checkIcon.
4233: ' symbol.'."\n".
4234: &Apache::loncommon::start_data_table().
4235: &Apache::loncommon::start_data_table_header_row().
4236: '<th align="center"> Prob. </th>'.
4237: '<th> '.($env{'form.vProb'} eq 'no' ? 'Title' : 'Problem Text').'/Grade</th>'.
4238: &Apache::loncommon::end_data_table_header_row();
4239:
4240: &Apache::lonxml::clear_problem_counter();
4241: my ($depth,$question,$prob) = (1,1,1);
4242: $iterator->next(); # skip the first BEGIN_MAP
4243: my $curRes = $iterator->next(); # for "current resource"
4244: while ($depth > 0) {
4245: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
4246: if($curRes == $iterator->END_MAP) { $depth--; }
4247:
4248: if (ref($curRes) && $curRes->is_problem()) {
4249: my $parts = $curRes->parts();
4250: my $title = $curRes->compTitle();
4251: my $symbx = $curRes->symb();
4252: $studentTable.=
4253: &Apache::loncommon::start_data_table_row().
4254: '<td align="center" valign="top" >'.$prob.
4255: (scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).' parts)').'</td>';
4256: $studentTable.='<td valign="top">';
4257: my %form = ('CODE' => $env{'form.CODE'},);
4258: if ($env{'form.vProb'} eq 'yes' ) {
4259: $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
4260: undef,'both',\%form);
4261: } else {
4262: my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
4263: $companswer =~ s|<form(.*?)>||g;
4264: $companswer =~ s|</form>||g;
4265: # while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
4266: # $companswer =~ s/$1/ /ms;
4267: # $request->print('match='.$1."<br />\n");
4268: # }
4269: # $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
4270: $studentTable.=' <b>'.$title.'</b> <br /> <b>Correct answer:</b><br />'.$companswer;
4271: }
4272:
4273: my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
4274:
4275: if ($env{'form.lastSub'} eq 'datesub') {
4276: if ($record{'version'} eq '') {
4277: $studentTable.='<br /> <span class="LC_warning">No recorded submission for this problem</span><br />';
4278: } else {
4279: my %responseType = ();
4280: foreach my $partid (@{$parts}) {
4281: my @responseIds =$curRes->responseIds($partid);
4282: my @responseType =$curRes->responseType($partid);
4283: my %responseIds;
4284: for (my $i=0;$i<=$#responseIds;$i++) {
4285: $responseIds{$responseIds[$i]}=$responseType[$i];
4286: }
4287: $responseType{$partid} = \%responseIds;
4288: }
4289: $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
4290:
4291: }
4292: } elsif ($env{'form.lastSub'} eq 'all') {
4293: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
4294: $studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
4295: $env{'request.course.id'},
4296: '','.submission');
4297:
4298: }
4299: if (&canmodify($usec)) {
4300: foreach my $partid (@{$parts}) {
4301: $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
4302: $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
4303: $question++;
4304: }
4305: $prob++;
4306: }
4307: $studentTable.='</td></tr>';
4308:
4309: }
4310: $curRes = $iterator->next();
4311: }
4312:
4313: $studentTable.='</table></td></tr></table>'."\n".
4314: '<input type="button" value="Save" '.
4315: 'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
4316: '</form>'."\n";
4317: $studentTable.=&show_grading_menu_form($symb);
4318: $request->print($studentTable);
4319:
4320: return '';
4321: }
4322:
4323: sub displaySubByDates {
4324: my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
4325: my $isCODE=0;
4326: my $isTask = ($symb =~/\.task$/);
4327: if (exists($record->{'resource.CODE'})) { $isCODE=1; }
4328: my $studentTable=&Apache::loncommon::start_data_table().
4329: &Apache::loncommon::start_data_table_header_row().
4330: '<th>'.&mt('Date/Time').'</th>'.
4331: ($isCODE?'<th>'.&mt('CODE').'</th>':'').
4332: '<th>'.&mt('Submission').'</th>'.
4333: '<th>'.&mt('Status').'</th>'.
4334: &Apache::loncommon::end_data_table_header_row();
4335: my ($version);
4336: my %mark;
4337: my %orders;
4338: $mark{'correct_by_student'} = $checkIcon;
4339: if (!exists($$record{'1:timestamp'})) {
4340: return '<br /> <span class="LC_warning">'.&mt('Nothing submitted - no attempts').'</span><br />';
4341: }
4342:
4343: my $interaction;
4344: for ($version=1;$version<=$$record{'version'};$version++) {
4345: my $timestamp =
4346: &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
4347: if (exists($$record{$version.':resource.0.version'})) {
4348: $interaction = $$record{$version.':resource.0.version'};
4349: }
4350:
4351: my $where = ($isTask ? "$version:resource.$interaction"
4352: : "$version:resource");
4353: $studentTable.=&Apache::loncommon::start_data_table_row().
4354: '<td>'.$timestamp.'</td>';
4355: if ($isCODE) {
4356: $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
4357: }
4358: my @versionKeys = split(/\:/,$$record{$version.':keys'});
4359: my @displaySub = ();
4360: foreach my $partid (@{$parts}) {
4361: my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
4362: : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
4363:
4364:
4365: # next if ($$record{"$version:resource.$partid.solved"} eq '');
4366: my $display_part=&get_display_part($partid,$symb);
4367: foreach my $matchKey (@matchKey) {
4368: if (exists($$record{$version.':'.$matchKey}) &&
4369: $$record{$version.':'.$matchKey} ne '') {
4370:
4371: my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
4372: : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
4373: $displaySub[0].='<b>'.&mt('Part:').'</b> '.$display_part.' ';
4374: $displaySub[0].='<span class="LC_internal_info">('.&mt('ID').' '.
4375: $responseId.')</span> <b>';
4376: if ($$record{"$where.$partid.tries"} eq '') {
4377: $displaySub[0].=&mt('Trial not counted');
4378: } else {
4379: $displaySub[0].=&mt('Trial [_1]',
4380: $$record{"$where.$partid.tries"});
4381: }
4382: my $responseType=($isTask ? 'Task'
4383: : $responseType->{$partid}->{$responseId});
4384: if (!exists($orders{$partid})) { $orders{$partid}={}; }
4385: if (!exists($orders{$partid}->{$responseId})) {
4386: $orders{$partid}->{$responseId}=
4387: &get_order($partid,$responseId,$symb,$uname,$udom);
4388: }
4389: $displaySub[0].='</b> '.
4390: &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
4391: }
4392: }
4393: if (exists($$record{"$where.$partid.checkedin"})) {
4394: $displaySub[1].='Checked in by '.
4395: $$record{"$where.$partid.checkedin"}.' into slot '.
4396: $$record{"$where.$partid.checkedin.slot"}.
4397: '<br />';
4398: }
4399: if (exists $$record{"$where.$partid.award"}) {
4400: $displaySub[1].='<b>Part:</b> '.$display_part.' '.
4401: lc($$record{"$where.$partid.award"}).' '.
4402: $mark{$$record{"$where.$partid.solved"}}.
4403: '<br />';
4404: }
4405: if (exists $$record{"$where.$partid.regrader"}) {
4406: $displaySub[2].=$$record{"$where.$partid.regrader"}.
4407: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
4408: } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
4409: $displaySub[2].=
4410: $$record{"$version:resource.$partid.regrader"}.
4411: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
4412: }
4413: }
4414: # needed because old essay regrader has not parts info
4415: if (exists $$record{"$version:resource.regrader"}) {
4416: $displaySub[2].=$$record{"$version:resource.regrader"};
4417: }
4418: $studentTable.='<td>'.$displaySub[0].' </td><td>'.$displaySub[1];
4419: if ($displaySub[2]) {
4420: $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
4421: }
4422: $studentTable.=' </td>'.
4423: &Apache::loncommon::end_data_table_row();
4424: }
4425: $studentTable.=&Apache::loncommon::end_data_table();
4426: return $studentTable;
4427: }
4428:
4429: sub updateGradeByPage {
4430: my ($request) = shift;
4431:
4432: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4433: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4434: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4435: my $pageTitle = $env{'form.page'};
4436: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
4437: my ($uname,$udom) = split(/:/,$env{'form.student'});
4438: my $usec=$classlist->{$env{'form.student'}}[5];
4439: if (!&canmodify($usec)) {
4440: $request->print('<span class="LC_warning">Unable to modify requested student.('.$env{'form.student'}.'</span>');
4441: $request->print(&show_grading_menu_form($env{'form.symb'}));
4442: return;
4443: }
4444: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
4445: $result.='<h3> Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
4446: '</h3>'."\n";
4447:
4448: $request->print($result);
4449:
4450: my $navmap = Apache::lonnavmaps::navmap->new();
4451: my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
4452: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
4453: if (!$map) {
4454: $request->print('<span class="LC_warning">Unable to grade requested sequence. ('.$resUrl.')</span>');
4455: my ($symb)=&get_symb($request);
4456: $request->print(&show_grading_menu_form($symb));
4457: return;
4458: }
4459: my $iterator = $navmap->getIterator($map->map_start(),
4460: $map->map_finish());
4461:
4462: my $studentTable=
4463: &Apache::loncommon::start_data_table().
4464: &Apache::loncommon::start_data_table_header_row().
4465: '<th align="center"> Prob. </th>'.
4466: '<th> Title </th>'.
4467: '<th> Previous Score </th>'.
4468: '<th> New Score </th>'.
4469: &Apache::loncommon::end_data_table_header_row();
4470:
4471: $iterator->next(); # skip the first BEGIN_MAP
4472: my $curRes = $iterator->next(); # for "current resource"
4473: my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
4474: while ($depth > 0) {
4475: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
4476: if($curRes == $iterator->END_MAP) { $depth--; }
4477:
4478: if (ref($curRes) && $curRes->is_problem()) {
4479: my $parts = $curRes->parts();
4480: my $title = $curRes->compTitle();
4481: my $symbx = $curRes->symb();
4482: $studentTable.=
4483: &Apache::loncommon::start_data_table_row().
4484: '<td align="center" valign="top" >'.$prob.
4485: (scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).' parts)').'</td>';
4486: $studentTable.='<td valign="top"> <b>'.$title.'</b> </td>';
4487:
4488: my %newrecord=();
4489: my @displayPts=();
4490: my %aggregate = ();
4491: my $aggregateflag = 0;
4492: foreach my $partid (@{$parts}) {
4493: my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
4494: my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
4495:
4496: my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ?
4497: $env{'form.WGT'.$question.'_'.$partid} : 1;
4498: my $partial = $newpts/$wgt;
4499: my $score;
4500: if ($partial > 0) {
4501: $score = 'correct_by_override';
4502: } elsif ($newpts ne '') { #empty is taken as 0
4503: $score = 'incorrect_by_override';
4504: }
4505: my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
4506: if ($dropMenu eq 'excused') {
4507: $partial = '';
4508: $score = 'excused';
4509: } elsif ($dropMenu eq 'reset status'
4510: && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
4511: $newrecord{'resource.'.$partid.'.tries'} = 0;
4512: $newrecord{'resource.'.$partid.'.solved'} = '';
4513: $newrecord{'resource.'.$partid.'.award'} = '';
4514: $newrecord{'resource.'.$partid.'.awarded'} = 0;
4515: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
4516: $changeflag++;
4517: $newpts = '';
4518:
4519: my $aggtries = $env{'form.aggtries'.$question.'_'.$partid};
4520: my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
4521: my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
4522: if ($aggtries > 0) {
4523: &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
4524: $aggregateflag = 1;
4525: }
4526: }
4527: my $display_part=&get_display_part($partid,$curRes->symb());
4528: my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
4529: $displayPts[0].=' <b>Part:</b> '.$display_part.' = '.
4530: (($oldstatus eq 'excused') ? 'excused' : $oldpts).
4531: ' <br />';
4532: $displayPts[1].=' <b>Part:</b> '.$display_part.' = '.
4533: (($score eq 'excused') ? 'excused' : $newpts).
4534: ' <br />';
4535: $question++;
4536: next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
4537:
4538: $newrecord{'resource.'.$partid.'.awarded'} = $partial if $partial ne '';
4539: $newrecord{'resource.'.$partid.'.solved'} = $score if $score ne '';
4540: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
4541: if (scalar(keys(%newrecord)) > 0);
4542:
4543: $changeflag++;
4544: }
4545: if (scalar(keys(%newrecord)) > 0) {
4546: my %record =
4547: &Apache::lonnet::restore($symbx,$env{'request.course.id'},
4548: $udom,$uname);
4549:
4550: if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
4551: $newrecord{'resource.CODE'} = $env{'form.CODE'};
4552: } elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
4553: $newrecord{'resource.CODE'} = '';
4554: }
4555: &Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
4556: $udom,$uname);
4557: %record = &Apache::lonnet::restore($symbx,
4558: $env{'request.course.id'},
4559: $udom,$uname);
4560: &check_and_remove_from_queue($parts,\%record,undef,$symbx,
4561: $cdom,$cnum,$udom,$uname);
4562: }
4563:
4564: if ($aggregateflag) {
4565: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
4566: $env{'course.'.$env{'request.course.id'}.'.domain'},
4567: $env{'course.'.$env{'request.course.id'}.'.num'});
4568: }
4569:
4570: $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
4571: '<td valign="top">'.$displayPts[1].'</td>'.
4572: &Apache::loncommon::end_data_table_row();
4573:
4574: $prob++;
4575: }
4576: $curRes = $iterator->next();
4577: }
4578:
4579: $studentTable.=&Apache::loncommon::end_data_table();
4580: $studentTable.=&show_grading_menu_form($env{'form.symb'});
4581: my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
4582: 'The scores were changed for '.
4583: $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
4584: $request->print($grademsg.$studentTable);
4585:
4586: return '';
4587: }
4588:
4589: #-------- end of section for handling grading by page/sequence ---------
4590: #
4591: #-------------------------------------------------------------------
4592:
4593: #--------------------Scantron Grading-----------------------------------
4594: #
4595: #------ start of section for handling grading by page/sequence ---------
4596:
4597: =pod
4598:
4599: =head1 Bubble sheet grading routines
4600:
4601: For this documentation:
4602:
4603: 'scanline' refers to the full line of characters
4604: from the file that we are parsing that represents one entire sheet
4605:
4606: 'bubble line' refers to the data
4607: representing the line of bubbles that are on the physical bubble sheet
4608:
4609:
4610: The overall process is that a scanned in bubble sheet data is uploaded
4611: into a course. When a user wants to grade, they select a
4612: sequence/folder of resources, a file of bubble sheet info, and pick
4613: one of the predefined configurations for what each scanline looks
4614: like.
4615:
4616: Next each scanline is checked for any errors of either 'missing
4617: bubbles' (it's an error because it may have been mis-scanned
4618: because too light bubbling), 'double bubble' (each bubble line should
4619: have no more that one letter picked), invalid or duplicated CODE,
4620: invalid student ID
4621:
4622: If the CODE option is used that determines the randomization of the
4623: homework problems, either way the student ID is looked up into a
4624: username:domain.
4625:
4626: During the validation phase the instructor can choose to skip scanlines.
4627:
4628: After the validation phase, there are now 3 bubble sheet files
4629:
4630: scantron_original_filename (unmodified original file)
4631: scantron_corrected_filename (file where the corrected information has replaced the original information)
4632: scantron_skipped_filename (contains the exact text of scanlines that where skipped)
4633:
4634: Also there is a separate hash nohist_scantrondata that contains extra
4635: correction information that isn't representable in the bubble sheet
4636: file (see &scantron_getfile() for more information)
4637:
4638: After all scanlines are either valid, marked as valid or skipped, then
4639: foreach line foreach problem in the picked sequence, an ssi request is
4640: made that simulates a user submitting their selected letter(s) against
4641: the homework problem.
4642:
4643: =over 4
4644:
4645:
4646:
4647: =item defaultFormData
4648:
4649: Returns html hidden inputs used to hold context/default values.
4650:
4651: Arguments:
4652: $symb - $symb of the current resource
4653:
4654: =cut
4655:
4656: sub defaultFormData {
4657: my ($symb)=@_;
4658: return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
4659: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
4660: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
4661: }
4662:
4663:
4664: =pod
4665:
4666: =item getSequenceDropDown
4667:
4668: Return html dropdown of possible sequences to grade
4669:
4670: Arguments:
4671: $symb - $symb of the current resource
4672:
4673: =cut
4674:
4675: sub getSequenceDropDown {
4676: my ($symb)=@_;
4677: my $result='<select name="selectpage">'."\n";
4678: my ($titles,$symbx) = &getSymbMap();
4679: my ($curpage)=&Apache::lonnet::decode_symb($symb);
4680: my $ctr=0;
4681: foreach (@$titles) {
4682: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4683: $result.='<option value="'.$$symbx{$_}.'" '.
4684: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
4685: '>'.$showtitle.'</option>'."\n";
4686: $ctr++;
4687: }
4688: $result.= '</select>';
4689: return $result;
4690: }
4691:
4692:
4693: =pod
4694:
4695: =item scantron_filenames
4696:
4697: Returns a list of the scantron files in the current course
4698:
4699: =cut
4700:
4701: sub scantron_filenames {
4702: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4703: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
4704: my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
4705: &propath($cdom,$cname));
4706: my @possiblenames;
4707: foreach my $filename (sort(@files)) {
4708: ($filename)=split(/&/,$filename);
4709: if ($filename!~/^scantron_orig_/) { next ; }
4710: $filename=~s/^scantron_orig_//;
4711: push(@possiblenames,$filename);
4712: }
4713: return @possiblenames;
4714: }
4715:
4716: =pod
4717:
4718: =item scantron_uploads
4719:
4720: Returns html drop-down list of scantron files in current course.
4721:
4722: Arguments:
4723: $file2grade - filename to set as selected in the dropdown
4724:
4725: =cut
4726:
4727: sub scantron_uploads {
4728: my ($file2grade) = @_;
4729: my $result= '<select name="scantron_selectfile">';
4730: $result.="<option></option>";
4731: foreach my $filename (sort(&scantron_filenames())) {
4732: $result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
4733: }
4734: $result.="</select>";
4735: return $result;
4736: }
4737:
4738: =pod
4739:
4740: =item scantron_scantab
4741:
4742: Returns html drop down of the scantron formats in the scantronformat.tab
4743: file.
4744:
4745: =cut
4746:
4747: sub scantron_scantab {
4748: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
4749: my $result='<select name="scantron_format">'."\n";
4750: $result.='<option></option>'."\n";
4751: foreach my $line (<$fh>) {
4752: my ($name,$descrip)=split(/:/,$line);
4753: if ($name =~ /^\#/) { next; }
4754: $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
4755: }
4756: $result.='</select>'."\n";
4757:
4758: return $result;
4759: }
4760:
4761: =pod
4762:
4763: =item scantron_CODElist
4764:
4765: Returns html drop down of the saved CODE lists from current course,
4766: generated from earlier printings.
4767:
4768: =cut
4769:
4770: sub scantron_CODElist {
4771: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4772: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4773: my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
4774: my $namechoice='<option></option>';
4775: foreach my $name (sort {uc($a) cmp uc($b)} @names) {
4776: if ($name =~ /^error: 2 /) { next; }
4777: if ($name =~ /^type\0/) { next; }
4778: $namechoice.='<option value="'.$name.'">'.$name.'</option>';
4779: }
4780: $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
4781: return $namechoice;
4782: }
4783:
4784: =pod
4785:
4786: =item scantron_CODEunique
4787:
4788: Returns the html for "Each CODE to be used once" radio.
4789:
4790: =cut
4791:
4792: sub scantron_CODEunique {
4793: my $result='<span style="white-space: nowrap;">
4794: <label><input type="radio" name="scantron_CODEunique"
4795: value="yes" checked="checked" />'.&mt('Yes').' </label>
4796: </span>
4797: <span style="white-space: nowrap;">
4798: <label><input type="radio" name="scantron_CODEunique"
4799: value="no" />'.&mt('No').' </label>
4800: </span>';
4801: return $result;
4802: }
4803:
4804: =pod
4805:
4806: =item scantron_selectphase
4807:
4808: Generates the initial screen to start the bubble sheet process.
4809: Allows for - starting a grading run.
4810: - downloading existing scan data (original, corrected
4811: or skipped info)
4812:
4813: - uploading new scan data
4814:
4815: Arguments:
4816: $r - The Apache request object
4817: $file2grade - name of the file that contain the scanned data to score
4818:
4819: =cut
4820:
4821: sub scantron_selectphase {
4822: my ($r,$file2grade) = @_;
4823: my ($symb)=&get_symb($r);
4824: if (!$symb) {return '';}
4825: my $sequence_selector=&getSequenceDropDown($symb);
4826: my $default_form_data=&defaultFormData($symb);
4827: my $grading_menu_button=&show_grading_menu_form($symb);
4828: my $file_selector=&scantron_uploads($file2grade);
4829: my $format_selector=&scantron_scantab();
4830: my $CODE_selector=&scantron_CODElist();
4831: my $CODE_unique=&scantron_CODEunique();
4832: my $result;
4833:
4834: # Chunk of form to prompt for a file to grade and how:
4835:
4836: $result.= <<SCANTRONFORM;
4837: <table width="100%" border="0">
4838: <tr>
4839: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
4840: <td bgcolor="#777777">
4841: <input type="hidden" name="command" value="scantron_warning" />
4842: $default_form_data
4843: <table width="100%" border="0">
4844: <tr bgcolor="#e6ffff">
4845: <td colspan="2">
4846: <b>Specify file and which Folder/Sequence to grade</b>
4847: </td>
4848: </tr>
4849: <tr bgcolor="#ffffe6">
4850: <td> Sequence to grade: </td><td> $sequence_selector </td>
4851: </tr>
4852: <tr bgcolor="#ffffe6">
4853: <td> Filename of scoring office file: </td><td> $file_selector </td>
4854: </tr>
4855: <tr bgcolor="#ffffe6">
4856: <td> Format of data file: </td><td> $format_selector </td>
4857: </tr>
4858: <tr bgcolor="#ffffe6">
4859: <td> Saved CODEs to validate against: </td><td> $CODE_selector</td>
4860: </tr>
4861: <tr bgcolor="#ffffe6">
4862: <td> Each CODE is only to be used once:</td><td> $CODE_unique </td>
4863: </tr>
4864: <tr bgcolor="#ffffe6">
4865: <td> Options: </td>
4866: <td>
4867: <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> Do only previously skipped records</label> <br />
4868: <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> Remove all existing corrections</label> <br />
4869: <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> Skip hidden resources when grading</label>
4870: </td>
4871: </tr>
4872: <tr bgcolor="#ffffe6">
4873: <td colspan="2">
4874: <input type="submit" value="Grading: Validate Scantron Records" />
4875: </td>
4876: </tr>
4877: </table>
4878: </td>
4879: </form>
4880: </tr>
4881: SCANTRONFORM
4882:
4883: $r->print($result);
4884:
4885: if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
4886: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
4887:
4888: # Chunk of form to prompt for a scantron file upload.
4889:
4890: $r->print(<<SCANTRONFORM);
4891: <tr>
4892: <td bgcolor="#777777">
4893: <table width="100%" border="0">
4894: <tr bgcolor="#e6ffff">
4895: <td>
4896: <b>Specify a Scantron data file to upload.</b>
4897: </td>
4898: </tr>
4899: <tr bgcolor="#ffffe6">
4900: <td>
4901: SCANTRONFORM
4902: my $default_form_data=&defaultFormData(&get_symb($r,1));
4903: my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
4904: my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
4905: $r->print(<<UPLOAD);
4906: <script type="text/javascript" language="javascript">
4907: function checkUpload(formname) {
4908: if (formname.upfile.value == "") {
4909: alert("Please use the browse button to select a file from your local directory.");
4910: return false;
4911: }
4912: formname.submit();
4913: }
4914: </script>
4915:
4916: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
4917: $default_form_data
4918: <input name='courseid' type='hidden' value='$cnum' />
4919: <input name='domainid' type='hidden' value='$cdom' />
4920: <input name='command' value='scantronupload_save' type='hidden' />
4921: File to upload:<input type="file" name="upfile" size="50" />
4922: <br />
4923: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
4924: </form>
4925: UPLOAD
4926:
4927: $r->print(<<SCANTRONFORM);
4928: </td>
4929: </tr>
4930: </table>
4931: </td>
4932: </tr>
4933: SCANTRONFORM
4934: }
4935:
4936: # Chunk of the form that prompts to view a scoring office file,
4937: # corrected file, skipped records in a file.
4938:
4939: $r->print(<<SCANTRONFORM);
4940: <tr>
4941: <form action='/adm/grades' name='scantron_download'>
4942: <td bgcolor="#777777">
4943: $default_form_data
4944: <input type="hidden" name="command" value="scantron_download" />
4945: <table width="100%" border="0">
4946: <tr bgcolor="#e6ffff">
4947: <td colspan="2">
4948: <b>Download a scoring office file</b>
4949: </td>
4950: </tr>
4951: <tr bgcolor="#ffffe6">
4952: <td> Filename of scoring office file: </td><td> $file_selector </td>
4953: </tr>
4954: <tr bgcolor="#ffffe6">
4955: <td colspan="2">
4956: <input type="submit" value="Download: Show List of Associated Files" />
4957: </td>
4958: </tr>
4959: </table>
4960: </td>
4961: </form>
4962: </tr>
4963: SCANTRONFORM
4964:
4965: $r->print('<tr><td bgcolor="#777777">');
4966: &Apache::lonpickcode::code_list($r,2);
4967: $r->print('</td></tr></table>');
4968: $r->print($grading_menu_button);
4969: return
4970: }
4971:
4972: =pod
4973:
4974: =item get_scantron_config
4975:
4976: Parse and return the scantron configuration line selected as a
4977: hash of configuration file fields.
4978:
4979: Arguments:
4980: which - the name of the configuration to parse from the file.
4981:
4982:
4983: Returns:
4984: If the named configuration is not in the file, an empty
4985: hash is returned.
4986: a hash with the fields
4987: name - internal name for the this configuration setup
4988: description - text to display to operator that describes this config
4989: CODElocation - if 0 or the string 'none'
4990: - no CODE exists for this config
4991: if -1 || the string 'letter'
4992: - a CODE exists for this config and is
4993: a string of letters
4994: Unsupported value (but planned for future support)
4995: if a positive integer
4996: - The CODE exists as the first n items from
4997: the question section of the form
4998: if the string 'number'
4999: - The CODE exists for this config and is
5000: a string of numbers
5001: CODEstart - (only matter if a CODE exists) column in the line where
5002: the CODE starts
5003: CODElength - length of the CODE
5004: IDstart - column where the student ID number starts
5005: IDlength - length of the student ID info
5006: Qstart - column where the information from the bubbled
5007: 'questions' start
5008: Qlength - number of columns comprising a single bubble line from
5009: the sheet. (usually either 1 or 10)
5010: Qon - either a single character representing the character used
5011: to signal a bubble was chosen in the positional setup, or
5012: the string 'letter' if the letter of the chosen bubble is
5013: in the final, or 'number' if a number representing the
5014: chosen bubble is in the file (1->A 0->J)
5015: Qoff - the character used to represent that a bubble was
5016: left blank
5017: PaperID - if the scanning process generates a unique number for each
5018: sheet scanned the column that this ID number starts in
5019: PaperIDlength - number of columns that comprise the unique ID number
5020: for the sheet of paper
5021: FirstName - column that the first name starts in
5022: FirstNameLength - number of columns that the first name spans
5023:
5024: LastName - column that the last name starts in
5025: LastNameLength - number of columns that the last name spans
5026:
5027: =cut
5028:
5029: sub get_scantron_config {
5030: my ($which) = @_;
5031: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
5032: my %config;
5033: #FIXME probably should move to XML it has already gotten a bit much now
5034: foreach my $line (<$fh>) {
5035: my ($name,$descrip)=split(/:/,$line);
5036: if ($name ne $which ) { next; }
5037: chomp($line);
5038: my @config=split(/:/,$line);
5039: $config{'name'}=$config[0];
5040: $config{'description'}=$config[1];
5041: $config{'CODElocation'}=$config[2];
5042: $config{'CODEstart'}=$config[3];
5043: $config{'CODElength'}=$config[4];
5044: $config{'IDstart'}=$config[5];
5045: $config{'IDlength'}=$config[6];
5046: $config{'Qstart'}=$config[7];
5047: $config{'Qlength'}=$config[8];
5048: $config{'Qoff'}=$config[9];
5049: $config{'Qon'}=$config[10];
5050: $config{'PaperID'}=$config[11];
5051: $config{'PaperIDlength'}=$config[12];
5052: $config{'FirstName'}=$config[13];
5053: $config{'FirstNamelength'}=$config[14];
5054: $config{'LastName'}=$config[15];
5055: $config{'LastNamelength'}=$config[16];
5056: last;
5057: }
5058: return %config;
5059: }
5060:
5061: =pod
5062:
5063: =item username_to_idmap
5064:
5065: creates a hash keyed by student id with values of the corresponding
5066: student username:domain.
5067:
5068: Arguments:
5069:
5070: $classlist - reference to the class list hash. This is a hash
5071: keyed by student name:domain whose elements are references
5072: to arrays containing various chunks of information
5073: about the student. (See loncoursedata for more info).
5074:
5075: Returns
5076: %idmap - the constructed hash
5077:
5078: =cut
5079:
5080: sub username_to_idmap {
5081: my ($classlist)= @_;
5082: my %idmap;
5083: foreach my $student (keys(%$classlist)) {
5084: $idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
5085: $student;
5086: }
5087: return %idmap;
5088: }
5089:
5090: =pod
5091:
5092: =item scantron_fixup_scanline
5093:
5094: Process a requested correction to a scanline.
5095:
5096: Arguments:
5097: $scantron_config - hash from &get_scantron_config()
5098: $scan_data - hash of correction information
5099: (see &scantron_getfile())
5100: $line - existing scanline
5101: $whichline - line number of the passed in scanline
5102: $field - type of change to process
5103: (either
5104: 'ID' -> correct the student ID number
5105: 'CODE' -> correct the CODE
5106: 'answer' -> fixup the submitted answers)
5107:
5108: $args - hash of additional info,
5109: - 'ID'
5110: 'newid' -> studentID to use in replacement
5111: of existing one
5112: - 'CODE'
5113: 'CODE_ignore_dup' - set to true if duplicates
5114: should be ignored.
5115: 'CODE' - is new code or 'use_unfound'
5116: if the existing unfound code should
5117: be used as is
5118: - 'answer'
5119: 'response' - new answer or 'none' if blank
5120: 'question' - the bubble line to change
5121:
5122: Returns:
5123: $line - the modified scanline
5124:
5125: Side effects:
5126: $scan_data - may be updated
5127:
5128: =cut
5129:
5130:
5131: sub scantron_fixup_scanline {
5132: my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
5133:
5134:
5135: if ($field eq 'ID') {
5136: if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
5137: return ($line,1,'New value too large');
5138: }
5139: if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
5140: $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
5141: $args->{'newid'});
5142: }
5143: substr($line,$$scantron_config{'IDstart'}-1,
5144: $$scantron_config{'IDlength'})=$args->{'newid'};
5145: if ($args->{'newid'}=~/^\s*$/) {
5146: &scan_data($scan_data,"$whichline.user",
5147: $args->{'username'}.':'.$args->{'domain'});
5148: }
5149: } elsif ($field eq 'CODE') {
5150: if ($args->{'CODE_ignore_dup'}) {
5151: &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
5152: }
5153: &scan_data($scan_data,"$whichline.useCODE",'1');
5154: if ($args->{'CODE'} ne 'use_unfound') {
5155: if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
5156: return ($line,1,'New CODE value too large');
5157: }
5158: if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
5159: $args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
5160: }
5161: substr($line,$$scantron_config{'CODEstart'}-1,
5162: $$scantron_config{'CODElength'})=$args->{'CODE'};
5163: }
5164: } elsif ($field eq 'answer') {
5165: &scantron_get_maxbubble(); # Need the bubble counter info.
5166: my $length =$scantron_config->{'Qlength'};
5167: my $off=$scantron_config->{'Qoff'};
5168: my $on=$scantron_config->{'Qon'};
5169: my $question_number = $args->{'question'} -1;
5170: my $first_position = $first_bubble_line{$question_number};
5171: my $bubble_count = $bubble_lines_per_response{$question_number};
5172: my $bubbles_per_line= $$scantron_config{'Qlength'};
5173: my $answer=${off}x($bubbles_per_line*$bubble_count);
5174: my $final_answer;
5175: if ($$scantron_config{'Qon'} eq 'letter' ||
5176: $$scantron_config{'Qon'} eq 'number') {
5177: $bubbles_per_line = 10;
5178: }
5179: if (defined $args->{'response'}) {
5180:
5181: if ($args->{'response'} eq 'none') {
5182: &scan_data($scan_data,
5183: "$whichline.no_bubble.".$args->{'question'},'1');
5184: } else {
5185: my ($bubble_line, $bubble_number) = split(/:/,$args->{'response'});
5186: if ($on eq 'letter') {
5187: my @alphabet=('A'..'Z');
5188: $answer=$alphabet[$bubble_number];
5189: } elsif ($on eq 'number') {
5190: $answer= $bubble_number+1;
5191: if ($answer == 10) { $answer = '0'; }
5192: } else {
5193: substr($answer,$bubble_number+$bubble_line*$bubbles_per_line,1)=$on;
5194: $final_answer = $answer;
5195: }
5196: &scan_data($scan_data,
5197: "$whichline.no_bubble.".$args->{'question'},undef,'1');
5198:
5199: # Positional notation already has the right final answer length..
5200:
5201: if (($on eq 'letter') || ($on eq 'number')) {
5202: for (my $l = 0; $l < $bubble_count; $l++) {
5203: if ($l eq $bubble_line) {
5204: $final_answer .= $answer;
5205: } else {
5206: $final_answer .= ' ';
5207: }
5208: }
5209: }
5210: }
5211: # $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
5212: #substr($line,$where-1,$length)=$answer;
5213: substr($line,
5214: $scantron_config->{'Qstart'}+$first_position-1,
5215: $bubbles_per_line*$length) = $final_answer;
5216: }
5217: }
5218: return $line;
5219: }
5220:
5221: =pod
5222:
5223: =item scan_data
5224:
5225: Edit or look up an item in the scan_data hash.
5226:
5227: Arguments:
5228: $scan_data - The hash (see scantron_getfile)
5229: $key - shorthand of the key to edit (actual key is
5230: scantronfilename_key).
5231: $data - New value of the hash entry.
5232: $delete - If true, the entry is removed from the hash.
5233:
5234: Returns:
5235: The new value of the hash table field (undefined if deleted).
5236:
5237: =cut
5238:
5239:
5240: sub scan_data {
5241: my ($scan_data,$key,$value,$delete)=@_;
5242: my $filename=$env{'form.scantron_selectfile'};
5243: if (defined($value)) {
5244: $scan_data->{$filename.'_'.$key} = $value;
5245: }
5246: if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
5247: return $scan_data->{$filename.'_'.$key};
5248: }
5249:
5250: =pod
5251:
5252: =item scantron_parse_scanline
5253:
5254: Decodes a scanline from the selected scantron file
5255:
5256: Arguments:
5257: line - The text of the scantron file line to process
5258: whichline - Line number
5259: scantron_config - Hash describing the format of the scantron lines.
5260: scan_data - Hash of extra information about the scanline
5261: (see scantron_getfile for more information)
5262: just_header - True if should not process question answers but only
5263: the stuff to the left of the answers.
5264: Returns:
5265: Hash containing the result of parsing the scanline
5266:
5267: Keys are all proceeded by the string 'scantron.'
5268:
5269: CODE - the CODE in use for this scanline
5270: useCODE - 1 if the CODE is invalid but it usage has been forced
5271: by the operator
5272: CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
5273: CODEs were selected, but the usage has been
5274: forced by the operator
5275: ID - student ID
5276: PaperID - if used, the ID number printed on the sheet when the
5277: paper was scanned
5278: FirstName - first name from the sheet
5279: LastName - last name from the sheet
5280:
5281: if just_header was not true these key may also exist
5282:
5283: missingerror - a list of bubble ranges that are considered to be answers
5284: to a single question that don't have any bubbles filled in.
5285: Of the form questionnumber:firstbubblenumber:count.
5286: doubleerror - a list of bubble ranges that are considered to be answers
5287: to a single question that have more than one bubble filled in.
5288: Of the form questionnumber::firstbubblenumber:count
5289:
5290: In the above, count is the number of bubble responses in the
5291: input line needed to represent the possible answers to the question.
5292: e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
5293: per line would have count = 2.
5294:
5295: maxquest - the number of the last bubble line that was parsed
5296:
5297: (<number> starts at 1)
5298: <number>.answer - zero or more letters representing the selected
5299: letters from the scanline for the bubble line
5300: <number>.
5301: if blank there was either no bubble or there where
5302: multiple bubbles, (consult the keys missingerror and
5303: doubleerror if this is an error condition)
5304:
5305: =cut
5306:
5307: sub scantron_parse_scanline {
5308: my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
5309:
5310: my %record;
5311: my $questions=substr($line,$$scantron_config{'Qstart'}-1); # Answers
5312: my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # earlier stuff
5313: if (!($$scantron_config{'CODElocation'} eq 0 ||
5314: $$scantron_config{'CODElocation'} eq 'none')) {
5315: if ($$scantron_config{'CODElocation'} < 0 ||
5316: $$scantron_config{'CODElocation'} eq 'letter' ||
5317: $$scantron_config{'CODElocation'} eq 'number') {
5318: $record{'scantron.CODE'}=substr($data,
5319: $$scantron_config{'CODEstart'}-1,
5320: $$scantron_config{'CODElength'});
5321: if (&scan_data($scan_data,"$whichline.useCODE")) {
5322: $record{'scantron.useCODE'}=1;
5323: }
5324: if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
5325: $record{'scantron.CODE_ignore_dup'}=1;
5326: }
5327: } else {
5328: #FIXME interpret first N questions
5329: }
5330: }
5331: $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
5332: $$scantron_config{'IDlength'});
5333: $record{'scantron.PaperID'}=
5334: substr($data,$$scantron_config{'PaperID'}-1,
5335: $$scantron_config{'PaperIDlength'});
5336: $record{'scantron.FirstName'}=
5337: substr($data,$$scantron_config{'FirstName'}-1,
5338: $$scantron_config{'FirstNamelength'});
5339: $record{'scantron.LastName'}=
5340: substr($data,$$scantron_config{'LastName'}-1,
5341: $$scantron_config{'LastNamelength'});
5342: if ($just_header) { return \%record; }
5343:
5344: my @alphabet=('A'..'Z');
5345: my $questnum=0;
5346: my $ansnum =1; # Multiple 'answer lines'/question.
5347:
5348: chomp($questions); # Get rid of any trailing \n.
5349: $questions =~ s/\r$//; # Get rid of trailing \r too (MAC or Win uploads).
5350: while (length($questions)) {
5351: my $answers_needed = $bubble_lines_per_response{$questnum};
5352: my $answer_length = $$scantron_config{'Qlength'} * $answers_needed;
5353:
5354:
5355:
5356: $questnum++;
5357: my $currentquest = substr($questions,0,$answer_length);
5358: $questions = substr($questions,0,$answer_length)='';
5359: if (length($currentquest) < $answer_length) { next; }
5360:
5361: # Qon letter implies for each slot in currentquest we have:
5362: # ? or * for doubles a letter in A-Z for a bubble and
5363: # about anything else (esp. a value of Qoff for missing
5364: # bubbles.
5365:
5366:
5367: if ($$scantron_config{'Qon'} eq 'letter') {
5368:
5369: if ($currentquest =~ /\?/
5370: || $currentquest =~ /\*/
5371: || (&occurence_count($currentquest, "[A-Z]") > 1)) {
5372: push(@{$record{'scantron.doubleerror'}},$questnum);
5373: for (my $ans = 0; $ans < $answers_needed; $ans++) {
5374: my $bubble = substr($currentquest, $ans, 1);
5375: if ($bubble =~ /[A-Z]/ ) {
5376: $record{"scantron.$ansnum.answer"} = $bubble;
5377: } else {
5378: $record{"scantron.$ansnum.answer"}='';
5379: }
5380: $ansnum++;
5381: }
5382:
5383: } elsif (!defined($currentquest)
5384: || (&occurence_count($currentquest, $$scantron_config{'Qoff'}) == length($currentquest))
5385: || (&occurence_count($currentquest, "[A-Z]") == 0)) {
5386: for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
5387: $record{"scantron.$ansnum.answer"}='';
5388: $ansnum++;
5389:
5390: }
5391: if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
5392: push(@{$record{"scantron.missingerror"}},$questnum);
5393: # $ansnum += $answers_needed;
5394: }
5395: } else {
5396: for (my $ans = 0; $ans < $answers_needed; $ans++) {
5397: $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
5398: $ansnum++;
5399: }
5400: }
5401:
5402: # Qon 'number' implies each slot gives a digit that indexes the
5403: # the bubbles filled or Qoff or a non number for unbubbled lines.
5404: # and *? for double bubbles on a line.
5405: # these answers are also stored as letters.
5406:
5407: } elsif ($$scantron_config{'Qon'} eq 'number') {
5408: if ($currentquest =~ /\?/
5409: || $currentquest =~ /\*/
5410: || (&occurence_count($currentquest, '\d') > 1)) {
5411: push(@{$record{'scantron.doubleerror'}},$questnum);
5412: for (my $ans = 0; $ans < $answers_needed; $ans++) {
5413: my $bubble = substr($currentquest, $ans, 1);
5414: if ($bubble =~ /\d/) {
5415: $record{"scantron.$ansnum.answer"} = $alphabet[$bubble];
5416: } else {
5417: $record{"scantron.$ansnum.answer"}=' ';
5418: }
5419: $ansnum++;
5420: }
5421:
5422: } elsif (!defined($currentquest)
5423: || (&occurence_count($currentquest,$$scantron_config{'Qoff'}) == length($currentquest))
5424: || (&occurence_count($currentquest, '\d') == 0)) {
5425: for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
5426: $record{"scantron.$ansnum.answer"}='';
5427: $ansnum++;
5428:
5429: }
5430: if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
5431: push(@{$record{"scantron.missingerror"}},$questnum);
5432: $ansnum += $answers_needed;
5433: }
5434:
5435: } else {
5436: $currentquest = &digits_to_letters($currentquest);
5437: for (my $ans =0; $ans < $answers_needed; $ans++) {
5438: $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
5439: $ansnum++;
5440: }
5441: }
5442: } else {
5443:
5444: # Otherwise there's a positional notation;
5445: # each bubble line requires Qlength items, and there are filled in
5446: # bubbles for each case where there 'Qon' characters.
5447: #
5448:
5449: my @array=split($$scantron_config{'Qon'},$currentquest,-1);
5450:
5451: # If the split only giveas us one element.. the full length of the
5452: # answser string, no bubbles are filled in:
5453:
5454: if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
5455: for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
5456: $record{"scantron.$ansnum.answer"}='';
5457: $ansnum++;
5458:
5459: }
5460: if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
5461: push(@{$record{"scantron.missingerror"}},$questnum);
5462: }
5463:
5464: # If the bubble is not the last position, there will be
5465: # 2 elements. If it is the last position, there will be 1 element.
5466:
5467: } elsif (scalar(@array) le 2) {
5468:
5469: my $location = length($array[0]);
5470: my $line_num = int($location / $$scantron_config{'Qlength'});
5471: my $bubble = $alphabet[$location % $$scantron_config{'Qlength'}];
5472:
5473:
5474: for (my $ans = 0; $ans < $answers_needed; $ans++) {
5475: if ($ans eq $line_num) {
5476: $record{"scantron.$ansnum.answer"} = $bubble;
5477: } else {
5478: $record{"scantron.$ansnum.answer"} = ' ';
5479: }
5480: $ansnum++;
5481: }
5482: }
5483: # If there's more than one instance of a bubble character
5484: # That's a double bubble; with positional notation we can
5485: # record all the bubbles filled in as well as the
5486: # fact this response consists of multiple bubbles.
5487: #
5488: else {
5489: push(@{$record{'scantron.doubleerror'}},$questnum);
5490:
5491: my $first_answer = $ansnum;
5492: for (my $ans =0; $ans < $answers_needed; $ans++) {
5493: my $item = $first_answer+$ans;
5494: $record{"scantron.$item.answer"} = '';
5495: }
5496:
5497: my @ans=@array;
5498: my $i=0;
5499: my $increment = 0;
5500: while ($#ans) {
5501: $i+=length($ans[0]) + $increment;
5502: my $line = int($i/$$scantron_config{'Qlength'} + $first_answer);
5503: my $bubble = $i%$$scantron_config{'Qlength'};
5504: $record{"scantron.$line.answer"}.=$alphabet[$bubble];
5505: shift(@ans);
5506: $increment = 1;
5507: }
5508: $ansnum += $answers_needed;
5509: }
5510: }
5511: }
5512: $record{'scantron.maxquest'}=$questnum;
5513: return \%record;
5514: }
5515:
5516: =pod
5517:
5518: =item scantron_add_delay
5519:
5520: Adds an error message that occurred during the grading phase to a
5521: queue of messages to be shown after grading pass is complete
5522:
5523: Arguments:
5524: $delayqueue - arrary ref of hash ref of error messages
5525: $scanline - the scanline that caused the error
5526: $errormesage - the error message
5527: $errorcode - a numeric code for the error
5528:
5529: Side Effects:
5530: updates the $delayqueue to have a new hash ref of the error
5531:
5532: =cut
5533:
5534: sub scantron_add_delay {
5535: my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
5536: push(@$delayqueue,
5537: {'line' => $scanline, 'emsg' => $errormessage,
5538: 'ecode' => $errorcode }
5539: );
5540: }
5541:
5542: =pod
5543:
5544: =item scantron_find_student
5545:
5546: Finds the username for the current scanline
5547:
5548: Arguments:
5549: $scantron_record - hash result from scantron_parse_scanline
5550: $scan_data - hash of correction information
5551: (see &scantron_getfile() form more information)
5552: $idmap - hash from &username_to_idmap()
5553: $line - number of current scanline
5554:
5555: Returns:
5556: Either 'username:domain' or undef if unknown
5557:
5558: =cut
5559:
5560: sub scantron_find_student {
5561: my ($scantron_record,$scan_data,$idmap,$line)=@_;
5562: my $scanID=$$scantron_record{'scantron.ID'};
5563: if ($scanID =~ /^\s*$/) {
5564: return &scan_data($scan_data,"$line.user");
5565: }
5566: foreach my $id (keys(%$idmap)) {
5567: if (lc($id) eq lc($scanID)) {
5568: return $$idmap{$id};
5569: }
5570: }
5571: return undef;
5572: }
5573:
5574: =pod
5575:
5576: =item scantron_filter
5577:
5578: Filter sub for lonnavmaps, filters out hidden resources if ignore
5579: hidden resources was selected
5580:
5581: =cut
5582:
5583: sub scantron_filter {
5584: my ($curres)=@_;
5585:
5586: if (ref($curres) && $curres->is_problem()) {
5587: # if the user has asked to not have either hidden
5588: # or 'randomout' controlled resources to be graded
5589: # don't include them
5590: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
5591: && $curres->randomout) {
5592: return 0;
5593: }
5594: return 1;
5595: }
5596: return 0;
5597: }
5598:
5599: =pod
5600:
5601: =item scantron_process_corrections
5602:
5603: Gets correction information out of submitted form data and corrects
5604: the scanline
5605:
5606: =cut
5607:
5608: sub scantron_process_corrections {
5609: my ($r) = @_;
5610: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
5611: my ($scanlines,$scan_data)=&scantron_getfile();
5612: my $classlist=&Apache::loncoursedata::get_classlist();
5613: my $which=$env{'form.scantron_line'};
5614: my $line=&scantron_get_line($scanlines,$scan_data,$which);
5615: my ($skip,$err,$errmsg);
5616: if ($env{'form.scantron_skip_record'}) {
5617: $skip=1;
5618: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
5619: my $newstudent=$env{'form.scantron_username'}.':'.
5620: $env{'form.scantron_domain'};
5621: my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
5622: ($line,$err,$errmsg)=
5623: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
5624: 'ID',{'newid'=>$newid,
5625: 'username'=>$env{'form.scantron_username'},
5626: 'domain'=>$env{'form.scantron_domain'}});
5627: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
5628: my $resolution=$env{'form.scantron_CODE_resolution'};
5629: my $newCODE;
5630: my %args;
5631: if ($resolution eq 'use_unfound') {
5632: $newCODE='use_unfound';
5633: } elsif ($resolution eq 'use_found') {
5634: $newCODE=$env{'form.scantron_CODE_selectedvalue'};
5635: } elsif ($resolution eq 'use_typed') {
5636: $newCODE=$env{'form.scantron_CODE_newvalue'};
5637: } elsif ($resolution =~ /^use_closest_(\d+)/) {
5638: $newCODE=$env{"form.scantron_CODE_closest_$1"};
5639: }
5640: if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
5641: $args{'CODE_ignore_dup'}=1;
5642: }
5643: $args{'CODE'}=$newCODE;
5644: ($line,$err,$errmsg)=
5645: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
5646: 'CODE',\%args);
5647: } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
5648: foreach my $question (split(',',$env{'form.scantron_questions'})) {
5649: ($line,$err,$errmsg)=
5650: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
5651: $which,'answer',
5652: { 'question'=>$question,
5653: 'response'=>$env{"form.scantron_correct_Q_$question"}});
5654: if ($err) { last; }
5655: }
5656: }
5657: if ($err) {
5658: $r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
5659: } else {
5660: &scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
5661: &scantron_putfile($scanlines,$scan_data);
5662: }
5663: }
5664:
5665: =pod
5666:
5667: =item reset_skipping_status
5668:
5669: Forgets the current set of remember skipped scanlines (and thus
5670: reverts back to considering all lines in the
5671: scantron_skipped_<filename> file)
5672:
5673: =cut
5674:
5675: sub reset_skipping_status {
5676: my ($scanlines,$scan_data)=&scantron_getfile();
5677: &scan_data($scan_data,'remember_skipping',undef,1);
5678: &scantron_putfile(undef,$scan_data);
5679: }
5680:
5681: =pod
5682:
5683: =item start_skipping
5684:
5685: Marks a scanline to be skipped.
5686:
5687: =cut
5688:
5689: sub start_skipping {
5690: my ($scan_data,$i)=@_;
5691: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
5692: if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
5693: $remembered{$i}=2;
5694: } else {
5695: $remembered{$i}=1;
5696: }
5697: &scan_data($scan_data,'remember_skipping',join(':',%remembered));
5698: }
5699:
5700: =pod
5701:
5702: =item should_be_skipped
5703:
5704: Checks whether a scanline should be skipped.
5705:
5706: =cut
5707:
5708: sub should_be_skipped {
5709: my ($scanlines,$scan_data,$i)=@_;
5710: if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
5711: # not redoing old skips
5712: if ($scanlines->{'skipped'}[$i]) { return 1; }
5713: return 0;
5714: }
5715: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
5716:
5717: if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
5718: return 0;
5719: }
5720: return 1;
5721: }
5722:
5723: =pod
5724:
5725: =item remember_current_skipped
5726:
5727: Discovers what scanlines are in the scantron_skipped_<filename>
5728: file and remembers them into scan_data for later use.
5729:
5730: =cut
5731:
5732: sub remember_current_skipped {
5733: my ($scanlines,$scan_data)=&scantron_getfile();
5734: my %to_remember;
5735: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
5736: if ($scanlines->{'skipped'}[$i]) {
5737: $to_remember{$i}=1;
5738: }
5739: }
5740:
5741: &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
5742: &scantron_putfile(undef,$scan_data);
5743: }
5744:
5745: =pod
5746:
5747: =item check_for_error
5748:
5749: Checks if there was an error when attempting to remove a specific
5750: scantron_.. bubble sheet data file. Prints out an error if
5751: something went wrong.
5752:
5753: =cut
5754:
5755: sub check_for_error {
5756: my ($r,$result)=@_;
5757: if ($result ne 'ok' && $result ne 'not_found' ) {
5758: $r->print("An error occurred ($result) when trying to Remove the existing corrections.");
5759: }
5760: }
5761:
5762: =pod
5763:
5764: =item scantron_warning_screen
5765:
5766: Interstitial screen to make sure the operator has selected the
5767: correct options before we start the validation phase.
5768:
5769: =cut
5770:
5771: sub scantron_warning_screen {
5772: my ($button_text)=@_;
5773: my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
5774: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
5775: my $CODElist;
5776: if ($scantron_config{'CODElocation'} &&
5777: $scantron_config{'CODEstart'} &&
5778: $scantron_config{'CODElength'}) {
5779: $CODElist=$env{'form.scantron_CODElist'};
5780: if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
5781: $CODElist=
5782: '<tr><td><b>List of CODES to validate against:</b></td><td><tt>'.
5783: $env{'form.scantron_CODElist'}.'</tt></td></tr>';
5784: }
5785: return (<<STUFF);
5786: <p>
5787: <span class="LC_warning">Please double check the information
5788: below before clicking on '$button_text'</span>
5789: </p>
5790: <table>
5791: <tr><td><b>Sequence to be Graded:</b></td><td>$title</td></tr>
5792: <tr><td><b>Data File that will be used:</b></td><td><tt>$env{'form.scantron_selectfile'}</tt></td></tr>
5793: $CODElist
5794: </table>
5795: <br />
5796: <p> If this information is correct, please click on '$button_text'.</p>
5797: <p> If something is incorrect, please click the 'Grading Menu' button to start over.</p>
5798:
5799: <br />
5800: STUFF
5801: }
5802:
5803: =pod
5804:
5805: =item scantron_do_warning
5806:
5807: Check if the operator has picked something for all required
5808: fields. Error out if something is missing.
5809:
5810: =cut
5811:
5812: sub scantron_do_warning {
5813: my ($r)=@_;
5814: my ($symb)=&get_symb($r);
5815: if (!$symb) {return '';}
5816: my $default_form_data=&defaultFormData($symb);
5817: $r->print(&scantron_form_start().$default_form_data);
5818: if ( $env{'form.selectpage'} eq '' ||
5819: $env{'form.scantron_selectfile'} eq '' ||
5820: $env{'form.scantron_format'} eq '' ) {
5821: $r->print("<p>You have forgetten to specify some information. Please go Back and try again.</p>");
5822: if ( $env{'form.selectpage'} eq '') {
5823: $r->print('<p><span class="LC_error">You have not selected a Sequence to grade</span></p>');
5824: }
5825: if ( $env{'form.scantron_selectfile'} eq '') {
5826: $r->print('<p><span class="LC_error">You have not selected a file that contains the student\'s response data.</span></p>');
5827: }
5828: if ( $env{'form.scantron_format'} eq '') {
5829: $r->print('<p><span class="LC_error">You have not selected a the format of the student\'s response data.</span></p>');
5830: }
5831: } else {
5832: my $warning=&scantron_warning_screen('Grading: Validate Records');
5833: $r->print(<<STUFF);
5834: $warning
5835: <input type="submit" name="submit" value="Grading: Validate Records" />
5836: <input type="hidden" name="command" value="scantron_validate" />
5837: STUFF
5838: }
5839: $r->print("</form><br />".&show_grading_menu_form($symb));
5840: return '';
5841: }
5842:
5843: =pod
5844:
5845: =item scantron_form_start
5846:
5847: html hidden input for remembering all selected grading options
5848:
5849: =cut
5850:
5851: sub scantron_form_start {
5852: my ($max_bubble)=@_;
5853: my $result= <<SCANTRONFORM;
5854: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
5855: <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
5856: <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
5857: <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
5858: <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
5859: <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
5860: <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
5861: <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
5862: <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
5863: <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
5864: SCANTRONFORM
5865:
5866: my $line = 0;
5867: while (defined($env{"form.scantron.bubblelines.$line"})) {
5868: my $chunk =
5869: '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
5870: $chunk .=
5871: '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
5872: $result .= $chunk;
5873: $line++;
5874: }
5875: return $result;
5876: }
5877:
5878: =pod
5879:
5880: =item scantron_validate_file
5881:
5882: Dispatch routine for doing validation of a bubble sheet data file.
5883:
5884: Also processes any necessary information resets that need to
5885: occur before validation begins (ignore previous corrections,
5886: restarting the skipped records processing)
5887:
5888: =cut
5889:
5890: sub scantron_validate_file {
5891: my ($r) = @_;
5892: my ($symb)=&get_symb($r);
5893: if (!$symb) {return '';}
5894: my $default_form_data=&defaultFormData($symb);
5895:
5896: # do the detection of only doing skipped records first befroe we delete
5897: # them when doing the corrections reset
5898: if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
5899: &reset_skipping_status();
5900: }
5901: if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
5902: &remember_current_skipped();
5903: $env{'form.scantron_options_redo'}='redo_skipped_ready';
5904: }
5905:
5906: if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
5907: &check_for_error($r,&scantron_remove_file('corrected'));
5908: &check_for_error($r,&scantron_remove_file('skipped'));
5909: &check_for_error($r,&scantron_remove_scan_data());
5910: $env{'form.scantron_options_ignore'}='done';
5911: }
5912:
5913: if ($env{'form.scantron_corrections'}) {
5914: &scantron_process_corrections($r);
5915: }
5916: $r->print("<p>Gathering necessary info.</p>");$r->rflush();
5917: #get the student pick code ready
5918: $r->print(&Apache::loncommon::studentbrowser_javascript());
5919: my $max_bubble=&scantron_get_maxbubble();
5920: my $result=&scantron_form_start($max_bubble).$default_form_data;
5921: $r->print($result);
5922:
5923: my @validate_phases=( 'sequence',
5924: 'ID',
5925: 'CODE',
5926: 'doublebubble',
5927: 'missingbubbles');
5928: if (!$env{'form.validatepass'}) {
5929: $env{'form.validatepass'} = 0;
5930: }
5931: my $currentphase=$env{'form.validatepass'};
5932:
5933:
5934: my $stop=0;
5935: while (!$stop && $currentphase < scalar(@validate_phases)) {
5936: $r->print("<p> Validating ".$validate_phases[$currentphase]."</p>");
5937: $r->rflush();
5938: my $which="scantron_validate_".$validate_phases[$currentphase];
5939: {
5940: no strict 'refs';
5941: ($stop,$currentphase)=&$which($r,$currentphase);
5942: }
5943: }
5944: if (!$stop) {
5945: my $warning=&scantron_warning_screen('Start Grading');
5946: $r->print(<<STUFF);
5947: Validation process complete.<br />
5948: $warning
5949: <input type="submit" name="submit" value="Start Grading" />
5950: <input type="hidden" name="command" value="scantron_process" />
5951: STUFF
5952:
5953: } else {
5954: $r->print('<input type="hidden" name="command" value="scantron_validate" />');
5955: $r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
5956: }
5957: if ($stop) {
5958: if ($validate_phases[$currentphase] eq 'sequence') {
5959: $r->print('<input type="submit" name="submit" value="Ignore -> " />');
5960: $r->print(' this error <br />');
5961:
5962: $r->print(" <p>Or click the 'Grading Menu' button to start over.</p>");
5963: } else {
5964: $r->print('<input type="submit" name="submit" value="Continue ->" />');
5965: $r->print(' using corrected info <br />');
5966: $r->print("<input type='submit' value='Skip' name='scantron_skip_record' />");
5967: $r->print(" this scanline saving it for later.");
5968: }
5969: }
5970: $r->print(" </form><br />".&show_grading_menu_form($symb));
5971: return '';
5972: }
5973:
5974:
5975: =pod
5976:
5977: =item scantron_remove_file
5978:
5979: Removes the requested bubble sheet data file, makes sure that
5980: scantron_original_<filename> is never removed
5981:
5982:
5983: =cut
5984:
5985: sub scantron_remove_file {
5986: my ($which)=@_;
5987: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5988: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5989: my $file='scantron_';
5990: if ($which eq 'corrected' || $which eq 'skipped') {
5991: $file.=$which.'_';
5992: } else {
5993: return 'refused';
5994: }
5995: $file.=$env{'form.scantron_selectfile'};
5996: return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
5997: }
5998:
5999:
6000: =pod
6001:
6002: =item scantron_remove_scan_data
6003:
6004: Removes all scan_data correction for the requested bubble sheet
6005: data file. (In the case that both the are doing skipped records we need
6006: to remember the old skipped lines for the time being so that element
6007: persists for a while.)
6008:
6009: =cut
6010:
6011: sub scantron_remove_scan_data {
6012: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6013: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6014: my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
6015: my @todelete;
6016: my $filename=$env{'form.scantron_selectfile'};
6017: foreach my $key (@keys) {
6018: if ($key=~/^\Q$filename\E_/) {
6019: if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
6020: $key=~/remember_skipping/) {
6021: next;
6022: }
6023: push(@todelete,$key);
6024: }
6025: }
6026: my $result;
6027: if (@todelete) {
6028: $result=&Apache::lonnet::del('nohist_scantrondata',\@todelete,$cdom,$cname);
6029: }
6030: return $result;
6031: }
6032:
6033:
6034: =pod
6035:
6036: =item scantron_getfile
6037:
6038: Fetches the requested bubble sheet data file (all 3 versions), and
6039: the scan_data hash
6040:
6041: Arguments:
6042: None
6043:
6044: Returns:
6045: 2 hash references
6046:
6047: - first one has
6048: orig -
6049: corrected -
6050: skipped - each of which points to an array ref of the specified
6051: file broken up into individual lines
6052: count - number of scanlines
6053:
6054: - second is the scan_data hash possible keys are
6055: ($number refers to scanline numbered $number and thus the key affects
6056: only that scanline
6057: $bubline refers to the specific bubble line element and the aspects
6058: refers to that specific bubble line element)
6059:
6060: $number.user - username:domain to use
6061: $number.CODE_ignore_dup
6062: - ignore the duplicate CODE error
6063: $number.useCODE
6064: - use the CODE in the scanline as is
6065: $number.no_bubble.$bubline
6066: - it is valid that there is no bubbled in bubble
6067: at $number $bubline
6068: remember_skipping
6069: - a frozen hash containing keys of $number and values
6070: of either
6071: 1 - we are on a 'do skipped records pass' and plan
6072: on processing this line
6073: 2 - we are on a 'do skipped records pass' and this
6074: scanline has been marked to skip yet again
6075:
6076: =cut
6077:
6078: sub scantron_getfile {
6079: #FIXME really would prefer a scantron directory
6080: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6081: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6082: my $lines;
6083: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
6084: 'scantron_orig_'.$env{'form.scantron_selectfile'});
6085: my %scanlines;
6086: $scanlines{'orig'}=[(split("\n",$lines,-1))];
6087: my $temp=$scanlines{'orig'};
6088: $scanlines{'count'}=$#$temp;
6089:
6090: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
6091: 'scantron_corrected_'.$env{'form.scantron_selectfile'});
6092: if ($lines eq '-1') {
6093: $scanlines{'corrected'}=[];
6094: } else {
6095: $scanlines{'corrected'}=[(split("\n",$lines,-1))];
6096: }
6097: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
6098: 'scantron_skipped_'.$env{'form.scantron_selectfile'});
6099: if ($lines eq '-1') {
6100: $scanlines{'skipped'}=[];
6101: } else {
6102: $scanlines{'skipped'}=[(split("\n",$lines,-1))];
6103: }
6104: my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
6105: if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
6106: my %scan_data = @tmp;
6107: return (\%scanlines,\%scan_data);
6108: }
6109:
6110: =pod
6111:
6112: =item lonnet_putfile
6113:
6114: Wrapper routine to call &Apache::lonnet::finishuserfileupload
6115:
6116: Arguments:
6117: $contents - data to store
6118: $filename - filename to store $contents into
6119:
6120: Returns:
6121: result value from &Apache::lonnet::finishuserfileupload
6122:
6123: =cut
6124:
6125: sub lonnet_putfile {
6126: my ($contents,$filename)=@_;
6127: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
6128: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6129: $env{'form.sillywaytopassafilearound'}=$contents;
6130: &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
6131:
6132: }
6133:
6134: =pod
6135:
6136: =item scantron_putfile
6137:
6138: Stores the current version of the bubble sheet data files, and the
6139: scan_data hash. (Does not modify the original version only the
6140: corrected and skipped versions.
6141:
6142: Arguments:
6143: $scanlines - hash ref that looks like the first return value from
6144: &scantron_getfile()
6145: $scan_data - hash ref that looks like the second return value from
6146: &scantron_getfile()
6147:
6148: =cut
6149:
6150: sub scantron_putfile {
6151: my ($scanlines,$scan_data) = @_;
6152: #FIXME really would prefer a scantron directory
6153: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6154: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6155: if ($scanlines) {
6156: my $prefix='scantron_';
6157: # no need to update orig, shouldn't change
6158: # &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
6159: # $env{'form.scantron_selectfile'});
6160: &lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
6161: $prefix.'corrected_'.
6162: $env{'form.scantron_selectfile'});
6163: &lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
6164: $prefix.'skipped_'.
6165: $env{'form.scantron_selectfile'});
6166: }
6167: &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
6168: }
6169:
6170: =pod
6171:
6172: =item scantron_get_line
6173:
6174: Returns the correct version of the scanline
6175:
6176: Arguments:
6177: $scanlines - hash ref that looks like the first return value from
6178: &scantron_getfile()
6179: $scan_data - hash ref that looks like the second return value from
6180: &scantron_getfile()
6181: $i - number of the requested line (starts at 0)
6182:
6183: Returns:
6184: A scanline, (either the original or the corrected one if it
6185: exists), or undef if the requested scanline should be
6186: skipped. (Either because it's an skipped scanline, or it's an
6187: unskipped scanline and we are not doing a 'do skipped scanlines'
6188: pass.
6189:
6190: =cut
6191:
6192: sub scantron_get_line {
6193: my ($scanlines,$scan_data,$i)=@_;
6194: if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
6195: #if ($scanlines->{'skipped'}[$i]) { return undef; }
6196: if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
6197: return $scanlines->{'orig'}[$i];
6198: }
6199:
6200: =pod
6201:
6202: =item scantron_todo_count
6203:
6204: Counts the number of scanlines that need processing.
6205:
6206: Arguments:
6207: $scanlines - hash ref that looks like the first return value from
6208: &scantron_getfile()
6209: $scan_data - hash ref that looks like the second return value from
6210: &scantron_getfile()
6211:
6212: Returns:
6213: $count - number of scanlines to process
6214:
6215: =cut
6216:
6217: sub get_todo_count {
6218: my ($scanlines,$scan_data)=@_;
6219: my $count=0;
6220: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6221: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6222: if ($line=~/^[\s\cz]*$/) { next; }
6223: $count++;
6224: }
6225: return $count;
6226: }
6227:
6228: =pod
6229:
6230: =item scantron_put_line
6231:
6232: Updates the 'corrected' or 'skipped' versions of the bubble sheet
6233: data file.
6234:
6235: Arguments:
6236: $scanlines - hash ref that looks like the first return value from
6237: &scantron_getfile()
6238: $scan_data - hash ref that looks like the second return value from
6239: &scantron_getfile()
6240: $i - line number to update
6241: $newline - contents of the updated scanline
6242: $skip - if true make the line for skipping and update the
6243: 'skipped' file
6244:
6245: =cut
6246:
6247: sub scantron_put_line {
6248: my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
6249: if ($skip) {
6250: $scanlines->{'skipped'}[$i]=$newline;
6251: &start_skipping($scan_data,$i);
6252: return;
6253: }
6254: $scanlines->{'corrected'}[$i]=$newline;
6255: }
6256:
6257: =pod
6258:
6259: =item scantron_clear_skip
6260:
6261: Remove a line from the 'skipped' file
6262:
6263: Arguments:
6264: $scanlines - hash ref that looks like the first return value from
6265: &scantron_getfile()
6266: $scan_data - hash ref that looks like the second return value from
6267: &scantron_getfile()
6268: $i - line number to update
6269:
6270: =cut
6271:
6272: sub scantron_clear_skip {
6273: my ($scanlines,$scan_data,$i)=@_;
6274: if (exists($scanlines->{'skipped'}[$i])) {
6275: undef($scanlines->{'skipped'}[$i]);
6276: return 1;
6277: }
6278: return 0;
6279: }
6280:
6281: =pod
6282:
6283: =item scantron_filter_not_exam
6284:
6285: Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
6286: filter out resources that are not marked as 'exam' mode
6287:
6288: =cut
6289:
6290: sub scantron_filter_not_exam {
6291: my ($curres)=@_;
6292:
6293: if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
6294: # if the user has asked to not have either hidden
6295: # or 'randomout' controlled resources to be graded
6296: # don't include them
6297: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
6298: && $curres->randomout) {
6299: return 0;
6300: }
6301: return 1;
6302: }
6303: return 0;
6304: }
6305:
6306: =pod
6307:
6308: =item scantron_validate_sequence
6309:
6310: Validates the selected sequence, checking for resource that are
6311: not set to exam mode.
6312:
6313: =cut
6314:
6315: sub scantron_validate_sequence {
6316: my ($r,$currentphase) = @_;
6317:
6318: my $navmap=Apache::lonnavmaps::navmap->new();
6319: my (undef,undef,$sequence)=
6320: &Apache::lonnet::decode_symb($env{'form.selectpage'});
6321:
6322: my $map=$navmap->getResourceByUrl($sequence);
6323:
6324: $r->print('<input type="hidden" name="validate_sequence_exam"
6325: value="ignore" />');
6326: if ($env{'form.validate_sequence_exam'} ne 'ignore') {
6327: my @resources=
6328: $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
6329: if (@resources) {
6330: $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>");
6331: return (1,$currentphase);
6332: }
6333: }
6334:
6335: return (0,$currentphase+1);
6336: }
6337:
6338: =pod
6339:
6340: =item scantron_validate_ID
6341:
6342: Validates all scanlines in the selected file to not have any
6343: invalid or underspecified student IDs
6344:
6345: =cut
6346:
6347: sub scantron_validate_ID {
6348: my ($r,$currentphase) = @_;
6349:
6350: #get student info
6351: my $classlist=&Apache::loncoursedata::get_classlist();
6352: my %idmap=&username_to_idmap($classlist);
6353:
6354: #get scantron line setup
6355: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6356: my ($scanlines,$scan_data)=&scantron_getfile();
6357:
6358: &scantron_get_maxbubble(); # parse needs the bubble_lines.. array.
6359:
6360: my %found=('ids'=>{},'usernames'=>{});
6361: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6362: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6363: if ($line=~/^[\s\cz]*$/) { next; }
6364: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6365: $scan_data);
6366: my $id=$$scan_record{'scantron.ID'};
6367: my $found;
6368: foreach my $checkid (keys(%idmap)) {
6369: if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
6370: }
6371: if ($found) {
6372: my $username=$idmap{$found};
6373: if ($found{'ids'}{$found}) {
6374: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6375: $line,'duplicateID',$found);
6376: return(1,$currentphase);
6377: } elsif ($found{'usernames'}{$username}) {
6378: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6379: $line,'duplicateID',$username);
6380: return(1,$currentphase);
6381: }
6382: #FIXME store away line we previously saw the ID on to use above
6383: $found{'ids'}{$found}++;
6384: $found{'usernames'}{$username}++;
6385: } else {
6386: if ($id =~ /^\s*$/) {
6387: my $username=&scan_data($scan_data,"$i.user");
6388: if (defined($username) && $found{'usernames'}{$username}) {
6389: &scantron_get_correction($r,$i,$scan_record,
6390: \%scantron_config,
6391: $line,'duplicateID',$username);
6392: return(1,$currentphase);
6393: } elsif (!defined($username)) {
6394: &scantron_get_correction($r,$i,$scan_record,
6395: \%scantron_config,
6396: $line,'incorrectID');
6397: return(1,$currentphase);
6398: }
6399: $found{'usernames'}{$username}++;
6400: } else {
6401: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6402: $line,'incorrectID');
6403: return(1,$currentphase);
6404: }
6405: }
6406: }
6407:
6408: return (0,$currentphase+1);
6409: }
6410:
6411: =pod
6412:
6413: =item scantron_get_correction
6414:
6415: Builds the interface screen to interact with the operator to fix a
6416: specific error condition in a specific scanline
6417:
6418: Arguments:
6419: $r - Apache request object
6420: $i - number of the current scanline
6421: $scan_record - hash ref as returned from &scantron_parse_scanline()
6422: $scan_config - hash ref as returned from &get_scantron_config()
6423: $line - full contents of the current scanline
6424: $error - error condition, valid values are
6425: 'incorrectCODE', 'duplicateCODE',
6426: 'doublebubble', 'missingbubble',
6427: 'duplicateID', 'incorrectID'
6428: $arg - extra information needed
6429: For errors:
6430: - duplicateID - paper number that this studentID was seen before on
6431: - duplicateCODE - array ref of the paper numbers this CODE was
6432: seen on before
6433: - incorrectCODE - current incorrect CODE
6434: - doublebubble - array ref of the bubble lines that have double
6435: bubble errors
6436: - missingbubble - array ref of the bubble lines that have missing
6437: bubble errors
6438:
6439: =cut
6440:
6441: sub scantron_get_correction {
6442: my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
6443:
6444: #FIXME in the case of a duplicated ID the previous line, probably need
6445: #to show both the current line and the previous one and allow skipping
6446: #the previous one or the current one
6447:
6448: $r->print("<p><b>An error was detected ($error)</b>");
6449: if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
6450: $r->print(" for PaperID <tt>".
6451: $$scan_record{'scantron.PaperID'}."</tt> \n");
6452: } else {
6453: $r->print(" in scanline $i <pre>".
6454: $line."</pre> \n");
6455: }
6456: my $message="<p>The ID on the form is <tt>".
6457: $$scan_record{'scantron.ID'}."</tt><br />\n".
6458: "The name on the paper is ".
6459: $$scan_record{'scantron.LastName'}.",".
6460: $$scan_record{'scantron.FirstName'}."</p>";
6461:
6462: $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
6463: $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
6464: if ($error =~ /ID$/) {
6465: if ($error eq 'incorrectID') {
6466: $r->print("The encoded ID is not in the classlist</p>\n");
6467: } elsif ($error eq 'duplicateID') {
6468: $r->print("The encoded ID has also been used by a previous paper $arg</p>\n");
6469: }
6470: $r->print($message);
6471: $r->print("<p>How should I handle this? <br /> \n");
6472: $r->print("\n<ul><li> ");
6473: #FIXME it would be nice if this sent back the user ID and
6474: #could do partial userID matches
6475: $r->print(&Apache::loncommon::selectstudent_link('scantronupload',
6476: 'scantron_username','scantron_domain'));
6477: $r->print(": <input type='text' name='scantron_username' value='' />");
6478: $r->print("\n@".
6479: &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
6480:
6481: $r->print('</li>');
6482: } elsif ($error =~ /CODE$/) {
6483: if ($error eq 'incorrectCODE') {
6484: $r->print("</p><p>The encoded CODE is not in the list of possible CODEs</p>\n");
6485: } elsif ($error eq 'duplicateCODE') {
6486: $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");
6487: }
6488: $r->print("<p>The CODE on the form is <tt>'".
6489: $$scan_record{'scantron.CODE'}."'</tt><br />\n");
6490: $r->print($message);
6491: $r->print("<p>How should I handle this? <br /> \n");
6492: $r->print("\n<br /> ");
6493: my $i=0;
6494: if ($error eq 'incorrectCODE'
6495: && $$scan_record{'scantron.CODE'}=~/\S/ ) {
6496: my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
6497: if ($closest > 0) {
6498: foreach my $testcode (@{$closest}) {
6499: my $checked='';
6500: if (!$i) { $checked=' checked="checked" '; }
6501: $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' />");
6502: $r->print("\n<br />");
6503: $i++;
6504: }
6505: }
6506: }
6507: if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
6508: my $checked; if (!$i) { $checked=' checked="checked" '; }
6509: $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>");
6510: $r->print("\n<br />");
6511: }
6512:
6513: $r->print(<<ENDSCRIPT);
6514: <script type="text/javascript">
6515: function change_radio(field) {
6516: var slct=document.scantronupload.scantron_CODE_resolution;
6517: var i;
6518: for (i=0;i<slct.length;i++) {
6519: if (slct[i].value==field) { slct[i].checked=true; }
6520: }
6521: }
6522: </script>
6523: ENDSCRIPT
6524: my $href="/adm/pickcode?".
6525: "form=".&escape("scantronupload").
6526: "&scantron_format=".&escape($env{'form.scantron_format'}).
6527: "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
6528: "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
6529: "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
6530: if ($env{'form.scantron_CODElist'} =~ /\S/) {
6531: $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')\" />");
6532: $r->print("\n<br />");
6533: }
6534: $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.");
6535: $r->print("\n<br /><br />");
6536: } elsif ($error eq 'doublebubble') {
6537: $r->print("<p>There have been multiple bubbles scanned for a some question(s)</p>\n");
6538: $r->print('<input type="hidden" name="scantron_questions" value="'.
6539: join(',',@{$arg}).'" />');
6540: $r->print($message);
6541: $r->print("<p>Please indicate which bubble should be used for grading</p>");
6542: foreach my $question (@{$arg}) {
6543: my $selected = &get_response_bubbles($scan_record, $question);
6544: my @select_array = split(/:/,$selected);
6545: &scantron_bubble_selector($r,$scan_config,$question,
6546: @select_array);
6547: }
6548: } elsif ($error eq 'missingbubble') {
6549: $r->print("<p>There have been <b>no</b> bubbles scanned for some question(s)</p>\n");
6550: $r->print($message);
6551: $r->print("<p>Please indicate which bubble should be used for grading</p>");
6552: $r->print("Some questions have no scanned bubbles\n");
6553: $r->print('<input type="hidden" name="scantron_questions" value="'.
6554: join(',',@{$arg}).'" />');
6555: foreach my $question (@{$arg}) {
6556: my $selected = &get_response_bubbles($scan_record, $question);
6557: my @select_array = split(/:/,$selected); # ought to be an array of empties.
6558: &scantron_bubble_selector($r,$scan_config,$question, @select_array);
6559: }
6560: } else {
6561: $r->print("\n<ul>");
6562: }
6563: $r->print("\n</li></ul>");
6564:
6565: }
6566:
6567: =pod
6568:
6569: =item scantron_bubble_selector
6570:
6571: Generates the html radiobuttons to correct a single bubble line
6572: possibly showing the existing the selected bubbles if known
6573:
6574: Arguments:
6575: $r - Apache request object
6576: $scan_config - hash from &get_scantron_config()
6577: $quest - number of the bubble line to make a corrector for
6578: @lines - array of answer lines.
6579:
6580: =cut
6581:
6582: sub scantron_bubble_selector {
6583: my ($r,$scan_config,$quest,@lines)=@_;
6584: my $max=$$scan_config{'Qlength'};
6585:
6586:
6587: my $scmode=$$scan_config{'Qon'};
6588:
6589: my $bubble_length = scalar(@lines);
6590:
6591:
6592: if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }
6593:
6594: my $response = $quest-1;
6595: my $lines = $bubble_lines_per_response{$response};
6596:
6597: my $total_lines = $lines*2;
6598: my @alphabet=('A'..'Z');
6599:
6600: $r->print("<table border='1'><tr><td rowspan='".$total_lines."'>$quest</td>");
6601:
6602: for (my $l = 0; $l < $lines; $l++) {
6603: if ($l != 0) {
6604: $r->print('<tr>');
6605: }
6606: my @selected = split(//,$lines[$l]);
6607: for (my $i=0;$i<$max;$i++) {
6608: $r->print("\n".'<td align="center">');
6609: if ($selected[0] eq $alphabet[$i]) {
6610: $r->print('X');
6611: shift(@selected) ;
6612: } else {
6613: $r->print(' ');
6614: }
6615: $r->print('</td>');
6616:
6617: }
6618:
6619: if ($l == 0) {
6620: my $lspan = $total_lines * 2; # 2 table rows per bubble line.
6621:
6622: $r->print('<td rowspan='.$lspan.'><label><input type="radio" name="scantron_correct_Q_'.
6623: $quest.'" value="none" /> No bubble </label></td>');
6624:
6625: }
6626:
6627: $r->print('</tr><tr>');
6628:
6629: # FIXME: This may have to be a bit more clever for
6630: # multiline questions (different values e.g..).
6631:
6632: for (my $i=0;$i<$max;$i++) {
6633: my $value = "$l:$i"; # Relative bubble line #: Bubble in line.
6634: $r->print("\n".
6635: '<td><label><input type="radio" name="scantron_correct_Q_'.
6636: $quest.'" value="'.$value.'" />'.$alphabet[$i]."</label></td>");
6637: }
6638: $r->print('</tr>');
6639:
6640:
6641: }
6642: $r->print('</table>');
6643: }
6644:
6645: =pod
6646:
6647: =item num_matches
6648:
6649: Counts the number of characters that are the same between the two arguments.
6650:
6651: Arguments:
6652: $orig - CODE from the scanline
6653: $code - CODE to match against
6654:
6655: Returns:
6656: $count - integer count of the number of same characters between the
6657: two arguments
6658:
6659: =cut
6660:
6661: sub num_matches {
6662: my ($orig,$code) = @_;
6663: my @code=split(//,$code);
6664: my @orig=split(//,$orig);
6665: my $same=0;
6666: for (my $i=0;$i<scalar(@code);$i++) {
6667: if ($code[$i] eq $orig[$i]) { $same++; }
6668: }
6669: return $same;
6670: }
6671:
6672: =pod
6673:
6674: =item scantron_get_closely_matching_CODEs
6675:
6676: Cycles through all CODEs and finds the set that has the greatest
6677: number of same characters as the provided CODE
6678:
6679: Arguments:
6680: $allcodes - hash ref returned by &get_codes()
6681: $CODE - CODE from the current scanline
6682:
6683: Returns:
6684: 2 element list
6685: - first elements is number of how closely matching the best fit is
6686: (5 means best set has 5 matching characters)
6687: - second element is an arrary ref containing the set of valid CODEs
6688: that best fit the passed in CODE
6689:
6690: =cut
6691:
6692: sub scantron_get_closely_matching_CODEs {
6693: my ($allcodes,$CODE)=@_;
6694: my @CODEs;
6695: foreach my $testcode (sort(keys(%{$allcodes}))) {
6696: push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
6697: }
6698:
6699: return ($#CODEs,$CODEs[-1]);
6700: }
6701:
6702: =pod
6703:
6704: =item get_codes
6705:
6706: Builds a hash which has keys of all of the valid CODEs from the selected
6707: set of remembered CODEs.
6708:
6709: Arguments:
6710: $old_name - name of the set of remembered CODEs
6711: $cdom - domain of the course
6712: $cnum - internal course name
6713:
6714: Returns:
6715: %allcodes - keys are the valid CODEs, values are all 1
6716:
6717: =cut
6718:
6719: sub get_codes {
6720: my ($old_name, $cdom, $cnum) = @_;
6721: if (!$old_name) {
6722: $old_name=$env{'form.scantron_CODElist'};
6723: }
6724: if (!$cdom) {
6725: $cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
6726: }
6727: if (!$cnum) {
6728: $cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
6729: }
6730: my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
6731: $cdom,$cnum);
6732: my %allcodes;
6733: if ($result{"type\0$old_name"} eq 'number') {
6734: %allcodes=map {($_,1)} split(',',$result{$old_name});
6735: } else {
6736: %allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
6737: }
6738: return %allcodes;
6739: }
6740:
6741: =pod
6742:
6743: =item scantron_validate_CODE
6744:
6745: Validates all scanlines in the selected file to not have any
6746: invalid or underspecified CODEs and that none of the codes are
6747: duplicated if this was requested.
6748:
6749: =cut
6750:
6751: sub scantron_validate_CODE {
6752: my ($r,$currentphase) = @_;
6753: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6754: if ($scantron_config{'CODElocation'} &&
6755: $scantron_config{'CODEstart'} &&
6756: $scantron_config{'CODElength'}) {
6757: if (!defined($env{'form.scantron_CODElist'})) {
6758: &FIXME_blow_up()
6759: }
6760: } else {
6761: return (0,$currentphase+1);
6762: }
6763:
6764: my %usedCODEs;
6765:
6766: my %allcodes=&get_codes();
6767:
6768: &scantron_get_maxbubble(); # parse needs the lines per response array.
6769:
6770: my ($scanlines,$scan_data)=&scantron_getfile();
6771: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6772: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6773: if ($line=~/^[\s\cz]*$/) { next; }
6774: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6775: $scan_data);
6776: my $CODE=$$scan_record{'scantron.CODE'};
6777: my $error=0;
6778: if (!&Apache::lonnet::validCODE($CODE)) {
6779: &scantron_get_correction($r,$i,$scan_record,
6780: \%scantron_config,
6781: $line,'incorrectCODE',\%allcodes);
6782: return(1,$currentphase);
6783: }
6784: if (%allcodes && !exists($allcodes{$CODE})
6785: && !$$scan_record{'scantron.useCODE'}) {
6786: &scantron_get_correction($r,$i,$scan_record,
6787: \%scantron_config,
6788: $line,'incorrectCODE',\%allcodes);
6789: return(1,$currentphase);
6790: }
6791: if (exists($usedCODEs{$CODE})
6792: && $env{'form.scantron_CODEunique'} eq 'yes'
6793: && !$$scan_record{'scantron.CODE_ignore_dup'}) {
6794: &scantron_get_correction($r,$i,$scan_record,
6795: \%scantron_config,
6796: $line,'duplicateCODE',$usedCODEs{$CODE});
6797: return(1,$currentphase);
6798: }
6799: push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
6800: }
6801: return (0,$currentphase+1);
6802: }
6803:
6804: =pod
6805:
6806: =item scantron_validate_doublebubble
6807:
6808: Validates all scanlines in the selected file to not have any
6809: bubble lines with multiple bubbles marked.
6810:
6811: =cut
6812:
6813: sub scantron_validate_doublebubble {
6814: my ($r,$currentphase) = @_;
6815: #get student info
6816: my $classlist=&Apache::loncoursedata::get_classlist();
6817: my %idmap=&username_to_idmap($classlist);
6818:
6819: #get scantron line setup
6820: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6821: my ($scanlines,$scan_data)=&scantron_getfile();
6822:
6823: &scantron_get_maxbubble(); # parse needs the bubble line array.
6824:
6825: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6826: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6827: if ($line=~/^[\s\cz]*$/) { next; }
6828: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6829: $scan_data);
6830: if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
6831: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
6832: 'doublebubble',
6833: $$scan_record{'scantron.doubleerror'});
6834: return (1,$currentphase);
6835: }
6836: return (0,$currentphase+1);
6837: }
6838:
6839: =pod
6840:
6841: =item scantron_get_maxbubble
6842:
6843: Returns the maximum number of bubble lines that are expected to
6844: occur. Does this by walking the selected sequence rendering the
6845: resource and then checking &Apache::lonxml::get_problem_counter()
6846: for what the current value of the problem counter is.
6847:
6848: Caches the results to $env{'form.scantron_maxbubble'},
6849: $env{'form.scantron.bubble_lines.n'} and
6850: $env{'form.scantron.first_bubble_line.n'}
6851: which are the total number of bubble, lines, the number of bubble
6852: lines for reponse n and number of the first bubble line for response n.
6853:
6854: =cut
6855:
6856: sub scantron_get_maxbubble {
6857: if (defined($env{'form.scantron_maxbubble'}) &&
6858: $env{'form.scantron_maxbubble'}) {
6859: &restore_bubble_lines();
6860: return $env{'form.scantron_maxbubble'};
6861: }
6862:
6863: my (undef, undef, $sequence) =
6864: &Apache::lonnet::decode_symb($env{'form.selectpage'});
6865:
6866: my $navmap=Apache::lonnavmaps::navmap->new();
6867: my $map=$navmap->getResourceByUrl($sequence);
6868: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
6869:
6870: &Apache::lonxml::clear_problem_counter();
6871:
6872: my $uname = $env{'form.student'};
6873: my $udom = $env{'form.userdom'};
6874: my $cid = $env{'request.course.id'};
6875: my $total_lines = 0;
6876: %bubble_lines_per_response = ();
6877: %first_bubble_line = ();
6878:
6879:
6880: my $response_number = 0;
6881: my $bubble_line = 0;
6882: foreach my $resource (@resources) {
6883: my $symb = $resource->symb();
6884: &Apache::lonxml::clear_bubble_lines_for_part();
6885: my $result=&Apache::lonnet::ssi($resource->src(),
6886: ('symb' => $resource->symb()),
6887: ('grade_target' => 'analyze'),
6888: ('grade_courseid' => $cid),
6889: ('grade_domain' => $udom),
6890: ('grade_username' => $uname));
6891: my (undef, $an) =
6892: split(/_HASH_REF__/,$result, 2);
6893:
6894: my %analysis = &Apache::lonnet::str2hash($an);
6895:
6896:
6897:
6898: foreach my $part_id (@{$analysis{'parts'}}) {
6899:
6900:
6901: my $lines = $analysis{"$part_id.bubble_lines"};;
6902:
6903: # TODO - make this a persistent hash not an array.
6904:
6905:
6906: $first_bubble_line{$response_number} = $bubble_line;
6907: $bubble_lines_per_response{$response_number} = $lines;
6908: $response_number++;
6909:
6910: $bubble_line += $lines;
6911: $total_lines += $lines;
6912: }
6913:
6914: }
6915: &Apache::lonnet::delenv('scantron\.');
6916:
6917: &save_bubble_lines();
6918: $env{'form.scantron_maxbubble'} =
6919: $total_lines;
6920: return $env{'form.scantron_maxbubble'};
6921: }
6922:
6923: =pod
6924:
6925: =item scantron_validate_missingbubbles
6926:
6927: Validates all scanlines in the selected file to not have any
6928: answers that don't have bubbles that have not been verified
6929: to be bubble free.
6930:
6931: =cut
6932:
6933: sub scantron_validate_missingbubbles {
6934: my ($r,$currentphase) = @_;
6935: #get student info
6936: my $classlist=&Apache::loncoursedata::get_classlist();
6937: my %idmap=&username_to_idmap($classlist);
6938:
6939: #get scantron line setup
6940: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6941: my ($scanlines,$scan_data)=&scantron_getfile();
6942: my $max_bubble=&scantron_get_maxbubble();
6943: if (!$max_bubble) { $max_bubble=2**31; }
6944: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6945: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6946: if ($line=~/^[\s\cz]*$/) { next; }
6947: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6948: $scan_data);
6949: if (!defined($$scan_record{'scantron.missingerror'})) { next; }
6950: my @to_correct;
6951:
6952: # Probably here's where the error is...
6953:
6954: foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
6955: if ($missing > $max_bubble) { next; }
6956: push(@to_correct,$missing);
6957: }
6958: if (@to_correct) {
6959: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6960: $line,'missingbubble',\@to_correct);
6961: return (1,$currentphase);
6962: }
6963:
6964: }
6965: return (0,$currentphase+1);
6966: }
6967:
6968: =pod
6969:
6970: =item scantron_process_students
6971:
6972: Routine that does the actual grading of the bubble sheet information.
6973:
6974: The parsed scanline hash is added to %env
6975:
6976: Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
6977: foreach resource , with the form data of
6978:
6979: 'submitted' =>'scantron'
6980: 'grade_target' =>'grade',
6981: 'grade_username'=> username of student
6982: 'grade_domain' => domain of student
6983: 'grade_courseid'=> of course
6984: 'grade_symb' => symb of resource to grade
6985:
6986: This triggers a grading pass. The problem grading code takes care
6987: of converting the bubbled letter information (now in %env) into a
6988: valid submission.
6989:
6990: =cut
6991:
6992: sub scantron_process_students {
6993: my ($r) = @_;
6994: my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
6995: my ($symb)=&get_symb($r);
6996: if (!$symb) {return '';}
6997: my $default_form_data=&defaultFormData($symb);
6998:
6999: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7000: my ($scanlines,$scan_data)=&scantron_getfile();
7001: my $classlist=&Apache::loncoursedata::get_classlist();
7002: my %idmap=&username_to_idmap($classlist);
7003: my $navmap=Apache::lonnavmaps::navmap->new();
7004: my $map=$navmap->getResourceByUrl($sequence);
7005: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
7006: # $r->print("geto ".scalar(@resources)."<br />");
7007: my $result= <<SCANTRONFORM;
7008: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
7009: <input type="hidden" name="command" value="scantron_configphase" />
7010: $default_form_data
7011: SCANTRONFORM
7012: $r->print($result);
7013:
7014: my @delayqueue;
7015: my %completedstudents;
7016:
7017: my $count=&get_todo_count($scanlines,$scan_data);
7018: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
7019: 'Scantron Progress',$count,
7020: 'inline',undef,'scantronupload');
7021: &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
7022: 'Processing first student');
7023: my $start=&Time::HiRes::time();
7024: my $i=-1;
7025: my ($uname,$udom,$started);
7026:
7027: &scantron_get_maxbubble(); # Need the bubble lines array to parse.
7028:
7029: while ($i<$scanlines->{'count'}) {
7030: ($uname,$udom)=('','');
7031: $i++;
7032: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7033: if ($line=~/^[\s\cz]*$/) { next; }
7034: if ($started) {
7035: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
7036: 'last student');
7037: }
7038: $started=1;
7039: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7040: $scan_data);
7041: unless ($uname=&scantron_find_student($scan_record,$scan_data,
7042: \%idmap,$i)) {
7043: &scantron_add_delay(\@delayqueue,$line,
7044: 'Unable to find a student that matches',1);
7045: next;
7046: }
7047: if (exists $completedstudents{$uname}) {
7048: &scantron_add_delay(\@delayqueue,$line,
7049: 'Student '.$uname.' has multiple sheets',2);
7050: next;
7051: }
7052: ($uname,$udom)=split(/:/,$uname);
7053:
7054: &Apache::lonxml::clear_problem_counter();
7055: &Apache::lonnet::appenv(%$scan_record);
7056:
7057: if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
7058: &scantron_putfile($scanlines,$scan_data);
7059: }
7060:
7061: my $i=0;
7062: foreach my $resource (@resources) {
7063: $i++;
7064: my %form=('submitted' =>'scantron',
7065: 'grade_target' =>'grade',
7066: 'grade_username'=>$uname,
7067: 'grade_domain' =>$udom,
7068: 'grade_courseid'=>$env{'request.course.id'},
7069: 'grade_symb' =>$resource->symb());
7070: if (exists($scan_record->{'scantron.CODE'})
7071: &&
7072: &Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
7073: $form{'CODE'}=$scan_record->{'scantron.CODE'};
7074: } else {
7075: $form{'CODE'}='';
7076: }
7077: my $result=&Apache::lonnet::ssi($resource->src(),%form);
7078: if ($result ne '') {
7079: }
7080: if (&Apache::loncommon::connection_aborted($r)) { last; }
7081: }
7082: $completedstudents{$uname}={'line'=>$line};
7083: if (&Apache::loncommon::connection_aborted($r)) { last; }
7084: } continue {
7085: &Apache::lonxml::clear_problem_counter();
7086: &Apache::lonnet::delenv('scantron\.');
7087: }
7088: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
7089: # my $lasttime = &Time::HiRes::time()-$start;
7090: # $r->print("<p>took $lasttime</p>");
7091:
7092: $r->print("</form>");
7093: $r->print(&show_grading_menu_form($symb));
7094: return '';
7095: }
7096:
7097: =pod
7098:
7099: =item scantron_upload_scantron_data
7100:
7101: Creates the screen for adding a new bubble sheet data file to a course.
7102:
7103: =cut
7104:
7105: sub scantron_upload_scantron_data {
7106: my ($r)=@_;
7107: $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
7108: my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
7109: 'domainid',
7110: 'coursename');
7111: my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
7112: 'domainid');
7113: my $default_form_data=&defaultFormData(&get_symb($r,1));
7114: $r->print(<<UPLOAD);
7115: <script type="text/javascript" language="javascript">
7116: function checkUpload(formname) {
7117: if (formname.upfile.value == "") {
7118: alert("Please use the browse button to select a file from your local directory.");
7119: return false;
7120: }
7121: formname.submit();
7122: }
7123: </script>
7124:
7125: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
7126: $default_form_data
7127: <table>
7128: <tr><td>$select_link </td></tr>
7129: <tr><td>Course ID: </td><td><input name='courseid' type='text' /> </td></tr>
7130: <tr><td>Course Name: </td><td><input name='coursename' type='text' /></td></tr>
7131: <tr><td>Domain: </td><td>$domsel </td></tr>
7132: <tr><td>File to upload:</td><td><input type="file" name="upfile" size="50" /></td></tr>
7133: </table>
7134: <input name='command' value='scantronupload_save' type='hidden' />
7135: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
7136: </form>
7137: UPLOAD
7138: return '';
7139: }
7140:
7141: =pod
7142:
7143: =item scantron_upload_scantron_data_save
7144:
7145: Adds a provided bubble information data file to the course if user
7146: has the correct privileges to do so.
7147:
7148: =cut
7149:
7150: sub scantron_upload_scantron_data_save {
7151: my($r)=@_;
7152: my ($symb)=&get_symb($r,1);
7153: my $doanotherupload=
7154: '<br /><form action="/adm/grades" method="post">'."\n".
7155: '<input type="hidden" name="command" value="scantronupload" />'."\n".
7156: '<input type="submit" name="submit" value="Do Another Upload" />'."\n".
7157: '</form>'."\n";
7158: if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
7159: !&Apache::lonnet::allowed('usc',
7160: $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
7161: $r->print("You are not allowed to upload Scantron data to the requested course.<br />");
7162: if ($symb) {
7163: $r->print(&show_grading_menu_form($symb));
7164: } else {
7165: $r->print($doanotherupload);
7166: }
7167: return '';
7168: }
7169: my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
7170: $r->print("Doing upload to ".$coursedata{'description'}." <br />");
7171: my $fname=$env{'form.upfile.filename'};
7172: #FIXME
7173: #copied from lonnet::userfileupload()
7174: #make that function able to target a specified course
7175: # Replace Windows backslashes by forward slashes
7176: $fname=~s/\\/\//g;
7177: # Get rid of everything but the actual filename
7178: $fname=~s/^.*\/([^\/]+)$/$1/;
7179: # Replace spaces by underscores
7180: $fname=~s/\s+/\_/g;
7181: # Replace all other weird characters by nothing
7182: $fname=~s/[^\w\.\-]//g;
7183: # See if there is anything left
7184: unless ($fname) { return 'error: no uploaded file'; }
7185: my $uploadedfile=$fname;
7186: $fname='scantron_orig_'.$fname;
7187: if (length($env{'form.upfile'}) < 2) {
7188: $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.");
7189: } else {
7190: my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
7191: if ($result =~ m|^/uploaded/|) {
7192: $r->print("<span class=\"LC_success\">Success:</span> Successfully uploaded ".(length($env{'form.upfile'})-1)." bytes of data into location <tt>".$result."</tt>");
7193: } else {
7194: $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>");
7195: }
7196: }
7197: if ($symb) {
7198: $r->print(&scantron_selectphase($r,$uploadedfile));
7199: } else {
7200: $r->print($doanotherupload);
7201: }
7202: return '';
7203: }
7204:
7205: =pod
7206:
7207: =item valid_file
7208:
7209: Validates that the requested bubble data file exists in the course.
7210:
7211: =cut
7212:
7213: sub valid_file {
7214: my ($requested_file)=@_;
7215: foreach my $filename (sort(&scantron_filenames())) {
7216: if ($requested_file eq $filename) { return 1; }
7217: }
7218: return 0;
7219: }
7220:
7221: =pod
7222:
7223: =item scantron_download_scantron_data
7224:
7225: Shows a list of the three internal files (original, corrected,
7226: skipped) for a specific bubble sheet data file that exists in the
7227: course.
7228:
7229: =cut
7230:
7231: sub scantron_download_scantron_data {
7232: my ($r)=@_;
7233: my $default_form_data=&defaultFormData(&get_symb($r,1));
7234: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7235: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7236: my $file=$env{'form.scantron_selectfile'};
7237: if (! &valid_file($file)) {
7238: $r->print(<<ERROR);
7239: <p>
7240: The requested file name was invalid.
7241: </p>
7242: ERROR
7243: $r->print(&show_grading_menu_form(&get_symb($r,1)));
7244: return;
7245: }
7246: my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
7247: my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
7248: my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
7249: &Apache::lonnet::allowuploaded('/adm/grades',$orig);
7250: &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
7251: &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
7252: $r->print(<<DOWNLOAD);
7253: <p>
7254: <a href="$orig">Original</a> file as uploaded by the scantron office.
7255: </p>
7256: <p>
7257: <a href="$corrected">Corrections</a>, a file of corrected records that were used in grading.
7258: </p>
7259: <p>
7260: <a href="$skipped">Skipped</a>, a file of records that were skipped.
7261: </p>
7262: DOWNLOAD
7263: $r->print(&show_grading_menu_form(&get_symb($r,1)));
7264: return '';
7265: }
7266:
7267: =pod
7268:
7269: =back
7270:
7271: =cut
7272:
7273: #-------- end of section for handling grading scantron forms -------
7274: #
7275: #-------------------------------------------------------------------
7276:
7277: #-------------------------- Menu interface -------------------------
7278: #
7279: #--- Show a Grading Menu button - Calls the next routine ---
7280: sub show_grading_menu_form {
7281: my ($symb)=@_;
7282: my $result.='<br /><form action="/adm/grades" method="post">'."\n".
7283: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
7284: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
7285: '<input type="hidden" name="command" value="gradingmenu" />'."\n".
7286: '<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
7287: '</form>'."\n";
7288: return $result;
7289: }
7290:
7291: # -- Retrieve choices for grading form
7292: sub savedState {
7293: my %savedState = ();
7294: if ($env{'form.saveState'}) {
7295: foreach (split(/:/,$env{'form.saveState'})) {
7296: my ($key,$value) = split(/=/,$_,2);
7297: $savedState{$key} = $value;
7298: }
7299: }
7300: return \%savedState;
7301: }
7302:
7303: sub grading_menu {
7304: my ($request) = @_;
7305: my ($symb)=&get_symb($request);
7306: if (!$symb) {return '';}
7307: my $probTitle = &Apache::lonnet::gettitle($symb);
7308: my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
7309:
7310: $request->print($table);
7311: my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
7312: 'handgrade'=>$hdgrade,
7313: 'probTitle'=>$probTitle,
7314: 'command'=>'submit_options',
7315: 'saveState'=>"",
7316: 'gradingMenu'=>1,
7317: 'showgrading'=>"yes");
7318: my $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
7319: my @menu = ({ url => $url,
7320: name => &mt('Manual Grading/View Submissions'),
7321: short_description =>
7322: &mt('Start the process of hand grading submissions.'),
7323: });
7324: $fields{'command'} = 'csvform';
7325: $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
7326: push (@menu, { url => $url,
7327: name => &mt('Upload Scores'),
7328: short_description =>
7329: &mt('Specify a file containing the class scores for current resource.')});
7330: $fields{'command'} = 'processclicker';
7331: $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
7332: push (@menu, { url => $url,
7333: name => &mt('Process Clicker'),
7334: short_description =>
7335: &mt('Specify a file containing the clicker information for this resource.')});
7336: $fields{'command'} = 'scantron_selectphase';
7337: $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
7338: push (@menu, { url => $url,
7339: name => &mt('Grade/Manage Scantron Forms'),
7340: short_description =>
7341: &mt('')});
7342: $fields{'command'} = 'verify';
7343: $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
7344: push (@menu, { url => "",
7345: name => &mt('Verify Receipt'),
7346: short_description =>
7347: &mt('')});
7348: #
7349: # Create the menu
7350: my $Str;
7351: # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
7352: $Str .= '<form method="post" action="" name="gradingMenu">';
7353: $Str .= '<input type="hidden" name="command" value="" />'.
7354: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
7355: '<input type="hidden" name="handgrade" value="'.$hdgrade.'" />'."\n".
7356: '<input type="hidden" name="probTitle" value="'.$probTitle.'" />'."\n".
7357: '<input type="hidden" name="saveState" value="" />'."\n".
7358: '<input type="hidden" name="gradingMenu" value="1" />'."\n".
7359: '<input type="hidden" name="showgrading" value="yes" />'."\n";
7360:
7361: foreach my $menudata (@menu) {
7362: if ($menudata->{'name'} ne &mt('Verify Receipt')) {
7363: $Str .=' <h3><a '.
7364: $menudata->{'jscript'}.
7365: ' href="'.
7366: $menudata->{'url'}.'" >'.
7367: $menudata->{'name'}."</a></h3>\n";
7368: } else {
7369: $Str .=' <h3><input type="button" value="Verify Receipt" '.
7370: $menudata->{'jscript'}.
7371: ' onClick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
7372: ' /></h3>';
7373: $Str .= (' 'x8).
7374: ' receipt: '.&Apache::lonnet::recprefix($env{'request.course.id'}).
7375: '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
7376: }
7377: $Str .= ' '.(' 'x8).$menudata->{'short_description'}.
7378: "\n";
7379: }
7380: $Str .="</form>\n";
7381: $request->print(<<GRADINGMENUJS);
7382: <script type="text/javascript" language="javascript">
7383: function checkChoice(formname,val,cmdx) {
7384: if (val <= 2) {
7385: var cmd = radioSelection(formname.radioChoice);
7386: var cmdsave = cmd;
7387: } else {
7388: cmd = cmdx;
7389: cmdsave = 'submission';
7390: }
7391: formname.command.value = cmd;
7392: if (val < 5) formname.submit();
7393: if (val == 5) {
7394: if (!checkReceiptNo(formname,'notOK')) {
7395: return false;
7396: } else {
7397: formname.submit();
7398: }
7399: }
7400: }
7401:
7402: function checkReceiptNo(formname,nospace) {
7403: var receiptNo = formname.receipt.value;
7404: var checkOpt = false;
7405: if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
7406: if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
7407: if (checkOpt) {
7408: alert("Please enter a receipt number given by a student in the receipt box.");
7409: formname.receipt.value = "";
7410: formname.receipt.focus();
7411: return false;
7412: }
7413: return true;
7414: }
7415: </script>
7416: GRADINGMENUJS
7417: &commonJSfunctions($request);
7418: return $Str;
7419: }
7420:
7421:
7422: #--- Displays the submissions first page -------
7423: sub submit_options {
7424: my ($request) = @_;
7425: my ($symb)=&get_symb($request);
7426: if (!$symb) {return '';}
7427: my $probTitle = &Apache::lonnet::gettitle($symb);
7428:
7429: $request->print(<<GRADINGMENUJS);
7430: <script type="text/javascript" language="javascript">
7431: function checkChoice(formname,val,cmdx) {
7432: if (val <= 2) {
7433: var cmd = radioSelection(formname.radioChoice);
7434: var cmdsave = cmd;
7435: } else {
7436: cmd = cmdx;
7437: cmdsave = 'submission';
7438: }
7439: formname.command.value = cmd;
7440: formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
7441: ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
7442: if (val < 5) formname.submit();
7443: if (val == 5) {
7444: if (!checkReceiptNo(formname,'notOK')) { return false;}
7445: formname.submit();
7446: }
7447: if (val < 7) formname.submit();
7448: }
7449:
7450: function checkReceiptNo(formname,nospace) {
7451: var receiptNo = formname.receipt.value;
7452: var checkOpt = false;
7453: if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
7454: if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
7455: if (checkOpt) {
7456: alert("Please enter a receipt number given by a student in the receipt box.");
7457: formname.receipt.value = "";
7458: formname.receipt.focus();
7459: return false;
7460: }
7461: return true;
7462: }
7463: </script>
7464: GRADINGMENUJS
7465: &commonJSfunctions($request);
7466: my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
7467: my $result;
7468: my (undef,$sections) = &getclasslist('all','0');
7469: my $savedState = &savedState();
7470: my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
7471: my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
7472: my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
7473: my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
7474:
7475: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
7476: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
7477: '<input type="hidden" name="handgrade" value="'.$hdgrade.'" />'."\n".
7478: '<input type="hidden" name="probTitle" value="'.$probTitle.'" />'."\n".
7479: '<input type="hidden" name="command" value="" />'."\n".
7480: '<input type="hidden" name="saveState" value="" />'."\n".
7481: '<input type="hidden" name="gradingMenu" value="1" />'."\n".
7482: '<input type="hidden" name="showgrading" value="yes" />'."\n";
7483:
7484: $result.='
7485: <div class="LC_grade_select_mode">
7486: <div class="LC_grade_select_mode_current">
7487: <h2>
7488: '.&mt('Grade Current Resource').'
7489: </h2>
7490: <div class="LC_grade_select_mode_body">
7491: <div class="LC_grades_resource_info">
7492: '.$table.'
7493: </div>
7494: <div class="LC_grade_select_mode_selector">
7495: <div class="LC_grade_select_mode_selector_header">
7496: '.&mt('Sections').'
7497: </div>
7498: <div class="LC_grade_select_mode_selector_body">
7499: <select name="section" multiple="multiple" size="5">'."\n";
7500: if (ref($sections)) {
7501: foreach my $section (sort (@$sections)) {
7502: $result.='<option value="'.$section.'" '.
7503: ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
7504: }
7505: }
7506: $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> ';
7507: $result.='
7508: </div>
7509: </div>
7510: <div class="LC_grade_select_mode_selector">
7511: <div class="LC_grade_select_mode_selector_header">
7512: '.&mt('Groups').'
7513: </div>
7514: <div class="LC_grade_select_mode_selector_body">
7515: '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
7516: </div>
7517: </div>
7518: <div class="LC_grade_select_mode_selector">
7519: <div class="LC_grade_select_mode_selector_header">
7520: '.&mt('Access Status').'
7521: </div>
7522: <div class="LC_grade_select_mode_selector_body">
7523: '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
7524: </div>
7525: </div>
7526: <div class="LC_grade_select_mode_selector">
7527: <div class="LC_grade_select_mode_selector_header">
7528: '.&mt('Submission Status').'
7529: </div>
7530: <div class="LC_grade_select_mode_selector_body">
7531: <select name="submitonly" size="5">
7532: <option value="yes" '. ($saveSub eq 'yes' ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
7533: <option value="queued" '. ($saveSub eq 'queued' ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
7534: <option value="graded" '. ($saveSub eq 'graded' ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
7535: <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
7536: <option value="all" '. ($saveSub eq 'all' ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
7537: </select>
7538: </div>
7539: </div>
7540: <div class="LC_grade_select_mode_type_body">
7541: <div class="LC_grade_select_mode_type">
7542: <label>
7543: <input type="radio" name="radioChoice" value="submission" '.
7544: ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
7545: &mt('Select individual students to grade and view submissions.').'
7546: </label>
7547: </div>
7548: <div class="LC_grade_select_mode_type">
7549: <label>
7550: <input type="radio" name="radioChoice" value="viewgrades" '.
7551: ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
7552: &mt('Grade all selected students in a grading table.').'
7553: </label>
7554: </div>
7555: <div class="LC_grade_select_mode_type">
7556: <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next->').'" />
7557: </div>
7558: </div>
7559: </div>
7560: </div>
7561: <div class="LC_grade_select_mode_page">
7562: <h2>
7563: '.&mt('Grade Complete Folder for One Student').'
7564: </h2>
7565: <div class="LC_grades_select_mode_body">
7566: <div class="LC_grade_select_mode_type_body">
7567: <div class="LC_grade_select_mode_type">
7568: <label>
7569: <input type="radio" name="radioChoice" value="pickStudentPage" '.
7570: ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
7571: &mt('The <b>complete</b> page/sequence/folder: For one student').'
7572: </label>
7573: </div>
7574: <div class="LC_grade_select_mode_type">
7575: <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next->').'" />
7576: </div>
7577: </div>
7578: </div>
7579: </div>
7580: </div>
7581: </form>';
7582: return $result;
7583: }
7584:
7585: sub reset_perm {
7586: undef(%perm);
7587: }
7588:
7589: sub init_perm {
7590: &reset_perm();
7591: foreach my $test_perm ('vgr','mgr','opa') {
7592:
7593: my $scope = $env{'request.course.id'};
7594: if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
7595:
7596: $scope .= '/'.$env{'request.course.sec'};
7597: if ( $perm{$test_perm}=
7598: &Apache::lonnet::allowed($test_perm,$scope)) {
7599: $perm{$test_perm.'_section'}=$env{'request.course.sec'};
7600: } else {
7601: delete($perm{$test_perm});
7602: }
7603: }
7604: }
7605: }
7606:
7607: sub gather_clicker_ids {
7608: my %clicker_ids;
7609:
7610: my $classlist = &Apache::loncoursedata::get_classlist();
7611:
7612: # Set up a couple variables.
7613: my $username_idx = &Apache::loncoursedata::CL_SNAME();
7614: my $domain_idx = &Apache::loncoursedata::CL_SDOM();
7615: my $status_idx = &Apache::loncoursedata::CL_STATUS();
7616:
7617: foreach my $student (keys(%$classlist)) {
7618: if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
7619: my $username = $classlist->{$student}->[$username_idx];
7620: my $domain = $classlist->{$student}->[$domain_idx];
7621: my $clickers =
7622: (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
7623: foreach my $id (split(/\,/,$clickers)) {
7624: $id=~s/^[\#0]+//;
7625: $id=~s/[\-\:]//g;
7626: if (exists($clicker_ids{$id})) {
7627: $clicker_ids{$id}.=','.$username.':'.$domain;
7628: } else {
7629: $clicker_ids{$id}=$username.':'.$domain;
7630: }
7631: }
7632: }
7633: return %clicker_ids;
7634: }
7635:
7636: sub gather_adv_clicker_ids {
7637: my %clicker_ids;
7638: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
7639: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7640: my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
7641: foreach my $element (sort(keys(%coursepersonnel))) {
7642: foreach my $person (split(/\,/,$coursepersonnel{$element})) {
7643: my ($puname,$pudom)=split(/\:/,$person);
7644: my $clickers =
7645: (&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
7646: foreach my $id (split(/\,/,$clickers)) {
7647: $id=~s/^[\#0]+//;
7648: $id=~s/[\-\:]//g;
7649: if (exists($clicker_ids{$id})) {
7650: $clicker_ids{$id}.=','.$puname.':'.$pudom;
7651: } else {
7652: $clicker_ids{$id}=$puname.':'.$pudom;
7653: }
7654: }
7655: }
7656: }
7657: return %clicker_ids;
7658: }
7659:
7660: sub clicker_grading_parameters {
7661: return ('gradingmechanism' => 'scalar',
7662: 'upfiletype' => 'scalar',
7663: 'specificid' => 'scalar',
7664: 'pcorrect' => 'scalar',
7665: 'pincorrect' => 'scalar');
7666: }
7667:
7668: sub process_clicker {
7669: my ($r)=@_;
7670: my ($symb)=&get_symb($r);
7671: if (!$symb) {return '';}
7672: my $result=&checkforfile_js();
7673: $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
7674: my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
7675: $result.=$table;
7676: $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
7677: $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
7678: $result.=' <b>'.&mt('Specify a file containing the clicker information for this resource').
7679: '.</b></td></tr>'."\n";
7680: $result.='<tr bgcolor=#ffffe6><td>'."\n";
7681: # Attempt to restore parameters from last session, set defaults if not present
7682: my %Saveable_Parameters=&clicker_grading_parameters();
7683: &Apache::loncommon::restore_course_settings('grades_clicker',
7684: \%Saveable_Parameters);
7685: if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
7686: if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
7687: if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
7688: if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
7689:
7690: my %checked;
7691: foreach my $gradingmechanism ('attendance','personnel','specific') {
7692: if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
7693: $checked{$gradingmechanism}="checked='checked'";
7694: }
7695: }
7696:
7697: my $upload=&mt("Upload File");
7698: my $type=&mt("Type");
7699: my $attendance=&mt("Award points just for participation");
7700: my $personnel=&mt("Correctness determined from response by course personnel");
7701: my $specific=&mt("Correctness determined from response with clicker ID(s)");
7702: my $pcorrect=&mt("Percentage points for correct solution");
7703: my $pincorrect=&mt("Percentage points for incorrect solution");
7704: my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
7705: ('iclicker' => 'i>clicker',
7706: 'interwrite' => 'interwrite PRS'));
7707: $symb = &Apache::lonenc::check_encrypt($symb);
7708: $result.=<<ENDUPFORM;
7709: <script type="text/javascript">
7710: function sanitycheck() {
7711: // Accept only integer percentages
7712: document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
7713: document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
7714: // Find out grading choice
7715: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
7716: if (document.forms.gradesupload.gradingmechanism[i].checked) {
7717: gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
7718: }
7719: }
7720: // By default, new choice equals user selection
7721: newgradingchoice=gradingchoice;
7722: // Not good to give more points for false answers than correct ones
7723: if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
7724: document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
7725: }
7726: // If new choice is attendance only, and old choice was correctness-based, restore defaults
7727: if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
7728: document.forms.gradesupload.pcorrect.value=100;
7729: document.forms.gradesupload.pincorrect.value=100;
7730: }
7731: // If the values are different, cannot be attendance only
7732: if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
7733: (gradingchoice=='attendance')) {
7734: newgradingchoice='personnel';
7735: }
7736: // Change grading choice to new one
7737: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
7738: if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
7739: document.forms.gradesupload.gradingmechanism[i].checked=true;
7740: } else {
7741: document.forms.gradesupload.gradingmechanism[i].checked=false;
7742: }
7743: }
7744: // Remember the old state
7745: document.forms.gradesupload.waschecked.value=newgradingchoice;
7746: }
7747: </script>
7748: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
7749: <input type="hidden" name="symb" value="$symb" />
7750: <input type="hidden" name="command" value="processclickerfile" />
7751: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
7752: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
7753: <input type="file" name="upfile" size="50" />
7754: <br /><label>$type: $selectform</label>
7755: <br /><label><input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
7756: <br /><label><input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
7757: <br /><label><input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" />$specific </label>
7758: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
7759: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
7760: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
7761: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
7762: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
7763: </form>
7764: ENDUPFORM
7765: $result.='</td></tr></table>'."\n".
7766: '</td></tr></table><br /><br />'."\n";
7767: $result.=&show_grading_menu_form($symb);
7768: return $result;
7769: }
7770:
7771: sub process_clicker_file {
7772: my ($r)=@_;
7773: my ($symb)=&get_symb($r);
7774: if (!$symb) {return '';}
7775:
7776: my %Saveable_Parameters=&clicker_grading_parameters();
7777: &Apache::loncommon::store_course_settings('grades_clicker',
7778: \%Saveable_Parameters);
7779:
7780: my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
7781: if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
7782: $result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
7783: return $result.&show_grading_menu_form($symb);
7784: }
7785: my %clicker_ids=&gather_clicker_ids();
7786: my %correct_ids;
7787: if ($env{'form.gradingmechanism'} eq 'personnel') {
7788: %correct_ids=&gather_adv_clicker_ids();
7789: }
7790: if ($env{'form.gradingmechanism'} eq 'specific') {
7791: foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
7792: $correct_id=~tr/a-z/A-Z/;
7793: $correct_id=~s/\s//gs;
7794: $correct_id=~s/^[\#0]+//;
7795: $correct_id=~s/[\-\:]//g;
7796: if ($correct_id) {
7797: $correct_ids{$correct_id}='specified';
7798: }
7799: }
7800: }
7801: if ($env{'form.gradingmechanism'} eq 'attendance') {
7802: $result.=&mt('Score based on attendance only');
7803: } else {
7804: my $number=0;
7805: $result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
7806: foreach my $id (sort(keys(%correct_ids))) {
7807: $result.='<br /><tt>'.$id.'</tt> - ';
7808: if ($correct_ids{$id} eq 'specified') {
7809: $result.=&mt('specified');
7810: } else {
7811: my ($uname,$udom)=split(/\:/,$correct_ids{$id});
7812: $result.=&Apache::loncommon::plainname($uname,$udom);
7813: }
7814: $number++;
7815: }
7816: $result.="</p>\n";
7817: if ($number==0) {
7818: $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
7819: return $result.&show_grading_menu_form($symb);
7820: }
7821: }
7822: if (length($env{'form.upfile'}) < 2) {
7823: $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
7824: '<span class="LC_error">',
7825: '</span>',
7826: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
7827: return $result.&show_grading_menu_form($symb);
7828: }
7829:
7830: # Were able to get all the info needed, now analyze the file
7831:
7832: $result.=&Apache::loncommon::studentbrowser_javascript();
7833: $symb = &Apache::lonenc::check_encrypt($symb);
7834: my $heading=&mt('Scanning clicker file');
7835: $result.=(<<ENDHEADER);
7836: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
7837: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
7838: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
7839: <form method="post" action="/adm/grades" name="clickeranalysis">
7840: <input type="hidden" name="symb" value="$symb" />
7841: <input type="hidden" name="command" value="assignclickergrades" />
7842: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
7843: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
7844: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
7845: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
7846: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
7847: ENDHEADER
7848: my %responses;
7849: my @questiontitles;
7850: my $errormsg='';
7851: my $number=0;
7852: if ($env{'form.upfiletype'} eq 'iclicker') {
7853: ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
7854: }
7855: if ($env{'form.upfiletype'} eq 'interwrite') {
7856: ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
7857: }
7858: $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
7859: '<input type="hidden" name="number" value="'.$number.'" />'.
7860: &mt('Awarding [_1] percent for corrion(s)',$number).'<br />'.
7861: '<input type="hidden" name="number" value="'.$number.'" />'.
7862: &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
7863: $env{'form.pcorrect'},$env{'form.pincorrect'}).
7864: '<br />';
7865: # Remember Question Titles
7866: # FIXME: Possibly need delimiter other than ":"
7867: for (my $i=0;$i<$number;$i++) {
7868: $result.='<input type="hidden" name="question:'.$i.'" value="'.
7869: &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
7870: }
7871: my $correct_count=0;
7872: my $student_count=0;
7873: my $unknown_count=0;
7874: # Match answers with usernames
7875: # FIXME: Possibly need delimiter other than ":"
7876: foreach my $id (keys(%responses)) {
7877: if ($correct_ids{$id}) {
7878: $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
7879: $correct_count++;
7880: } elsif ($clicker_ids{$id}) {
7881: if ($clicker_ids{$id}=~/\,/) {
7882: # More than one user with the same clicker!
7883: $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
7884: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
7885: "<select name='multi".$id."'>";
7886: foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
7887: $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
7888: }
7889: $result.='</select>';
7890: $unknown_count++;
7891: } else {
7892: # Good: found one and only one user with the right clicker
7893: $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
7894: $student_count++;
7895: }
7896: } else {
7897: $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
7898: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
7899: "\n".&mt("Username").": <input type='text' name='uname".$id."' /> ".
7900: "\n".&mt("Domain").": ".
7901: &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).' '.
7902: &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
7903: $unknown_count++;
7904: }
7905: }
7906: $result.='<hr />'.
7907: &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
7908: if ($env{'form.gradingmechanism'} ne 'attendance') {
7909: if ($correct_count==0) {
7910: $errormsg.="Found no correct answers answers for grading!";
7911: } elsif ($correct_count>1) {
7912: $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
7913: }
7914: }
7915: if ($number<1) {
7916: $errormsg.="Found no questions.";
7917: }
7918: if ($errormsg) {
7919: $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
7920: } else {
7921: $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
7922: }
7923: $result.='</form></td></tr></table>'."\n".
7924: '</td></tr></table><br /><br />'."\n";
7925: return $result.&show_grading_menu_form($symb);
7926: }
7927:
7928: sub iclicker_eval {
7929: my ($questiontitles,$responses)=@_;
7930: my $number=0;
7931: my $errormsg='';
7932: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
7933: my %components=&Apache::loncommon::record_sep($line);
7934: my @entries=map {$components{$_}} (sort(keys(%components)));
7935: if ($entries[0] eq 'Question') {
7936: for (my $i=3;$i<$#entries;$i+=6) {
7937: $$questiontitles[$number]=$entries[$i];
7938: $number++;
7939: }
7940: }
7941: if ($entries[0]=~/^\#/) {
7942: my $id=$entries[0];
7943: my @idresponses;
7944: $id=~s/^[\#0]+//;
7945: for (my $i=0;$i<$number;$i++) {
7946: my $idx=3+$i*6;
7947: push(@idresponses,$entries[$idx]);
7948: }
7949: $$responses{$id}=join(',',@idresponses);
7950: }
7951: }
7952: return ($errormsg,$number);
7953: }
7954:
7955: sub interwrite_eval {
7956: my ($questiontitles,$responses)=@_;
7957: my $number=0;
7958: my $errormsg='';
7959: my $skipline=1;
7960: my $questionnumber=0;
7961: my %idresponses=();
7962: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
7963: my %components=&Apache::loncommon::record_sep($line);
7964: my @entries=map {$components{$_}} (sort(keys(%components)));
7965: if ($entries[1] eq 'Time') { $skipline=0; next; }
7966: if ($entries[1] eq 'Response') { $skipline=1; }
7967: next if $skipline;
7968: if ($entries[0]!=$questionnumber) {
7969: $questionnumber=$entries[0];
7970: $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
7971: $number++;
7972: }
7973: my $id=$entries[4];
7974: $id=~s/^[\#0]+//;
7975: $id=~s/^v\d*\://i;
7976: $id=~s/[\-\:]//g;
7977: $idresponses{$id}[$number]=$entries[6];
7978: }
7979: foreach my $id (keys %idresponses) {
7980: $$responses{$id}=join(',',@{$idresponses{$id}});
7981: $$responses{$id}=~s/^\s*\,//;
7982: }
7983: return ($errormsg,$number);
7984: }
7985:
7986: sub assign_clicker_grades {
7987: my ($r)=@_;
7988: my ($symb)=&get_symb($r);
7989: if (!$symb) {return '';}
7990: # See which part we are saving to
7991: my ($partlist,$handgrade,$responseType) = &response_type($symb);
7992: # FIXME: This should probably look for the first handgradeable part
7993: my $part=$$partlist[0];
7994: # Start screen output
7995: my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
7996:
7997: my $heading=&mt('Assigning grades based on clicker file');
7998: $result.=(<<ENDHEADER);
7999: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
8000: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
8001: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
8002: ENDHEADER
8003: # Get correct result
8004: # FIXME: Possibly need delimiter other than ":"
8005: my @correct=();
8006: my $gradingmechanism=$env{'form.gradingmechanism'};
8007: my $number=$env{'form.number'};
8008: if ($gradingmechanism ne 'attendance') {
8009: foreach my $key (keys(%env)) {
8010: if ($key=~/^form\.correct\:/) {
8011: my @input=split(/\,/,$env{$key});
8012: for (my $i=0;$i<=$#input;$i++) {
8013: if (($correct[$i]) && ($input[$i]) &&
8014: ($correct[$i] ne $input[$i])) {
8015: $result.='<br /><span class="LC_warning">'.
8016: &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
8017: $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
8018: } elsif ($input[$i]) {
8019: $correct[$i]=$input[$i];
8020: }
8021: }
8022: }
8023: }
8024: for (my $i=0;$i<$number;$i++) {
8025: if (!$correct[$i]) {
8026: $result.='<br /><span class="LC_error">'.
8027: &mt('No correct result given for question "[_1]"!',
8028: $env{'form.question:'.$i}).'</span>';
8029: }
8030: }
8031: $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
8032: }
8033: # Start grading
8034: my $pcorrect=$env{'form.pcorrect'};
8035: my $pincorrect=$env{'form.pincorrect'};
8036: my $storecount=0;
8037: foreach my $key (keys(%env)) {
8038: my $user='';
8039: if ($key=~/^form\.student\:(.*)$/) {
8040: $user=$1;
8041: }
8042: if ($key=~/^form\.unknown\:(.*)$/) {
8043: my $id=$1;
8044: if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
8045: $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
8046: } elsif ($env{'form.multi'.$id}) {
8047: $user=$env{'form.multi'.$id};
8048: }
8049: }
8050: if ($user) {
8051: my @answer=split(/\,/,$env{$key});
8052: my $sum=0;
8053: for (my $i=0;$i<$number;$i++) {
8054: if ($answer[$i]) {
8055: if ($gradingmechanism eq 'attendance') {
8056: $sum+=$pcorrect;
8057: } else {
8058: if ($answer[$i] eq $correct[$i]) {
8059: $sum+=$pcorrect;
8060: } else {
8061: $sum+=$pincorrect;
8062: }
8063: }
8064: }
8065: }
8066: my $ave=$sum/(100*$number);
8067: # Store
8068: my ($username,$domain)=split(/\:/,$user);
8069: my %grades=();
8070: $grades{"resource.$part.solved"}='correct_by_override';
8071: $grades{"resource.$part.awarded"}=$ave;
8072: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
8073: my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
8074: $env{'request.course.id'},
8075: $domain,$username);
8076: if ($returncode ne 'ok') {
8077: $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
8078: } else {
8079: $storecount++;
8080: }
8081: }
8082: }
8083: # We are done
8084: $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
8085: '</td></tr></table>'."\n".
8086: '</td></tr></table><br /><br />'."\n";
8087: return $result.&show_grading_menu_form($symb);
8088: }
8089:
8090: sub handler {
8091: my $request=$_[0];
8092: &reset_caches();
8093: if ($env{'browser.mathml'}) {
8094: &Apache::loncommon::content_type($request,'text/xml');
8095: } else {
8096: &Apache::loncommon::content_type($request,'text/html');
8097: }
8098: $request->send_http_header;
8099: return '' if $request->header_only;
8100: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
8101: my $symb=&get_symb($request,1);
8102: my @commands=&Apache::loncommon::get_env_multiple('form.command');
8103: my $command=$commands[0];
8104:
8105: if ($#commands > 0) {
8106: &Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
8107: }
8108:
8109:
8110: $request->print(&Apache::loncommon::start_page('Grading'));
8111: if ($symb eq '' && $command eq '') {
8112: if ($env{'user.adv'}) {
8113: if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
8114: ($env{'form.codethree'})) {
8115: my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
8116: $env{'form.codethree'};
8117: my ($tsymb,$tuname,$tudom,$tcrsid)=
8118: &Apache::lonnet::checkin($token);
8119: if ($tsymb) {
8120: my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
8121: if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
8122: $request->print(&Apache::lonnet::ssi_body('/res/'.$url,
8123: ('grade_username' => $tuname,
8124: 'grade_domain' => $tudom,
8125: 'grade_courseid' => $tcrsid,
8126: 'grade_symb' => $tsymb)));
8127: } else {
8128: $request->print('<h3>Not authorized: '.$token.'</h3>');
8129: }
8130: } else {
8131: $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
8132: }
8133: } else {
8134: $request->print(&Apache::lonxml::tokeninputfield());
8135: }
8136: }
8137: } else {
8138: &init_perm();
8139: if ($command eq 'submission' && $perm{'vgr'}) {
8140: ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
8141: } elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
8142: &pickStudentPage($request);
8143: } elsif ($command eq 'displayPage' && $perm{'vgr'}) {
8144: &displayPage($request);
8145: } elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
8146: &updateGradeByPage($request);
8147: } elsif ($command eq 'processGroup' && $perm{'vgr'}) {
8148: &processGroup($request);
8149: } elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
8150: $request->print(&grading_menu($request));
8151: } elsif ($command eq 'submit_options' && $perm{'vgr'}) {
8152: $request->print(&submit_options($request));
8153: } elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
8154: $request->print(&viewgrades($request));
8155: } elsif ($command eq 'handgrade' && $perm{'mgr'}) {
8156: $request->print(&processHandGrade($request));
8157: } elsif ($command eq 'editgrades' && $perm{'mgr'}) {
8158: $request->print(&editgrades($request));
8159: } elsif ($command eq 'verify' && $perm{'vgr'}) {
8160: $request->print(&verifyreceipt($request));
8161: } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
8162: $request->print(&process_clicker($request));
8163: } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
8164: $request->print(&process_clicker_file($request));
8165: } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
8166: $request->print(&assign_clicker_grades($request));
8167: } elsif ($command eq 'csvform' && $perm{'mgr'}) {
8168: $request->print(&upcsvScores_form($request));
8169: } elsif ($command eq 'csvupload' && $perm{'mgr'}) {
8170: $request->print(&csvupload($request));
8171: } elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
8172: $request->print(&csvuploadmap($request));
8173: } elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
8174: if ($env{'form.associate'} ne 'Reverse Association') {
8175: $request->print(&csvuploadoptions($request));
8176: } else {
8177: if ( $env{'form.upfile_associate'} ne 'reverse' ) {
8178: $env{'form.upfile_associate'} = 'reverse';
8179: } else {
8180: $env{'form.upfile_associate'} = 'forward';
8181: }
8182: $request->print(&csvuploadmap($request));
8183: }
8184: } elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
8185: $request->print(&csvuploadassign($request));
8186: } elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
8187: $request->print(&scantron_selectphase($request));
8188: } elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
8189: $request->print(&scantron_do_warning($request));
8190: } elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
8191: $request->print(&scantron_validate_file($request));
8192: } elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
8193: $request->print(&scantron_process_students($request));
8194: } elsif ($command eq 'scantronupload' &&
8195: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
8196: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
8197: $request->print(&scantron_upload_scantron_data($request));
8198: } elsif ($command eq 'scantronupload_save' &&
8199: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
8200: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
8201: $request->print(&scantron_upload_scantron_data_save($request));
8202: } elsif ($command eq 'scantron_download' &&
8203: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
8204: $request->print(&scantron_download_scantron_data($request));
8205: } elsif ($command) {
8206: $request->print("Access Denied ($command)");
8207: }
8208: }
8209: $request->print(&Apache::loncommon::end_page());
8210: &reset_caches();
8211: return '';
8212: }
8213:
8214: 1;
8215:
8216: __END__;
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>