1: # The LearningOnline Network with CAPA
2: # The LON-CAPA Grading handler
3: #
4: # $Id: grades.pm,v 1.470 2007/10/29 09:46:28 foxr Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28:
29: package Apache::grades;
30: use strict;
31: use Apache::style;
32: use Apache::lonxml;
33: use Apache::lonnet;
34: use Apache::loncommon;
35: use Apache::lonhtmlcommon;
36: use Apache::lonnavmaps;
37: use Apache::lonhomework;
38: use Apache::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.='<table border="0"><tr><td bgcolor="#777777">'.
906: '<table border="0"><tr bgcolor="#e6ffff">';
907: my $loop = 0;
908: while ($loop < 2) {
909: $gradeTable.='<td><b> No.</b> </td><td><b> Select </b></td>'.
910: '<td>'.&nameUserString('header').' Section/Group</td>';
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.='<td><b> Part: '.$display_part.
917: ' Status </b></td>';
918: }
919: } elsif ($submitonly eq 'queued') {
920: $gradeTable.='<td><b> '.&mt('Queue Status').' </b></td>';
921: }
922: $loop++;
923: # $gradeTable.='<td></td>' if ($loop%2 ==1);
924: }
925: $gradeTable.='</tr>'."\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: $gradeTable.='<tr bgcolor="#ffffe6">' if ($ctr%2 ==1);
982: $gradeTable.='<td align="right">'.$ctr.' </td>'.
983: '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
984: $student.':'.$$fullname{$student}.':::SECTION'.$section.
985: ') " /> </label></td>'."\n".'<td>'.
986: &nameUserString(undef,$$fullname{$student},$uname,$udom).
987: ' '.$section.'/'.$group.'</td>'."\n";
988:
989: if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
990: foreach (sort keys(%status)) {
991: next if (/^resource.*?submitted_by$/);
992: $gradeTable.='<td align="center"> '.$status{$_}.' </td>'."\n";
993: }
994: }
995: # $gradeTable.='<td></td>' if ($ctr%2 ==1);
996: $gradeTable.='</tr>'."\n" if ($ctr%2 ==0);
997: }
998: }
999: if ($ctr%2 ==1) {
1000: $gradeTable.='<td> </td><td> </td><td> </td>';
1001: if ($env{'form.showgrading'} eq 'yes'
1002: && $submitonly ne 'queued'
1003: && $submitonly ne 'all') {
1004: foreach (@$partlist) {
1005: $gradeTable.='<td> </td>';
1006: }
1007: } elsif ($submitonly eq 'queued') {
1008: $gradeTable.='<td> </td>';
1009: }
1010: $gradeTable.='</tr>';
1011: }
1012:
1013: $gradeTable.='</table></td></tr></table>'."\n".
1014: '<input type="button" '.
1015: 'onClick="javascript:checkSelect(this.form.stuinfo);" '.
1016: 'value="Next->" /></form>'."\n";
1017: if ($ctr == 0) {
1018: my $num_students=(scalar(keys(%$fullname)));
1019: if ($num_students eq 0) {
1020: $gradeTable='<br /> <span class="LC_warning">There are no students currently enrolled.</span>';
1021: } else {
1022: my $submissions='submissions';
1023: if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
1024: if ($submitonly eq 'graded' ) { $submissions = 'ungraded submissions'; }
1025: if ($submitonly eq 'queued' ) { $submissions = 'queued submissions'; }
1026: $gradeTable='<br /> <span class="LC_warning">'.
1027: 'No '.$submissions.' found for this resource for any students. ('.$num_students.
1028: ' students checked for '.$submissions.')</span><br />';
1029: }
1030: } elsif ($ctr == 1) {
1031: $gradeTable =~ s/type=checkbox/type=checkbox checked/;
1032: }
1033: $gradeTable.=&show_grading_menu_form($symb);
1034: $request->print($gradeTable);
1035: return '';
1036: }
1037:
1038: #---- Called from the listStudents routine
1039:
1040: sub check_script {
1041: my ($form, $type)=@_;
1042: my $chkallscript='<script type="text/javascript">
1043: function checkall() {
1044: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1045: ele = document.forms.'.$form.'.elements[i];
1046: if (ele.name == "'.$type.'") {
1047: document.forms.'.$form.'.elements[i].checked=true;
1048: }
1049: }
1050: }
1051:
1052: function checksec() {
1053: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1054: ele = document.forms.'.$form.'.elements[i];
1055: string = document.forms.'.$form.'.chksec.value;
1056: if
1057: (ele.value.indexOf(":::SECTION"+string)>0) {
1058: document.forms.'.$form.'.elements[i].checked=true;
1059: }
1060: }
1061: }
1062:
1063:
1064: function uncheckall() {
1065: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1066: ele = document.forms.'.$form.'.elements[i];
1067: if (ele.name == "'.$type.'") {
1068: document.forms.'.$form.'.elements[i].checked=false;
1069: }
1070: }
1071: }
1072:
1073: </script>'."\n";
1074: return $chkallscript;
1075: }
1076:
1077: sub check_buttons {
1078: my $buttons.='<input type="button" onclick="checkall()" value="Check All" />';
1079: $buttons.='<input type="button" onclick="uncheckall()" value="Uncheck All" /> ';
1080: $buttons.='<input type="button" onclick="checksec()" value="Check Section/Group" />';
1081: $buttons.='<input type="text" size="5" name="chksec" /> ';
1082: return $buttons;
1083: }
1084:
1085: # Displays the submissions for one student or a group of students
1086: sub processGroup {
1087: my ($request) = shift;
1088: my $ctr = 0;
1089: my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1090: my $total = scalar(@stuchecked)-1;
1091:
1092: foreach my $student (@stuchecked) {
1093: my ($uname,$udom,$fullname) = split(/:/,$student);
1094: $env{'form.student'} = $uname;
1095: $env{'form.userdom'} = $udom;
1096: $env{'form.fullname'} = $fullname;
1097: &submission($request,$ctr,$total);
1098: $ctr++;
1099: }
1100: return '';
1101: }
1102:
1103: #------------------------------------------------------------------------------------
1104: #
1105: #-------------------------- Next few routines handles grading by student, essentially
1106: # handles essay response type problem/part
1107: #
1108: #--- Javascript to handle the submission page functionality ---
1109: sub sub_page_js {
1110: my $request = shift;
1111: $request->print(<<SUBJAVASCRIPT);
1112: <script type="text/javascript" language="javascript">
1113: function updateRadio(formname,id,weight) {
1114: var gradeBox = formname["GD_BOX"+id];
1115: var radioButton = formname["RADVAL"+id];
1116: var oldpts = formname["oldpts"+id].value;
1117: var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1118: gradeBox.value = pts;
1119: var resetbox = false;
1120: if (isNaN(pts) || pts < 0) {
1121: alert("A number equal or greater than 0 is expected. Entered value = "+pts);
1122: for (var i=0; i<radioButton.length; i++) {
1123: if (radioButton[i].checked) {
1124: gradeBox.value = i;
1125: resetbox = true;
1126: }
1127: }
1128: if (!resetbox) {
1129: formtextbox.value = "";
1130: }
1131: return;
1132: }
1133:
1134: if (pts > weight) {
1135: var resp = confirm("You entered a value ("+pts+
1136: ") greater than the weight for the part. Accept?");
1137: if (resp == false) {
1138: gradeBox.value = oldpts;
1139: return;
1140: }
1141: }
1142:
1143: for (var i=0; i<radioButton.length; i++) {
1144: radioButton[i].checked=false;
1145: if (pts == i && pts != "") {
1146: radioButton[i].checked=true;
1147: }
1148: }
1149: updateSelect(formname,id);
1150: formname["stores"+id].value = "0";
1151: }
1152:
1153: function writeBox(formname,id,pts) {
1154: var gradeBox = formname["GD_BOX"+id];
1155: if (checkSolved(formname,id) == 'update') {
1156: gradeBox.value = pts;
1157: } else {
1158: var oldpts = formname["oldpts"+id].value;
1159: gradeBox.value = oldpts;
1160: var radioButton = formname["RADVAL"+id];
1161: for (var i=0; i<radioButton.length; i++) {
1162: radioButton[i].checked=false;
1163: if (i == oldpts) {
1164: radioButton[i].checked=true;
1165: }
1166: }
1167: }
1168: formname["stores"+id].value = "0";
1169: updateSelect(formname,id);
1170: return;
1171: }
1172:
1173: function clearRadBox(formname,id) {
1174: if (checkSolved(formname,id) == 'noupdate') {
1175: updateSelect(formname,id);
1176: return;
1177: }
1178: gradeSelect = formname["GD_SEL"+id];
1179: for (var i=0; i<gradeSelect.length; i++) {
1180: if (gradeSelect[i].selected) {
1181: var selectx=i;
1182: }
1183: }
1184: var stores = formname["stores"+id];
1185: if (selectx == stores.value) { return };
1186: var gradeBox = formname["GD_BOX"+id];
1187: gradeBox.value = "";
1188: var radioButton = formname["RADVAL"+id];
1189: for (var i=0; i<radioButton.length; i++) {
1190: radioButton[i].checked=false;
1191: }
1192: stores.value = selectx;
1193: }
1194:
1195: function checkSolved(formname,id) {
1196: if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1197: var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
1198: if (!reply) {return "noupdate";}
1199: formname.overRideScore.value = 'yes';
1200: }
1201: return "update";
1202: }
1203:
1204: function updateSelect(formname,id) {
1205: formname["GD_SEL"+id][0].selected = true;
1206: return;
1207: }
1208:
1209: //=========== Check that a point is assigned for all the parts ============
1210: function checksubmit(formname,val,total,parttot) {
1211: formname.gradeOpt.value = val;
1212: if (val == "Save & Next") {
1213: for (i=0;i<=total;i++) {
1214: for (j=0;j<parttot;j++) {
1215: var partid = formname["partid"+i+"_"+j].value;
1216: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1217: var points = formname["GD_BOX"+i+"_"+partid].value;
1218: if (points == "") {
1219: var name = formname["name"+i].value;
1220: var studentID = (name != '' ? name : formname["unamedom"+i].value);
1221: var resp = confirm("You did not assign a score for "+studentID+
1222: ", part "+partid+". Continue?");
1223: if (resp == false) {
1224: formname["GD_BOX"+i+"_"+partid].focus();
1225: return false;
1226: }
1227: }
1228: }
1229:
1230: }
1231: }
1232:
1233: }
1234: if (val == "Grade Student") {
1235: formname.showgrading.value = "yes";
1236: if (formname.Status.value == "") {
1237: formname.Status.value = "Active";
1238: }
1239: formname.studentNo.value = total;
1240: }
1241: formname.submit();
1242: }
1243:
1244: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
1245: function checkSubmitPage(formname,total) {
1246: noscore = new Array(100);
1247: var ptr = 0;
1248: for (i=1;i<total;i++) {
1249: var partid = formname["q_"+i].value;
1250: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1251: var points = formname["GD_BOX"+i+"_"+partid].value;
1252: var status = formname["solved"+i+"_"+partid].value;
1253: if (points == "" && status != "correct_by_student") {
1254: noscore[ptr] = i;
1255: ptr++;
1256: }
1257: }
1258: }
1259: if (ptr != 0) {
1260: var sense = ptr == 1 ? ": " : "s: ";
1261: var prolist = "";
1262: if (ptr == 1) {
1263: prolist = noscore[0];
1264: } else {
1265: var i = 0;
1266: while (i < ptr-1) {
1267: prolist += noscore[i]+", ";
1268: i++;
1269: }
1270: prolist += "and "+noscore[i];
1271: }
1272: var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
1273: if (resp == false) {
1274: return false;
1275: }
1276: }
1277:
1278: formname.submit();
1279: }
1280: </script>
1281: SUBJAVASCRIPT
1282: }
1283:
1284: #--- javascript for essay type problem --
1285: sub sub_page_kw_js {
1286: my $request = shift;
1287: my $iconpath = $request->dir_config('lonIconsURL');
1288: &commonJSfunctions($request);
1289:
1290: my $inner_js_msg_central=<<INNERJS;
1291: <script text="text/javascript">
1292: function checkInput() {
1293: opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
1294: var nmsg = opener.document.SCORE.savemsgN.value;
1295: var usrctr = document.msgcenter.usrctr.value;
1296: var newval = opener.document.SCORE["newmsg"+usrctr];
1297: newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
1298:
1299: var msgchk = "";
1300: if (document.msgcenter.subchk.checked) {
1301: msgchk = "msgsub,";
1302: }
1303: var includemsg = 0;
1304: for (var i=1; i<=nmsg; i++) {
1305: var opnmsg = opener.document.SCORE["savemsg"+i];
1306: var frmmsg = document.msgcenter["msg"+i];
1307: opnmsg.value = opener.checkEntities(frmmsg.value);
1308: var showflg = opener.document.SCORE["shownOnce"+i];
1309: showflg.value = "1";
1310: var chkbox = document.msgcenter["msgn"+i];
1311: if (chkbox.checked) {
1312: msgchk += "savemsg"+i+",";
1313: includemsg = 1;
1314: }
1315: }
1316: if (document.msgcenter.newmsgchk.checked) {
1317: msgchk += "newmsg"+usrctr;
1318: includemsg = 1;
1319: }
1320: imgformname = opener.document.SCORE["mailicon"+usrctr];
1321: imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
1322: var includemsg = opener.document.SCORE["includemsg"+usrctr];
1323: includemsg.value = msgchk;
1324:
1325: self.close()
1326:
1327: }
1328: </script>
1329: INNERJS
1330:
1331: my $inner_js_highlight_central=<<INNERJS;
1332: <script type="text/javascript">
1333: function updateChoice(flag) {
1334: opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
1335: opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
1336: opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
1337: opener.document.SCORE.refresh.value = "on";
1338: if (opener.document.SCORE.keywords.value!=""){
1339: opener.document.SCORE.submit();
1340: }
1341: self.close()
1342: }
1343: </script>
1344: INNERJS
1345:
1346: my $start_page_msg_central =
1347: &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
1348: {'js_ready' => 1,
1349: 'only_body' => 1,
1350: 'bgcolor' =>'#FFFFFF',});
1351: my $end_page_msg_central =
1352: &Apache::loncommon::end_page({'js_ready' => 1});
1353:
1354:
1355: my $start_page_highlight_central =
1356: &Apache::loncommon::start_page('Highlight Central',
1357: $inner_js_highlight_central,
1358: {'js_ready' => 1,
1359: 'only_body' => 1,
1360: 'bgcolor' =>'#FFFFFF',});
1361: my $end_page_highlight_central =
1362: &Apache::loncommon::end_page({'js_ready' => 1});
1363:
1364: my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1365: $docopen=~s/^document\.//;
1366: $request->print(<<SUBJAVASCRIPT);
1367: <script type="text/javascript" language="javascript">
1368:
1369: //===================== Show list of keywords ====================
1370: function keywords(formname) {
1371: var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1372: if (nret==null) return;
1373: formname.keywords.value = nret;
1374:
1375: if (formname.keywords.value != "") {
1376: formname.refresh.value = "on";
1377: formname.submit();
1378: }
1379: return;
1380: }
1381:
1382: //===================== Script to view submitted by ==================
1383: function viewSubmitter(submitter) {
1384: document.SCORE.refresh.value = "on";
1385: document.SCORE.NCT.value = "1";
1386: document.SCORE.unamedom0.value = submitter;
1387: document.SCORE.submit();
1388: return;
1389: }
1390:
1391: //===================== Script to add keyword(s) ==================
1392: function getSel() {
1393: if (document.getSelection) txt = document.getSelection();
1394: else if (document.selection) txt = document.selection.createRange().text;
1395: else return;
1396: var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
1397: if (cleantxt=="") {
1398: alert("Please select a word or group of words from document and then click this link.");
1399: return;
1400: }
1401: var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
1402: if (nret==null) return;
1403: document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1404: if (document.SCORE.keywords.value != "") {
1405: document.SCORE.refresh.value = "on";
1406: document.SCORE.submit();
1407: }
1408: return;
1409: }
1410:
1411: //====================== Script for composing message ==============
1412: // preload images
1413: img1 = new Image();
1414: img1.src = "$iconpath/mailbkgrd.gif";
1415: img2 = new Image();
1416: img2.src = "$iconpath/mailto.gif";
1417:
1418: function msgCenter(msgform,usrctr,fullname) {
1419: var Nmsg = msgform.savemsgN.value;
1420: savedMsgHeader(Nmsg,usrctr,fullname);
1421: var subject = msgform.msgsub.value;
1422: var msgchk = document.SCORE["includemsg"+usrctr].value;
1423: re = /msgsub/;
1424: var shwsel = "";
1425: if (re.test(msgchk)) { shwsel = "checked" }
1426: subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
1427: displaySubject(checkEntities(subject),shwsel);
1428: for (var i=1; i<=Nmsg; i++) {
1429: var testmsg = "savemsg"+i+",";
1430: re = new RegExp(testmsg,"g");
1431: shwsel = "";
1432: if (re.test(msgchk)) { shwsel = "checked" }
1433: var message = document.SCORE["savemsg"+i].value;
1434: message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1435: displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
1436: //any < is already converted to <, etc. However, only once!!
1437: }
1438: newmsg = document.SCORE["newmsg"+usrctr].value;
1439: shwsel = "";
1440: re = /newmsg/;
1441: if (re.test(msgchk)) { shwsel = "checked" }
1442: newMsg(newmsg,shwsel);
1443: msgTail();
1444: return;
1445: }
1446:
1447: function checkEntities(strx) {
1448: if (strx.length == 0) return strx;
1449: var orgStr = ["&", "<", ">", '"'];
1450: var newStr = ["&", "<", ">", """];
1451: var counter = 0;
1452: while (counter < 4) {
1453: strx = strReplace(strx,orgStr[counter],newStr[counter]);
1454: counter++;
1455: }
1456: return strx;
1457: }
1458:
1459: function strReplace(strx, orgStr, newStr) {
1460: return strx.split(orgStr).join(newStr);
1461: }
1462:
1463: function savedMsgHeader(Nmsg,usrctr,fullname) {
1464: var height = 70*Nmsg+250;
1465: var scrollbar = "no";
1466: if (height > 600) {
1467: height = 600;
1468: scrollbar = "yes";
1469: }
1470: var xpos = (screen.width-600)/2;
1471: xpos = (xpos < 0) ? '0' : xpos;
1472: var ypos = (screen.height-height)/2-30;
1473: ypos = (ypos < 0) ? '0' : ypos;
1474:
1475: pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1476: pWin.focus();
1477: pDoc = pWin.document;
1478: pDoc.$docopen;
1479: pDoc.write('$start_page_msg_central');
1480:
1481: pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
1482: pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1483: pDoc.write("<h3><span class=\\"LC_info\\"> Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
1484:
1485: pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
1486: pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
1487: pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
1488: }
1489: function displaySubject(msg,shwsel) {
1490: pDoc = pWin.document;
1491: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1492: pDoc.write("<td>Subject<\\/td>");
1493: pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1494: pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1495: }
1496:
1497: function displaySavedMsg(ctr,msg,shwsel) {
1498: pDoc = pWin.document;
1499: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1500: pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
1501: pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1502: pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1503: }
1504:
1505: function newMsg(newmsg,shwsel) {
1506: pDoc = pWin.document;
1507: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1508: pDoc.write("<td align=\\"center\\">New<\\/td>");
1509: pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1510: pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1511: }
1512:
1513: function msgTail() {
1514: pDoc = pWin.document;
1515: pDoc.write("<\\/table>");
1516: pDoc.write("<\\/td><\\/tr><\\/table> ");
1517: pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\"> ");
1518: pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1519: pDoc.write("<\\/form>");
1520: pDoc.write('$end_page_msg_central');
1521: pDoc.close();
1522: }
1523:
1524: //====================== Script for keyword highlight options ==============
1525: function kwhighlight() {
1526: var kwclr = document.SCORE.kwclr.value;
1527: var kwsize = document.SCORE.kwsize.value;
1528: var kwstyle = document.SCORE.kwstyle.value;
1529: var redsel = "";
1530: var grnsel = "";
1531: var blusel = "";
1532: if (kwclr=="red") {var redsel="checked"};
1533: if (kwclr=="green") {var grnsel="checked"};
1534: if (kwclr=="blue") {var blusel="checked"};
1535: var sznsel = "";
1536: var sz1sel = "";
1537: var sz2sel = "";
1538: if (kwsize=="0") {var sznsel="checked"};
1539: if (kwsize=="+1") {var sz1sel="checked"};
1540: if (kwsize=="+2") {var sz2sel="checked"};
1541: var synsel = "";
1542: var syisel = "";
1543: var sybsel = "";
1544: if (kwstyle=="") {var synsel="checked"};
1545: if (kwstyle=="<i>") {var syisel="checked"};
1546: if (kwstyle=="<b>") {var sybsel="checked"};
1547: highlightCentral();
1548: highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
1549: highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
1550: highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
1551: highlightend();
1552: return;
1553: }
1554:
1555: function highlightCentral() {
1556: // if (window.hwdWin) window.hwdWin.close();
1557: var xpos = (screen.width-400)/2;
1558: xpos = (xpos < 0) ? '0' : xpos;
1559: var ypos = (screen.height-330)/2-30;
1560: ypos = (ypos < 0) ? '0' : ypos;
1561:
1562: hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1563: hwdWin.focus();
1564: var hDoc = hwdWin.document;
1565: hDoc.$docopen;
1566: hDoc.write('$start_page_highlight_central');
1567: hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1568: hDoc.write("<h3><span class=\\"LC_info\\"> Keyword Highlight Options<\\/span><\\/h3><br /><br />");
1569:
1570: hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
1571: hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
1572: hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
1573: }
1574:
1575: function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) {
1576: var hDoc = hwdWin.document;
1577: hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1578: hDoc.write("<td align=\\"left\\">");
1579: hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+"> "+clrtxt+"<\\/td>");
1580: hDoc.write("<td align=\\"left\\">");
1581: hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+"> "+sztxt+"<\\/td>");
1582: hDoc.write("<td align=\\"left\\">");
1583: hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+"> "+sytxt+"<\\/td>");
1584: hDoc.write("<\\/tr>");
1585: }
1586:
1587: function highlightend() {
1588: var hDoc = hwdWin.document;
1589: hDoc.write("<\\/table>");
1590: hDoc.write("<\\/td><\\/tr><\\/table> ");
1591: hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\"> ");
1592: hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1593: hDoc.write("<\\/form>");
1594: hDoc.write('$end_page_highlight_central');
1595: hDoc.close();
1596: }
1597:
1598: </script>
1599: SUBJAVASCRIPT
1600: }
1601:
1602: sub get_increment {
1603: my $increment = $env{'form.increment'};
1604: if ($increment != 1 && $increment != .5 && $increment != .25 &&
1605: $increment != .1) {
1606: $increment = 1;
1607: }
1608: return $increment;
1609: }
1610:
1611: #--- displays the grading box, used in essay type problem and grading by page/sequence
1612: sub gradeBox {
1613: my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1614: my $checkIcon = '<img alt="'.&mt('Check Mark').
1615: '" src="'.$request->dir_config('lonIconsURL').
1616: '/check.gif" height="16" border="0" />';
1617: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1618: my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)')
1619: : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1620: $wgt = ($wgt > 0 ? $wgt : '1');
1621: my $score = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1622: '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1623: my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1624: my $display_part= &get_display_part($partid,$symb);
1625: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
1626: [$partid]);
1627: my $aggtries = $$record{'resource.'.$partid.'.tries'};
1628: if ($last_resets{$partid}) {
1629: $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
1630: }
1631: $result.='<table border="0"><tr><td>'.
1632: '<b>Part: </b>'.$display_part.' <b>Points: </b></td><td>'."\n";
1633: my $ctr = 0;
1634: my $thisweight = 0;
1635: my $increment = &get_increment();
1636: $result.='<table border="0"><tr>'."\n"; # display radio buttons in a nice table 10 across
1637: while ($thisweight<=$wgt) {
1638: $result.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1639: 'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1640: $thisweight.')" value="'.$thisweight.'" '.
1641: ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1642: $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1643: $thisweight += $increment;
1644: $ctr++;
1645: }
1646: $result.='</tr></table>';
1647: $result.='</td><td> <b>or</b> </td>'."\n";
1648: $result.='<td><input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1649: ($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1650: 'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1651: $wgt.')" /></td>'."\n";
1652: $result.='<td>/'.$wgt.' '.$wgtmsg.
1653: ($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? ' '.$checkIcon : '').
1654: ' </td><td>'."\n";
1655: $result.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
1656: 'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1657: if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1658: $result.='<option></option>'.
1659: '<option selected="selected">excused</option>';
1660: } else {
1661: $result.='<option selected="selected"></option>'.
1662: '<option>excused</option>';
1663: }
1664: $result.='<option>reset status</option></select>'."\n";
1665: $result.=" \n";
1666: $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
1667: '<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
1668: '<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1669: $$record{'resource.'.$partid.'.solved'}.'" />'."\n".
1670: '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
1671: $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
1672: '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
1673: $aggtries.'" />'."\n";
1674: $result.='</td></tr></table>'."\n";
1675: $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
1676: return $result;
1677: }
1678:
1679: sub handback_box {
1680: my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
1681: my ($partlist,$handgrade,$responseType) = &response_type($symb);
1682: my (@respids);
1683: my @part_response_id = &flatten_responseType($responseType);
1684: foreach my $part_response_id (@part_response_id) {
1685: my ($part,$resp) = @{ $part_response_id };
1686: if ($part eq $partid) {
1687: push(@respids,$resp);
1688: }
1689: }
1690: my $result;
1691: foreach my $respid (@respids) {
1692: my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
1693: my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
1694: next if (!@$files);
1695: my $file_counter = 1;
1696: foreach my $file (@$files) {
1697: if ($file =~ /\/portfolio\//) {
1698: my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1699: my ($name,$version,$ext) = &file_name_version_ext($file_disp);
1700: $file_disp = "$name.$ext";
1701: $file = $file_path.$file_disp;
1702: $result.=&mt('Return commented version of [_1] to student.',
1703: '<span class="LC_filename">'.$file_disp.'</span>');
1704: $result.='<input type="file" name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1705: $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1706: $result.='(File will be uploaded when you click on Save & Next below.)<br />';
1707: $file_counter++;
1708: }
1709: }
1710: }
1711: return $result;
1712: }
1713:
1714: sub show_problem {
1715: my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1716: my $rendered;
1717: my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1718: &Apache::lonxml::remember_problem_counter();
1719: if ($mode eq 'both' or $mode eq 'text') {
1720: $rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1721: $env{'request.course.id'},
1722: undef,\%form);
1723: }
1724: if ($removeform) {
1725: $rendered=~s|<form(.*?)>||g;
1726: $rendered=~s|</form>||g;
1727: $rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1728: }
1729: my $companswer;
1730: if ($mode eq 'both' or $mode eq 'answer') {
1731: &Apache::lonxml::restore_problem_counter();
1732: $companswer=
1733: &Apache::loncommon::get_student_answers($symb,$uname,$udom,
1734: $env{'request.course.id'},
1735: %form);
1736: }
1737: if ($removeform) {
1738: $companswer=~s|<form(.*?)>||g;
1739: $companswer=~s|</form>||g;
1740: $companswer=~s|name="submit"|name="would_have_been_submit"|g;
1741: }
1742: $rendered=
1743: '<div class="LC_grade_show_problem_header">'.
1744: &mt('View of the problem').
1745: '</div><div class="LC_grade_show_problem_problem">'.
1746: $rendered.
1747: '</div>';
1748: $companswer=
1749: '<div class="LC_grade_show_problem_header">'.
1750: &mt('Correct answer').
1751: '</div><div class="LC_grade_show_problem_problem">'.
1752: $companswer.
1753: '</div>';
1754: my $result;
1755: if ($mode eq 'both') {
1756: $result=$rendered.$companswer;
1757: } elsif ($mode eq 'text') {
1758: $result=$rendered;
1759: } elsif ($mode eq 'answer') {
1760: $result=$companswer;
1761: }
1762: $result='<div class="LC_grade_show_problem">'.$result.'</div>';
1763: return $result;
1764: }
1765:
1766: sub files_exist {
1767: my ($r, $symb) = @_;
1768: my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1769:
1770: foreach my $student (@students) {
1771: my ($uname,$udom,$fullname) = split(/:/,$student);
1772: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
1773: $udom,$uname);
1774: my ($string,$timestamp)= &get_last_submission(\%record);
1775: foreach my $submission (@$string) {
1776: my ($partid,$respid) =
1777: ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1778: my $files=&get_submitted_files($udom,$uname,$partid,$respid,
1779: \%record);
1780: return 1 if (@$files);
1781: }
1782: }
1783: return 0;
1784: }
1785:
1786: sub download_all_link {
1787: my ($r,$symb) = @_;
1788: my $all_students =
1789: join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
1790:
1791: my $parts =
1792: join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
1793:
1794: my $identifier = &Apache::loncommon::get_cgi_id();
1795: &Apache::lonnet::appenv('cgi.'.$identifier.'.students' => $all_students,
1796: 'cgi.'.$identifier.'.symb' => $symb,
1797: 'cgi.'.$identifier.'.parts' => $parts,);
1798: $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
1799: &mt('Download All Submitted Documents').'</a>');
1800: return
1801: }
1802:
1803: sub build_section_inputs {
1804: my $section_inputs;
1805: if ($env{'form.section'} eq '') {
1806: $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
1807: } else {
1808: my @sections = &Apache::loncommon::get_env_multiple('form.section');
1809: foreach my $section (@sections) {
1810: $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
1811: }
1812: }
1813: return $section_inputs;
1814: }
1815:
1816: # --------------------------- show submissions of a student, option to grade
1817: sub submission {
1818: my ($request,$counter,$total) = @_;
1819: my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
1820: $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
1821: my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
1822: $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1823: my $symb = &get_symb($request);
1824: if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1825:
1826: if (!&canview($usec)) {
1827: $request->print('<span class="LC_warning">Unable to view requested student.('.
1828: $uname.':'.$udom.' in section '.$usec.' in course id '.
1829: $env{'request.course.id'}.')</span>');
1830: $request->print(&show_grading_menu_form($symb));
1831: return;
1832: }
1833:
1834: if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
1835: if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
1836: if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
1837: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1838: my $checkIcon = '<img alt="'.&mt('Check Mark').
1839: '" src="'.$request->dir_config('lonIconsURL').
1840: '/check.gif" height="16" border="0" />';
1841:
1842: my %old_essays;
1843: # header info
1844: if ($counter == 0) {
1845: &sub_page_js($request);
1846: &sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
1847: $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ?
1848: &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1849: if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1850: &download_all_link($request, $symb);
1851: }
1852: $request->print('<h3> <span class="LC_info">Submission Record</span></h3>'."\n".
1853: '<h4> <b>Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n");
1854:
1855: # option to display problem, only once else it cause problems
1856: # with the form later since the problem has a form.
1857: if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1858: my $mode;
1859: if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1860: $mode='both';
1861: } elsif ($env{'form.vProb'} eq 'yes') {
1862: $mode='text';
1863: } elsif ($env{'form.vAns'} eq 'yes') {
1864: $mode='answer';
1865: }
1866: &Apache::lonxml::clear_problem_counter();
1867: $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1868: }
1869:
1870: # kwclr is the only variable that is guaranteed to be non blank
1871: # if this subroutine has been called once.
1872: my %keyhash = ();
1873: if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1874: %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1875: $env{'course.'.$env{'request.course.id'}.'.domain'},
1876: $env{'course.'.$env{'request.course.id'}.'.num'});
1877:
1878: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1879: $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
1880: $env{'form.kwclr'} = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
1881: $env{'form.kwsize'} = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
1882: $env{'form.kwstyle'} = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
1883: $env{'form.msgsub'} = $keyhash{$symb.'_subject'} ne '' ?
1884: $keyhash{$symb.'_subject'} : $env{'form.probTitle'};
1885: $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1886: }
1887: my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1888: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1889: $request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1890: '<input type="hidden" name="command" value="handgrade" />'."\n".
1891: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1892: '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
1893: '<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1894: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
1895: '<input type="hidden" name="refresh" value="off" />'."\n".
1896: '<input type="hidden" name="studentNo" value="" />'."\n".
1897: '<input type="hidden" name="gradeOpt" value="" />'."\n".
1898: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1899: '<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
1900: '<input type="hidden" name="vProb" value="'.$env{'form.vProb'}.'" />'."\n".
1901: '<input type="hidden" name="vAns" value="'.$env{'form.vAns'}.'" />'."\n".
1902: '<input type="hidden" name="lastSub" value="'.$env{'form.lastSub'}.'" />'."\n".
1903: &build_section_inputs().
1904: '<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1905: '<input type="hidden" name="handgrade" value="'.$env{'form.handgrade'}.'" />'."\n".
1906: '<input type="hidden" name="NCT"'.
1907: ' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1908: if ($env{'form.handgrade'} eq 'yes') {
1909: $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
1910: '<input type="hidden" name="kwclr" value="'.$env{'form.kwclr'}.'" />'."\n".
1911: '<input type="hidden" name="kwsize" value="'.$env{'form.kwsize'}.'" />'."\n".
1912: '<input type="hidden" name="kwstyle" value="'.$env{'form.kwstyle'}.'" />'."\n".
1913: '<input type="hidden" name="msgsub" value="'.$env{'form.msgsub'}.'" />'."\n".
1914: '<input type="hidden" name="shownSub" value="0" />'."\n".
1915: '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1916: foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
1917: $request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
1918: }
1919: }
1920:
1921: my ($cts,$prnmsg) = (1,'');
1922: while ($cts <= $env{'form.savemsgN'}) {
1923: $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1924: (!exists($keyhash{$symb.'_savemsg'.$cts}) ?
1925: &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1926: &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1927: '" />'."\n".
1928: '<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1929: $cts++;
1930: }
1931: $request->print($prnmsg);
1932:
1933: if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1934: #
1935: # Print out the keyword options line
1936: #
1937: $request->print(<<KEYWORDS);
1938: <b>Keyword Options:</b>
1939: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>
1940: <a href="#" onMouseDown="javascript:getSel(); return false"
1941: CLASS="page">Paste Selection to List</a>
1942: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1943: KEYWORDS
1944: #
1945: # Load the other essays for similarity check
1946: #
1947: my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1948: my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1949: $apath=&escape($apath);
1950: $apath=~s/\W/\_/gs;
1951: %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1952: }
1953: }
1954:
1955: # This is where output for one specific student would start
1956: my $add_class = ($counter%2) ? 'LC_grade_show_user_odd_row' : '';
1957: $request->print("\n\n".
1958: '<div class="LC_grade_show_user '.$add_class.'">'.
1959: '<div class="LC_grade_user_name">'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</div>'.
1960: '<div class="LC_grade_show_user_body">'."\n");
1961:
1962: if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1963: my $mode;
1964: if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1965: $mode='both';
1966: } elsif ($env{'form.vProb'} eq 'all' ) {
1967: $mode='text';
1968: } elsif ($env{'form.vAns'} eq 'all') {
1969: $mode='answer';
1970: }
1971: &Apache::lonxml::clear_problem_counter();
1972: $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode));
1973: }
1974:
1975: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1976: my ($partlist,$handgrade,$responseType) = &response_type($symb);
1977:
1978: # Display student info
1979: $request->print(($counter == 0 ? '' : '<br />'));
1980: my $result='<div class="LC_grade_submissions">';
1981:
1982: $result.='<div class="LC_grade_submissions_header">';
1983: $result.= &mt('Submissions');
1984: $result.='<input type="hidden" name="name'.$counter.
1985: '" value="'.$env{'form.fullname'}.'" />'."\n";
1986: if ($env{'form.handgrade'} eq 'no') {
1987: $result.='<span class="LC_grade_check_note">'.
1988: &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)."</span>\n";
1989:
1990: }
1991:
1992:
1993:
1994: # If any part of the problem is an essay-response (handgraded), then check for collaborators
1995: my $fullname;
1996: my $col_fullnames = [];
1997: if ($env{'form.handgrade'} eq 'yes') {
1998: (my $sub_result,$fullname,$col_fullnames)=
1999: &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
2000: $counter);
2001: $result.=$sub_result;
2002: }
2003: $request->print($result."\n");
2004: $request->print('</div>'."\n");
2005: # print student answer/submission
2006: # Options are (1) Handgaded submission only
2007: # (2) Last submission, includes submission that is not handgraded
2008: # (for multi-response type part)
2009: # (3) Last submission plus the parts info
2010: # (4) The whole record for this student
2011: if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
2012: my ($string,$timestamp)= &get_last_submission(\%record);
2013:
2014: my $lastsubonly;
2015:
2016: if ($$timestamp eq '') {
2017: $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>';
2018: } else {
2019: $lastsubonly = '<div class="LC_grade_submissions_body"> <b>Date Submitted:</b> '.$$timestamp."\n";
2020:
2021: my %seenparts;
2022: my @part_response_id = &flatten_responseType($responseType);
2023: foreach my $part (@part_response_id) {
2024: next if ($env{'form.lastSub'} eq 'hdgrade'
2025: && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
2026:
2027: my ($partid,$respid) = @{ $part };
2028: my $display_part=&get_display_part($partid,$symb);
2029: if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
2030: if (exists($seenparts{$partid})) { next; }
2031: $seenparts{$partid}=1;
2032: my $submitby='<b>Part:</b> '.$display_part.
2033: ' <b>Collaborative submission by:</b> '.
2034: '<a href="javascript:viewSubmitter(\''.
2035: $env{"form.$uname:$udom:$partid:submitted_by"}.
2036: '\');" target="_self">'.
2037: $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
2038: $request->print($submitby);
2039: next;
2040: }
2041: my $responsetype = $responseType->{$partid}->{$respid};
2042: if (!exists($record{"resource.$partid.$respid.submission"})) {
2043: $lastsubonly.="\n".'<div class="LC_grade_submission_part"><b>Part:</b> '.
2044: $display_part.' <span class="LC_internal_info">( ID '.$respid.
2045: ' )</span> '.
2046: '<span class="LC_warning">'.&mt('Nothing submitted - no attempts').'</span><br /><br /></div>';
2047: next;
2048: }
2049: foreach my $submission (@$string) {
2050: my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
2051: if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
2052: my ($ressub,$subval) = split(/:/,$submission,2);
2053: # Similarity check
2054: my $similar='';
2055: if($env{'form.checkPlag'}){
2056: my ($oname,$odom,$ocrsid,$oessay,$osim)=
2057: &most_similar($uname,$udom,$subval,\%old_essays);
2058: if ($osim) {
2059: $osim=int($osim*100.0);
2060: my %old_course_desc =
2061: &Apache::lonnet::coursedescription($ocrsid,
2062: {'one_time' => 1});
2063:
2064: $similar="<hr /><h3><span class=\"LC_warning\">".
2065: &mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
2066: $osim,
2067: &Apache::loncommon::plainname($oname,$odom),
2068: $oname,$odom,
2069: $old_course_desc{'description'},
2070: $old_course_desc{'num'},
2071: $old_course_desc{'domain'}).
2072: '</span></h3><blockquote><i>'.
2073: &keywords_highlight($oessay).
2074: '</i></blockquote><hr />';
2075: }
2076: }
2077: my $order=&get_order($partid,$respid,$symb,$uname,$udom);
2078: if ($env{'form.lastSub'} eq 'lastonly' ||
2079: ($env{'form.lastSub'} eq 'hdgrade' &&
2080: $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
2081: my $display_part=&get_display_part($partid,$symb);
2082: $lastsubonly.='<div class="LC_grade_submission_part"><b>Part:</b> '.
2083: $display_part.' <span class="LC_internal_info">( ID '.$respid.
2084: ' )</span> ';
2085: my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
2086: if (@$files) {
2087: $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain virusses').'</span><br />';
2088: my $file_counter = 0;
2089: foreach my $file (@$files) {
2090: $file_counter++;
2091: &Apache::lonnet::allowuploaded('/adm/grades',$file);
2092: $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
2093: }
2094: $lastsubonly.='<br />';
2095: }
2096: $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
2097: &cleanRecord($subval,$responsetype,$symb,$partid,
2098: $respid,\%record,$order);
2099: if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
2100: $lastsubonly.='</div>';
2101: }
2102: }
2103: }
2104: $lastsubonly.='</div>'."\n";
2105: }
2106: $request->print($lastsubonly);
2107: } elsif ($env{'form.lastSub'} eq 'datesub') {
2108: my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
2109: $request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
2110: } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
2111: $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
2112: $env{'request.course.id'},
2113: $last,'.submission',
2114: 'Apache::grades::keywords_highlight'));
2115: }
2116:
2117: $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
2118: .$udom.'" />'."\n");
2119: # return if view submission with no grading option
2120: if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
2121: my $toGrade.='<input type="button" value="Grade Student" '.
2122: 'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
2123: .$counter.'\');" target="_self" /> '."\n" if (&canmodify($usec));
2124: $toGrade.='</div>'."\n";
2125: if (($env{'form.command'} eq 'submission') ||
2126: ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
2127: $toGrade.='</form>'.&show_grading_menu_form($symb);
2128: }
2129: $request->print($toGrade);
2130: return;
2131: } else {
2132: $request->print('</div>'."\n");
2133: }
2134:
2135: # essay grading message center
2136: if ($env{'form.handgrade'} eq 'yes') {
2137: my $result='<div class="LC_grade_message_center">';
2138:
2139: $result.='<div class="LC_grade_message_center_header">'.
2140: &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
2141: my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
2142: my $msgfor = $givenn.' '.$lastname;
2143: if (scalar(@$col_fullnames) > 0) {
2144: my $lastone = pop(@$col_fullnames);
2145: $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
2146: }
2147: $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
2148: $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
2149: '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
2150: $result.=' <a href="javascript:msgCenter(document.SCORE,'.$counter.
2151: ',\''.$msgfor.'\');" target="_self">'.
2152: &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
2153: &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
2154: '<img src="'.$request->dir_config('lonIconsURL').
2155: '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
2156: '<br /> ('.
2157: &mt('Message will be sent when you click on Save & Next below.').")\n";
2158: $result.='</div></div>';
2159: $request->print($result);
2160: }
2161:
2162: my %seen = ();
2163: my @partlist;
2164: my @gradePartRespid;
2165: my @part_response_id = &flatten_responseType($responseType);
2166: $request->print('<div class="LC_grade_assign">'.
2167:
2168: '<div class="LC_grade_assign_header">'.
2169: &mt('Assign Grades').'</div>'.
2170: '<div class="LC_grade_assign_body">');
2171: foreach my $part_response_id (@part_response_id) {
2172: my ($partid,$respid) = @{ $part_response_id };
2173: my $part_resp = join('_',@{ $part_response_id });
2174: next if ($seen{$partid} > 0);
2175: $seen{$partid}++;
2176: next if ($$handgrade{$part_resp} ne 'yes'
2177: && $env{'form.lastSub'} eq 'hdgrade');
2178: push @partlist,$partid;
2179: push @gradePartRespid,$partid.'.'.$respid;
2180: $request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
2181: }
2182: $request->print('</div></div>');
2183:
2184: $request->print('<div class="LC_grade_info_links">');
2185: if ($perm{'vgr'}) {
2186: $request->print(
2187: &Apache::loncommon::track_student_link(&mt('View recent activity'),
2188: $uname,$udom,'check'));
2189: }
2190: if ($perm{'opa'}) {
2191: $request->print(
2192: &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
2193: $uname,$udom,$symb,'check'));
2194: }
2195: $request->print('</div>');
2196:
2197: $result='<input type="hidden" name="partlist'.$counter.
2198: '" value="'.(join ":",@partlist).'" />'."\n";
2199: $result.='<input type="hidden" name="gradePartRespid'.
2200: '" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
2201: my $ctr = 0;
2202: while ($ctr < scalar(@partlist)) {
2203: $result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
2204: $partlist[$ctr].'" />'."\n";
2205: $ctr++;
2206: }
2207: $request->print($result.''."\n");
2208:
2209: # Done with printing info for one student
2210:
2211: $request->print('</div>');#LC_grade_show_user_body
2212: $request->print('</div>');#LC_grade_show_user
2213:
2214:
2215: # print end of form
2216: if ($counter == $total) {
2217: my $endform='<table border="0"><tr><td>'."\n";
2218: $endform.='<input type="button" value="Save & Next" '.
2219: 'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
2220: $total.','.scalar(@partlist).');" target="_self" /> '."\n";
2221: my $ntstu ='<select name="NTSTU">'.
2222: '<option>1</option><option>2</option>'.
2223: '<option>3</option><option>5</option>'.
2224: '<option>7</option><option>10</option></select>'."\n";
2225: my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
2226: $ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
2227: $endform.=$ntstu.'student(s) ';
2228: $endform.='<input type="button" value="Previous" '.
2229: 'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> '."\n".
2230: '<input type="button" value="Next" '.
2231: 'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> ';
2232: $endform.='(Next and Previous (student) do not save the scores.)'."\n" ;
2233: $endform.="<input type='hidden' value='".&get_increment().
2234: "' name='increment' />";
2235: $endform.='</td><tr></table></form>';
2236: $endform.=&show_grading_menu_form($symb);
2237: $request->print($endform);
2238: }
2239: return '';
2240: }
2241:
2242: sub check_collaborators {
2243: my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
2244: my ($result,@col_fullnames);
2245: my ($classlist,undef,$fullname) = &getclasslist('all','0');
2246: foreach my $part (keys(%$handgrade)) {
2247: my $ncol = &Apache::lonnet::EXT('resource.'.$part.
2248: '.maxcollaborators',
2249: $symb,$udom,$uname);
2250: next if ($ncol <= 0);
2251: $part =~ s/\_/\./g;
2252: next if ($record->{'resource.'.$part.'.collaborators'} eq '');
2253: my (@good_collaborators, @bad_collaborators);
2254: foreach my $possible_collaborator
2255: (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) {
2256: $possible_collaborator =~ s/[\$\^\(\)]//g;
2257: next if ($possible_collaborator eq '');
2258: my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
2259: $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
2260: next if ($co_name eq $uname && $co_dom eq $udom);
2261: # Doing this grep allows 'fuzzy' specification
2262: my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i,
2263: keys(%$classlist));
2264: if (! scalar(@matches)) {
2265: push(@bad_collaborators, $possible_collaborator);
2266: } else {
2267: push(@good_collaborators, @matches);
2268: }
2269: }
2270: if (scalar(@good_collaborators) != 0) {
2271: $result.='<br />'.&mt('Collaborators: ');
2272: foreach my $name (@good_collaborators) {
2273: my ($lastname,$givenn) = split(/,/,$$fullname{$name});
2274: push(@col_fullnames, $givenn.' '.$lastname);
2275: $result.=$fullname->{$name}.' ';
2276: }
2277: $result.='<br />'."\n";
2278: my ($part)=split(/\./,$part);
2279: $result.='<input type="hidden" name="collaborator'.$counter.
2280: '" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
2281: "\n";
2282: }
2283: if (scalar(@bad_collaborators) > 0) {
2284: $result.='<div class="LC_warning">';
2285: $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
2286: $result .= '</div>';
2287: }
2288: if (scalar(@bad_collaborators > $ncol)) {
2289: $result .= '<div class="LC_warning">';
2290: $result .= &mt('This student has submitted too many '.
2291: 'collaborators. Maximum is [_1].',$ncol);
2292: $result .= '</div>';
2293: }
2294: }
2295: return ($result,$fullname,\@col_fullnames);
2296: }
2297:
2298: #--- Retrieve the last submission for all the parts
2299: sub get_last_submission {
2300: my ($returnhash)=@_;
2301: my (@string,$timestamp);
2302: if ($$returnhash{'version'}) {
2303: my %lasthash=();
2304: my ($version);
2305: for ($version=1;$version<=$$returnhash{'version'};$version++) {
2306: foreach my $key (sort(split(/\:/,
2307: $$returnhash{$version.':keys'}))) {
2308: $lasthash{$key}=$$returnhash{$version.':'.$key};
2309: $timestamp =
2310: scalar(localtime($$returnhash{$version.':timestamp'}));
2311: }
2312: }
2313: foreach my $key (keys(%lasthash)) {
2314: next if ($key !~ /\.submission$/);
2315:
2316: my ($partid,$foo) = split(/submission$/,$key);
2317: my $draft = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
2318: '<span class="LC_warning">Draft Copy</span> ' : '';
2319: push(@string, join(':', $key, $draft.$lasthash{$key}));
2320: }
2321: }
2322: if (!@string) {
2323: $string[0] =
2324: '<span class="LC_warning">Nothing submitted - no attempts.</span>';
2325: }
2326: return (\@string,\$timestamp);
2327: }
2328:
2329: #--- High light keywords, with style choosen by user.
2330: sub keywords_highlight {
2331: my $string = shift;
2332: my $size = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
2333: my $styleon = $env{'form.kwstyle'} eq '' ? '' : $env{'form.kwstyle'};
2334: (my $styleoff = $styleon) =~ s/\</\<\//;
2335: my @keylist = split(/[,\s+]/,$env{'form.keywords'});
2336: foreach my $keyword (@keylist) {
2337: $string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
2338: }
2339: return $string;
2340: }
2341:
2342: #--- Called from submission routine
2343: sub processHandGrade {
2344: my ($request) = shift;
2345: my $symb = &get_symb($request);
2346: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
2347: my $button = $env{'form.gradeOpt'};
2348: my $ngrade = $env{'form.NCT'};
2349: my $ntstu = $env{'form.NTSTU'};
2350: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2351: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2352:
2353: if ($button eq 'Save & Next') {
2354: my $ctr = 0;
2355: while ($ctr < $ngrade) {
2356: my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
2357: my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
2358: if ($errorflag eq 'no_score') {
2359: $ctr++;
2360: next;
2361: }
2362: if ($errorflag eq 'not_allowed') {
2363: $request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
2364: $ctr++;
2365: next;
2366: }
2367: my $includemsg = $env{'form.includemsg'.$ctr};
2368: my ($subject,$message,$msgstatus) = ('','','');
2369: my $restitle = &Apache::lonnet::gettitle($symb);
2370: my ($feedurl,$showsymb) =
2371: &get_feedurl_and_symb($symb,$uname,$udom);
2372: my $messagetail;
2373: if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
2374: $subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
2375: unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
2376: $subject.=' ['.$restitle.']';
2377: my (@msgnum) = split(/,/,$includemsg);
2378: foreach (@msgnum) {
2379: $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
2380: }
2381: $message =&Apache::lonfeedback::clear_out_html($message);
2382: if ($env{'form.withgrades'.$ctr}) {
2383: $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
2384: $messagetail = " for <a href=\"".
2385: $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
2386: }
2387: $msgstatus =
2388: &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
2389: $message.$messagetail,
2390: undef,$feedurl,undef,
2391: undef,undef,$showsymb,
2392: $restitle);
2393: $request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
2394: $msgstatus);
2395: }
2396: if ($env{'form.collaborator'.$ctr}) {
2397: my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
2398: foreach my $collabstr (@collabstrs) {
2399: my ($part,@collaborators) = split(/:/,$collabstr);
2400: foreach my $collaborator (@collaborators) {
2401: my ($errorflag,$pts,$wgt) =
2402: &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
2403: $env{'form.unamedom'.$ctr},$part);
2404: if ($errorflag eq 'not_allowed') {
2405: $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
2406: next;
2407: } elsif ($message ne '') {
2408: my ($baseurl,$showsymb) =
2409: &get_feedurl_and_symb($symb,$collaborator,
2410: $udom);
2411: if ($env{'form.withgrades'.$ctr}) {
2412: $messagetail = " for <a href=\"".
2413: $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
2414: }
2415: $msgstatus =
2416: &Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
2417: }
2418: }
2419: }
2420: }
2421: $ctr++;
2422: }
2423: }
2424:
2425: if ($env{'form.handgrade'} eq 'yes') {
2426: # Keywords sorted in alphabatical order
2427: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
2428: my %keyhash = ();
2429: $env{'form.keywords'} =~ s/,\s{0,}|\s+/ /g;
2430: $env{'form.keywords'} =~ s/^\s+|\s+$//;
2431: my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
2432: $env{'form.keywords'} = join(' ',@keywords);
2433: $keyhash{$symb.'_keywords'} = $env{'form.keywords'};
2434: $keyhash{$symb.'_subject'} = $env{'form.msgsub'};
2435: $keyhash{$loginuser.'_kwclr'} = $env{'form.kwclr'};
2436: $keyhash{$loginuser.'_kwsize'} = $env{'form.kwsize'};
2437: $keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
2438:
2439: # message center - Order of message gets changed. Blank line is eliminated.
2440: # New messages are saved in env for the next student.
2441: # All messages are saved in nohist_handgrade.db
2442: my ($ctr,$idx) = (1,1);
2443: while ($ctr <= $env{'form.savemsgN'}) {
2444: if ($env{'form.savemsg'.$ctr} ne '') {
2445: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
2446: $idx++;
2447: }
2448: $ctr++;
2449: }
2450: $ctr = 0;
2451: while ($ctr < $ngrade) {
2452: if ($env{'form.newmsg'.$ctr} ne '') {
2453: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2454: $env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2455: $idx++;
2456: }
2457: $ctr++;
2458: }
2459: $env{'form.savemsgN'} = --$idx;
2460: $keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
2461: my $putresult = &Apache::lonnet::put
2462: ('nohist_handgrade',\%keyhash,$cdom,$cnum);
2463: }
2464: # Called by Save & Refresh from Highlight Attribute Window
2465: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
2466: if ($env{'form.refresh'} eq 'on') {
2467: my ($ctr,$total) = (0,0);
2468: while ($ctr < $ngrade) {
2469: $total++ if $env{'form.unamedom'.$ctr} ne '';
2470: $ctr++;
2471: }
2472: $env{'form.NTSTU'}=$ngrade;
2473: $ctr = 0;
2474: while ($ctr < $total) {
2475: my $processUser = $env{'form.unamedom'.$ctr};
2476: ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
2477: $env{'form.fullname'} = $$fullname{$processUser};
2478: &submission($request,$ctr,$total-1);
2479: $ctr++;
2480: }
2481: return '';
2482: }
2483:
2484: # Go directly to grade student - from submission or link from chart page
2485: if ($button eq 'Grade Student') {
2486: (undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
2487: my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
2488: ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
2489: $env{'form.fullname'} = $$fullname{$processUser};
2490: &submission($request,0,0);
2491: return '';
2492: }
2493:
2494: # Get the next/previous one or group of students
2495: my $firststu = $env{'form.unamedom0'};
2496: my $laststu = $env{'form.unamedom'.($ngrade-1)};
2497: my $ctr = 2;
2498: while ($laststu eq '') {
2499: $laststu = $env{'form.unamedom'.($ngrade-$ctr)};
2500: $ctr++;
2501: $laststu = $firststu if ($ctr > $ngrade);
2502: }
2503:
2504: my (@parsedlist,@nextlist);
2505: my ($nextflg) = 0;
2506: foreach (sort
2507: {
2508: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
2509: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
2510: }
2511: return $a cmp $b;
2512: } (keys(%$fullname))) {
2513: if ($nextflg == 1 && $button =~ /Next$/) {
2514: push @parsedlist,$_;
2515: }
2516: $nextflg = 1 if ($_ eq $laststu);
2517: if ($button eq 'Previous') {
2518: last if ($_ eq $firststu);
2519: push @parsedlist,$_;
2520: }
2521: }
2522: $ctr = 0;
2523: @parsedlist = reverse @parsedlist if ($button eq 'Previous');
2524: my ($partlist) = &response_type($symb);
2525: foreach my $student (@parsedlist) {
2526: my $submitonly=$env{'form.submitonly'};
2527: my ($uname,$udom) = split(/:/,$student);
2528:
2529: if ($submitonly eq 'queued') {
2530: my %queue_status =
2531: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
2532: $udom,$uname);
2533: next if (!defined($queue_status{'gradingqueue'}));
2534: }
2535:
2536: if ($submitonly =~ /^(yes|graded|incorrect)$/) {
2537: # my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
2538: my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
2539: my $submitted = 0;
2540: my $ungraded = 0;
2541: my $incorrect = 0;
2542: foreach (keys(%status)) {
2543: $submitted = 1 if ($status{$_} ne 'nothing');
2544: $ungraded = 1 if ($status{$_} =~ /^ungraded/);
2545: $incorrect = 1 if ($status{$_} =~ /^incorrect/);
2546: my ($foo,$partid,$foo1) = split(/\./,$_);
2547: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
2548: $submitted = 0;
2549: }
2550: }
2551: next if (!$submitted && ($submitonly eq 'yes' ||
2552: $submitonly eq 'incorrect' ||
2553: $submitonly eq 'graded'));
2554: next if (!$ungraded && ($submitonly eq 'graded'));
2555: next if (!$incorrect && $submitonly eq 'incorrect');
2556: }
2557: push @nextlist,$student if ($ctr < $ntstu);
2558: last if ($ctr == $ntstu);
2559: $ctr++;
2560: }
2561:
2562: $ctr = 0;
2563: my $total = scalar(@nextlist)-1;
2564:
2565: foreach (sort @nextlist) {
2566: my ($uname,$udom,$submitter) = split(/:/);
2567: $env{'form.student'} = $uname;
2568: $env{'form.userdom'} = $udom;
2569: $env{'form.fullname'} = $$fullname{$_};
2570: &submission($request,$ctr,$total);
2571: $ctr++;
2572: }
2573: if ($total < 0) {
2574: my $the_end = '<h3><span class="LC_info">LON-CAPA User Message</span></h3><br />'."\n";
2575: $the_end.='<b>Message: </b> No more students for this section or class.<br /><br />'."\n";
2576: $the_end.='Click on the button below to return to the grading menu.<br /><br />'."\n";
2577: $the_end.=&show_grading_menu_form($symb);
2578: $request->print($the_end);
2579: }
2580: return '';
2581: }
2582:
2583: #---- Save the score and award for each student, if changed
2584: sub saveHandGrade {
2585: my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
2586: my @version_parts;
2587: my $usec = &Apache::lonnet::getsection($domain,$stuname,
2588: $env{'request.course.id'});
2589: if (!&canmodify($usec)) { return('not_allowed'); }
2590: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
2591: my @parts_graded;
2592: my %newrecord = ();
2593: my ($pts,$wgt) = ('','');
2594: my %aggregate = ();
2595: my $aggregateflag = 0;
2596: my @parts = split(/:/,$env{'form.partlist'.$newflg});
2597: foreach my $new_part (@parts) {
2598: #collaborator ($submi may vary for different parts
2599: if ($submitter && $new_part ne $part) { next; }
2600: my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
2601: if ($dropMenu eq 'excused') {
2602: if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
2603: $newrecord{'resource.'.$new_part.'.solved'} = 'excused';
2604: if (exists($record{'resource.'.$new_part.'.awarded'})) {
2605: $newrecord{'resource.'.$new_part.'.awarded'} = '';
2606: }
2607: $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
2608: }
2609: } elsif ($dropMenu eq 'reset status'
2610: && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
2611: foreach my $key (keys (%record)) {
2612: if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
2613: }
2614: $newrecord{'resource.'.$new_part.'.regrader'}=
2615: "$env{'user.name'}:$env{'user.domain'}";
2616: my $totaltries = $record{'resource.'.$part.'.tries'};
2617:
2618: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
2619: [$new_part]);
2620: my $aggtries =$totaltries;
2621: if ($last_resets{$new_part}) {
2622: $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
2623: $new_part);
2624: }
2625:
2626: my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
2627: if ($aggtries > 0) {
2628: &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
2629: $aggregateflag = 1;
2630: }
2631: } elsif ($dropMenu eq '') {
2632: $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ?
2633: $env{'form.GD_BOX'.$newflg.'_'.$new_part} :
2634: $env{'form.RADVAL'.$newflg.'_'.$new_part});
2635: if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
2636: next;
2637: }
2638: $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 :
2639: $env{'form.WGT'.$newflg.'_'.$new_part};
2640: my $partial= $pts/$wgt;
2641: if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
2642: #do not update score for part if not changed.
2643: &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
2644: next;
2645: } else {
2646: push @parts_graded, $new_part;
2647: }
2648: if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
2649: $newrecord{'resource.'.$new_part.'.awarded'} = $partial;
2650: }
2651: my $reckey = 'resource.'.$new_part.'.solved';
2652: if ($partial == 0) {
2653: if ($record{$reckey} ne 'incorrect_by_override') {
2654: $newrecord{$reckey} = 'incorrect_by_override';
2655: }
2656: } else {
2657: if ($record{$reckey} ne 'correct_by_override') {
2658: $newrecord{$reckey} = 'correct_by_override';
2659: }
2660: }
2661: if ($submitter &&
2662: ($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
2663: $newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
2664: }
2665: $newrecord{'resource.'.$new_part.'.regrader'}=
2666: "$env{'user.name'}:$env{'user.domain'}";
2667: }
2668: # unless problem has been graded, set flag to version the submitted files
2669: unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/ ||
2670: $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
2671: $dropMenu eq 'reset status')
2672: {
2673: push (@version_parts,$new_part);
2674: }
2675: }
2676: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2677: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2678:
2679: if (%newrecord) {
2680: if (@version_parts) {
2681: my @changed_keys = &version_portfiles(\%record, \@parts_graded,
2682: $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
2683: @newrecord{@changed_keys} = @record{@changed_keys};
2684: foreach my $new_part (@version_parts) {
2685: &handback_files($request,$symb,$stuname,$domain,$newflg,
2686: $new_part,\%newrecord);
2687: }
2688: }
2689: &Apache::lonnet::cstore(\%newrecord,$symb,
2690: $env{'request.course.id'},$domain,$stuname);
2691: &check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
2692: $cdom,$cnum,$domain,$stuname);
2693: }
2694: if ($aggregateflag) {
2695: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
2696: $cdom,$cnum);
2697: }
2698: return ('',$pts,$wgt);
2699: }
2700:
2701: sub check_and_remove_from_queue {
2702: my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
2703: my @ungraded_parts;
2704: foreach my $part (@{$parts}) {
2705: if ( $record->{ 'resource.'.$part.'.awarded'} eq ''
2706: && $record->{ 'resource.'.$part.'.solved' } ne 'excused'
2707: && $newrecord->{'resource.'.$part.'.awarded'} eq ''
2708: && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
2709: ) {
2710: push(@ungraded_parts, $part);
2711: }
2712: }
2713: if ( !@ungraded_parts ) {
2714: &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
2715: $cnum,$domain,$stuname);
2716: }
2717: }
2718:
2719: sub handback_files {
2720: my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
2721: my $portfolio_root = &propath($domain,$stuname).'/userfiles/portfolio';
2722: my ($partlist,$handgrade,$responseType) = &response_type($symb);
2723:
2724: my @part_response_id = &flatten_responseType($responseType);
2725: foreach my $part_response_id (@part_response_id) {
2726: my ($part_id,$resp_id) = @{ $part_response_id };
2727: my $part_resp = join('_',@{ $part_response_id });
2728: if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
2729: # if multiple files are uploaded names will be 'returndoc2','returndoc3'
2730: my $file_counter = 1;
2731: my $file_msg;
2732: while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
2733: my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
2734: my ($directory,$answer_file) =
2735: ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
2736: my ($answer_name,$answer_ver,$answer_ext) =
2737: &file_name_version_ext($answer_file);
2738: my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
2739: my @dir_list = &Apache::lonnet::dirlist($portfolio_path,$domain,$stuname,$portfolio_root);
2740: my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
2741: # fix file name
2742: my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
2743: my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
2744: $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
2745: $save_file_name);
2746: if ($result !~ m|^/uploaded/|) {
2747: $request->print('<span class="LC_error">An error occurred ('.$result.
2748: ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</span><br />');
2749: } else {
2750: # mark the file as read only
2751: my @files = ($save_file_name);
2752: my @what = ($symb,$env{'request.course.id'},'handback');
2753: &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
2754: if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
2755: $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
2756: }
2757: $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
2758: $file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
2759:
2760: }
2761: $request->print("<br />".$fname." will be the uploaded file name");
2762: $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
2763: $file_counter++;
2764: }
2765: my $subject = "File Handed Back by Instructor ";
2766: my $message = "A file has been returned that was originally submitted in reponse to: <br />";
2767: $message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
2768: $message .= ' The returned file(s) are named: '. $file_msg;
2769: $message .= " and can be found in your portfolio space.";
2770: my ($feedurl,$showsymb) =
2771: &get_feedurl_and_symb($symb,$domain,$stuname);
2772: my $restitle = &Apache::lonnet::gettitle($symb);
2773: my $msgstatus =
2774: &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
2775: ' (File Returned) ['.$restitle.']',$message,undef,
2776: $feedurl,undef,undef,undef,$showsymb,$restitle);
2777: }
2778: }
2779: return;
2780: }
2781:
2782: sub get_feedurl_and_symb {
2783: my ($symb,$uname,$udom) = @_;
2784: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
2785: $url = &Apache::lonnet::clutter($url);
2786: my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
2787: $symb,$udom,$uname);
2788: if ($encrypturl =~ /^yes$/i) {
2789: &Apache::lonenc::encrypted(\$url,1);
2790: &Apache::lonenc::encrypted(\$symb,1);
2791: }
2792: return ($url,$symb);
2793: }
2794:
2795: sub get_submitted_files {
2796: my ($udom,$uname,$partid,$respid,$record) = @_;
2797: my @files;
2798: if ($$record{"resource.$partid.$respid.portfiles"}) {
2799: my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
2800: foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
2801: push(@files,$file_url.$file);
2802: }
2803: }
2804: if ($$record{"resource.$partid.$respid.uploadedurl"}) {
2805: push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
2806: }
2807: return (\@files);
2808: }
2809:
2810: # ----------- Provides number of tries since last reset.
2811: sub get_num_tries {
2812: my ($record,$last_reset,$part) = @_;
2813: my $timestamp = '';
2814: my $num_tries = 0;
2815: if ($$record{'version'}) {
2816: for (my $version=$$record{'version'};$version>=1;$version--) {
2817: if (exists($$record{$version.':resource.'.$part.'.solved'})) {
2818: $timestamp = $$record{$version.':timestamp'};
2819: if ($timestamp > $last_reset) {
2820: $num_tries ++;
2821: } else {
2822: last;
2823: }
2824: }
2825: }
2826: }
2827: return $num_tries;
2828: }
2829:
2830: # ----------- Determine decrements required in aggregate totals
2831: sub decrement_aggs {
2832: my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
2833: my %decrement = (
2834: attempts => 0,
2835: users => 0,
2836: correct => 0
2837: );
2838: $decrement{'attempts'} = $aggtries;
2839: if ($solvedstatus =~ /^correct/) {
2840: $decrement{'correct'} = 1;
2841: }
2842: if ($aggtries == $totaltries) {
2843: $decrement{'users'} = 1;
2844: }
2845: foreach my $type (keys (%decrement)) {
2846: $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
2847: }
2848: return;
2849: }
2850:
2851: # ----------- Determine timestamps for last reset of aggregate totals for parts
2852: sub get_last_resets {
2853: my ($symb,$courseid,$partids) =@_;
2854: my %last_resets;
2855: my $cdom = $env{'course.'.$courseid.'.domain'};
2856: my $cname = $env{'course.'.$courseid.'.num'};
2857: my @keys;
2858: foreach my $part (@{$partids}) {
2859: push(@keys,"$symb\0$part\0resettime");
2860: }
2861: my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
2862: $cdom,$cname);
2863: foreach my $part (@{$partids}) {
2864: $last_resets{$part}=$results{"$symb\0$part\0resettime"};
2865: }
2866: return %last_resets;
2867: }
2868:
2869: # ----------- Handles creating versions for portfolio files as answers
2870: sub version_portfiles {
2871: my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
2872: my $version_parts = join('|',@$v_flag);
2873: my @returned_keys;
2874: my $parts = join('|', @$parts_graded);
2875: my $portfolio_root = &propath($domain,$stu_name).
2876: '/userfiles/portfolio';
2877: foreach my $key (keys(%$record)) {
2878: my $new_portfiles;
2879: if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
2880: my @versioned_portfiles;
2881: my @portfiles = split(/\s*,\s*/,$$record{$key});
2882: foreach my $file (@portfiles) {
2883: &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
2884: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
2885: my ($answer_name,$answer_ver,$answer_ext) =
2886: &file_name_version_ext($answer_file);
2887: my @dir_list = &Apache::lonnet::dirlist($directory,$domain,$stu_name,$portfolio_root);
2888: my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
2889: my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
2890: if ($new_answer ne 'problem getting file') {
2891: push(@versioned_portfiles, $directory.$new_answer);
2892: &Apache::lonnet::mark_as_readonly($domain,$stu_name,
2893: [$directory.$new_answer],
2894: [$symb,$env{'request.course.id'},'graded']);
2895: }
2896: }
2897: $$record{$key} = join(',',@versioned_portfiles);
2898: push(@returned_keys,$key);
2899: }
2900: }
2901: return (@returned_keys);
2902: }
2903:
2904: sub get_next_version {
2905: my ($answer_name, $answer_ext, $dir_list) = @_;
2906: my $version;
2907: foreach my $row (@$dir_list) {
2908: my ($file) = split(/\&/,$row,2);
2909: my ($file_name,$file_version,$file_ext) =
2910: &file_name_version_ext($file);
2911: if (($file_name eq $answer_name) &&
2912: ($file_ext eq $answer_ext)) {
2913: # gets here if filename and extension match, regardless of version
2914: if ($file_version ne '') {
2915: # a versioned file is found so save it for later
2916: if ($file_version > $version) {
2917: $version = $file_version;
2918: }
2919: }
2920: }
2921: }
2922: $version ++;
2923: return($version);
2924: }
2925:
2926: sub version_selected_portfile {
2927: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
2928: my ($answer_name,$answer_ver,$answer_ext) =
2929: &file_name_version_ext($file_name);
2930: my $new_answer;
2931: $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
2932: if($env{'form.copy'} eq '-1') {
2933: $new_answer = 'problem getting file';
2934: } else {
2935: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
2936: my $copy_result = &Apache::lonnet::finishuserfileupload(
2937: $stu_name,$domain,'copy',
2938: '/portfolio'.$directory.$new_answer);
2939: }
2940: return ($new_answer);
2941: }
2942:
2943: sub file_name_version_ext {
2944: my ($file)=@_;
2945: my @file_parts = split(/\./, $file);
2946: my ($name,$version,$ext);
2947: if (@file_parts > 1) {
2948: $ext=pop(@file_parts);
2949: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
2950: $version=pop(@file_parts);
2951: }
2952: $name=join('.',@file_parts);
2953: } else {
2954: $name=join('.',@file_parts);
2955: }
2956: return($name,$version,$ext);
2957: }
2958:
2959: #--------------------------------------------------------------------------------------
2960: #
2961: #-------------------------- Next few routines handles grading by section or whole class
2962: #
2963: #--- Javascript to handle grading by section or whole class
2964: sub viewgrades_js {
2965: my ($request) = shift;
2966:
2967: $request->print(<<VIEWJAVASCRIPT);
2968: <script type="text/javascript" language="javascript">
2969: function writePoint(partid,weight,point) {
2970: var radioButton = document.classgrade["RADVAL_"+partid];
2971: var textbox = document.classgrade["TEXTVAL_"+partid];
2972: if (point == "textval") {
2973: point = document.classgrade["TEXTVAL_"+partid].value;
2974: if (isNaN(point) || parseFloat(point) < 0) {
2975: alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
2976: var resetbox = false;
2977: for (var i=0; i<radioButton.length; i++) {
2978: if (radioButton[i].checked) {
2979: textbox.value = i;
2980: resetbox = true;
2981: }
2982: }
2983: if (!resetbox) {
2984: textbox.value = "";
2985: }
2986: return;
2987: }
2988: if (parseFloat(point) > parseFloat(weight)) {
2989: var resp = confirm("You entered a value ("+parseFloat(point)+
2990: ") greater than the weight for the part. Accept?");
2991: if (resp == false) {
2992: textbox.value = "";
2993: return;
2994: }
2995: }
2996: for (var i=0; i<radioButton.length; i++) {
2997: radioButton[i].checked=false;
2998: if (parseFloat(point) == i) {
2999: radioButton[i].checked=true;
3000: }
3001: }
3002:
3003: } else {
3004: textbox.value = parseFloat(point);
3005: }
3006: for (i=0;i<document.classgrade.total.value;i++) {
3007: var user = document.classgrade["ctr"+i].value;
3008: user = user.replace(new RegExp(':', 'g'),"_");
3009: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3010: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3011: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3012: if (saveval != "correct") {
3013: scorename.value = point;
3014: if (selname[0].selected != true) {
3015: selname[0].selected = true;
3016: }
3017: }
3018: }
3019: document.classgrade["SELVAL_"+partid][0].selected = true;
3020: }
3021:
3022: function writeRadText(partid,weight) {
3023: var selval = document.classgrade["SELVAL_"+partid];
3024: var radioButton = document.classgrade["RADVAL_"+partid];
3025: var override = document.classgrade["FORCE_"+partid].checked;
3026: var textbox = document.classgrade["TEXTVAL_"+partid];
3027: if (selval[1].selected || selval[2].selected) {
3028: for (var i=0; i<radioButton.length; i++) {
3029: radioButton[i].checked=false;
3030:
3031: }
3032: textbox.value = "";
3033:
3034: for (i=0;i<document.classgrade.total.value;i++) {
3035: var user = document.classgrade["ctr"+i].value;
3036: user = user.replace(new RegExp(':', 'g'),"_");
3037: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3038: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3039: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3040: if ((saveval != "correct") || override) {
3041: scorename.value = "";
3042: if (selval[1].selected) {
3043: selname[1].selected = true;
3044: } else {
3045: selname[2].selected = true;
3046: if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value))
3047: {document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
3048: }
3049: }
3050: }
3051: } else {
3052: for (i=0;i<document.classgrade.total.value;i++) {
3053: var user = document.classgrade["ctr"+i].value;
3054: user = user.replace(new RegExp(':', 'g'),"_");
3055: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3056: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3057: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3058: if ((saveval != "correct") || override) {
3059: scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
3060: selname[0].selected = true;
3061: }
3062: }
3063: }
3064: }
3065:
3066: function changeSelect(partid,user) {
3067: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
3068: var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
3069: var point = textbox.value;
3070: var weight = document.classgrade["weight_"+partid].value;
3071:
3072: if (isNaN(point) || parseFloat(point) < 0) {
3073: alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
3074: textbox.value = "";
3075: return;
3076: }
3077: if (parseFloat(point) > parseFloat(weight)) {
3078: var resp = confirm("You entered a value ("+parseFloat(point)+
3079: ") greater than the weight of the part. Accept?");
3080: if (resp == false) {
3081: textbox.value = "";
3082: return;
3083: }
3084: }
3085: selval[0].selected = true;
3086: }
3087:
3088: function changeOneScore(partid,user) {
3089: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
3090: if (selval[1].selected || selval[2].selected) {
3091: document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
3092: if (selval[2].selected) {
3093: document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
3094: }
3095: }
3096: }
3097:
3098: function resetEntry(numpart) {
3099: for (ctpart=0;ctpart<numpart;ctpart++) {
3100: var partid = document.classgrade["partid_"+ctpart].value;
3101: var radioButton = document.classgrade["RADVAL_"+partid];
3102: var textbox = document.classgrade["TEXTVAL_"+partid];
3103: var selval = document.classgrade["SELVAL_"+partid];
3104: for (var i=0; i<radioButton.length; i++) {
3105: radioButton[i].checked=false;
3106:
3107: }
3108: textbox.value = "";
3109: selval[0].selected = true;
3110:
3111: for (i=0;i<document.classgrade.total.value;i++) {
3112: var user = document.classgrade["ctr"+i].value;
3113: user = user.replace(new RegExp(':', 'g'),"_");
3114: var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3115: resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
3116: var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
3117: resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
3118: var saveselval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3119: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3120: if (saveselval == "excused") {
3121: if (selname[1].selected == false) { selname[1].selected = true;}
3122: } else {
3123: if (selname[0].selected == false) {selname[0].selected = true};
3124: }
3125: }
3126: }
3127: }
3128:
3129: </script>
3130: VIEWJAVASCRIPT
3131: }
3132:
3133: #--- show scores for a section or whole class w/ option to change/update a score
3134: sub viewgrades {
3135: my ($request) = shift;
3136: &viewgrades_js($request);
3137:
3138: my ($symb) = &get_symb($request);
3139: #need to make sure we have the correct data for later EXT calls,
3140: #thus invalidate the cache
3141: &Apache::lonnet::devalidatecourseresdata(
3142: $env{'course.'.$env{'request.course.id'}.'.num'},
3143: $env{'course.'.$env{'request.course.id'}.'.domain'});
3144: &Apache::lonnet::clear_EXT_cache_status();
3145:
3146: my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
3147: $result.='<h4><b>Current Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n";
3148:
3149: #view individual student submission form - called using Javascript viewOneStudent
3150: $result.=&jscriptNform($symb);
3151:
3152: #beginning of class grading form
3153: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
3154: $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
3155: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
3156: '<input type="hidden" name="command" value="editgrades" />'."\n".
3157: &build_section_inputs().
3158: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
3159: '<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
3160: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
3161:
3162: my $sectionClass;
3163: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3164: if ($env{'form.section'} eq 'all') {
3165: $sectionClass='Class </h3>';
3166: } elsif ($env{'form.section'} eq 'none') {
3167: $sectionClass=&mt('Students in no Section').'</h3>';
3168: } else {
3169: $sectionClass=&mt('Students in Section(s) [_1]',$section_display).'</h3>';
3170: }
3171: $result.='<h3>'.&mt('Assign Common Grade To [_1]',$sectionClass);
3172: $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
3173: '<table border=0><tr bgcolor="#ffffdd"><td>';
3174: #radio buttons/text box for assigning points for a section or class.
3175: #handles different parts of a problem
3176: my ($partlist,$handgrade,$responseType) = &response_type($symb);
3177: my %weight = ();
3178: my $ctsparts = 0;
3179: $result.='<table border="0">';
3180: my %seen = ();
3181: my @part_response_id = &flatten_responseType($responseType);
3182: foreach my $part_response_id (@part_response_id) {
3183: my ($partid,$respid) = @{ $part_response_id };
3184: my $part_resp = join('_',@{ $part_response_id });
3185: next if $seen{$partid};
3186: $seen{$partid}++;
3187: my $handgrade=$$handgrade{$part_resp};
3188: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
3189: $weight{$partid} = $wgt eq '' ? '1' : $wgt;
3190:
3191: $result.='<input type="hidden" name="partid_'.
3192: $ctsparts.'" value="'.$partid.'" />'."\n";
3193: $result.='<input type="hidden" name="weight_'.
3194: $partid.'" value="'.$weight{$partid}.'" />'."\n";
3195: my $display_part=&get_display_part($partid,$symb);
3196: $result.='<tr><td><b>Part:</b> '.$display_part.' <b>Point:</b> </td><td>';
3197: $result.='<table border="0"><tr>';
3198: my $ctr = 0;
3199: while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
3200: $result.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
3201: 'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
3202: ','.$ctr.')" />'.$ctr."</label></td>\n";
3203: $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
3204: $ctr++;
3205: }
3206: $result.='</tr></table>';
3207: $result.= '</td><td><b> or </b><input type="text" name="TEXTVAL_'.
3208: $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
3209: $partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
3210: $weight{$partid}.' (problem weight)</td>'."\n";
3211: $result.= '</td><td><select name="SELVAL_'.$partid.'"'.
3212: 'onChange="javascript:writeRadText(\''.$partid.'\','.
3213: $weight{$partid}.')"> '.
3214: '<option selected="selected"> </option>'.
3215: '<option>excused</option>'.
3216: '<option>reset status</option></select></td>'.
3217: '<td><label><input type="checkbox" name="FORCE_'.$partid.'" /> Override "Correct"</label></td></tr>'."\n";
3218: $ctsparts++;
3219: }
3220: $result.='</table>'.'</td></tr></table>'.'</td></tr></table>'."\n".
3221: '<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
3222: $result.='<input type="button" value="Revert to Default" '.
3223: 'onClick="javascript:resetEntry('.$ctsparts.');" target="_self" />';
3224:
3225: #table listing all the students in a section/class
3226: #header of table
3227: $result.= '<h3>Assign Grade to Specific Students in '.$sectionClass;
3228: $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
3229: '<table border=0><tr bgcolor="#deffff"><td> <b>No.</b> </td>'.
3230: '<td>'.&nameUserString('header')."</td>\n";
3231: my (@parts) = sort(&getpartlist($symb));
3232: my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
3233: my @partids = ();
3234: foreach my $part (@parts) {
3235: my $display=&Apache::lonnet::metadata($url,$part.'.display');
3236: $display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
3237: if (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
3238: my ($partid) = &split_part_type($part);
3239: push(@partids, $partid);
3240: my $display_part=&get_display_part($partid,$symb);
3241: if ($display =~ /^Partial Credit Factor/) {
3242: $result.='<td><b>Score Part:</b> '.$display_part.
3243: ' <br /><b>(weight = '.$weight{$partid}.')</b></td>'."\n";
3244: next;
3245: } else {
3246: $display =~s/\[Part: \Q$partid\E\]/Part:<\/b> $display_part/;
3247: }
3248: $display =~ s|Problem Status|Grade Status<br />|;
3249: $result.='<td><b>'.$display.'</td>'."\n";
3250: }
3251: $result.='</tr>';
3252:
3253: my %last_resets =
3254: &get_last_resets($symb,$env{'request.course.id'},\@partids);
3255:
3256: #get info for each student
3257: #list all the students - with points and grade status
3258: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
3259: my $ctr = 0;
3260: foreach (sort
3261: {
3262: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
3263: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
3264: }
3265: return $a cmp $b;
3266: } (keys(%$fullname))) {
3267: $ctr++;
3268: $result.=&viewstudentgrade($symb,$env{'request.course.id'},
3269: $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
3270: }
3271: $result.='</table></td></tr></table>';
3272: $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
3273: $result.='<input type="button" value="Save" '.
3274: 'onClick="javascript:submit();" target="_self" /></form>'."\n";
3275: if (scalar(%$fullname) eq 0) {
3276: my $colspan=3+scalar(@parts);
3277: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3278: my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
3279: $result='<span class="LC_warning">'.
3280: &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade',
3281: $section_display, $stu_status).
3282: '</span>';
3283: }
3284: $result.=&show_grading_menu_form($symb);
3285: return $result;
3286: }
3287:
3288: #--- call by previous routine to display each student
3289: sub viewstudentgrade {
3290: my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
3291: my ($uname,$udom) = split(/:/,$student);
3292: my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
3293: my %aggregates = ();
3294: my $result='<tr bgcolor="#ffffdd"><td align="right">'.
3295: '<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
3296: "\n".$ctr.' </td><td> '.
3297: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
3298: '\');" target="_self">'.$fullname.'</a> '.
3299: '<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
3300: $student=~s/:/_/; # colon doen't work in javascript for names
3301: foreach my $apart (@$parts) {
3302: my ($part,$type) = &split_part_type($apart);
3303: my $score=$record{"resource.$part.$type"};
3304: $result.='<td align="center">';
3305: my ($aggtries,$totaltries);
3306: unless (exists($aggregates{$part})) {
3307: $totaltries = $record{'resource.'.$part.'.tries'};
3308:
3309: $aggtries = $totaltries;
3310: if ($$last_resets{$part}) {
3311: $aggtries = &get_num_tries(\%record,$$last_resets{$part},
3312: $part);
3313: }
3314: $result.='<input type="hidden" name="'.
3315: 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
3316: $result.='<input type="hidden" name="'.
3317: 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
3318: $aggregates{$part} = 1;
3319: }
3320: if ($type eq 'awarded') {
3321: my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
3322: $result.='<input type="hidden" name="'.
3323: 'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
3324: $result.='<input type="text" name="'.
3325: 'GD_'.$student.'_'.$part.'_awarded" '.
3326: 'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
3327: '\')" value="'.$pts.'" size="4" /></td>'."\n";
3328: } elsif ($type eq 'solved') {
3329: my ($status,$foo)=split(/_/,$score,2);
3330: $status = 'nothing' if ($status eq '');
3331: $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
3332: $part.'_solved_s" value="'.$status.'" />'."\n";
3333: $result.=' <select name="'.
3334: 'GD_'.$student.'_'.$part.'_solved" '.
3335: 'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
3336: $result.= (($status eq 'excused') ? '<option> </option><option selected="selected">excused</option>'
3337: : '<option selected="selected"> </option><option>excused</option>')."\n";
3338: $result.='<option>reset status</option>';
3339: $result.="</select> </td>\n";
3340: } else {
3341: $result.='<input type="hidden" name="'.
3342: 'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
3343: "\n";
3344: $result.='<input type="text" name="'.
3345: 'GD_'.$student.'_'.$part.'_'.$type.'" '.
3346: 'value="'.$score.'" size="4" /></td>'."\n";
3347: }
3348: }
3349: $result.='</tr>';
3350: return $result;
3351: }
3352:
3353: #--- change scores for all the students in a section/class
3354: # record does not get update if unchanged
3355: sub editgrades {
3356: my ($request) = @_;
3357:
3358: my $symb=&get_symb($request);
3359: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3360: my $title='<h3><span class="LC_info">'.&mt('Current Grade Status').'</span></h3>';
3361: $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4><br />'."\n";
3362: $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
3363:
3364: my $result= '<table border="0"><tr><td bgcolor="#777777">'."\n";
3365: $result.= '<table border="0"><tr bgcolor="#deffff">'.
3366: '<td rowspan=2 valign="center"> <b>No.</b> </td>'.
3367: '<td rowspan=2 valign="center">'.&nameUserString('header')."</td>\n";
3368:
3369: my %scoreptr = (
3370: 'correct' =>'correct_by_override',
3371: 'incorrect'=>'incorrect_by_override',
3372: 'excused' =>'excused',
3373: 'ungraded' =>'ungraded_attempted',
3374: 'nothing' => '',
3375: );
3376: my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
3377:
3378: my (@partid);
3379: my %weight = ();
3380: my %columns = ();
3381: my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
3382:
3383: my (@parts) = sort(&getpartlist($symb));
3384: my $header;
3385: while ($ctr < $env{'form.totalparts'}) {
3386: my $partid = $env{'form.partid_'.$ctr};
3387: push @partid,$partid;
3388: $weight{$partid} = $env{'form.weight_'.$partid};
3389: $ctr++;
3390: }
3391: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3392: foreach my $partid (@partid) {
3393: $header .= '<td align="center"> <b>Old Score</b> </td>'.
3394: '<td align="center"> <b>New Score</b> </td>';
3395: $columns{$partid}=2;
3396: foreach my $stores (@parts) {
3397: my ($part,$type) = &split_part_type($stores);
3398: if ($part !~ m/^\Q$partid\E/) { next;}
3399: if ($type eq 'awarded' || $type eq 'solved') { next; }
3400: my $display=&Apache::lonnet::metadata($url,$stores.'.display');
3401: $display =~ s/\[Part: (\w)+\]//;
3402: $display =~ s/Number of Attempts/Tries/;
3403: $header .= '<td align="center"> <b>Old '.$display.'</b> </td>'.
3404: '<td align="center"> <b>New '.$display.'</b> </td>';
3405: $columns{$partid}+=2;
3406: }
3407: }
3408: foreach my $partid (@partid) {
3409: my $display_part=&get_display_part($partid,$symb);
3410: $result .= '<td colspan="'.$columns{$partid}.
3411: '" align="center"><b>Part:</b> '.$display_part.
3412: ' (Weight = '.$weight{$partid}.')</td>';
3413:
3414: }
3415: $result .= '</tr><tr bgcolor="#deffff">';
3416: $result .= $header;
3417: $result .= '</tr>'."\n";
3418: my $noupdate;
3419: my ($updateCtr,$noupdateCtr) = (1,1);
3420: for ($i=0; $i<$env{'form.total'}; $i++) {
3421: my $line;
3422: my $user = $env{'form.ctr'.$i};
3423: my ($uname,$udom)=split(/:/,$user);
3424: my %newrecord;
3425: my $updateflag = 0;
3426: $line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
3427: my $usec=$classlist->{"$uname:$udom"}[5];
3428: if (!&canmodify($usec)) {
3429: my $numcols=scalar(@partid)*4+2;
3430: $noupdate.=$line."<td colspan=\"$numcols\"><span class=\"LC_warning\">Not allowed to modify student</span></td></tr>";
3431: next;
3432: }
3433: my %aggregate = ();
3434: my $aggregateflag = 0;
3435: $user=~s/:/_/; # colon doen't work in javascript for names
3436: foreach (@partid) {
3437: my $old_aw = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
3438: my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
3439: my $old_part = $old_aw eq '' ? '' : $old_part_pcr;
3440: my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
3441: my $awarded = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
3442: my $pcr = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
3443: my $partial = $awarded eq '' ? '' : $pcr;
3444: my $score;
3445: if ($partial eq '') {
3446: $score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
3447: } elsif ($partial > 0) {
3448: $score = 'correct_by_override';
3449: } elsif ($partial == 0) {
3450: $score = 'incorrect_by_override';
3451: }
3452: my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
3453: $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
3454:
3455: $newrecord{'resource.'.$_.'.regrader'}=
3456: "$env{'user.name'}:$env{'user.domain'}";
3457: if ($dropMenu eq 'reset status' &&
3458: $old_score ne '') { # ignore if no previous attempts => nothing to reset
3459: $newrecord{'resource.'.$_.'.tries'} = '';
3460: $newrecord{'resource.'.$_.'.solved'} = '';
3461: $newrecord{'resource.'.$_.'.award'} = '';
3462: $newrecord{'resource.'.$_.'.awarded'} = '';
3463: $updateflag = 1;
3464: if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
3465: my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
3466: my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
3467: my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
3468: &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
3469: $aggregateflag = 1;
3470: }
3471: } elsif (!($old_part eq $partial && $old_score eq $score)) {
3472: $updateflag = 1;
3473: $newrecord{'resource.'.$_.'.awarded'} = $partial if $partial ne '';
3474: $newrecord{'resource.'.$_.'.solved'} = $score;
3475: $rec_update++;
3476: }
3477:
3478: $line .= '<td align="center">'.$old_aw.' </td>'.
3479: '<td align="center">'.$awarded.
3480: ($score eq 'excused' ? $score : '').' </td>';
3481:
3482:
3483: my $partid=$_;
3484: foreach my $stores (@parts) {
3485: my ($part,$type) = &split_part_type($stores);
3486: if ($part !~ m/^\Q$partid\E/) { next;}
3487: if ($type eq 'awarded' || $type eq 'solved') { next; }
3488: my $old_aw = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
3489: my $awarded = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
3490: if ($awarded ne '' && $awarded ne $old_aw) {
3491: $newrecord{'resource.'.$part.'.'.$type}= $awarded;
3492: $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
3493: $updateflag=1;
3494: }
3495: $line .= '<td align="center">'.$old_aw.' </td>'.
3496: '<td align="center">'.$awarded.' </td>';
3497: }
3498: }
3499: $line.='</tr>'."\n";
3500:
3501: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3502: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3503:
3504: if ($updateflag) {
3505: $count++;
3506: &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
3507: $udom,$uname);
3508:
3509: if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
3510: $cnum,$udom,$uname)) {
3511: # need to figure out if should be in queue.
3512: my %record =
3513: &Apache::lonnet::restore($symb,$env{'request.course.id'},
3514: $udom,$uname);
3515: my $all_graded = 1;
3516: my $none_graded = 1;
3517: foreach my $part (@parts) {
3518: if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
3519: $all_graded = 0;
3520: } else {
3521: $none_graded = 0;
3522: }
3523: }
3524:
3525: if ($all_graded || $none_graded) {
3526: &Apache::bridgetask::remove_from_queue('gradingqueue',
3527: $symb,$cdom,$cnum,
3528: $udom,$uname);
3529: }
3530: }
3531:
3532: $result.='<tr bgcolor="#ffffde"><td align="right"> '.$updateCtr.' </td>'.$line;
3533: $updateCtr++;
3534: } else {
3535: $noupdate.='<tr bgcolor="#ffffde"><td align="right"> '.$noupdateCtr.' </td>'.$line;
3536: $noupdateCtr++;
3537: }
3538: if ($aggregateflag) {
3539: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
3540: $cdom,$cnum);
3541: }
3542: }
3543: if ($noupdate) {
3544: # my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
3545: my $numcols=scalar(@partid)*4+2;
3546: $result .= '<tr bgcolor="#ffffff"><td align="center" colspan="'.$numcols.'">No Changes Occurred For the Students Below</td></tr><tr bgcolor="#ffffde">'.$noupdate;
3547: }
3548: $result .= '</table></td></tr></table>'."\n".
3549: &show_grading_menu_form ($symb);
3550: my $msg = '<br /><b>Number of records updated = '.$rec_update.
3551: ' for '.$count.' student'.($count <= 1 ? '' : 's').'.</b><br />'.
3552: '<b>Total number of students = '.$env{'form.total'}.'</b><br />';
3553: return $title.$msg.$result;
3554: }
3555:
3556: sub split_part_type {
3557: my ($partstr) = @_;
3558: my ($temp,@allparts)=split(/_/,$partstr);
3559: my $type=pop(@allparts);
3560: my $part=join('_',@allparts);
3561: return ($part,$type);
3562: }
3563:
3564: #------------- end of section for handling grading by section/class ---------
3565: #
3566: #----------------------------------------------------------------------------
3567:
3568:
3569: #----------------------------------------------------------------------------
3570: #
3571: #-------------------------- Next few routines handles grading by csv upload
3572: #
3573: #--- Javascript to handle csv upload
3574: sub csvupload_javascript_reverse_associate {
3575: my $error1=&mt('You need to specify the username or ID');
3576: my $error2=&mt('You need to specify at least one grading field');
3577: return(<<ENDPICK);
3578: function verify(vf) {
3579: var foundsomething=0;
3580: var founduname=0;
3581: var foundID=0;
3582: for (i=0;i<=vf.nfields.value;i++) {
3583: tw=eval('vf.f'+i+'.selectedIndex');
3584: if (i==0 && tw!=0) { foundID=1; }
3585: if (i==1 && tw!=0) { founduname=1; }
3586: if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
3587: }
3588: if (founduname==0 && foundID==0) {
3589: alert('$error1');
3590: return;
3591: }
3592: if (foundsomething==0) {
3593: alert('$error2');
3594: return;
3595: }
3596: vf.submit();
3597: }
3598: function flip(vf,tf) {
3599: var nw=eval('vf.f'+tf+'.selectedIndex');
3600: var i;
3601: for (i=0;i<=vf.nfields.value;i++) {
3602: //can not pick the same destination field for both name and domain
3603: if (((i ==0)||(i ==1)) &&
3604: ((tf==0)||(tf==1)) &&
3605: (i!=tf) &&
3606: (eval('vf.f'+i+'.selectedIndex')==nw)) {
3607: eval('vf.f'+i+'.selectedIndex=0;')
3608: }
3609: }
3610: }
3611: ENDPICK
3612: }
3613:
3614: sub csvupload_javascript_forward_associate {
3615: my $error1=&mt('You need to specify the username or ID');
3616: my $error2=&mt('You need to specify at least one grading field');
3617: return(<<ENDPICK);
3618: function verify(vf) {
3619: var foundsomething=0;
3620: var founduname=0;
3621: var foundID=0;
3622: for (i=0;i<=vf.nfields.value;i++) {
3623: tw=eval('vf.f'+i+'.selectedIndex');
3624: if (tw==1) { foundID=1; }
3625: if (tw==2) { founduname=1; }
3626: if (tw>3) { foundsomething=1; }
3627: }
3628: if (founduname==0 && foundID==0) {
3629: alert('$error1');
3630: return;
3631: }
3632: if (foundsomething==0) {
3633: alert('$error2');
3634: return;
3635: }
3636: vf.submit();
3637: }
3638: function flip(vf,tf) {
3639: var nw=eval('vf.f'+tf+'.selectedIndex');
3640: var i;
3641: //can not pick the same destination field twice
3642: for (i=0;i<=vf.nfields.value;i++) {
3643: if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
3644: eval('vf.f'+i+'.selectedIndex=0;')
3645: }
3646: }
3647: }
3648: ENDPICK
3649: }
3650:
3651: sub csvuploadmap_header {
3652: my ($request,$symb,$datatoken,$distotal)= @_;
3653: my $javascript;
3654: if ($env{'form.upfile_associate'} eq 'reverse') {
3655: $javascript=&csvupload_javascript_reverse_associate();
3656: } else {
3657: $javascript=&csvupload_javascript_forward_associate();
3658: }
3659:
3660: my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
3661: my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
3662: my $ignore=&mt('Ignore First Line');
3663: $symb = &Apache::lonenc::check_encrypt($symb);
3664: $request->print(<<ENDPICK);
3665: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3666: <h3><span class="LC_info">Uploading Class Grades</span></h3>
3667: $result
3668: <hr />
3669: <h3>Identify fields</h3>
3670: Total number of records found in file: $distotal <hr />
3671: Enter as many fields as you can. The system will inform you and bring you back
3672: to this page if the data selected is insufficient to run your class.<hr />
3673: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
3674: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
3675: <input type="hidden" name="associate" value="" />
3676: <input type="hidden" name="phase" value="three" />
3677: <input type="hidden" name="datatoken" value="$datatoken" />
3678: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
3679: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
3680: <input type="hidden" name="upfile_associate"
3681: value="$env{'form.upfile_associate'}" />
3682: <input type="hidden" name="symb" value="$symb" />
3683: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
3684: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
3685: <input type="hidden" name="command" value="csvuploadoptions" />
3686: <hr />
3687: <script type="text/javascript" language="Javascript">
3688: $javascript
3689: </script>
3690: ENDPICK
3691: return '';
3692:
3693: }
3694:
3695: sub csvupload_fields {
3696: my ($symb) = @_;
3697: my (@parts) = &getpartlist($symb);
3698: my @fields=(['ID','Student ID'],
3699: ['username','Student Username'],
3700: ['domain','Student Domain']);
3701: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3702: foreach my $part (sort(@parts)) {
3703: my @datum;
3704: my $display=&Apache::lonnet::metadata($url,$part.'.display');
3705: my $name=$part;
3706: if (!$display) { $display = $name; }
3707: @datum=($name,$display);
3708: if ($name=~/^stores_(.*)_awarded/) {
3709: push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
3710: }
3711: push(@fields,\@datum);
3712: }
3713: return (@fields);
3714: }
3715:
3716: sub csvuploadmap_footer {
3717: my ($request,$i,$keyfields) =@_;
3718: $request->print(<<ENDPICK);
3719: </table>
3720: <input type="hidden" name="nfields" value="$i" />
3721: <input type="hidden" name="keyfields" value="$keyfields" />
3722: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
3723: </form>
3724: ENDPICK
3725: }
3726:
3727: sub checkforfile_js {
3728: my $result =<<CSVFORMJS;
3729: <script type="text/javascript" language="javascript">
3730: function checkUpload(formname) {
3731: if (formname.upfile.value == "") {
3732: alert("Please use the browse button to select a file from your local directory.");
3733: return false;
3734: }
3735: formname.submit();
3736: }
3737: </script>
3738: CSVFORMJS
3739: return $result;
3740: }
3741:
3742: sub upcsvScores_form {
3743: my ($request) = shift;
3744: my ($symb)=&get_symb($request);
3745: if (!$symb) {return '';}
3746: my $result=&checkforfile_js();
3747: $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
3748: my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
3749: $result.=$table;
3750: $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
3751: $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
3752: $result.=' <b>'.&mt('Specify a file containing the class scores for current resource').
3753: '.</b></td></tr>'."\n";
3754: $result.='<tr bgcolor=#ffffe6><td>'."\n";
3755: my $upload=&mt("Upload Scores");
3756: my $upfile_select=&Apache::loncommon::upfile_select_html();
3757: my $ignore=&mt('Ignore First Line');
3758: $symb = &Apache::lonenc::check_encrypt($symb);
3759: $result.=<<ENDUPFORM;
3760: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3761: <input type="hidden" name="symb" value="$symb" />
3762: <input type="hidden" name="command" value="csvuploadmap" />
3763: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
3764: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
3765: $upfile_select
3766: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
3767: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
3768: </form>
3769: ENDUPFORM
3770: $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
3771: &mt("How do I create a CSV file from a spreadsheet"))
3772: .'</td></tr></table>'."\n";
3773: $result.='</td></tr></table><br /><br />'."\n";
3774: $result.=&show_grading_menu_form($symb);
3775: return $result;
3776: }
3777:
3778:
3779: sub csvuploadmap {
3780: my ($request)= @_;
3781: my ($symb)=&get_symb($request);
3782: if (!$symb) {return '';}
3783:
3784: my $datatoken;
3785: if (!$env{'form.datatoken'}) {
3786: $datatoken=&Apache::loncommon::upfile_store($request);
3787: } else {
3788: $datatoken=$env{'form.datatoken'};
3789: &Apache::loncommon::load_tmp_file($request);
3790: }
3791: my @records=&Apache::loncommon::upfile_record_sep();
3792: if ($env{'form.noFirstLine'}) { shift(@records); }
3793: &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
3794: my ($i,$keyfields);
3795: if (@records) {
3796: my @fields=&csvupload_fields($symb);
3797:
3798: if ($env{'form.upfile_associate'} eq 'reverse') {
3799: &Apache::loncommon::csv_print_samples($request,\@records);
3800: $i=&Apache::loncommon::csv_print_select_table($request,\@records,
3801: \@fields);
3802: foreach (@fields) { $keyfields.=$_->[0].','; }
3803: chop($keyfields);
3804: } else {
3805: unshift(@fields,['none','']);
3806: $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
3807: \@fields);
3808: foreach my $rec (@records) {
3809: my %temp = &Apache::loncommon::record_sep($rec);
3810: if (%temp) {
3811: $keyfields=join(',',sort(keys(%temp)));
3812: last;
3813: }
3814: }
3815: }
3816: }
3817: &csvuploadmap_footer($request,$i,$keyfields);
3818: $request->print(&show_grading_menu_form($symb));
3819:
3820: return '';
3821: }
3822:
3823: sub csvuploadoptions {
3824: my ($request)= @_;
3825: my ($symb)=&get_symb($request);
3826: my $checked=(($env{'form.noFirstLine'})?'1':'0');
3827: my $ignore=&mt('Ignore First Line');
3828: $request->print(<<ENDPICK);
3829: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3830: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
3831: <input type="hidden" name="command" value="csvuploadassign" />
3832: <!--
3833: <p>
3834: <label>
3835: <input type="checkbox" name="show_full_results" />
3836: Show a table of all changes
3837: </label>
3838: </p>
3839: -->
3840: <p>
3841: <label>
3842: <input type="checkbox" name="overwite_scores" checked="checked" />
3843: Overwrite any existing score
3844: </label>
3845: </p>
3846: ENDPICK
3847: my %fields=&get_fields();
3848: if (!defined($fields{'domain'})) {
3849: my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
3850: $request->print("\n<p> Users are in domain: ".$domform."</p>\n");
3851: }
3852: foreach my $key (sort(keys(%env))) {
3853: if ($key !~ /^form\.(.*)$/) { next; }
3854: my $cleankey=$1;
3855: if ($cleankey eq 'command') { next; }
3856: $request->print('<input type="hidden" name="'.$cleankey.
3857: '" value="'.$env{$key}.'" />'."\n");
3858: }
3859: # FIXME do a check for any duplicated user ids...
3860: # FIXME do a check for any invalid user ids?...
3861: $request->print('<input type="submit" value="Assign Grades" /><br />
3862: <hr /></form>'."\n");
3863: $request->print(&show_grading_menu_form($symb));
3864: return '';
3865: }
3866:
3867: sub get_fields {
3868: my %fields;
3869: my @keyfields = split(/\,/,$env{'form.keyfields'});
3870: for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
3871: if ($env{'form.upfile_associate'} eq 'reverse') {
3872: if ($env{'form.f'.$i} ne 'none') {
3873: $fields{$keyfields[$i]}=$env{'form.f'.$i};
3874: }
3875: } else {
3876: if ($env{'form.f'.$i} ne 'none') {
3877: $fields{$env{'form.f'.$i}}=$keyfields[$i];
3878: }
3879: }
3880: }
3881: return %fields;
3882: }
3883:
3884: sub csvuploadassign {
3885: my ($request)= @_;
3886: my ($symb)=&get_symb($request);
3887: if (!$symb) {return '';}
3888: my $error_msg = '';
3889: &Apache::loncommon::load_tmp_file($request);
3890: my @gradedata = &Apache::loncommon::upfile_record_sep();
3891: if ($env{'form.noFirstLine'}) { shift(@gradedata); }
3892: my %fields=&get_fields();
3893: $request->print('<h3>Assigning Grades</h3>');
3894: my $courseid=$env{'request.course.id'};
3895: my ($classlist) = &getclasslist('all',0);
3896: my @notallowed;
3897: my @skipped;
3898: my $countdone=0;
3899: foreach my $grade (@gradedata) {
3900: my %entries=&Apache::loncommon::record_sep($grade);
3901: my $domain;
3902: if ($entries{$fields{'domain'}}) {
3903: $domain=$entries{$fields{'domain'}};
3904: } else {
3905: $domain=$env{'form.default_domain'};
3906: }
3907: $domain=~s/\s//g;
3908: my $username=$entries{$fields{'username'}};
3909: $username=~s/\s//g;
3910: if (!$username) {
3911: my $id=$entries{$fields{'ID'}};
3912: $id=~s/\s//g;
3913: my %ids=&Apache::lonnet::idget($domain,$id);
3914: $username=$ids{$id};
3915: }
3916: if (!exists($$classlist{"$username:$domain"})) {
3917: my $id=$entries{$fields{'ID'}};
3918: $id=~s/\s//g;
3919: if ($id) {
3920: push(@skipped,"$id:$domain");
3921: } else {
3922: push(@skipped,"$username:$domain");
3923: }
3924: next;
3925: }
3926: my $usec=$classlist->{"$username:$domain"}[5];
3927: if (!&canmodify($usec)) {
3928: push(@notallowed,"$username:$domain");
3929: next;
3930: }
3931: my %points;
3932: my %grades;
3933: foreach my $dest (keys(%fields)) {
3934: if ($dest eq 'ID' || $dest eq 'username' ||
3935: $dest eq 'domain') { next; }
3936: if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
3937: if ($dest=~/stores_(.*)_points/) {
3938: my $part=$1;
3939: my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
3940: $symb,$domain,$username);
3941: if ($wgt) {
3942: $entries{$fields{$dest}}=~s/\s//g;
3943: my $pcr=$entries{$fields{$dest}} / $wgt;
3944: my $award=($pcr == 0) ? 'incorrect_by_override'
3945: : 'correct_by_override';
3946: $grades{"resource.$part.awarded"}=$pcr;
3947: $grades{"resource.$part.solved"}=$award;
3948: $points{$part}=1;
3949: } else {
3950: $error_msg = "<br />" .
3951: &mt("Some point values were assigned"
3952: ." for problems with a weight "
3953: ."of zero. These values were "
3954: ."ignored.");
3955: }
3956: } else {
3957: if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
3958: if ($dest=~/stores_(.*)_solved/) { if ($points{$1}) {next;} }
3959: my $store_key=$dest;
3960: $store_key=~s/^stores/resource/;
3961: $store_key=~s/_/\./g;
3962: $grades{$store_key}=$entries{$fields{$dest}};
3963: }
3964: }
3965: if (! %grades) { push(@skipped,"$username:$domain no data to save"); }
3966: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
3967: my $result=&Apache::lonnet::cstore(\%grades,$symb,
3968: $env{'request.course.id'},
3969: $domain,$username);
3970: if ($result eq 'ok') {
3971: $request->print('.');
3972: } else {
3973: $request->print("<p>
3974: <span class=\"LC_error\">
3975: Failed to save student $username:$domain.
3976: Message when trying to save was ($result)
3977: </span>
3978: </p>" );
3979: }
3980: $request->rflush();
3981: $countdone++;
3982: }
3983: $request->print("<br />Saved $countdone students\n");
3984: if (@skipped) {
3985: $request->print('<p><h4><b>Skipped Students</b></h4></p>');
3986: foreach my $student (@skipped) { $request->print("$student<br />\n"); }
3987: }
3988: if (@notallowed) {
3989: $request->print('<p><span class="LC_error">Students Not Allowed to Modify</span></p>');
3990: foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
3991: }
3992: $request->print("<br />\n");
3993: $request->print(&show_grading_menu_form($symb));
3994: return $error_msg;
3995: }
3996: #------------- end of section for handling csv file upload ---------
3997: #
3998: #-------------------------------------------------------------------
3999: #
4000: #-------------- Next few routines handle grading by page/sequence
4001: #
4002: #--- Select a page/sequence and a student to grade
4003: sub pickStudentPage {
4004: my ($request) = shift;
4005:
4006: $request->print(<<LISTJAVASCRIPT);
4007: <script type="text/javascript" language="javascript">
4008:
4009: function checkPickOne(formname) {
4010: if (radioSelection(formname.student) == null) {
4011: alert("Please select the student you wish to grade.");
4012: return;
4013: }
4014: ptr = pullDownSelection(formname.selectpage);
4015: formname.page.value = formname["page"+ptr].value;
4016: formname.title.value = formname["title"+ptr].value;
4017: formname.submit();
4018: }
4019:
4020: </script>
4021: LISTJAVASCRIPT
4022: &commonJSfunctions($request);
4023: my ($symb) = &get_symb($request);
4024: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4025: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4026: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4027:
4028: my $result='<h3><span class="LC_info"> '.
4029: 'Manual Grading by Page or Sequence</span></h3>';
4030:
4031: $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
4032: $result.=' <b>Problems from:</b> <select name="selectpage">'."\n";
4033: my ($titles,$symbx) = &getSymbMap();
4034: my ($curpage) =&Apache::lonnet::decode_symb($symb);
4035: # my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb);
4036: # my $type=($curpage =~ /\.(page|sequence)/);
4037: my $ctr=0;
4038: foreach (@$titles) {
4039: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4040: $result.='<option value="'.$ctr.'" '.
4041: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
4042: '>'.$showtitle.'</option>'."\n";
4043: $ctr++;
4044: }
4045: $result.= '</select>'."<br />\n";
4046: $ctr=0;
4047: foreach (@$titles) {
4048: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4049: $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
4050: $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
4051: $ctr++;
4052: }
4053: $result.='<input type="hidden" name="page" />'."\n".
4054: '<input type="hidden" name="title" />'."\n";
4055:
4056: $result.=' <b>View Problems Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
4057: '<label><input type="radio" name="vProb" value="yes" /> yes </label>'."<br />\n";
4058:
4059: $result.=' <b>Submission Details: </b>'.
4060: '<label><input type="radio" name="lastSub" value="none" /> none</label>'."\n".
4061: '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> by dates and submissions</label>'."\n".
4062: '<label><input type="radio" name="lastSub" value="all" /> all details</label>'."\n";
4063:
4064: $result.=&build_section_inputs();
4065: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
4066: $result.='<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
4067: '<input type="hidden" name="command" value="displayPage" />'."\n".
4068: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
4069: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
4070:
4071: $result.=' <b>'.&mt('Use CODE:').' </b>'.
4072: '<input type="text" name="CODE" value="" /><br />'."\n";
4073:
4074: $result.=' <input type="button" '.
4075: 'onClick="javascript:checkPickOne(this.form);"value="Next->" /><br />'."\n";
4076:
4077: $request->print($result);
4078:
4079: my $studentTable.=' <b>Select a student you wish to grade and then click on the Next button.</b><br />'.
4080: '<table border="0"><tr><td bgcolor="#777777">'.
4081: '<table border="0"><tr bgcolor="#e6ffff">'.
4082: '<td align="right"> <b>No.</b></td>'.
4083: '<td>'.&nameUserString('header').'</td>'.
4084: '<td align="right"> <b>No.</b></td>'.
4085: '<td>'.&nameUserString('header').'</td></tr>';
4086:
4087: my (undef,undef,$fullname) = &getclasslist($getsec,'1');
4088: my $ptr = 1;
4089: foreach my $student (sort
4090: {
4091: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
4092: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
4093: }
4094: return $a cmp $b;
4095: } (keys(%$fullname))) {
4096: my ($uname,$udom) = split(/:/,$student);
4097: $studentTable.=($ptr%2 == 1 ? '<tr bgcolor="#ffffe6">' : '</td>');
4098: $studentTable.='<td align="right">'.$ptr.' </td>';
4099: $studentTable.='<td> <label><input type="radio" name="student" value="'.$student.'" /> '
4100: .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
4101: $studentTable.=($ptr%2 == 0 ? '</td></tr>' : '');
4102: $ptr++;
4103: }
4104: $studentTable.='</td><td> </td><td> </td></tr>' if ($ptr%2 == 0);
4105: $studentTable.='</table></td></tr></table>'."\n";
4106: $studentTable.='<input type="button" '.
4107: 'onClick="javascript:checkPickOne(this.form);"value="Next->" /></form>'."\n";
4108:
4109: $studentTable.=&show_grading_menu_form($symb);
4110: $request->print($studentTable);
4111:
4112: return '';
4113: }
4114:
4115: sub getSymbMap {
4116: my $navmap = Apache::lonnavmaps::navmap->new();
4117:
4118: my %symbx = ();
4119: my @titles = ();
4120: my $minder = 0;
4121:
4122: # Gather every sequence that has problems.
4123: my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
4124: 1,0,1);
4125: for my $sequence ($navmap->getById('0.0'), @sequences) {
4126: if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
4127: my $title = $minder.'.'.
4128: &HTML::Entities::encode($sequence->compTitle(),'"\'&');
4129: push(@titles, $title); # minder in case two titles are identical
4130: $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
4131: $minder++;
4132: }
4133: }
4134: return \@titles,\%symbx;
4135: }
4136:
4137: #
4138: #--- Displays a page/sequence w/wo problems, w/wo submissions
4139: sub displayPage {
4140: my ($request) = shift;
4141:
4142: my ($symb) = &get_symb($request);
4143: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4144: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4145: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4146: my $pageTitle = $env{'form.page'};
4147: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
4148: my ($uname,$udom) = split(/:/,$env{'form.student'});
4149: my $usec=$classlist->{$env{'form.student'}}[5];
4150:
4151: #need to make sure we have the correct data for later EXT calls,
4152: #thus invalidate the cache
4153: &Apache::lonnet::devalidatecourseresdata(
4154: $env{'course.'.$env{'request.course.id'}.'.num'},
4155: $env{'course.'.$env{'request.course.id'}.'.domain'});
4156: &Apache::lonnet::clear_EXT_cache_status();
4157:
4158: if (!&canview($usec)) {
4159: $request->print('<span class="LC_warning">Unable to view requested student.('.$env{'form.student'}.')</span>');
4160: $request->print(&show_grading_menu_form($symb));
4161: return;
4162: }
4163: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
4164: $result.='<h3> Student: '.&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom).
4165: '</h3>'."\n";
4166: if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
4167: $result.='<h3> CODE: '.$env{'form.CODE'}.'</h3>'."\n";
4168: } else {
4169: delete($env{'form.CODE'});
4170: }
4171: &sub_page_js($request);
4172: $request->print($result);
4173:
4174: my $navmap = Apache::lonnavmaps::navmap->new();
4175: my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
4176: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
4177: if (!$map) {
4178: $request->print('<span class="LC_warning">Unable to view requested sequence. ('.$resUrl.')</span>');
4179: $request->print(&show_grading_menu_form($symb));
4180: return;
4181: }
4182: my $iterator = $navmap->getIterator($map->map_start(),
4183: $map->map_finish());
4184:
4185: my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
4186: '<input type="hidden" name="command" value="gradeByPage" />'."\n".
4187: '<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
4188: '<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
4189: '<input type="hidden" name="page" value="'.$pageTitle.'" />'."\n".
4190: '<input type="hidden" name="title" value="'.$env{'form.title'}.'" />'."\n".
4191: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
4192: '<input type="hidden" name="overRideScore" value="no" />'."\n".
4193: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
4194:
4195: if (defined($env{'form.CODE'})) {
4196: $studentTable.=
4197: '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
4198: }
4199: my $checkIcon = '<img alt="'.&mt('Check Mark').
4200: '" src="'.$request->dir_config('lonIconsURL').
4201: '/check.gif" height="16" border="0" />';
4202:
4203: $studentTable.=' <b>Note:</b> Problems graded correct by the computer are marked with a '.$checkIcon.
4204: ' symbol.'."\n".
4205: '<table border="0"><tr><td bgcolor="#777777">'.
4206: '<table border="0"><tr bgcolor="#e6ffff">'.
4207: '<td align="center"><b> Prob. </b></td>'.
4208: '<td><b> '.($env{'form.vProb'} eq 'no' ? 'Title' : 'Problem Text').'/Grade</b></td></tr>';
4209:
4210: &Apache::lonxml::clear_problem_counter();
4211: my ($depth,$question,$prob) = (1,1,1);
4212: $iterator->next(); # skip the first BEGIN_MAP
4213: my $curRes = $iterator->next(); # for "current resource"
4214: while ($depth > 0) {
4215: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
4216: if($curRes == $iterator->END_MAP) { $depth--; }
4217:
4218: if (ref($curRes) && $curRes->is_problem()) {
4219: my $parts = $curRes->parts();
4220: my $title = $curRes->compTitle();
4221: my $symbx = $curRes->symb();
4222: $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
4223: (scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).' parts)').'</td>';
4224: $studentTable.='<td valign="top">';
4225: my %form = ('CODE' => $env{'form.CODE'},);
4226: if ($env{'form.vProb'} eq 'yes' ) {
4227: $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
4228: undef,'both',\%form);
4229: } else {
4230: my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
4231: $companswer =~ s|<form(.*?)>||g;
4232: $companswer =~ s|</form>||g;
4233: # while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
4234: # $companswer =~ s/$1/ /ms;
4235: # $request->print('match='.$1."<br />\n");
4236: # }
4237: # $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
4238: $studentTable.=' <b>'.$title.'</b> <br /> <b>Correct answer:</b><br />'.$companswer;
4239: }
4240:
4241: my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
4242:
4243: if ($env{'form.lastSub'} eq 'datesub') {
4244: if ($record{'version'} eq '') {
4245: $studentTable.='<br /> <span class="LC_warning">No recorded submission for this problem</span><br />';
4246: } else {
4247: my %responseType = ();
4248: foreach my $partid (@{$parts}) {
4249: my @responseIds =$curRes->responseIds($partid);
4250: my @responseType =$curRes->responseType($partid);
4251: my %responseIds;
4252: for (my $i=0;$i<=$#responseIds;$i++) {
4253: $responseIds{$responseIds[$i]}=$responseType[$i];
4254: }
4255: $responseType{$partid} = \%responseIds;
4256: }
4257: $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
4258:
4259: }
4260: } elsif ($env{'form.lastSub'} eq 'all') {
4261: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
4262: $studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
4263: $env{'request.course.id'},
4264: '','.submission');
4265:
4266: }
4267: if (&canmodify($usec)) {
4268: foreach my $partid (@{$parts}) {
4269: $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
4270: $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
4271: $question++;
4272: }
4273: $prob++;
4274: }
4275: $studentTable.='</td></tr>';
4276:
4277: }
4278: $curRes = $iterator->next();
4279: }
4280:
4281: $studentTable.='</table></td></tr></table>'."\n".
4282: '<input type="button" value="Save" '.
4283: 'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
4284: '</form>'."\n";
4285: $studentTable.=&show_grading_menu_form($symb);
4286: $request->print($studentTable);
4287:
4288: return '';
4289: }
4290:
4291: sub displaySubByDates {
4292: my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
4293: my $isCODE=0;
4294: my $isTask = ($symb =~/\.task$/);
4295: if (exists($record->{'resource.CODE'})) { $isCODE=1; }
4296: my $studentTable=&Apache::loncommon::start_data_table().
4297: &Apache::loncommon::start_data_table_header_row().
4298: '<th>'.&mt('Date/Time').'</th>'.
4299: ($isCODE?'<th>'.&mt('CODE').'</th>':'').
4300: '<th>'.&mt('Submission').'</th>'.
4301: '<th>'.&mt('Status').'</th>'.
4302: &Apache::loncommon::end_data_table_header_row();
4303: my ($version);
4304: my %mark;
4305: my %orders;
4306: $mark{'correct_by_student'} = $checkIcon;
4307: if (!exists($$record{'1:timestamp'})) {
4308: return '<br /> <span class="LC_warning">'.&mt('Nothing submitted - no attempts').'</span><br />';
4309: }
4310:
4311: my $interaction;
4312: for ($version=1;$version<=$$record{'version'};$version++) {
4313: my $timestamp =
4314: &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
4315: if (exists($$record{$version.':resource.0.version'})) {
4316: $interaction = $$record{$version.':resource.0.version'};
4317: }
4318:
4319: my $where = ($isTask ? "$version:resource.$interaction"
4320: : "$version:resource");
4321: $studentTable.=&Apache::loncommon::start_data_table_row().
4322: '<td>'.$timestamp.'</td>';
4323: if ($isCODE) {
4324: $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
4325: }
4326: my @versionKeys = split(/\:/,$$record{$version.':keys'});
4327: my @displaySub = ();
4328: foreach my $partid (@{$parts}) {
4329: my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
4330: : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
4331:
4332:
4333: # next if ($$record{"$version:resource.$partid.solved"} eq '');
4334: my $display_part=&get_display_part($partid,$symb);
4335: foreach my $matchKey (@matchKey) {
4336: if (exists($$record{$version.':'.$matchKey}) &&
4337: $$record{$version.':'.$matchKey} ne '') {
4338:
4339: my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
4340: : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
4341: $displaySub[0].='<b>'.&mt('Part:').'</b> '.$display_part.' ';
4342: $displaySub[0].='<span class="LC_internal_info">('.&mt('ID').' '.
4343: $responseId.')</span> <b>';
4344: if ($$record{"$where.$partid.tries"} eq '') {
4345: $displaySub[0].=&mt('Trial not counted');
4346: } else {
4347: $displaySub[0].=&mt('Trial [_1]',
4348: $$record{"$where.$partid.tries"});
4349: }
4350: my $responseType=($isTask ? 'Task'
4351: : $responseType->{$partid}->{$responseId});
4352: if (!exists($orders{$partid})) { $orders{$partid}={}; }
4353: if (!exists($orders{$partid}->{$responseId})) {
4354: $orders{$partid}->{$responseId}=
4355: &get_order($partid,$responseId,$symb,$uname,$udom);
4356: }
4357: $displaySub[0].='</b> '.
4358: &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
4359: }
4360: }
4361: if (exists($$record{"$where.$partid.checkedin"})) {
4362: $displaySub[1].='Checked in by '.
4363: $$record{"$where.$partid.checkedin"}.' into slot '.
4364: $$record{"$where.$partid.checkedin.slot"}.
4365: '<br />';
4366: }
4367: if (exists $$record{"$where.$partid.award"}) {
4368: $displaySub[1].='<b>Part:</b> '.$display_part.' '.
4369: lc($$record{"$where.$partid.award"}).' '.
4370: $mark{$$record{"$where.$partid.solved"}}.
4371: '<br />';
4372: }
4373: if (exists $$record{"$where.$partid.regrader"}) {
4374: $displaySub[2].=$$record{"$where.$partid.regrader"}.
4375: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
4376: } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
4377: $displaySub[2].=
4378: $$record{"$version:resource.$partid.regrader"}.
4379: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
4380: }
4381: }
4382: # needed because old essay regrader has not parts info
4383: if (exists $$record{"$version:resource.regrader"}) {
4384: $displaySub[2].=$$record{"$version:resource.regrader"};
4385: }
4386: $studentTable.='<td>'.$displaySub[0].' </td><td>'.$displaySub[1];
4387: if ($displaySub[2]) {
4388: $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
4389: }
4390: $studentTable.=' </td>'.
4391: &Apache::loncommon::end_data_table_row();
4392: }
4393: $studentTable.=&Apache::loncommon::end_data_table();
4394: return $studentTable;
4395: }
4396:
4397: sub updateGradeByPage {
4398: my ($request) = shift;
4399:
4400: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4401: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4402: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4403: my $pageTitle = $env{'form.page'};
4404: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
4405: my ($uname,$udom) = split(/:/,$env{'form.student'});
4406: my $usec=$classlist->{$env{'form.student'}}[5];
4407: if (!&canmodify($usec)) {
4408: $request->print('<span class="LC_warning">Unable to modify requested student.('.$env{'form.student'}.'</span>');
4409: $request->print(&show_grading_menu_form($env{'form.symb'}));
4410: return;
4411: }
4412: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
4413: $result.='<h3> Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
4414: '</h3>'."\n";
4415:
4416: $request->print($result);
4417:
4418: my $navmap = Apache::lonnavmaps::navmap->new();
4419: my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
4420: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
4421: if (!$map) {
4422: $request->print('<span class="LC_warning">Unable to grade requested sequence. ('.$resUrl.')</span>');
4423: my ($symb)=&get_symb($request);
4424: $request->print(&show_grading_menu_form($symb));
4425: return;
4426: }
4427: my $iterator = $navmap->getIterator($map->map_start(),
4428: $map->map_finish());
4429:
4430: my $studentTable='<table border="0"><tr><td bgcolor="#777777">'.
4431: '<table border="0"><tr bgcolor="#e6ffff">'.
4432: '<td align="center"><b> Prob. </b></td>'.
4433: '<td><b> Title </b></td>'.
4434: '<td><b> Previous Score </b></td>'.
4435: '<td><b> New Score </b></td></tr>';
4436:
4437: $iterator->next(); # skip the first BEGIN_MAP
4438: my $curRes = $iterator->next(); # for "current resource"
4439: my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
4440: while ($depth > 0) {
4441: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
4442: if($curRes == $iterator->END_MAP) { $depth--; }
4443:
4444: if (ref($curRes) && $curRes->is_problem()) {
4445: my $parts = $curRes->parts();
4446: my $title = $curRes->compTitle();
4447: my $symbx = $curRes->symb();
4448: $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
4449: (scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).' parts)').'</td>';
4450: $studentTable.='<td valign="top"> <b>'.$title.'</b> </td>';
4451:
4452: my %newrecord=();
4453: my @displayPts=();
4454: my %aggregate = ();
4455: my $aggregateflag = 0;
4456: foreach my $partid (@{$parts}) {
4457: my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
4458: my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
4459:
4460: my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ?
4461: $env{'form.WGT'.$question.'_'.$partid} : 1;
4462: my $partial = $newpts/$wgt;
4463: my $score;
4464: if ($partial > 0) {
4465: $score = 'correct_by_override';
4466: } elsif ($newpts ne '') { #empty is taken as 0
4467: $score = 'incorrect_by_override';
4468: }
4469: my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
4470: if ($dropMenu eq 'excused') {
4471: $partial = '';
4472: $score = 'excused';
4473: } elsif ($dropMenu eq 'reset status'
4474: && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
4475: $newrecord{'resource.'.$partid.'.tries'} = 0;
4476: $newrecord{'resource.'.$partid.'.solved'} = '';
4477: $newrecord{'resource.'.$partid.'.award'} = '';
4478: $newrecord{'resource.'.$partid.'.awarded'} = 0;
4479: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
4480: $changeflag++;
4481: $newpts = '';
4482:
4483: my $aggtries = $env{'form.aggtries'.$question.'_'.$partid};
4484: my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
4485: my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
4486: if ($aggtries > 0) {
4487: &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
4488: $aggregateflag = 1;
4489: }
4490: }
4491: my $display_part=&get_display_part($partid,$curRes->symb());
4492: my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
4493: $displayPts[0].=' <b>Part:</b> '.$display_part.' = '.
4494: (($oldstatus eq 'excused') ? 'excused' : $oldpts).
4495: ' <br />';
4496: $displayPts[1].=' <b>Part:</b> '.$display_part.' = '.
4497: (($score eq 'excused') ? 'excused' : $newpts).
4498: ' <br />';
4499: $question++;
4500: next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
4501:
4502: $newrecord{'resource.'.$partid.'.awarded'} = $partial if $partial ne '';
4503: $newrecord{'resource.'.$partid.'.solved'} = $score if $score ne '';
4504: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
4505: if (scalar(keys(%newrecord)) > 0);
4506:
4507: $changeflag++;
4508: }
4509: if (scalar(keys(%newrecord)) > 0) {
4510: my %record =
4511: &Apache::lonnet::restore($symbx,$env{'request.course.id'},
4512: $udom,$uname);
4513:
4514: if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
4515: $newrecord{'resource.CODE'} = $env{'form.CODE'};
4516: } elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
4517: $newrecord{'resource.CODE'} = '';
4518: }
4519: &Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
4520: $udom,$uname);
4521: %record = &Apache::lonnet::restore($symbx,
4522: $env{'request.course.id'},
4523: $udom,$uname);
4524: &check_and_remove_from_queue($parts,\%record,undef,$symbx,
4525: $cdom,$cnum,$udom,$uname);
4526: }
4527:
4528: if ($aggregateflag) {
4529: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
4530: $env{'course.'.$env{'request.course.id'}.'.domain'},
4531: $env{'course.'.$env{'request.course.id'}.'.num'});
4532: }
4533:
4534: $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
4535: '<td valign="top">'.$displayPts[1].'</td>'.
4536: '</tr>';
4537:
4538: $prob++;
4539: }
4540: $curRes = $iterator->next();
4541: }
4542:
4543: $studentTable.='</td></tr></table></td></tr></table>';
4544: $studentTable.=&show_grading_menu_form($env{'form.symb'});
4545: my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
4546: 'The scores were changed for '.
4547: $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
4548: $request->print($grademsg.$studentTable);
4549:
4550: return '';
4551: }
4552:
4553: #-------- end of section for handling grading by page/sequence ---------
4554: #
4555: #-------------------------------------------------------------------
4556:
4557: #--------------------Scantron Grading-----------------------------------
4558: #
4559: #------ start of section for handling grading by page/sequence ---------
4560:
4561: =pod
4562:
4563: =head1 Bubble sheet grading routines
4564:
4565: For this documentation:
4566:
4567: 'scanline' refers to the full line of characters
4568: from the file that we are parsing that represents one entire sheet
4569:
4570: 'bubble line' refers to the data
4571: representing the line of bubbles that are on the physical bubble sheet
4572:
4573:
4574: The overall process is that a scanned in bubble sheet data is uploaded
4575: into a course. When a user wants to grade, they select a
4576: sequence/folder of resources, a file of bubble sheet info, and pick
4577: one of the predefined configurations for what each scanline looks
4578: like.
4579:
4580: Next each scanline is checked for any errors of either 'missing
4581: bubbles' (it's an error because it may have been mis-scanned
4582: because too light bubbling), 'double bubble' (each bubble line should
4583: have no more that one letter picked), invalid or duplicated CODE,
4584: invalid student ID
4585:
4586: If the CODE option is used that determines the randomization of the
4587: homework problems, either way the student ID is looked up into a
4588: username:domain.
4589:
4590: During the validation phase the instructor can choose to skip scanlines.
4591:
4592: After the validation phase, there are now 3 bubble sheet files
4593:
4594: scantron_original_filename (unmodified original file)
4595: scantron_corrected_filename (file where the corrected information has replaced the original information)
4596: scantron_skipped_filename (contains the exact text of scanlines that where skipped)
4597:
4598: Also there is a separate hash nohist_scantrondata that contains extra
4599: correction information that isn't representable in the bubble sheet
4600: file (see &scantron_getfile() for more information)
4601:
4602: After all scanlines are either valid, marked as valid or skipped, then
4603: foreach line foreach problem in the picked sequence, an ssi request is
4604: made that simulates a user submitting their selected letter(s) against
4605: the homework problem.
4606:
4607: =over 4
4608:
4609:
4610:
4611: =item defaultFormData
4612:
4613: Returns html hidden inputs used to hold context/default values.
4614:
4615: Arguments:
4616: $symb - $symb of the current resource
4617:
4618: =cut
4619:
4620: sub defaultFormData {
4621: my ($symb)=@_;
4622: return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
4623: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
4624: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
4625: }
4626:
4627:
4628: =pod
4629:
4630: =item getSequenceDropDown
4631:
4632: Return html dropdown of possible sequences to grade
4633:
4634: Arguments:
4635: $symb - $symb of the current resource
4636:
4637: =cut
4638:
4639: sub getSequenceDropDown {
4640: my ($symb)=@_;
4641: my $result='<select name="selectpage">'."\n";
4642: my ($titles,$symbx) = &getSymbMap();
4643: my ($curpage)=&Apache::lonnet::decode_symb($symb);
4644: my $ctr=0;
4645: foreach (@$titles) {
4646: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4647: $result.='<option value="'.$$symbx{$_}.'" '.
4648: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
4649: '>'.$showtitle.'</option>'."\n";
4650: $ctr++;
4651: }
4652: $result.= '</select>';
4653: return $result;
4654: }
4655:
4656:
4657: =pod
4658:
4659: =item scantron_filenames
4660:
4661: Returns a list of the scantron files in the current course
4662:
4663: =cut
4664:
4665: sub scantron_filenames {
4666: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4667: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
4668: my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
4669: &propath($cdom,$cname));
4670: my @possiblenames;
4671: foreach my $filename (sort(@files)) {
4672: ($filename)=split(/&/,$filename);
4673: if ($filename!~/^scantron_orig_/) { next ; }
4674: $filename=~s/^scantron_orig_//;
4675: push(@possiblenames,$filename);
4676: }
4677: return @possiblenames;
4678: }
4679:
4680: =pod
4681:
4682: =item scantron_uploads
4683:
4684: Returns html drop-down list of scantron files in current course.
4685:
4686: Arguments:
4687: $file2grade - filename to set as selected in the dropdown
4688:
4689: =cut
4690:
4691: sub scantron_uploads {
4692: my ($file2grade) = @_;
4693: my $result= '<select name="scantron_selectfile">';
4694: $result.="<option></option>";
4695: foreach my $filename (sort(&scantron_filenames())) {
4696: $result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
4697: }
4698: $result.="</select>";
4699: return $result;
4700: }
4701:
4702: =pod
4703:
4704: =item scantron_scantab
4705:
4706: Returns html drop down of the scantron formats in the scantronformat.tab
4707: file.
4708:
4709: =cut
4710:
4711: sub scantron_scantab {
4712: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
4713: my $result='<select name="scantron_format">'."\n";
4714: $result.='<option></option>'."\n";
4715: foreach my $line (<$fh>) {
4716: my ($name,$descrip)=split(/:/,$line);
4717: if ($name =~ /^\#/) { next; }
4718: $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
4719: }
4720: $result.='</select>'."\n";
4721:
4722: return $result;
4723: }
4724:
4725: =pod
4726:
4727: =item scantron_CODElist
4728:
4729: Returns html drop down of the saved CODE lists from current course,
4730: generated from earlier printings.
4731:
4732: =cut
4733:
4734: sub scantron_CODElist {
4735: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4736: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4737: my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
4738: my $namechoice='<option></option>';
4739: foreach my $name (sort {uc($a) cmp uc($b)} @names) {
4740: if ($name =~ /^error: 2 /) { next; }
4741: if ($name =~ /^type\0/) { next; }
4742: $namechoice.='<option value="'.$name.'">'.$name.'</option>';
4743: }
4744: $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
4745: return $namechoice;
4746: }
4747:
4748: =pod
4749:
4750: =item scantron_CODEunique
4751:
4752: Returns the html for "Each CODE to be used once" radio.
4753:
4754: =cut
4755:
4756: sub scantron_CODEunique {
4757: my $result='<span style="white-space: nowrap;">
4758: <label><input type="radio" name="scantron_CODEunique"
4759: value="yes" checked="checked" />'.&mt('Yes').' </label>
4760: </span>
4761: <span style="white-space: nowrap;">
4762: <label><input type="radio" name="scantron_CODEunique"
4763: value="no" />'.&mt('No').' </label>
4764: </span>';
4765: return $result;
4766: }
4767:
4768: =pod
4769:
4770: =item scantron_selectphase
4771:
4772: Generates the initial screen to start the bubble sheet process.
4773: Allows for - starting a grading run.
4774: - downloading existing scan data (original, corrected
4775: or skipped info)
4776:
4777: - uploading new scan data
4778:
4779: Arguments:
4780: $r - The Apache request object
4781: $file2grade - name of the file that contain the scanned data to score
4782:
4783: =cut
4784:
4785: sub scantron_selectphase {
4786: my ($r,$file2grade) = @_;
4787: my ($symb)=&get_symb($r);
4788: if (!$symb) {return '';}
4789: my $sequence_selector=&getSequenceDropDown($symb);
4790: my $default_form_data=&defaultFormData($symb);
4791: my $grading_menu_button=&show_grading_menu_form($symb);
4792: my $file_selector=&scantron_uploads($file2grade);
4793: my $format_selector=&scantron_scantab();
4794: my $CODE_selector=&scantron_CODElist();
4795: my $CODE_unique=&scantron_CODEunique();
4796: my $result;
4797:
4798: # Chunk of form to prompt for a file to grade and how:
4799:
4800: $result.= <<SCANTRONFORM;
4801: <table width="100%" border="0">
4802: <tr>
4803: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
4804: <td bgcolor="#777777">
4805: <input type="hidden" name="command" value="scantron_warning" />
4806: $default_form_data
4807: <table width="100%" border="0">
4808: <tr bgcolor="#e6ffff">
4809: <td colspan="2">
4810: <b>Specify file and which Folder/Sequence to grade</b>
4811: </td>
4812: </tr>
4813: <tr bgcolor="#ffffe6">
4814: <td> Sequence to grade: </td><td> $sequence_selector </td>
4815: </tr>
4816: <tr bgcolor="#ffffe6">
4817: <td> Filename of scoring office file: </td><td> $file_selector </td>
4818: </tr>
4819: <tr bgcolor="#ffffe6">
4820: <td> Format of data file: </td><td> $format_selector </td>
4821: </tr>
4822: <tr bgcolor="#ffffe6">
4823: <td> Saved CODEs to validate against: </td><td> $CODE_selector</td>
4824: </tr>
4825: <tr bgcolor="#ffffe6">
4826: <td> Each CODE is only to be used once:</td><td> $CODE_unique </td>
4827: </tr>
4828: <tr bgcolor="#ffffe6">
4829: <td> Options: </td>
4830: <td>
4831: <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> Do only previously skipped records</label> <br />
4832: <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> Remove all existing corrections</label> <br />
4833: <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> Skip hidden resources when grading</label>
4834: </td>
4835: </tr>
4836: <tr bgcolor="#ffffe6">
4837: <td colspan="2">
4838: <input type="submit" value="Grading: Validate Scantron Records" />
4839: </td>
4840: </tr>
4841: </table>
4842: </td>
4843: </form>
4844: </tr>
4845: SCANTRONFORM
4846:
4847: $r->print($result);
4848:
4849: if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
4850: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
4851:
4852: # Chunk of form to prompt for a scantron file upload.
4853:
4854: $r->print(<<SCANTRONFORM);
4855: <tr>
4856: <td bgcolor="#777777">
4857: <table width="100%" border="0">
4858: <tr bgcolor="#e6ffff">
4859: <td>
4860: <b>Specify a Scantron data file to upload.</b>
4861: </td>
4862: </tr>
4863: <tr bgcolor="#ffffe6">
4864: <td>
4865: SCANTRONFORM
4866: my $default_form_data=&defaultFormData(&get_symb($r,1));
4867: my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
4868: my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
4869: $r->print(<<UPLOAD);
4870: <script type="text/javascript" language="javascript">
4871: function checkUpload(formname) {
4872: if (formname.upfile.value == "") {
4873: alert("Please use the browse button to select a file from your local directory.");
4874: return false;
4875: }
4876: formname.submit();
4877: }
4878: </script>
4879:
4880: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
4881: $default_form_data
4882: <input name='courseid' type='hidden' value='$cnum' />
4883: <input name='domainid' type='hidden' value='$cdom' />
4884: <input name='command' value='scantronupload_save' type='hidden' />
4885: File to upload:<input type="file" name="upfile" size="50" />
4886: <br />
4887: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
4888: </form>
4889: UPLOAD
4890:
4891: $r->print(<<SCANTRONFORM);
4892: </td>
4893: </tr>
4894: </table>
4895: </td>
4896: </tr>
4897: SCANTRONFORM
4898: }
4899:
4900: # Chunk of the form that prompts to view a scoring office file,
4901: # corrected file, skipped records in a file.
4902:
4903: $r->print(<<SCANTRONFORM);
4904: <tr>
4905: <form action='/adm/grades' name='scantron_download'>
4906: <td bgcolor="#777777">
4907: $default_form_data
4908: <input type="hidden" name="command" value="scantron_download" />
4909: <table width="100%" border="0">
4910: <tr bgcolor="#e6ffff">
4911: <td colspan="2">
4912: <b>Download a scoring office file</b>
4913: </td>
4914: </tr>
4915: <tr bgcolor="#ffffe6">
4916: <td> Filename of scoring office file: </td><td> $file_selector </td>
4917: </tr>
4918: <tr bgcolor="#ffffe6">
4919: <td colspan="2">
4920: <input type="submit" value="Download: Show List of Associated Files" />
4921: </td>
4922: </tr>
4923: </table>
4924: </td>
4925: </form>
4926: </tr>
4927: SCANTRONFORM
4928:
4929: $r->print('<tr><td bgcolor="#777777">');
4930: &Apache::lonpickcode::code_list($r,2);
4931: $r->print('</td></tr></table>');
4932: $r->print($grading_menu_button);
4933: return
4934: }
4935:
4936: =pod
4937:
4938: =item get_scantron_config
4939:
4940: Parse and return the scantron configuration line selected as a
4941: hash of configuration file fields.
4942:
4943: Arguments:
4944: which - the name of the configuration to parse from the file.
4945:
4946:
4947: Returns:
4948: If the named configuration is not in the file, an empty
4949: hash is returned.
4950: a hash with the fields
4951: name - internal name for the this configuration setup
4952: description - text to display to operator that describes this config
4953: CODElocation - if 0 or the string 'none'
4954: - no CODE exists for this config
4955: if -1 || the string 'letter'
4956: - a CODE exists for this config and is
4957: a string of letters
4958: Unsupported value (but planned for future support)
4959: if a positive integer
4960: - The CODE exists as the first n items from
4961: the question section of the form
4962: if the string 'number'
4963: - The CODE exists for this config and is
4964: a string of numbers
4965: CODEstart - (only matter if a CODE exists) column in the line where
4966: the CODE starts
4967: CODElength - length of the CODE
4968: IDstart - column where the student ID number starts
4969: IDlength - length of the student ID info
4970: Qstart - column where the information from the bubbled
4971: 'questions' start
4972: Qlength - number of columns comprising a single bubble line from
4973: the sheet. (usually either 1 or 10)
4974: Qon - either a single character representing the character used
4975: to signal a bubble was chosen in the positional setup, or
4976: the string 'letter' if the letter of the chosen bubble is
4977: in the final, or 'number' if a number representing the
4978: chosen bubble is in the file (1->A 0->J)
4979: Qoff - the character used to represent that a bubble was
4980: left blank
4981: PaperID - if the scanning process generates a unique number for each
4982: sheet scanned the column that this ID number starts in
4983: PaperIDlength - number of columns that comprise the unique ID number
4984: for the sheet of paper
4985: FirstName - column that the first name starts in
4986: FirstNameLength - number of columns that the first name spans
4987:
4988: LastName - column that the last name starts in
4989: LastNameLength - number of columns that the last name spans
4990:
4991: =cut
4992:
4993: sub get_scantron_config {
4994: my ($which) = @_;
4995: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
4996: my %config;
4997: #FIXME probably should move to XML it has already gotten a bit much now
4998: foreach my $line (<$fh>) {
4999: my ($name,$descrip)=split(/:/,$line);
5000: if ($name ne $which ) { next; }
5001: chomp($line);
5002: my @config=split(/:/,$line);
5003: $config{'name'}=$config[0];
5004: $config{'description'}=$config[1];
5005: $config{'CODElocation'}=$config[2];
5006: $config{'CODEstart'}=$config[3];
5007: $config{'CODElength'}=$config[4];
5008: $config{'IDstart'}=$config[5];
5009: $config{'IDlength'}=$config[6];
5010: $config{'Qstart'}=$config[7];
5011: $config{'Qlength'}=$config[8];
5012: $config{'Qoff'}=$config[9];
5013: $config{'Qon'}=$config[10];
5014: $config{'PaperID'}=$config[11];
5015: $config{'PaperIDlength'}=$config[12];
5016: $config{'FirstName'}=$config[13];
5017: $config{'FirstNamelength'}=$config[14];
5018: $config{'LastName'}=$config[15];
5019: $config{'LastNamelength'}=$config[16];
5020: last;
5021: }
5022: return %config;
5023: }
5024:
5025: =pod
5026:
5027: =item username_to_idmap
5028:
5029: creates a hash keyed by student id with values of the corresponding
5030: student username:domain.
5031:
5032: Arguments:
5033:
5034: $classlist - reference to the class list hash. This is a hash
5035: keyed by student name:domain whose elements are references
5036: to arrays containing various chunks of information
5037: about the student. (See loncoursedata for more info).
5038:
5039: Returns
5040: %idmap - the constructed hash
5041:
5042: =cut
5043:
5044: sub username_to_idmap {
5045: my ($classlist)= @_;
5046: my %idmap;
5047: foreach my $student (keys(%$classlist)) {
5048: $idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
5049: $student;
5050: }
5051: return %idmap;
5052: }
5053:
5054: =pod
5055:
5056: =item scantron_fixup_scanline
5057:
5058: Process a requested correction to a scanline.
5059:
5060: Arguments:
5061: $scantron_config - hash from &get_scantron_config()
5062: $scan_data - hash of correction information
5063: (see &scantron_getfile())
5064: $line - existing scanline
5065: $whichline - line number of the passed in scanline
5066: $field - type of change to process
5067: (either
5068: 'ID' -> correct the student ID number
5069: 'CODE' -> correct the CODE
5070: 'answer' -> fixup the submitted answers)
5071:
5072: $args - hash of additional info,
5073: - 'ID'
5074: 'newid' -> studentID to use in replacement
5075: of existing one
5076: - 'CODE'
5077: 'CODE_ignore_dup' - set to true if duplicates
5078: should be ignored.
5079: 'CODE' - is new code or 'use_unfound'
5080: if the existing unfound code should
5081: be used as is
5082: - 'answer'
5083: 'response' - new answer or 'none' if blank
5084: 'question' - the bubble line to change
5085:
5086: Returns:
5087: $line - the modified scanline
5088:
5089: Side effects:
5090: $scan_data - may be updated
5091:
5092: =cut
5093:
5094:
5095: sub scantron_fixup_scanline {
5096: my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
5097:
5098: if ($field eq 'ID') {
5099: if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
5100: return ($line,1,'New value too large');
5101: }
5102: if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
5103: $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
5104: $args->{'newid'});
5105: }
5106: substr($line,$$scantron_config{'IDstart'}-1,
5107: $$scantron_config{'IDlength'})=$args->{'newid'};
5108: if ($args->{'newid'}=~/^\s*$/) {
5109: &scan_data($scan_data,"$whichline.user",
5110: $args->{'username'}.':'.$args->{'domain'});
5111: }
5112: } elsif ($field eq 'CODE') {
5113: if ($args->{'CODE_ignore_dup'}) {
5114: &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
5115: }
5116: &scan_data($scan_data,"$whichline.useCODE",'1');
5117: if ($args->{'CODE'} ne 'use_unfound') {
5118: if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
5119: return ($line,1,'New CODE value too large');
5120: }
5121: if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
5122: $args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
5123: }
5124: substr($line,$$scantron_config{'CODEstart'}-1,
5125: $$scantron_config{'CODElength'})=$args->{'CODE'};
5126: }
5127: } elsif ($field eq 'answer') {
5128: my $length=$scantron_config->{'Qlength'};
5129: my $off=$scantron_config->{'Qoff'};
5130: my $on=$scantron_config->{'Qon'};
5131: my $answer=${off}x$length;
5132: if ($args->{'response'} eq 'none') {
5133: &scan_data($scan_data,
5134: "$whichline.no_bubble.".$args->{'question'},'1');
5135: } else {
5136: if ($on eq 'letter') {
5137: my @alphabet=('A'..'Z');
5138: $answer=$alphabet[$args->{'response'}];
5139: } elsif ($on eq 'number') {
5140: $answer=$args->{'response'}+1;
5141: if ($answer == 10) { $answer = '0'; }
5142: } else {
5143: substr($answer,$args->{'response'},1)=$on;
5144: }
5145: &scan_data($scan_data,
5146: "$whichline.no_bubble.".$args->{'question'},undef,'1');
5147: }
5148: my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
5149: substr($line,$where-1,$length)=$answer;
5150: }
5151: return $line;
5152: }
5153:
5154: =pod
5155:
5156: =item scan_data
5157:
5158: Edit or look up an item in the scan_data hash.
5159:
5160: Arguments:
5161: $scan_data - The hash (see scantron_getfile)
5162: $key - shorthand of the key to edit (actual key is
5163: scantronfilename_key).
5164: $data - New value of the hash entry.
5165: $delete - If true, the entry is removed from the hash.
5166:
5167: Returns:
5168: The new value of the hash table field (undefined if deleted).
5169:
5170: =cut
5171:
5172:
5173: sub scan_data {
5174: my ($scan_data,$key,$value,$delete)=@_;
5175: my $filename=$env{'form.scantron_selectfile'};
5176: if (defined($value)) {
5177: $scan_data->{$filename.'_'.$key} = $value;
5178: }
5179: if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
5180: return $scan_data->{$filename.'_'.$key};
5181: }
5182:
5183: =pod
5184:
5185: =item scantron_parse_scanline
5186:
5187: Decodes a scanline from the selected scantron file
5188:
5189: Arguments:
5190: line - The text of the scantron file line to process
5191: whichline - Line number
5192: scantron_config - Hash describing the format of the scantron lines.
5193: scan_data - Hash of extra information about the scanline
5194: (see scantron_getfile for more information)
5195: just_header - True if should not process question answers but only
5196: the stuff to the left of the answers.
5197: Returns:
5198: Hash containing the result of parsing the scanline
5199:
5200: Keys are all proceeded by the string 'scantron.'
5201:
5202: CODE - the CODE in use for this scanline
5203: useCODE - 1 if the CODE is invalid but it usage has been forced
5204: by the operator
5205: CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
5206: CODEs were selected, but the usage has been
5207: forced by the operator
5208: ID - student ID
5209: PaperID - if used, the ID number printed on the sheet when the
5210: paper was scanned
5211: FirstName - first name from the sheet
5212: LastName - last name from the sheet
5213:
5214: if just_header was not true these key may also exist
5215:
5216: missingerror - a list of bubble ranges that are considered to be answers
5217: to a single question that don't have any bubbles filled in.
5218: Of the form questionnumber:firstbubblenumber:count.
5219: doubleerror - a list of bubble ranges that are considered to be answers
5220: to a single question that have more than one bubble filled in.
5221: Of the form questionnumber::firstbubblenumber:count
5222:
5223: In the above, count is the number of bubble responses in the
5224: input line needed to represent the possible answers to the question.
5225: e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
5226: per line would have count = 2.
5227:
5228: maxquest - the number of the last bubble line that was parsed
5229:
5230: (<number> starts at 1)
5231: <number>.answer - zero or more letters representing the selected
5232: letters from the scanline for the bubble line
5233: <number>.
5234: if blank there was either no bubble or there where
5235: multiple bubbles, (consult the keys missingerror and
5236: doubleerror if this is an error condition)
5237:
5238: =cut
5239:
5240: sub scantron_parse_scanline {
5241: my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
5242:
5243: my %record;
5244: my $questions=substr($line,$$scantron_config{'Qstart'}-1); # Answers
5245: my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # earlier stuff
5246: if (!($$scantron_config{'CODElocation'} eq 0 ||
5247: $$scantron_config{'CODElocation'} eq 'none')) {
5248: if ($$scantron_config{'CODElocation'} < 0 ||
5249: $$scantron_config{'CODElocation'} eq 'letter' ||
5250: $$scantron_config{'CODElocation'} eq 'number') {
5251: $record{'scantron.CODE'}=substr($data,
5252: $$scantron_config{'CODEstart'}-1,
5253: $$scantron_config{'CODElength'});
5254: if (&scan_data($scan_data,"$whichline.useCODE")) {
5255: $record{'scantron.useCODE'}=1;
5256: }
5257: if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
5258: $record{'scantron.CODE_ignore_dup'}=1;
5259: }
5260: } else {
5261: #FIXME interpret first N questions
5262: }
5263: }
5264: $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
5265: $$scantron_config{'IDlength'});
5266: $record{'scantron.PaperID'}=
5267: substr($data,$$scantron_config{'PaperID'}-1,
5268: $$scantron_config{'PaperIDlength'});
5269: $record{'scantron.FirstName'}=
5270: substr($data,$$scantron_config{'FirstName'}-1,
5271: $$scantron_config{'FirstNamelength'});
5272: $record{'scantron.LastName'}=
5273: substr($data,$$scantron_config{'LastName'}-1,
5274: $$scantron_config{'LastNamelength'});
5275: if ($just_header) { return \%record; }
5276:
5277: my @alphabet=('A'..'Z');
5278: my $questnum=0;
5279: my $ansnum =1; # Multiple 'answer lines'/question.
5280:
5281: chomp($questions); # Get rid of any trailing \n.
5282: $questions =~ s/\r$//; # Get rid of trailing \r too (MAC or Win uploads).
5283: while (length($questions)) {
5284: my $answers_needed = $bubble_lines_per_response{$questnum};
5285: my $answer_length = $$scantron_config{'Qlength'} * $answers_needed;
5286:
5287:
5288:
5289: $questnum++;
5290: my $currentquest = substr($questions,0,$answer_length);
5291: $questions = substr($questions,0,$answer_length)='';
5292: if (length($currentquest) < $answer_length) { next; }
5293:
5294: # Qon letter implies for each slot in currentquest we have:
5295: # ? or * for doubles a letter in A-Z for a bubble and
5296: # about anything else (esp. a value of Qoff for missing
5297: # bubbles.
5298:
5299:
5300: if ($$scantron_config{'Qon'} eq 'letter') {
5301:
5302: if ($currentquest =~ /\?/
5303: || $currentquest =~ /\*/
5304: || (&occurence_count($currentquest, "[A-Z]") > 1)) {
5305: push(@{$record{'scantron.doubleerror'}},$questnum);
5306: for (my $ans = 0; $ans < $answers_needed; $ans++) {
5307: my $bubble = substr($currentquest, $ans, 1);
5308: if ($bubble =~ /[A-Z]/ ) {
5309: $record{"scantron.$ansnum.answer"} = $bubble;
5310: } else {
5311: $record{"scantron.$ansnum.answer"}='';
5312: }
5313: $ansnum++;
5314: }
5315:
5316: } elsif (!defined($currentquest)
5317: || (&occurence_count($currentquest, $$scantron_config{'Qoff'}) == length($currentquest))
5318: || (&occurence_count($currentquest, "[A-Z]") == 0)) {
5319: &Apache::lonnet::logthis("Missing if, $questnum, $ansnum");
5320: for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
5321: $record{"scantron.$ansnum.answer"}='';
5322: $ansnum++;
5323:
5324: }
5325: if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
5326: &Apache::lonnet::logthis("Parsed missing: $questnum");
5327: push(@{$record{"scantron.missingerror"}},$questnum);
5328: # $ansnum += $answers_needed;
5329: }
5330: &Apache::lonnet::logthis("Residual scanline: '$questions'");
5331:
5332: } else {
5333: for (my $ans = 0; $ans < $answers_needed; $ans++) {
5334: $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
5335: $ansnum++;
5336: }
5337: }
5338:
5339: # Qon 'number' implies each slot gives a digit that indexes the
5340: # the bubbles filled or Qoff or a non number for unbubbled lines.
5341: # and *? for double bubbles on a line.
5342: # these answers are also stored as letters.
5343:
5344: } elsif ($$scantron_config{'Qon'} eq 'number') {
5345: if ($currentquest =~ /\?/
5346: || $currentquest =~ /\*/
5347: || (&occurence_count($currentquest, '\d') > 1)) {
5348: push(@{$record{'scantron.doubleerror'}},$questnum);
5349: for (my $ans = 0; $ans < $answers_needed; $ans++) {
5350: my $bubble = substr($currentquest, $ans, 1);
5351: if ($bubble =~ /\d/) {
5352: $record{"scantron.$ansnum.answer"} = $alphabet[$bubble];
5353: } else {
5354: $record{"scantron.$ansnum.answer"}=' ';
5355: }
5356: $ansnum++;
5357: }
5358:
5359: } elsif (!defined($currentquest)
5360: || (&occurence_count($currentquest,$$scantron_config{'Qoff'}) == length($currentquest))
5361: || (&occurence_count($currentquest, '\d') == 0)) {
5362: for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
5363: $record{"scantron.$ansnum.answer"}='';
5364: $ansnum++;
5365:
5366: }
5367: if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
5368: push(@{$record{"scantron.missingerror"}},$questnum);
5369: $ansnum += $answers_needed;
5370: }
5371:
5372: } else {
5373: $currentquest = &digits_to_letters($currentquest);
5374: for (my $ans =0; $ans < $answers_needed; $ans++) {
5375: $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
5376: $ansnum++;
5377: }
5378: }
5379: } else {
5380:
5381: # Otherwise there's a positional notation;
5382: # each bubble line requires Qlength items, and there are filled in
5383: # bubbles for each case where there 'Qon' characters.
5384: #
5385:
5386: my @array=split($$scantron_config{'Qon'},$currentquest,-1);
5387:
5388: # If the split only giveas us one element.. the full length of the
5389: # answser string, no bubbles are filled in:
5390:
5391: if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
5392: for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
5393: $record{"scantron.$ansnum.answer"}='';
5394: $ansnum++;
5395:
5396: }
5397: if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
5398: push(@{$record{"scantron.missingerror"}},$questnum);
5399: }
5400: } elsif (scalar(@array) lt 2) {
5401:
5402: my $location = length($array[0]);
5403: my $line_num = $location / $$scantron_config{'Qlength'};
5404: my $bubble = $alphabet[$location % $$scantron_config{'Qlength'}];
5405:
5406: for (my $ans = 0; $ans < $answers_needed; $ans++) {
5407: if ($ans eq $line_num) {
5408: $record{"scantron.$ansnum.answer"} = $bubble;
5409: } else {
5410: $record{"scantron.$ansnum.answer"} = ' ';
5411: }
5412: $ansnum++;
5413: }
5414: }
5415: # If there's more than one instance of a bubble character
5416: # That's a double bubble; with positional notation we can
5417: # record all the bubbles filled in as well as the
5418: # fact this response consists of multiple bubbles.
5419: #
5420: else {
5421: push(@{$record{'scantron.doubleerror'}},$questnum);
5422:
5423: my $first_answer = $ansnum;
5424: for (my $ans =0; $ans < $answers_needed; $ans++) {
5425: my $item = $first_answer+$ans;
5426: $record{"scantron.$item.answer"} = '';
5427: }
5428:
5429: my @ans=@array;
5430: my $i=0;
5431: my $increment = 0;
5432: while ($#ans) {
5433: $i+=length($ans[0]) + $increment;
5434: my $line = int($i/$$scantron_config{'Qlength'} + $first_answer);
5435: my $bubble = $i%$$scantron_config{'Qlength'};
5436: $record{"scantron.$line.answer"}.=$alphabet[$bubble];
5437: shift(@ans);
5438: $increment = 1;
5439: }
5440: $ansnum += $answers_needed;
5441: }
5442: }
5443: }
5444: $record{'scantron.maxquest'}=$questnum;
5445: return \%record;
5446: }
5447:
5448: =pod
5449:
5450: =item scantron_add_delay
5451:
5452: Adds an error message that occurred during the grading phase to a
5453: queue of messages to be shown after grading pass is complete
5454:
5455: Arguments:
5456: $delayqueue - arrary ref of hash ref of error messages
5457: $scanline - the scanline that caused the error
5458: $errormesage - the error message
5459: $errorcode - a numeric code for the error
5460:
5461: Side Effects:
5462: updates the $delayqueue to have a new hash ref of the error
5463:
5464: =cut
5465:
5466: sub scantron_add_delay {
5467: my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
5468: push(@$delayqueue,
5469: {'line' => $scanline, 'emsg' => $errormessage,
5470: 'ecode' => $errorcode }
5471: );
5472: }
5473:
5474: =pod
5475:
5476: =item scantron_find_student
5477:
5478: Finds the username for the current scanline
5479:
5480: Arguments:
5481: $scantron_record - hash result from scantron_parse_scanline
5482: $scan_data - hash of correction information
5483: (see &scantron_getfile() form more information)
5484: $idmap - hash from &username_to_idmap()
5485: $line - number of current scanline
5486:
5487: Returns:
5488: Either 'username:domain' or undef if unknown
5489:
5490: =cut
5491:
5492: sub scantron_find_student {
5493: my ($scantron_record,$scan_data,$idmap,$line)=@_;
5494: my $scanID=$$scantron_record{'scantron.ID'};
5495: if ($scanID =~ /^\s*$/) {
5496: return &scan_data($scan_data,"$line.user");
5497: }
5498: foreach my $id (keys(%$idmap)) {
5499: if (lc($id) eq lc($scanID)) {
5500: return $$idmap{$id};
5501: }
5502: }
5503: return undef;
5504: }
5505:
5506: =pod
5507:
5508: =item scantron_filter
5509:
5510: Filter sub for lonnavmaps, filters out hidden resources if ignore
5511: hidden resources was selected
5512:
5513: =cut
5514:
5515: sub scantron_filter {
5516: my ($curres)=@_;
5517:
5518: if (ref($curres) && $curres->is_problem()) {
5519: # if the user has asked to not have either hidden
5520: # or 'randomout' controlled resources to be graded
5521: # don't include them
5522: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
5523: && $curres->randomout) {
5524: return 0;
5525: }
5526: return 1;
5527: }
5528: return 0;
5529: }
5530:
5531: =pod
5532:
5533: =item scantron_process_corrections
5534:
5535: Gets correction information out of submitted form data and corrects
5536: the scanline
5537:
5538: =cut
5539:
5540: sub scantron_process_corrections {
5541: my ($r) = @_;
5542: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
5543: my ($scanlines,$scan_data)=&scantron_getfile();
5544: my $classlist=&Apache::loncoursedata::get_classlist();
5545: my $which=$env{'form.scantron_line'};
5546: my $line=&scantron_get_line($scanlines,$scan_data,$which);
5547: my ($skip,$err,$errmsg);
5548: if ($env{'form.scantron_skip_record'}) {
5549: $skip=1;
5550: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
5551: my $newstudent=$env{'form.scantron_username'}.':'.
5552: $env{'form.scantron_domain'};
5553: my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
5554: ($line,$err,$errmsg)=
5555: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
5556: 'ID',{'newid'=>$newid,
5557: 'username'=>$env{'form.scantron_username'},
5558: 'domain'=>$env{'form.scantron_domain'}});
5559: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
5560: my $resolution=$env{'form.scantron_CODE_resolution'};
5561: my $newCODE;
5562: my %args;
5563: if ($resolution eq 'use_unfound') {
5564: $newCODE='use_unfound';
5565: } elsif ($resolution eq 'use_found') {
5566: $newCODE=$env{'form.scantron_CODE_selectedvalue'};
5567: } elsif ($resolution eq 'use_typed') {
5568: $newCODE=$env{'form.scantron_CODE_newvalue'};
5569: } elsif ($resolution =~ /^use_closest_(\d+)/) {
5570: $newCODE=$env{"form.scantron_CODE_closest_$1"};
5571: }
5572: if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
5573: $args{'CODE_ignore_dup'}=1;
5574: }
5575: $args{'CODE'}=$newCODE;
5576: ($line,$err,$errmsg)=
5577: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
5578: 'CODE',\%args);
5579: } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
5580: foreach my $question (split(',',$env{'form.scantron_questions'})) {
5581: ($line,$err,$errmsg)=
5582: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
5583: $which,'answer',
5584: { 'question'=>$question,
5585: 'response'=>$env{"form.scantron_correct_Q_$question"}});
5586: if ($err) { last; }
5587: }
5588: }
5589: if ($err) {
5590: $r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
5591: } else {
5592: &scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
5593: &scantron_putfile($scanlines,$scan_data);
5594: }
5595: }
5596:
5597: =pod
5598:
5599: =item reset_skipping_status
5600:
5601: Forgets the current set of remember skipped scanlines (and thus
5602: reverts back to considering all lines in the
5603: scantron_skipped_<filename> file)
5604:
5605: =cut
5606:
5607: sub reset_skipping_status {
5608: my ($scanlines,$scan_data)=&scantron_getfile();
5609: &scan_data($scan_data,'remember_skipping',undef,1);
5610: &scantron_putfile(undef,$scan_data);
5611: }
5612:
5613: =pod
5614:
5615: =item start_skipping
5616:
5617: Marks a scanline to be skipped.
5618:
5619: =cut
5620:
5621: sub start_skipping {
5622: my ($scan_data,$i)=@_;
5623: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
5624: if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
5625: $remembered{$i}=2;
5626: } else {
5627: $remembered{$i}=1;
5628: }
5629: &scan_data($scan_data,'remember_skipping',join(':',%remembered));
5630: }
5631:
5632: =pod
5633:
5634: =item should_be_skipped
5635:
5636: Checks whether a scanline should be skipped.
5637:
5638: =cut
5639:
5640: sub should_be_skipped {
5641: my ($scanlines,$scan_data,$i)=@_;
5642: if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
5643: # not redoing old skips
5644: if ($scanlines->{'skipped'}[$i]) { return 1; }
5645: return 0;
5646: }
5647: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
5648:
5649: if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
5650: return 0;
5651: }
5652: return 1;
5653: }
5654:
5655: =pod
5656:
5657: =item remember_current_skipped
5658:
5659: Discovers what scanlines are in the scantron_skipped_<filename>
5660: file and remembers them into scan_data for later use.
5661:
5662: =cut
5663:
5664: sub remember_current_skipped {
5665: my ($scanlines,$scan_data)=&scantron_getfile();
5666: my %to_remember;
5667: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
5668: if ($scanlines->{'skipped'}[$i]) {
5669: $to_remember{$i}=1;
5670: }
5671: }
5672:
5673: &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
5674: &scantron_putfile(undef,$scan_data);
5675: }
5676:
5677: =pod
5678:
5679: =item check_for_error
5680:
5681: Checks if there was an error when attempting to remove a specific
5682: scantron_.. bubble sheet data file. Prints out an error if
5683: something went wrong.
5684:
5685: =cut
5686:
5687: sub check_for_error {
5688: my ($r,$result)=@_;
5689: if ($result ne 'ok' && $result ne 'not_found' ) {
5690: $r->print("An error occurred ($result) when trying to Remove the existing corrections.");
5691: }
5692: }
5693:
5694: =pod
5695:
5696: =item scantron_warning_screen
5697:
5698: Interstitial screen to make sure the operator has selected the
5699: correct options before we start the validation phase.
5700:
5701: =cut
5702:
5703: sub scantron_warning_screen {
5704: my ($button_text)=@_;
5705: my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
5706: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
5707: my $CODElist;
5708: if ($scantron_config{'CODElocation'} &&
5709: $scantron_config{'CODEstart'} &&
5710: $scantron_config{'CODElength'}) {
5711: $CODElist=$env{'form.scantron_CODElist'};
5712: if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
5713: $CODElist=
5714: '<tr><td><b>List of CODES to validate against:</b></td><td><tt>'.
5715: $env{'form.scantron_CODElist'}.'</tt></td></tr>';
5716: }
5717: return (<<STUFF);
5718: <p>
5719: <span class="LC_warning">Please double check the information
5720: below before clicking on '$button_text'</span>
5721: </p>
5722: <table>
5723: <tr><td><b>Sequence to be Graded:</b></td><td>$title</td></tr>
5724: <tr><td><b>Data File that will be used:</b></td><td><tt>$env{'form.scantron_selectfile'}</tt></td></tr>
5725: $CODElist
5726: </table>
5727: <br />
5728: <p> If this information is correct, please click on '$button_text'.</p>
5729: <p> If something is incorrect, please click the 'Grading Menu' button to start over.</p>
5730:
5731: <br />
5732: STUFF
5733: }
5734:
5735: =pod
5736:
5737: =item scantron_do_warning
5738:
5739: Check if the operator has picked something for all required
5740: fields. Error out if something is missing.
5741:
5742: =cut
5743:
5744: sub scantron_do_warning {
5745: my ($r)=@_;
5746: my ($symb)=&get_symb($r);
5747: if (!$symb) {return '';}
5748: my $default_form_data=&defaultFormData($symb);
5749: $r->print(&scantron_form_start().$default_form_data);
5750: if ( $env{'form.selectpage'} eq '' ||
5751: $env{'form.scantron_selectfile'} eq '' ||
5752: $env{'form.scantron_format'} eq '' ) {
5753: $r->print("<p>You have forgetten to specify some information. Please go Back and try again.</p>");
5754: if ( $env{'form.selectpage'} eq '') {
5755: $r->print('<p><span class="LC_error">You have not selected a Sequence to grade</span></p>');
5756: }
5757: if ( $env{'form.scantron_selectfile'} eq '') {
5758: $r->print('<p><span class="LC_error">You have not selected a file that contains the student\'s response data.</span></p>');
5759: }
5760: if ( $env{'form.scantron_format'} eq '') {
5761: $r->print('<p><span class="LC_error">You have not selected a the format of the student\'s response data.</span></p>');
5762: }
5763: } else {
5764: my $warning=&scantron_warning_screen('Grading: Validate Records');
5765: $r->print(<<STUFF);
5766: $warning
5767: <input type="submit" name="submit" value="Grading: Validate Records" />
5768: <input type="hidden" name="command" value="scantron_validate" />
5769: STUFF
5770: }
5771: $r->print("</form><br />".&show_grading_menu_form($symb));
5772: return '';
5773: }
5774:
5775: =pod
5776:
5777: =item scantron_form_start
5778:
5779: html hidden input for remembering all selected grading options
5780:
5781: =cut
5782:
5783: sub scantron_form_start {
5784: my ($max_bubble)=@_;
5785: my $result= <<SCANTRONFORM;
5786: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
5787: <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
5788: <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
5789: <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
5790: <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
5791: <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
5792: <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
5793: <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
5794: <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
5795: <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
5796: SCANTRONFORM
5797:
5798: my $line = 0;
5799: while (defined($env{"form.scantron.bubblelines.$line"})) {
5800: my $chunk =
5801: '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
5802: $chunk .=
5803: '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
5804: $result .= $chunk;
5805: $line++;
5806: }
5807: return $result;
5808: }
5809:
5810: =pod
5811:
5812: =item scantron_validate_file
5813:
5814: Dispatch routine for doing validation of a bubble sheet data file.
5815:
5816: Also processes any necessary information resets that need to
5817: occur before validation begins (ignore previous corrections,
5818: restarting the skipped records processing)
5819:
5820: =cut
5821:
5822: sub scantron_validate_file {
5823: my ($r) = @_;
5824: my ($symb)=&get_symb($r);
5825: if (!$symb) {return '';}
5826: my $default_form_data=&defaultFormData($symb);
5827:
5828: # do the detection of only doing skipped records first befroe we delete
5829: # them when doing the corrections reset
5830: if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
5831: &reset_skipping_status();
5832: }
5833: if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
5834: &remember_current_skipped();
5835: $env{'form.scantron_options_redo'}='redo_skipped_ready';
5836: }
5837:
5838: if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
5839: &check_for_error($r,&scantron_remove_file('corrected'));
5840: &check_for_error($r,&scantron_remove_file('skipped'));
5841: &check_for_error($r,&scantron_remove_scan_data());
5842: $env{'form.scantron_options_ignore'}='done';
5843: }
5844:
5845: if ($env{'form.scantron_corrections'}) {
5846: &scantron_process_corrections($r);
5847: }
5848: $r->print("<p>Gathering necessary info.</p>");$r->rflush();
5849: #get the student pick code ready
5850: $r->print(&Apache::loncommon::studentbrowser_javascript());
5851: my $max_bubble=&scantron_get_maxbubble();
5852: my $result=&scantron_form_start($max_bubble).$default_form_data;
5853: $r->print($result);
5854:
5855: my @validate_phases=( 'sequence',
5856: 'ID',
5857: 'CODE',
5858: 'doublebubble',
5859: 'missingbubbles');
5860: if (!$env{'form.validatepass'}) {
5861: $env{'form.validatepass'} = 0;
5862: }
5863: my $currentphase=$env{'form.validatepass'};
5864:
5865:
5866: my $stop=0;
5867: while (!$stop && $currentphase < scalar(@validate_phases)) {
5868: $r->print("<p> Validating ".$validate_phases[$currentphase]."</p>");
5869: $r->rflush();
5870: my $which="scantron_validate_".$validate_phases[$currentphase];
5871: {
5872: no strict 'refs';
5873: ($stop,$currentphase)=&$which($r,$currentphase);
5874: }
5875: }
5876: if (!$stop) {
5877: my $warning=&scantron_warning_screen('Start Grading');
5878: $r->print(<<STUFF);
5879: Validation process complete.<br />
5880: $warning
5881: <input type="submit" name="submit" value="Start Grading" />
5882: <input type="hidden" name="command" value="scantron_process" />
5883: STUFF
5884:
5885: } else {
5886: $r->print('<input type="hidden" name="command" value="scantron_validate" />');
5887: $r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
5888: }
5889: if ($stop) {
5890: if ($validate_phases[$currentphase] eq 'sequence') {
5891: $r->print('<input type="submit" name="submit" value="Ignore -> " />');
5892: $r->print(' this error <br />');
5893:
5894: $r->print(" <p>Or click the 'Grading Menu' button to start over.</p>");
5895: } else {
5896: $r->print('<input type="submit" name="submit" value="Continue ->" />');
5897: $r->print(' using corrected info <br />');
5898: $r->print("<input type='submit' value='Skip' name='scantron_skip_record' />");
5899: $r->print(" this scanline saving it for later.");
5900: }
5901: }
5902: $r->print(" </form><br />".&show_grading_menu_form($symb));
5903: return '';
5904: }
5905:
5906:
5907: =pod
5908:
5909: =item scantron_remove_file
5910:
5911: Removes the requested bubble sheet data file, makes sure that
5912: scantron_original_<filename> is never removed
5913:
5914:
5915: =cut
5916:
5917: sub scantron_remove_file {
5918: my ($which)=@_;
5919: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5920: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5921: my $file='scantron_';
5922: if ($which eq 'corrected' || $which eq 'skipped') {
5923: $file.=$which.'_';
5924: } else {
5925: return 'refused';
5926: }
5927: $file.=$env{'form.scantron_selectfile'};
5928: return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
5929: }
5930:
5931:
5932: =pod
5933:
5934: =item scantron_remove_scan_data
5935:
5936: Removes all scan_data correction for the requested bubble sheet
5937: data file. (In the case that both the are doing skipped records we need
5938: to remember the old skipped lines for the time being so that element
5939: persists for a while.)
5940:
5941: =cut
5942:
5943: sub scantron_remove_scan_data {
5944: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5945: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5946: my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
5947: my @todelete;
5948: my $filename=$env{'form.scantron_selectfile'};
5949: foreach my $key (@keys) {
5950: if ($key=~/^\Q$filename\E_/) {
5951: if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
5952: $key=~/remember_skipping/) {
5953: next;
5954: }
5955: push(@todelete,$key);
5956: }
5957: }
5958: my $result;
5959: if (@todelete) {
5960: $result=&Apache::lonnet::del('nohist_scantrondata',\@todelete,$cdom,$cname);
5961: }
5962: return $result;
5963: }
5964:
5965:
5966: =pod
5967:
5968: =item scantron_getfile
5969:
5970: Fetches the requested bubble sheet data file (all 3 versions), and
5971: the scan_data hash
5972:
5973: Arguments:
5974: None
5975:
5976: Returns:
5977: 2 hash references
5978:
5979: - first one has
5980: orig -
5981: corrected -
5982: skipped - each of which points to an array ref of the specified
5983: file broken up into individual lines
5984: count - number of scanlines
5985:
5986: - second is the scan_data hash possible keys are
5987: ($number refers to scanline numbered $number and thus the key affects
5988: only that scanline
5989: $bubline refers to the specific bubble line element and the aspects
5990: refers to that specific bubble line element)
5991:
5992: $number.user - username:domain to use
5993: $number.CODE_ignore_dup
5994: - ignore the duplicate CODE error
5995: $number.useCODE
5996: - use the CODE in the scanline as is
5997: $number.no_bubble.$bubline
5998: - it is valid that there is no bubbled in bubble
5999: at $number $bubline
6000: remember_skipping
6001: - a frozen hash containing keys of $number and values
6002: of either
6003: 1 - we are on a 'do skipped records pass' and plan
6004: on processing this line
6005: 2 - we are on a 'do skipped records pass' and this
6006: scanline has been marked to skip yet again
6007:
6008: =cut
6009:
6010: sub scantron_getfile {
6011: #FIXME really would prefer a scantron directory
6012: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6013: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6014: my $lines;
6015: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
6016: 'scantron_orig_'.$env{'form.scantron_selectfile'});
6017: my %scanlines;
6018: $scanlines{'orig'}=[(split("\n",$lines,-1))];
6019: my $temp=$scanlines{'orig'};
6020: $scanlines{'count'}=$#$temp;
6021:
6022: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
6023: 'scantron_corrected_'.$env{'form.scantron_selectfile'});
6024: if ($lines eq '-1') {
6025: $scanlines{'corrected'}=[];
6026: } else {
6027: $scanlines{'corrected'}=[(split("\n",$lines,-1))];
6028: }
6029: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
6030: 'scantron_skipped_'.$env{'form.scantron_selectfile'});
6031: if ($lines eq '-1') {
6032: $scanlines{'skipped'}=[];
6033: } else {
6034: $scanlines{'skipped'}=[(split("\n",$lines,-1))];
6035: }
6036: my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
6037: if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
6038: my %scan_data = @tmp;
6039: return (\%scanlines,\%scan_data);
6040: }
6041:
6042: =pod
6043:
6044: =item lonnet_putfile
6045:
6046: Wrapper routine to call &Apache::lonnet::finishuserfileupload
6047:
6048: Arguments:
6049: $contents - data to store
6050: $filename - filename to store $contents into
6051:
6052: Returns:
6053: result value from &Apache::lonnet::finishuserfileupload
6054:
6055: =cut
6056:
6057: sub lonnet_putfile {
6058: my ($contents,$filename)=@_;
6059: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
6060: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6061: $env{'form.sillywaytopassafilearound'}=$contents;
6062: &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
6063:
6064: }
6065:
6066: =pod
6067:
6068: =item scantron_putfile
6069:
6070: Stores the current version of the bubble sheet data files, and the
6071: scan_data hash. (Does not modify the original version only the
6072: corrected and skipped versions.
6073:
6074: Arguments:
6075: $scanlines - hash ref that looks like the first return value from
6076: &scantron_getfile()
6077: $scan_data - hash ref that looks like the second return value from
6078: &scantron_getfile()
6079:
6080: =cut
6081:
6082: sub scantron_putfile {
6083: my ($scanlines,$scan_data) = @_;
6084: #FIXME really would prefer a scantron directory
6085: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6086: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6087: if ($scanlines) {
6088: my $prefix='scantron_';
6089: # no need to update orig, shouldn't change
6090: # &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
6091: # $env{'form.scantron_selectfile'});
6092: &lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
6093: $prefix.'corrected_'.
6094: $env{'form.scantron_selectfile'});
6095: &lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
6096: $prefix.'skipped_'.
6097: $env{'form.scantron_selectfile'});
6098: }
6099: &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
6100: }
6101:
6102: =pod
6103:
6104: =item scantron_get_line
6105:
6106: Returns the correct version of the scanline
6107:
6108: Arguments:
6109: $scanlines - hash ref that looks like the first return value from
6110: &scantron_getfile()
6111: $scan_data - hash ref that looks like the second return value from
6112: &scantron_getfile()
6113: $i - number of the requested line (starts at 0)
6114:
6115: Returns:
6116: A scanline, (either the original or the corrected one if it
6117: exists), or undef if the requested scanline should be
6118: skipped. (Either because it's an skipped scanline, or it's an
6119: unskipped scanline and we are not doing a 'do skipped scanlines'
6120: pass.
6121:
6122: =cut
6123:
6124: sub scantron_get_line {
6125: my ($scanlines,$scan_data,$i)=@_;
6126: if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
6127: #if ($scanlines->{'skipped'}[$i]) { return undef; }
6128: if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
6129: return $scanlines->{'orig'}[$i];
6130: }
6131:
6132: =pod
6133:
6134: =item scantron_todo_count
6135:
6136: Counts the number of scanlines that need processing.
6137:
6138: Arguments:
6139: $scanlines - hash ref that looks like the first return value from
6140: &scantron_getfile()
6141: $scan_data - hash ref that looks like the second return value from
6142: &scantron_getfile()
6143:
6144: Returns:
6145: $count - number of scanlines to process
6146:
6147: =cut
6148:
6149: sub get_todo_count {
6150: my ($scanlines,$scan_data)=@_;
6151: my $count=0;
6152: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6153: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6154: if ($line=~/^[\s\cz]*$/) { next; }
6155: $count++;
6156: }
6157: return $count;
6158: }
6159:
6160: =pod
6161:
6162: =item scantron_put_line
6163:
6164: Updates the 'corrected' or 'skipped' versions of the bubble sheet
6165: data file.
6166:
6167: Arguments:
6168: $scanlines - hash ref that looks like the first return value from
6169: &scantron_getfile()
6170: $scan_data - hash ref that looks like the second return value from
6171: &scantron_getfile()
6172: $i - line number to update
6173: $newline - contents of the updated scanline
6174: $skip - if true make the line for skipping and update the
6175: 'skipped' file
6176:
6177: =cut
6178:
6179: sub scantron_put_line {
6180: my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
6181: if ($skip) {
6182: $scanlines->{'skipped'}[$i]=$newline;
6183: &start_skipping($scan_data,$i);
6184: return;
6185: }
6186: $scanlines->{'corrected'}[$i]=$newline;
6187: }
6188:
6189: =pod
6190:
6191: =item scantron_clear_skip
6192:
6193: Remove a line from the 'skipped' file
6194:
6195: Arguments:
6196: $scanlines - hash ref that looks like the first return value from
6197: &scantron_getfile()
6198: $scan_data - hash ref that looks like the second return value from
6199: &scantron_getfile()
6200: $i - line number to update
6201:
6202: =cut
6203:
6204: sub scantron_clear_skip {
6205: my ($scanlines,$scan_data,$i)=@_;
6206: if (exists($scanlines->{'skipped'}[$i])) {
6207: undef($scanlines->{'skipped'}[$i]);
6208: return 1;
6209: }
6210: return 0;
6211: }
6212:
6213: =pod
6214:
6215: =item scantron_filter_not_exam
6216:
6217: Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
6218: filter out resources that are not marked as 'exam' mode
6219:
6220: =cut
6221:
6222: sub scantron_filter_not_exam {
6223: my ($curres)=@_;
6224:
6225: if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
6226: # if the user has asked to not have either hidden
6227: # or 'randomout' controlled resources to be graded
6228: # don't include them
6229: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
6230: && $curres->randomout) {
6231: return 0;
6232: }
6233: return 1;
6234: }
6235: return 0;
6236: }
6237:
6238: =pod
6239:
6240: =item scantron_validate_sequence
6241:
6242: Validates the selected sequence, checking for resource that are
6243: not set to exam mode.
6244:
6245: =cut
6246:
6247: sub scantron_validate_sequence {
6248: my ($r,$currentphase) = @_;
6249:
6250: my $navmap=Apache::lonnavmaps::navmap->new();
6251: my (undef,undef,$sequence)=
6252: &Apache::lonnet::decode_symb($env{'form.selectpage'});
6253:
6254: my $map=$navmap->getResourceByUrl($sequence);
6255:
6256: $r->print('<input type="hidden" name="validate_sequence_exam"
6257: value="ignore" />');
6258: if ($env{'form.validate_sequence_exam'} ne 'ignore') {
6259: my @resources=
6260: $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
6261: if (@resources) {
6262: $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>");
6263: return (1,$currentphase);
6264: }
6265: }
6266:
6267: return (0,$currentphase+1);
6268: }
6269:
6270: =pod
6271:
6272: =item scantron_validate_ID
6273:
6274: Validates all scanlines in the selected file to not have any
6275: invalid or underspecified student IDs
6276:
6277: =cut
6278:
6279: sub scantron_validate_ID {
6280: my ($r,$currentphase) = @_;
6281:
6282: #get student info
6283: my $classlist=&Apache::loncoursedata::get_classlist();
6284: my %idmap=&username_to_idmap($classlist);
6285:
6286: #get scantron line setup
6287: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6288: my ($scanlines,$scan_data)=&scantron_getfile();
6289:
6290: &scantron_get_maxbubble(); # parse needs the bubble_lines.. array.
6291:
6292: my %found=('ids'=>{},'usernames'=>{});
6293: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6294: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6295: if ($line=~/^[\s\cz]*$/) { next; }
6296: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6297: $scan_data);
6298: my $id=$$scan_record{'scantron.ID'};
6299: my $found;
6300: foreach my $checkid (keys(%idmap)) {
6301: if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
6302: }
6303: if ($found) {
6304: my $username=$idmap{$found};
6305: if ($found{'ids'}{$found}) {
6306: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6307: $line,'duplicateID',$found);
6308: return(1,$currentphase);
6309: } elsif ($found{'usernames'}{$username}) {
6310: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6311: $line,'duplicateID',$username);
6312: return(1,$currentphase);
6313: }
6314: #FIXME store away line we previously saw the ID on to use above
6315: $found{'ids'}{$found}++;
6316: $found{'usernames'}{$username}++;
6317: } else {
6318: if ($id =~ /^\s*$/) {
6319: my $username=&scan_data($scan_data,"$i.user");
6320: if (defined($username) && $found{'usernames'}{$username}) {
6321: &scantron_get_correction($r,$i,$scan_record,
6322: \%scantron_config,
6323: $line,'duplicateID',$username);
6324: return(1,$currentphase);
6325: } elsif (!defined($username)) {
6326: &scantron_get_correction($r,$i,$scan_record,
6327: \%scantron_config,
6328: $line,'incorrectID');
6329: return(1,$currentphase);
6330: }
6331: $found{'usernames'}{$username}++;
6332: } else {
6333: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6334: $line,'incorrectID');
6335: return(1,$currentphase);
6336: }
6337: }
6338: }
6339:
6340: return (0,$currentphase+1);
6341: }
6342:
6343: =pod
6344:
6345: =item scantron_get_correction
6346:
6347: Builds the interface screen to interact with the operator to fix a
6348: specific error condition in a specific scanline
6349:
6350: Arguments:
6351: $r - Apache request object
6352: $i - number of the current scanline
6353: $scan_record - hash ref as returned from &scantron_parse_scanline()
6354: $scan_config - hash ref as returned from &get_scantron_config()
6355: $line - full contents of the current scanline
6356: $error - error condition, valid values are
6357: 'incorrectCODE', 'duplicateCODE',
6358: 'doublebubble', 'missingbubble',
6359: 'duplicateID', 'incorrectID'
6360: $arg - extra information needed
6361: For errors:
6362: - duplicateID - paper number that this studentID was seen before on
6363: - duplicateCODE - array ref of the paper numbers this CODE was
6364: seen on before
6365: - incorrectCODE - current incorrect CODE
6366: - doublebubble - array ref of the bubble lines that have double
6367: bubble errors
6368: - missingbubble - array ref of the bubble lines that have missing
6369: bubble errors
6370:
6371: =cut
6372:
6373: sub scantron_get_correction {
6374: my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
6375:
6376: #FIXME in the case of a duplicated ID the previous line, probably need
6377: #to show both the current line and the previous one and allow skipping
6378: #the previous one or the current one
6379:
6380: $r->print("<p><b>An error was detected ($error)</b>");
6381: if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
6382: $r->print(" for PaperID <tt>".
6383: $$scan_record{'scantron.PaperID'}."</tt> \n");
6384: } else {
6385: $r->print(" in scanline $i <pre>".
6386: $line."</pre> \n");
6387: }
6388: my $message="<p>The ID on the form is <tt>".
6389: $$scan_record{'scantron.ID'}."</tt><br />\n".
6390: "The name on the paper is ".
6391: $$scan_record{'scantron.LastName'}.",".
6392: $$scan_record{'scantron.FirstName'}."</p>";
6393:
6394: $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
6395: $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
6396: if ($error =~ /ID$/) {
6397: if ($error eq 'incorrectID') {
6398: $r->print("The encoded ID is not in the classlist</p>\n");
6399: } elsif ($error eq 'duplicateID') {
6400: $r->print("The encoded ID has also been used by a previous paper $arg</p>\n");
6401: }
6402: $r->print($message);
6403: $r->print("<p>How should I handle this? <br /> \n");
6404: $r->print("\n<ul><li> ");
6405: #FIXME it would be nice if this sent back the user ID and
6406: #could do partial userID matches
6407: $r->print(&Apache::loncommon::selectstudent_link('scantronupload',
6408: 'scantron_username','scantron_domain'));
6409: $r->print(": <input type='text' name='scantron_username' value='' />");
6410: $r->print("\n@".
6411: &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
6412:
6413: $r->print('</li>');
6414: } elsif ($error =~ /CODE$/) {
6415: if ($error eq 'incorrectCODE') {
6416: $r->print("</p><p>The encoded CODE is not in the list of possible CODEs</p>\n");
6417: } elsif ($error eq 'duplicateCODE') {
6418: $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");
6419: }
6420: $r->print("<p>The CODE on the form is <tt>'".
6421: $$scan_record{'scantron.CODE'}."'</tt><br />\n");
6422: $r->print($message);
6423: $r->print("<p>How should I handle this? <br /> \n");
6424: $r->print("\n<br /> ");
6425: my $i=0;
6426: if ($error eq 'incorrectCODE'
6427: && $$scan_record{'scantron.CODE'}=~/\S/ ) {
6428: my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
6429: if ($closest > 0) {
6430: foreach my $testcode (@{$closest}) {
6431: my $checked='';
6432: if (!$i) { $checked=' checked="checked" '; }
6433: $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' />");
6434: $r->print("\n<br />");
6435: $i++;
6436: }
6437: }
6438: }
6439: if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
6440: my $checked; if (!$i) { $checked=' checked="checked" '; }
6441: $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>");
6442: $r->print("\n<br />");
6443: }
6444:
6445: $r->print(<<ENDSCRIPT);
6446: <script type="text/javascript">
6447: function change_radio(field) {
6448: var slct=document.scantronupload.scantron_CODE_resolution;
6449: var i;
6450: for (i=0;i<slct.length;i++) {
6451: if (slct[i].value==field) { slct[i].checked=true; }
6452: }
6453: }
6454: </script>
6455: ENDSCRIPT
6456: my $href="/adm/pickcode?".
6457: "form=".&escape("scantronupload").
6458: "&scantron_format=".&escape($env{'form.scantron_format'}).
6459: "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
6460: "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
6461: "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
6462: if ($env{'form.scantron_CODElist'} =~ /\S/) {
6463: $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')\" />");
6464: $r->print("\n<br />");
6465: }
6466: $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.");
6467: $r->print("\n<br /><br />");
6468: } elsif ($error eq 'doublebubble') {
6469: $r->print("<p>There have been multiple bubbles scanned for a some question(s)</p>\n");
6470: $r->print('<input type="hidden" name="scantron_questions" value="'.
6471: join(',',@{$arg}).'" />');
6472: $r->print($message);
6473: $r->print("<p>Please indicate which bubble should be used for grading</p>");
6474: foreach my $question (@{$arg}) {
6475: my $selected = &get_response_bubbles($scan_record, $question);
6476: my @select_array = split(/:/,$selected);
6477: &scantron_bubble_selector($r,$scan_config,$question,
6478: @select_array);
6479: }
6480: } elsif ($error eq 'missingbubble') {
6481: $r->print("<p>There have been <b>no</b> bubbles scanned for some question(s)</p>\n");
6482: $r->print($message);
6483: $r->print("<p>Please indicate which bubble should be used for grading</p>");
6484: $r->print("Some questions have no scanned bubbles\n");
6485: $r->print('<input type="hidden" name="scantron_questions" value="'.
6486: join(',',@{$arg}).'" />');
6487: foreach my $question (@{$arg}) {
6488: my $selected = &get_response_bubbles($scan_record, $question);
6489: my @select_array = split(/:/,$selected); # ought to be an array of empties.
6490: &Apache::lonnet::logthis("Calling bubble selector (missing)");
6491: &scantron_bubble_selector($r,$scan_config,$question, @select_array);
6492: }
6493: } else {
6494: $r->print("\n<ul>");
6495: }
6496: $r->print("\n</li></ul>");
6497:
6498: }
6499:
6500: =pod
6501:
6502: =item scantron_bubble_selector
6503:
6504: Generates the html radiobuttons to correct a single bubble line
6505: possibly showing the existing the selected bubbles if known
6506:
6507: Arguments:
6508: $r - Apache request object
6509: $scan_config - hash from &get_scantron_config()
6510: $quest - number of the bubble line to make a corrector for
6511: @lines - array of answer lines.
6512:
6513: =cut
6514:
6515: sub scantron_bubble_selector {
6516: my ($r,$scan_config,$quest,@lines)=@_;
6517: my $max=$$scan_config{'Qlength'};
6518:
6519:
6520: my $scmode=$$scan_config{'Qon'};
6521:
6522: my $bubble_length = scalar(@lines);
6523:
6524:
6525: if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }
6526:
6527: my $response = $quest-1;
6528: my $lines = $bubble_lines_per_response{$response};
6529:
6530: my $total_lines = $lines*2;
6531: my @alphabet=('A'..'Z');
6532: &Apache::lonnet::logthis("Putting in question number $quest");
6533: $r->print("<table border='1'><tr><td rowspan='".$total_lines."'>$quest</td>");
6534:
6535: for (my $l = 0; $l < $lines; $l++) {
6536: if ($l != 0) {
6537: $r->print('<tr>');
6538: }
6539: my @selected = split(//,$lines[$l]);
6540: for (my $i=0;$i<$max;$i++) {
6541: $r->print("\n".'<td align="center">');
6542: if ($selected[0] eq $alphabet[$i]) {
6543: $r->print('X');
6544: shift(@selected) ;
6545: } else {
6546: $r->print(' ');
6547: }
6548: $r->print('</td>');
6549:
6550: }
6551:
6552: if ($l == 0) {
6553: my $lspan = $total_lines * 2; # 2 table rows per bubble line.
6554:
6555: $r->print('<td rowspan='.$lspan.'><label><input type="radio" name="scantron_correct_Q_'.
6556: $quest.'" value="none" /> No bubble </label></td>');
6557:
6558: }
6559:
6560: $r->print('</tr><tr>');
6561:
6562: # FIXME: This may have to be a bit more clever for
6563: # multiline questions (different values e.g..).
6564:
6565: for (my $i=0;$i<$max;$i++) {
6566: $r->print("\n".
6567: '<td><label><input type="radio" name="scantron_correct_Q_'.
6568: $quest.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
6569: }
6570: $r->print('</tr>');
6571:
6572:
6573: }
6574: $r->print('</table>');
6575: }
6576:
6577: =pod
6578:
6579: =item num_matches
6580:
6581: Counts the number of characters that are the same between the two arguments.
6582:
6583: Arguments:
6584: $orig - CODE from the scanline
6585: $code - CODE to match against
6586:
6587: Returns:
6588: $count - integer count of the number of same characters between the
6589: two arguments
6590:
6591: =cut
6592:
6593: sub num_matches {
6594: my ($orig,$code) = @_;
6595: my @code=split(//,$code);
6596: my @orig=split(//,$orig);
6597: my $same=0;
6598: for (my $i=0;$i<scalar(@code);$i++) {
6599: if ($code[$i] eq $orig[$i]) { $same++; }
6600: }
6601: return $same;
6602: }
6603:
6604: =pod
6605:
6606: =item scantron_get_closely_matching_CODEs
6607:
6608: Cycles through all CODEs and finds the set that has the greatest
6609: number of same characters as the provided CODE
6610:
6611: Arguments:
6612: $allcodes - hash ref returned by &get_codes()
6613: $CODE - CODE from the current scanline
6614:
6615: Returns:
6616: 2 element list
6617: - first elements is number of how closely matching the best fit is
6618: (5 means best set has 5 matching characters)
6619: - second element is an arrary ref containing the set of valid CODEs
6620: that best fit the passed in CODE
6621:
6622: =cut
6623:
6624: sub scantron_get_closely_matching_CODEs {
6625: my ($allcodes,$CODE)=@_;
6626: my @CODEs;
6627: foreach my $testcode (sort(keys(%{$allcodes}))) {
6628: push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
6629: }
6630:
6631: return ($#CODEs,$CODEs[-1]);
6632: }
6633:
6634: =pod
6635:
6636: =item get_codes
6637:
6638: Builds a hash which has keys of all of the valid CODEs from the selected
6639: set of remembered CODEs.
6640:
6641: Arguments:
6642: $old_name - name of the set of remembered CODEs
6643: $cdom - domain of the course
6644: $cnum - internal course name
6645:
6646: Returns:
6647: %allcodes - keys are the valid CODEs, values are all 1
6648:
6649: =cut
6650:
6651: sub get_codes {
6652: my ($old_name, $cdom, $cnum) = @_;
6653: if (!$old_name) {
6654: $old_name=$env{'form.scantron_CODElist'};
6655: }
6656: if (!$cdom) {
6657: $cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
6658: }
6659: if (!$cnum) {
6660: $cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
6661: }
6662: my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
6663: $cdom,$cnum);
6664: my %allcodes;
6665: if ($result{"type\0$old_name"} eq 'number') {
6666: %allcodes=map {($_,1)} split(',',$result{$old_name});
6667: } else {
6668: %allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
6669: }
6670: return %allcodes;
6671: }
6672:
6673: =pod
6674:
6675: =item scantron_validate_CODE
6676:
6677: Validates all scanlines in the selected file to not have any
6678: invalid or underspecified CODEs and that none of the codes are
6679: duplicated if this was requested.
6680:
6681: =cut
6682:
6683: sub scantron_validate_CODE {
6684: my ($r,$currentphase) = @_;
6685: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6686: if ($scantron_config{'CODElocation'} &&
6687: $scantron_config{'CODEstart'} &&
6688: $scantron_config{'CODElength'}) {
6689: if (!defined($env{'form.scantron_CODElist'})) {
6690: &FIXME_blow_up()
6691: }
6692: } else {
6693: return (0,$currentphase+1);
6694: }
6695:
6696: my %usedCODEs;
6697:
6698: my %allcodes=&get_codes();
6699:
6700: &scantron_get_maxbubble(); # parse needs the lines per response array.
6701:
6702: my ($scanlines,$scan_data)=&scantron_getfile();
6703: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6704: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6705: if ($line=~/^[\s\cz]*$/) { next; }
6706: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6707: $scan_data);
6708: my $CODE=$$scan_record{'scantron.CODE'};
6709: my $error=0;
6710: if (!&Apache::lonnet::validCODE($CODE)) {
6711: &scantron_get_correction($r,$i,$scan_record,
6712: \%scantron_config,
6713: $line,'incorrectCODE',\%allcodes);
6714: return(1,$currentphase);
6715: }
6716: if (%allcodes && !exists($allcodes{$CODE})
6717: && !$$scan_record{'scantron.useCODE'}) {
6718: &scantron_get_correction($r,$i,$scan_record,
6719: \%scantron_config,
6720: $line,'incorrectCODE',\%allcodes);
6721: return(1,$currentphase);
6722: }
6723: if (exists($usedCODEs{$CODE})
6724: && $env{'form.scantron_CODEunique'} eq 'yes'
6725: && !$$scan_record{'scantron.CODE_ignore_dup'}) {
6726: &scantron_get_correction($r,$i,$scan_record,
6727: \%scantron_config,
6728: $line,'duplicateCODE',$usedCODEs{$CODE});
6729: return(1,$currentphase);
6730: }
6731: push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
6732: }
6733: return (0,$currentphase+1);
6734: }
6735:
6736: =pod
6737:
6738: =item scantron_validate_doublebubble
6739:
6740: Validates all scanlines in the selected file to not have any
6741: bubble lines with multiple bubbles marked.
6742:
6743: =cut
6744:
6745: sub scantron_validate_doublebubble {
6746: my ($r,$currentphase) = @_;
6747: #get student info
6748: my $classlist=&Apache::loncoursedata::get_classlist();
6749: my %idmap=&username_to_idmap($classlist);
6750:
6751: #get scantron line setup
6752: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6753: my ($scanlines,$scan_data)=&scantron_getfile();
6754:
6755: &scantron_get_maxbubble(); # parse needs the bubble line array.
6756:
6757: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6758: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6759: if ($line=~/^[\s\cz]*$/) { next; }
6760: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6761: $scan_data);
6762: if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
6763: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
6764: 'doublebubble',
6765: $$scan_record{'scantron.doubleerror'});
6766: return (1,$currentphase);
6767: }
6768: return (0,$currentphase+1);
6769: }
6770:
6771: =pod
6772:
6773: =item scantron_get_maxbubble
6774:
6775: Returns the maximum number of bubble lines that are expected to
6776: occur. Does this by walking the selected sequence rendering the
6777: resource and then checking &Apache::lonxml::get_problem_counter()
6778: for what the current value of the problem counter is.
6779:
6780: Caches the results to $env{'form.scantron_maxbubble'},
6781: $env{'form.scantron.bubble_lines.n'} and
6782: $env{'form.scantron.first_bubble_line.n'}
6783: which are the total number of bubble, lines, the number of bubble
6784: lines for reponse n and number of the first bubble line for response n.
6785:
6786: =cut
6787:
6788: sub scantron_get_maxbubble {
6789: if (defined($env{'form.scantron_maxbubble'}) &&
6790: $env{'form.scantron_maxbubble'}) {
6791: &restore_bubble_lines();
6792: return $env{'form.scantron_maxbubble'};
6793: }
6794:
6795: my (undef, undef, $sequence) =
6796: &Apache::lonnet::decode_symb($env{'form.selectpage'});
6797:
6798: my $navmap=Apache::lonnavmaps::navmap->new();
6799: my $map=$navmap->getResourceByUrl($sequence);
6800: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
6801:
6802: &Apache::lonxml::clear_problem_counter();
6803:
6804: my $uname = $env{'form.student'};
6805: my $udom = $env{'form.userdom'};
6806: my $cid = $env{'request.course.id'};
6807: my $total_lines = 0;
6808: %bubble_lines_per_response = ();
6809: %first_bubble_line = ();
6810:
6811:
6812: my $response_number = 0;
6813: my $bubble_line = 0;
6814: foreach my $resource (@resources) {
6815: my $symb = $resource->symb();
6816: &Apache::lonxml::clear_bubble_lines_for_part();
6817: my $result=&Apache::lonnet::ssi($resource->src(),
6818: ('symb' => $resource->symb()),
6819: ('grade_target' => 'analyze'),
6820: ('grade_courseid' => $cid),
6821: ('grade_domain' => $udom),
6822: ('grade_username' => $uname));
6823: my (undef, $an) =
6824: split(/_HASH_REF__/,$result, 2);
6825:
6826: my %analysis = &Apache::lonnet::str2hash($an);
6827:
6828:
6829:
6830: foreach my $part_id (@{$analysis{'parts'}}) {
6831:
6832:
6833: my $lines = $analysis{"$part_id.bubble_lines"};;
6834:
6835: # TODO - make this a persistent hash not an array.
6836:
6837:
6838: $first_bubble_line{$response_number} = $bubble_line;
6839: $bubble_lines_per_response{$response_number} = $lines;
6840: $response_number++;
6841:
6842: $bubble_line += $lines;
6843: $total_lines += $lines;
6844: }
6845:
6846: }
6847: &Apache::lonnet::delenv('scantron\.');
6848:
6849: &save_bubble_lines();
6850: $env{'form.scantron_maxbubble'} =
6851: $total_lines;
6852: return $env{'form.scantron_maxbubble'};
6853: }
6854:
6855: =pod
6856:
6857: =item scantron_validate_missingbubbles
6858:
6859: Validates all scanlines in the selected file to not have any
6860: answers that don't have bubbles that have not been verified
6861: to be bubble free.
6862:
6863: =cut
6864:
6865: sub scantron_validate_missingbubbles {
6866: my ($r,$currentphase) = @_;
6867: #get student info
6868: my $classlist=&Apache::loncoursedata::get_classlist();
6869: my %idmap=&username_to_idmap($classlist);
6870:
6871: #get scantron line setup
6872: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6873: my ($scanlines,$scan_data)=&scantron_getfile();
6874: my $max_bubble=&scantron_get_maxbubble();
6875: if (!$max_bubble) { $max_bubble=2**31; }
6876: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6877: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6878: if ($line=~/^[\s\cz]*$/) { next; }
6879: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6880: $scan_data);
6881: if (!defined($$scan_record{'scantron.missingerror'})) { next; }
6882: my @to_correct;
6883:
6884: # Probably here's where the error is...
6885:
6886: foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
6887: if ($missing > $max_bubble) { next; }
6888: &Apache::lonnet::logthis("Marking $missing for missing bubble check");
6889: push(@to_correct,$missing);
6890: }
6891: if (@to_correct) {
6892: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6893: $line,'missingbubble',\@to_correct);
6894: return (1,$currentphase);
6895: }
6896:
6897: }
6898: return (0,$currentphase+1);
6899: }
6900:
6901: =pod
6902:
6903: =item scantron_process_students
6904:
6905: Routine that does the actual grading of the bubble sheet information.
6906:
6907: The parsed scanline hash is added to %env
6908:
6909: Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
6910: foreach resource , with the form data of
6911:
6912: 'submitted' =>'scantron'
6913: 'grade_target' =>'grade',
6914: 'grade_username'=> username of student
6915: 'grade_domain' => domain of student
6916: 'grade_courseid'=> of course
6917: 'grade_symb' => symb of resource to grade
6918:
6919: This triggers a grading pass. The problem grading code takes care
6920: of converting the bubbled letter information (now in %env) into a
6921: valid submission.
6922:
6923: =cut
6924:
6925: sub scantron_process_students {
6926: my ($r) = @_;
6927: my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
6928: my ($symb)=&get_symb($r);
6929: if (!$symb) {return '';}
6930: my $default_form_data=&defaultFormData($symb);
6931:
6932: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6933: my ($scanlines,$scan_data)=&scantron_getfile();
6934: my $classlist=&Apache::loncoursedata::get_classlist();
6935: my %idmap=&username_to_idmap($classlist);
6936: my $navmap=Apache::lonnavmaps::navmap->new();
6937: my $map=$navmap->getResourceByUrl($sequence);
6938: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
6939: # $r->print("geto ".scalar(@resources)."<br />");
6940: my $result= <<SCANTRONFORM;
6941: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
6942: <input type="hidden" name="command" value="scantron_configphase" />
6943: $default_form_data
6944: SCANTRONFORM
6945: $r->print($result);
6946:
6947: my @delayqueue;
6948: my %completedstudents;
6949:
6950: my $count=&get_todo_count($scanlines,$scan_data);
6951: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
6952: 'Scantron Progress',$count,
6953: 'inline',undef,'scantronupload');
6954: &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
6955: 'Processing first student');
6956: my $start=&Time::HiRes::time();
6957: my $i=-1;
6958: my ($uname,$udom,$started);
6959:
6960: &scantron_get_maxbubble(); # Need the bubble lines array to parse.
6961:
6962: while ($i<$scanlines->{'count'}) {
6963: ($uname,$udom)=('','');
6964: $i++;
6965: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6966: if ($line=~/^[\s\cz]*$/) { next; }
6967: if ($started) {
6968: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
6969: 'last student');
6970: }
6971: $started=1;
6972: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6973: $scan_data);
6974: unless ($uname=&scantron_find_student($scan_record,$scan_data,
6975: \%idmap,$i)) {
6976: &scantron_add_delay(\@delayqueue,$line,
6977: 'Unable to find a student that matches',1);
6978: next;
6979: }
6980: if (exists $completedstudents{$uname}) {
6981: &scantron_add_delay(\@delayqueue,$line,
6982: 'Student '.$uname.' has multiple sheets',2);
6983: next;
6984: }
6985: ($uname,$udom)=split(/:/,$uname);
6986:
6987: &Apache::lonxml::clear_problem_counter();
6988: &Apache::lonnet::appenv(%$scan_record);
6989:
6990: if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
6991: &scantron_putfile($scanlines,$scan_data);
6992: }
6993:
6994: my $i=0;
6995: foreach my $resource (@resources) {
6996: $i++;
6997: my %form=('submitted' =>'scantron',
6998: 'grade_target' =>'grade',
6999: 'grade_username'=>$uname,
7000: 'grade_domain' =>$udom,
7001: 'grade_courseid'=>$env{'request.course.id'},
7002: 'grade_symb' =>$resource->symb());
7003: if (exists($scan_record->{'scantron.CODE'})
7004: &&
7005: &Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
7006: $form{'CODE'}=$scan_record->{'scantron.CODE'};
7007: } else {
7008: $form{'CODE'}='';
7009: }
7010: my $result=&Apache::lonnet::ssi($resource->src(),%form);
7011: if ($result ne '') {
7012: }
7013: if (&Apache::loncommon::connection_aborted($r)) { last; }
7014: }
7015: $completedstudents{$uname}={'line'=>$line};
7016: if (&Apache::loncommon::connection_aborted($r)) { last; }
7017: } continue {
7018: &Apache::lonxml::clear_problem_counter();
7019: &Apache::lonnet::delenv('scantron\.');
7020: }
7021: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
7022: # my $lasttime = &Time::HiRes::time()-$start;
7023: # $r->print("<p>took $lasttime</p>");
7024:
7025: $r->print("</form>");
7026: $r->print(&show_grading_menu_form($symb));
7027: return '';
7028: }
7029:
7030: =pod
7031:
7032: =item scantron_upload_scantron_data
7033:
7034: Creates the screen for adding a new bubble sheet data file to a course.
7035:
7036: =cut
7037:
7038: sub scantron_upload_scantron_data {
7039: my ($r)=@_;
7040: $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
7041: my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
7042: 'domainid',
7043: 'coursename');
7044: my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
7045: 'domainid');
7046: my $default_form_data=&defaultFormData(&get_symb($r,1));
7047: $r->print(<<UPLOAD);
7048: <script type="text/javascript" language="javascript">
7049: function checkUpload(formname) {
7050: if (formname.upfile.value == "") {
7051: alert("Please use the browse button to select a file from your local directory.");
7052: return false;
7053: }
7054: formname.submit();
7055: }
7056: </script>
7057:
7058: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
7059: $default_form_data
7060: <table>
7061: <tr><td>$select_link </td></tr>
7062: <tr><td>Course ID: </td><td><input name='courseid' type='text' /> </td></tr>
7063: <tr><td>Course Name: </td><td><input name='coursename' type='text' /></td></tr>
7064: <tr><td>Domain: </td><td>$domsel </td></tr>
7065: <tr><td>File to upload:</td><td><input type="file" name="upfile" size="50" /></td></tr>
7066: </table>
7067: <input name='command' value='scantronupload_save' type='hidden' />
7068: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
7069: </form>
7070: UPLOAD
7071: return '';
7072: }
7073:
7074: =pod
7075:
7076: =item scantron_upload_scantron_data_save
7077:
7078: Adds a provided bubble information data file to the course if user
7079: has the correct privileges to do so.
7080:
7081: =cut
7082:
7083: sub scantron_upload_scantron_data_save {
7084: my($r)=@_;
7085: my ($symb)=&get_symb($r,1);
7086: my $doanotherupload=
7087: '<br /><form action="/adm/grades" method="post">'."\n".
7088: '<input type="hidden" name="command" value="scantronupload" />'."\n".
7089: '<input type="submit" name="submit" value="Do Another Upload" />'."\n".
7090: '</form>'."\n";
7091: if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
7092: !&Apache::lonnet::allowed('usc',
7093: $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
7094: $r->print("You are not allowed to upload Scantron data to the requested course.<br />");
7095: if ($symb) {
7096: $r->print(&show_grading_menu_form($symb));
7097: } else {
7098: $r->print($doanotherupload);
7099: }
7100: return '';
7101: }
7102: my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
7103: $r->print("Doing upload to ".$coursedata{'description'}." <br />");
7104: my $fname=$env{'form.upfile.filename'};
7105: #FIXME
7106: #copied from lonnet::userfileupload()
7107: #make that function able to target a specified course
7108: # Replace Windows backslashes by forward slashes
7109: $fname=~s/\\/\//g;
7110: # Get rid of everything but the actual filename
7111: $fname=~s/^.*\/([^\/]+)$/$1/;
7112: # Replace spaces by underscores
7113: $fname=~s/\s+/\_/g;
7114: # Replace all other weird characters by nothing
7115: $fname=~s/[^\w\.\-]//g;
7116: # See if there is anything left
7117: unless ($fname) { return 'error: no uploaded file'; }
7118: my $uploadedfile=$fname;
7119: $fname='scantron_orig_'.$fname;
7120: if (length($env{'form.upfile'}) < 2) {
7121: $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.");
7122: } else {
7123: my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
7124: if ($result =~ m|^/uploaded/|) {
7125: $r->print("<span class=\"LC_success\">Success:</span> Successfully uploaded ".(length($env{'form.upfile'})-1)." bytes of data into location <tt>".$result."</tt>");
7126: } else {
7127: $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>");
7128: }
7129: }
7130: if ($symb) {
7131: $r->print(&scantron_selectphase($r,$uploadedfile));
7132: } else {
7133: $r->print($doanotherupload);
7134: }
7135: return '';
7136: }
7137:
7138: =pod
7139:
7140: =item valid_file
7141:
7142: Validates that the requested bubble data file exists in the course.
7143:
7144: =cut
7145:
7146: sub valid_file {
7147: my ($requested_file)=@_;
7148: foreach my $filename (sort(&scantron_filenames())) {
7149: if ($requested_file eq $filename) { return 1; }
7150: }
7151: return 0;
7152: }
7153:
7154: =pod
7155:
7156: =item scantron_download_scantron_data
7157:
7158: Shows a list of the three internal files (original, corrected,
7159: skipped) for a specific bubble sheet data file that exists in the
7160: course.
7161:
7162: =cut
7163:
7164: sub scantron_download_scantron_data {
7165: my ($r)=@_;
7166: my $default_form_data=&defaultFormData(&get_symb($r,1));
7167: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7168: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7169: my $file=$env{'form.scantron_selectfile'};
7170: if (! &valid_file($file)) {
7171: $r->print(<<ERROR);
7172: <p>
7173: The requested file name was invalid.
7174: </p>
7175: ERROR
7176: $r->print(&show_grading_menu_form(&get_symb($r,1)));
7177: return;
7178: }
7179: my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
7180: my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
7181: my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
7182: &Apache::lonnet::allowuploaded('/adm/grades',$orig);
7183: &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
7184: &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
7185: $r->print(<<DOWNLOAD);
7186: <p>
7187: <a href="$orig">Original</a> file as uploaded by the scantron office.
7188: </p>
7189: <p>
7190: <a href="$corrected">Corrections</a>, a file of corrected records that were used in grading.
7191: </p>
7192: <p>
7193: <a href="$skipped">Skipped</a>, a file of records that were skipped.
7194: </p>
7195: DOWNLOAD
7196: $r->print(&show_grading_menu_form(&get_symb($r,1)));
7197: return '';
7198: }
7199:
7200: =pod
7201:
7202: =back
7203:
7204: =cut
7205:
7206: #-------- end of section for handling grading scantron forms -------
7207: #
7208: #-------------------------------------------------------------------
7209:
7210: #-------------------------- Menu interface -------------------------
7211: #
7212: #--- Show a Grading Menu button - Calls the next routine ---
7213: sub show_grading_menu_form {
7214: my ($symb)=@_;
7215: my $result.='<br /><form action="/adm/grades" method="post">'."\n".
7216: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
7217: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
7218: '<input type="hidden" name="command" value="gradingmenu" />'."\n".
7219: '<input type="submit" name="submit" value="Grading Menu" />'."\n".
7220: '</form>'."\n";
7221: return $result;
7222: }
7223:
7224: # -- Retrieve choices for grading form
7225: sub savedState {
7226: my %savedState = ();
7227: if ($env{'form.saveState'}) {
7228: foreach (split(/:/,$env{'form.saveState'})) {
7229: my ($key,$value) = split(/=/,$_,2);
7230: $savedState{$key} = $value;
7231: }
7232: }
7233: return \%savedState;
7234: }
7235:
7236: sub grading_menu {
7237: my ($request) = @_;
7238: my ($symb)=&get_symb($request);
7239: if (!$symb) {return '';}
7240: my $probTitle = &Apache::lonnet::gettitle($symb);
7241: my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
7242:
7243: $request->print($table);
7244: my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
7245: 'handgrade'=>$hdgrade,
7246: 'probTitle'=>$probTitle,
7247: 'command'=>'submit_options',
7248: 'saveState'=>"",
7249: 'gradingMenu'=>1,
7250: 'showgrading'=>"yes");
7251: my $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
7252: my @menu = ({ url => $url,
7253: name => &mt('Manual Grading/View Submissions'),
7254: short_description =>
7255: &mt('Start the process of hand grading submissions.'),
7256: });
7257: $fields{'command'} = 'csvform';
7258: $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
7259: push (@menu, { url => $url,
7260: name => &mt('Upload Scores'),
7261: short_description =>
7262: &mt('Specify a file containing the class scores for current resource.')});
7263: $fields{'command'} = 'processclicker';
7264: $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
7265: push (@menu, { url => $url,
7266: name => &mt('Process Clicker'),
7267: short_description =>
7268: &mt('Specify a file containing the clicker information for this resource.')});
7269: $fields{'command'} = 'scantron_selectphase';
7270: $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
7271: push (@menu, { url => $url,
7272: name => &mt('Grade/Manage Scantron Forms'),
7273: short_description =>
7274: &mt('')});
7275: $fields{'command'} = 'verify';
7276: $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
7277: push (@menu, { url => "",
7278: name => &mt('Verify Receipt'),
7279: short_description =>
7280: &mt('')});
7281: #
7282: # Create the menu
7283: my $Str;
7284: # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
7285: $Str .= '<form method="post" action="" name="gradingMenu">';
7286: $Str .= '<input type="hidden" name="command" value="" />'.
7287: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
7288: '<input type="hidden" name="handgrade" value="'.$hdgrade.'" />'."\n".
7289: '<input type="hidden" name="probTitle" value="'.$probTitle.'" ue="" />'."\n".
7290: '<input type="hidden" name="saveState" value="" />'."\n".
7291: '<input type="hidden" name="gradingMenu" value="1" />'."\n".
7292: '<input type="hidden" name="showgrading" value="yes" />'."\n";
7293:
7294: foreach my $menudata (@menu) {
7295: if ($menudata->{'name'} ne &mt('Verify Receipt')) {
7296: $Str .=' <h3><a '.
7297: $menudata->{'jscript'}.
7298: ' href="'.
7299: $menudata->{'url'}.'" >'.
7300: $menudata->{'name'}."</a></h3>\n";
7301: } else {
7302: $Str .=' <h3><input type="button" value="Verify Receipt" '.
7303: $menudata->{'jscript'}.
7304: ' onClick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
7305: ' /></h3>';
7306: $Str .= (' 'x8).
7307: ' receipt: '.&Apache::lonnet::recprefix($env{'request.course.id'}).
7308: '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
7309: }
7310: $Str .= ' '.(' 'x8).$menudata->{'short_description'}.
7311: "\n";
7312: }
7313: $Str .="</dl>\n";
7314: $Str .="</form>\n";
7315: $request->print(<<GRADINGMENUJS);
7316: <script type="text/javascript" language="javascript">
7317: function checkChoice(formname,val,cmdx) {
7318: if (val <= 2) {
7319: var cmd = radioSelection(formname.radioChoice);
7320: var cmdsave = cmd;
7321: } else {
7322: cmd = cmdx;
7323: cmdsave = 'submission';
7324: }
7325: formname.command.value = cmd;
7326: if (val < 5) formname.submit();
7327: if (val == 5) {
7328: if (!checkReceiptNo(formname,'notOK')) {
7329: return false;
7330: } else {
7331: formname.submit();
7332: }
7333: }
7334: }
7335:
7336: function checkReceiptNo(formname,nospace) {
7337: var receiptNo = formname.receipt.value;
7338: var checkOpt = false;
7339: if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
7340: if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
7341: if (checkOpt) {
7342: alert("Please enter a receipt number given by a student in the receipt box.");
7343: formname.receipt.value = "";
7344: formname.receipt.focus();
7345: return false;
7346: }
7347: return true;
7348: }
7349: </script>
7350: GRADINGMENUJS
7351: &commonJSfunctions($request);
7352: return $Str;
7353: }
7354:
7355:
7356: #--- Displays the submissions first page -------
7357: sub submit_options {
7358: my ($request) = @_;
7359: my ($symb)=&get_symb($request);
7360: if (!$symb) {return '';}
7361: my $probTitle = &Apache::lonnet::gettitle($symb);
7362:
7363: $request->print(<<GRADINGMENUJS);
7364: <script type="text/javascript" language="javascript">
7365: function checkChoice(formname,val,cmdx) {
7366: if (val <= 2) {
7367: var cmd = radioSelection(formname.radioChoice);
7368: var cmdsave = cmd;
7369: } else {
7370: cmd = cmdx;
7371: cmdsave = 'submission';
7372: }
7373: formname.command.value = cmd;
7374: formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
7375: ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
7376: if (val < 5) formname.submit();
7377: if (val == 5) {
7378: if (!checkReceiptNo(formname,'notOK')) { return false;}
7379: formname.submit();
7380: }
7381: if (val < 7) formname.submit();
7382: }
7383:
7384: function checkReceiptNo(formname,nospace) {
7385: var receiptNo = formname.receipt.value;
7386: var checkOpt = false;
7387: if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
7388: if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
7389: if (checkOpt) {
7390: alert("Please enter a receipt number given by a student in the receipt box.");
7391: formname.receipt.value = "";
7392: formname.receipt.focus();
7393: return false;
7394: }
7395: return true;
7396: }
7397: </script>
7398: GRADINGMENUJS
7399: &commonJSfunctions($request);
7400: my $result='<h3> <span class="LC_info">Manual Grading/View Submission</span></h3>';
7401: my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
7402: $result.=$table;
7403: my (undef,$sections) = &getclasslist('all','0');
7404: my $savedState = &savedState();
7405: my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
7406: my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
7407: my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
7408: my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
7409:
7410: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
7411: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
7412: '<input type="hidden" name="handgrade" value="'.$hdgrade.'" />'."\n".
7413: '<input type="hidden" name="probTitle" value="'.$probTitle.'" />'."\n".
7414: '<input type="hidden" name="command" value="" />'."\n".
7415: '<input type="hidden" name="saveState" value="" />'."\n".
7416: '<input type="hidden" name="gradingMenu" value="1" />'."\n".
7417: '<input type="hidden" name="showgrading" value="yes" />'."\n";
7418:
7419: $result.='<table border="0"><tr><td bgcolor=#777777>'."\n".
7420: '<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n".
7421: ' <b>Select a Grading/Viewing Option</b></td></tr>'."\n".
7422: '<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
7423:
7424: $result.='<table width="100%" border="0">';
7425: $result.='<tr bgcolor="#ffffe6" valign="top">'."\n";
7426: $result.='<td><b>'.&mt('Sections').'</b></td>';
7427: $result.='<td><b>'.&mt('Groups').'</b></td>';
7428: $result.='<td><b>'.&mt('Access Status').'</td>'."\n";
7429: $result.='<td><b>'.&mt('Submission Status').'</td>'."\n";
7430: $result.='</tr>';
7431: $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
7432: ' <select name="section" multiple="multiple" size="3">'."\n";
7433: if (ref($sections)) {
7434: foreach (sort (@$sections)) {
7435: $result.='<option value="'.$_.'" '.
7436: ($saveSec eq $_ ? 'selected="selected"':'').'>'.$_.'</option>'."\n";
7437: }
7438: }
7439: $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> ';
7440: $result.= '</td><td>'."\n";
7441: $result.= &Apache::lonstatistics::GroupSelect('group','multiple',3);
7442: $result.='</td><td>'."\n";
7443: $result.=&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,3,undef,'mult');
7444:
7445: $result.='</td>';
7446: $result.='<td><select name="submitonly" size="3">'.
7447: '<option value="yes" '.
7448: ($saveSub eq 'yes' ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>'.
7449: '<option value="queued" '.
7450: ($saveSub eq 'queued' ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>'.
7451: '<option value="graded" '.
7452: ($saveSub eq 'graded' ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>'.
7453: '<option value="incorrect" '.
7454: ($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>'.
7455: '<option value="all" '.
7456: ($saveSub eq 'all' ? 'selected="selected"' : '').'>'.&mt('with any status').'</option></select></td></tr>';
7457:
7458: $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="3"><label>'.
7459: '<input type="radio" name="radioChoice" value="submission" '.
7460: ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.'<b>'.&mt('Current Resource').':</b> '.&mt('For one or more students').
7461: '</label> </td></tr>'."\n";
7462:
7463: $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="3">'.
7464: '<label><input type="radio" name="radioChoice" value="viewgrades" '.
7465: ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
7466: '<b>Current Resource:</b> For all students in selected section or course</label></td></tr>'."\n";
7467:
7468: $result.='<tr bgcolor="#ffffe6"><td colspan="3"><br />'.
7469: '<input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="Next->" />'.
7470: '</td></tr>'."\n";
7471:
7472:
7473: $result.='<tr bgcolor="#ffffe6" valign="top"><td colspan="3">'.
7474: '<br /><label><input type="radio" name="radioChoice" value="pickStudentPage" '.
7475: ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
7476: 'The <b>complete</b> set/page/sequence/folder: For one student</label></td></tr>'."\n";
7477:
7478: $result.='<tr bgcolor="#ffffe6"><td colspan="3"><br />'.
7479: '<input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="Next->" />'.
7480: '</td></tr></table>'."\n";
7481:
7482: $result.='</td>'; #<td valign="top">';
7483:
7484: # $result.='<table width="100%" border="0">';
7485: # $result.='<tr bgcolor="#ffffe6"><td>'.
7486: # '<input type="button" onClick="javascript:checkChoice(this.form,\'3\',\'csvform\');" value="'.&mt('Upload').'" />'.
7487: # ' '.&mt('scores from file').' </td></tr>'."\n";
7488: #
7489: # $result.='<tr bgcolor="#ffffe6"><td>'.
7490: # '<input type="button" onClick="javascript:checkChoice(this.form,\'6\',\'processclicker\');" value="'.&mt('Process').'" />'.
7491: # ' '.&mt('clicker file').' </td></tr>'."\n";
7492: #
7493: # $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
7494: # '<input type="button" onClick="javascript:checkChoice(this.form,\'4\',\'scantron_selectphase\');'.
7495: # '" value="'.&mt('Grade').'" /> scantron forms</td></tr>'."\n";
7496: #
7497: # if ((&Apache::lonnet::allowed('mgr',$env{'request.course.id'})) && ($symb)) {
7498: # $result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
7499: # '<input type="button" onClick="javascript:checkChoice(this.form,\'5\',\'verify\');" value="'.&mt('Verify').'" />'.
7500: # ' '.&mt('receipt').': '.
7501: # &Apache::lonnet::recprefix($env{'request.course.id'}).
7502: # '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />'.
7503: # '</td></tr>'."\n";
7504: # }
7505: # $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
7506: # '<input type="button" onClick="javascript:this.form.action=\'/adm/helper/resettimes.helper\';this.form.submit();'.
7507: # '" value="'.&mt('Manage').'" /> access times.</td></tr>'."\n";
7508: # $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
7509: # '<input type="button" onClick="javascript:this.form.command.value=\'codelist\';this.form.action=\'/adm/pickcode\';this.form.submit();'.
7510: # '" value="'.&mt('View').'" /> saved CODEs.</td></tr>'."\n";
7511: #
7512: # $result.='</table>'."\n".'</td>';
7513: $result.= '</tr></table>'."\n".
7514: '</td></tr></table></form>'."\n";
7515: return $result;
7516: }
7517:
7518: sub reset_perm {
7519: undef(%perm);
7520: }
7521:
7522: sub init_perm {
7523: &reset_perm();
7524: foreach my $test_perm ('vgr','mgr','opa') {
7525:
7526: my $scope = $env{'request.course.id'};
7527: if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
7528:
7529: $scope .= '/'.$env{'request.course.sec'};
7530: if ( $perm{$test_perm}=
7531: &Apache::lonnet::allowed($test_perm,$scope)) {
7532: $perm{$test_perm.'_section'}=$env{'request.course.sec'};
7533: } else {
7534: delete($perm{$test_perm});
7535: }
7536: }
7537: }
7538: }
7539:
7540: sub gather_clicker_ids {
7541: my %clicker_ids;
7542:
7543: my $classlist = &Apache::loncoursedata::get_classlist();
7544:
7545: # Set up a couple variables.
7546: my $username_idx = &Apache::loncoursedata::CL_SNAME();
7547: my $domain_idx = &Apache::loncoursedata::CL_SDOM();
7548: my $status_idx = &Apache::loncoursedata::CL_STATUS();
7549:
7550: foreach my $student (keys(%$classlist)) {
7551: if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
7552: my $username = $classlist->{$student}->[$username_idx];
7553: my $domain = $classlist->{$student}->[$domain_idx];
7554: my $clickers =
7555: (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
7556: foreach my $id (split(/\,/,$clickers)) {
7557: $id=~s/^[\#0]+//;
7558: $id=~s/[\-\:]//g;
7559: if (exists($clicker_ids{$id})) {
7560: $clicker_ids{$id}.=','.$username.':'.$domain;
7561: } else {
7562: $clicker_ids{$id}=$username.':'.$domain;
7563: }
7564: }
7565: }
7566: return %clicker_ids;
7567: }
7568:
7569: sub gather_adv_clicker_ids {
7570: my %clicker_ids;
7571: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
7572: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7573: my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
7574: foreach my $element (sort(keys(%coursepersonnel))) {
7575: foreach my $person (split(/\,/,$coursepersonnel{$element})) {
7576: my ($puname,$pudom)=split(/\:/,$person);
7577: my $clickers =
7578: (&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
7579: foreach my $id (split(/\,/,$clickers)) {
7580: $id=~s/^[\#0]+//;
7581: $id=~s/[\-\:]//g;
7582: if (exists($clicker_ids{$id})) {
7583: $clicker_ids{$id}.=','.$puname.':'.$pudom;
7584: } else {
7585: $clicker_ids{$id}=$puname.':'.$pudom;
7586: }
7587: }
7588: }
7589: }
7590: return %clicker_ids;
7591: }
7592:
7593: sub clicker_grading_parameters {
7594: return ('gradingmechanism' => 'scalar',
7595: 'upfiletype' => 'scalar',
7596: 'specificid' => 'scalar',
7597: 'pcorrect' => 'scalar',
7598: 'pincorrect' => 'scalar');
7599: }
7600:
7601: sub process_clicker {
7602: my ($r)=@_;
7603: my ($symb)=&get_symb($r);
7604: if (!$symb) {return '';}
7605: my $result=&checkforfile_js();
7606: $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
7607: my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
7608: $result.=$table;
7609: $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
7610: $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
7611: $result.=' <b>'.&mt('Specify a file containing the clicker information for this resource').
7612: '.</b></td></tr>'."\n";
7613: $result.='<tr bgcolor=#ffffe6><td>'."\n";
7614: # Attempt to restore parameters from last session, set defaults if not present
7615: my %Saveable_Parameters=&clicker_grading_parameters();
7616: &Apache::loncommon::restore_course_settings('grades_clicker',
7617: \%Saveable_Parameters);
7618: if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
7619: if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
7620: if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
7621: if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
7622:
7623: my %checked;
7624: foreach my $gradingmechanism ('attendance','personnel','specific') {
7625: if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
7626: $checked{$gradingmechanism}="checked='checked'";
7627: }
7628: }
7629:
7630: my $upload=&mt("Upload File");
7631: my $type=&mt("Type");
7632: my $attendance=&mt("Award points just for participation");
7633: my $personnel=&mt("Correctness determined from response by course personnel");
7634: my $specific=&mt("Correctness determined from response with clicker ID(s)");
7635: my $pcorrect=&mt("Percentage points for correct solution");
7636: my $pincorrect=&mt("Percentage points for incorrect solution");
7637: my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
7638: ('iclicker' => 'i>clicker',
7639: 'interwrite' => 'interwrite PRS'));
7640: $symb = &Apache::lonenc::check_encrypt($symb);
7641: $result.=<<ENDUPFORM;
7642: <script type="text/javascript">
7643: function sanitycheck() {
7644: // Accept only integer percentages
7645: document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
7646: document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
7647: // Find out grading choice
7648: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
7649: if (document.forms.gradesupload.gradingmechanism[i].checked) {
7650: gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
7651: }
7652: }
7653: // By default, new choice equals user selection
7654: newgradingchoice=gradingchoice;
7655: // Not good to give more points for false answers than correct ones
7656: if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
7657: document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
7658: }
7659: // If new choice is attendance only, and old choice was correctness-based, restore defaults
7660: if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
7661: document.forms.gradesupload.pcorrect.value=100;
7662: document.forms.gradesupload.pincorrect.value=100;
7663: }
7664: // If the values are different, cannot be attendance only
7665: if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
7666: (gradingchoice=='attendance')) {
7667: newgradingchoice='personnel';
7668: }
7669: // Change grading choice to new one
7670: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
7671: if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
7672: document.forms.gradesupload.gradingmechanism[i].checked=true;
7673: } else {
7674: document.forms.gradesupload.gradingmechanism[i].checked=false;
7675: }
7676: }
7677: // Remember the old state
7678: document.forms.gradesupload.waschecked.value=newgradingchoice;
7679: }
7680: </script>
7681: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
7682: <input type="hidden" name="symb" value="$symb" />
7683: <input type="hidden" name="command" value="processclickerfile" />
7684: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
7685: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
7686: <input type="file" name="upfile" size="50" />
7687: <br /><label>$type: $selectform</label>
7688: <br /><label><input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
7689: <br /><label><input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
7690: <br /><label><input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" />$specific </label>
7691: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
7692: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
7693: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
7694: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
7695: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
7696: </form>
7697: ENDUPFORM
7698: $result.='</td></tr></table>'."\n".
7699: '</td></tr></table><br /><br />'."\n";
7700: $result.=&show_grading_menu_form($symb);
7701: return $result;
7702: }
7703:
7704: sub process_clicker_file {
7705: my ($r)=@_;
7706: my ($symb)=&get_symb($r);
7707: if (!$symb) {return '';}
7708:
7709: my %Saveable_Parameters=&clicker_grading_parameters();
7710: &Apache::loncommon::store_course_settings('grades_clicker',
7711: \%Saveable_Parameters);
7712:
7713: my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
7714: if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
7715: $result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
7716: return $result.&show_grading_menu_form($symb);
7717: }
7718: my %clicker_ids=&gather_clicker_ids();
7719: my %correct_ids;
7720: if ($env{'form.gradingmechanism'} eq 'personnel') {
7721: %correct_ids=&gather_adv_clicker_ids();
7722: }
7723: if ($env{'form.gradingmechanism'} eq 'specific') {
7724: foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
7725: $correct_id=~tr/a-z/A-Z/;
7726: $correct_id=~s/\s//gs;
7727: $correct_id=~s/^[\#0]+//;
7728: $correct_id=~s/[\-\:]//g;
7729: if ($correct_id) {
7730: $correct_ids{$correct_id}='specified';
7731: }
7732: }
7733: }
7734: if ($env{'form.gradingmechanism'} eq 'attendance') {
7735: $result.=&mt('Score based on attendance only');
7736: } else {
7737: my $number=0;
7738: $result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
7739: foreach my $id (sort(keys(%correct_ids))) {
7740: $result.='<br /><tt>'.$id.'</tt> - ';
7741: if ($correct_ids{$id} eq 'specified') {
7742: $result.=&mt('specified');
7743: } else {
7744: my ($uname,$udom)=split(/\:/,$correct_ids{$id});
7745: $result.=&Apache::loncommon::plainname($uname,$udom);
7746: }
7747: $number++;
7748: }
7749: $result.="</p>\n";
7750: if ($number==0) {
7751: $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
7752: return $result.&show_grading_menu_form($symb);
7753: }
7754: }
7755: if (length($env{'form.upfile'}) < 2) {
7756: $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
7757: '<span class="LC_error">',
7758: '</span>',
7759: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
7760: return $result.&show_grading_menu_form($symb);
7761: }
7762:
7763: # Were able to get all the info needed, now analyze the file
7764:
7765: $result.=&Apache::loncommon::studentbrowser_javascript();
7766: $symb = &Apache::lonenc::check_encrypt($symb);
7767: my $heading=&mt('Scanning clicker file');
7768: $result.=(<<ENDHEADER);
7769: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
7770: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
7771: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
7772: <form method="post" action="/adm/grades" name="clickeranalysis">
7773: <input type="hidden" name="symb" value="$symb" />
7774: <input type="hidden" name="command" value="assignclickergrades" />
7775: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
7776: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
7777: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
7778: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
7779: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
7780: ENDHEADER
7781: my %responses;
7782: my @questiontitles;
7783: my $errormsg='';
7784: my $number=0;
7785: if ($env{'form.upfiletype'} eq 'iclicker') {
7786: ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
7787: }
7788: if ($env{'form.upfiletype'} eq 'interwrite') {
7789: ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
7790: }
7791: $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
7792: '<input type="hidden" name="number" value="'.$number.'" />'.
7793: &mt('Awarding [_1] percent for corrion(s)',$number).'<br />'.
7794: '<input type="hidden" name="number" value="'.$number.'" />'.
7795: &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
7796: $env{'form.pcorrect'},$env{'form.pincorrect'}).
7797: '<br />';
7798: # Remember Question Titles
7799: # FIXME: Possibly need delimiter other than ":"
7800: for (my $i=0;$i<$number;$i++) {
7801: $result.='<input type="hidden" name="question:'.$i.'" value="'.
7802: &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
7803: }
7804: my $correct_count=0;
7805: my $student_count=0;
7806: my $unknown_count=0;
7807: # Match answers with usernames
7808: # FIXME: Possibly need delimiter other than ":"
7809: foreach my $id (keys(%responses)) {
7810: if ($correct_ids{$id}) {
7811: $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
7812: $correct_count++;
7813: } elsif ($clicker_ids{$id}) {
7814: if ($clicker_ids{$id}=~/\,/) {
7815: # More than one user with the same clicker!
7816: $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
7817: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
7818: "<select name='multi".$id."'>";
7819: foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
7820: $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
7821: }
7822: $result.='</select>';
7823: $unknown_count++;
7824: } else {
7825: # Good: found one and only one user with the right clicker
7826: $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
7827: $student_count++;
7828: }
7829: } else {
7830: $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
7831: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
7832: "\n".&mt("Username").": <input type='text' name='uname".$id."' /> ".
7833: "\n".&mt("Domain").": ".
7834: &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).' '.
7835: &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
7836: $unknown_count++;
7837: }
7838: }
7839: $result.='<hr />'.
7840: &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
7841: if ($env{'form.gradingmechanism'} ne 'attendance') {
7842: if ($correct_count==0) {
7843: $errormsg.="Found no correct answers answers for grading!";
7844: } elsif ($correct_count>1) {
7845: $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
7846: }
7847: }
7848: if ($number<1) {
7849: $errormsg.="Found no questions.";
7850: }
7851: if ($errormsg) {
7852: $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
7853: } else {
7854: $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
7855: }
7856: $result.='</form></td></tr></table>'."\n".
7857: '</td></tr></table><br /><br />'."\n";
7858: return $result.&show_grading_menu_form($symb);
7859: }
7860:
7861: sub iclicker_eval {
7862: my ($questiontitles,$responses)=@_;
7863: my $number=0;
7864: my $errormsg='';
7865: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
7866: my %components=&Apache::loncommon::record_sep($line);
7867: my @entries=map {$components{$_}} (sort(keys(%components)));
7868: if ($entries[0] eq 'Question') {
7869: for (my $i=3;$i<$#entries;$i+=6) {
7870: $$questiontitles[$number]=$entries[$i];
7871: $number++;
7872: }
7873: }
7874: if ($entries[0]=~/^\#/) {
7875: my $id=$entries[0];
7876: my @idresponses;
7877: $id=~s/^[\#0]+//;
7878: for (my $i=0;$i<$number;$i++) {
7879: my $idx=3+$i*6;
7880: push(@idresponses,$entries[$idx]);
7881: }
7882: $$responses{$id}=join(',',@idresponses);
7883: }
7884: }
7885: return ($errormsg,$number);
7886: }
7887:
7888: sub interwrite_eval {
7889: my ($questiontitles,$responses)=@_;
7890: my $number=0;
7891: my $errormsg='';
7892: my $skipline=1;
7893: my $questionnumber=0;
7894: my %idresponses=();
7895: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
7896: my %components=&Apache::loncommon::record_sep($line);
7897: my @entries=map {$components{$_}} (sort(keys(%components)));
7898: if ($entries[1] eq 'Time') { $skipline=0; next; }
7899: if ($entries[1] eq 'Response') { $skipline=1; }
7900: next if $skipline;
7901: if ($entries[0]!=$questionnumber) {
7902: $questionnumber=$entries[0];
7903: $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
7904: $number++;
7905: }
7906: my $id=$entries[4];
7907: $id=~s/^[\#0]+//;
7908: $id=~s/^v\d*\://i;
7909: $id=~s/[\-\:]//g;
7910: $idresponses{$id}[$number]=$entries[6];
7911: }
7912: foreach my $id (keys %idresponses) {
7913: $$responses{$id}=join(',',@{$idresponses{$id}});
7914: $$responses{$id}=~s/^\s*\,//;
7915: }
7916: return ($errormsg,$number);
7917: }
7918:
7919: sub assign_clicker_grades {
7920: my ($r)=@_;
7921: my ($symb)=&get_symb($r);
7922: if (!$symb) {return '';}
7923: # See which part we are saving to
7924: my ($partlist,$handgrade,$responseType) = &response_type($symb);
7925: # FIXME: This should probably look for the first handgradeable part
7926: my $part=$$partlist[0];
7927: # Start screen output
7928: my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
7929:
7930: my $heading=&mt('Assigning grades based on clicker file');
7931: $result.=(<<ENDHEADER);
7932: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
7933: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
7934: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
7935: ENDHEADER
7936: # Get correct result
7937: # FIXME: Possibly need delimiter other than ":"
7938: my @correct=();
7939: my $gradingmechanism=$env{'form.gradingmechanism'};
7940: my $number=$env{'form.number'};
7941: if ($gradingmechanism ne 'attendance') {
7942: foreach my $key (keys(%env)) {
7943: if ($key=~/^form\.correct\:/) {
7944: my @input=split(/\,/,$env{$key});
7945: for (my $i=0;$i<=$#input;$i++) {
7946: if (($correct[$i]) && ($input[$i]) &&
7947: ($correct[$i] ne $input[$i])) {
7948: $result.='<br /><span class="LC_warning">'.
7949: &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
7950: $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
7951: } elsif ($input[$i]) {
7952: $correct[$i]=$input[$i];
7953: }
7954: }
7955: }
7956: }
7957: for (my $i=0;$i<$number;$i++) {
7958: if (!$correct[$i]) {
7959: $result.='<br /><span class="LC_error">'.
7960: &mt('No correct result given for question "[_1]"!',
7961: $env{'form.question:'.$i}).'</span>';
7962: }
7963: }
7964: $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
7965: }
7966: # Start grading
7967: my $pcorrect=$env{'form.pcorrect'};
7968: my $pincorrect=$env{'form.pincorrect'};
7969: my $storecount=0;
7970: foreach my $key (keys(%env)) {
7971: my $user='';
7972: if ($key=~/^form\.student\:(.*)$/) {
7973: $user=$1;
7974: }
7975: if ($key=~/^form\.unknown\:(.*)$/) {
7976: my $id=$1;
7977: if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
7978: $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
7979: } elsif ($env{'form.multi'.$id}) {
7980: $user=$env{'form.multi'.$id};
7981: }
7982: }
7983: if ($user) {
7984: my @answer=split(/\,/,$env{$key});
7985: my $sum=0;
7986: for (my $i=0;$i<$number;$i++) {
7987: if ($answer[$i]) {
7988: if ($gradingmechanism eq 'attendance') {
7989: $sum+=$pcorrect;
7990: } else {
7991: if ($answer[$i] eq $correct[$i]) {
7992: $sum+=$pcorrect;
7993: } else {
7994: $sum+=$pincorrect;
7995: }
7996: }
7997: }
7998: }
7999: my $ave=$sum/(100*$number);
8000: # Store
8001: my ($username,$domain)=split(/\:/,$user);
8002: my %grades=();
8003: $grades{"resource.$part.solved"}='correct_by_override';
8004: $grades{"resource.$part.awarded"}=$ave;
8005: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
8006: my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
8007: $env{'request.course.id'},
8008: $domain,$username);
8009: if ($returncode ne 'ok') {
8010: $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
8011: } else {
8012: $storecount++;
8013: }
8014: }
8015: }
8016: # We are done
8017: $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
8018: '</td></tr></table>'."\n".
8019: '</td></tr></table><br /><br />'."\n";
8020: return $result.&show_grading_menu_form($symb);
8021: }
8022:
8023: sub handler {
8024: my $request=$_[0];
8025: &reset_caches();
8026: if ($env{'browser.mathml'}) {
8027: &Apache::loncommon::content_type($request,'text/xml');
8028: } else {
8029: &Apache::loncommon::content_type($request,'text/html');
8030: }
8031: $request->send_http_header;
8032: return '' if $request->header_only;
8033: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
8034: my $symb=&get_symb($request,1);
8035: my @commands=&Apache::loncommon::get_env_multiple('form.command');
8036: my $command=$commands[0];
8037:
8038: if ($#commands > 0) {
8039: &Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
8040: }
8041:
8042:
8043: $request->print(&Apache::loncommon::start_page('Grading'));
8044: if ($symb eq '' && $command eq '') {
8045: if ($env{'user.adv'}) {
8046: if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
8047: ($env{'form.codethree'})) {
8048: my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
8049: $env{'form.codethree'};
8050: my ($tsymb,$tuname,$tudom,$tcrsid)=
8051: &Apache::lonnet::checkin($token);
8052: if ($tsymb) {
8053: my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
8054: if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
8055: $request->print(&Apache::lonnet::ssi_body('/res/'.$url,
8056: ('grade_username' => $tuname,
8057: 'grade_domain' => $tudom,
8058: 'grade_courseid' => $tcrsid,
8059: 'grade_symb' => $tsymb)));
8060: } else {
8061: $request->print('<h3>Not authorized: '.$token.'</h3>');
8062: }
8063: } else {
8064: $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
8065: }
8066: } else {
8067: $request->print(&Apache::lonxml::tokeninputfield());
8068: }
8069: }
8070: } else {
8071: &init_perm();
8072: if ($command eq 'submission' && $perm{'vgr'}) {
8073: ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
8074: } elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
8075: &pickStudentPage($request);
8076: } elsif ($command eq 'displayPage' && $perm{'vgr'}) {
8077: &displayPage($request);
8078: } elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
8079: &updateGradeByPage($request);
8080: } elsif ($command eq 'processGroup' && $perm{'vgr'}) {
8081: &processGroup($request);
8082: } elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
8083: $request->print(&grading_menu($request));
8084: } elsif ($command eq 'submit_options' && $perm{'vgr'}) {
8085: $request->print(&submit_options($request));
8086: } elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
8087: $request->print(&viewgrades($request));
8088: } elsif ($command eq 'handgrade' && $perm{'mgr'}) {
8089: $request->print(&processHandGrade($request));
8090: } elsif ($command eq 'editgrades' && $perm{'mgr'}) {
8091: $request->print(&editgrades($request));
8092: } elsif ($command eq 'verify' && $perm{'vgr'}) {
8093: $request->print(&verifyreceipt($request));
8094: } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
8095: $request->print(&process_clicker($request));
8096: } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
8097: $request->print(&process_clicker_file($request));
8098: } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
8099: $request->print(&assign_clicker_grades($request));
8100: } elsif ($command eq 'csvform' && $perm{'mgr'}) {
8101: $request->print(&upcsvScores_form($request));
8102: } elsif ($command eq 'csvupload' && $perm{'mgr'}) {
8103: $request->print(&csvupload($request));
8104: } elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
8105: $request->print(&csvuploadmap($request));
8106: } elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
8107: if ($env{'form.associate'} ne 'Reverse Association') {
8108: $request->print(&csvuploadoptions($request));
8109: } else {
8110: if ( $env{'form.upfile_associate'} ne 'reverse' ) {
8111: $env{'form.upfile_associate'} = 'reverse';
8112: } else {
8113: $env{'form.upfile_associate'} = 'forward';
8114: }
8115: $request->print(&csvuploadmap($request));
8116: }
8117: } elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
8118: $request->print(&csvuploadassign($request));
8119: } elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
8120: $request->print(&scantron_selectphase($request));
8121: } elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
8122: $request->print(&scantron_do_warning($request));
8123: } elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
8124: $request->print(&scantron_validate_file($request));
8125: } elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
8126: $request->print(&scantron_process_students($request));
8127: } elsif ($command eq 'scantronupload' &&
8128: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
8129: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
8130: $request->print(&scantron_upload_scantron_data($request));
8131: } elsif ($command eq 'scantronupload_save' &&
8132: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
8133: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
8134: $request->print(&scantron_upload_scantron_data_save($request));
8135: } elsif ($command eq 'scantron_download' &&
8136: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
8137: $request->print(&scantron_download_scantron_data($request));
8138: } elsif ($command) {
8139: $request->print("Access Denied ($command)");
8140: }
8141: }
8142: $request->print(&Apache::loncommon::end_page());
8143: &reset_caches();
8144: return '';
8145: }
8146:
8147: 1;
8148:
8149: __END__;
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>