1: # The LearningOnline Network with CAPA
2: # The LON-CAPA Grading handler
3: #
4: # $Id: grades.pm,v 1.433 2007/08/22 18:27:03 banghart Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28:
29: package Apache::grades;
30: use strict;
31: use Apache::style;
32: use Apache::lonxml;
33: use Apache::lonnet;
34: use Apache::loncommon;
35: use Apache::lonhtmlcommon;
36: use Apache::lonnavmaps;
37: use Apache::lonhomework;
38: use Apache::loncoursedata;
39: use Apache::lonmsg();
40: use Apache::Constants qw(:common);
41: use Apache::lonlocal;
42: use Apache::lonenc;
43: use String::Similarity;
44: use LONCAPA;
45:
46: use POSIX qw(floor);
47:
48: my %perm=();
49:
50: # ----- These first few routines are general use routines.----
51: #
52: # --- Retrieve the parts from the metadata file.---
53: sub getpartlist {
54: my ($symb) = @_;
55: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
56: my $partorder = &Apache::lonnet::metadata($url, 'partorder');
57: my @parts;
58: if ($partorder) {
59: for my $part (split (/,/,$partorder)) {
60: if (!&Apache::loncommon::check_if_partid_hidden($part,$symb)) {
61: push(@parts, $part);
62: }
63: }
64: } else {
65: my $metadata = &Apache::lonnet::metadata($url, 'packages');
66: foreach (split(/\,/,$metadata)) {
67: if ($_ =~ /^part_(.*)$/) {
68: if (!&Apache::loncommon::check_if_partid_hidden($1,$symb)) {
69: push(@parts, $1);
70: }
71: }
72: }
73: }
74: my @stores;
75: foreach my $part (@parts) {
76: my (@metakeys) = split(/,/,&Apache::lonnet::metadata($url,'keys'));
77: foreach my $key (@metakeys) {
78: if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
79: }
80: }
81: return @stores;
82: }
83:
84: # --- Get the symbolic name of a problem and the url
85: sub get_symb {
86: my ($request,$silent) = @_;
87: (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
88: my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
89: if ($symb eq '') {
90: if (!$silent) {
91: $request->print("Unable to handle ambiguous references:$url:.");
92: return ();
93: }
94: }
95: &Apache::lonenc::check_decrypt(\$symb);
96: return ($symb);
97: }
98:
99: #--- Format fullname, username:domain if different for display
100: #--- Use anywhere where the student names are listed
101: sub nameUserString {
102: my ($type,$fullname,$uname,$udom) = @_;
103: if ($type eq 'header') {
104: return '<b> Fullname </b><span class="LC_internal_info">(Username)</span>';
105: } else {
106: return ' '.$fullname.'<span class="LC_internal_info"> ('.$uname.
107: ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
108: }
109: }
110:
111: #--- Get the partlist and the response type for a given problem. ---
112: #--- Indicate if a response type is coded handgraded or not. ---
113: sub response_type {
114: my ($symb) = shift;
115:
116: my $navmap = Apache::lonnavmaps::navmap->new();
117: my $res = $navmap->getBySymb($symb);
118: my $partlist = $res->parts();
119: my %vPart =
120: map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
121: my (%response_types,%handgrade);
122: foreach my $part (@{ $partlist }) {
123: next if (%vPart && !exists($vPart{$part}));
124:
125: my @types = $res->responseType($part);
126: my @ids = $res->responseIds($part);
127: for (my $i=0; $i < scalar(@ids); $i++) {
128: $response_types{$part}{$ids[$i]} = $types[$i];
129: $handgrade{$part.'_'.$ids[$i]} =
130: &Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
131: '.handgrade',$symb);
132: }
133: }
134: return ($partlist,\%handgrade,\%response_types);
135: }
136:
137: sub flatten_responseType {
138: my ($responseType) = @_;
139: my @part_response_id =
140: map {
141: my $part = $_;
142: map {
143: [$part,$_]
144: } sort(keys(%{ $responseType->{$part} }));
145: } sort(keys(%$responseType));
146: return @part_response_id;
147: }
148:
149: sub get_display_part {
150: my ($partID,$symb)=@_;
151: my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
152: if (defined($display) and $display ne '') {
153: $display.= " (<span class=\"LC_internal_info\">id $partID</span>)";
154: } else {
155: $display=$partID;
156: }
157: return $display;
158: }
159:
160: #--- Show resource title
161: #--- and parts and response type
162: sub showResourceInfo {
163: my ($symb,$probTitle,$checkboxes) = @_;
164: my $col=3;
165: if ($checkboxes) { $col=4; }
166: my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
167: $result .='<table border="0">';
168: my ($partlist,$handgrade,$responseType) = &response_type($symb);
169: my %resptype = ();
170: my $hdgrade='no';
171: my %partsseen;
172: foreach my $partID (sort keys(%$responseType)) {
173: foreach my $resID (sort keys(%{ $responseType->{$partID} })) {
174: my $handgrade=$$handgrade{$partID.'_'.$resID};
175: my $responsetype = $responseType->{$partID}->{$resID};
176: $hdgrade = $handgrade if ($handgrade eq 'yes');
177: $result.='<tr>';
178: if ($checkboxes) {
179: if (exists($partsseen{$partID})) {
180: $result.="<td> </td>";
181: } else {
182: $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
183: }
184: $partsseen{$partID}=1;
185: }
186: my $display_part=&get_display_part($partID,$symb);
187: $result.='<td><b>Part: </b>'.$display_part.' <span class="LC_internal_info">'.
188: $resID.'</span></td>'.
189: '<td><b>Type: </b>'.$responsetype.'</td></tr>';
190: # '<td><b>Handgrade: </b>'.$handgrade.'</td></tr>';
191: }
192: }
193: $result.='</table>'."\n";
194: return $result,$responseType,$hdgrade,$partlist,$handgrade;
195: }
196:
197:
198: sub get_order {
199: my ($partid,$respid,$symb,$uname,$udom)=@_;
200: my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
201: $url=&Apache::lonnet::clutter($url);
202: my $subresult=&Apache::lonnet::ssi($url,
203: ('grade_target' => 'analyze'),
204: ('grade_domain' => $udom),
205: ('grade_symb' => $symb),
206: ('grade_courseid' =>
207: $env{'request.course.id'}),
208: ('grade_username' => $uname));
209: (undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
210: my %analyze=&Apache::lonnet::str2hash($subresult);
211: return ($analyze{"$partid.$respid.shown"});
212: }
213: #--- Clean response type for display
214: #--- Currently filters option/rank/radiobutton/match/essay/Task
215: # response types only.
216: sub cleanRecord {
217: my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
218: $uname,$udom) = @_;
219: my $grayFont = '<span class="LC_internal_info">';
220: if ($response =~ /^(option|rank)$/) {
221: my %answer=&Apache::lonnet::str2hash($answer);
222: my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
223: my ($toprow,$bottomrow);
224: foreach my $foil (@$order) {
225: if ($grading{$foil} == 1) {
226: $toprow.='<td><b>'.$answer{$foil}.' </b></td>';
227: } else {
228: $toprow.='<td><i>'.$answer{$foil}.' </i></td>';
229: }
230: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
231: }
232: return '<blockquote><table border="1">'.
233: '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
234: '<tr valign="top"><td>'.$grayFont.'Option ID</span></td>'.
235: $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
236: } elsif ($response eq 'match') {
237: my %answer=&Apache::lonnet::str2hash($answer);
238: my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
239: my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
240: my ($toprow,$middlerow,$bottomrow);
241: foreach my $foil (@$order) {
242: my $item=shift(@items);
243: if ($grading{$foil} == 1) {
244: $toprow.='<td><b>'.$item.' </b></td>';
245: $middlerow.='<td><b>'.$grayFont.$answer{$foil}.' </span></b></td>';
246: } else {
247: $toprow.='<td><i>'.$item.' </i></td>';
248: $middlerow.='<td><i>'.$grayFont.$answer{$foil}.' </span></i></td>';
249: }
250: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
251: }
252: return '<blockquote><table border="1">'.
253: '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
254: '<tr valign="top"><td>'.$grayFont.'Item ID</span></td>'.
255: $middlerow.'</tr>'.
256: '<tr valign="top"><td>'.$grayFont.'Option ID</span></td>'.
257: $bottomrow.'</tr>'.'</table></blockquote>';
258: } elsif ($response eq 'radiobutton') {
259: my %answer=&Apache::lonnet::str2hash($answer);
260: my ($toprow,$bottomrow);
261: my $correct=($order->[0])+1;
262: for (my $i=1;$i<=$#$order;$i++) {
263: my $foil=$order->[$i];
264: if (exists($answer{$foil})) {
265: if ($i == $correct) {
266: $toprow.='<td><b>true</b></td>';
267: } else {
268: $toprow.='<td><i>true</i></td>';
269: }
270: } else {
271: $toprow.='<td>false</td>';
272: }
273: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
274: }
275: return '<blockquote><table border="1">'.
276: '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
277: '<tr valign="top"><td>'.$grayFont.'Option ID</span></td>'.
278: $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
279: } elsif ($response eq 'essay') {
280: if (! exists ($env{'form.'.$symb})) {
281: my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
282: $env{'course.'.$env{'request.course.id'}.'.domain'},
283: $env{'course.'.$env{'request.course.id'}.'.num'});
284:
285: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
286: $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
287: $env{'form.kwclr'} = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
288: $env{'form.kwsize'} = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
289: $env{'form.kwstyle'} = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
290: $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
291: }
292: $answer =~ s-\n-<br />-g;
293: return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
294: } elsif ( $response eq 'organic') {
295: my $result='Smile representation: "<tt>'.$answer.'</tt>"';
296: my $jme=$record->{$version."resource.$partid.$respid.molecule"};
297: $result.=&Apache::chemresponse::jme_img($jme,$answer,400);
298: return $result;
299: } elsif ( $response eq 'Task') {
300: if ( $answer eq 'SUBMITTED') {
301: my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
302: my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
303: return $result;
304: } elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
305: my @matches = grep(/^\Q$version\E.*?\.instance$/,
306: keys(%{$record}));
307: return join('<br />',($version,@matches));
308:
309:
310: } else {
311: my $result =
312: '<p>'
313: .&mt('Overall result: [_1]',
314: $record->{$version."resource.$respid.$partid.status"})
315: .'</p>';
316:
317: $result .= '<ul>';
318: my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
319: keys(%{$record}));
320: foreach my $grade (sort(@grade)) {
321: my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
322: $result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
323: $dim, $record->{$grade}).
324: '</li>';
325: }
326: $result.='</ul>';
327: return $result;
328: }
329:
330: }
331: return $answer;
332: }
333:
334: #-- A couple of common js functions
335: sub commonJSfunctions {
336: my $request = shift;
337: $request->print(<<COMMONJSFUNCTIONS);
338: <script type="text/javascript" language="javascript">
339: function radioSelection(radioButton) {
340: var selection=null;
341: if (radioButton.length > 1) {
342: for (var i=0; i<radioButton.length; i++) {
343: if (radioButton[i].checked) {
344: return radioButton[i].value;
345: }
346: }
347: } else {
348: if (radioButton.checked) return radioButton.value;
349: }
350: return selection;
351: }
352:
353: function pullDownSelection(selectOne) {
354: var selection="";
355: if (selectOne.length > 1) {
356: for (var i=0; i<selectOne.length; i++) {
357: if (selectOne[i].selected) {
358: return selectOne[i].value;
359: }
360: }
361: } else {
362: // only one value it must be the selected one
363: return selectOne.value;
364: }
365: }
366: </script>
367: COMMONJSFUNCTIONS
368: }
369:
370: #--- Dumps the class list with usernames,list of sections,
371: #--- section, ids and fullnames for each user.
372: sub getclasslist {
373: my ($getsec,$filterlist) = @_;
374: my @getsec;
375: if (!ref($getsec)) {
376: if ($getsec ne '' && $getsec ne 'all') {
377: @getsec=($getsec);
378: }
379: } else {
380: @getsec=@{$getsec};
381: }
382: if (grep(/^all$/,@getsec)) { undef(@getsec); }
383:
384: my $classlist=&Apache::loncoursedata::get_classlist();
385: # Bail out if we were unable to get the classlist
386: return if (! defined($classlist));
387: #
388: my %sections;
389: my %fullnames;
390: foreach my $student (keys(%$classlist)) {
391: my $end =
392: $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
393: my $start =
394: $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
395: my $id =
396: $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
397: my $section =
398: $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
399: my $fullname =
400: $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
401: my $status =
402: $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
403: # filter students according to status selected
404: if ($filterlist && $env{'form.Status'} ne 'Any') {
405: if ($env{'form.Status'} ne $status) {
406: delete ($classlist->{$student});
407: next;
408: }
409: }
410: $section = ($section ne '' ? $section : 'none');
411: if (&canview($section)) {
412: if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
413: $sections{$section}++;
414: $fullnames{$student}=$fullname;
415: } else {
416: delete($classlist->{$student});
417: }
418: } else {
419: delete($classlist->{$student});
420: }
421: }
422: my %seen = ();
423: my @sections = sort(keys(%sections));
424: return ($classlist,\@sections,\%fullnames);
425: }
426:
427: sub canmodify {
428: my ($sec)=@_;
429: if ($perm{'mgr'}) {
430: if (!defined($perm{'mgr_section'})) {
431: # can modify whole class
432: return 1;
433: } else {
434: if ($sec eq $perm{'mgr_section'}) {
435: #can modify the requested section
436: return 1;
437: } else {
438: # can't modify the request section
439: return 0;
440: }
441: }
442: }
443: #can't modify
444: return 0;
445: }
446:
447: sub canview {
448: my ($sec)=@_;
449: if ($perm{'vgr'}) {
450: if (!defined($perm{'vgr_section'})) {
451: # can modify whole class
452: return 1;
453: } else {
454: if ($sec eq $perm{'vgr_section'}) {
455: #can modify the requested section
456: return 1;
457: } else {
458: # can't modify the request section
459: return 0;
460: }
461: }
462: }
463: #can't modify
464: return 0;
465: }
466:
467: #--- Retrieve the grade status of a student for all the parts
468: sub student_gradeStatus {
469: my ($symb,$udom,$uname,$partlist) = @_;
470: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
471: my %partstatus = ();
472: foreach (@$partlist) {
473: my ($status,undef) = split(/_/,$record{"resource.$_.solved"},2);
474: $status = 'nothing' if ($status eq '');
475: $partstatus{$_} = $status;
476: my $subkey = "resource.$_.submitted_by";
477: $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
478: }
479: return %partstatus;
480: }
481:
482: # hidden form and javascript that calls the form
483: # Use by verifyscript and viewgrades
484: # Shows a student's view of problem and submission
485: sub jscriptNform {
486: my ($symb) = @_;
487: my $jscript='<script type="text/javascript" language="javascript">'."\n".
488: ' function viewOneStudent(user,domain) {'."\n".
489: ' document.onestudent.student.value = user;'."\n".
490: ' document.onestudent.userdom.value = domain;'."\n".
491: ' document.onestudent.submit();'."\n".
492: ' }'."\n".
493: '</script>'."\n";
494: $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
495: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
496: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
497: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
498: '<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n".
499: '<input type="hidden" name="command" value="submission" />'."\n".
500: '<input type="hidden" name="student" value="" />'."\n".
501: '<input type="hidden" name="userdom" value="" />'."\n".
502: '</form>'."\n";
503: return $jscript;
504: }
505:
506: # Given the score (as a number [0-1] and the weight) what is the final
507: # point value? This function will round to the nearest tenth, third,
508: # or quarter if one of those is within the tolerance of .00001.
509: sub compute_points {
510: my ($score, $weight) = @_;
511:
512: my $tolerance = .00001;
513: my $points = $score * $weight;
514:
515: # Check for nearness to 1/x.
516: my $check_for_nearness = sub {
517: my ($factor) = @_;
518: my $num = ($points * $factor) + $tolerance;
519: my $floored_num = floor($num);
520: if ($num - $floored_num < 2 * $tolerance * $factor) {
521: return $floored_num / $factor;
522: }
523: return $points;
524: };
525:
526: $points = $check_for_nearness->(10);
527: $points = $check_for_nearness->(3);
528: $points = $check_for_nearness->(4);
529:
530: return $points;
531: }
532:
533: #------------------ End of general use routines --------------------
534:
535: #
536: # Find most similar essay
537: #
538:
539: sub most_similar {
540: my ($uname,$udom,$uessay,$old_essays)=@_;
541:
542: # ignore spaces and punctuation
543:
544: $uessay=~s/\W+/ /gs;
545:
546: # ignore empty submissions (occuring when only files are sent)
547:
548: unless ($uessay=~/\w+/) { return ''; }
549:
550: # these will be returned. Do not care if not at least 50 percent similar
551: my $limit=0.6;
552: my $sname='';
553: my $sdom='';
554: my $scrsid='';
555: my $sessay='';
556: # go through all essays ...
557: foreach my $tkey (keys(%$old_essays)) {
558: my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
559: # ... except the same student
560: next if (($tname eq $uname) && ($tdom eq $udom));
561: my $tessay=$old_essays->{$tkey};
562: $tessay=~s/\W+/ /gs;
563: # String similarity gives up if not even limit
564: my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
565: # Found one
566: if ($tsimilar>$limit) {
567: $limit=$tsimilar;
568: $sname=$tname;
569: $sdom=$tdom;
570: $scrsid=$tcrsid;
571: $sessay=$old_essays->{$tkey};
572: }
573: }
574: if ($limit>0.6) {
575: return ($sname,$sdom,$scrsid,$sessay,$limit);
576: } else {
577: return ('','','','',0);
578: }
579: }
580:
581: #-------------------------------------------------------------------
582:
583: #------------------------------------ Receipt Verification Routines
584: #
585: #--- Check whether a receipt number is valid.---
586: sub verifyreceipt {
587: my $request = shift;
588:
589: my $courseid = $env{'request.course.id'};
590: my $receipt = &Apache::lonnet::recprefix($courseid).'-'.
591: $env{'form.receipt'};
592: $receipt =~ s/[^\-\d]//g;
593: my ($symb) = &get_symb($request);
594:
595: my $title.='<h3><span class="LC_info">Verifying Submission Receipt '.
596: $receipt.'</h3></span>'."\n".
597: '<h4><b>Resource: </b>'.$env{'form.probTitle'}.'</h4><br /><br />'."\n";
598:
599: my ($string,$contents,$matches) = ('','',0);
600: my (undef,undef,$fullname) = &getclasslist('all','0');
601:
602: my $receiptparts=0;
603: if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
604: $env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
605: my $parts=['0'];
606: if ($receiptparts) { ($parts)=&response_type($symb); }
607: foreach (sort
608: {
609: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
610: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
611: }
612: return $a cmp $b;
613: } (keys(%$fullname))) {
614: my ($uname,$udom)=split(/\:/);
615: foreach my $part (@$parts) {
616: if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
617: $contents.='<tr bgcolor="#ffffe6"><td> '."\n".
618: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
619: '\');" target="_self">'.$$fullname{$_}.'</a> </td>'."\n".
620: '<td> '.$uname.' </td>'.
621: '<td> '.$udom.' </td>';
622: if ($receiptparts) {
623: $contents.='<td> '.$part.' </td>';
624: }
625: $contents.='</tr>'."\n";
626:
627: $matches++;
628: }
629: }
630: }
631: if ($matches == 0) {
632: $string = $title.'No match found for the above receipt.';
633: } else {
634: $string = &jscriptNform($symb).$title.
635: 'The above receipt matches the following student'.
636: ($matches <= 1 ? '.' : 's.')."\n".
637: '<table border="0"><tr><td bgcolor="#777777">'."\n".
638: '<table border="0"><tr bgcolor="#e6ffff">'."\n".
639: '<td><b> Fullname </b></td>'."\n".
640: '<td><b> Username </b></td>'."\n".
641: '<td><b> Domain </b></td>';
642: if ($receiptparts) {
643: $string.='<td> Problem Part </td>';
644: }
645: $string.='</tr>'."\n".$contents.
646: '</table></td></tr></table>'."\n";
647: }
648: return $string.&show_grading_menu_form($symb);
649: }
650:
651: #--- This is called by a number of programs.
652: #--- Called from the Grading Menu - View/Grade an individual student
653: #--- Also called directly when one clicks on the subm button
654: # on the problem page.
655: sub listStudents {
656: my ($request) = shift;
657:
658: my ($symb) = &get_symb($request);
659: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
660: my $cnum = $env{"course.$env{'request.course.id'}.num"};
661: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
662: my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
663:
664: my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
665: $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ?
666: &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
667:
668: my $result='<h3><span class="LC_info"> '.$viewgrade.
669: ' Submissions for a Student or a Group of Students</span></h3>';
670:
671: my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
672:
673: $request->print(<<LISTJAVASCRIPT);
674: <script type="text/javascript" language="javascript">
675: function checkSelect(checkBox) {
676: var ctr=0;
677: var sense="";
678: if (checkBox.length > 1) {
679: for (var i=0; i<checkBox.length; i++) {
680: if (checkBox[i].checked) {
681: ctr++;
682: }
683: }
684: sense = "a student or group of students";
685: } else {
686: if (checkBox.checked) {
687: ctr = 1;
688: }
689: sense = "the student";
690: }
691: if (ctr == 0) {
692: alert("Please select "+sense+" before clicking on the Next button.");
693: return false;
694: }
695: document.gradesub.submit();
696: }
697:
698: function reLoadList(formname) {
699: if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
700: formname.command.value = 'submission';
701: formname.submit();
702: }
703: </script>
704: LISTJAVASCRIPT
705:
706: &commonJSfunctions($request);
707: $request->print($result);
708:
709: my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
710: my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
711: my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
712: "\n".$table.
713: ' <b>View Problem Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
714: '<label><input type="radio" name="vProb" value="yes" /> one student </label>'."\n".
715: '<label><input type="radio" name="vProb" value="all" /> all students </label><br />'."\n".
716: ' <b>View Answer: </b><label><input type="radio" name="vAns" value="no" /> no </label>'."\n".
717: '<label><input type="radio" name="vAns" value="yes" /> one student </label>'."\n".
718: '<label><input type="radio" name="vAns" value="all" checked="checked" /> all students </label><br />'."\n".
719: ' <b>Submissions: </b>'."\n";
720: if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
721: $gradeTable.='<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> essay part only </label>'."\n";
722: }
723:
724: my $saveStatus = $env{'form.Status'} eq '' ? 'Active' : $env{'form.Status'};
725: $env{'form.Status'} = $saveStatus;
726: $gradeTable.='<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> last submission only </label>'."\n".
727: '<label><input type="radio" name="lastSub" value="last" /> last submission & parts info </label>'."\n".
728: '<label><input type="radio" name="lastSub" value="datesub" /> by dates and submissions </label>'."\n".
729: '<label><input type="radio" name="lastSub" value="all" /> all details</label><br />'."\n".
730: ' <b>Grading Increments:</b> <select name="increment">'.
731: '<option value="1">Whole Points</option>'.
732: '<option value=".5">Half Points</option>'.
733: '<option value=".25">Quarter Points</option>'.
734: '<option value=".1">Tenths of a Point</option>'.
735: '</select>'.
736: &build_section_inputs().
737: '<input type="hidden" name="submitonly" value="'.$submitonly.'" />'."\n".
738: '<input type="hidden" name="handgrade" value="'.$env{'form.handgrade'}.'" /><br />'."\n".
739: '<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
740: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
741: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
742: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
743: '<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
744:
745: if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
746: $gradeTable.='<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n";
747: } else {
748: $gradeTable.='<b>Student Status:</b> '.
749: &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);').'<br />';
750: }
751:
752: $gradeTable.='To '.lc($viewgrade).' a submission or a group of submissions, click on the check box(es) '.
753: 'next to the student\'s name(s). Then click on the Next button.<br />'."\n".
754: '<input type="hidden" name="command" value="processGroup" />'."\n";
755:
756: # checkall buttons
757: $gradeTable.=&check_script('gradesub', 'stuinfo');
758: $gradeTable.='<input type="button" '."\n".
759: 'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
760: 'value="Next->" /> <br />'."\n";
761: $gradeTable.=&check_buttons();
762: $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />Check For Plagiarism</label>';
763: my ($classlist, undef, $fullname) = &getclasslist($getsec,'1');
764: $gradeTable.='<table border="0"><tr><td bgcolor="#777777">'.
765: '<table border="0"><tr bgcolor="#e6ffff">';
766: my $loop = 0;
767: while ($loop < 2) {
768: $gradeTable.='<td><b> No.</b> </td><td><b> Select </b></td>'.
769: '<td>'.&nameUserString('header').' Section/Group</td>';
770: if ($env{'form.showgrading'} eq 'yes'
771: && $submitonly ne 'queued'
772: && $submitonly ne 'all') {
773: foreach (sort(@$partlist)) {
774: my $display_part=&get_display_part((split(/_/))[0],$symb);
775: $gradeTable.='<td><b> Part: '.$display_part.
776: ' Status </b></td>';
777: }
778: } elsif ($submitonly eq 'queued') {
779: $gradeTable.='<td><b> '.&mt('Queue Status').' </b></td>';
780: }
781: $loop++;
782: # $gradeTable.='<td></td>' if ($loop%2 ==1);
783: }
784: $gradeTable.='</tr>'."\n";
785:
786: my $ctr = 0;
787: foreach my $student (sort
788: {
789: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
790: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
791: }
792: return $a cmp $b;
793: }
794: (keys(%$fullname))) {
795: my ($uname,$udom) = split(/:/,$student);
796:
797: my %status = ();
798:
799: if ($submitonly eq 'queued') {
800: my %queue_status =
801: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
802: $udom,$uname);
803: next if (!defined($queue_status{'gradingqueue'}));
804: $status{'gradingqueue'} = $queue_status{'gradingqueue'};
805: }
806:
807: if ($env{'form.showgrading'} eq 'yes'
808: && $submitonly ne 'queued'
809: && $submitonly ne 'all') {
810: (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
811: my $submitted = 0;
812: my $graded = 0;
813: my $incorrect = 0;
814: foreach (keys(%status)) {
815: $submitted = 1 if ($status{$_} ne 'nothing');
816: $graded = 1 if ($status{$_} =~ /^ungraded/);
817: $incorrect = 1 if ($status{$_} =~ /^incorrect/);
818:
819: my ($foo,$partid,$foo1) = split(/\./,$_);
820: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
821: $submitted = 0;
822: my ($part)=split(/\./,$partid);
823: $gradeTable.='<input type="hidden" name="'.
824: $student.':'.$part.':submitted_by" value="'.
825: $status{'resource.'.$partid.'.submitted_by'}.'" />';
826: }
827: }
828:
829: next if (!$submitted && ($submitonly eq 'yes' ||
830: $submitonly eq 'incorrect' ||
831: $submitonly eq 'graded'));
832: next if (!$graded && ($submitonly eq 'graded'));
833: next if (!$incorrect && $submitonly eq 'incorrect');
834: }
835:
836: $ctr++;
837: my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
838:
839: if ( $perm{'vgr'} eq 'F' ) {
840: $gradeTable.='<tr bgcolor="#ffffe6">' if ($ctr%2 ==1);
841: $gradeTable.='<td align="right">'.$ctr.' </td>'.
842: '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
843: $student.':'.$$fullname{$student}.':::SECTION'.$section.
844: ') " /> </label></td>'."\n".'<td>'.
845: &nameUserString(undef,$$fullname{$student},$uname,$udom).
846: ' '.$section.'</td>'."\n";
847:
848: if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
849: foreach (sort keys(%status)) {
850: next if (/^resource.*?submitted_by$/);
851: $gradeTable.='<td align="center"> '.$status{$_}.' </td>'."\n";
852: }
853: }
854: # $gradeTable.='<td></td>' if ($ctr%2 ==1);
855: $gradeTable.='</tr>'."\n" if ($ctr%2 ==0);
856: }
857: }
858: if ($ctr%2 ==1) {
859: $gradeTable.='<td> </td><td> </td><td> </td>';
860: if ($env{'form.showgrading'} eq 'yes'
861: && $submitonly ne 'queued'
862: && $submitonly ne 'all') {
863: foreach (@$partlist) {
864: $gradeTable.='<td> </td>';
865: }
866: } elsif ($submitonly eq 'queued') {
867: $gradeTable.='<td> </td>';
868: }
869: $gradeTable.='</tr>';
870: }
871:
872: $gradeTable.='</table></td></tr></table>'."\n".
873: '<input type="button" '.
874: 'onClick="javascript:checkSelect(this.form.stuinfo);" '.
875: 'value="Next->" /></form>'."\n";
876: if ($ctr == 0) {
877: my $num_students=(scalar(keys(%$fullname)));
878: if ($num_students eq 0) {
879: $gradeTable='<br /> <span class="LC_warning">There are no students currently enrolled.</span>';
880: } else {
881: my $submissions='submissions';
882: if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
883: if ($submitonly eq 'graded' ) { $submissions = 'ungraded submissions'; }
884: if ($submitonly eq 'queued' ) { $submissions = 'queued submissions'; }
885: $gradeTable='<br /> <span class="LC_warning">'.
886: 'No '.$submissions.' found for this resource for any students. ('.$num_students.
887: ' students checked for '.$submissions.')</span><br />';
888: }
889: } elsif ($ctr == 1) {
890: $gradeTable =~ s/type=checkbox/type=checkbox checked/;
891: }
892: $gradeTable.=&show_grading_menu_form($symb);
893: $request->print($gradeTable);
894: return '';
895: }
896:
897: #---- Called from the listStudents routine
898:
899: sub check_script {
900: my ($form, $type)=@_;
901: my $chkallscript='<script type="text/javascript">
902: function checkall() {
903: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
904: ele = document.forms.'.$form.'.elements[i];
905: if (ele.name == "'.$type.'") {
906: document.forms.'.$form.'.elements[i].checked=true;
907: }
908: }
909: }
910:
911: function checksec() {
912: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
913: ele = document.forms.'.$form.'.elements[i];
914: string = document.forms.'.$form.'.chksec.value;
915: if
916: (ele.value.indexOf(":::SECTION"+string)>0) {
917: document.forms.'.$form.'.elements[i].checked=true;
918: }
919: }
920: }
921:
922:
923: function uncheckall() {
924: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
925: ele = document.forms.'.$form.'.elements[i];
926: if (ele.name == "'.$type.'") {
927: document.forms.'.$form.'.elements[i].checked=false;
928: }
929: }
930: }
931:
932: </script>'."\n";
933: return $chkallscript;
934: }
935:
936: sub check_buttons {
937: my $buttons.='<input type="button" onclick="checkall()" value="Check All" />';
938: $buttons.='<input type="button" onclick="uncheckall()" value="Uncheck All" /> ';
939: $buttons.='<input type="button" onclick="checksec()" value="Check Section/Group" />';
940: $buttons.='<input type="text" size="5" name="chksec" /> ';
941: return $buttons;
942: }
943:
944: # Displays the submissions for one student or a group of students
945: sub processGroup {
946: my ($request) = shift;
947: my $ctr = 0;
948: my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
949: my $total = scalar(@stuchecked)-1;
950:
951: foreach my $student (@stuchecked) {
952: my ($uname,$udom,$fullname) = split(/:/,$student);
953: $env{'form.student'} = $uname;
954: $env{'form.userdom'} = $udom;
955: $env{'form.fullname'} = $fullname;
956: &submission($request,$ctr,$total);
957: $ctr++;
958: }
959: return '';
960: }
961:
962: #------------------------------------------------------------------------------------
963: #
964: #-------------------------- Next few routines handles grading by student, essentially
965: # handles essay response type problem/part
966: #
967: #--- Javascript to handle the submission page functionality ---
968: sub sub_page_js {
969: my $request = shift;
970: $request->print(<<SUBJAVASCRIPT);
971: <script type="text/javascript" language="javascript">
972: function updateRadio(formname,id,weight) {
973: var gradeBox = formname["GD_BOX"+id];
974: var radioButton = formname["RADVAL"+id];
975: var oldpts = formname["oldpts"+id].value;
976: var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
977: gradeBox.value = pts;
978: var resetbox = false;
979: if (isNaN(pts) || pts < 0) {
980: alert("A number equal or greater than 0 is expected. Entered value = "+pts);
981: for (var i=0; i<radioButton.length; i++) {
982: if (radioButton[i].checked) {
983: gradeBox.value = i;
984: resetbox = true;
985: }
986: }
987: if (!resetbox) {
988: formtextbox.value = "";
989: }
990: return;
991: }
992:
993: if (pts > weight) {
994: var resp = confirm("You entered a value ("+pts+
995: ") greater than the weight for the part. Accept?");
996: if (resp == false) {
997: gradeBox.value = oldpts;
998: return;
999: }
1000: }
1001:
1002: for (var i=0; i<radioButton.length; i++) {
1003: radioButton[i].checked=false;
1004: if (pts == i && pts != "") {
1005: radioButton[i].checked=true;
1006: }
1007: }
1008: updateSelect(formname,id);
1009: formname["stores"+id].value = "0";
1010: }
1011:
1012: function writeBox(formname,id,pts) {
1013: var gradeBox = formname["GD_BOX"+id];
1014: if (checkSolved(formname,id) == 'update') {
1015: gradeBox.value = pts;
1016: } else {
1017: var oldpts = formname["oldpts"+id].value;
1018: gradeBox.value = oldpts;
1019: var radioButton = formname["RADVAL"+id];
1020: for (var i=0; i<radioButton.length; i++) {
1021: radioButton[i].checked=false;
1022: if (i == oldpts) {
1023: radioButton[i].checked=true;
1024: }
1025: }
1026: }
1027: formname["stores"+id].value = "0";
1028: updateSelect(formname,id);
1029: return;
1030: }
1031:
1032: function clearRadBox(formname,id) {
1033: if (checkSolved(formname,id) == 'noupdate') {
1034: updateSelect(formname,id);
1035: return;
1036: }
1037: gradeSelect = formname["GD_SEL"+id];
1038: for (var i=0; i<gradeSelect.length; i++) {
1039: if (gradeSelect[i].selected) {
1040: var selectx=i;
1041: }
1042: }
1043: var stores = formname["stores"+id];
1044: if (selectx == stores.value) { return };
1045: var gradeBox = formname["GD_BOX"+id];
1046: gradeBox.value = "";
1047: var radioButton = formname["RADVAL"+id];
1048: for (var i=0; i<radioButton.length; i++) {
1049: radioButton[i].checked=false;
1050: }
1051: stores.value = selectx;
1052: }
1053:
1054: function checkSolved(formname,id) {
1055: if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1056: var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
1057: if (!reply) {return "noupdate";}
1058: formname.overRideScore.value = 'yes';
1059: }
1060: return "update";
1061: }
1062:
1063: function updateSelect(formname,id) {
1064: formname["GD_SEL"+id][0].selected = true;
1065: return;
1066: }
1067:
1068: //=========== Check that a point is assigned for all the parts ============
1069: function checksubmit(formname,val,total,parttot) {
1070: formname.gradeOpt.value = val;
1071: if (val == "Save & Next") {
1072: for (i=0;i<=total;i++) {
1073: for (j=0;j<parttot;j++) {
1074: var partid = formname["partid"+i+"_"+j].value;
1075: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1076: var points = formname["GD_BOX"+i+"_"+partid].value;
1077: if (points == "") {
1078: var name = formname["name"+i].value;
1079: var studentID = (name != '' ? name : formname["unamedom"+i].value);
1080: var resp = confirm("You did not assign a score for "+studentID+
1081: ", part "+partid+". Continue?");
1082: if (resp == false) {
1083: formname["GD_BOX"+i+"_"+partid].focus();
1084: return false;
1085: }
1086: }
1087: }
1088:
1089: }
1090: }
1091:
1092: }
1093: if (val == "Grade Student") {
1094: formname.showgrading.value = "yes";
1095: if (formname.Status.value == "") {
1096: formname.Status.value = "Active";
1097: }
1098: formname.studentNo.value = total;
1099: }
1100: formname.submit();
1101: }
1102:
1103: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
1104: function checkSubmitPage(formname,total) {
1105: noscore = new Array(100);
1106: var ptr = 0;
1107: for (i=1;i<total;i++) {
1108: var partid = formname["q_"+i].value;
1109: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1110: var points = formname["GD_BOX"+i+"_"+partid].value;
1111: var status = formname["solved"+i+"_"+partid].value;
1112: if (points == "" && status != "correct_by_student") {
1113: noscore[ptr] = i;
1114: ptr++;
1115: }
1116: }
1117: }
1118: if (ptr != 0) {
1119: var sense = ptr == 1 ? ": " : "s: ";
1120: var prolist = "";
1121: if (ptr == 1) {
1122: prolist = noscore[0];
1123: } else {
1124: var i = 0;
1125: while (i < ptr-1) {
1126: prolist += noscore[i]+", ";
1127: i++;
1128: }
1129: prolist += "and "+noscore[i];
1130: }
1131: var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
1132: if (resp == false) {
1133: return false;
1134: }
1135: }
1136:
1137: formname.submit();
1138: }
1139: </script>
1140: SUBJAVASCRIPT
1141: }
1142:
1143: #--- javascript for essay type problem --
1144: sub sub_page_kw_js {
1145: my $request = shift;
1146: my $iconpath = $request->dir_config('lonIconsURL');
1147: &commonJSfunctions($request);
1148:
1149: my $inner_js_msg_central=<<INNERJS;
1150: <script text="text/javascript">
1151: function checkInput() {
1152: opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
1153: var nmsg = opener.document.SCORE.savemsgN.value;
1154: var usrctr = document.msgcenter.usrctr.value;
1155: var newval = opener.document.SCORE["newmsg"+usrctr];
1156: newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
1157:
1158: var msgchk = "";
1159: if (document.msgcenter.subchk.checked) {
1160: msgchk = "msgsub,";
1161: }
1162: var includemsg = 0;
1163: for (var i=1; i<=nmsg; i++) {
1164: var opnmsg = opener.document.SCORE["savemsg"+i];
1165: var frmmsg = document.msgcenter["msg"+i];
1166: opnmsg.value = opener.checkEntities(frmmsg.value);
1167: var showflg = opener.document.SCORE["shownOnce"+i];
1168: showflg.value = "1";
1169: var chkbox = document.msgcenter["msgn"+i];
1170: if (chkbox.checked) {
1171: msgchk += "savemsg"+i+",";
1172: includemsg = 1;
1173: }
1174: }
1175: if (document.msgcenter.newmsgchk.checked) {
1176: msgchk += "newmsg"+usrctr;
1177: includemsg = 1;
1178: }
1179: imgformname = opener.document.SCORE["mailicon"+usrctr];
1180: imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
1181: var includemsg = opener.document.SCORE["includemsg"+usrctr];
1182: includemsg.value = msgchk;
1183:
1184: self.close()
1185:
1186: }
1187: </script>
1188: INNERJS
1189:
1190: my $inner_js_highlight_central=<<INNERJS;
1191: <script type="text/javascript">
1192: function updateChoice(flag) {
1193: opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
1194: opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
1195: opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
1196: opener.document.SCORE.refresh.value = "on";
1197: if (opener.document.SCORE.keywords.value!=""){
1198: opener.document.SCORE.submit();
1199: }
1200: self.close()
1201: }
1202: </script>
1203: INNERJS
1204:
1205: my $start_page_msg_central =
1206: &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
1207: {'js_ready' => 1,
1208: 'only_body' => 1,
1209: 'bgcolor' =>'#FFFFFF',});
1210: my $end_page_msg_central =
1211: &Apache::loncommon::end_page({'js_ready' => 1});
1212:
1213:
1214: my $start_page_highlight_central =
1215: &Apache::loncommon::start_page('Highlight Central',
1216: $inner_js_highlight_central,
1217: {'js_ready' => 1,
1218: 'only_body' => 1,
1219: 'bgcolor' =>'#FFFFFF',});
1220: my $end_page_highlight_central =
1221: &Apache::loncommon::end_page({'js_ready' => 1});
1222:
1223: my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1224: $docopen=~s/^document\.//;
1225: $request->print(<<SUBJAVASCRIPT);
1226: <script type="text/javascript" language="javascript">
1227:
1228: //===================== Show list of keywords ====================
1229: function keywords(formname) {
1230: var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1231: if (nret==null) return;
1232: formname.keywords.value = nret;
1233:
1234: if (formname.keywords.value != "") {
1235: formname.refresh.value = "on";
1236: formname.submit();
1237: }
1238: return;
1239: }
1240:
1241: //===================== Script to view submitted by ==================
1242: function viewSubmitter(submitter) {
1243: document.SCORE.refresh.value = "on";
1244: document.SCORE.NCT.value = "1";
1245: document.SCORE.unamedom0.value = submitter;
1246: document.SCORE.submit();
1247: return;
1248: }
1249:
1250: //===================== Script to add keyword(s) ==================
1251: function getSel() {
1252: if (document.getSelection) txt = document.getSelection();
1253: else if (document.selection) txt = document.selection.createRange().text;
1254: else return;
1255: var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
1256: if (cleantxt=="") {
1257: alert("Please select a word or group of words from document and then click this link.");
1258: return;
1259: }
1260: var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
1261: if (nret==null) return;
1262: document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1263: if (document.SCORE.keywords.value != "") {
1264: document.SCORE.refresh.value = "on";
1265: document.SCORE.submit();
1266: }
1267: return;
1268: }
1269:
1270: //====================== Script for composing message ==============
1271: // preload images
1272: img1 = new Image();
1273: img1.src = "$iconpath/mailbkgrd.gif";
1274: img2 = new Image();
1275: img2.src = "$iconpath/mailto.gif";
1276:
1277: function msgCenter(msgform,usrctr,fullname) {
1278: var Nmsg = msgform.savemsgN.value;
1279: savedMsgHeader(Nmsg,usrctr,fullname);
1280: var subject = msgform.msgsub.value;
1281: var msgchk = document.SCORE["includemsg"+usrctr].value;
1282: re = /msgsub/;
1283: var shwsel = "";
1284: if (re.test(msgchk)) { shwsel = "checked" }
1285: subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
1286: displaySubject(checkEntities(subject),shwsel);
1287: for (var i=1; i<=Nmsg; i++) {
1288: var testmsg = "savemsg"+i+",";
1289: re = new RegExp(testmsg,"g");
1290: shwsel = "";
1291: if (re.test(msgchk)) { shwsel = "checked" }
1292: var message = document.SCORE["savemsg"+i].value;
1293: message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1294: displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
1295: //any < is already converted to <, etc. However, only once!!
1296: }
1297: newmsg = document.SCORE["newmsg"+usrctr].value;
1298: shwsel = "";
1299: re = /newmsg/;
1300: if (re.test(msgchk)) { shwsel = "checked" }
1301: newMsg(newmsg,shwsel);
1302: msgTail();
1303: return;
1304: }
1305:
1306: function checkEntities(strx) {
1307: if (strx.length == 0) return strx;
1308: var orgStr = ["&", "<", ">", '"'];
1309: var newStr = ["&", "<", ">", """];
1310: var counter = 0;
1311: while (counter < 4) {
1312: strx = strReplace(strx,orgStr[counter],newStr[counter]);
1313: counter++;
1314: }
1315: return strx;
1316: }
1317:
1318: function strReplace(strx, orgStr, newStr) {
1319: return strx.split(orgStr).join(newStr);
1320: }
1321:
1322: function savedMsgHeader(Nmsg,usrctr,fullname) {
1323: var height = 70*Nmsg+250;
1324: var scrollbar = "no";
1325: if (height > 600) {
1326: height = 600;
1327: scrollbar = "yes";
1328: }
1329: var xpos = (screen.width-600)/2;
1330: xpos = (xpos < 0) ? '0' : xpos;
1331: var ypos = (screen.height-height)/2-30;
1332: ypos = (ypos < 0) ? '0' : ypos;
1333:
1334: pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1335: pWin.focus();
1336: pDoc = pWin.document;
1337: pDoc.$docopen;
1338: pDoc.write('$start_page_msg_central');
1339:
1340: pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
1341: pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1342: pDoc.write("<h3><span class=\\"LC_info\\"> Compose Message for \"+fullname+\"</span></h3><br /><br />");
1343:
1344: pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
1345: pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
1346: pDoc.write("<td><b>Type</b></td><td><b>Include</b></td><td><b>Message</td></tr>");
1347: }
1348: function displaySubject(msg,shwsel) {
1349: pDoc = pWin.document;
1350: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1351: pDoc.write("<td>Subject</td>");
1352: pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
1353: pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"></td></tr>");
1354: }
1355:
1356: function displaySavedMsg(ctr,msg,shwsel) {
1357: pDoc = pWin.document;
1358: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1359: pDoc.write("<td align=\\"center\\">"+ctr+"</td>");
1360: pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"></td>");
1361: pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"</textarea></td></tr>");
1362: }
1363:
1364: function newMsg(newmsg,shwsel) {
1365: pDoc = pWin.document;
1366: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1367: pDoc.write("<td align=\\"center\\">New</td>");
1368: pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
1369: pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"</textarea></td></tr>");
1370: }
1371:
1372: function msgTail() {
1373: pDoc = pWin.document;
1374: pDoc.write("</table>");
1375: pDoc.write("</td></tr></table> ");
1376: pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\"> ");
1377: pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1378: pDoc.write("</form>");
1379: pDoc.write('$end_page_msg_central');
1380: pDoc.close();
1381: }
1382:
1383: //====================== Script for keyword highlight options ==============
1384: function kwhighlight() {
1385: var kwclr = document.SCORE.kwclr.value;
1386: var kwsize = document.SCORE.kwsize.value;
1387: var kwstyle = document.SCORE.kwstyle.value;
1388: var redsel = "";
1389: var grnsel = "";
1390: var blusel = "";
1391: if (kwclr=="red") {var redsel="checked"};
1392: if (kwclr=="green") {var grnsel="checked"};
1393: if (kwclr=="blue") {var blusel="checked"};
1394: var sznsel = "";
1395: var sz1sel = "";
1396: var sz2sel = "";
1397: if (kwsize=="0") {var sznsel="checked"};
1398: if (kwsize=="+1") {var sz1sel="checked"};
1399: if (kwsize=="+2") {var sz2sel="checked"};
1400: var synsel = "";
1401: var syisel = "";
1402: var sybsel = "";
1403: if (kwstyle=="") {var synsel="checked"};
1404: if (kwstyle=="<i>") {var syisel="checked"};
1405: if (kwstyle=="<b>") {var sybsel="checked"};
1406: highlightCentral();
1407: highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
1408: highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
1409: highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
1410: highlightend();
1411: return;
1412: }
1413:
1414: function highlightCentral() {
1415: // if (window.hwdWin) window.hwdWin.close();
1416: var xpos = (screen.width-400)/2;
1417: xpos = (xpos < 0) ? '0' : xpos;
1418: var ypos = (screen.height-330)/2-30;
1419: ypos = (ypos < 0) ? '0' : ypos;
1420:
1421: hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1422: hwdWin.focus();
1423: var hDoc = hwdWin.document;
1424: hDoc.$docopen;
1425: hDoc.write('$start_page_highlight_central');
1426: hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1427: hDoc.write("<h3><span class=\\"LC_info\\"> Keyword Highlight Options</span></h3><br /><br />");
1428:
1429: hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
1430: hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
1431: hDoc.write("<td><b>Text Color</b></td><td><b>Font Size</b></td><td><b>Font Style</td></tr>");
1432: }
1433:
1434: function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) {
1435: var hDoc = hwdWin.document;
1436: hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1437: hDoc.write("<td align=\\"left\\">");
1438: hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+"> "+clrtxt+"</td>");
1439: hDoc.write("<td align=\\"left\\">");
1440: hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+"> "+sztxt+"</td>");
1441: hDoc.write("<td align=\\"left\\">");
1442: hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+"> "+sytxt+"</td>");
1443: hDoc.write("</tr>");
1444: }
1445:
1446: function highlightend() {
1447: var hDoc = hwdWin.document;
1448: hDoc.write("</table>");
1449: hDoc.write("</td></tr></table> ");
1450: hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\"> ");
1451: hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1452: hDoc.write("</form>");
1453: hDoc.write('$end_page_highlight_central');
1454: hDoc.close();
1455: }
1456:
1457: </script>
1458: SUBJAVASCRIPT
1459: }
1460:
1461: sub get_increment {
1462: my $increment = $env{'form.increment'};
1463: if ($increment != 1 && $increment != .5 && $increment != .25 &&
1464: $increment != .1) {
1465: $increment = 1;
1466: }
1467: return $increment;
1468: }
1469:
1470: #--- displays the grading box, used in essay type problem and grading by page/sequence
1471: sub gradeBox {
1472: my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1473: my $checkIcon = '<img alt="'.&mt('Check Mark').
1474: '" src="'.$request->dir_config('lonIconsURL').
1475: '/check.gif" height="16" border="0" />';
1476: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1477: my $wgtmsg = ($wgt > 0 ? '(problem weight)' :
1478: '<span class="LC_info">problem weight assigned by computer</span>');
1479: $wgt = ($wgt > 0 ? $wgt : '1');
1480: my $score = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1481: '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1482: my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1483: my $display_part=&get_display_part($partid,$symb);
1484: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
1485: [$partid]);
1486: my $aggtries = $$record{'resource.'.$partid.'.tries'};
1487: if ($last_resets{$partid}) {
1488: $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
1489: }
1490: $result.='<table border="0"><tr><td>'.
1491: '<b>Part: </b>'.$display_part.' <b>Points: </b></td><td>'."\n";
1492: my $ctr = 0;
1493: my $thisweight = 0;
1494: my $increment = &get_increment();
1495: $result.='<table border="0"><tr>'."\n"; # display radio buttons in a nice table 10 across
1496: while ($thisweight<=$wgt) {
1497: $result.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1498: 'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1499: $thisweight.')" value="'.$thisweight.'" '.
1500: ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1501: $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1502: $thisweight += $increment;
1503: $ctr++;
1504: }
1505: $result.='</tr></table>';
1506: $result.='</td><td> <b>or</b> </td>'."\n";
1507: $result.='<td><input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1508: ($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1509: 'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1510: $wgt.')" /></td>'."\n";
1511: $result.='<td>/'.$wgt.' '.$wgtmsg.
1512: ($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? ' '.$checkIcon : '').
1513: ' </td><td>'."\n";
1514: $result.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
1515: 'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1516: if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1517: $result.='<option></option>'.
1518: '<option selected="selected">excused</option>';
1519: } else {
1520: $result.='<option selected="selected"></option>'.
1521: '<option>excused</option>';
1522: }
1523: $result.='<option>reset status</option></select>'."\n";
1524: $result.=" \n";
1525: $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
1526: '<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
1527: '<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1528: $$record{'resource.'.$partid.'.solved'}.'" />'."\n".
1529: '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
1530: $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
1531: '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
1532: $aggtries.'" />'."\n";
1533: $result.='</td></tr></table>'."\n";
1534: $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
1535: return $result;
1536: }
1537:
1538: sub handback_box {
1539: my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
1540: my ($partlist,$handgrade,$responseType) = &response_type($symb);
1541: my (@respids);
1542: my @part_response_id = &flatten_responseType($responseType);
1543: foreach my $part_response_id (@part_response_id) {
1544: my ($part,$resp) = @{ $part_response_id };
1545: if ($part eq $partid) {
1546: push(@respids,$resp);
1547: }
1548: }
1549: my $result;
1550: foreach my $respid (@respids) {
1551: my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
1552: my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
1553: next if (!@$files);
1554: my $file_counter = 1;
1555: foreach my $file (@$files) {
1556: if ($file =~ /\/portfolio\//) {
1557: my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1558: my ($name,$version,$ext) = &file_name_version_ext($file_disp);
1559: $file_disp = "$name.$ext";
1560: $file = $file_path.$file_disp;
1561: $result.=&mt('Return commented version of [_1] to student.',
1562: '<span class="LC_filename">'.$file_disp.'</span>');
1563: $result.='<input type="file" name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1564: $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1565: $result.='(File will be uploaded when you click on Save & Next below.)<br />';
1566: $file_counter++;
1567: }
1568: }
1569: }
1570: return $result;
1571: }
1572:
1573: sub show_problem {
1574: my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1575: my $rendered;
1576: my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1577: &Apache::lonxml::remember_problem_counter();
1578: if ($mode eq 'both' or $mode eq 'text') {
1579: $rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1580: $env{'request.course.id'},
1581: undef,\%form);
1582: }
1583: if ($removeform) {
1584: $rendered=~s|<form(.*?)>||g;
1585: $rendered=~s|</form>||g;
1586: $rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1587: }
1588: my $companswer;
1589: if ($mode eq 'both' or $mode eq 'answer') {
1590: &Apache::lonxml::restore_problem_counter();
1591: $companswer=
1592: &Apache::loncommon::get_student_answers($symb,$uname,$udom,
1593: $env{'request.course.id'},
1594: %form);
1595: }
1596: if ($removeform) {
1597: $companswer=~s|<form(.*?)>||g;
1598: $companswer=~s|</form>||g;
1599: $companswer=~s|name="submit"|name="would_have_been_submit"|g;
1600: }
1601: my $result.='<table border="0" width="100%"><tr><td bgcolor="#777777">';
1602: $result.='<table border="0" width="100%">';
1603: if ($viewon) {
1604: $result.='<tr><td bgcolor="#e6ffff"><b> ';
1605: if ($mode eq 'both' or $mode eq 'text') {
1606: $result.='View of the problem - ';
1607: } else {
1608: $result.='Correct answer: ';
1609: }
1610: $result.=$env{'form.fullname'}.'</b></td></tr>';
1611: }
1612: if ($mode eq 'both') {
1613: $result.='<tr><td bgcolor="#ffffff">'.$rendered.'<br />';
1614: $result.='<b>Correct answer:</b><br />'.$companswer;
1615: } elsif ($mode eq 'text') {
1616: $result.='<tr><td bgcolor="#ffffff">'.$rendered;
1617: } elsif ($mode eq 'answer') {
1618: $result.='<tr><td bgcolor="#ffffff">'.$companswer;
1619: }
1620: $result.='</td></tr></table>';
1621: $result.='</td></tr></table><br />';
1622: return $result;
1623: }
1624:
1625: sub files_exist {
1626: my ($r, $symb) = @_;
1627: my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1628:
1629: foreach my $student (@students) {
1630: my ($uname,$udom,$fullname) = split(/:/,$student);
1631: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
1632: $udom,$uname);
1633: my ($string,$timestamp)= &get_last_submission(\%record);
1634: foreach my $submission (@$string) {
1635: my ($partid,$respid) =
1636: ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1637: my $files=&get_submitted_files($udom,$uname,$partid,$respid,
1638: \%record);
1639: return 1 if (@$files);
1640: }
1641: }
1642: return 0;
1643: }
1644:
1645: sub download_all_link {
1646: my ($r,$symb) = @_;
1647: my $all_students =
1648: join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
1649:
1650: my $parts =
1651: join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
1652:
1653: my $identifier = &Apache::loncommon::get_cgi_id();
1654: &Apache::lonnet::appenv('cgi.'.$identifier.'.students' => $all_students,
1655: 'cgi.'.$identifier.'.symb' => $symb,
1656: 'cgi.'.$identifier.'.parts' => $parts,);
1657: $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
1658: &mt('Download All Submitted Documents').'</a>');
1659: return
1660: }
1661:
1662: sub build_section_inputs {
1663: my $section_inputs;
1664: if ($env{'form.section'} eq '') {
1665: $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
1666: } else {
1667: my @sections = &Apache::loncommon::get_env_multiple('form.section');
1668: foreach my $section(@sections) {
1669: $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
1670: }
1671: }
1672: return $section_inputs;
1673: }
1674:
1675: # --------------------------- show submissions of a student, option to grade
1676: sub submission {
1677: my ($request,$counter,$total) = @_;
1678:
1679: my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
1680: $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
1681: my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
1682: $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1683:
1684: my $symb = &get_symb($request);
1685: if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1686:
1687: if (!&canview($usec)) {
1688: $request->print('<span class="LC_warning">Unable to view requested student.('.
1689: $uname.':'.$udom.' in section '.$usec.' in course id '.
1690: $env{'request.course.id'}.')</span>');
1691: $request->print(&show_grading_menu_form($symb));
1692: return;
1693: }
1694:
1695: if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
1696: if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
1697: if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
1698: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1699: my $checkIcon = '<img alt="'.&mt('Check Mark').
1700: '" src="'.$request->dir_config('lonIconsURL').
1701: '/check.gif" height="16" border="0" />';
1702:
1703: my %old_essays;
1704: # header info
1705: if ($counter == 0) {
1706: &sub_page_js($request);
1707: &sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
1708: $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ?
1709: &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1710: if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1711: &download_all_link($request, $symb);
1712: }
1713: $request->print('<h3> <span class="LC_info">Submission Record</span></h3>'."\n".
1714: '<h4> <b>Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n");
1715:
1716: if ($env{'form.handgrade'} eq 'no') {
1717: my $checkMark='<br /><br /> <b>Note:</b> Part(s) graded correct by the computer is marked with a '.
1718: $checkIcon.' symbol.'."\n";
1719: $request->print($checkMark);
1720: }
1721:
1722: # option to display problem, only once else it cause problems
1723: # with the form later since the problem has a form.
1724: if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1725: my $mode;
1726: if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1727: $mode='both';
1728: } elsif ($env{'form.vProb'} eq 'yes') {
1729: $mode='text';
1730: } elsif ($env{'form.vAns'} eq 'yes') {
1731: $mode='answer';
1732: }
1733: &Apache::lonxml::clear_problem_counter();
1734: $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1735: }
1736:
1737: # kwclr is the only variable that is guaranteed to be non blank
1738: # if this subroutine has been called once.
1739: my %keyhash = ();
1740: if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1741: %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1742: $env{'course.'.$env{'request.course.id'}.'.domain'},
1743: $env{'course.'.$env{'request.course.id'}.'.num'});
1744:
1745: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1746: $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
1747: $env{'form.kwclr'} = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
1748: $env{'form.kwsize'} = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
1749: $env{'form.kwstyle'} = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
1750: $env{'form.msgsub'} = $keyhash{$symb.'_subject'} ne '' ?
1751: $keyhash{$symb.'_subject'} : $env{'form.probTitle'};
1752: $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1753: }
1754: my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1755: $request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1756: '<input type="hidden" name="command" value="handgrade" />'."\n".
1757: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1758: '<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n".
1759: '<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1760: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
1761: '<input type="hidden" name="refresh" value="off" />'."\n".
1762: '<input type="hidden" name="studentNo" value="" />'."\n".
1763: '<input type="hidden" name="gradeOpt" value="" />'."\n".
1764: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1765: '<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
1766: '<input type="hidden" name="vProb" value="'.$env{'form.vProb'}.'" />'."\n".
1767: '<input type="hidden" name="vAns" value="'.$env{'form.vAns'}.'" />'."\n".
1768: '<input type="hidden" name="lastSub" value="'.$env{'form.lastSub'}.'" />'."\n".
1769: &build_section_inputs().
1770: '<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1771: '<input type="hidden" name="handgrade" value="'.$env{'form.handgrade'}.'" />'."\n".
1772: '<input type="hidden" name="NCT"'.
1773: ' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1774: if ($env{'form.handgrade'} eq 'yes') {
1775: $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
1776: '<input type="hidden" name="kwclr" value="'.$env{'form.kwclr'}.'" />'."\n".
1777: '<input type="hidden" name="kwsize" value="'.$env{'form.kwsize'}.'" />'."\n".
1778: '<input type="hidden" name="kwstyle" value="'.$env{'form.kwstyle'}.'" />'."\n".
1779: '<input type="hidden" name="msgsub" value="'.$env{'form.msgsub'}.'" />'."\n".
1780: '<input type="hidden" name="shownSub" value="0" />'."\n".
1781: '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1782: foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
1783: $request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
1784: }
1785: }
1786:
1787: my ($cts,$prnmsg) = (1,'');
1788: while ($cts <= $env{'form.savemsgN'}) {
1789: $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1790: (!exists($keyhash{$symb.'_savemsg'.$cts}) ?
1791: &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1792: &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1793: '" />'."\n".
1794: '<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1795: $cts++;
1796: }
1797: $request->print($prnmsg);
1798:
1799: if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1800: #
1801: # Print out the keyword options line
1802: #
1803: $request->print(<<KEYWORDS);
1804: <b>Keyword Options:</b>
1805: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>
1806: <a href="#" onMouseDown="javascript:getSel(); return false"
1807: CLASS="page">Paste Selection to List</a>
1808: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1809: KEYWORDS
1810: #
1811: # Load the other essays for similarity check
1812: #
1813: my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1814: my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1815: $apath=&escape($apath);
1816: $apath=~s/\W/\_/gs;
1817: %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1818: }
1819: }
1820:
1821: if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1822: $request->print('<br /><br /><br />') if ($counter > 0);
1823: my $mode;
1824: if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1825: $mode='both';
1826: } elsif ($env{'form.vProb'} eq 'all' ) {
1827: $mode='text';
1828: } elsif ($env{'form.vAns'} eq 'all') {
1829: $mode='answer';
1830: }
1831: &Apache::lonxml::clear_problem_counter();
1832: $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode));
1833: }
1834:
1835: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1836: my ($partlist,$handgrade,$responseType) = &response_type($symb);
1837:
1838: # Display student info
1839: $request->print(($counter == 0 ? '' : '<br />'));
1840: my $result='<table border="0" width="100%"><tr><td bgcolor="#777777">'."\n".
1841: '<table border="0" width="100%"><tr bgcolor="#edffff"><td>'."\n";
1842:
1843: $result.='<b>Fullname: </b>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'<br />'."\n";
1844: $result.='<input type="hidden" name="name'.$counter.
1845: '" value="'.$env{'form.fullname'}.'" />'."\n";
1846:
1847: # If any part of the problem is an essay-response (handgraded), then check for collaborators
1848: my @col_fullnames;
1849: my ($classlist,$fullname);
1850: if ($env{'form.handgrade'} eq 'yes') {
1851: ($classlist,undef,$fullname) = &getclasslist('all','0');
1852: for (keys (%$handgrade)) {
1853: my $ncol = &Apache::lonnet::EXT('resource.'.$_.
1854: '.maxcollaborators',
1855: $symb,$udom,$uname);
1856: next if ($ncol <= 0);
1857: s/\_/\./g;
1858: next if ($record{'resource.'.$_.'.collaborators'} eq '');
1859: my @goodcollaborators = ();
1860: my @badcollaborators = ();
1861: foreach (split(/,?\s+/,$record{'resource.'.$_.'.collaborators'})) {
1862: $_ =~ s/[\$\^\(\)]//g;
1863: next if ($_ eq '');
1864: my ($co_name,$co_dom) = split /\@|:/,$_;
1865: $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
1866: next if ($co_name eq $uname && $co_dom eq $udom);
1867: # Doing this grep allows 'fuzzy' specification
1868: my @Matches = grep /^$co_name:$co_dom$/i,keys %$classlist;
1869: if (! scalar(@Matches)) {
1870: push @badcollaborators,$_;
1871: } else {
1872: push @goodcollaborators, @Matches;
1873: }
1874: }
1875: if (scalar(@goodcollaborators) != 0) {
1876: $result.='<b>Collaborators: </b>';
1877: foreach (@goodcollaborators) {
1878: my ($lastname,$givenn) = split(/,/,$$fullname{$_});
1879: push @col_fullnames, $givenn.' '.$lastname;
1880: $result.=$$fullname{$_}.' ';
1881: }
1882: $result.='<br />'."\n";
1883: my ($part)=split(/\./,$_);
1884: $result.='<input type="hidden" name="collaborator'.$counter.
1885: '" value="'.$part.':'.(join ':',@goodcollaborators).'" />'.
1886: "\n";
1887: }
1888: if (scalar(@badcollaborators) > 0) {
1889: $result.='<table border="0"><tr bgcolor="#ffbbbb"><td>';
1890: $result.='This student has submitted ';
1891: $result.=(scalar(@badcollaborators) == 1) ? 'an invalid collaborator' : 'invalid collaborators';
1892: $result .= ': '.join(', ',@badcollaborators);
1893: $result .= '</td></tr></table>';
1894: }
1895: if (scalar(@badcollaborators > $ncol)) {
1896: $result .= '<table border="0"><tr bgcolor="#ffbbbb"><td>';
1897: $result .= 'This student has submitted too many '.
1898: 'collaborators. Maximum is '.$ncol.'.';
1899: $result .= '</td></tr></table>';
1900: }
1901: }
1902: }
1903: $request->print($result."\n");
1904:
1905: # print student answer/submission
1906: # Options are (1) Handgaded submission only
1907: # (2) Last submission, includes submission that is not handgraded
1908: # (for multi-response type part)
1909: # (3) Last submission plus the parts info
1910: # (4) The whole record for this student
1911: if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1912: my ($string,$timestamp)= &get_last_submission(\%record);
1913: my $lastsubonly=''.
1914: ($$timestamp eq '' ? '' : '<b>Date Submitted:</b> '.
1915: $$timestamp)."</td></tr>\n";
1916: if ($$timestamp eq '') {
1917: $lastsubonly.='<tr><td bgcolor="#ffffe6">'.$$string[0];
1918: } else {
1919: my %seenparts;
1920: my @part_response_id = &flatten_responseType($responseType);
1921: foreach my $part (@part_response_id) {
1922: next if ($env{'form.lastSub'} eq 'hdgrade'
1923: && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
1924:
1925: my ($partid,$respid) = @{ $part };
1926: my $display_part=&get_display_part($partid,$symb);
1927: if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1928: if (exists($seenparts{$partid})) { next; }
1929: $seenparts{$partid}=1;
1930: my $submitby='<b>Part:</b> '.$display_part.
1931: ' <b>Collaborative submission by:</b> '.
1932: '<a href="javascript:viewSubmitter(\''.
1933: $env{"form.$uname:$udom:$partid:submitted_by"}.
1934: '\');" target="_self">'.
1935: $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1936: $request->print($submitby);
1937: next;
1938: }
1939: my $responsetype = $responseType->{$partid}->{$respid};
1940: if (!exists($record{"resource.$partid.$respid.submission"})) {
1941: $lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
1942: $display_part.' <span class="LC_internal_info">( ID '.$respid.
1943: ' )</span> '.
1944: '<span class="LC_warning">Nothing submitted - no attempts</span><br /><br />';
1945: next;
1946: }
1947: foreach (@$string) {
1948: my ($partid,$respid) = /^resource\.([^\.]*)\.([^\.]*)\.submission/;
1949: if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1950: my ($ressub,$subval) = split(/:/,$_,2);
1951: # Similarity check
1952: my $similar='';
1953: if($env{'form.checkPlag'}){
1954: my ($oname,$odom,$ocrsid,$oessay,$osim)=
1955: &most_similar($uname,$udom,$subval,\%old_essays);
1956: if ($osim) {
1957: $osim=int($osim*100.0);
1958: my %old_course_desc =
1959: &Apache::lonnet::coursedescription($ocrsid,
1960: {'one_time' => 1});
1961:
1962: $similar="<hr /><h3><span class=\"LC_warning\">".
1963: &mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
1964: $osim,
1965: &Apache::loncommon::plainname($oname,$odom),
1966: $oname,$odom,
1967: $old_course_desc{'description'},
1968: $old_course_desc{'num'},
1969: $old_course_desc{'domain'}).
1970: '</span></h3><blockquote><i>'.
1971: &keywords_highlight($oessay).
1972: '</i></blockquote><hr />';
1973: }
1974: }
1975: my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1976: if ($env{'form.lastSub'} eq 'lastonly' ||
1977: ($env{'form.lastSub'} eq 'hdgrade' &&
1978: $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1979: my $display_part=&get_display_part($partid,$symb);
1980: $lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
1981: $display_part.' <span class="LC_internal_info">( ID '.$respid.
1982: ' )</span> ';
1983: my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
1984: if (@$files) {
1985: $lastsubonly.='<br /><span class="LC_warning">Like all files provided by users, this file may contain virusses</span><br />';
1986: my $file_counter = 0;
1987: foreach my $file (@$files) {
1988: $file_counter ++;
1989: &Apache::lonnet::allowuploaded('/adm/grades',$file);
1990: $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
1991: }
1992: $lastsubonly.='<br />';
1993: }
1994: $lastsubonly.='<b>Submitted Answer: </b>'.
1995: &cleanRecord($subval,$responsetype,$symb,$partid,
1996: $respid,\%record,$order);
1997: if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1998: }
1999: }
2000: }
2001: }
2002: $lastsubonly.='</td></tr><tr bgcolor="#ffffff"><td>'."\n";
2003: $request->print($lastsubonly);
2004: } elsif ($env{'form.lastSub'} eq 'datesub') {
2005: my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
2006: $request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
2007: } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
2008: $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
2009: $env{'request.course.id'},
2010: $last,'.submission',
2011: 'Apache::grades::keywords_highlight'));
2012: }
2013:
2014: $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
2015: .$udom.'" />'."\n");
2016:
2017: # return if view submission with no grading option
2018: if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
2019: my $toGrade.='<input type="button" value="Grade Student" '.
2020: 'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
2021: .$counter.'\');" target="_self" /> '."\n" if (&canmodify($usec));
2022: $toGrade.='</td></tr></table></td></tr></table>'."\n";
2023: if (($env{'form.command'} eq 'submission') ||
2024: ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
2025: $toGrade.='</form>'.&show_grading_menu_form($symb);
2026: }
2027: $request->print($toGrade);
2028: return;
2029: } else {
2030: $request->print('</td></tr></table></td></tr></table>'."\n");
2031: }
2032:
2033: # essay grading message center
2034: if ($env{'form.handgrade'} eq 'yes') {
2035: my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
2036: my $msgfor = $givenn.' '.$lastname;
2037: if (scalar(@col_fullnames) > 0) {
2038: my $lastone = pop @col_fullnames;
2039: $msgfor .= ', '.(join ', ',@col_fullnames).' and '.$lastone.'.';
2040: }
2041: $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
2042: $result='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
2043: '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
2044: $result.=' <a href="javascript:msgCenter(document.SCORE,'.$counter.
2045: ',\''.$msgfor.'\');" target="_self">'.
2046: &mt('Compose message to student').(scalar(@col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
2047: &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
2048: '<img src="'.$request->dir_config('lonIconsURL').
2049: '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
2050: '<br /> ('.
2051: &mt('Message will be sent when you click on Save & Next below.').")\n";
2052: $request->print($result);
2053: }
2054: if ($perm{'vgr'}) {
2055: $request->print('<br />'.
2056: &Apache::loncommon::track_student_link(&mt('View recent activity'),
2057: $uname,$udom,'check'));
2058: }
2059: if ($perm{'opa'}) {
2060: $request->print('<br />'.
2061: &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
2062: $uname,$udom,$symb,'check'));
2063: }
2064:
2065: my %seen = ();
2066: my @partlist;
2067: my @gradePartRespid;
2068: my @part_response_id = &flatten_responseType($responseType);
2069: foreach my $part_response_id (@part_response_id) {
2070: my ($partid,$respid) = @{ $part_response_id };
2071: my $part_resp = join('_',@{ $part_response_id });
2072: next if ($seen{$partid} > 0);
2073: $seen{$partid}++;
2074: next if ($$handgrade{$part_resp} ne 'yes'
2075: && $env{'form.lastSub'} eq 'hdgrade');
2076: push @partlist,$partid;
2077: push @gradePartRespid,$partid.'.'.$respid;
2078: $request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
2079: }
2080: $result='<input type="hidden" name="partlist'.$counter.
2081: '" value="'.(join ":",@partlist).'" />'."\n";
2082: $result.='<input type="hidden" name="gradePartRespid'.
2083: '" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
2084: my $ctr = 0;
2085: while ($ctr < scalar(@partlist)) {
2086: $result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
2087: $partlist[$ctr].'" />'."\n";
2088: $ctr++;
2089: }
2090: $request->print($result.'</td></tr></table></td></tr></table>'."\n");
2091:
2092: # print end of form
2093: if ($counter == $total) {
2094: my $endform='<table border="0"><tr><td>'."\n";
2095: $endform.='<input type="button" value="Save & Next" '.
2096: 'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
2097: $total.','.scalar(@partlist).');" target="_self" /> '."\n";
2098: my $ntstu ='<select name="NTSTU">'.
2099: '<option>1</option><option>2</option>'.
2100: '<option>3</option><option>5</option>'.
2101: '<option>7</option><option>10</option></select>'."\n";
2102: my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
2103: $ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
2104: $endform.=$ntstu.'student(s) ';
2105: $endform.='<input type="button" value="Previous" '.
2106: 'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> '."\n".
2107: '<input type="button" value="Next" '.
2108: 'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> ';
2109: $endform.='(Next and Previous (student) do not save the scores.)'."\n" ;
2110: $endform.="<input type='hidden' value='".&get_increment().
2111: "' name='increment' />";
2112: $endform.='</td><tr></table></form>';
2113: $endform.=&show_grading_menu_form($symb);
2114: $request->print($endform);
2115: }
2116: return '';
2117: }
2118:
2119: #--- Retrieve the last submission for all the parts
2120: sub get_last_submission {
2121: my ($returnhash)=@_;
2122: my (@string,$timestamp);
2123: if ($$returnhash{'version'}) {
2124: my %lasthash=();
2125: my ($version);
2126: for ($version=1;$version<=$$returnhash{'version'};$version++) {
2127: foreach my $key (sort(split(/\:/,
2128: $$returnhash{$version.':keys'}))) {
2129: $lasthash{$key}=$$returnhash{$version.':'.$key};
2130: $timestamp =
2131: scalar(localtime($$returnhash{$version.':timestamp'}));
2132: }
2133: }
2134: foreach my $key (keys(%lasthash)) {
2135: next if ($key !~ /\.submission$/);
2136:
2137: my ($partid,$foo) = split(/submission$/,$key);
2138: my $draft = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
2139: '<span class="LC_warning">Draft Copy</span> ' : '';
2140: push(@string, join(':', $key, $draft.$lasthash{$key}));
2141: }
2142: }
2143: if (!@string) {
2144: $string[0] =
2145: '<span class="LC_warning">Nothing submitted - no attempts.</span>';
2146: }
2147: return (\@string,\$timestamp);
2148: }
2149:
2150: #--- High light keywords, with style choosen by user.
2151: sub keywords_highlight {
2152: my $string = shift;
2153: my $size = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
2154: my $styleon = $env{'form.kwstyle'} eq '' ? '' : $env{'form.kwstyle'};
2155: (my $styleoff = $styleon) =~ s/\</\<\//;
2156: my @keylist = split(/[,\s+]/,$env{'form.keywords'});
2157: foreach my $keyword (@keylist) {
2158: $string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
2159: }
2160: return $string;
2161: }
2162:
2163: #--- Called from submission routine
2164: sub processHandGrade {
2165: my ($request) = shift;
2166: my $symb = &get_symb($request);
2167: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
2168: my $button = $env{'form.gradeOpt'};
2169: my $ngrade = $env{'form.NCT'};
2170: my $ntstu = $env{'form.NTSTU'};
2171: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2172: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2173:
2174: if ($button eq 'Save & Next') {
2175: my $ctr = 0;
2176: while ($ctr < $ngrade) {
2177: my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
2178: my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
2179: if ($errorflag eq 'no_score') {
2180: $ctr++;
2181: next;
2182: }
2183: if ($errorflag eq 'not_allowed') {
2184: $request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
2185: $ctr++;
2186: next;
2187: }
2188: my $includemsg = $env{'form.includemsg'.$ctr};
2189: my ($subject,$message,$msgstatus) = ('','','');
2190: my $restitle = &Apache::lonnet::gettitle($symb);
2191: my ($feedurl,$showsymb) =
2192: &get_feedurl_and_symb($symb,$uname,$udom);
2193: my $messagetail;
2194: if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
2195: $subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
2196: unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
2197: $subject.=' ['.$restitle.']';
2198: my (@msgnum) = split(/,/,$includemsg);
2199: foreach (@msgnum) {
2200: $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
2201: }
2202: $message =&Apache::lonfeedback::clear_out_html($message);
2203: if ($env{'form.withgrades'.$ctr}) {
2204: $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
2205: $messagetail = " for <a href=\"".
2206: $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
2207: }
2208: $msgstatus =
2209: &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
2210: $message.$messagetail,
2211: undef,$feedurl,undef,
2212: undef,undef,$showsymb,
2213: $restitle);
2214: $request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
2215: $msgstatus);
2216: }
2217: if ($env{'form.collaborator'.$ctr}) {
2218: my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
2219: foreach my $collabstr (@collabstrs) {
2220: my ($part,@collaborators) = split(/:/,$collabstr);
2221: foreach my $collaborator (@collaborators) {
2222: my ($errorflag,$pts,$wgt) =
2223: &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
2224: $env{'form.unamedom'.$ctr},$part);
2225: if ($errorflag eq 'not_allowed') {
2226: $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
2227: next;
2228: } elsif ($message ne '') {
2229: my ($baseurl,$showsymb) =
2230: &get_feedurl_and_symb($symb,$collaborator,
2231: $udom);
2232: if ($env{'form.withgrades'.$ctr}) {
2233: $messagetail = " for <a href=\"".
2234: $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
2235: }
2236: $msgstatus =
2237: &Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
2238: }
2239: }
2240: }
2241: }
2242: $ctr++;
2243: }
2244: }
2245:
2246: if ($env{'form.handgrade'} eq 'yes') {
2247: # Keywords sorted in alphabatical order
2248: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
2249: my %keyhash = ();
2250: $env{'form.keywords'} =~ s/,\s{0,}|\s+/ /g;
2251: $env{'form.keywords'} =~ s/^\s+|\s+$//;
2252: my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
2253: $env{'form.keywords'} = join(' ',@keywords);
2254: $keyhash{$symb.'_keywords'} = $env{'form.keywords'};
2255: $keyhash{$symb.'_subject'} = $env{'form.msgsub'};
2256: $keyhash{$loginuser.'_kwclr'} = $env{'form.kwclr'};
2257: $keyhash{$loginuser.'_kwsize'} = $env{'form.kwsize'};
2258: $keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
2259:
2260: # message center - Order of message gets changed. Blank line is eliminated.
2261: # New messages are saved in env for the next student.
2262: # All messages are saved in nohist_handgrade.db
2263: my ($ctr,$idx) = (1,1);
2264: while ($ctr <= $env{'form.savemsgN'}) {
2265: if ($env{'form.savemsg'.$ctr} ne '') {
2266: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
2267: $idx++;
2268: }
2269: $ctr++;
2270: }
2271: $ctr = 0;
2272: while ($ctr < $ngrade) {
2273: if ($env{'form.newmsg'.$ctr} ne '') {
2274: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2275: $env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2276: $idx++;
2277: }
2278: $ctr++;
2279: }
2280: $env{'form.savemsgN'} = --$idx;
2281: $keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
2282: my $putresult = &Apache::lonnet::put
2283: ('nohist_handgrade',\%keyhash,$cdom,$cnum);
2284: }
2285: # Called by Save & Refresh from Highlight Attribute Window
2286: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
2287: if ($env{'form.refresh'} eq 'on') {
2288: my ($ctr,$total) = (0,0);
2289: while ($ctr < $ngrade) {
2290: $total++ if $env{'form.unamedom'.$ctr} ne '';
2291: $ctr++;
2292: }
2293: $env{'form.NTSTU'}=$ngrade;
2294: $ctr = 0;
2295: while ($ctr < $total) {
2296: my $processUser = $env{'form.unamedom'.$ctr};
2297: ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
2298: $env{'form.fullname'} = $$fullname{$processUser};
2299: &submission($request,$ctr,$total-1);
2300: $ctr++;
2301: }
2302: return '';
2303: }
2304:
2305: # Go directly to grade student - from submission or link from chart page
2306: if ($button eq 'Grade Student') {
2307: (undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
2308: my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
2309: ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
2310: $env{'form.fullname'} = $$fullname{$processUser};
2311: &submission($request,0,0);
2312: return '';
2313: }
2314:
2315: # Get the next/previous one or group of students
2316: my $firststu = $env{'form.unamedom0'};
2317: my $laststu = $env{'form.unamedom'.($ngrade-1)};
2318: my $ctr = 2;
2319: while ($laststu eq '') {
2320: $laststu = $env{'form.unamedom'.($ngrade-$ctr)};
2321: $ctr++;
2322: $laststu = $firststu if ($ctr > $ngrade);
2323: }
2324:
2325: my (@parsedlist,@nextlist);
2326: my ($nextflg) = 0;
2327: foreach (sort
2328: {
2329: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
2330: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
2331: }
2332: return $a cmp $b;
2333: } (keys(%$fullname))) {
2334: if ($nextflg == 1 && $button =~ /Next$/) {
2335: push @parsedlist,$_;
2336: }
2337: $nextflg = 1 if ($_ eq $laststu);
2338: if ($button eq 'Previous') {
2339: last if ($_ eq $firststu);
2340: push @parsedlist,$_;
2341: }
2342: }
2343: $ctr = 0;
2344: @parsedlist = reverse @parsedlist if ($button eq 'Previous');
2345: my ($partlist) = &response_type($symb);
2346: foreach my $student (@parsedlist) {
2347: my $submitonly=$env{'form.submitonly'};
2348: my ($uname,$udom) = split(/:/,$student);
2349:
2350: if ($submitonly eq 'queued') {
2351: my %queue_status =
2352: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
2353: $udom,$uname);
2354: next if (!defined($queue_status{'gradingqueue'}));
2355: }
2356:
2357: if ($submitonly =~ /^(yes|graded|incorrect)$/) {
2358: # my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
2359: my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
2360: my $submitted = 0;
2361: my $ungraded = 0;
2362: my $incorrect = 0;
2363: foreach (keys(%status)) {
2364: $submitted = 1 if ($status{$_} ne 'nothing');
2365: $ungraded = 1 if ($status{$_} =~ /^ungraded/);
2366: $incorrect = 1 if ($status{$_} =~ /^incorrect/);
2367: my ($foo,$partid,$foo1) = split(/\./,$_);
2368: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
2369: $submitted = 0;
2370: }
2371: }
2372: next if (!$submitted && ($submitonly eq 'yes' ||
2373: $submitonly eq 'incorrect' ||
2374: $submitonly eq 'graded'));
2375: next if (!$ungraded && ($submitonly eq 'graded'));
2376: next if (!$incorrect && $submitonly eq 'incorrect');
2377: }
2378: push @nextlist,$student if ($ctr < $ntstu);
2379: last if ($ctr == $ntstu);
2380: $ctr++;
2381: }
2382:
2383: $ctr = 0;
2384: my $total = scalar(@nextlist)-1;
2385:
2386: foreach (sort @nextlist) {
2387: my ($uname,$udom,$submitter) = split(/:/);
2388: $env{'form.student'} = $uname;
2389: $env{'form.userdom'} = $udom;
2390: $env{'form.fullname'} = $$fullname{$_};
2391: &submission($request,$ctr,$total);
2392: $ctr++;
2393: }
2394: if ($total < 0) {
2395: my $the_end = '<h3><span class="LC_info">LON-CAPA User Message</span></h3><br />'."\n";
2396: $the_end.='<b>Message: </b> No more students for this section or class.<br /><br />'."\n";
2397: $the_end.='Click on the button below to return to the grading menu.<br /><br />'."\n";
2398: $the_end.=&show_grading_menu_form($symb);
2399: $request->print($the_end);
2400: }
2401: return '';
2402: }
2403:
2404: #---- Save the score and award for each student, if changed
2405: sub saveHandGrade {
2406: my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
2407: my @version_parts;
2408: my $usec = &Apache::lonnet::getsection($domain,$stuname,
2409: $env{'request.course.id'});
2410: if (!&canmodify($usec)) { return('not_allowed'); }
2411: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
2412: my @parts_graded;
2413: my %newrecord = ();
2414: my ($pts,$wgt) = ('','');
2415: my %aggregate = ();
2416: my $aggregateflag = 0;
2417: my @parts = split(/:/,$env{'form.partlist'.$newflg});
2418: foreach my $new_part (@parts) {
2419: #collaborator ($submi may vary for different parts
2420: if ($submitter && $new_part ne $part) { next; }
2421: my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
2422: if ($dropMenu eq 'excused') {
2423: if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
2424: $newrecord{'resource.'.$new_part.'.solved'} = 'excused';
2425: if (exists($record{'resource.'.$new_part.'.awarded'})) {
2426: $newrecord{'resource.'.$new_part.'.awarded'} = '';
2427: }
2428: $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
2429: }
2430: } elsif ($dropMenu eq 'reset status'
2431: && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
2432: foreach my $key (keys (%record)) {
2433: if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
2434: }
2435: $newrecord{'resource.'.$new_part.'.regrader'}=
2436: "$env{'user.name'}:$env{'user.domain'}";
2437: my $totaltries = $record{'resource.'.$part.'.tries'};
2438:
2439: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
2440: [$new_part]);
2441: my $aggtries =$totaltries;
2442: if ($last_resets{$new_part}) {
2443: $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
2444: $new_part);
2445: }
2446:
2447: my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
2448: if ($aggtries > 0) {
2449: &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
2450: $aggregateflag = 1;
2451: }
2452: } elsif ($dropMenu eq '') {
2453: $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ?
2454: $env{'form.GD_BOX'.$newflg.'_'.$new_part} :
2455: $env{'form.RADVAL'.$newflg.'_'.$new_part});
2456: if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
2457: next;
2458: }
2459: $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 :
2460: $env{'form.WGT'.$newflg.'_'.$new_part};
2461: my $partial= $pts/$wgt;
2462: if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
2463: #do not update score for part if not changed.
2464: &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
2465: next;
2466: } else {
2467: push @parts_graded, $new_part;
2468: }
2469: if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
2470: $newrecord{'resource.'.$new_part.'.awarded'} = $partial;
2471: }
2472: my $reckey = 'resource.'.$new_part.'.solved';
2473: if ($partial == 0) {
2474: if ($record{$reckey} ne 'incorrect_by_override') {
2475: $newrecord{$reckey} = 'incorrect_by_override';
2476: }
2477: } else {
2478: if ($record{$reckey} ne 'correct_by_override') {
2479: $newrecord{$reckey} = 'correct_by_override';
2480: }
2481: }
2482: if ($submitter &&
2483: ($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
2484: $newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
2485: }
2486: $newrecord{'resource.'.$new_part.'.regrader'}=
2487: "$env{'user.name'}:$env{'user.domain'}";
2488: }
2489: # unless problem has been graded, set flag to version the submitted files
2490: unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/ ||
2491: $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
2492: $dropMenu eq 'reset status')
2493: {
2494: push (@version_parts,$new_part);
2495: }
2496: }
2497: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2498: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2499:
2500: if (%newrecord) {
2501: if (@version_parts) {
2502: my @changed_keys = &version_portfiles(\%record, \@parts_graded,
2503: $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
2504: @newrecord{@changed_keys} = @record{@changed_keys};
2505: foreach my $new_part (@version_parts) {
2506: &handback_files($request,$symb,$stuname,$domain,$newflg,
2507: $new_part,\%newrecord);
2508: }
2509: }
2510: &Apache::lonnet::cstore(\%newrecord,$symb,
2511: $env{'request.course.id'},$domain,$stuname);
2512: &check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
2513: $cdom,$cnum,$domain,$stuname);
2514: }
2515: if ($aggregateflag) {
2516: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
2517: $cdom,$cnum);
2518: }
2519: return ('',$pts,$wgt);
2520: }
2521:
2522: sub check_and_remove_from_queue {
2523: my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
2524: my @ungraded_parts;
2525: foreach my $part (@{$parts}) {
2526: if ( $record->{ 'resource.'.$part.'.awarded'} eq ''
2527: && $record->{ 'resource.'.$part.'.solved' } ne 'excused'
2528: && $newrecord->{'resource.'.$part.'.awarded'} eq ''
2529: && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
2530: ) {
2531: push(@ungraded_parts, $part);
2532: }
2533: }
2534: if ( !@ungraded_parts ) {
2535: &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
2536: $cnum,$domain,$stuname);
2537: }
2538: }
2539:
2540: sub handback_files {
2541: my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
2542: my $portfolio_root = &propath($domain,$stuname).'/userfiles/portfolio';
2543: my ($partlist,$handgrade,$responseType) = &response_type($symb);
2544:
2545: my @part_response_id = &flatten_responseType($responseType);
2546: foreach my $part_response_id (@part_response_id) {
2547: my ($part_id,$resp_id) = @{ $part_response_id };
2548: my $part_resp = join('_',@{ $part_response_id });
2549: if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
2550: # if multiple files are uploaded names will be 'returndoc2','returndoc3'
2551: my $file_counter = 1;
2552: my $file_msg;
2553: while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
2554: my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
2555: my ($directory,$answer_file) =
2556: ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
2557: my ($answer_name,$answer_ver,$answer_ext) =
2558: &file_name_version_ext($answer_file);
2559: my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
2560: my @dir_list = &Apache::lonnet::dirlist($portfolio_path,$domain,$stuname,$portfolio_root);
2561: my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
2562: # fix file name
2563: my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
2564: my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
2565: $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
2566: $save_file_name);
2567: if ($result !~ m|^/uploaded/|) {
2568: $request->print('<span class="LC_error">An error occurred ('.$result.
2569: ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</span><br />');
2570: } else {
2571: # mark the file as read only
2572: my @files = ($save_file_name);
2573: my @what = ($symb,$env{'request.course.id'},'handback');
2574: &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
2575: if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
2576: $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
2577: }
2578: $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
2579: $file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
2580:
2581: }
2582: $request->print("<br />".$fname." will be the uploaded file name");
2583: $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
2584: $file_counter++;
2585: }
2586: my $subject = "File Handed Back by Instructor ";
2587: my $message = "A file has been returned that was originally submitted in reponse to: <br />";
2588: $message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
2589: $message .= ' The returned file(s) are named: '. $file_msg;
2590: $message .= " and can be found in your portfolio space.";
2591: my ($feedurl,$showsymb) =
2592: &get_feedurl_and_symb($symb,$domain,$stuname);
2593: my $restitle = &Apache::lonnet::gettitle($symb);
2594: my $msgstatus =
2595: &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
2596: ' (File Returned) ['.$restitle.']',$message,undef,
2597: $feedurl,undef,undef,undef,$showsymb,$restitle);
2598: }
2599: }
2600: return;
2601: }
2602:
2603: sub get_feedurl_and_symb {
2604: my ($symb,$uname,$udom) = @_;
2605: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
2606: $url = &Apache::lonnet::clutter($url);
2607: my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
2608: $symb,$udom,$uname);
2609: if ($encrypturl =~ /^yes$/i) {
2610: &Apache::lonenc::encrypted(\$url,1);
2611: &Apache::lonenc::encrypted(\$symb,1);
2612: }
2613: return ($url,$symb);
2614: }
2615:
2616: sub get_submitted_files {
2617: my ($udom,$uname,$partid,$respid,$record) = @_;
2618: my @files;
2619: if ($$record{"resource.$partid.$respid.portfiles"}) {
2620: my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
2621: foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
2622: push(@files,$file_url.$file);
2623: }
2624: }
2625: if ($$record{"resource.$partid.$respid.uploadedurl"}) {
2626: push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
2627: }
2628: return (\@files);
2629: }
2630:
2631: # ----------- Provides number of tries since last reset.
2632: sub get_num_tries {
2633: my ($record,$last_reset,$part) = @_;
2634: my $timestamp = '';
2635: my $num_tries = 0;
2636: if ($$record{'version'}) {
2637: for (my $version=$$record{'version'};$version>=1;$version--) {
2638: if (exists($$record{$version.':resource.'.$part.'.solved'})) {
2639: $timestamp = $$record{$version.':timestamp'};
2640: if ($timestamp > $last_reset) {
2641: $num_tries ++;
2642: } else {
2643: last;
2644: }
2645: }
2646: }
2647: }
2648: return $num_tries;
2649: }
2650:
2651: # ----------- Determine decrements required in aggregate totals
2652: sub decrement_aggs {
2653: my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
2654: my %decrement = (
2655: attempts => 0,
2656: users => 0,
2657: correct => 0
2658: );
2659: $decrement{'attempts'} = $aggtries;
2660: if ($solvedstatus =~ /^correct/) {
2661: $decrement{'correct'} = 1;
2662: }
2663: if ($aggtries == $totaltries) {
2664: $decrement{'users'} = 1;
2665: }
2666: foreach my $type (keys (%decrement)) {
2667: $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
2668: }
2669: return;
2670: }
2671:
2672: # ----------- Determine timestamps for last reset of aggregate totals for parts
2673: sub get_last_resets {
2674: my ($symb,$courseid,$partids) =@_;
2675: my %last_resets;
2676: my $cdom = $env{'course.'.$courseid.'.domain'};
2677: my $cname = $env{'course.'.$courseid.'.num'};
2678: my @keys;
2679: foreach my $part (@{$partids}) {
2680: push(@keys,"$symb\0$part\0resettime");
2681: }
2682: my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
2683: $cdom,$cname);
2684: foreach my $part (@{$partids}) {
2685: $last_resets{$part}=$results{"$symb\0$part\0resettime"};
2686: }
2687: return %last_resets;
2688: }
2689:
2690: # ----------- Handles creating versions for portfolio files as answers
2691: sub version_portfiles {
2692: my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
2693: my $version_parts = join('|',@$v_flag);
2694: my @returned_keys;
2695: my $parts = join('|', @$parts_graded);
2696: my $portfolio_root = &propath($domain,$stu_name).
2697: '/userfiles/portfolio';
2698: foreach my $key (keys(%$record)) {
2699: my $new_portfiles;
2700: if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
2701: my @versioned_portfiles;
2702: my @portfiles = split(/\s*,\s*/,$$record{$key});
2703: foreach my $file (@portfiles) {
2704: &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
2705: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
2706: my ($answer_name,$answer_ver,$answer_ext) =
2707: &file_name_version_ext($answer_file);
2708: my @dir_list = &Apache::lonnet::dirlist($directory,$domain,$stu_name,$portfolio_root);
2709: my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
2710: my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
2711: if ($new_answer ne 'problem getting file') {
2712: push(@versioned_portfiles, $directory.$new_answer);
2713: &Apache::lonnet::mark_as_readonly($domain,$stu_name,
2714: [$directory.$new_answer],
2715: [$symb,$env{'request.course.id'},'graded']);
2716: }
2717: }
2718: $$record{$key} = join(',',@versioned_portfiles);
2719: push(@returned_keys,$key);
2720: }
2721: }
2722: return (@returned_keys);
2723: }
2724:
2725: sub get_next_version {
2726: my ($answer_name, $answer_ext, $dir_list) = @_;
2727: my $version;
2728: foreach my $row (@$dir_list) {
2729: my ($file) = split(/\&/,$row,2);
2730: my ($file_name,$file_version,$file_ext) =
2731: &file_name_version_ext($file);
2732: if (($file_name eq $answer_name) &&
2733: ($file_ext eq $answer_ext)) {
2734: # gets here if filename and extension match, regardless of version
2735: if ($file_version ne '') {
2736: # a versioned file is found so save it for later
2737: if ($file_version > $version) {
2738: $version = $file_version;
2739: }
2740: }
2741: }
2742: }
2743: $version ++;
2744: return($version);
2745: }
2746:
2747: sub version_selected_portfile {
2748: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
2749: my ($answer_name,$answer_ver,$answer_ext) =
2750: &file_name_version_ext($file_name);
2751: my $new_answer;
2752: $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
2753: if($env{'form.copy'} eq '-1') {
2754: &Apache::lonnet::logthis('problem getting file '.$file_name);
2755: $new_answer = 'problem getting file';
2756: } else {
2757: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
2758: my $copy_result = &Apache::lonnet::finishuserfileupload(
2759: $stu_name,$domain,'copy',
2760: '/portfolio'.$directory.$new_answer);
2761: }
2762: return ($new_answer);
2763: }
2764:
2765: sub file_name_version_ext {
2766: my ($file)=@_;
2767: my @file_parts = split(/\./, $file);
2768: my ($name,$version,$ext);
2769: if (@file_parts > 1) {
2770: $ext=pop(@file_parts);
2771: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
2772: $version=pop(@file_parts);
2773: }
2774: $name=join('.',@file_parts);
2775: } else {
2776: $name=join('.',@file_parts);
2777: }
2778: return($name,$version,$ext);
2779: }
2780:
2781: #--------------------------------------------------------------------------------------
2782: #
2783: #-------------------------- Next few routines handles grading by section or whole class
2784: #
2785: #--- Javascript to handle grading by section or whole class
2786: sub viewgrades_js {
2787: my ($request) = shift;
2788:
2789: $request->print(<<VIEWJAVASCRIPT);
2790: <script type="text/javascript" language="javascript">
2791: function writePoint(partid,weight,point) {
2792: var radioButton = document.classgrade["RADVAL_"+partid];
2793: var textbox = document.classgrade["TEXTVAL_"+partid];
2794: if (point == "textval") {
2795: point = document.classgrade["TEXTVAL_"+partid].value;
2796: if (isNaN(point) || parseFloat(point) < 0) {
2797: alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
2798: var resetbox = false;
2799: for (var i=0; i<radioButton.length; i++) {
2800: if (radioButton[i].checked) {
2801: textbox.value = i;
2802: resetbox = true;
2803: }
2804: }
2805: if (!resetbox) {
2806: textbox.value = "";
2807: }
2808: return;
2809: }
2810: if (parseFloat(point) > parseFloat(weight)) {
2811: var resp = confirm("You entered a value ("+parseFloat(point)+
2812: ") greater than the weight for the part. Accept?");
2813: if (resp == false) {
2814: textbox.value = "";
2815: return;
2816: }
2817: }
2818: for (var i=0; i<radioButton.length; i++) {
2819: radioButton[i].checked=false;
2820: if (parseFloat(point) == i) {
2821: radioButton[i].checked=true;
2822: }
2823: }
2824:
2825: } else {
2826: textbox.value = parseFloat(point);
2827: }
2828: for (i=0;i<document.classgrade.total.value;i++) {
2829: var user = document.classgrade["ctr"+i].value;
2830: user = user.replace(new RegExp(':', 'g'),"_");
2831: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
2832: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
2833: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
2834: if (saveval != "correct") {
2835: scorename.value = point;
2836: if (selname[0].selected != true) {
2837: selname[0].selected = true;
2838: }
2839: }
2840: }
2841: document.classgrade["SELVAL_"+partid][0].selected = true;
2842: }
2843:
2844: function writeRadText(partid,weight) {
2845: var selval = document.classgrade["SELVAL_"+partid];
2846: var radioButton = document.classgrade["RADVAL_"+partid];
2847: var override = document.classgrade["FORCE_"+partid].checked;
2848: var textbox = document.classgrade["TEXTVAL_"+partid];
2849: if (selval[1].selected || selval[2].selected) {
2850: for (var i=0; i<radioButton.length; i++) {
2851: radioButton[i].checked=false;
2852:
2853: }
2854: textbox.value = "";
2855:
2856: for (i=0;i<document.classgrade.total.value;i++) {
2857: var user = document.classgrade["ctr"+i].value;
2858: user = user.replace(new RegExp(':', 'g'),"_");
2859: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
2860: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
2861: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
2862: if ((saveval != "correct") || override) {
2863: scorename.value = "";
2864: if (selval[1].selected) {
2865: selname[1].selected = true;
2866: } else {
2867: selname[2].selected = true;
2868: if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value))
2869: {document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
2870: }
2871: }
2872: }
2873: } else {
2874: for (i=0;i<document.classgrade.total.value;i++) {
2875: var user = document.classgrade["ctr"+i].value;
2876: user = user.replace(new RegExp(':', 'g'),"_");
2877: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
2878: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
2879: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
2880: if ((saveval != "correct") || override) {
2881: scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
2882: selname[0].selected = true;
2883: }
2884: }
2885: }
2886: }
2887:
2888: function changeSelect(partid,user) {
2889: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
2890: var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
2891: var point = textbox.value;
2892: var weight = document.classgrade["weight_"+partid].value;
2893:
2894: if (isNaN(point) || parseFloat(point) < 0) {
2895: alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
2896: textbox.value = "";
2897: return;
2898: }
2899: if (parseFloat(point) > parseFloat(weight)) {
2900: var resp = confirm("You entered a value ("+parseFloat(point)+
2901: ") greater than the weight of the part. Accept?");
2902: if (resp == false) {
2903: textbox.value = "";
2904: return;
2905: }
2906: }
2907: selval[0].selected = true;
2908: }
2909:
2910: function changeOneScore(partid,user) {
2911: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
2912: if (selval[1].selected || selval[2].selected) {
2913: document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
2914: if (selval[2].selected) {
2915: document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
2916: }
2917: }
2918: }
2919:
2920: function resetEntry(numpart) {
2921: for (ctpart=0;ctpart<numpart;ctpart++) {
2922: var partid = document.classgrade["partid_"+ctpart].value;
2923: var radioButton = document.classgrade["RADVAL_"+partid];
2924: var textbox = document.classgrade["TEXTVAL_"+partid];
2925: var selval = document.classgrade["SELVAL_"+partid];
2926: for (var i=0; i<radioButton.length; i++) {
2927: radioButton[i].checked=false;
2928:
2929: }
2930: textbox.value = "";
2931: selval[0].selected = true;
2932:
2933: for (i=0;i<document.classgrade.total.value;i++) {
2934: var user = document.classgrade["ctr"+i].value;
2935: user = user.replace(new RegExp(':', 'g'),"_");
2936: var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
2937: resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
2938: var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
2939: resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
2940: var saveselval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
2941: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
2942: if (saveselval == "excused") {
2943: if (selname[1].selected == false) { selname[1].selected = true;}
2944: } else {
2945: if (selname[0].selected == false) {selname[0].selected = true};
2946: }
2947: }
2948: }
2949: }
2950:
2951: </script>
2952: VIEWJAVASCRIPT
2953: }
2954:
2955: #--- show scores for a section or whole class w/ option to change/update a score
2956: sub viewgrades {
2957: my ($request) = shift;
2958: &viewgrades_js($request);
2959:
2960: my ($symb) = &get_symb($request);
2961: #need to make sure we have the correct data for later EXT calls,
2962: #thus invalidate the cache
2963: &Apache::lonnet::devalidatecourseresdata(
2964: $env{'course.'.$env{'request.course.id'}.'.num'},
2965: $env{'course.'.$env{'request.course.id'}.'.domain'});
2966: &Apache::lonnet::clear_EXT_cache_status();
2967:
2968: my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
2969: $result.='<h4><b>Current Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n";
2970:
2971: #view individual student submission form - called using Javascript viewOneStudent
2972: $result.=&jscriptNform($symb);
2973:
2974: #beginning of class grading form
2975: $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
2976: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
2977: '<input type="hidden" name="command" value="editgrades" />'."\n".
2978: &build_section_inputs().
2979: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
2980: '<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n".
2981: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
2982:
2983: my $sectionClass;
2984: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
2985: if ($env{'form.section'} eq 'all') {
2986: $sectionClass='Class </h3>';
2987: } elsif ($env{'form.section'} eq 'none') {
2988: $sectionClass=&mt('Students in no Section').'</h3>';
2989: } else {
2990: $sectionClass=&mt('Students in Section(s) [_1]',$section_display).'</h3>';
2991: }
2992: $result.='<h3>'.&mt('Assign Common Grade To [_1]',$sectionClass);
2993: $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
2994: '<table border=0><tr bgcolor="#ffffdd"><td>';
2995: #radio buttons/text box for assigning points for a section or class.
2996: #handles different parts of a problem
2997: my ($partlist,$handgrade,$responseType) = &response_type($symb);
2998: my %weight = ();
2999: my $ctsparts = 0;
3000: $result.='<table border="0">';
3001: my %seen = ();
3002: my @part_response_id = &flatten_responseType($responseType);
3003: foreach my $part_response_id (@part_response_id) {
3004: my ($partid,$respid) = @{ $part_response_id };
3005: my $part_resp = join('_',@{ $part_response_id });
3006: next if $seen{$partid};
3007: $seen{$partid}++;
3008: my $handgrade=$$handgrade{$part_resp};
3009: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
3010: $weight{$partid} = $wgt eq '' ? '1' : $wgt;
3011:
3012: $result.='<input type="hidden" name="partid_'.
3013: $ctsparts.'" value="'.$partid.'" />'."\n";
3014: $result.='<input type="hidden" name="weight_'.
3015: $partid.'" value="'.$weight{$partid}.'" />'."\n";
3016: my $display_part=&get_display_part($partid,$symb);
3017: $result.='<tr><td><b>Part:</b> '.$display_part.' <b>Point:</b> </td><td>';
3018: $result.='<table border="0"><tr>';
3019: my $ctr = 0;
3020: while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
3021: $result.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
3022: 'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
3023: ','.$ctr.')" />'.$ctr."</label></td>\n";
3024: $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
3025: $ctr++;
3026: }
3027: $result.='</tr></table>';
3028: $result.= '</td><td><b> or </b><input type="text" name="TEXTVAL_'.
3029: $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
3030: $partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
3031: $weight{$partid}.' (problem weight)</td>'."\n";
3032: $result.= '</td><td><select name="SELVAL_'.$partid.'"'.
3033: 'onChange="javascript:writeRadText(\''.$partid.'\','.
3034: $weight{$partid}.')"> '.
3035: '<option selected="selected"> </option>'.
3036: '<option>excused</option>'.
3037: '<option>reset status</option></select></td>'.
3038: '<td><label><input type="checkbox" name="FORCE_'.$partid.'" /> Override "Correct"</label></td></tr>'."\n";
3039: $ctsparts++;
3040: }
3041: $result.='</table>'.'</td></tr></table>'.'</td></tr></table>'."\n".
3042: '<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
3043: $result.='<input type="button" value="Revert to Default" '.
3044: 'onClick="javascript:resetEntry('.$ctsparts.');" target="_self" />';
3045:
3046: #table listing all the students in a section/class
3047: #header of table
3048: $result.= '<h3>Assign Grade to Specific Students in '.$sectionClass;
3049: $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
3050: '<table border=0><tr bgcolor="#deffff"><td> <b>No.</b> </td>'.
3051: '<td>'.&nameUserString('header')."</td>\n";
3052: my (@parts) = sort(&getpartlist($symb));
3053: my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
3054: my @partids = ();
3055: foreach my $part (@parts) {
3056: my $display=&Apache::lonnet::metadata($url,$part.'.display');
3057: $display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
3058: if (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
3059: my ($partid) = &split_part_type($part);
3060: push(@partids, $partid);
3061: my $display_part=&get_display_part($partid,$symb);
3062: if ($display =~ /^Partial Credit Factor/) {
3063: $result.='<td><b>Score Part:</b> '.$display_part.
3064: ' <br /><b>(weight = '.$weight{$partid}.')</b></td>'."\n";
3065: next;
3066: } else {
3067: $display =~s/\[Part: \Q$partid\E\]/Part:<\/b> $display_part/;
3068: }
3069: $display =~ s|Problem Status|Grade Status<br />|;
3070: $result.='<td><b>'.$display.'</td>'."\n";
3071: }
3072: $result.='</tr>';
3073:
3074: my %last_resets =
3075: &get_last_resets($symb,$env{'request.course.id'},\@partids);
3076:
3077: #get info for each student
3078: #list all the students - with points and grade status
3079: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
3080: my $ctr = 0;
3081: foreach (sort
3082: {
3083: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
3084: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
3085: }
3086: return $a cmp $b;
3087: } (keys(%$fullname))) {
3088: $ctr++;
3089: $result.=&viewstudentgrade($symb,$env{'request.course.id'},
3090: $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
3091: }
3092: $result.='</table></td></tr></table>';
3093: $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
3094: $result.='<input type="button" value="Save" '.
3095: 'onClick="javascript:submit();" target="_self" /></form>'."\n";
3096: if (scalar(%$fullname) eq 0) {
3097: my $colspan=3+scalar(@parts);
3098: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3099: $result='<span class="LC_warning">'.
3100: &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade',
3101: $section_display, $env{'form.Status'}).
3102: '</span>';
3103: }
3104: $result.=&show_grading_menu_form($symb);
3105: return $result;
3106: }
3107:
3108: #--- call by previous routine to display each student
3109: sub viewstudentgrade {
3110: my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
3111: my ($uname,$udom) = split(/:/,$student);
3112: my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
3113: my %aggregates = ();
3114: my $result='<tr bgcolor="#ffffdd"><td align="right">'.
3115: '<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
3116: "\n".$ctr.' </td><td> '.
3117: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
3118: '\');" target="_self">'.$fullname.'</a> '.
3119: '<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
3120: $student=~s/:/_/; # colon doen't work in javascript for names
3121: foreach my $apart (@$parts) {
3122: my ($part,$type) = &split_part_type($apart);
3123: my $score=$record{"resource.$part.$type"};
3124: $result.='<td align="center">';
3125: my ($aggtries,$totaltries);
3126: unless (exists($aggregates{$part})) {
3127: $totaltries = $record{'resource.'.$part.'.tries'};
3128:
3129: $aggtries = $totaltries;
3130: if ($$last_resets{$part}) {
3131: $aggtries = &get_num_tries(\%record,$$last_resets{$part},
3132: $part);
3133: }
3134: $result.='<input type="hidden" name="'.
3135: 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
3136: $result.='<input type="hidden" name="'.
3137: 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
3138: $aggregates{$part} = 1;
3139: }
3140: if ($type eq 'awarded') {
3141: my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
3142: $result.='<input type="hidden" name="'.
3143: 'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
3144: $result.='<input type="text" name="'.
3145: 'GD_'.$student.'_'.$part.'_awarded" '.
3146: 'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
3147: '\')" value="'.$pts.'" size="4" /></td>'."\n";
3148: } elsif ($type eq 'solved') {
3149: my ($status,$foo)=split(/_/,$score,2);
3150: $status = 'nothing' if ($status eq '');
3151: $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
3152: $part.'_solved_s" value="'.$status.'" />'."\n";
3153: $result.=' <select name="'.
3154: 'GD_'.$student.'_'.$part.'_solved" '.
3155: 'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
3156: $result.= (($status eq 'excused') ? '<option> </option><option selected="selected">excused</option>'
3157: : '<option selected="selected"> </option><option>excused</option>')."\n";
3158: $result.='<option>reset status</option>';
3159: $result.="</select> </td>\n";
3160: } else {
3161: $result.='<input type="hidden" name="'.
3162: 'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
3163: "\n";
3164: $result.='<input type="text" name="'.
3165: 'GD_'.$student.'_'.$part.'_'.$type.'" '.
3166: 'value="'.$score.'" size="4" /></td>'."\n";
3167: }
3168: }
3169: $result.='</tr>';
3170: return $result;
3171: }
3172:
3173: #--- change scores for all the students in a section/class
3174: # record does not get update if unchanged
3175: sub editgrades {
3176: my ($request) = @_;
3177:
3178: my $symb=&get_symb($request);
3179: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3180: my $title='<h3><span class="LC_info">'.&mt('Current Grade Status').'</span></h3>';
3181: $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4><br />'."\n";
3182: $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
3183:
3184: my $result= '<table border="0"><tr><td bgcolor="#777777">'."\n";
3185: $result.= '<table border="0"><tr bgcolor="#deffff">'.
3186: '<td rowspan=2 valign="center"> <b>No.</b> </td>'.
3187: '<td rowspan=2 valign="center">'.&nameUserString('header')."</td>\n";
3188:
3189: my %scoreptr = (
3190: 'correct' =>'correct_by_override',
3191: 'incorrect'=>'incorrect_by_override',
3192: 'excused' =>'excused',
3193: 'ungraded' =>'ungraded_attempted',
3194: 'nothing' => '',
3195: );
3196: my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
3197:
3198: my (@partid);
3199: my %weight = ();
3200: my %columns = ();
3201: my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
3202:
3203: my (@parts) = sort(&getpartlist($symb));
3204: my $header;
3205: while ($ctr < $env{'form.totalparts'}) {
3206: my $partid = $env{'form.partid_'.$ctr};
3207: push @partid,$partid;
3208: $weight{$partid} = $env{'form.weight_'.$partid};
3209: $ctr++;
3210: }
3211: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3212: foreach my $partid (@partid) {
3213: $header .= '<td align="center"> <b>Old Score</b> </td>'.
3214: '<td align="center"> <b>New Score</b> </td>';
3215: $columns{$partid}=2;
3216: foreach my $stores (@parts) {
3217: my ($part,$type) = &split_part_type($stores);
3218: if ($part !~ m/^\Q$partid\E/) { next;}
3219: if ($type eq 'awarded' || $type eq 'solved') { next; }
3220: my $display=&Apache::lonnet::metadata($url,$stores.'.display');
3221: $display =~ s/\[Part: (\w)+\]//;
3222: $display =~ s/Number of Attempts/Tries/;
3223: $header .= '<td align="center"> <b>Old '.$display.'</b> </td>'.
3224: '<td align="center"> <b>New '.$display.'</b> </td>';
3225: $columns{$partid}+=2;
3226: }
3227: }
3228: foreach my $partid (@partid) {
3229: my $display_part=&get_display_part($partid,$symb);
3230: $result .= '<td colspan="'.$columns{$partid}.
3231: '" align="center"><b>Part:</b> '.$display_part.
3232: ' (Weight = '.$weight{$partid}.')</td>';
3233:
3234: }
3235: $result .= '</tr><tr bgcolor="#deffff">';
3236: $result .= $header;
3237: $result .= '</tr>'."\n";
3238: my $noupdate;
3239: my ($updateCtr,$noupdateCtr) = (1,1);
3240: for ($i=0; $i<$env{'form.total'}; $i++) {
3241: my $line;
3242: my $user = $env{'form.ctr'.$i};
3243: my ($uname,$udom)=split(/:/,$user);
3244: my %newrecord;
3245: my $updateflag = 0;
3246: $line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
3247: my $usec=$classlist->{"$uname:$udom"}[5];
3248: if (!&canmodify($usec)) {
3249: my $numcols=scalar(@partid)*4+2;
3250: $noupdate.=$line."<td colspan=\"$numcols\"><span class=\"LC_warning\">Not allowed to modify student</span></td></tr>";
3251: next;
3252: }
3253: my %aggregate = ();
3254: my $aggregateflag = 0;
3255: $user=~s/:/_/; # colon doen't work in javascript for names
3256: foreach (@partid) {
3257: my $old_aw = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
3258: my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
3259: my $old_part = $old_aw eq '' ? '' : $old_part_pcr;
3260: my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
3261: my $awarded = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
3262: my $pcr = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
3263: my $partial = $awarded eq '' ? '' : $pcr;
3264: my $score;
3265: if ($partial eq '') {
3266: $score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
3267: } elsif ($partial > 0) {
3268: $score = 'correct_by_override';
3269: } elsif ($partial == 0) {
3270: $score = 'incorrect_by_override';
3271: }
3272: my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
3273: $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
3274:
3275: $newrecord{'resource.'.$_.'.regrader'}=
3276: "$env{'user.name'}:$env{'user.domain'}";
3277: if ($dropMenu eq 'reset status' &&
3278: $old_score ne '') { # ignore if no previous attempts => nothing to reset
3279: $newrecord{'resource.'.$_.'.tries'} = '';
3280: $newrecord{'resource.'.$_.'.solved'} = '';
3281: $newrecord{'resource.'.$_.'.award'} = '';
3282: $newrecord{'resource.'.$_.'.awarded'} = '';
3283: $updateflag = 1;
3284: if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
3285: my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
3286: my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
3287: my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
3288: &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
3289: $aggregateflag = 1;
3290: }
3291: } elsif (!($old_part eq $partial && $old_score eq $score)) {
3292: $updateflag = 1;
3293: $newrecord{'resource.'.$_.'.awarded'} = $partial if $partial ne '';
3294: $newrecord{'resource.'.$_.'.solved'} = $score;
3295: $rec_update++;
3296: }
3297:
3298: $line .= '<td align="center">'.$old_aw.' </td>'.
3299: '<td align="center">'.$awarded.
3300: ($score eq 'excused' ? $score : '').' </td>';
3301:
3302:
3303: my $partid=$_;
3304: foreach my $stores (@parts) {
3305: my ($part,$type) = &split_part_type($stores);
3306: if ($part !~ m/^\Q$partid\E/) { next;}
3307: if ($type eq 'awarded' || $type eq 'solved') { next; }
3308: my $old_aw = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
3309: my $awarded = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
3310: if ($awarded ne '' && $awarded ne $old_aw) {
3311: $newrecord{'resource.'.$part.'.'.$type}= $awarded;
3312: $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
3313: $updateflag=1;
3314: }
3315: $line .= '<td align="center">'.$old_aw.' </td>'.
3316: '<td align="center">'.$awarded.' </td>';
3317: }
3318: }
3319: $line.='</tr>'."\n";
3320:
3321: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3322: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3323:
3324: if ($updateflag) {
3325: $count++;
3326: &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
3327: $udom,$uname);
3328:
3329: if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
3330: $cnum,$udom,$uname)) {
3331: # need to figure out if should be in queue.
3332: my %record =
3333: &Apache::lonnet::restore($symb,$env{'request.course.id'},
3334: $udom,$uname);
3335: my $all_graded = 1;
3336: my $none_graded = 1;
3337: foreach my $part (@parts) {
3338: if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
3339: $all_graded = 0;
3340: } else {
3341: $none_graded = 0;
3342: }
3343: }
3344:
3345: if ($all_graded || $none_graded) {
3346: &Apache::bridgetask::remove_from_queue('gradingqueue',
3347: $symb,$cdom,$cnum,
3348: $udom,$uname);
3349: }
3350: }
3351:
3352: $result.='<tr bgcolor="#ffffde"><td align="right"> '.$updateCtr.' </td>'.$line;
3353: $updateCtr++;
3354: } else {
3355: $noupdate.='<tr bgcolor="#ffffde"><td align="right"> '.$noupdateCtr.' </td>'.$line;
3356: $noupdateCtr++;
3357: }
3358: if ($aggregateflag) {
3359: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
3360: $cdom,$cnum);
3361: }
3362: }
3363: if ($noupdate) {
3364: # my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
3365: my $numcols=scalar(@partid)*4+2;
3366: $result .= '<tr bgcolor="#ffffff"><td align="center" colspan="'.$numcols.'">No Changes Occurred For the Students Below</td></tr><tr bgcolor="#ffffde">'.$noupdate;
3367: }
3368: $result .= '</table></td></tr></table>'."\n".
3369: &show_grading_menu_form ($symb);
3370: my $msg = '<br /><b>Number of records updated = '.$rec_update.
3371: ' for '.$count.' student'.($count <= 1 ? '' : 's').'.</b><br />'.
3372: '<b>Total number of students = '.$env{'form.total'}.'</b><br />';
3373: return $title.$msg.$result;
3374: }
3375:
3376: sub split_part_type {
3377: my ($partstr) = @_;
3378: my ($temp,@allparts)=split(/_/,$partstr);
3379: my $type=pop(@allparts);
3380: my $part=join('.',@allparts);
3381: return ($part,$type);
3382: }
3383:
3384: #------------- end of section for handling grading by section/class ---------
3385: #
3386: #----------------------------------------------------------------------------
3387:
3388:
3389: #----------------------------------------------------------------------------
3390: #
3391: #-------------------------- Next few routines handles grading by csv upload
3392: #
3393: #--- Javascript to handle csv upload
3394: sub csvupload_javascript_reverse_associate {
3395: my $error1=&mt('You need to specify the username or ID');
3396: my $error2=&mt('You need to specify at least one grading field');
3397: return(<<ENDPICK);
3398: function verify(vf) {
3399: var foundsomething=0;
3400: var founduname=0;
3401: var foundID=0;
3402: for (i=0;i<=vf.nfields.value;i++) {
3403: tw=eval('vf.f'+i+'.selectedIndex');
3404: if (i==0 && tw!=0) { foundID=1; }
3405: if (i==1 && tw!=0) { founduname=1; }
3406: if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
3407: }
3408: if (founduname==0 && foundID==0) {
3409: alert('$error1');
3410: return;
3411: }
3412: if (foundsomething==0) {
3413: alert('$error2');
3414: return;
3415: }
3416: vf.submit();
3417: }
3418: function flip(vf,tf) {
3419: var nw=eval('vf.f'+tf+'.selectedIndex');
3420: var i;
3421: for (i=0;i<=vf.nfields.value;i++) {
3422: //can not pick the same destination field for both name and domain
3423: if (((i ==0)||(i ==1)) &&
3424: ((tf==0)||(tf==1)) &&
3425: (i!=tf) &&
3426: (eval('vf.f'+i+'.selectedIndex')==nw)) {
3427: eval('vf.f'+i+'.selectedIndex=0;')
3428: }
3429: }
3430: }
3431: ENDPICK
3432: }
3433:
3434: sub csvupload_javascript_forward_associate {
3435: my $error1=&mt('You need to specify the username or ID');
3436: my $error2=&mt('You need to specify at least one grading field');
3437: return(<<ENDPICK);
3438: function verify(vf) {
3439: var foundsomething=0;
3440: var founduname=0;
3441: var foundID=0;
3442: for (i=0;i<=vf.nfields.value;i++) {
3443: tw=eval('vf.f'+i+'.selectedIndex');
3444: if (tw==1) { foundID=1; }
3445: if (tw==2) { founduname=1; }
3446: if (tw>3) { foundsomething=1; }
3447: }
3448: if (founduname==0 && foundID==0) {
3449: alert('$error1');
3450: return;
3451: }
3452: if (foundsomething==0) {
3453: alert('$error2');
3454: return;
3455: }
3456: vf.submit();
3457: }
3458: function flip(vf,tf) {
3459: var nw=eval('vf.f'+tf+'.selectedIndex');
3460: var i;
3461: //can not pick the same destination field twice
3462: for (i=0;i<=vf.nfields.value;i++) {
3463: if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
3464: eval('vf.f'+i+'.selectedIndex=0;')
3465: }
3466: }
3467: }
3468: ENDPICK
3469: }
3470:
3471: sub csvuploadmap_header {
3472: my ($request,$symb,$datatoken,$distotal)= @_;
3473: my $javascript;
3474: if ($env{'form.upfile_associate'} eq 'reverse') {
3475: $javascript=&csvupload_javascript_reverse_associate();
3476: } else {
3477: $javascript=&csvupload_javascript_forward_associate();
3478: }
3479:
3480: my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
3481: my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
3482: my $ignore=&mt('Ignore First Line');
3483: $symb = &Apache::lonenc::check_encrypt($symb);
3484: $request->print(<<ENDPICK);
3485: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3486: <h3><span class="LC_info">Uploading Class Grades</span></h3>
3487: $result
3488: <hr />
3489: <h3>Identify fields</h3>
3490: Total number of records found in file: $distotal <hr />
3491: Enter as many fields as you can. The system will inform you and bring you back
3492: to this page if the data selected is insufficient to run your class.<hr />
3493: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
3494: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
3495: <input type="hidden" name="associate" value="" />
3496: <input type="hidden" name="phase" value="three" />
3497: <input type="hidden" name="datatoken" value="$datatoken" />
3498: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
3499: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
3500: <input type="hidden" name="upfile_associate"
3501: value="$env{'form.upfile_associate'}" />
3502: <input type="hidden" name="symb" value="$symb" />
3503: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
3504: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
3505: <input type="hidden" name="command" value="csvuploadoptions" />
3506: <hr />
3507: <script type="text/javascript" language="Javascript">
3508: $javascript
3509: </script>
3510: ENDPICK
3511: return '';
3512:
3513: }
3514:
3515: sub csvupload_fields {
3516: my ($symb) = @_;
3517: my (@parts) = &getpartlist($symb);
3518: my @fields=(['ID','Student ID'],
3519: ['username','Student Username'],
3520: ['domain','Student Domain']);
3521: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3522: foreach my $part (sort(@parts)) {
3523: my @datum;
3524: my $display=&Apache::lonnet::metadata($url,$part.'.display');
3525: my $name=$part;
3526: if (!$display) { $display = $name; }
3527: @datum=($name,$display);
3528: if ($name=~/^stores_(.*)_awarded/) {
3529: push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
3530: }
3531: push(@fields,\@datum);
3532: }
3533: return (@fields);
3534: }
3535:
3536: sub csvuploadmap_footer {
3537: my ($request,$i,$keyfields) =@_;
3538: $request->print(<<ENDPICK);
3539: </table>
3540: <input type="hidden" name="nfields" value="$i" />
3541: <input type="hidden" name="keyfields" value="$keyfields" />
3542: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
3543: </form>
3544: ENDPICK
3545: }
3546:
3547: sub checkforfile_js {
3548: my $result =<<CSVFORMJS;
3549: <script type="text/javascript" language="javascript">
3550: function checkUpload(formname) {
3551: if (formname.upfile.value == "") {
3552: alert("Please use the browse button to select a file from your local directory.");
3553: return false;
3554: }
3555: formname.submit();
3556: }
3557: </script>
3558: CSVFORMJS
3559: return $result;
3560: }
3561:
3562: sub upcsvScores_form {
3563: my ($request) = shift;
3564: my ($symb)=&get_symb($request);
3565: if (!$symb) {return '';}
3566: my $result=&checkforfile_js();
3567: $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
3568: my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
3569: $result.=$table;
3570: $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
3571: $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
3572: $result.=' <b>'.&mt('Specify a file containing the class scores for current resource').
3573: '.</b></td></tr>'."\n";
3574: $result.='<tr bgcolor=#ffffe6><td>'."\n";
3575: my $upload=&mt("Upload Scores");
3576: my $upfile_select=&Apache::loncommon::upfile_select_html();
3577: my $ignore=&mt('Ignore First Line');
3578: $symb = &Apache::lonenc::check_encrypt($symb);
3579: $result.=<<ENDUPFORM;
3580: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3581: <input type="hidden" name="symb" value="$symb" />
3582: <input type="hidden" name="command" value="csvuploadmap" />
3583: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
3584: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
3585: $upfile_select
3586: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
3587: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
3588: </form>
3589: ENDUPFORM
3590: $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
3591: &mt("How do I create a CSV file from a spreadsheet"))
3592: .'</td></tr></table>'."\n";
3593: $result.='</td></tr></table><br /><br />'."\n";
3594: $result.=&show_grading_menu_form($symb);
3595: return $result;
3596: }
3597:
3598:
3599: sub csvuploadmap {
3600: my ($request)= @_;
3601: my ($symb)=&get_symb($request);
3602: if (!$symb) {return '';}
3603:
3604: my $datatoken;
3605: if (!$env{'form.datatoken'}) {
3606: $datatoken=&Apache::loncommon::upfile_store($request);
3607: } else {
3608: $datatoken=$env{'form.datatoken'};
3609: &Apache::loncommon::load_tmp_file($request);
3610: }
3611: my @records=&Apache::loncommon::upfile_record_sep();
3612: if ($env{'form.noFirstLine'}) { shift(@records); }
3613: &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
3614: my ($i,$keyfields);
3615: if (@records) {
3616: my @fields=&csvupload_fields($symb);
3617:
3618: if ($env{'form.upfile_associate'} eq 'reverse') {
3619: &Apache::loncommon::csv_print_samples($request,\@records);
3620: $i=&Apache::loncommon::csv_print_select_table($request,\@records,
3621: \@fields);
3622: foreach (@fields) { $keyfields.=$_->[0].','; }
3623: chop($keyfields);
3624: } else {
3625: unshift(@fields,['none','']);
3626: $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
3627: \@fields);
3628: foreach my $rec (@records) {
3629: my %temp = &Apache::loncommon::record_sep($rec);
3630: if (%temp) {
3631: $keyfields=join(',',sort(keys(%temp)));
3632: last;
3633: }
3634: }
3635: }
3636: }
3637: &csvuploadmap_footer($request,$i,$keyfields);
3638: $request->print(&show_grading_menu_form($symb));
3639:
3640: return '';
3641: }
3642:
3643: sub csvuploadoptions {
3644: my ($request)= @_;
3645: my ($symb)=&get_symb($request);
3646: my $checked=(($env{'form.noFirstLine'})?'1':'0');
3647: my $ignore=&mt('Ignore First Line');
3648: $request->print(<<ENDPICK);
3649: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3650: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
3651: <input type="hidden" name="command" value="csvuploadassign" />
3652: <!--
3653: <p>
3654: <label>
3655: <input type="checkbox" name="show_full_results" />
3656: Show a table of all changes
3657: </label>
3658: </p>
3659: -->
3660: <p>
3661: <label>
3662: <input type="checkbox" name="overwite_scores" checked="checked" />
3663: Overwrite any existing score
3664: </label>
3665: </p>
3666: ENDPICK
3667: my %fields=&get_fields();
3668: if (!defined($fields{'domain'})) {
3669: my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
3670: $request->print("\n<p> Users are in domain: ".$domform."</p>\n");
3671: }
3672: foreach my $key (sort(keys(%env))) {
3673: if ($key !~ /^form\.(.*)$/) { next; }
3674: my $cleankey=$1;
3675: if ($cleankey eq 'command') { next; }
3676: $request->print('<input type="hidden" name="'.$cleankey.
3677: '" value="'.$env{$key}.'" />'."\n");
3678: }
3679: # FIXME do a check for any duplicated user ids...
3680: # FIXME do a check for any invalid user ids?...
3681: $request->print('<input type="submit" value="Assign Grades" /><br />
3682: <hr /></form>'."\n");
3683: $request->print(&show_grading_menu_form($symb));
3684: return '';
3685: }
3686:
3687: sub get_fields {
3688: my %fields;
3689: my @keyfields = split(/\,/,$env{'form.keyfields'});
3690: for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
3691: if ($env{'form.upfile_associate'} eq 'reverse') {
3692: if ($env{'form.f'.$i} ne 'none') {
3693: $fields{$keyfields[$i]}=$env{'form.f'.$i};
3694: }
3695: } else {
3696: if ($env{'form.f'.$i} ne 'none') {
3697: $fields{$env{'form.f'.$i}}=$keyfields[$i];
3698: }
3699: }
3700: }
3701: return %fields;
3702: }
3703:
3704: sub csvuploadassign {
3705: my ($request)= @_;
3706: my ($symb)=&get_symb($request);
3707: if (!$symb) {return '';}
3708: my $error_msg = '';
3709: &Apache::loncommon::load_tmp_file($request);
3710: my @gradedata = &Apache::loncommon::upfile_record_sep();
3711: if ($env{'form.noFirstLine'}) { shift(@gradedata); }
3712: my %fields=&get_fields();
3713: $request->print('<h3>Assigning Grades</h3>');
3714: my $courseid=$env{'request.course.id'};
3715: my ($classlist) = &getclasslist('all',0);
3716: my @notallowed;
3717: my @skipped;
3718: my $countdone=0;
3719: foreach my $grade (@gradedata) {
3720: my %entries=&Apache::loncommon::record_sep($grade);
3721: my $domain;
3722: if ($entries{$fields{'domain'}}) {
3723: $domain=$entries{$fields{'domain'}};
3724: } else {
3725: $domain=$env{'form.default_domain'};
3726: }
3727: $domain=~s/\s//g;
3728: my $username=$entries{$fields{'username'}};
3729: $username=~s/\s//g;
3730: if (!$username) {
3731: my $id=$entries{$fields{'ID'}};
3732: $id=~s/\s//g;
3733: my %ids=&Apache::lonnet::idget($domain,$id);
3734: $username=$ids{$id};
3735: }
3736: if (!exists($$classlist{"$username:$domain"})) {
3737: my $id=$entries{$fields{'ID'}};
3738: $id=~s/\s//g;
3739: if ($id) {
3740: push(@skipped,"$id:$domain");
3741: } else {
3742: push(@skipped,"$username:$domain");
3743: }
3744: next;
3745: }
3746: my $usec=$classlist->{"$username:$domain"}[5];
3747: if (!&canmodify($usec)) {
3748: push(@notallowed,"$username:$domain");
3749: next;
3750: }
3751: my %points;
3752: my %grades;
3753: foreach my $dest (keys(%fields)) {
3754: if ($dest eq 'ID' || $dest eq 'username' ||
3755: $dest eq 'domain') { next; }
3756: if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
3757: if ($dest=~/stores_(.*)_points/) {
3758: my $part=$1;
3759: my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
3760: $symb,$domain,$username);
3761: if ($wgt) {
3762: $entries{$fields{$dest}}=~s/\s//g;
3763: my $pcr=$entries{$fields{$dest}} / $wgt;
3764: my $award='correct_by_override';
3765: $grades{"resource.$part.awarded"}=$pcr;
3766: $grades{"resource.$part.solved"}=$award;
3767: $points{$part}=1;
3768: } else {
3769: $error_msg = "<br />" .
3770: &mt("Some point values were assigned"
3771: ." for problems with a weight "
3772: ."of zero. These values were "
3773: ."ignored.");
3774: }
3775: } else {
3776: if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
3777: if ($dest=~/stores_(.*)_solved/) { if ($points{$1}) {next;} }
3778: my $store_key=$dest;
3779: $store_key=~s/^stores/resource/;
3780: $store_key=~s/_/\./g;
3781: $grades{$store_key}=$entries{$fields{$dest}};
3782: }
3783: }
3784: if (! %grades) { push(@skipped,"$username:$domain no data to save"); }
3785: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
3786: # &Apache::lonnet::logthis(" storing ".(join('-',%grades)));
3787: my $result=&Apache::lonnet::cstore(\%grades,$symb,
3788: $env{'request.course.id'},
3789: $domain,$username);
3790: if ($result eq 'ok') {
3791: $request->print('.');
3792: } else {
3793: $request->print("<p>
3794: <span class=\"LC_error\">
3795: Failed to save student $username:$domain.
3796: Message when trying to save was ($result)
3797: </span>
3798: </p>" );
3799: }
3800: $request->rflush();
3801: $countdone++;
3802: }
3803: $request->print("<br />Saved $countdone students\n");
3804: if (@skipped) {
3805: $request->print('<p><h4><b>Skipped Students</b></h4></p>');
3806: foreach my $student (@skipped) { $request->print("$student<br />\n"); }
3807: }
3808: if (@notallowed) {
3809: $request->print('<p><span class="LC_error">Students Not Allowed to Modify</span></p>');
3810: foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
3811: }
3812: $request->print("<br />\n");
3813: $request->print(&show_grading_menu_form($symb));
3814: return $error_msg;
3815: }
3816: #------------- end of section for handling csv file upload ---------
3817: #
3818: #-------------------------------------------------------------------
3819: #
3820: #-------------- Next few routines handle grading by page/sequence
3821: #
3822: #--- Select a page/sequence and a student to grade
3823: sub pickStudentPage {
3824: my ($request) = shift;
3825:
3826: $request->print(<<LISTJAVASCRIPT);
3827: <script type="text/javascript" language="javascript">
3828:
3829: function checkPickOne(formname) {
3830: if (radioSelection(formname.student) == null) {
3831: alert("Please select the student you wish to grade.");
3832: return;
3833: }
3834: ptr = pullDownSelection(formname.selectpage);
3835: formname.page.value = formname["page"+ptr].value;
3836: formname.title.value = formname["title"+ptr].value;
3837: formname.submit();
3838: }
3839:
3840: </script>
3841: LISTJAVASCRIPT
3842: &commonJSfunctions($request);
3843: my ($symb) = &get_symb($request);
3844: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
3845: my $cnum = $env{"course.$env{'request.course.id'}.num"};
3846: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
3847:
3848: my $result='<h3><span class="LC_info"> '.
3849: 'Manual Grading by Page or Sequence</span></h3>';
3850:
3851: $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
3852: $result.=' <b>Problems from:</b> <select name="selectpage">'."\n";
3853: my ($titles,$symbx) = &getSymbMap();
3854: my ($curpage) =&Apache::lonnet::decode_symb($symb);
3855: # my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb);
3856: # my $type=($curpage =~ /\.(page|sequence)/);
3857: my $ctr=0;
3858: foreach (@$titles) {
3859: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
3860: $result.='<option value="'.$ctr.'" '.
3861: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
3862: '>'.$showtitle.'</option>'."\n";
3863: $ctr++;
3864: }
3865: $result.= '</select>'."<br />\n";
3866: $ctr=0;
3867: foreach (@$titles) {
3868: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
3869: $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
3870: $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
3871: $ctr++;
3872: }
3873: $result.='<input type="hidden" name="page" />'."\n".
3874: '<input type="hidden" name="title" />'."\n";
3875:
3876: $result.=' <b>View Problems Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
3877: '<label><input type="radio" name="vProb" value="yes" /> yes </label>'."<br />\n";
3878:
3879: $result.=' <b>Submission Details: </b>'.
3880: '<label><input type="radio" name="lastSub" value="none" /> none</label>'."\n".
3881: '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> by dates and submissions</label>'."\n".
3882: '<label><input type="radio" name="lastSub" value="all" /> all details</label>'."\n";
3883:
3884: $result.=&build_section_inputs();
3885: $result.='<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n".
3886: '<input type="hidden" name="command" value="displayPage" />'."\n".
3887: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
3888: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
3889:
3890: $result.=' <b>'.&mt('Use CODE:').' </b>'.
3891: '<input type="text" name="CODE" value="" /><br />'."\n";
3892:
3893: $result.=' <input type="button" '.
3894: 'onClick="javascript:checkPickOne(this.form);"value="Next->" /><br />'."\n";
3895:
3896: $request->print($result);
3897:
3898: my $studentTable.=' <b>Select a student you wish to grade and then click on the Next button.</b><br />'.
3899: '<table border="0"><tr><td bgcolor="#777777">'.
3900: '<table border="0"><tr bgcolor="#e6ffff">'.
3901: '<td align="right"> <b>No.</b></td>'.
3902: '<td>'.&nameUserString('header').'</td>'.
3903: '<td align="right"> <b>No.</b></td>'.
3904: '<td>'.&nameUserString('header').'</td></tr>';
3905:
3906: my (undef,undef,$fullname) = &getclasslist($getsec,'1');
3907: my $ptr = 1;
3908: foreach my $student (sort
3909: {
3910: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
3911: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
3912: }
3913: return $a cmp $b;
3914: } (keys(%$fullname))) {
3915: my ($uname,$udom) = split(/:/,$student);
3916: $studentTable.=($ptr%2 == 1 ? '<tr bgcolor="#ffffe6">' : '</td>');
3917: $studentTable.='<td align="right">'.$ptr.' </td>';
3918: $studentTable.='<td> <label><input type="radio" name="student" value="'.$student.'" /> '
3919: .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
3920: $studentTable.=($ptr%2 == 0 ? '</td></tr>' : '');
3921: $ptr++;
3922: }
3923: $studentTable.='</td><td> </td><td> </td></tr>' if ($ptr%2 == 0);
3924: $studentTable.='</table></td></tr></table>'."\n";
3925: $studentTable.='<input type="button" '.
3926: 'onClick="javascript:checkPickOne(this.form);"value="Next->" /></form>'."\n";
3927:
3928: $studentTable.=&show_grading_menu_form($symb);
3929: $request->print($studentTable);
3930:
3931: return '';
3932: }
3933:
3934: sub getSymbMap {
3935: my $navmap = Apache::lonnavmaps::navmap->new();
3936:
3937: my %symbx = ();
3938: my @titles = ();
3939: my $minder = 0;
3940:
3941: # Gather every sequence that has problems.
3942: my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
3943: 1,0,1);
3944: for my $sequence ($navmap->getById('0.0'), @sequences) {
3945: if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
3946: my $title = $minder.'.'.
3947: &HTML::Entities::encode($sequence->compTitle(),'"\'&');
3948: push(@titles, $title); # minder in case two titles are identical
3949: $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
3950: $minder++;
3951: }
3952: }
3953: return \@titles,\%symbx;
3954: }
3955:
3956: #
3957: #--- Displays a page/sequence w/wo problems, w/wo submissions
3958: sub displayPage {
3959: my ($request) = shift;
3960:
3961: my ($symb) = &get_symb($request);
3962: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
3963: my $cnum = $env{"course.$env{'request.course.id'}.num"};
3964: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
3965: my $pageTitle = $env{'form.page'};
3966: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
3967: my ($uname,$udom) = split(/:/,$env{'form.student'});
3968: my $usec=$classlist->{$env{'form.student'}}[5];
3969:
3970: #need to make sure we have the correct data for later EXT calls,
3971: #thus invalidate the cache
3972: &Apache::lonnet::devalidatecourseresdata(
3973: $env{'course.'.$env{'request.course.id'}.'.num'},
3974: $env{'course.'.$env{'request.course.id'}.'.domain'});
3975: &Apache::lonnet::clear_EXT_cache_status();
3976:
3977: if (!&canview($usec)) {
3978: $request->print('<span class="LC_warning">Unable to view requested student.('.$env{'form.student'}.')</span>');
3979: $request->print(&show_grading_menu_form($symb));
3980: return;
3981: }
3982: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
3983: $result.='<h3> Student: '.&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom).
3984: '</h3>'."\n";
3985: if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
3986: $result.='<h3> CODE: '.$env{'form.CODE'}.'</h3>'."\n";
3987: } else {
3988: delete($env{'form.CODE'});
3989: }
3990: &sub_page_js($request);
3991: $request->print($result);
3992:
3993: my $navmap = Apache::lonnavmaps::navmap->new();
3994: my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
3995: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
3996: if (!$map) {
3997: $request->print('<span class="LC_warning">Unable to view requested sequence. ('.$resUrl.')</span>');
3998: $request->print(&show_grading_menu_form($symb));
3999: return;
4000: }
4001: my $iterator = $navmap->getIterator($map->map_start(),
4002: $map->map_finish());
4003:
4004: my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
4005: '<input type="hidden" name="command" value="gradeByPage" />'."\n".
4006: '<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
4007: '<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
4008: '<input type="hidden" name="page" value="'.$pageTitle.'" />'."\n".
4009: '<input type="hidden" name="title" value="'.$env{'form.title'}.'" />'."\n".
4010: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
4011: '<input type="hidden" name="overRideScore" value="no" />'."\n".
4012: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
4013:
4014: if (defined($env{'form.CODE'})) {
4015: $studentTable.=
4016: '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
4017: }
4018: my $checkIcon = '<img alt="'.&mt('Check Mark').
4019: '" src="'.$request->dir_config('lonIconsURL').
4020: '/check.gif" height="16" border="0" />';
4021:
4022: $studentTable.=' <b>Note:</b> Problems graded correct by the computer are marked with a '.$checkIcon.
4023: ' symbol.'."\n".
4024: '<table border="0"><tr><td bgcolor="#777777">'.
4025: '<table border="0"><tr bgcolor="#e6ffff">'.
4026: '<td align="center"><b> Prob. </b></td>'.
4027: '<td><b> '.($env{'form.vProb'} eq 'no' ? 'Title' : 'Problem Text').'/Grade</b></td></tr>';
4028:
4029: &Apache::lonxml::clear_problem_counter();
4030: my ($depth,$question,$prob) = (1,1,1);
4031: $iterator->next(); # skip the first BEGIN_MAP
4032: my $curRes = $iterator->next(); # for "current resource"
4033: while ($depth > 0) {
4034: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
4035: if($curRes == $iterator->END_MAP) { $depth--; }
4036:
4037: if (ref($curRes) && $curRes->is_problem()) {
4038: my $parts = $curRes->parts();
4039: my $title = $curRes->compTitle();
4040: my $symbx = $curRes->symb();
4041: $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
4042: (scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).' parts)').'</td>';
4043: $studentTable.='<td valign="top">';
4044: my %form = ('CODE' => $env{'form.CODE'},);
4045: if ($env{'form.vProb'} eq 'yes' ) {
4046: $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
4047: undef,'both',\%form);
4048: } else {
4049: my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
4050: $companswer =~ s|<form(.*?)>||g;
4051: $companswer =~ s|</form>||g;
4052: # while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
4053: # $companswer =~ s/$1/ /ms;
4054: # $request->print('match='.$1."<br />\n");
4055: # }
4056: # $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
4057: $studentTable.=' <b>'.$title.'</b> <br /> <b>Correct answer:</b><br />'.$companswer;
4058: }
4059:
4060: my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
4061:
4062: if ($env{'form.lastSub'} eq 'datesub') {
4063: if ($record{'version'} eq '') {
4064: $studentTable.='<br /> <span class="LC_warning">No recorded submission for this problem</span><br />';
4065: } else {
4066: my %responseType = ();
4067: foreach my $partid (@{$parts}) {
4068: my @responseIds =$curRes->responseIds($partid);
4069: my @responseType =$curRes->responseType($partid);
4070: my %responseIds;
4071: for (my $i=0;$i<=$#responseIds;$i++) {
4072: $responseIds{$responseIds[$i]}=$responseType[$i];
4073: }
4074: $responseType{$partid} = \%responseIds;
4075: }
4076: $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
4077:
4078: }
4079: } elsif ($env{'form.lastSub'} eq 'all') {
4080: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
4081: $studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
4082: $env{'request.course.id'},
4083: '','.submission');
4084:
4085: }
4086: if (&canmodify($usec)) {
4087: foreach my $partid (@{$parts}) {
4088: $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
4089: $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
4090: $question++;
4091: }
4092: $prob++;
4093: }
4094: $studentTable.='</td></tr>';
4095:
4096: }
4097: $curRes = $iterator->next();
4098: }
4099:
4100: $studentTable.='</table></td></tr></table>'."\n".
4101: '<input type="button" value="Save" '.
4102: 'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
4103: '</form>'."\n";
4104: $studentTable.=&show_grading_menu_form($symb);
4105: $request->print($studentTable);
4106:
4107: return '';
4108: }
4109:
4110: sub displaySubByDates {
4111: my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
4112: my $isCODE=0;
4113: my $isTask = ($symb =~/\.task$/);
4114: if (exists($record->{'resource.CODE'})) { $isCODE=1; }
4115: my $studentTable='<table border="0" width="100%"><tr><td bgcolor="#777777">'.
4116: '<table border="0" width="100%"><tr bgcolor="#e6ffff">'.
4117: '<td><b>Date/Time</b></td>'.
4118: ($isCODE?'<td><b>CODE</b></td>':'').
4119: '<td><b>Submission</b></td>'.
4120: '<td><b>Status </b></td></tr>';
4121: my ($version);
4122: my %mark;
4123: my %orders;
4124: $mark{'correct_by_student'} = $checkIcon;
4125: if (!exists($$record{'1:timestamp'})) {
4126: return '<br /> <span class="LC_warning">Nothing submitted - no attempts</span><br />';
4127: }
4128:
4129: my $interaction;
4130: for ($version=1;$version<=$$record{'version'};$version++) {
4131: my $timestamp = scalar(localtime($$record{$version.':timestamp'}));
4132: if (exists($$record{$version.':resource.0.version'})) {
4133: $interaction = $$record{$version.':resource.0.version'};
4134: }
4135:
4136: my $where = ($isTask ? "$version:resource.$interaction"
4137: : "$version:resource");
4138: #&Apache::lonnet::logthis(" got $where");
4139: $studentTable.='<tr bgcolor="#ffffff" valign="top"><td>'.$timestamp.'</td>';
4140: if ($isCODE) {
4141: $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
4142: }
4143: my @versionKeys = split(/\:/,$$record{$version.':keys'});
4144: my @displaySub = ();
4145: foreach my $partid (@{$parts}) {
4146: my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
4147: : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
4148:
4149:
4150: # next if ($$record{"$version:resource.$partid.solved"} eq '');
4151: my $display_part=&get_display_part($partid,$symb);
4152: foreach my $matchKey (@matchKey) {
4153: if (exists($$record{$version.':'.$matchKey}) &&
4154: $$record{$version.':'.$matchKey} ne '') {
4155:
4156: my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
4157: : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
4158: #&Apache::lonnet::logthis("match $matchKey $responseId (".$$record{$version.':'.$matchKey});
4159: $displaySub[0].='<b>Part:</b> '.$display_part.' ';
4160: $displaySub[0].='<span class="LC_internal_info">(ID '.
4161: $responseId.')</span> <b>';
4162: if ($$record{"$where.$partid.tries"} eq '') {
4163: $displaySub[0].='Trial not counted';
4164: } else {
4165: $displaySub[0].='Trial '.
4166: $$record{"$where.$partid.tries"};
4167: }
4168: my $responseType=($isTask ? 'Task'
4169: : $responseType->{$partid}->{$responseId});
4170: if (!exists($orders{$partid})) { $orders{$partid}={}; }
4171: if (!exists($orders{$partid}->{$responseId})) {
4172: $orders{$partid}->{$responseId}=
4173: &get_order($partid,$responseId,$symb,$uname,$udom);
4174: }
4175: $displaySub[0].='</b> '.
4176: &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
4177: }
4178: }
4179: if (exists($$record{"$where.$partid.checkedin"})) {
4180: $displaySub[1].='Checked in by '.
4181: $$record{"$where.$partid.checkedin"}.' into slot '.
4182: $$record{"$where.$partid.checkedin.slot"}.
4183: '<br />';
4184: }
4185: if (exists $$record{"$where.$partid.award"}) {
4186: $displaySub[1].='<b>Part:</b> '.$display_part.' '.
4187: lc($$record{"$where.$partid.award"}).' '.
4188: $mark{$$record{"$where.$partid.solved"}}.
4189: '<br />';
4190: }
4191: if (exists $$record{"$where.$partid.regrader"}) {
4192: $displaySub[2].=$$record{"$where.$partid.regrader"}.
4193: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
4194: } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
4195: $displaySub[2].=
4196: $$record{"$version:resource.$partid.regrader"}.
4197: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
4198: }
4199: }
4200: # needed because old essay regrader has not parts info
4201: if (exists $$record{"$version:resource.regrader"}) {
4202: $displaySub[2].=$$record{"$version:resource.regrader"};
4203: }
4204: $studentTable.='<td>'.$displaySub[0].' </td><td>'.$displaySub[1];
4205: if ($displaySub[2]) {
4206: $studentTable.='Manually graded by '.$displaySub[2];
4207: }
4208: $studentTable.=' </td></tr>';
4209:
4210: }
4211: $studentTable.='</table></td></tr></table>';
4212: return $studentTable;
4213: }
4214:
4215: sub updateGradeByPage {
4216: my ($request) = shift;
4217:
4218: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4219: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4220: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4221: my $pageTitle = $env{'form.page'};
4222: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
4223: my ($uname,$udom) = split(/:/,$env{'form.student'});
4224: my $usec=$classlist->{$env{'form.student'}}[5];
4225: if (!&canmodify($usec)) {
4226: $request->print('<span class="LC_warning">Unable to modify requested student.('.$env{'form.student'}.'</span>');
4227: $request->print(&show_grading_menu_form($env{'form.symb'}));
4228: return;
4229: }
4230: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
4231: $result.='<h3> Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
4232: '</h3>'."\n";
4233:
4234: $request->print($result);
4235:
4236: my $navmap = Apache::lonnavmaps::navmap->new();
4237: my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
4238: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
4239: if (!$map) {
4240: $request->print('<span class="LC_warning">Unable to grade requested sequence. ('.$resUrl.')</span>');
4241: my ($symb)=&get_symb($request);
4242: $request->print(&show_grading_menu_form($symb));
4243: return;
4244: }
4245: my $iterator = $navmap->getIterator($map->map_start(),
4246: $map->map_finish());
4247:
4248: my $studentTable='<table border="0"><tr><td bgcolor="#777777">'.
4249: '<table border="0"><tr bgcolor="#e6ffff">'.
4250: '<td align="center"><b> Prob. </b></td>'.
4251: '<td><b> Title </b></td>'.
4252: '<td><b> Previous Score </b></td>'.
4253: '<td><b> New Score </b></td></tr>';
4254:
4255: $iterator->next(); # skip the first BEGIN_MAP
4256: my $curRes = $iterator->next(); # for "current resource"
4257: my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
4258: while ($depth > 0) {
4259: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
4260: if($curRes == $iterator->END_MAP) { $depth--; }
4261:
4262: if (ref($curRes) && $curRes->is_problem()) {
4263: my $parts = $curRes->parts();
4264: my $title = $curRes->compTitle();
4265: my $symbx = $curRes->symb();
4266: $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
4267: (scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).' parts)').'</td>';
4268: $studentTable.='<td valign="top"> <b>'.$title.'</b> </td>';
4269:
4270: my %newrecord=();
4271: my @displayPts=();
4272: my %aggregate = ();
4273: my $aggregateflag = 0;
4274: foreach my $partid (@{$parts}) {
4275: my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
4276: my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
4277:
4278: my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ?
4279: $env{'form.WGT'.$question.'_'.$partid} : 1;
4280: my $partial = $newpts/$wgt;
4281: my $score;
4282: if ($partial > 0) {
4283: $score = 'correct_by_override';
4284: } elsif ($newpts ne '') { #empty is taken as 0
4285: $score = 'incorrect_by_override';
4286: }
4287: my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
4288: if ($dropMenu eq 'excused') {
4289: $partial = '';
4290: $score = 'excused';
4291: } elsif ($dropMenu eq 'reset status'
4292: && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
4293: $newrecord{'resource.'.$partid.'.tries'} = 0;
4294: $newrecord{'resource.'.$partid.'.solved'} = '';
4295: $newrecord{'resource.'.$partid.'.award'} = '';
4296: $newrecord{'resource.'.$partid.'.awarded'} = 0;
4297: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
4298: $changeflag++;
4299: $newpts = '';
4300:
4301: my $aggtries = $env{'form.aggtries'.$question.'_'.$partid};
4302: my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
4303: my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
4304: if ($aggtries > 0) {
4305: &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
4306: $aggregateflag = 1;
4307: }
4308: }
4309: my $display_part=&get_display_part($partid,$curRes->symb());
4310: my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
4311: $displayPts[0].=' <b>Part:</b> '.$display_part.' = '.
4312: (($oldstatus eq 'excused') ? 'excused' : $oldpts).
4313: ' <br />';
4314: $displayPts[1].=' <b>Part:</b> '.$display_part.' = '.
4315: (($score eq 'excused') ? 'excused' : $newpts).
4316: ' <br />';
4317: $question++;
4318: next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
4319:
4320: $newrecord{'resource.'.$partid.'.awarded'} = $partial if $partial ne '';
4321: $newrecord{'resource.'.$partid.'.solved'} = $score if $score ne '';
4322: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
4323: if (scalar(keys(%newrecord)) > 0);
4324:
4325: $changeflag++;
4326: }
4327: if (scalar(keys(%newrecord)) > 0) {
4328: my %record =
4329: &Apache::lonnet::restore($symbx,$env{'request.course.id'},
4330: $udom,$uname);
4331:
4332: if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
4333: $newrecord{'resource.CODE'} = $env{'form.CODE'};
4334: } elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
4335: $newrecord{'resource.CODE'} = '';
4336: }
4337: &Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
4338: $udom,$uname);
4339: %record = &Apache::lonnet::restore($symbx,
4340: $env{'request.course.id'},
4341: $udom,$uname);
4342: &check_and_remove_from_queue($parts,\%record,undef,$symbx,
4343: $cdom,$cnum,$udom,$uname);
4344: }
4345:
4346: if ($aggregateflag) {
4347: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
4348: $env{'course.'.$env{'request.course.id'}.'.domain'},
4349: $env{'course.'.$env{'request.course.id'}.'.num'});
4350: }
4351:
4352: $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
4353: '<td valign="top">'.$displayPts[1].'</td>'.
4354: '</tr>';
4355:
4356: $prob++;
4357: }
4358: $curRes = $iterator->next();
4359: }
4360:
4361: $studentTable.='</td></tr></table></td></tr></table>';
4362: $studentTable.=&show_grading_menu_form($env{'form.symb'});
4363: my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
4364: 'The scores were changed for '.
4365: $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
4366: $request->print($grademsg.$studentTable);
4367:
4368: return '';
4369: }
4370:
4371: #-------- end of section for handling grading by page/sequence ---------
4372: #
4373: #-------------------------------------------------------------------
4374:
4375: #--------------------Scantron Grading-----------------------------------
4376: #
4377: #------ start of section for handling grading by page/sequence ---------
4378:
4379: =pod
4380:
4381: =head1 Bubble sheet grading routines
4382:
4383: For this documentation:
4384:
4385: 'scanline' refers to the full line of characters
4386: from the file that we are parsing that represents one entire sheet
4387:
4388: 'bubble line' refers to the data
4389: representing the line of bubbles that are on the physical bubble sheet
4390:
4391:
4392: The overall process is that a scanned in bubble sheet data is uploaded
4393: into a course. When a user wants to grade, they select a
4394: sequence/folder of resources, a file of bubble sheet info, and pick
4395: one of the predefined configurations for what each scanline looks
4396: like.
4397:
4398: Next each scanline is checked for any errors of either 'missing
4399: bubbles' (it's an error because it may have been missed scanned
4400: because too light bubbling), 'double bubble' (each bubble line should
4401: have no more that one letter picked), invalid or duplicated CODE,
4402: invalid student ID
4403:
4404: If the CODE option is used that determines the randomization of the
4405: homework problems, either way the student ID is looked up into a
4406: username:domain.
4407:
4408: During the validation phase the instructor can choose to skip scanlines.
4409:
4410: After the validation phase, there is now 3 bubble sheet files
4411:
4412: scantron_original_filename (unmodified original file)
4413: scantron_corrected_filename (file where the corrected information has replaced the original information)
4414: scantron_skipped_filename (contains the exact text of scanlines that where skipped)
4415:
4416: Also there is a separate hash nohist_scantrondata that contains extra
4417: correction information that isn't representable in the bubble sheet
4418: file (see &scantron_getfile() for more information)
4419:
4420: After all scanlines are either valid, marked as valid or skipped, then
4421: foreach line foreach problem in the picked sequence, an ssi request is
4422: made that simulates a user submitting their selected letter(s) against
4423: the homework problem.
4424:
4425: =over 4
4426:
4427: =cut
4428:
4429:
4430: =pod
4431:
4432: =item defaultFormData
4433:
4434: Returns html hidden inputs used to hold context/default values.
4435:
4436: Arguments:
4437: $symb - $symb of the current resource
4438:
4439: =cut
4440:
4441: sub defaultFormData {
4442: my ($symb)=@_;
4443: return '
4444: <input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
4445: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
4446: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
4447: }
4448:
4449: =pod
4450:
4451: =item getSequenceDropDown
4452:
4453: Return html dropdown of possible sequences to grade
4454:
4455: Arguments:
4456: $symb - $symb of the current resource
4457:
4458: =cut
4459:
4460: sub getSequenceDropDown {
4461: my ($symb)=@_;
4462: my $result='<select name="selectpage">'."\n";
4463: my ($titles,$symbx) = &getSymbMap();
4464: my ($curpage)=&Apache::lonnet::decode_symb($symb);
4465: my $ctr=0;
4466: foreach (@$titles) {
4467: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4468: $result.='<option value="'.$$symbx{$_}.'" '.
4469: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
4470: '>'.$showtitle.'</option>'."\n";
4471: $ctr++;
4472: }
4473: $result.= '</select>';
4474: return $result;
4475: }
4476:
4477:
4478: =pod
4479:
4480: =item scantron_filenames
4481:
4482: Returns a list of the scantron files in the current course
4483:
4484: =cut
4485:
4486: sub scantron_filenames {
4487: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4488: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
4489: my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
4490: &propath($cdom,$cname));
4491: my @possiblenames;
4492: foreach my $filename (sort(@files)) {
4493: ($filename)=split(/&/,$filename);
4494: if ($filename!~/^scantron_orig_/) { next ; }
4495: $filename=~s/^scantron_orig_//;
4496: push(@possiblenames,$filename);
4497: }
4498: return @possiblenames;
4499: }
4500:
4501: =pod
4502:
4503: =item scantron_uploads
4504:
4505: Returns html drop-down list of scantron files in current course.
4506:
4507: Arguments:
4508: $file2grade - filename to set as selected in the dropdown
4509:
4510: =cut
4511:
4512: sub scantron_uploads {
4513: my ($file2grade) = @_;
4514: my $result= '<select name="scantron_selectfile">';
4515: $result.="<option></option>";
4516: foreach my $filename (sort(&scantron_filenames())) {
4517: $result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
4518: }
4519: $result.="</select>";
4520: return $result;
4521: }
4522:
4523: =pod
4524:
4525: =item scantron_scantab
4526:
4527: Returns html drop down of the scantron formats in the scantronformat.tab
4528: file.
4529:
4530: =cut
4531:
4532: sub scantron_scantab {
4533: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
4534: my $result='<select name="scantron_format">'."\n";
4535: $result.='<option></option>'."\n";
4536: foreach my $line (<$fh>) {
4537: my ($name,$descrip)=split(/:/,$line);
4538: if ($name =~ /^\#/) { next; }
4539: $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
4540: }
4541: $result.='</select>'."\n";
4542:
4543: return $result;
4544: }
4545:
4546: =pod
4547:
4548: =item scantron_CODElist
4549:
4550: Returns html drop down of the saved CODE lists from current course,
4551: generated from earlier printings.
4552:
4553: =cut
4554:
4555: sub scantron_CODElist {
4556: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4557: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4558: my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
4559: my $namechoice='<option></option>';
4560: foreach my $name (sort {uc($a) cmp uc($b)} @names) {
4561: if ($name =~ /^error: 2 /) { next; }
4562: if ($name =~ /^type\0/) { next; }
4563: $namechoice.='<option value="'.$name.'">'.$name.'</option>';
4564: }
4565: $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
4566: return $namechoice;
4567: }
4568:
4569: =pod
4570:
4571: =item scantron_CODEunique
4572:
4573: Returns the html for "Each CODE to be used once" radio.
4574:
4575: =cut
4576:
4577: sub scantron_CODEunique {
4578: my $result='<span style="white-space: nowrap;">
4579: <label><input type="radio" name="scantron_CODEunique"
4580: value="yes" checked="checked" />'.&mt('Yes').' </label>
4581: </span>
4582: <span style="white-space: nowrap;">
4583: <label><input type="radio" name="scantron_CODEunique"
4584: value="no" />'.&mt('No').' </label>
4585: </span>';
4586: return $result;
4587: }
4588:
4589: =pod
4590:
4591: =item scantron_selectphase
4592:
4593: Generates the initial screen to start the bubble sheet process.
4594: Allows for - starting a grading run.
4595: - downloading existing scan data (original, corrected
4596: or skipped info)
4597:
4598: - uploading new scan data
4599:
4600: Arguments:
4601: $r - The Apache request object
4602: $file2grade - name of the file that contain the scanned data to score
4603:
4604: =cut
4605:
4606: sub scantron_selectphase {
4607: my ($r,$file2grade) = @_;
4608: my ($symb)=&get_symb($r);
4609: if (!$symb) {return '';}
4610: my $sequence_selector=&getSequenceDropDown($symb);
4611: my $default_form_data=&defaultFormData($symb);
4612: my $grading_menu_button=&show_grading_menu_form($symb);
4613: my $file_selector=&scantron_uploads($file2grade);
4614: my $format_selector=&scantron_scantab();
4615: my $CODE_selector=&scantron_CODElist();
4616: my $CODE_unique=&scantron_CODEunique();
4617: my $result;
4618:
4619: # Chunk of form to prompt for a file to grade and how:
4620:
4621: $result.= <<SCANTRONFORM;
4622: <table width="100%" border="0">
4623: <tr>
4624: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
4625: <td bgcolor="#777777">
4626: <input type="hidden" name="command" value="scantron_warning" />
4627: $default_form_data
4628: <table width="100%" border="0">
4629: <tr bgcolor="#e6ffff">
4630: <td colspan="2">
4631: <b>Specify file and which Folder/Sequence to grade</b>
4632: </td>
4633: </tr>
4634: <tr bgcolor="#ffffe6">
4635: <td> Sequence to grade: </td><td> $sequence_selector </td>
4636: </tr>
4637: <tr bgcolor="#ffffe6">
4638: <td> Filename of scoring office file: </td><td> $file_selector </td>
4639: </tr>
4640: <tr bgcolor="#ffffe6">
4641: <td> Format of data file: </td><td> $format_selector </td>
4642: </tr>
4643: <tr bgcolor="#ffffe6">
4644: <td> Saved CODEs to validate against: </td><td> $CODE_selector</td>
4645: </tr>
4646: <tr bgcolor="#ffffe6">
4647: <td> Each CODE is only to be used once:</td><td> $CODE_unique </td>
4648: </tr>
4649: <tr bgcolor="#ffffe6">
4650: <td> Options: </td>
4651: <td>
4652: <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> Do only previously skipped records</label> <br />
4653: <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> Remove all existing corrections</label> <br />
4654: <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> Skip hidden resources when grading</label>
4655: </td>
4656: </tr>
4657: <tr bgcolor="#ffffe6">
4658: <td colspan="2">
4659: <input type="submit" value="Grading: Validate Scantron Records" />
4660: </td>
4661: </tr>
4662: </table>
4663: </td>
4664: </form>
4665: </tr>
4666: SCANTRONFORM
4667:
4668: $r->print($result);
4669:
4670: if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
4671: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
4672:
4673: # Chunk of form to prompt for a scantron file upload.
4674:
4675: $r->print(<<SCANTRONFORM);
4676: <tr>
4677: <td bgcolor="#777777">
4678: <table width="100%" border="0">
4679: <tr bgcolor="#e6ffff">
4680: <td>
4681: <b>Specify a Scantron data file to upload.</b>
4682: </td>
4683: </tr>
4684: <tr bgcolor="#ffffe6">
4685: <td>
4686: SCANTRONFORM
4687: my $default_form_data=&defaultFormData(&get_symb($r,1));
4688: my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
4689: my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
4690: $r->print(<<UPLOAD);
4691: <script type="text/javascript" language="javascript">
4692: function checkUpload(formname) {
4693: if (formname.upfile.value == "") {
4694: alert("Please use the browse button to select a file from your local directory.");
4695: return false;
4696: }
4697: formname.submit();
4698: }
4699: </script>
4700:
4701: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
4702: $default_form_data
4703: <input name='courseid' type='hidden' value='$cnum' />
4704: <input name='domainid' type='hidden' value='$cdom' />
4705: <input name='command' value='scantronupload_save' type='hidden' />
4706: File to upload:<input type="file" name="upfile" size="50" />
4707: <br />
4708: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
4709: </form>
4710: UPLOAD
4711:
4712: $r->print(<<SCANTRONFORM);
4713: </td>
4714: </tr>
4715: </table>
4716: </td>
4717: </tr>
4718: SCANTRONFORM
4719: }
4720:
4721: # Chunk of the form that prompts to view a scoring office file,
4722: # corrected file, skipped records in a file.
4723:
4724: $r->print(<<SCANTRONFORM);
4725: <tr>
4726: <form action='/adm/grades' name='scantron_download'>
4727: <td bgcolor="#777777">
4728: $default_form_data
4729: <input type="hidden" name="command" value="scantron_download" />
4730: <table width="100%" border="0">
4731: <tr bgcolor="#e6ffff">
4732: <td colspan="2">
4733: <b>Download a scoring office file</b>
4734: </td>
4735: </tr>
4736: <tr bgcolor="#ffffe6">
4737: <td> Filename of scoring office file: </td><td> $file_selector </td>
4738: </tr>
4739: <tr bgcolor="#ffffe6">
4740: <td colspan="2">
4741: <input type="submit" value="Download: Show List of Associated Files" />
4742: </td>
4743: </tr>
4744: </table>
4745: </td>
4746: </form>
4747: </tr>
4748: SCANTRONFORM
4749:
4750: $r->print(<<SCANTRONFORM);
4751: </table>
4752: $grading_menu_button
4753: SCANTRONFORM
4754:
4755: return
4756: }
4757:
4758: =pod
4759:
4760: =item get_scantron_config
4761:
4762: Parse and return the scantron configuration line selected as a
4763: hash of configuration file fields.
4764:
4765: Arguments:
4766: which - the name of the configuration to parse from the file.
4767:
4768:
4769: Returns:
4770: If the named configuration is not in the file, an empty
4771: hash is returned.
4772: a hash with the fields
4773: name - internal name for the this configuration setup
4774: description - text to display to operator that describes this config
4775: CODElocation - if 0 or the string 'none'
4776: - no CODE exists for this config
4777: if -1 || the string 'letter'
4778: - a CODE exists for this config and is
4779: a string of letters
4780: Unsupported value (but planned for future support)
4781: if a positive integer
4782: - The CODE exists as the first n items from
4783: the question section of the form
4784: if the string 'number'
4785: - The CODE exists for this config and is
4786: a string of numbers
4787: CODEstart - (only matter if a CODE exists) column in the line where
4788: the CODE starts
4789: CODElength - length of the CODE
4790: IDstart - column where the student ID number starts
4791: IDlength - length of the student ID info
4792: Qstart - column where the information from the bubbled
4793: 'questions' start
4794: Qlength - number of columns comprising a single bubble line from
4795: the sheet. (usually either 1 or 10)
4796: Qon - either a single character representing the character used
4797: to signal a bubble was chosen in the positional setup, or
4798: the string 'letter' if the letter of the chosen bubble is
4799: in the final, or 'number' if a number representing the
4800: chosen bubble is in the file (1->A 0->J)
4801: Qoff - the character used to represent that a bubble was
4802: left blank
4803: PaperID - if the scanning process generates a unique number for each
4804: sheet scanned the column that this ID number starts in
4805: PaperIDlength - number of columns that comprise the unique ID number
4806: for the sheet of paper
4807: FirstName - column that the first name starts in
4808: FirstNameLength - number of columns that the first name spans
4809:
4810: LastName - column that the last name starts in
4811: LastNameLength - number of columns that the last name spans
4812:
4813: =cut
4814:
4815: sub get_scantron_config {
4816: my ($which) = @_;
4817: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
4818: my %config;
4819: #FIXME probably should move to XML it has already gotten a bit much now
4820: foreach my $line (<$fh>) {
4821: my ($name,$descrip)=split(/:/,$line);
4822: if ($name ne $which ) { next; }
4823: chomp($line);
4824: my @config=split(/:/,$line);
4825: $config{'name'}=$config[0];
4826: $config{'description'}=$config[1];
4827: $config{'CODElocation'}=$config[2];
4828: $config{'CODEstart'}=$config[3];
4829: $config{'CODElength'}=$config[4];
4830: $config{'IDstart'}=$config[5];
4831: $config{'IDlength'}=$config[6];
4832: $config{'Qstart'}=$config[7];
4833: $config{'Qlength'}=$config[8];
4834: $config{'Qoff'}=$config[9];
4835: $config{'Qon'}=$config[10];
4836: $config{'PaperID'}=$config[11];
4837: $config{'PaperIDlength'}=$config[12];
4838: $config{'FirstName'}=$config[13];
4839: $config{'FirstNamelength'}=$config[14];
4840: $config{'LastName'}=$config[15];
4841: $config{'LastNamelength'}=$config[16];
4842: last;
4843: }
4844: return %config;
4845: }
4846:
4847: =pod
4848:
4849: =item username_to_idmap
4850:
4851: creates a hash keyed by student id with values of the corresponding
4852: student username:domain.
4853:
4854: Arguments:
4855:
4856: $classlist - reference to the class list hash. This is a hash
4857: keyed by student name:domain whose elements are references
4858: to arrays containing various chunks of information
4859: about the student. (See loncoursedata for more info).
4860:
4861: Returns
4862: %idmap - the constructed hash
4863:
4864: =cut
4865:
4866: sub username_to_idmap {
4867: my ($classlist)= @_;
4868: my %idmap;
4869: foreach my $student (keys(%$classlist)) {
4870: $idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
4871: $student;
4872: }
4873: return %idmap;
4874: }
4875:
4876: =pod
4877:
4878: =item scantron_fixup_scanline
4879:
4880: Process a requested correction to a scanline.
4881:
4882: Arguments:
4883: $scantron_config - hash from &get_scantron_config()
4884: $scan_data - hash of correction information
4885: (see &scantron_getfile())
4886: $line - existing scanline
4887: $whichline - line number of the passed in scanline
4888: $field - type of change to process
4889: (either
4890: 'ID' -> correct the student ID number
4891: 'CODE' -> correct the CODE
4892: 'answer' -> fixup the submitted answers)
4893:
4894: $args - hash of additional info,
4895: - 'ID'
4896: 'newid' -> studentID to use in replacement
4897: of existing one
4898: - 'CODE'
4899: 'CODE_ignore_dup' - set to true if duplicates
4900: should be ignored.
4901: 'CODE' - is new code or 'use_unfound'
4902: if the existing unfound code should
4903: be used as is
4904: - 'answer'
4905: 'response' - new answer or 'none' if blank
4906: 'question' - the bubble line to change
4907:
4908: Returns:
4909: $line - the modified scanline
4910:
4911: Side effects:
4912: $scan_data - may be updated
4913:
4914: =cut
4915:
4916:
4917: sub scantron_fixup_scanline {
4918: my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
4919:
4920: if ($field eq 'ID') {
4921: if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
4922: return ($line,1,'New value too large');
4923: }
4924: if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
4925: $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
4926: $args->{'newid'});
4927: }
4928: substr($line,$$scantron_config{'IDstart'}-1,
4929: $$scantron_config{'IDlength'})=$args->{'newid'};
4930: if ($args->{'newid'}=~/^\s*$/) {
4931: &scan_data($scan_data,"$whichline.user",
4932: $args->{'username'}.':'.$args->{'domain'});
4933: }
4934: } elsif ($field eq 'CODE') {
4935: if ($args->{'CODE_ignore_dup'}) {
4936: &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
4937: }
4938: &scan_data($scan_data,"$whichline.useCODE",'1');
4939: if ($args->{'CODE'} ne 'use_unfound') {
4940: if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
4941: return ($line,1,'New CODE value too large');
4942: }
4943: if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
4944: $args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
4945: }
4946: substr($line,$$scantron_config{'CODEstart'}-1,
4947: $$scantron_config{'CODElength'})=$args->{'CODE'};
4948: }
4949: } elsif ($field eq 'answer') {
4950: my $length=$scantron_config->{'Qlength'};
4951: my $off=$scantron_config->{'Qoff'};
4952: my $on=$scantron_config->{'Qon'};
4953: my $answer=${off}x$length;
4954: if ($args->{'response'} eq 'none') {
4955: &scan_data($scan_data,
4956: "$whichline.no_bubble.".$args->{'question'},'1');
4957: } else {
4958: if ($on eq 'letter') {
4959: my @alphabet=('A'..'Z');
4960: $answer=$alphabet[$args->{'response'}];
4961: } elsif ($on eq 'number') {
4962: $answer=$args->{'response'}+1;
4963: if ($answer == 10) { $answer = '0'; }
4964: } else {
4965: substr($answer,$args->{'response'},1)=$on;
4966: }
4967: &scan_data($scan_data,
4968: "$whichline.no_bubble.".$args->{'question'},undef,'1');
4969: }
4970: my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
4971: substr($line,$where-1,$length)=$answer;
4972: }
4973: return $line;
4974: }
4975:
4976: =pod
4977:
4978: =item scan_data
4979:
4980: Edit or look up an item in the scan_data hash.
4981:
4982: Arguments:
4983: $scan_data - The hash (see scantron_getfile)
4984: $key - shorthand of the key to edit (actual key is
4985: scantronfilename_key).
4986: $data - New value of the hash entry.
4987: $delete - If true, the entry is removed from the hash.
4988:
4989: Returns:
4990: The new value of the hash table field (undefined if deleted).
4991:
4992: =cut
4993:
4994:
4995: sub scan_data {
4996: my ($scan_data,$key,$value,$delete)=@_;
4997: my $filename=$env{'form.scantron_selectfile'};
4998: if (defined($value)) {
4999: $scan_data->{$filename.'_'.$key} = $value;
5000: }
5001: if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
5002: return $scan_data->{$filename.'_'.$key};
5003: }
5004:
5005: =pod
5006:
5007: =item scantron_parse_scanline
5008:
5009: Decodes a scanline from the selected scantron file
5010:
5011: Arguments:
5012: line - The text of the scantron file line to process
5013: whichline - Line number
5014: scantron_config - Hash describing the format of the scantron lines.
5015: scan_data - Hash of extra information about the scanline
5016: (see scantron_getfile for more information)
5017: just_header - True if should not process question answers but only
5018: the stuff to the left of the answers.
5019: Returns:
5020: Hash containing the result of parsing the scanline
5021:
5022: Keys are all proceeded by the string 'scantron.'
5023:
5024: CODE - the CODE in use for this scanline
5025: useCODE - 1 if the CODE is invalid but it usage has been forced
5026: by the operator
5027: CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
5028: CODEs were selected, but the usage has been
5029: forced by the operator
5030: ID - student ID
5031: PaperID - if used, the ID number printed on the sheet when the
5032: paper was scanned
5033: FirstName - first name from the sheet
5034: LastName - last name from the sheet
5035:
5036: if just_header was not true these key may also exist
5037:
5038: missingerror - a list of bubbled line numbers that had a blank bubble
5039: that is considered an error (if the operator had already
5040: okayed a blank bubble line as really being blank then
5041: that bubble line number won't appear here.
5042: doubleerror - a list of bubbled line numbers that had more than one
5043: bubble filled in and has not been corrected by the
5044: operator
5045: maxquest - the number of the last bubble line that was parsed
5046:
5047: (<number> starts at 1)
5048: <number>.answer - zero or more letters representing the selected
5049: letters from the scanline for the bubble line
5050: <number>.
5051: if blank there was either no bubble or there where
5052: multiple bubbles, (consult the keys missingerror and
5053: doubleerror if this is an error condition)
5054:
5055: =cut
5056:
5057: sub scantron_parse_scanline {
5058: my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
5059: my %record;
5060: my $questions=substr($line,$$scantron_config{'Qstart'}-1); # Answers
5061: my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # earlier stuff
5062: if (!($$scantron_config{'CODElocation'} eq 0 ||
5063: $$scantron_config{'CODElocation'} eq 'none')) {
5064: if ($$scantron_config{'CODElocation'} < 0 ||
5065: $$scantron_config{'CODElocation'} eq 'letter' ||
5066: $$scantron_config{'CODElocation'} eq 'number') {
5067: $record{'scantron.CODE'}=substr($data,
5068: $$scantron_config{'CODEstart'}-1,
5069: $$scantron_config{'CODElength'});
5070: if (&scan_data($scan_data,"$whichline.useCODE")) {
5071: $record{'scantron.useCODE'}=1;
5072: }
5073: if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
5074: $record{'scantron.CODE_ignore_dup'}=1;
5075: }
5076: } else {
5077: #FIXME interpret first N questions
5078: }
5079: }
5080: $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
5081: $$scantron_config{'IDlength'});
5082: $record{'scantron.PaperID'}=
5083: substr($data,$$scantron_config{'PaperID'}-1,
5084: $$scantron_config{'PaperIDlength'});
5085: $record{'scantron.FirstName'}=
5086: substr($data,$$scantron_config{'FirstName'}-1,
5087: $$scantron_config{'FirstNamelength'});
5088: $record{'scantron.LastName'}=
5089: substr($data,$$scantron_config{'LastName'}-1,
5090: $$scantron_config{'LastNamelength'});
5091: if ($just_header) { return \%record; }
5092:
5093: my @alphabet=('A'..'Z');
5094: my $questnum=0;
5095: while ($questions) {
5096: $questnum++;
5097: my $currentquest=substr($questions,0,$$scantron_config{'Qlength'});
5098: substr($questions,0,$$scantron_config{'Qlength'})='';
5099: if (length($currentquest) < $$scantron_config{'Qlength'}) { next; }
5100: if ($$scantron_config{'Qon'} eq 'letter') {
5101: if ($currentquest eq '?'
5102: || $currentquest eq '*') {
5103: push(@{$record{'scantron.doubleerror'}},$questnum);
5104: $record{"scantron.$questnum.answer"}='';
5105: } elsif (!defined($currentquest)
5106: || $currentquest eq $$scantron_config{'Qoff'}
5107: || $currentquest !~ /^[A-Z]$/) {
5108: $record{"scantron.$questnum.answer"}='';
5109: if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
5110: push(@{$record{"scantron.missingerror"}},$questnum);
5111: }
5112: } else {
5113: $record{"scantron.$questnum.answer"}=$currentquest;
5114: }
5115: } elsif ($$scantron_config{'Qon'} eq 'number') {
5116: if ($currentquest eq '?'
5117: || $currentquest eq '*') {
5118: push(@{$record{'scantron.doubleerror'}},$questnum);
5119: $record{"scantron.$questnum.answer"}='';
5120: } elsif (!defined($currentquest)
5121: || $currentquest eq $$scantron_config{'Qoff'}
5122: || $currentquest !~ /^\d$/) {
5123: $record{"scantron.$questnum.answer"}='';
5124: if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
5125: push(@{$record{"scantron.missingerror"}},$questnum);
5126: }
5127: } else {
5128: # wrap zero back to J
5129: if ($currentquest eq '0') {
5130: $record{"scantron.$questnum.answer"}=
5131: $alphabet[9];
5132: } else {
5133: $record{"scantron.$questnum.answer"}=
5134: $alphabet[$currentquest-1];
5135: }
5136: }
5137: } else {
5138: my @array=split($$scantron_config{'Qon'},$currentquest,-1);
5139: if (length($array[0]) eq $$scantron_config{'Qlength'}) {
5140: $record{"scantron.$questnum.answer"}='';
5141: if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
5142: push(@{$record{"scantron.missingerror"}},$questnum);
5143: }
5144: } else {
5145: $record{"scantron.$questnum.answer"}=
5146: $alphabet[length($array[0])];
5147: }
5148: if (scalar(@array) gt 2) {
5149: push(@{$record{'scantron.doubleerror'}},$questnum);
5150: my @ans=@array;
5151: my $i=length($ans[0]);shift(@ans);
5152: while ($#ans) {
5153: $i+=length($ans[0])+1;
5154: $record{"scantron.$questnum.answer"}.=$alphabet[$i];
5155: shift(@ans);
5156: }
5157: }
5158: }
5159: }
5160: $record{'scantron.maxquest'}=$questnum;
5161: return \%record;
5162: }
5163:
5164: =pod
5165:
5166: =item scantron_add_delay
5167:
5168: Adds an error message that occurred during the grading phase to a
5169: queue of messages to be shown after grading pass is complete
5170:
5171: Arguments:
5172: $delayqueue - arrary ref of hash ref of error messages
5173: $scanline - the scanline that caused the error
5174: $errormesage - the error message
5175: $errorcode - a numeric code for the error
5176:
5177: Side Effects:
5178: updates the $delayqueue to have a new hash ref of the error
5179:
5180: =cut
5181:
5182: sub scantron_add_delay {
5183: my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
5184: push(@$delayqueue,
5185: {'line' => $scanline, 'emsg' => $errormessage,
5186: 'ecode' => $errorcode }
5187: );
5188: }
5189:
5190: =pod
5191:
5192: =item scantron_find_student
5193:
5194: Finds the username for the current scanline
5195:
5196: Arguments:
5197: $scantron_record - hash result from scantron_parse_scanline
5198: $scan_data - hash of correction information
5199: (see &scantron_getfile() form more information)
5200: $idmap - hash from &username_to_idmap()
5201: $line - number of current scanline
5202:
5203: Returns:
5204: Either 'username:domain' or undef if unknown
5205:
5206: =cut
5207:
5208: sub scantron_find_student {
5209: my ($scantron_record,$scan_data,$idmap,$line)=@_;
5210: my $scanID=$$scantron_record{'scantron.ID'};
5211: if ($scanID =~ /^\s*$/) {
5212: return &scan_data($scan_data,"$line.user");
5213: }
5214: foreach my $id (keys(%$idmap)) {
5215: if (lc($id) eq lc($scanID)) {
5216: return $$idmap{$id};
5217: }
5218: }
5219: return undef;
5220: }
5221:
5222: =pod
5223:
5224: =item scantron_filter
5225:
5226: Filter sub for lonnavmaps, filters out hidden resources if ignore
5227: hidden resources was selected
5228:
5229: =cut
5230:
5231: sub scantron_filter {
5232: my ($curres)=@_;
5233:
5234: if (ref($curres) && $curres->is_problem()) {
5235: # if the user has asked to not have either hidden
5236: # or 'randomout' controlled resources to be graded
5237: # don't include them
5238: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
5239: && $curres->randomout) {
5240: return 0;
5241: }
5242: return 1;
5243: }
5244: return 0;
5245: }
5246:
5247: =pod
5248:
5249: =item scantron_process_corrections
5250:
5251: Gets correction information out of submitted form data and corrects
5252: the scanline
5253:
5254: =cut
5255:
5256: sub scantron_process_corrections {
5257: my ($r) = @_;
5258: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
5259: my ($scanlines,$scan_data)=&scantron_getfile();
5260: my $classlist=&Apache::loncoursedata::get_classlist();
5261: my $which=$env{'form.scantron_line'};
5262: my $line=&scantron_get_line($scanlines,$scan_data,$which);
5263: my ($skip,$err,$errmsg);
5264: if ($env{'form.scantron_skip_record'}) {
5265: $skip=1;
5266: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
5267: my $newstudent=$env{'form.scantron_username'}.':'.
5268: $env{'form.scantron_domain'};
5269: my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
5270: ($line,$err,$errmsg)=
5271: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
5272: 'ID',{'newid'=>$newid,
5273: 'username'=>$env{'form.scantron_username'},
5274: 'domain'=>$env{'form.scantron_domain'}});
5275: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
5276: my $resolution=$env{'form.scantron_CODE_resolution'};
5277: my $newCODE;
5278: my %args;
5279: if ($resolution eq 'use_unfound') {
5280: $newCODE='use_unfound';
5281: } elsif ($resolution eq 'use_found') {
5282: $newCODE=$env{'form.scantron_CODE_selectedvalue'};
5283: } elsif ($resolution eq 'use_typed') {
5284: $newCODE=$env{'form.scantron_CODE_newvalue'};
5285: } elsif ($resolution =~ /^use_closest_(\d+)/) {
5286: $newCODE=$env{"form.scantron_CODE_closest_$1"};
5287: }
5288: if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
5289: $args{'CODE_ignore_dup'}=1;
5290: }
5291: $args{'CODE'}=$newCODE;
5292: ($line,$err,$errmsg)=
5293: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
5294: 'CODE',\%args);
5295: } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
5296: foreach my $question (split(',',$env{'form.scantron_questions'})) {
5297: ($line,$err,$errmsg)=
5298: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
5299: $which,'answer',
5300: { 'question'=>$question,
5301: 'response'=>$env{"form.scantron_correct_Q_$question"}});
5302: if ($err) { last; }
5303: }
5304: }
5305: if ($err) {
5306: $r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
5307: } else {
5308: &scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
5309: &scantron_putfile($scanlines,$scan_data);
5310: }
5311: }
5312:
5313: =pod
5314:
5315: =item reset_skipping_status
5316:
5317: Forgets the current set of remember skipped scanlines (and thus
5318: reverts back to considering all lines in the
5319: scantron_skipped_<filename> file)
5320:
5321: =cut
5322:
5323: sub reset_skipping_status {
5324: my ($scanlines,$scan_data)=&scantron_getfile();
5325: &scan_data($scan_data,'remember_skipping',undef,1);
5326: &scantron_putfile(undef,$scan_data);
5327: }
5328:
5329: =pod
5330:
5331: =item start_skipping
5332:
5333: Marks a scanline to be skipped.
5334:
5335: =cut
5336:
5337: sub start_skipping {
5338: my ($scan_data,$i)=@_;
5339: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
5340: if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
5341: $remembered{$i}=2;
5342: } else {
5343: $remembered{$i}=1;
5344: }
5345: &scan_data($scan_data,'remember_skipping',join(':',%remembered));
5346: }
5347:
5348: =pod
5349:
5350: =item should_be_skipped
5351:
5352: Checks whether a scanline should be skipped.
5353:
5354: =cut
5355:
5356: sub should_be_skipped {
5357: my ($scanlines,$scan_data,$i)=@_;
5358: if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
5359: # not redoing old skips
5360: if ($scanlines->{'skipped'}[$i]) { return 1; }
5361: return 0;
5362: }
5363: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
5364:
5365: if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
5366: return 0;
5367: }
5368: return 1;
5369: }
5370:
5371: =pod
5372:
5373: =item remember_current_skipped
5374:
5375: Discovers what scanlines are in the scantron_skipped_<filename>
5376: file and remembers them into scan_data for later use.
5377:
5378: =cut
5379:
5380: sub remember_current_skipped {
5381: my ($scanlines,$scan_data)=&scantron_getfile();
5382: my %to_remember;
5383: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
5384: if ($scanlines->{'skipped'}[$i]) {
5385: $to_remember{$i}=1;
5386: }
5387: }
5388:
5389: &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
5390: &scantron_putfile(undef,$scan_data);
5391: }
5392:
5393: =pod
5394:
5395: =item check_for_error
5396:
5397: Checks if there was an error when attempting to remove a specific
5398: scantron_.. bubble sheet data file. Prints out an error if
5399: something went wrong.
5400:
5401: =cut
5402:
5403: sub check_for_error {
5404: my ($r,$result)=@_;
5405: if ($result ne 'ok' && $result ne 'not_found' ) {
5406: $r->print("An error occurred ($result) when trying to Remove the existing corrections.");
5407: }
5408: }
5409:
5410: =pod
5411:
5412: =item scantron_warning_screen
5413:
5414: Interstitial screen to make sure the operator has selected the
5415: correct options before we start the validation phase.
5416:
5417: =cut
5418:
5419: sub scantron_warning_screen {
5420: my ($button_text)=@_;
5421: my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
5422: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
5423: my $CODElist;
5424: if ($scantron_config{'CODElocation'} &&
5425: $scantron_config{'CODEstart'} &&
5426: $scantron_config{'CODElength'}) {
5427: $CODElist=$env{'form.scantron_CODElist'};
5428: if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
5429: $CODElist=
5430: '<tr><td><b>List of CODES to validate against:</b></td><td><tt>'.
5431: $env{'form.scantron_CODElist'}.'</tt></td></tr>';
5432: }
5433: return (<<STUFF);
5434: <p>
5435: <span class="LC_warning">Please double check the information
5436: below before clicking on '$button_text'</span>
5437: </p>
5438: <table>
5439: <tr><td><b>Sequence to be Graded:</b></td><td>$title</td></tr>
5440: <tr><td><b>Data File that will be used:</b></td><td><tt>$env{'form.scantron_selectfile'}</tt></td></tr>
5441: $CODElist
5442: </table>
5443: <br />
5444: <p> If this information is correct, please click on '$button_text'.</p>
5445: <p> If something is incorrect, please click the 'Grading Menu' button to start over.</p>
5446:
5447: <br />
5448: STUFF
5449: }
5450:
5451: =pod
5452:
5453: =item scantron_do_warning
5454:
5455: Check if the operator has picked something for all required
5456: fields. Error out if something is missing.
5457:
5458: =cut
5459:
5460: sub scantron_do_warning {
5461: my ($r)=@_;
5462: my ($symb)=&get_symb($r);
5463: if (!$symb) {return '';}
5464: my $default_form_data=&defaultFormData($symb);
5465: $r->print(&scantron_form_start().$default_form_data);
5466: if ( $env{'form.selectpage'} eq '' ||
5467: $env{'form.scantron_selectfile'} eq '' ||
5468: $env{'form.scantron_format'} eq '' ) {
5469: $r->print("<p>You have forgetten to specify some information. Please go Back and try again.</p>");
5470: if ( $env{'form.selectpage'} eq '') {
5471: $r->print('<p><span class="LC_error">You have not selected a Sequence to grade</span></p>');
5472: }
5473: if ( $env{'form.scantron_selectfile'} eq '') {
5474: $r->print('<p><span class="LC_error">You have not selected a file that contains the student\'s response data.</span></p>');
5475: }
5476: if ( $env{'form.scantron_format'} eq '') {
5477: $r->print('<p><span class="LC_error">You have not selected a the format of the student\'s response data.</span></p>');
5478: }
5479: } else {
5480: my $warning=&scantron_warning_screen('Grading: Validate Records');
5481: $r->print(<<STUFF);
5482: $warning
5483: <input type="submit" name="submit" value="Grading: Validate Records" />
5484: <input type="hidden" name="command" value="scantron_validate" />
5485: STUFF
5486: }
5487: $r->print("</form><br />".&show_grading_menu_form($symb));
5488: return '';
5489: }
5490:
5491: =pod
5492:
5493: =item scantron_form_start
5494:
5495: html hidden input for remembering all selected grading options
5496:
5497: =cut
5498:
5499: sub scantron_form_start {
5500: my ($max_bubble)=@_;
5501: my $result= <<SCANTRONFORM;
5502: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
5503: <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
5504: <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
5505: <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
5506: <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
5507: <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
5508: <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
5509: <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
5510: <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
5511: <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
5512: SCANTRONFORM
5513: return $result;
5514: }
5515:
5516: =pod
5517:
5518: =item scantron_validate_file
5519:
5520: Dispatch routine for doing validation of a bubble sheet data file.
5521:
5522: Also processes any necessary information resets that need to
5523: occur before validation begins (ignore previous corrections,
5524: restarting the skipped records processing)
5525:
5526: =cut
5527:
5528: sub scantron_validate_file {
5529: my ($r) = @_;
5530: my ($symb)=&get_symb($r);
5531: if (!$symb) {return '';}
5532: my $default_form_data=&defaultFormData($symb);
5533:
5534: # do the detection of only doing skipped records first befroe we delete
5535: # them when doing the corrections reset
5536: if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
5537: &reset_skipping_status();
5538: }
5539: if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
5540: &remember_current_skipped();
5541: $env{'form.scantron_options_redo'}='redo_skipped_ready';
5542: }
5543:
5544: if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
5545: &check_for_error($r,&scantron_remove_file('corrected'));
5546: &check_for_error($r,&scantron_remove_file('skipped'));
5547: &check_for_error($r,&scantron_remove_scan_data());
5548: $env{'form.scantron_options_ignore'}='done';
5549: }
5550:
5551: if ($env{'form.scantron_corrections'}) {
5552: &scantron_process_corrections($r);
5553: }
5554: $r->print("<p>Gathering necessary info.</p>");$r->rflush();
5555: #get the student pick code ready
5556: $r->print(&Apache::loncommon::studentbrowser_javascript());
5557: my $max_bubble=&scantron_get_maxbubble();
5558: my $result=&scantron_form_start($max_bubble).$default_form_data;
5559: $r->print($result);
5560:
5561: my @validate_phases=( 'sequence',
5562: 'ID',
5563: 'CODE',
5564: 'doublebubble',
5565: 'missingbubbles');
5566: if (!$env{'form.validatepass'}) {
5567: $env{'form.validatepass'} = 0;
5568: }
5569: my $currentphase=$env{'form.validatepass'};
5570:
5571: my $stop=0;
5572: while (!$stop && $currentphase < scalar(@validate_phases)) {
5573: $r->print("<p> Validating ".$validate_phases[$currentphase]."</p>");
5574: $r->rflush();
5575: my $which="scantron_validate_".$validate_phases[$currentphase];
5576: {
5577: no strict 'refs';
5578: ($stop,$currentphase)=&$which($r,$currentphase);
5579: }
5580: }
5581: if (!$stop) {
5582: my $warning=&scantron_warning_screen('Start Grading');
5583: $r->print(<<STUFF);
5584: Validation process complete.<br />
5585: $warning
5586: <input type="submit" name="submit" value="Start Grading" />
5587: <input type="hidden" name="command" value="scantron_process" />
5588: STUFF
5589:
5590: } else {
5591: $r->print('<input type="hidden" name="command" value="scantron_validate" />');
5592: $r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
5593: }
5594: if ($stop) {
5595: if ($validate_phases[$currentphase] eq 'sequence') {
5596: $r->print('<input type="submit" name="submit" value="Ignore -> " />');
5597: $r->print(' this error <br />');
5598:
5599: $r->print(" <p>Or click the 'Grading Menu' button to start over.</p>");
5600: } else {
5601: $r->print('<input type="submit" name="submit" value="Continue ->" />');
5602: $r->print(' using corrected info <br />');
5603: $r->print("<input type='submit' value='Skip' name='scantron_skip_record' />");
5604: $r->print(" this scanline saving it for later.");
5605: }
5606: }
5607: $r->print(" </form><br />".&show_grading_menu_form($symb));
5608: return '';
5609: }
5610:
5611:
5612: =pod
5613:
5614: =item scantron_remove_file
5615:
5616: Removes the requested bubble sheet data file, makes sure that
5617: scantron_original_<filename> is never removed
5618:
5619:
5620: =cut
5621:
5622: sub scantron_remove_file {
5623: my ($which)=@_;
5624: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5625: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5626: my $file='scantron_';
5627: if ($which eq 'corrected' || $which eq 'skipped') {
5628: $file.=$which.'_';
5629: } else {
5630: return 'refused';
5631: }
5632: $file.=$env{'form.scantron_selectfile'};
5633: return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
5634: }
5635:
5636:
5637: =pod
5638:
5639: =item scantron_remove_scan_data
5640:
5641: Removes all scan_data correction for the requested bubble sheet
5642: data file. (In the case that both the are doing skipped records we need
5643: to remember the old skipped lines for the time being so that element
5644: persists for a while.)
5645:
5646: =cut
5647:
5648: sub scantron_remove_scan_data {
5649: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5650: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5651: my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
5652: my @todelete;
5653: my $filename=$env{'form.scantron_selectfile'};
5654: foreach my $key (@keys) {
5655: if ($key=~/^\Q$filename\E_/) {
5656: if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
5657: $key=~/remember_skipping/) {
5658: next;
5659: }
5660: push(@todelete,$key);
5661: }
5662: }
5663: my $result;
5664: if (@todelete) {
5665: $result=&Apache::lonnet::del('nohist_scantrondata',\@todelete,$cdom,$cname);
5666: }
5667: return $result;
5668: }
5669:
5670:
5671: =pod
5672:
5673: =item scantron_getfile
5674:
5675: Fetches the requested bubble sheet data file (all 3 versions), and
5676: the scan_data hash
5677:
5678: Arguments:
5679: None
5680:
5681: Returns:
5682: 2 hash references
5683:
5684: - first one has
5685: orig -
5686: corrected -
5687: skipped - each of which points to an array ref of the specified
5688: file broken up into individual lines
5689: count - number of scanlines
5690:
5691: - second is the scan_data hash possible keys are
5692: ($number refers to scanline numbered $number and thus the key affects
5693: only that scanline
5694: $bubline refers to the specific bubble line element and the aspects
5695: refers to that specific bubble line element)
5696:
5697: $number.user - username:domain to use
5698: $number.CODE_ignore_dup
5699: - ignore the duplicate CODE error
5700: $number.useCODE
5701: - use the CODE in the scanline as is
5702: $number.no_bubble.$bubline
5703: - it is valid that there is no bubbled in bubble
5704: at $number $bubline
5705: remember_skipping
5706: - a frozen hash containing keys of $number and values
5707: of either
5708: 1 - we are on a 'do skipped records pass' and plan
5709: on processing this line
5710: 2 - we are on a 'do skipped records pass' and this
5711: scanline has been marked to skip yet again
5712:
5713: =cut
5714:
5715: sub scantron_getfile {
5716: #FIXME really would prefer a scantron directory
5717: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5718: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5719: my $lines;
5720: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
5721: 'scantron_orig_'.$env{'form.scantron_selectfile'});
5722: my %scanlines;
5723: $scanlines{'orig'}=[(split("\n",$lines,-1))];
5724: my $temp=$scanlines{'orig'};
5725: $scanlines{'count'}=$#$temp;
5726:
5727: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
5728: 'scantron_corrected_'.$env{'form.scantron_selectfile'});
5729: if ($lines eq '-1') {
5730: $scanlines{'corrected'}=[];
5731: } else {
5732: $scanlines{'corrected'}=[(split("\n",$lines,-1))];
5733: }
5734: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
5735: 'scantron_skipped_'.$env{'form.scantron_selectfile'});
5736: if ($lines eq '-1') {
5737: $scanlines{'skipped'}=[];
5738: } else {
5739: $scanlines{'skipped'}=[(split("\n",$lines,-1))];
5740: }
5741: my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
5742: if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
5743: my %scan_data = @tmp;
5744: return (\%scanlines,\%scan_data);
5745: }
5746:
5747: =pod
5748:
5749: =item lonnet_putfile
5750:
5751: Wrapper routine to call &Apache::lonnet::finishuserfileupload
5752:
5753: Arguments:
5754: $contents - data to store
5755: $filename - filename to store $contents into
5756:
5757: Returns:
5758: result value from &Apache::lonnet::finishuserfileupload
5759:
5760: =cut
5761:
5762: sub lonnet_putfile {
5763: my ($contents,$filename)=@_;
5764: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
5765: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5766: $env{'form.sillywaytopassafilearound'}=$contents;
5767: &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
5768:
5769: }
5770:
5771: =pod
5772:
5773: =item scantron_putfile
5774:
5775: Stores the current version of the bubble sheet data files, and the
5776: scan_data hash. (Does not modify the original version only the
5777: corrected and skipped versions.
5778:
5779: Arguments:
5780: $scanlines - hash ref that looks like the first return value from
5781: &scantron_getfile()
5782: $scan_data - hash ref that looks like the second return value from
5783: &scantron_getfile()
5784:
5785: =cut
5786:
5787: sub scantron_putfile {
5788: my ($scanlines,$scan_data) = @_;
5789: #FIXME really would prefer a scantron directory
5790: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5791: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5792: if ($scanlines) {
5793: my $prefix='scantron_';
5794: # no need to update orig, shouldn't change
5795: # &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
5796: # $env{'form.scantron_selectfile'});
5797: &lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
5798: $prefix.'corrected_'.
5799: $env{'form.scantron_selectfile'});
5800: &lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
5801: $prefix.'skipped_'.
5802: $env{'form.scantron_selectfile'});
5803: }
5804: &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
5805: }
5806:
5807: =pod
5808:
5809: =item scantron_get_line
5810:
5811: Returns the correct version of the scanline
5812:
5813: Arguments:
5814: $scanlines - hash ref that looks like the first return value from
5815: &scantron_getfile()
5816: $scan_data - hash ref that looks like the second return value from
5817: &scantron_getfile()
5818: $i - number of the requested line (starts at 0)
5819:
5820: Returns:
5821: A scanline, (either the original or the corrected one if it
5822: exists), or undef if the requested scanline should be
5823: skipped. (Either because it's an skipped scanline, or it's an
5824: unskipped scanline and we are not doing a 'do skipped scanlines'
5825: pass.
5826:
5827: =cut
5828:
5829: sub scantron_get_line {
5830: my ($scanlines,$scan_data,$i)=@_;
5831: if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
5832: #if ($scanlines->{'skipped'}[$i]) { return undef; }
5833: if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
5834: return $scanlines->{'orig'}[$i];
5835: }
5836:
5837: =pod
5838:
5839: =item scantron_todo_count
5840:
5841: Counts the number of scanlines that need processing.
5842:
5843: Arguments:
5844: $scanlines - hash ref that looks like the first return value from
5845: &scantron_getfile()
5846: $scan_data - hash ref that looks like the second return value from
5847: &scantron_getfile()
5848:
5849: Returns:
5850: $count - number of scanlines to process
5851:
5852: =cut
5853:
5854: sub get_todo_count {
5855: my ($scanlines,$scan_data)=@_;
5856: my $count=0;
5857: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
5858: my $line=&scantron_get_line($scanlines,$scan_data,$i);
5859: if ($line=~/^[\s\cz]*$/) { next; }
5860: $count++;
5861: }
5862: return $count;
5863: }
5864:
5865: =pod
5866:
5867: =item scantron_put_line
5868:
5869: Updates the 'corrected' or 'skipped' versions of the bubble sheet
5870: data file.
5871:
5872: Arguments:
5873: $scanlines - hash ref that looks like the first return value from
5874: &scantron_getfile()
5875: $scan_data - hash ref that looks like the second return value from
5876: &scantron_getfile()
5877: $i - line number to update
5878: $newline - contents of the updated scanline
5879: $skip - if true make the line for skipping and update the
5880: 'skipped' file
5881:
5882: =cut
5883:
5884: sub scantron_put_line {
5885: my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
5886: if ($skip) {
5887: $scanlines->{'skipped'}[$i]=$newline;
5888: &start_skipping($scan_data,$i);
5889: return;
5890: }
5891: $scanlines->{'corrected'}[$i]=$newline;
5892: }
5893:
5894: =pod
5895:
5896: =item scantron_clear_skip
5897:
5898: Remove a line from the 'skipped' file
5899:
5900: Arguments:
5901: $scanlines - hash ref that looks like the first return value from
5902: &scantron_getfile()
5903: $scan_data - hash ref that looks like the second return value from
5904: &scantron_getfile()
5905: $i - line number to update
5906:
5907: =cut
5908:
5909: sub scantron_clear_skip {
5910: my ($scanlines,$scan_data,$i)=@_;
5911: if (exists($scanlines->{'skipped'}[$i])) {
5912: undef($scanlines->{'skipped'}[$i]);
5913: return 1;
5914: }
5915: return 0;
5916: }
5917:
5918: =pod
5919:
5920: =item scantron_filter_not_exam
5921:
5922: Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
5923: filter out resources that are not marked as 'exam' mode
5924:
5925: =cut
5926:
5927: sub scantron_filter_not_exam {
5928: my ($curres)=@_;
5929:
5930: if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
5931: # if the user has asked to not have either hidden
5932: # or 'randomout' controlled resources to be graded
5933: # don't include them
5934: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
5935: && $curres->randomout) {
5936: return 0;
5937: }
5938: return 1;
5939: }
5940: return 0;
5941: }
5942:
5943: =pod
5944:
5945: =item scantron_validate_sequence
5946:
5947: Validates the selected sequence, checking for resource that are
5948: not set to exam mode.
5949:
5950: =cut
5951:
5952: sub scantron_validate_sequence {
5953: my ($r,$currentphase) = @_;
5954:
5955: my $navmap=Apache::lonnavmaps::navmap->new();
5956: my (undef,undef,$sequence)=
5957: &Apache::lonnet::decode_symb($env{'form.selectpage'});
5958:
5959: my $map=$navmap->getResourceByUrl($sequence);
5960:
5961: $r->print('<input type="hidden" name="validate_sequence_exam"
5962: value="ignore" />');
5963: if ($env{'form.validate_sequence_exam'} ne 'ignore') {
5964: my @resources=
5965: $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
5966: if (@resources) {
5967: $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>");
5968: return (1,$currentphase);
5969: }
5970: }
5971:
5972: return (0,$currentphase+1);
5973: }
5974:
5975: =pod
5976:
5977: =item scantron_validate_ID
5978:
5979: Validates all scanlines in the selected file to not have any
5980: invalid or underspecified student IDs
5981:
5982: =cut
5983:
5984: sub scantron_validate_ID {
5985: my ($r,$currentphase) = @_;
5986:
5987: #get student info
5988: my $classlist=&Apache::loncoursedata::get_classlist();
5989: my %idmap=&username_to_idmap($classlist);
5990:
5991: #get scantron line setup
5992: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
5993: my ($scanlines,$scan_data)=&scantron_getfile();
5994:
5995: my %found=('ids'=>{},'usernames'=>{});
5996: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
5997: my $line=&scantron_get_line($scanlines,$scan_data,$i);
5998: if ($line=~/^[\s\cz]*$/) { next; }
5999: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6000: $scan_data);
6001: my $id=$$scan_record{'scantron.ID'};
6002: my $found;
6003: foreach my $checkid (keys(%idmap)) {
6004: if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
6005: }
6006: if ($found) {
6007: my $username=$idmap{$found};
6008: if ($found{'ids'}{$found}) {
6009: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6010: $line,'duplicateID',$found);
6011: return(1,$currentphase);
6012: } elsif ($found{'usernames'}{$username}) {
6013: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6014: $line,'duplicateID',$username);
6015: return(1,$currentphase);
6016: }
6017: #FIXME store away line we previously saw the ID on to use above
6018: $found{'ids'}{$found}++;
6019: $found{'usernames'}{$username}++;
6020: } else {
6021: if ($id =~ /^\s*$/) {
6022: my $username=&scan_data($scan_data,"$i.user");
6023: if (defined($username) && $found{'usernames'}{$username}) {
6024: &scantron_get_correction($r,$i,$scan_record,
6025: \%scantron_config,
6026: $line,'duplicateID',$username);
6027: return(1,$currentphase);
6028: } elsif (!defined($username)) {
6029: &scantron_get_correction($r,$i,$scan_record,
6030: \%scantron_config,
6031: $line,'incorrectID');
6032: return(1,$currentphase);
6033: }
6034: $found{'usernames'}{$username}++;
6035: } else {
6036: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6037: $line,'incorrectID');
6038: return(1,$currentphase);
6039: }
6040: }
6041: }
6042:
6043: return (0,$currentphase+1);
6044: }
6045:
6046: =pod
6047:
6048: =item scantron_get_correction
6049:
6050: Builds the interface screen to interact with the operator to fix a
6051: specific error condition in a specific scanline
6052:
6053: Arguments:
6054: $r - Apache request object
6055: $i - number of the current scanline
6056: $scan_record - hash ref as returned from &scantron_parse_scanline()
6057: $scan_config - hash ref as returned from &get_scantron_config()
6058: $line - full contents of the current scanline
6059: $error - error condition, valid values are
6060: 'incorrectCODE', 'duplicateCODE',
6061: 'doublebubble', 'missingbubble',
6062: 'duplicateID', 'incorrectID'
6063: $arg - extra information needed
6064: For errors:
6065: - duplicateID - paper number that this studentID was seen before on
6066: - duplicateCODE - array ref of the paper numbers this CODE was
6067: seen on before
6068: - incorrectCODE - current incorrect CODE
6069: - doublebubble - array ref of the bubble lines that have double
6070: bubble errors
6071: - missingbubble - array ref of the bubble lines that have missing
6072: bubble errors
6073:
6074: =cut
6075:
6076: sub scantron_get_correction {
6077: my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
6078:
6079: #FIXME in the case of a duplicated ID the previous line, probaly need
6080: #to show both the current line and the previous one and allow skipping
6081: #the previous one or the current one
6082:
6083: $r->print("<p><b>An error was detected ($error)</b>");
6084: if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
6085: $r->print(" for PaperID <tt>".
6086: $$scan_record{'scantron.PaperID'}."</tt> \n");
6087: } else {
6088: $r->print(" in scanline $i <pre>".
6089: $line."</pre> \n");
6090: }
6091: my $message="<p>The ID on the form is <tt>".
6092: $$scan_record{'scantron.ID'}."</tt><br />\n".
6093: "The name on the paper is ".
6094: $$scan_record{'scantron.LastName'}.",".
6095: $$scan_record{'scantron.FirstName'}."</p>";
6096:
6097: $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
6098: $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
6099: if ($error =~ /ID$/) {
6100: if ($error eq 'incorrectID') {
6101: $r->print("The encoded ID is not in the classlist</p>\n");
6102: } elsif ($error eq 'duplicateID') {
6103: $r->print("The encoded ID has also been used by a previous paper $arg</p>\n");
6104: }
6105: $r->print($message);
6106: $r->print("<p>How should I handle this? <br /> \n");
6107: $r->print("\n<ul><li> ");
6108: #FIXME it would be nice if this sent back the user ID and
6109: #could do partial userID matches
6110: $r->print(&Apache::loncommon::selectstudent_link('scantronupload',
6111: 'scantron_username','scantron_domain'));
6112: $r->print(": <input type='text' name='scantron_username' value='' />");
6113: $r->print("\n@".
6114: &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
6115:
6116: $r->print('</li>');
6117: } elsif ($error =~ /CODE$/) {
6118: if ($error eq 'incorrectCODE') {
6119: $r->print("</p><p>The encoded CODE is not in the list of possible CODEs</p>\n");
6120: } elsif ($error eq 'duplicateCODE') {
6121: $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");
6122: }
6123: $r->print("<p>The CODE on the form is <tt>'".
6124: $$scan_record{'scantron.CODE'}."'</tt><br />\n");
6125: $r->print($message);
6126: $r->print("<p>How should I handle this? <br /> \n");
6127: $r->print("\n<br /> ");
6128: my $i=0;
6129: if ($error eq 'incorrectCODE'
6130: && $$scan_record{'scantron.CODE'}=~/\S/ ) {
6131: my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
6132: if ($closest > 0) {
6133: foreach my $testcode (@{$closest}) {
6134: my $checked='';
6135: if (!$i) { $checked=' checked="checked" '; }
6136: $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' />");
6137: $r->print("\n<br />");
6138: $i++;
6139: }
6140: }
6141: }
6142: if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
6143: my $checked; if (!$i) { $checked=' checked="checked" '; }
6144: $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>");
6145: $r->print("\n<br />");
6146: }
6147:
6148: $r->print(<<ENDSCRIPT);
6149: <script type="text/javascript">
6150: function change_radio(field) {
6151: var slct=document.scantronupload.scantron_CODE_resolution;
6152: var i;
6153: for (i=0;i<slct.length;i++) {
6154: if (slct[i].value==field) { slct[i].checked=true; }
6155: }
6156: }
6157: </script>
6158: ENDSCRIPT
6159: my $href="/adm/pickcode?".
6160: "form=".&escape("scantronupload").
6161: "&scantron_format=".&escape($env{'form.scantron_format'}).
6162: "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
6163: "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
6164: "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
6165: if ($env{'form.scantron_CODElist'} =~ /\S/) {
6166: $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')\" />");
6167: $r->print("\n<br />");
6168: }
6169: $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.");
6170: $r->print("\n<br /><br />");
6171: } elsif ($error eq 'doublebubble') {
6172: $r->print("<p>There have been multiple bubbles scanned for a some question(s)</p>\n");
6173: $r->print('<input type="hidden" name="scantron_questions" value="'.
6174: join(',',@{$arg}).'" />');
6175: $r->print($message);
6176: $r->print("<p>Please indicate which bubble should be used for grading</p>");
6177: foreach my $question (@{$arg}) {
6178: my $selected=$$scan_record{"scantron.$question.answer"};
6179: &scantron_bubble_selector($r,$scan_config,$question,
6180: split('',$selected));
6181: }
6182: } elsif ($error eq 'missingbubble') {
6183: $r->print("<p>There have been <b>no</b> bubbles scanned for some question(s)</p>\n");
6184: $r->print($message);
6185: $r->print("<p>Please indicate which bubble should be used for grading</p>");
6186: $r->print("Some questions have no scanned bubbles\n");
6187: $r->print('<input type="hidden" name="scantron_questions" value="'.
6188: join(',',@{$arg}).'" />');
6189: foreach my $question (@{$arg}) {
6190: my $selected=$$scan_record{"scantron.$question.answer"};
6191: &scantron_bubble_selector($r,$scan_config,$question);
6192: }
6193: } else {
6194: $r->print("\n<ul>");
6195: }
6196: $r->print("\n</li></ul>");
6197:
6198: }
6199:
6200: =pod
6201:
6202: =item scantron_bubble_selector
6203:
6204: Generates the html radiobuttons to correct a single bubble line
6205: possibly showing the existing the selected bubbles if known
6206:
6207: Arguments:
6208: $r - Apache request object
6209: $scan_config - hash from &get_scantron_config()
6210: $quest - number of the bubble line to make a corrector for
6211: $selected - array of letters of previously selected bubbles
6212: $lines - if present, number of bubble lines to show
6213:
6214: =cut
6215:
6216: sub scantron_bubble_selector {
6217: my ($r,$scan_config,$quest,@selected, $lines)=@_;
6218: my $max=$$scan_config{'Qlength'};
6219:
6220: my $scmode=$$scan_config{'Qon'};
6221: if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }
6222:
6223:
6224: if (!defined($lines)) {
6225: $lines = 1;
6226: }
6227: my $total_lines = $lines*2;
6228: my @alphabet=('A'..'Z');
6229: $r->print("<table border='1'><tr><td rowspan='".$total_lines."'>$quest</td>");
6230:
6231: for (my $l = 0; $l < $lines; $l++) {
6232: if ($l != 0) {
6233: $r->print('<tr>');
6234: }
6235:
6236: # FIXME: This loop probably has to be considerably more clever for
6237: # multiline bubbles: User can multibubble by having bubbles in
6238: # several lines. User can skip lines legitimately etc. etc.
6239:
6240: for (my $i=0;$i<$max;$i++) {
6241: $r->print("\n".'<td align="center">');
6242: if ($selected[0] eq $alphabet[$i]) {
6243: $r->print('X');
6244: shift(@selected) ;
6245: } else {
6246: $r->print(' ');
6247: }
6248: $r->print('</td>');
6249:
6250: }
6251:
6252: if ($l == 0) {
6253: my $lspan = $total_lines * 2; # 2 table rows per bubble line.
6254:
6255: $r->print('<td rowspan='.$lspan.'><label><input type="radio" name="scantron_correct_Q_'.
6256: $quest.'" value="none" /> No bubble </label></td>');
6257:
6258: }
6259:
6260: $r->print('</tr><tr>');
6261:
6262: # FIXME: This may have to be a bit more clever for
6263: # multiline questions (different values e.g..).
6264:
6265: for (my $i=0;$i<$max;$i++) {
6266: $r->print("\n".
6267: '<td><label><input type="radio" name="scantron_correct_Q_'.
6268: $quest.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
6269: }
6270: $r->print('</tr>');
6271:
6272:
6273: }
6274: $r->print('</table>');
6275: }
6276:
6277: =pod
6278:
6279: =item num_matches
6280:
6281: Counts the number of characters that are the same between the two arguments.
6282:
6283: Arguments:
6284: $orig - CODE from the scanline
6285: $code - CODE to match against
6286:
6287: Returns:
6288: $count - integer count of the number of same characters between the
6289: two arguments
6290:
6291: =cut
6292:
6293: sub num_matches {
6294: my ($orig,$code) = @_;
6295: my @code=split(//,$code);
6296: my @orig=split(//,$orig);
6297: my $same=0;
6298: for (my $i=0;$i<scalar(@code);$i++) {
6299: if ($code[$i] eq $orig[$i]) { $same++; }
6300: }
6301: return $same;
6302: }
6303:
6304: =pod
6305:
6306: =item scantron_get_closely_matching_CODEs
6307:
6308: Cycles through all CODEs and finds the set that has the greatest
6309: number of same characters as the provided CODE
6310:
6311: Arguments:
6312: $allcodes - hash ref returned by &get_codes()
6313: $CODE - CODE from the current scanline
6314:
6315: Returns:
6316: 2 element list
6317: - first elements is number of how closely matching the best fit is
6318: (5 means best set has 5 matching characters)
6319: - second element is an arrary ref containing the set of valid CODEs
6320: that best fit the passed in CODE
6321:
6322: =cut
6323:
6324: sub scantron_get_closely_matching_CODEs {
6325: my ($allcodes,$CODE)=@_;
6326: my @CODEs;
6327: foreach my $testcode (sort(keys(%{$allcodes}))) {
6328: push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
6329: }
6330:
6331: return ($#CODEs,$CODEs[-1]);
6332: }
6333:
6334: =pod
6335:
6336: =item get_codes
6337:
6338: Builds a hash which has keys of all of the valid CODEs from the selected
6339: set of remembered CODEs.
6340:
6341: Arguments:
6342: $old_name - name of the set of remembered CODEs
6343: $cdom - domain of the course
6344: $cnum - internal course name
6345:
6346: Returns:
6347: %allcodes - keys are the valid CODEs, values are all 1
6348:
6349: =cut
6350:
6351: sub get_codes {
6352: my ($old_name, $cdom, $cnum) = @_;
6353: if (!$old_name) {
6354: $old_name=$env{'form.scantron_CODElist'};
6355: }
6356: if (!$cdom) {
6357: $cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
6358: }
6359: if (!$cnum) {
6360: $cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
6361: }
6362: my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
6363: $cdom,$cnum);
6364: my %allcodes;
6365: if ($result{"type\0$old_name"} eq 'number') {
6366: %allcodes=map {($_,1)} split(',',$result{$old_name});
6367: } else {
6368: %allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
6369: }
6370: return %allcodes;
6371: }
6372:
6373: =pod
6374:
6375: =item scantron_validate_CODE
6376:
6377: Validates all scanlines in the selected file to not have any
6378: invalid or underspecified CODEs and that none of the codes are
6379: duplicated if this was requested.
6380:
6381: =cut
6382:
6383: sub scantron_validate_CODE {
6384: my ($r,$currentphase) = @_;
6385: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6386: if ($scantron_config{'CODElocation'} &&
6387: $scantron_config{'CODEstart'} &&
6388: $scantron_config{'CODElength'}) {
6389: if (!defined($env{'form.scantron_CODElist'})) {
6390: &FIXME_blow_up()
6391: }
6392: } else {
6393: return (0,$currentphase+1);
6394: }
6395:
6396: my %usedCODEs;
6397:
6398: my %allcodes=&get_codes();
6399:
6400: my ($scanlines,$scan_data)=&scantron_getfile();
6401: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6402: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6403: if ($line=~/^[\s\cz]*$/) { next; }
6404: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6405: $scan_data);
6406: my $CODE=$$scan_record{'scantron.CODE'};
6407: my $error=0;
6408: if (!&Apache::lonnet::validCODE($CODE)) {
6409: &scantron_get_correction($r,$i,$scan_record,
6410: \%scantron_config,
6411: $line,'incorrectCODE',\%allcodes);
6412: return(1,$currentphase);
6413: }
6414: if (%allcodes && !exists($allcodes{$CODE})
6415: && !$$scan_record{'scantron.useCODE'}) {
6416: &scantron_get_correction($r,$i,$scan_record,
6417: \%scantron_config,
6418: $line,'incorrectCODE',\%allcodes);
6419: return(1,$currentphase);
6420: }
6421: if (exists($usedCODEs{$CODE})
6422: && $env{'form.scantron_CODEunique'} eq 'yes'
6423: && !$$scan_record{'scantron.CODE_ignore_dup'}) {
6424: &scantron_get_correction($r,$i,$scan_record,
6425: \%scantron_config,
6426: $line,'duplicateCODE',$usedCODEs{$CODE});
6427: return(1,$currentphase);
6428: }
6429: push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
6430: }
6431: return (0,$currentphase+1);
6432: }
6433:
6434: =pod
6435:
6436: =item scantron_validate_doublebubble
6437:
6438: Validates all scanlines in the selected file to not have any
6439: bubble lines with multiple bubbles marked.
6440:
6441: =cut
6442:
6443: sub scantron_validate_doublebubble {
6444: my ($r,$currentphase) = @_;
6445: #get student info
6446: my $classlist=&Apache::loncoursedata::get_classlist();
6447: my %idmap=&username_to_idmap($classlist);
6448:
6449: #get scantron line setup
6450: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6451: my ($scanlines,$scan_data)=&scantron_getfile();
6452: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6453: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6454: if ($line=~/^[\s\cz]*$/) { next; }
6455: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6456: $scan_data);
6457: if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
6458: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
6459: 'doublebubble',
6460: $$scan_record{'scantron.doubleerror'});
6461: return (1,$currentphase);
6462: }
6463: return (0,$currentphase+1);
6464: }
6465:
6466: =pod
6467:
6468: =item scantron_get_maxbubble
6469:
6470: Returns the maximum number of bubble lines that are expected to
6471: occur. Does this by walking the selected sequence rendering the
6472: resource and then checking &Apache::lonxml::get_problem_counter()
6473: for what the current value of the problem counter is.
6474:
6475: Caches the result to $env{'form.scantron_maxbubble'}
6476:
6477: =cut
6478:
6479: sub scantron_get_maxbubble {
6480: if (defined($env{'form.scantron_maxbubble'}) &&
6481: $env{'form.scantron_maxbubble'}) {
6482: return $env{'form.scantron_maxbubble'};
6483: }
6484:
6485: my $navmap=Apache::lonnavmaps::navmap->new();
6486: my (undef,undef,$sequence)=
6487: &Apache::lonnet::decode_symb($env{'form.selectpage'});
6488:
6489: my $map=$navmap->getResourceByUrl($sequence);
6490: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
6491:
6492: &Apache::lonxml::clear_problem_counter();
6493:
6494: foreach my $resource (@resources) {
6495: my $result=&Apache::lonnet::ssi($resource->src(),
6496: ('symb' => $resource->symb()));
6497: }
6498: &Apache::lonnet::delenv('scantron\.');
6499: $env{'form.scantron_maxbubble'} =
6500: &Apache::lonxml::get_problem_counter()-1;
6501:
6502: return $env{'form.scantron_maxbubble'};
6503: }
6504:
6505: =pod
6506:
6507: =item scantron_validate_missingbubbles
6508:
6509: Validates all scanlines in the selected file to not have any
6510: bubble lines with missing bubbles that haven't been verified as missing.
6511:
6512: =cut
6513:
6514: sub scantron_validate_missingbubbles {
6515: my ($r,$currentphase) = @_;
6516: #get student info
6517: my $classlist=&Apache::loncoursedata::get_classlist();
6518: my %idmap=&username_to_idmap($classlist);
6519:
6520: #get scantron line setup
6521: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6522: my ($scanlines,$scan_data)=&scantron_getfile();
6523: my $max_bubble=&scantron_get_maxbubble();
6524: if (!$max_bubble) { $max_bubble=2**31; }
6525: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6526: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6527: if ($line=~/^[\s\cz]*$/) { next; }
6528: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6529: $scan_data);
6530: if (!defined($$scan_record{'scantron.missingerror'})) { next; }
6531: my @to_correct;
6532: foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
6533: if ($missing > $max_bubble) { next; }
6534: push(@to_correct,$missing);
6535: }
6536: if (@to_correct) {
6537: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6538: $line,'missingbubble',\@to_correct);
6539: return (1,$currentphase);
6540: }
6541:
6542: }
6543: return (0,$currentphase+1);
6544: }
6545:
6546: =pod
6547:
6548: =item scantron_process_students
6549:
6550: Routine that does the actual grading of the bubble sheet information.
6551:
6552: The parsed scanline hash is added to %env
6553:
6554: Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
6555: foreach resource , with the form data of
6556:
6557: 'submitted' =>'scantron'
6558: 'grade_target' =>'grade',
6559: 'grade_username'=> username of student
6560: 'grade_domain' => domain of student
6561: 'grade_courseid'=> of course
6562: 'grade_symb' => symb of resource to grade
6563:
6564: This triggers a grading pass. The problem grading code takes care
6565: of converting the bubbled letter information (now in %env) into a
6566: valid submission.
6567:
6568: =cut
6569:
6570: sub scantron_process_students {
6571: my ($r) = @_;
6572: my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
6573: my ($symb)=&get_symb($r);
6574: if (!$symb) {return '';}
6575: my $default_form_data=&defaultFormData($symb);
6576:
6577: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6578: my ($scanlines,$scan_data)=&scantron_getfile();
6579: my $classlist=&Apache::loncoursedata::get_classlist();
6580: my %idmap=&username_to_idmap($classlist);
6581: my $navmap=Apache::lonnavmaps::navmap->new();
6582: my $map=$navmap->getResourceByUrl($sequence);
6583: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
6584: # $r->print("geto ".scalar(@resources)."<br />");
6585: my $result= <<SCANTRONFORM;
6586: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
6587: <input type="hidden" name="command" value="scantron_configphase" />
6588: $default_form_data
6589: SCANTRONFORM
6590: $r->print($result);
6591:
6592: my @delayqueue;
6593: my %completedstudents;
6594:
6595: my $count=&get_todo_count($scanlines,$scan_data);
6596: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
6597: 'Scantron Progress',$count,
6598: 'inline',undef,'scantronupload');
6599: &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
6600: 'Processing first student');
6601: my $start=&Time::HiRes::time();
6602: my $i=-1;
6603: my ($uname,$udom,$started);
6604: while ($i<$scanlines->{'count'}) {
6605: ($uname,$udom)=('','');
6606: $i++;
6607: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6608: if ($line=~/^[\s\cz]*$/) { next; }
6609: if ($started) {
6610: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
6611: 'last student');
6612: }
6613: $started=1;
6614: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6615: $scan_data);
6616: unless ($uname=&scantron_find_student($scan_record,$scan_data,
6617: \%idmap,$i)) {
6618: &scantron_add_delay(\@delayqueue,$line,
6619: 'Unable to find a student that matches',1);
6620: next;
6621: }
6622: if (exists $completedstudents{$uname}) {
6623: &scantron_add_delay(\@delayqueue,$line,
6624: 'Student '.$uname.' has multiple sheets',2);
6625: next;
6626: }
6627: ($uname,$udom)=split(/:/,$uname);
6628:
6629: &Apache::lonxml::clear_problem_counter();
6630: &Apache::lonnet::appenv(%$scan_record);
6631:
6632: if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
6633: &scantron_putfile($scanlines,$scan_data);
6634: }
6635:
6636: my $i=0;
6637: foreach my $resource (@resources) {
6638: $i++;
6639: my %form=('submitted' =>'scantron',
6640: 'grade_target' =>'grade',
6641: 'grade_username'=>$uname,
6642: 'grade_domain' =>$udom,
6643: 'grade_courseid'=>$env{'request.course.id'},
6644: 'grade_symb' =>$resource->symb());
6645: if (exists($scan_record->{'scantron.CODE'})
6646: &&
6647: &Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
6648: $form{'CODE'}=$scan_record->{'scantron.CODE'};
6649: } else {
6650: $form{'CODE'}='';
6651: }
6652: my $result=&Apache::lonnet::ssi($resource->src(),%form);
6653: if ($result ne '') {
6654: &Apache::lonnet::logthis("scantron grading error -> $result");
6655: &Apache::lonnet::logthis("scantron grading error info name $uname domain $udom course $env{'request.course.id'} url ".$resource->src());
6656: }
6657: if (&Apache::loncommon::connection_aborted($r)) { last; }
6658: }
6659: $completedstudents{$uname}={'line'=>$line};
6660: if (&Apache::loncommon::connection_aborted($r)) { last; }
6661: } continue {
6662: &Apache::lonxml::clear_problem_counter();
6663: &Apache::lonnet::delenv('scantron\.');
6664: }
6665: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
6666: # my $lasttime = &Time::HiRes::time()-$start;
6667: # $r->print("<p>took $lasttime</p>");
6668:
6669: $r->print("</form>");
6670: $r->print(&show_grading_menu_form($symb));
6671: return '';
6672: }
6673:
6674: =pod
6675:
6676: =item scantron_upload_scantron_data
6677:
6678: Creates the screen for adding a new bubble sheet data file to a course.
6679:
6680: =cut
6681:
6682: sub scantron_upload_scantron_data {
6683: my ($r)=@_;
6684: $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
6685: my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
6686: 'domainid',
6687: 'coursename');
6688: my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
6689: 'domainid');
6690: my $default_form_data=&defaultFormData(&get_symb($r,1));
6691: $r->print(<<UPLOAD);
6692: <script type="text/javascript" language="javascript">
6693: function checkUpload(formname) {
6694: if (formname.upfile.value == "") {
6695: alert("Please use the browse button to select a file from your local directory.");
6696: return false;
6697: }
6698: formname.submit();
6699: }
6700: </script>
6701:
6702: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
6703: $default_form_data
6704: <table>
6705: <tr><td>$select_link </td></tr>
6706: <tr><td>Course ID: </td><td><input name='courseid' type='text' /> </td></tr>
6707: <tr><td>Course Name: </td><td><input name='coursename' type='text' /></td></tr>
6708: <tr><td>Domain: </td><td>$domsel </td></tr>
6709: <tr><td>File to upload:</td><td><input type="file" name="upfile" size="50" /></td></tr>
6710: </table>
6711: <input name='command' value='scantronupload_save' type='hidden' />
6712: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
6713: </form>
6714: UPLOAD
6715: return '';
6716: }
6717:
6718: =pod
6719:
6720: =item scantron_upload_scantron_data_save
6721:
6722: Adds a provided bubble information data file to the course if user
6723: has the correct privileges to do so.
6724:
6725: =cut
6726:
6727: sub scantron_upload_scantron_data_save {
6728: my($r)=@_;
6729: my ($symb)=&get_symb($r,1);
6730: my $doanotherupload=
6731: '<br /><form action="/adm/grades" method="post">'."\n".
6732: '<input type="hidden" name="command" value="scantronupload" />'."\n".
6733: '<input type="submit" name="submit" value="Do Another Upload" />'."\n".
6734: '</form>'."\n";
6735: if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
6736: !&Apache::lonnet::allowed('usc',
6737: $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
6738: $r->print("You are not allowed to upload Scantron data to the requested course.<br />");
6739: if ($symb) {
6740: $r->print(&show_grading_menu_form($symb));
6741: } else {
6742: $r->print($doanotherupload);
6743: }
6744: return '';
6745: }
6746: my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
6747: $r->print("Doing upload to ".$coursedata{'description'}." <br />");
6748: my $fname=$env{'form.upfile.filename'};
6749: #FIXME
6750: #copied from lonnet::userfileupload()
6751: #make that function able to target a specified course
6752: # Replace Windows backslashes by forward slashes
6753: $fname=~s/\\/\//g;
6754: # Get rid of everything but the actual filename
6755: $fname=~s/^.*\/([^\/]+)$/$1/;
6756: # Replace spaces by underscores
6757: $fname=~s/\s+/\_/g;
6758: # Replace all other weird characters by nothing
6759: $fname=~s/[^\w\.\-]//g;
6760: # See if there is anything left
6761: unless ($fname) { return 'error: no uploaded file'; }
6762: my $uploadedfile=$fname;
6763: $fname='scantron_orig_'.$fname;
6764: if (length($env{'form.upfile'}) < 2) {
6765: $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.");
6766: } else {
6767: my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
6768: if ($result =~ m|^/uploaded/|) {
6769: $r->print("<span class=\"LC_success\">Success:</span> Successfully uploaded ".(length($env{'form.upfile'})-1)." bytes of data into location <tt>".$result."</tt>");
6770: } else {
6771: $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>");
6772: }
6773: }
6774: if ($symb) {
6775: $r->print(&scantron_selectphase($r,$uploadedfile));
6776: } else {
6777: $r->print($doanotherupload);
6778: }
6779: return '';
6780: }
6781:
6782: =pod
6783:
6784: =item valid_file
6785:
6786: Validates that the requested bubble data file exists in the course.
6787:
6788: =cut
6789:
6790: sub valid_file {
6791: my ($requested_file)=@_;
6792: foreach my $filename (sort(&scantron_filenames())) {
6793: if ($requested_file eq $filename) { return 1; }
6794: }
6795: return 0;
6796: }
6797:
6798: =pod
6799:
6800: =item scantron_download_scantron_data
6801:
6802: Shows a list of the three internal files (original, corrected,
6803: skipped) for a specific bubble sheet data file that exists in the
6804: course.
6805:
6806: =cut
6807:
6808: sub scantron_download_scantron_data {
6809: my ($r)=@_;
6810: my $default_form_data=&defaultFormData(&get_symb($r,1));
6811: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6812: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6813: my $file=$env{'form.scantron_selectfile'};
6814: if (! &valid_file($file)) {
6815: $r->print(<<ERROR);
6816: <p>
6817: The requested file name was invalid.
6818: </p>
6819: ERROR
6820: $r->print(&show_grading_menu_form(&get_symb($r,1)));
6821: return;
6822: }
6823: my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
6824: my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
6825: my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
6826: &Apache::lonnet::allowuploaded('/adm/grades',$orig);
6827: &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
6828: &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
6829: $r->print(<<DOWNLOAD);
6830: <p>
6831: <a href="$orig">Original</a> file as uploaded by the scantron office.
6832: </p>
6833: <p>
6834: <a href="$corrected">Corrections</a>, a file of corrected records that were used in grading.
6835: </p>
6836: <p>
6837: <a href="$skipped">Skipped</a>, a file of records that were skipped.
6838: </p>
6839: DOWNLOAD
6840: $r->print(&show_grading_menu_form(&get_symb($r,1)));
6841: return '';
6842: }
6843:
6844: =pod
6845:
6846: =back
6847:
6848: =cut
6849:
6850: #-------- end of section for handling grading scantron forms -------
6851: #
6852: #-------------------------------------------------------------------
6853:
6854: #-------------------------- Menu interface -------------------------
6855: #
6856: #--- Show a Grading Menu button - Calls the next routine ---
6857: sub show_grading_menu_form {
6858: my ($symb)=@_;
6859: my $result.='<br /><form action="/adm/grades" method="post">'."\n".
6860: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
6861: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
6862: '<input type="hidden" name="command" value="gradingmenu" />'."\n".
6863: '<input type="submit" name="submit" value="Grading Menu" />'."\n".
6864: '</form>'."\n";
6865: return $result;
6866: }
6867:
6868: # -- Retrieve choices for grading form
6869: sub savedState {
6870: my %savedState = ();
6871: if ($env{'form.saveState'}) {
6872: foreach (split(/:/,$env{'form.saveState'})) {
6873: my ($key,$value) = split(/=/,$_,2);
6874: $savedState{$key} = $value;
6875: }
6876: }
6877: return \%savedState;
6878: }
6879:
6880: #--- Displays the main menu page -------
6881: sub gradingmenu {
6882: my ($request) = @_;
6883: my ($symb)=&get_symb($request);
6884: if (!$symb) {return '';}
6885: my $probTitle = &Apache::lonnet::gettitle($symb);
6886:
6887: $request->print(<<GRADINGMENUJS);
6888: <script type="text/javascript" language="javascript">
6889: function checkChoice(formname,val,cmdx) {
6890: if (val <= 2) {
6891: var cmd = radioSelection(formname.radioChoice);
6892: var cmdsave = cmd;
6893: } else {
6894: cmd = cmdx;
6895: cmdsave = 'submission';
6896: }
6897: formname.command.value = cmd;
6898: formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
6899: ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
6900: if (val < 5) formname.submit();
6901: if (val == 5) {
6902: if (!checkReceiptNo(formname,'notOK')) { return false;}
6903: formname.submit();
6904: }
6905: if (val < 7) formname.submit();
6906: }
6907:
6908: function checkReceiptNo(formname,nospace) {
6909: var receiptNo = formname.receipt.value;
6910: var checkOpt = false;
6911: if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
6912: if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
6913: if (checkOpt) {
6914: alert("Please enter a receipt number given by a student in the receipt box.");
6915: formname.receipt.value = "";
6916: formname.receipt.focus();
6917: return false;
6918: }
6919: return true;
6920: }
6921: </script>
6922: GRADINGMENUJS
6923: &commonJSfunctions($request);
6924: my $result='<h3> <span class="LC_info">Manual Grading/View Submission</span></h3>';
6925: my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
6926: $result.=$table;
6927: my (undef,$sections) = &getclasslist('all','0');
6928: my $savedState = &savedState();
6929: my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
6930: my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
6931: my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
6932: my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
6933:
6934: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
6935: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
6936: '<input type="hidden" name="handgrade" value="'.$hdgrade.'" />'."\n".
6937: '<input type="hidden" name="probTitle" value="'.$probTitle.'" />'."\n".
6938: '<input type="hidden" name="command" value="" />'."\n".
6939: '<input type="hidden" name="saveState" value="" />'."\n".
6940: '<input type="hidden" name="gradingMenu" value="1" />'."\n".
6941: '<input type="hidden" name="showgrading" value="yes" />'."\n";
6942:
6943: $result.='<table width="100%" border="0"><tr><td bgcolor=#777777>'."\n".
6944: '<table width="100%" border="0"><tr bgcolor="#e6ffff"><td colspan="2">'."\n".
6945: ' <b>Select a Grading/Viewing Option</b></td></tr>'."\n".
6946: '<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
6947:
6948: $result.='<table width="100%" border="0">';
6949: $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
6950: ' '.&mt('Select Section').': <select name="section" multiple="multiple" size="3">'."\n";
6951: if (ref($sections)) {
6952: foreach (sort (@$sections)) {
6953: $result.='<option value="'.$_.'" '.
6954: ($saveSec eq $_ ? 'selected="selected"':'').'>'.$_.'</option>'."\n";
6955: }
6956: }
6957: $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> ';
6958:
6959: $result.=&mt('Student Status').':'.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,undef);
6960:
6961: $result.='</td></tr>';
6962:
6963: $result.='<tr bgcolor="#ffffe6"valign="top"><td><label>'.
6964: '<input type="radio" name="radioChoice" value="submission" '.
6965: ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.'<b>'.&mt('Current Resource').':</b> '.&mt('For one or more students').
6966: '</label> <select name="submitonly">'.
6967: '<option value="yes" '.
6968: ($saveSub eq 'yes' ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>'.
6969: '<option value="queued" '.
6970: ($saveSub eq 'queued' ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>'.
6971: '<option value="graded" '.
6972: ($saveSub eq 'graded' ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>'.
6973: '<option value="incorrect" '.
6974: ($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>'.
6975: '<option value="all" '.
6976: ($saveSub eq 'all' ? 'selected="selected"' : '').'>'.&mt('with any status').'</option></select></td></tr>'."\n";
6977:
6978: $result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
6979: '<label><input type="radio" name="radioChoice" value="viewgrades" '.
6980: ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
6981: '<b>Current Resource:</b> For all students in selected section or course</label></td></tr>'."\n";
6982:
6983: $result.='<tr bgcolor="#ffffe6" valign="top"><td>'.
6984: '<label><input type="radio" name="radioChoice" value="pickStudentPage" '.
6985: ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
6986: 'The <b>complete</b> set/page/sequence: For one student</label></td></tr>'."\n";
6987:
6988: $result.='<tr bgcolor="#ffffe6"><td><br />'.
6989: '<input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="Next->" />'.
6990: '</td></tr></table>'."\n";
6991:
6992: $result.='</td><td valign="top">';
6993:
6994: $result.='<table width="100%" border="0">';
6995: $result.='<tr bgcolor="#ffffe6"><td>'.
6996: '<input type="button" onClick="javascript:checkChoice(this.form,\'3\',\'csvform\');" value="'.&mt('Upload').'" />'.
6997: ' '.&mt('scores from file').' </td></tr>'."\n";
6998:
6999: $result.='<tr bgcolor="#ffffe6"><td>'.
7000: '<input type="button" onClick="javascript:checkChoice(this.form,\'6\',\'processclicker\');" value="'.&mt('Process').'" />'.
7001: ' '.&mt('clicker file').' </td></tr>'."\n";
7002:
7003: $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
7004: '<input type="button" onClick="javascript:checkChoice(this.form,\'4\',\'scantron_selectphase\');'.
7005: '" value="'.&mt('Grade').'" /> scantron forms</td></tr>'."\n";
7006:
7007: if ((&Apache::lonnet::allowed('mgr',$env{'request.course.id'})) && ($symb)) {
7008: $result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
7009: '<input type="button" onClick="javascript:checkChoice(this.form,\'5\',\'verify\');" value="'.&mt('Verify').'" />'.
7010: ' '.&mt('receipt').': '.
7011: &Apache::lonnet::recprefix($env{'request.course.id'}).
7012: '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />'.
7013: '</td></tr>'."\n";
7014: }
7015: $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
7016: '<input type="button" onClick="javascript:this.form.action=\'/adm/helper/resettimes.helper\';this.form.submit();'.
7017: '" value="'.&mt('Manage').'" /> access times.</td></tr>'."\n";
7018: $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
7019: '<input type="button" onClick="javascript:this.form.command.value=\'codelist\';this.form.action=\'/adm/pickcode\';this.form.submit();'.
7020: '" value="'.&mt('View').'" /> saved CODEs.</td></tr>'."\n";
7021:
7022: $result.='</table>'."\n".
7023: '</td></tr></table>'."\n".
7024: '</td></tr></table></form>'."\n";
7025: return $result;
7026: }
7027:
7028: sub reset_perm {
7029: undef(%perm);
7030: }
7031:
7032: sub init_perm {
7033: &reset_perm();
7034: foreach my $test_perm ('vgr','mgr','opa') {
7035:
7036: my $scope = $env{'request.course.id'};
7037: if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
7038:
7039: $scope .= '/'.$env{'request.course.sec'};
7040: if ( $perm{$test_perm}=
7041: &Apache::lonnet::allowed($test_perm,$scope)) {
7042: $perm{$test_perm.'_section'}=$env{'request.course.sec'};
7043: } else {
7044: delete($perm{$test_perm});
7045: }
7046: }
7047: }
7048: }
7049:
7050: sub gather_clicker_ids {
7051: my %clicker_ids;
7052:
7053: my $classlist = &Apache::loncoursedata::get_classlist();
7054:
7055: # Set up a couple variables.
7056: my $username_idx = &Apache::loncoursedata::CL_SNAME();
7057: my $domain_idx = &Apache::loncoursedata::CL_SDOM();
7058:
7059: foreach my $student (keys(%$classlist)) {
7060:
7061: my $username = $classlist->{$student}->[$username_idx];
7062: my $domain = $classlist->{$student}->[$domain_idx];
7063: my $clickers =
7064: (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
7065: foreach my $id (split(/\,/,$clickers)) {
7066: $id=~s/^[\#0]+//;
7067: $id=~s/[\-\:]//g;
7068: if (exists($clicker_ids{$id})) {
7069: $clicker_ids{$id}.=','.$username.':'.$domain;
7070: } else {
7071: $clicker_ids{$id}=$username.':'.$domain;
7072: }
7073: }
7074: }
7075: return %clicker_ids;
7076: }
7077:
7078: sub gather_adv_clicker_ids {
7079: my %clicker_ids;
7080: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
7081: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7082: my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
7083: foreach my $element (sort(keys(%coursepersonnel))) {
7084: foreach my $person (split(/\,/,$coursepersonnel{$element})) {
7085: my ($puname,$pudom)=split(/\:/,$person);
7086: my $clickers =
7087: (&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
7088: foreach my $id (split(/\,/,$clickers)) {
7089: $id=~s/^[\#0]+//;
7090: $id=~s/[\-\:]//g;
7091: if (exists($clicker_ids{$id})) {
7092: $clicker_ids{$id}.=','.$puname.':'.$pudom;
7093: } else {
7094: $clicker_ids{$id}=$puname.':'.$pudom;
7095: }
7096: }
7097: }
7098: }
7099: return %clicker_ids;
7100: }
7101:
7102: sub clicker_grading_parameters {
7103: return ('gradingmechanism' => 'scalar',
7104: 'upfiletype' => 'scalar',
7105: 'specificid' => 'scalar',
7106: 'pcorrect' => 'scalar',
7107: 'pincorrect' => 'scalar');
7108: }
7109:
7110: sub process_clicker {
7111: my ($r)=@_;
7112: my ($symb)=&get_symb($r);
7113: if (!$symb) {return '';}
7114: my $result=&checkforfile_js();
7115: $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
7116: my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
7117: $result.=$table;
7118: $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
7119: $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
7120: $result.=' <b>'.&mt('Specify a file containing the clicker information for this resource').
7121: '.</b></td></tr>'."\n";
7122: $result.='<tr bgcolor=#ffffe6><td>'."\n";
7123: # Attempt to restore parameters from last session, set defaults if not present
7124: my %Saveable_Parameters=&clicker_grading_parameters();
7125: &Apache::loncommon::restore_course_settings('grades_clicker',
7126: \%Saveable_Parameters);
7127: if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
7128: if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
7129: if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
7130: if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
7131:
7132: my %checked;
7133: foreach my $gradingmechanism ('attendance','personnel','specific') {
7134: if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
7135: $checked{$gradingmechanism}="checked='checked'";
7136: }
7137: }
7138:
7139: my $upload=&mt("Upload File");
7140: my $type=&mt("Type");
7141: my $attendance=&mt("Award points just for participation");
7142: my $personnel=&mt("Correctness determined from response by course personnel");
7143: my $specific=&mt("Correctness determined from response with clicker ID(s)");
7144: my $pcorrect=&mt("Percentage points for correct solution");
7145: my $pincorrect=&mt("Percentage points for incorrect solution");
7146: my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
7147: ('iclicker' => 'i>clicker',
7148: 'interwrite' => 'interwrite PRS'));
7149: $symb = &Apache::lonenc::check_encrypt($symb);
7150: $result.=<<ENDUPFORM;
7151: <script type="text/javascript">
7152: function sanitycheck() {
7153: // Accept only integer percentages
7154: document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
7155: document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
7156: // Find out grading choice
7157: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
7158: if (document.forms.gradesupload.gradingmechanism[i].checked) {
7159: gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
7160: }
7161: }
7162: // By default, new choice equals user selection
7163: newgradingchoice=gradingchoice;
7164: // Not good to give more points for false answers than correct ones
7165: if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
7166: document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
7167: }
7168: // If new choice is attendance only, and old choice was correctness-based, restore defaults
7169: if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
7170: document.forms.gradesupload.pcorrect.value=100;
7171: document.forms.gradesupload.pincorrect.value=100;
7172: }
7173: // If the values are different, cannot be attendance only
7174: if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
7175: (gradingchoice=='attendance')) {
7176: newgradingchoice='personnel';
7177: }
7178: // Change grading choice to new one
7179: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
7180: if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
7181: document.forms.gradesupload.gradingmechanism[i].checked=true;
7182: } else {
7183: document.forms.gradesupload.gradingmechanism[i].checked=false;
7184: }
7185: }
7186: // Remember the old state
7187: document.forms.gradesupload.waschecked.value=newgradingchoice;
7188: }
7189: </script>
7190: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
7191: <input type="hidden" name="symb" value="$symb" />
7192: <input type="hidden" name="command" value="processclickerfile" />
7193: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
7194: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
7195: <input type="file" name="upfile" size="50" />
7196: <br /><label>$type: $selectform</label>
7197: <br /><label>$attendance: <input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" /></label>
7198: <br /><label>$personnel: <input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" /></label>
7199: <br /><label>$specific: <input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" /></label>
7200: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
7201: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
7202: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
7203: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
7204: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
7205: </form>
7206: ENDUPFORM
7207: $result.='</td></tr></table>'."\n".
7208: '</td></tr></table><br /><br />'."\n";
7209: $result.=&show_grading_menu_form($symb);
7210: return $result;
7211: }
7212:
7213: sub process_clicker_file {
7214: my ($r)=@_;
7215: my ($symb)=&get_symb($r);
7216: if (!$symb) {return '';}
7217:
7218: my %Saveable_Parameters=&clicker_grading_parameters();
7219: &Apache::loncommon::store_course_settings('grades_clicker',
7220: \%Saveable_Parameters);
7221:
7222: my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
7223: if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
7224: $result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
7225: return $result.&show_grading_menu_form($symb);
7226: }
7227: my %clicker_ids=&gather_clicker_ids();
7228: my %correct_ids;
7229: if ($env{'form.gradingmechanism'} eq 'personnel') {
7230: %correct_ids=&gather_adv_clicker_ids();
7231: }
7232: if ($env{'form.gradingmechanism'} eq 'specific') {
7233: foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
7234: $correct_id=~tr/a-z/A-Z/;
7235: $correct_id=~s/\s//gs;
7236: $correct_id=~s/^[\#0]+//;
7237: $correct_id=~s/[\-\:]//g;
7238: if ($correct_id) {
7239: $correct_ids{$correct_id}='specified';
7240: }
7241: }
7242: }
7243: if ($env{'form.gradingmechanism'} eq 'attendance') {
7244: $result.=&mt('Score based on attendance only');
7245: } else {
7246: my $number=0;
7247: $result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
7248: foreach my $id (sort(keys(%correct_ids))) {
7249: $result.='<br /><tt>'.$id.'</tt> - ';
7250: if ($correct_ids{$id} eq 'specified') {
7251: $result.=&mt('specified');
7252: } else {
7253: my ($uname,$udom)=split(/\:/,$correct_ids{$id});
7254: $result.=&Apache::loncommon::plainname($uname,$udom);
7255: }
7256: $number++;
7257: }
7258: $result.="</p>\n";
7259: if ($number==0) {
7260: $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
7261: return $result.&show_grading_menu_form($symb);
7262: }
7263: }
7264: if (length($env{'form.upfile'}) < 2) {
7265: $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
7266: '<span class="LC_error">',
7267: '</span>',
7268: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
7269: return $result.&show_grading_menu_form($symb);
7270: }
7271:
7272: # Were able to get all the info needed, now analyze the file
7273:
7274: $result.=&Apache::loncommon::studentbrowser_javascript();
7275: $symb = &Apache::lonenc::check_encrypt($symb);
7276: my $heading=&mt('Scanning clicker file');
7277: $result.=(<<ENDHEADER);
7278: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
7279: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
7280: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
7281: <form method="post" action="/adm/grades" name="clickeranalysis">
7282: <input type="hidden" name="symb" value="$symb" />
7283: <input type="hidden" name="command" value="assignclickergrades" />
7284: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
7285: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
7286: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
7287: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
7288: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
7289: ENDHEADER
7290: my %responses;
7291: my @questiontitles;
7292: my $errormsg='';
7293: my $number=0;
7294: if ($env{'form.upfiletype'} eq 'iclicker') {
7295: ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
7296: }
7297: if ($env{'form.upfiletype'} eq 'interwrite') {
7298: ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
7299: }
7300: $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
7301: '<input type="hidden" name="number" value="'.$number.'" />'.
7302: &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
7303: $env{'form.pcorrect'},$env{'form.pincorrect'}).
7304: '<br />';
7305: # Remember Question Titles
7306: # FIXME: Possibly need delimiter other than ":"
7307: for (my $i=0;$i<$number;$i++) {
7308: $result.='<input type="hidden" name="question:'.$i.'" value="'.
7309: &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
7310: }
7311: my $correct_count=0;
7312: my $student_count=0;
7313: my $unknown_count=0;
7314: # Match answers with usernames
7315: # FIXME: Possibly need delimiter other than ":"
7316: foreach my $id (keys(%responses)) {
7317: if ($correct_ids{$id}) {
7318: $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
7319: $correct_count++;
7320: } elsif ($clicker_ids{$id}) {
7321: $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
7322: $student_count++;
7323: } else {
7324: $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
7325: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
7326: "\n".&mt("Username").": <input type='text' name='uname".$id."' /> ".
7327: "\n".&mt("Domain").": ".
7328: &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).' '.
7329: &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
7330: $unknown_count++;
7331: }
7332: }
7333: $result.='<hr />'.
7334: &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
7335: if ($env{'form.gradingmechanism'} ne 'attendance') {
7336: if ($correct_count==0) {
7337: $errormsg.="Found no correct answers answers for grading!";
7338: } elsif ($correct_count>1) {
7339: $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
7340: }
7341: }
7342: if ($number<1) {
7343: $errormsg.="Found no questions.";
7344: }
7345: if ($errormsg) {
7346: $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
7347: } else {
7348: $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
7349: }
7350: $result.='</form></td></tr></table>'."\n".
7351: '</td></tr></table><br /><br />'."\n";
7352: return $result.&show_grading_menu_form($symb);
7353: }
7354:
7355: sub iclicker_eval {
7356: my ($questiontitles,$responses)=@_;
7357: my $number=0;
7358: my $errormsg='';
7359: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
7360: my %components=&Apache::loncommon::record_sep($line);
7361: my @entries=map {$components{$_}} (sort(keys(%components)));
7362: if ($entries[0] eq 'Question') {
7363: for (my $i=3;$i<$#entries;$i+=6) {
7364: $$questiontitles[$number]=$entries[$i];
7365: $number++;
7366: }
7367: }
7368: if ($entries[0]=~/^\#/) {
7369: my $id=$entries[0];
7370: my @idresponses;
7371: $id=~s/^[\#0]+//;
7372: for (my $i=0;$i<$number;$i++) {
7373: my $idx=3+$i*6;
7374: push(@idresponses,$entries[$idx]);
7375: }
7376: $$responses{$id}=join(',',@idresponses);
7377: }
7378: }
7379: return ($errormsg,$number);
7380: }
7381:
7382: sub interwrite_eval {
7383: my ($questiontitles,$responses)=@_;
7384: my $number=0;
7385: my $errormsg='';
7386: my $skipline=1;
7387: my $questionnumber=0;
7388: my %idresponses=();
7389: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
7390: my %components=&Apache::loncommon::record_sep($line);
7391: my @entries=map {$components{$_}} (sort(keys(%components)));
7392: if ($entries[1] eq 'Time') { $skipline=0; next; }
7393: if ($entries[1] eq 'Response') { $skipline=1; }
7394: next if $skipline;
7395: if ($entries[0]!=$questionnumber) {
7396: $questionnumber=$entries[0];
7397: $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
7398: $number++;
7399: }
7400: my $id=$entries[4];
7401: $id=~s/^[\#0]+//;
7402: $id=~s/^v\d*\://i;
7403: $id=~s/[\-\:]//g;
7404: $idresponses{$id}[$number]=$entries[6];
7405: }
7406: foreach my $id (keys %idresponses) {
7407: $$responses{$id}=join(',',@{$idresponses{$id}});
7408: $$responses{$id}=~s/^\s*\,//;
7409: }
7410: return ($errormsg,$number);
7411: }
7412:
7413: sub assign_clicker_grades {
7414: my ($r)=@_;
7415: my ($symb)=&get_symb($r);
7416: if (!$symb) {return '';}
7417: # See which part we are saving to
7418: my ($partlist,$handgrade,$responseType) = &response_type($symb);
7419: # FIXME: This should probably look for the first handgradeable part
7420: my $part=$$partlist[0];
7421: # Start screen output
7422: my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
7423:
7424: my $heading=&mt('Assigning grades based on clicker file');
7425: $result.=(<<ENDHEADER);
7426: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
7427: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
7428: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
7429: ENDHEADER
7430: # Get correct result
7431: # FIXME: Possibly need delimiter other than ":"
7432: my @correct=();
7433: my $gradingmechanism=$env{'form.gradingmechanism'};
7434: my $number=$env{'form.number'};
7435: if ($gradingmechanism ne 'attendance') {
7436: foreach my $key (keys(%env)) {
7437: if ($key=~/^form\.correct\:/) {
7438: my @input=split(/\,/,$env{$key});
7439: for (my $i=0;$i<=$#input;$i++) {
7440: if (($correct[$i]) && ($input[$i]) &&
7441: ($correct[$i] ne $input[$i])) {
7442: $result.='<br /><span class="LC_warning">'.
7443: &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
7444: $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
7445: } elsif ($input[$i]) {
7446: $correct[$i]=$input[$i];
7447: }
7448: }
7449: }
7450: }
7451: for (my $i=0;$i<$number;$i++) {
7452: if (!$correct[$i]) {
7453: $result.='<br /><span class="LC_error">'.
7454: &mt('No correct result given for question "[_1]"!',
7455: $env{'form.question:'.$i}).'</span>';
7456: }
7457: }
7458: $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
7459: }
7460: # Start grading
7461: my $pcorrect=$env{'form.pcorrect'};
7462: my $pincorrect=$env{'form.pincorrect'};
7463: my $storecount=0;
7464: foreach my $key (keys(%env)) {
7465: my $user='';
7466: if ($key=~/^form\.student\:(.*)$/) {
7467: $user=$1;
7468: }
7469: if ($key=~/^form\.unknown\:(.*)$/) {
7470: my $id=$1;
7471: if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
7472: $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
7473: }
7474: }
7475: if ($user) {
7476: my @answer=split(/\,/,$env{$key});
7477: my $sum=0;
7478: for (my $i=0;$i<$number;$i++) {
7479: if ($answer[$i]) {
7480: if ($gradingmechanism eq 'attendance') {
7481: $sum+=$pcorrect;
7482: } else {
7483: if ($answer[$i] eq $correct[$i]) {
7484: $sum+=$pcorrect;
7485: } else {
7486: $sum+=$pincorrect;
7487: }
7488: }
7489: }
7490: }
7491: my $ave=$sum/(100*$number);
7492: # Store
7493: my ($username,$domain)=split(/\:/,$user);
7494: my %grades=();
7495: $grades{"resource.$part.solved"}='correct_by_override';
7496: $grades{"resource.$part.awarded"}=$ave;
7497: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
7498: my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
7499: $env{'request.course.id'},
7500: $domain,$username);
7501: if ($returncode ne 'ok') {
7502: $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
7503: } else {
7504: $storecount++;
7505: }
7506: }
7507: }
7508: # We are done
7509: $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
7510: '</td></tr></table>'."\n".
7511: '</td></tr></table><br /><br />'."\n";
7512: return $result.&show_grading_menu_form($symb);
7513: }
7514:
7515: sub handler {
7516: my $request=$_[0];
7517:
7518: &reset_perm();
7519: if ($env{'browser.mathml'}) {
7520: &Apache::loncommon::content_type($request,'text/xml');
7521: } else {
7522: &Apache::loncommon::content_type($request,'text/html');
7523: }
7524: $request->send_http_header;
7525: return '' if $request->header_only;
7526: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
7527: my $symb=&get_symb($request,1);
7528: my @commands=&Apache::loncommon::get_env_multiple('form.command');
7529: my $command=$commands[0];
7530: if ($#commands > 0) {
7531: &Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
7532: }
7533: $request->print(&Apache::loncommon::start_page('Grading'));
7534: if ($symb eq '' && $command eq '') {
7535: if ($env{'user.adv'}) {
7536: if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
7537: ($env{'form.codethree'})) {
7538: my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
7539: $env{'form.codethree'};
7540: my ($tsymb,$tuname,$tudom,$tcrsid)=
7541: &Apache::lonnet::checkin($token);
7542: if ($tsymb) {
7543: my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
7544: if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
7545: $request->print(&Apache::lonnet::ssi_body('/res/'.$url,
7546: ('grade_username' => $tuname,
7547: 'grade_domain' => $tudom,
7548: 'grade_courseid' => $tcrsid,
7549: 'grade_symb' => $tsymb)));
7550: } else {
7551: $request->print('<h3>Not authorized: '.$token.'</h3>');
7552: }
7553: } else {
7554: $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
7555: }
7556: } else {
7557: $request->print(&Apache::lonxml::tokeninputfield());
7558: }
7559: }
7560: } else {
7561: &init_perm();
7562: if ($command eq 'submission' && $perm{'vgr'}) {
7563: ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
7564: } elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
7565: &pickStudentPage($request);
7566: } elsif ($command eq 'displayPage' && $perm{'vgr'}) {
7567: &displayPage($request);
7568: } elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
7569: &updateGradeByPage($request);
7570: } elsif ($command eq 'processGroup' && $perm{'vgr'}) {
7571: &processGroup($request);
7572: } elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
7573: $request->print(&gradingmenu($request));
7574: } elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
7575: $request->print(&viewgrades($request));
7576: } elsif ($command eq 'handgrade' && $perm{'mgr'}) {
7577: $request->print(&processHandGrade($request));
7578: } elsif ($command eq 'editgrades' && $perm{'mgr'}) {
7579: $request->print(&editgrades($request));
7580: } elsif ($command eq 'verify' && $perm{'vgr'}) {
7581: $request->print(&verifyreceipt($request));
7582: } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
7583: $request->print(&process_clicker($request));
7584: } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
7585: $request->print(&process_clicker_file($request));
7586: } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
7587: $request->print(&assign_clicker_grades($request));
7588: } elsif ($command eq 'csvform' && $perm{'mgr'}) {
7589: $request->print(&upcsvScores_form($request));
7590: } elsif ($command eq 'csvupload' && $perm{'mgr'}) {
7591: $request->print(&csvupload($request));
7592: } elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
7593: $request->print(&csvuploadmap($request));
7594: } elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
7595: if ($env{'form.associate'} ne 'Reverse Association') {
7596: $request->print(&csvuploadoptions($request));
7597: } else {
7598: if ( $env{'form.upfile_associate'} ne 'reverse' ) {
7599: $env{'form.upfile_associate'} = 'reverse';
7600: } else {
7601: $env{'form.upfile_associate'} = 'forward';
7602: }
7603: $request->print(&csvuploadmap($request));
7604: }
7605: } elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
7606: $request->print(&csvuploadassign($request));
7607: } elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
7608: $request->print(&scantron_selectphase($request));
7609: } elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
7610: $request->print(&scantron_do_warning($request));
7611: } elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
7612: $request->print(&scantron_validate_file($request));
7613: } elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
7614: $request->print(&scantron_process_students($request));
7615: } elsif ($command eq 'scantronupload' &&
7616: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
7617: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
7618: $request->print(&scantron_upload_scantron_data($request));
7619: } elsif ($command eq 'scantronupload_save' &&
7620: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
7621: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
7622: $request->print(&scantron_upload_scantron_data_save($request));
7623: } elsif ($command eq 'scantron_download' &&
7624: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
7625: $request->print(&scantron_download_scantron_data($request));
7626: } elsif ($command) {
7627: $request->print("Access Denied ($command)");
7628: }
7629: }
7630: $request->print(&Apache::loncommon::end_page());
7631: return '';
7632: }
7633:
7634: 1;
7635:
7636: __END__;
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>