1: # The LearningOnline Network with CAPA
2: # The LON-CAPA Grading handler
3: #
4: # $Id: grades.pm,v 1.432 2007/08/21 22:21:54 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: $result='<span class="LC_warning">There are no students in section "'.$env{'form.section'}.
3099: '" with enrollment status "'.$env{'form.Status'}.'" to modify or grade.</span>';
3100: }
3101: $result.=&show_grading_menu_form($symb);
3102: return $result;
3103: }
3104:
3105: #--- call by previous routine to display each student
3106: sub viewstudentgrade {
3107: my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
3108: my ($uname,$udom) = split(/:/,$student);
3109: my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
3110: my %aggregates = ();
3111: my $result='<tr bgcolor="#ffffdd"><td align="right">'.
3112: '<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
3113: "\n".$ctr.' </td><td> '.
3114: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
3115: '\');" target="_self">'.$fullname.'</a> '.
3116: '<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
3117: $student=~s/:/_/; # colon doen't work in javascript for names
3118: foreach my $apart (@$parts) {
3119: my ($part,$type) = &split_part_type($apart);
3120: my $score=$record{"resource.$part.$type"};
3121: $result.='<td align="center">';
3122: my ($aggtries,$totaltries);
3123: unless (exists($aggregates{$part})) {
3124: $totaltries = $record{'resource.'.$part.'.tries'};
3125:
3126: $aggtries = $totaltries;
3127: if ($$last_resets{$part}) {
3128: $aggtries = &get_num_tries(\%record,$$last_resets{$part},
3129: $part);
3130: }
3131: $result.='<input type="hidden" name="'.
3132: 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
3133: $result.='<input type="hidden" name="'.
3134: 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
3135: $aggregates{$part} = 1;
3136: }
3137: if ($type eq 'awarded') {
3138: my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
3139: $result.='<input type="hidden" name="'.
3140: 'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
3141: $result.='<input type="text" name="'.
3142: 'GD_'.$student.'_'.$part.'_awarded" '.
3143: 'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
3144: '\')" value="'.$pts.'" size="4" /></td>'."\n";
3145: } elsif ($type eq 'solved') {
3146: my ($status,$foo)=split(/_/,$score,2);
3147: $status = 'nothing' if ($status eq '');
3148: $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
3149: $part.'_solved_s" value="'.$status.'" />'."\n";
3150: $result.=' <select name="'.
3151: 'GD_'.$student.'_'.$part.'_solved" '.
3152: 'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
3153: $result.= (($status eq 'excused') ? '<option> </option><option selected="selected">excused</option>'
3154: : '<option selected="selected"> </option><option>excused</option>')."\n";
3155: $result.='<option>reset status</option>';
3156: $result.="</select> </td>\n";
3157: } else {
3158: $result.='<input type="hidden" name="'.
3159: 'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
3160: "\n";
3161: $result.='<input type="text" name="'.
3162: 'GD_'.$student.'_'.$part.'_'.$type.'" '.
3163: 'value="'.$score.'" size="4" /></td>'."\n";
3164: }
3165: }
3166: $result.='</tr>';
3167: return $result;
3168: }
3169:
3170: #--- change scores for all the students in a section/class
3171: # record does not get update if unchanged
3172: sub editgrades {
3173: my ($request) = @_;
3174:
3175: my $symb=&get_symb($request);
3176: my $title='<h3><span class="LC_info">Current Grade Status</span></h3>';
3177: $title.='<h4><b>Current Resource: </b>'.$env{'form.probTitle'}.'</h4><br />'."\n";
3178: $title.='<h4><b>Section: </b>'.$env{'form.section'}.'</h4>'."\n";
3179:
3180: my $result= '<table border="0"><tr><td bgcolor="#777777">'."\n";
3181: $result.= '<table border="0"><tr bgcolor="#deffff">'.
3182: '<td rowspan=2 valign="center"> <b>No.</b> </td>'.
3183: '<td rowspan=2 valign="center">'.&nameUserString('header')."</td>\n";
3184:
3185: my %scoreptr = (
3186: 'correct' =>'correct_by_override',
3187: 'incorrect'=>'incorrect_by_override',
3188: 'excused' =>'excused',
3189: 'ungraded' =>'ungraded_attempted',
3190: 'nothing' => '',
3191: );
3192: my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
3193:
3194: my (@partid);
3195: my %weight = ();
3196: my %columns = ();
3197: my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
3198:
3199: my (@parts) = sort(&getpartlist($symb));
3200: my $header;
3201: while ($ctr < $env{'form.totalparts'}) {
3202: my $partid = $env{'form.partid_'.$ctr};
3203: push @partid,$partid;
3204: $weight{$partid} = $env{'form.weight_'.$partid};
3205: $ctr++;
3206: }
3207: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3208: foreach my $partid (@partid) {
3209: $header .= '<td align="center"> <b>Old Score</b> </td>'.
3210: '<td align="center"> <b>New Score</b> </td>';
3211: $columns{$partid}=2;
3212: foreach my $stores (@parts) {
3213: my ($part,$type) = &split_part_type($stores);
3214: if ($part !~ m/^\Q$partid\E/) { next;}
3215: if ($type eq 'awarded' || $type eq 'solved') { next; }
3216: my $display=&Apache::lonnet::metadata($url,$stores.'.display');
3217: $display =~ s/\[Part: (\w)+\]//;
3218: $display =~ s/Number of Attempts/Tries/;
3219: $header .= '<td align="center"> <b>Old '.$display.'</b> </td>'.
3220: '<td align="center"> <b>New '.$display.'</b> </td>';
3221: $columns{$partid}+=2;
3222: }
3223: }
3224: foreach my $partid (@partid) {
3225: my $display_part=&get_display_part($partid,$symb);
3226: $result .= '<td colspan="'.$columns{$partid}.
3227: '" align="center"><b>Part:</b> '.$display_part.
3228: ' (Weight = '.$weight{$partid}.')</td>';
3229:
3230: }
3231: $result .= '</tr><tr bgcolor="#deffff">';
3232: $result .= $header;
3233: $result .= '</tr>'."\n";
3234: my $noupdate;
3235: my ($updateCtr,$noupdateCtr) = (1,1);
3236: for ($i=0; $i<$env{'form.total'}; $i++) {
3237: my $line;
3238: my $user = $env{'form.ctr'.$i};
3239: my ($uname,$udom)=split(/:/,$user);
3240: my %newrecord;
3241: my $updateflag = 0;
3242: $line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
3243: my $usec=$classlist->{"$uname:$udom"}[5];
3244: if (!&canmodify($usec)) {
3245: my $numcols=scalar(@partid)*4+2;
3246: $noupdate.=$line."<td colspan=\"$numcols\"><span class=\"LC_warning\">Not allowed to modify student</span></td></tr>";
3247: next;
3248: }
3249: my %aggregate = ();
3250: my $aggregateflag = 0;
3251: $user=~s/:/_/; # colon doen't work in javascript for names
3252: foreach (@partid) {
3253: my $old_aw = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
3254: my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
3255: my $old_part = $old_aw eq '' ? '' : $old_part_pcr;
3256: my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
3257: my $awarded = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
3258: my $pcr = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
3259: my $partial = $awarded eq '' ? '' : $pcr;
3260: my $score;
3261: if ($partial eq '') {
3262: $score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
3263: } elsif ($partial > 0) {
3264: $score = 'correct_by_override';
3265: } elsif ($partial == 0) {
3266: $score = 'incorrect_by_override';
3267: }
3268: my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
3269: $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
3270:
3271: $newrecord{'resource.'.$_.'.regrader'}=
3272: "$env{'user.name'}:$env{'user.domain'}";
3273: if ($dropMenu eq 'reset status' &&
3274: $old_score ne '') { # ignore if no previous attempts => nothing to reset
3275: $newrecord{'resource.'.$_.'.tries'} = '';
3276: $newrecord{'resource.'.$_.'.solved'} = '';
3277: $newrecord{'resource.'.$_.'.award'} = '';
3278: $newrecord{'resource.'.$_.'.awarded'} = '';
3279: $updateflag = 1;
3280: if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
3281: my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
3282: my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
3283: my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
3284: &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
3285: $aggregateflag = 1;
3286: }
3287: } elsif (!($old_part eq $partial && $old_score eq $score)) {
3288: $updateflag = 1;
3289: $newrecord{'resource.'.$_.'.awarded'} = $partial if $partial ne '';
3290: $newrecord{'resource.'.$_.'.solved'} = $score;
3291: $rec_update++;
3292: }
3293:
3294: $line .= '<td align="center">'.$old_aw.' </td>'.
3295: '<td align="center">'.$awarded.
3296: ($score eq 'excused' ? $score : '').' </td>';
3297:
3298:
3299: my $partid=$_;
3300: foreach my $stores (@parts) {
3301: my ($part,$type) = &split_part_type($stores);
3302: if ($part !~ m/^\Q$partid\E/) { next;}
3303: if ($type eq 'awarded' || $type eq 'solved') { next; }
3304: my $old_aw = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
3305: my $awarded = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
3306: if ($awarded ne '' && $awarded ne $old_aw) {
3307: $newrecord{'resource.'.$part.'.'.$type}= $awarded;
3308: $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
3309: $updateflag=1;
3310: }
3311: $line .= '<td align="center">'.$old_aw.' </td>'.
3312: '<td align="center">'.$awarded.' </td>';
3313: }
3314: }
3315: $line.='</tr>'."\n";
3316:
3317: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3318: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3319:
3320: if ($updateflag) {
3321: $count++;
3322: &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
3323: $udom,$uname);
3324:
3325: if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
3326: $cnum,$udom,$uname)) {
3327: # need to figure out if should be in queue.
3328: my %record =
3329: &Apache::lonnet::restore($symb,$env{'request.course.id'},
3330: $udom,$uname);
3331: my $all_graded = 1;
3332: my $none_graded = 1;
3333: foreach my $part (@parts) {
3334: if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
3335: $all_graded = 0;
3336: } else {
3337: $none_graded = 0;
3338: }
3339: }
3340:
3341: if ($all_graded || $none_graded) {
3342: &Apache::bridgetask::remove_from_queue('gradingqueue',
3343: $symb,$cdom,$cnum,
3344: $udom,$uname);
3345: }
3346: }
3347:
3348: $result.='<tr bgcolor="#ffffde"><td align="right"> '.$updateCtr.' </td>'.$line;
3349: $updateCtr++;
3350: } else {
3351: $noupdate.='<tr bgcolor="#ffffde"><td align="right"> '.$noupdateCtr.' </td>'.$line;
3352: $noupdateCtr++;
3353: }
3354: if ($aggregateflag) {
3355: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
3356: $cdom,$cnum);
3357: }
3358: }
3359: if ($noupdate) {
3360: # my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
3361: my $numcols=scalar(@partid)*4+2;
3362: $result .= '<tr bgcolor="#ffffff"><td align="center" colspan="'.$numcols.'">No Changes Occurred For the Students Below</td></tr><tr bgcolor="#ffffde">'.$noupdate;
3363: }
3364: $result .= '</table></td></tr></table>'."\n".
3365: &show_grading_menu_form ($symb);
3366: my $msg = '<br /><b>Number of records updated = '.$rec_update.
3367: ' for '.$count.' student'.($count <= 1 ? '' : 's').'.</b><br />'.
3368: '<b>Total number of students = '.$env{'form.total'}.'</b><br />';
3369: return $title.$msg.$result;
3370: }
3371:
3372: sub split_part_type {
3373: my ($partstr) = @_;
3374: my ($temp,@allparts)=split(/_/,$partstr);
3375: my $type=pop(@allparts);
3376: my $part=join('.',@allparts);
3377: return ($part,$type);
3378: }
3379:
3380: #------------- end of section for handling grading by section/class ---------
3381: #
3382: #----------------------------------------------------------------------------
3383:
3384:
3385: #----------------------------------------------------------------------------
3386: #
3387: #-------------------------- Next few routines handles grading by csv upload
3388: #
3389: #--- Javascript to handle csv upload
3390: sub csvupload_javascript_reverse_associate {
3391: my $error1=&mt('You need to specify the username or ID');
3392: my $error2=&mt('You need to specify at least one grading field');
3393: return(<<ENDPICK);
3394: function verify(vf) {
3395: var foundsomething=0;
3396: var founduname=0;
3397: var foundID=0;
3398: for (i=0;i<=vf.nfields.value;i++) {
3399: tw=eval('vf.f'+i+'.selectedIndex');
3400: if (i==0 && tw!=0) { foundID=1; }
3401: if (i==1 && tw!=0) { founduname=1; }
3402: if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
3403: }
3404: if (founduname==0 && foundID==0) {
3405: alert('$error1');
3406: return;
3407: }
3408: if (foundsomething==0) {
3409: alert('$error2');
3410: return;
3411: }
3412: vf.submit();
3413: }
3414: function flip(vf,tf) {
3415: var nw=eval('vf.f'+tf+'.selectedIndex');
3416: var i;
3417: for (i=0;i<=vf.nfields.value;i++) {
3418: //can not pick the same destination field for both name and domain
3419: if (((i ==0)||(i ==1)) &&
3420: ((tf==0)||(tf==1)) &&
3421: (i!=tf) &&
3422: (eval('vf.f'+i+'.selectedIndex')==nw)) {
3423: eval('vf.f'+i+'.selectedIndex=0;')
3424: }
3425: }
3426: }
3427: ENDPICK
3428: }
3429:
3430: sub csvupload_javascript_forward_associate {
3431: my $error1=&mt('You need to specify the username or ID');
3432: my $error2=&mt('You need to specify at least one grading field');
3433: return(<<ENDPICK);
3434: function verify(vf) {
3435: var foundsomething=0;
3436: var founduname=0;
3437: var foundID=0;
3438: for (i=0;i<=vf.nfields.value;i++) {
3439: tw=eval('vf.f'+i+'.selectedIndex');
3440: if (tw==1) { foundID=1; }
3441: if (tw==2) { founduname=1; }
3442: if (tw>3) { foundsomething=1; }
3443: }
3444: if (founduname==0 && foundID==0) {
3445: alert('$error1');
3446: return;
3447: }
3448: if (foundsomething==0) {
3449: alert('$error2');
3450: return;
3451: }
3452: vf.submit();
3453: }
3454: function flip(vf,tf) {
3455: var nw=eval('vf.f'+tf+'.selectedIndex');
3456: var i;
3457: //can not pick the same destination field twice
3458: for (i=0;i<=vf.nfields.value;i++) {
3459: if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
3460: eval('vf.f'+i+'.selectedIndex=0;')
3461: }
3462: }
3463: }
3464: ENDPICK
3465: }
3466:
3467: sub csvuploadmap_header {
3468: my ($request,$symb,$datatoken,$distotal)= @_;
3469: my $javascript;
3470: if ($env{'form.upfile_associate'} eq 'reverse') {
3471: $javascript=&csvupload_javascript_reverse_associate();
3472: } else {
3473: $javascript=&csvupload_javascript_forward_associate();
3474: }
3475:
3476: my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
3477: my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
3478: my $ignore=&mt('Ignore First Line');
3479: $symb = &Apache::lonenc::check_encrypt($symb);
3480: $request->print(<<ENDPICK);
3481: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3482: <h3><span class="LC_info">Uploading Class Grades</span></h3>
3483: $result
3484: <hr />
3485: <h3>Identify fields</h3>
3486: Total number of records found in file: $distotal <hr />
3487: Enter as many fields as you can. The system will inform you and bring you back
3488: to this page if the data selected is insufficient to run your class.<hr />
3489: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
3490: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
3491: <input type="hidden" name="associate" value="" />
3492: <input type="hidden" name="phase" value="three" />
3493: <input type="hidden" name="datatoken" value="$datatoken" />
3494: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
3495: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
3496: <input type="hidden" name="upfile_associate"
3497: value="$env{'form.upfile_associate'}" />
3498: <input type="hidden" name="symb" value="$symb" />
3499: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
3500: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
3501: <input type="hidden" name="command" value="csvuploadoptions" />
3502: <hr />
3503: <script type="text/javascript" language="Javascript">
3504: $javascript
3505: </script>
3506: ENDPICK
3507: return '';
3508:
3509: }
3510:
3511: sub csvupload_fields {
3512: my ($symb) = @_;
3513: my (@parts) = &getpartlist($symb);
3514: my @fields=(['ID','Student ID'],
3515: ['username','Student Username'],
3516: ['domain','Student Domain']);
3517: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3518: foreach my $part (sort(@parts)) {
3519: my @datum;
3520: my $display=&Apache::lonnet::metadata($url,$part.'.display');
3521: my $name=$part;
3522: if (!$display) { $display = $name; }
3523: @datum=($name,$display);
3524: if ($name=~/^stores_(.*)_awarded/) {
3525: push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
3526: }
3527: push(@fields,\@datum);
3528: }
3529: return (@fields);
3530: }
3531:
3532: sub csvuploadmap_footer {
3533: my ($request,$i,$keyfields) =@_;
3534: $request->print(<<ENDPICK);
3535: </table>
3536: <input type="hidden" name="nfields" value="$i" />
3537: <input type="hidden" name="keyfields" value="$keyfields" />
3538: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
3539: </form>
3540: ENDPICK
3541: }
3542:
3543: sub checkforfile_js {
3544: my $result =<<CSVFORMJS;
3545: <script type="text/javascript" language="javascript">
3546: function checkUpload(formname) {
3547: if (formname.upfile.value == "") {
3548: alert("Please use the browse button to select a file from your local directory.");
3549: return false;
3550: }
3551: formname.submit();
3552: }
3553: </script>
3554: CSVFORMJS
3555: return $result;
3556: }
3557:
3558: sub upcsvScores_form {
3559: my ($request) = shift;
3560: my ($symb)=&get_symb($request);
3561: if (!$symb) {return '';}
3562: my $result=&checkforfile_js();
3563: $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
3564: my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
3565: $result.=$table;
3566: $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
3567: $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
3568: $result.=' <b>'.&mt('Specify a file containing the class scores for current resource').
3569: '.</b></td></tr>'."\n";
3570: $result.='<tr bgcolor=#ffffe6><td>'."\n";
3571: my $upload=&mt("Upload Scores");
3572: my $upfile_select=&Apache::loncommon::upfile_select_html();
3573: my $ignore=&mt('Ignore First Line');
3574: $symb = &Apache::lonenc::check_encrypt($symb);
3575: $result.=<<ENDUPFORM;
3576: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3577: <input type="hidden" name="symb" value="$symb" />
3578: <input type="hidden" name="command" value="csvuploadmap" />
3579: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
3580: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
3581: $upfile_select
3582: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
3583: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
3584: </form>
3585: ENDUPFORM
3586: $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
3587: &mt("How do I create a CSV file from a spreadsheet"))
3588: .'</td></tr></table>'."\n";
3589: $result.='</td></tr></table><br /><br />'."\n";
3590: $result.=&show_grading_menu_form($symb);
3591: return $result;
3592: }
3593:
3594:
3595: sub csvuploadmap {
3596: my ($request)= @_;
3597: my ($symb)=&get_symb($request);
3598: if (!$symb) {return '';}
3599:
3600: my $datatoken;
3601: if (!$env{'form.datatoken'}) {
3602: $datatoken=&Apache::loncommon::upfile_store($request);
3603: } else {
3604: $datatoken=$env{'form.datatoken'};
3605: &Apache::loncommon::load_tmp_file($request);
3606: }
3607: my @records=&Apache::loncommon::upfile_record_sep();
3608: if ($env{'form.noFirstLine'}) { shift(@records); }
3609: &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
3610: my ($i,$keyfields);
3611: if (@records) {
3612: my @fields=&csvupload_fields($symb);
3613:
3614: if ($env{'form.upfile_associate'} eq 'reverse') {
3615: &Apache::loncommon::csv_print_samples($request,\@records);
3616: $i=&Apache::loncommon::csv_print_select_table($request,\@records,
3617: \@fields);
3618: foreach (@fields) { $keyfields.=$_->[0].','; }
3619: chop($keyfields);
3620: } else {
3621: unshift(@fields,['none','']);
3622: $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
3623: \@fields);
3624: foreach my $rec (@records) {
3625: my %temp = &Apache::loncommon::record_sep($rec);
3626: if (%temp) {
3627: $keyfields=join(',',sort(keys(%temp)));
3628: last;
3629: }
3630: }
3631: }
3632: }
3633: &csvuploadmap_footer($request,$i,$keyfields);
3634: $request->print(&show_grading_menu_form($symb));
3635:
3636: return '';
3637: }
3638:
3639: sub csvuploadoptions {
3640: my ($request)= @_;
3641: my ($symb)=&get_symb($request);
3642: my $checked=(($env{'form.noFirstLine'})?'1':'0');
3643: my $ignore=&mt('Ignore First Line');
3644: $request->print(<<ENDPICK);
3645: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3646: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
3647: <input type="hidden" name="command" value="csvuploadassign" />
3648: <!--
3649: <p>
3650: <label>
3651: <input type="checkbox" name="show_full_results" />
3652: Show a table of all changes
3653: </label>
3654: </p>
3655: -->
3656: <p>
3657: <label>
3658: <input type="checkbox" name="overwite_scores" checked="checked" />
3659: Overwrite any existing score
3660: </label>
3661: </p>
3662: ENDPICK
3663: my %fields=&get_fields();
3664: if (!defined($fields{'domain'})) {
3665: my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
3666: $request->print("\n<p> Users are in domain: ".$domform."</p>\n");
3667: }
3668: foreach my $key (sort(keys(%env))) {
3669: if ($key !~ /^form\.(.*)$/) { next; }
3670: my $cleankey=$1;
3671: if ($cleankey eq 'command') { next; }
3672: $request->print('<input type="hidden" name="'.$cleankey.
3673: '" value="'.$env{$key}.'" />'."\n");
3674: }
3675: # FIXME do a check for any duplicated user ids...
3676: # FIXME do a check for any invalid user ids?...
3677: $request->print('<input type="submit" value="Assign Grades" /><br />
3678: <hr /></form>'."\n");
3679: $request->print(&show_grading_menu_form($symb));
3680: return '';
3681: }
3682:
3683: sub get_fields {
3684: my %fields;
3685: my @keyfields = split(/\,/,$env{'form.keyfields'});
3686: for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
3687: if ($env{'form.upfile_associate'} eq 'reverse') {
3688: if ($env{'form.f'.$i} ne 'none') {
3689: $fields{$keyfields[$i]}=$env{'form.f'.$i};
3690: }
3691: } else {
3692: if ($env{'form.f'.$i} ne 'none') {
3693: $fields{$env{'form.f'.$i}}=$keyfields[$i];
3694: }
3695: }
3696: }
3697: return %fields;
3698: }
3699:
3700: sub csvuploadassign {
3701: my ($request)= @_;
3702: my ($symb)=&get_symb($request);
3703: if (!$symb) {return '';}
3704: my $error_msg = '';
3705: &Apache::loncommon::load_tmp_file($request);
3706: my @gradedata = &Apache::loncommon::upfile_record_sep();
3707: if ($env{'form.noFirstLine'}) { shift(@gradedata); }
3708: my %fields=&get_fields();
3709: $request->print('<h3>Assigning Grades</h3>');
3710: my $courseid=$env{'request.course.id'};
3711: my ($classlist) = &getclasslist('all',0);
3712: my @notallowed;
3713: my @skipped;
3714: my $countdone=0;
3715: foreach my $grade (@gradedata) {
3716: my %entries=&Apache::loncommon::record_sep($grade);
3717: my $domain;
3718: if ($entries{$fields{'domain'}}) {
3719: $domain=$entries{$fields{'domain'}};
3720: } else {
3721: $domain=$env{'form.default_domain'};
3722: }
3723: $domain=~s/\s//g;
3724: my $username=$entries{$fields{'username'}};
3725: $username=~s/\s//g;
3726: if (!$username) {
3727: my $id=$entries{$fields{'ID'}};
3728: $id=~s/\s//g;
3729: my %ids=&Apache::lonnet::idget($domain,$id);
3730: $username=$ids{$id};
3731: }
3732: if (!exists($$classlist{"$username:$domain"})) {
3733: my $id=$entries{$fields{'ID'}};
3734: $id=~s/\s//g;
3735: if ($id) {
3736: push(@skipped,"$id:$domain");
3737: } else {
3738: push(@skipped,"$username:$domain");
3739: }
3740: next;
3741: }
3742: my $usec=$classlist->{"$username:$domain"}[5];
3743: if (!&canmodify($usec)) {
3744: push(@notallowed,"$username:$domain");
3745: next;
3746: }
3747: my %points;
3748: my %grades;
3749: foreach my $dest (keys(%fields)) {
3750: if ($dest eq 'ID' || $dest eq 'username' ||
3751: $dest eq 'domain') { next; }
3752: if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
3753: if ($dest=~/stores_(.*)_points/) {
3754: my $part=$1;
3755: my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
3756: $symb,$domain,$username);
3757: if ($wgt) {
3758: $entries{$fields{$dest}}=~s/\s//g;
3759: my $pcr=$entries{$fields{$dest}} / $wgt;
3760: my $award='correct_by_override';
3761: $grades{"resource.$part.awarded"}=$pcr;
3762: $grades{"resource.$part.solved"}=$award;
3763: $points{$part}=1;
3764: } else {
3765: $error_msg = "<br />" .
3766: &mt("Some point values were assigned"
3767: ." for problems with a weight "
3768: ."of zero. These values were "
3769: ."ignored.");
3770: }
3771: } else {
3772: if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
3773: if ($dest=~/stores_(.*)_solved/) { if ($points{$1}) {next;} }
3774: my $store_key=$dest;
3775: $store_key=~s/^stores/resource/;
3776: $store_key=~s/_/\./g;
3777: $grades{$store_key}=$entries{$fields{$dest}};
3778: }
3779: }
3780: if (! %grades) { push(@skipped,"$username:$domain no data to save"); }
3781: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
3782: # &Apache::lonnet::logthis(" storing ".(join('-',%grades)));
3783: my $result=&Apache::lonnet::cstore(\%grades,$symb,
3784: $env{'request.course.id'},
3785: $domain,$username);
3786: if ($result eq 'ok') {
3787: $request->print('.');
3788: } else {
3789: $request->print("<p>
3790: <span class=\"LC_error\">
3791: Failed to save student $username:$domain.
3792: Message when trying to save was ($result)
3793: </span>
3794: </p>" );
3795: }
3796: $request->rflush();
3797: $countdone++;
3798: }
3799: $request->print("<br />Saved $countdone students\n");
3800: if (@skipped) {
3801: $request->print('<p><h4><b>Skipped Students</b></h4></p>');
3802: foreach my $student (@skipped) { $request->print("$student<br />\n"); }
3803: }
3804: if (@notallowed) {
3805: $request->print('<p><span class="LC_error">Students Not Allowed to Modify</span></p>');
3806: foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
3807: }
3808: $request->print("<br />\n");
3809: $request->print(&show_grading_menu_form($symb));
3810: return $error_msg;
3811: }
3812: #------------- end of section for handling csv file upload ---------
3813: #
3814: #-------------------------------------------------------------------
3815: #
3816: #-------------- Next few routines handle grading by page/sequence
3817: #
3818: #--- Select a page/sequence and a student to grade
3819: sub pickStudentPage {
3820: my ($request) = shift;
3821:
3822: $request->print(<<LISTJAVASCRIPT);
3823: <script type="text/javascript" language="javascript">
3824:
3825: function checkPickOne(formname) {
3826: if (radioSelection(formname.student) == null) {
3827: alert("Please select the student you wish to grade.");
3828: return;
3829: }
3830: ptr = pullDownSelection(formname.selectpage);
3831: formname.page.value = formname["page"+ptr].value;
3832: formname.title.value = formname["title"+ptr].value;
3833: formname.submit();
3834: }
3835:
3836: </script>
3837: LISTJAVASCRIPT
3838: &commonJSfunctions($request);
3839: my ($symb) = &get_symb($request);
3840: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
3841: my $cnum = $env{"course.$env{'request.course.id'}.num"};
3842: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
3843:
3844: my $result='<h3><span class="LC_info"> '.
3845: 'Manual Grading by Page or Sequence</span></h3>';
3846:
3847: $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
3848: $result.=' <b>Problems from:</b> <select name="selectpage">'."\n";
3849: my ($titles,$symbx) = &getSymbMap();
3850: my ($curpage) =&Apache::lonnet::decode_symb($symb);
3851: # my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb);
3852: # my $type=($curpage =~ /\.(page|sequence)/);
3853: my $ctr=0;
3854: foreach (@$titles) {
3855: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
3856: $result.='<option value="'.$ctr.'" '.
3857: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
3858: '>'.$showtitle.'</option>'."\n";
3859: $ctr++;
3860: }
3861: $result.= '</select>'."<br />\n";
3862: $ctr=0;
3863: foreach (@$titles) {
3864: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
3865: $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
3866: $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
3867: $ctr++;
3868: }
3869: $result.='<input type="hidden" name="page" />'."\n".
3870: '<input type="hidden" name="title" />'."\n";
3871:
3872: $result.=' <b>View Problems Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
3873: '<label><input type="radio" name="vProb" value="yes" /> yes </label>'."<br />\n";
3874:
3875: $result.=' <b>Submission Details: </b>'.
3876: '<label><input type="radio" name="lastSub" value="none" /> none</label>'."\n".
3877: '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> by dates and submissions</label>'."\n".
3878: '<label><input type="radio" name="lastSub" value="all" /> all details</label>'."\n";
3879:
3880: $result.=&build_section_inputs();
3881: $result.='<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n".
3882: '<input type="hidden" name="command" value="displayPage" />'."\n".
3883: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
3884: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
3885:
3886: $result.=' <b>'.&mt('Use CODE:').' </b>'.
3887: '<input type="text" name="CODE" value="" /><br />'."\n";
3888:
3889: $result.=' <input type="button" '.
3890: 'onClick="javascript:checkPickOne(this.form);"value="Next->" /><br />'."\n";
3891:
3892: $request->print($result);
3893:
3894: my $studentTable.=' <b>Select a student you wish to grade and then click on the Next button.</b><br />'.
3895: '<table border="0"><tr><td bgcolor="#777777">'.
3896: '<table border="0"><tr bgcolor="#e6ffff">'.
3897: '<td align="right"> <b>No.</b></td>'.
3898: '<td>'.&nameUserString('header').'</td>'.
3899: '<td align="right"> <b>No.</b></td>'.
3900: '<td>'.&nameUserString('header').'</td></tr>';
3901:
3902: my (undef,undef,$fullname) = &getclasslist($getsec,'1');
3903: my $ptr = 1;
3904: foreach my $student (sort
3905: {
3906: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
3907: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
3908: }
3909: return $a cmp $b;
3910: } (keys(%$fullname))) {
3911: my ($uname,$udom) = split(/:/,$student);
3912: $studentTable.=($ptr%2 == 1 ? '<tr bgcolor="#ffffe6">' : '</td>');
3913: $studentTable.='<td align="right">'.$ptr.' </td>';
3914: $studentTable.='<td> <label><input type="radio" name="student" value="'.$student.'" /> '
3915: .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
3916: $studentTable.=($ptr%2 == 0 ? '</td></tr>' : '');
3917: $ptr++;
3918: }
3919: $studentTable.='</td><td> </td><td> </td></tr>' if ($ptr%2 == 0);
3920: $studentTable.='</table></td></tr></table>'."\n";
3921: $studentTable.='<input type="button" '.
3922: 'onClick="javascript:checkPickOne(this.form);"value="Next->" /></form>'."\n";
3923:
3924: $studentTable.=&show_grading_menu_form($symb);
3925: $request->print($studentTable);
3926:
3927: return '';
3928: }
3929:
3930: sub getSymbMap {
3931: my $navmap = Apache::lonnavmaps::navmap->new();
3932:
3933: my %symbx = ();
3934: my @titles = ();
3935: my $minder = 0;
3936:
3937: # Gather every sequence that has problems.
3938: my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
3939: 1,0,1);
3940: for my $sequence ($navmap->getById('0.0'), @sequences) {
3941: if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
3942: my $title = $minder.'.'.
3943: &HTML::Entities::encode($sequence->compTitle(),'"\'&');
3944: push(@titles, $title); # minder in case two titles are identical
3945: $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
3946: $minder++;
3947: }
3948: }
3949: return \@titles,\%symbx;
3950: }
3951:
3952: #
3953: #--- Displays a page/sequence w/wo problems, w/wo submissions
3954: sub displayPage {
3955: my ($request) = shift;
3956:
3957: my ($symb) = &get_symb($request);
3958: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
3959: my $cnum = $env{"course.$env{'request.course.id'}.num"};
3960: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
3961: my $pageTitle = $env{'form.page'};
3962: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
3963: my ($uname,$udom) = split(/:/,$env{'form.student'});
3964: my $usec=$classlist->{$env{'form.student'}}[5];
3965:
3966: #need to make sure we have the correct data for later EXT calls,
3967: #thus invalidate the cache
3968: &Apache::lonnet::devalidatecourseresdata(
3969: $env{'course.'.$env{'request.course.id'}.'.num'},
3970: $env{'course.'.$env{'request.course.id'}.'.domain'});
3971: &Apache::lonnet::clear_EXT_cache_status();
3972:
3973: if (!&canview($usec)) {
3974: $request->print('<span class="LC_warning">Unable to view requested student.('.$env{'form.student'}.')</span>');
3975: $request->print(&show_grading_menu_form($symb));
3976: return;
3977: }
3978: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
3979: $result.='<h3> Student: '.&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom).
3980: '</h3>'."\n";
3981: if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
3982: $result.='<h3> CODE: '.$env{'form.CODE'}.'</h3>'."\n";
3983: } else {
3984: delete($env{'form.CODE'});
3985: }
3986: &sub_page_js($request);
3987: $request->print($result);
3988:
3989: my $navmap = Apache::lonnavmaps::navmap->new();
3990: my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
3991: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
3992: if (!$map) {
3993: $request->print('<span class="LC_warning">Unable to view requested sequence. ('.$resUrl.')</span>');
3994: $request->print(&show_grading_menu_form($symb));
3995: return;
3996: }
3997: my $iterator = $navmap->getIterator($map->map_start(),
3998: $map->map_finish());
3999:
4000: my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
4001: '<input type="hidden" name="command" value="gradeByPage" />'."\n".
4002: '<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
4003: '<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
4004: '<input type="hidden" name="page" value="'.$pageTitle.'" />'."\n".
4005: '<input type="hidden" name="title" value="'.$env{'form.title'}.'" />'."\n".
4006: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
4007: '<input type="hidden" name="overRideScore" value="no" />'."\n".
4008: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
4009:
4010: if (defined($env{'form.CODE'})) {
4011: $studentTable.=
4012: '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
4013: }
4014: my $checkIcon = '<img alt="'.&mt('Check Mark').
4015: '" src="'.$request->dir_config('lonIconsURL').
4016: '/check.gif" height="16" border="0" />';
4017:
4018: $studentTable.=' <b>Note:</b> Problems graded correct by the computer are marked with a '.$checkIcon.
4019: ' symbol.'."\n".
4020: '<table border="0"><tr><td bgcolor="#777777">'.
4021: '<table border="0"><tr bgcolor="#e6ffff">'.
4022: '<td align="center"><b> Prob. </b></td>'.
4023: '<td><b> '.($env{'form.vProb'} eq 'no' ? 'Title' : 'Problem Text').'/Grade</b></td></tr>';
4024:
4025: &Apache::lonxml::clear_problem_counter();
4026: my ($depth,$question,$prob) = (1,1,1);
4027: $iterator->next(); # skip the first BEGIN_MAP
4028: my $curRes = $iterator->next(); # for "current resource"
4029: while ($depth > 0) {
4030: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
4031: if($curRes == $iterator->END_MAP) { $depth--; }
4032:
4033: if (ref($curRes) && $curRes->is_problem()) {
4034: my $parts = $curRes->parts();
4035: my $title = $curRes->compTitle();
4036: my $symbx = $curRes->symb();
4037: $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
4038: (scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).' parts)').'</td>';
4039: $studentTable.='<td valign="top">';
4040: my %form = ('CODE' => $env{'form.CODE'},);
4041: if ($env{'form.vProb'} eq 'yes' ) {
4042: $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
4043: undef,'both',\%form);
4044: } else {
4045: my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
4046: $companswer =~ s|<form(.*?)>||g;
4047: $companswer =~ s|</form>||g;
4048: # while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
4049: # $companswer =~ s/$1/ /ms;
4050: # $request->print('match='.$1."<br />\n");
4051: # }
4052: # $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
4053: $studentTable.=' <b>'.$title.'</b> <br /> <b>Correct answer:</b><br />'.$companswer;
4054: }
4055:
4056: my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
4057:
4058: if ($env{'form.lastSub'} eq 'datesub') {
4059: if ($record{'version'} eq '') {
4060: $studentTable.='<br /> <span class="LC_warning">No recorded submission for this problem</span><br />';
4061: } else {
4062: my %responseType = ();
4063: foreach my $partid (@{$parts}) {
4064: my @responseIds =$curRes->responseIds($partid);
4065: my @responseType =$curRes->responseType($partid);
4066: my %responseIds;
4067: for (my $i=0;$i<=$#responseIds;$i++) {
4068: $responseIds{$responseIds[$i]}=$responseType[$i];
4069: }
4070: $responseType{$partid} = \%responseIds;
4071: }
4072: $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
4073:
4074: }
4075: } elsif ($env{'form.lastSub'} eq 'all') {
4076: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
4077: $studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
4078: $env{'request.course.id'},
4079: '','.submission');
4080:
4081: }
4082: if (&canmodify($usec)) {
4083: foreach my $partid (@{$parts}) {
4084: $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
4085: $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
4086: $question++;
4087: }
4088: $prob++;
4089: }
4090: $studentTable.='</td></tr>';
4091:
4092: }
4093: $curRes = $iterator->next();
4094: }
4095:
4096: $studentTable.='</table></td></tr></table>'."\n".
4097: '<input type="button" value="Save" '.
4098: 'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
4099: '</form>'."\n";
4100: $studentTable.=&show_grading_menu_form($symb);
4101: $request->print($studentTable);
4102:
4103: return '';
4104: }
4105:
4106: sub displaySubByDates {
4107: my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
4108: my $isCODE=0;
4109: my $isTask = ($symb =~/\.task$/);
4110: if (exists($record->{'resource.CODE'})) { $isCODE=1; }
4111: my $studentTable='<table border="0" width="100%"><tr><td bgcolor="#777777">'.
4112: '<table border="0" width="100%"><tr bgcolor="#e6ffff">'.
4113: '<td><b>Date/Time</b></td>'.
4114: ($isCODE?'<td><b>CODE</b></td>':'').
4115: '<td><b>Submission</b></td>'.
4116: '<td><b>Status </b></td></tr>';
4117: my ($version);
4118: my %mark;
4119: my %orders;
4120: $mark{'correct_by_student'} = $checkIcon;
4121: if (!exists($$record{'1:timestamp'})) {
4122: return '<br /> <span class="LC_warning">Nothing submitted - no attempts</span><br />';
4123: }
4124:
4125: my $interaction;
4126: for ($version=1;$version<=$$record{'version'};$version++) {
4127: my $timestamp = scalar(localtime($$record{$version.':timestamp'}));
4128: if (exists($$record{$version.':resource.0.version'})) {
4129: $interaction = $$record{$version.':resource.0.version'};
4130: }
4131:
4132: my $where = ($isTask ? "$version:resource.$interaction"
4133: : "$version:resource");
4134: #&Apache::lonnet::logthis(" got $where");
4135: $studentTable.='<tr bgcolor="#ffffff" valign="top"><td>'.$timestamp.'</td>';
4136: if ($isCODE) {
4137: $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
4138: }
4139: my @versionKeys = split(/\:/,$$record{$version.':keys'});
4140: my @displaySub = ();
4141: foreach my $partid (@{$parts}) {
4142: my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
4143: : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
4144:
4145:
4146: # next if ($$record{"$version:resource.$partid.solved"} eq '');
4147: my $display_part=&get_display_part($partid,$symb);
4148: foreach my $matchKey (@matchKey) {
4149: if (exists($$record{$version.':'.$matchKey}) &&
4150: $$record{$version.':'.$matchKey} ne '') {
4151:
4152: my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
4153: : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
4154: #&Apache::lonnet::logthis("match $matchKey $responseId (".$$record{$version.':'.$matchKey});
4155: $displaySub[0].='<b>Part:</b> '.$display_part.' ';
4156: $displaySub[0].='<span class="LC_internal_info">(ID '.
4157: $responseId.')</span> <b>';
4158: if ($$record{"$where.$partid.tries"} eq '') {
4159: $displaySub[0].='Trial not counted';
4160: } else {
4161: $displaySub[0].='Trial '.
4162: $$record{"$where.$partid.tries"};
4163: }
4164: my $responseType=($isTask ? 'Task'
4165: : $responseType->{$partid}->{$responseId});
4166: if (!exists($orders{$partid})) { $orders{$partid}={}; }
4167: if (!exists($orders{$partid}->{$responseId})) {
4168: $orders{$partid}->{$responseId}=
4169: &get_order($partid,$responseId,$symb,$uname,$udom);
4170: }
4171: $displaySub[0].='</b> '.
4172: &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
4173: }
4174: }
4175: if (exists($$record{"$where.$partid.checkedin"})) {
4176: $displaySub[1].='Checked in by '.
4177: $$record{"$where.$partid.checkedin"}.' into slot '.
4178: $$record{"$where.$partid.checkedin.slot"}.
4179: '<br />';
4180: }
4181: if (exists $$record{"$where.$partid.award"}) {
4182: $displaySub[1].='<b>Part:</b> '.$display_part.' '.
4183: lc($$record{"$where.$partid.award"}).' '.
4184: $mark{$$record{"$where.$partid.solved"}}.
4185: '<br />';
4186: }
4187: if (exists $$record{"$where.$partid.regrader"}) {
4188: $displaySub[2].=$$record{"$where.$partid.regrader"}.
4189: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
4190: } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
4191: $displaySub[2].=
4192: $$record{"$version:resource.$partid.regrader"}.
4193: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
4194: }
4195: }
4196: # needed because old essay regrader has not parts info
4197: if (exists $$record{"$version:resource.regrader"}) {
4198: $displaySub[2].=$$record{"$version:resource.regrader"};
4199: }
4200: $studentTable.='<td>'.$displaySub[0].' </td><td>'.$displaySub[1];
4201: if ($displaySub[2]) {
4202: $studentTable.='Manually graded by '.$displaySub[2];
4203: }
4204: $studentTable.=' </td></tr>';
4205:
4206: }
4207: $studentTable.='</table></td></tr></table>';
4208: return $studentTable;
4209: }
4210:
4211: sub updateGradeByPage {
4212: my ($request) = shift;
4213:
4214: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4215: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4216: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4217: my $pageTitle = $env{'form.page'};
4218: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
4219: my ($uname,$udom) = split(/:/,$env{'form.student'});
4220: my $usec=$classlist->{$env{'form.student'}}[5];
4221: if (!&canmodify($usec)) {
4222: $request->print('<span class="LC_warning">Unable to modify requested student.('.$env{'form.student'}.'</span>');
4223: $request->print(&show_grading_menu_form($env{'form.symb'}));
4224: return;
4225: }
4226: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
4227: $result.='<h3> Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
4228: '</h3>'."\n";
4229:
4230: $request->print($result);
4231:
4232: my $navmap = Apache::lonnavmaps::navmap->new();
4233: my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
4234: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
4235: if (!$map) {
4236: $request->print('<span class="LC_warning">Unable to grade requested sequence. ('.$resUrl.')</span>');
4237: my ($symb)=&get_symb($request);
4238: $request->print(&show_grading_menu_form($symb));
4239: return;
4240: }
4241: my $iterator = $navmap->getIterator($map->map_start(),
4242: $map->map_finish());
4243:
4244: my $studentTable='<table border="0"><tr><td bgcolor="#777777">'.
4245: '<table border="0"><tr bgcolor="#e6ffff">'.
4246: '<td align="center"><b> Prob. </b></td>'.
4247: '<td><b> Title </b></td>'.
4248: '<td><b> Previous Score </b></td>'.
4249: '<td><b> New Score </b></td></tr>';
4250:
4251: $iterator->next(); # skip the first BEGIN_MAP
4252: my $curRes = $iterator->next(); # for "current resource"
4253: my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
4254: while ($depth > 0) {
4255: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
4256: if($curRes == $iterator->END_MAP) { $depth--; }
4257:
4258: if (ref($curRes) && $curRes->is_problem()) {
4259: my $parts = $curRes->parts();
4260: my $title = $curRes->compTitle();
4261: my $symbx = $curRes->symb();
4262: $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
4263: (scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).' parts)').'</td>';
4264: $studentTable.='<td valign="top"> <b>'.$title.'</b> </td>';
4265:
4266: my %newrecord=();
4267: my @displayPts=();
4268: my %aggregate = ();
4269: my $aggregateflag = 0;
4270: foreach my $partid (@{$parts}) {
4271: my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
4272: my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
4273:
4274: my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ?
4275: $env{'form.WGT'.$question.'_'.$partid} : 1;
4276: my $partial = $newpts/$wgt;
4277: my $score;
4278: if ($partial > 0) {
4279: $score = 'correct_by_override';
4280: } elsif ($newpts ne '') { #empty is taken as 0
4281: $score = 'incorrect_by_override';
4282: }
4283: my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
4284: if ($dropMenu eq 'excused') {
4285: $partial = '';
4286: $score = 'excused';
4287: } elsif ($dropMenu eq 'reset status'
4288: && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
4289: $newrecord{'resource.'.$partid.'.tries'} = 0;
4290: $newrecord{'resource.'.$partid.'.solved'} = '';
4291: $newrecord{'resource.'.$partid.'.award'} = '';
4292: $newrecord{'resource.'.$partid.'.awarded'} = 0;
4293: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
4294: $changeflag++;
4295: $newpts = '';
4296:
4297: my $aggtries = $env{'form.aggtries'.$question.'_'.$partid};
4298: my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
4299: my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
4300: if ($aggtries > 0) {
4301: &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
4302: $aggregateflag = 1;
4303: }
4304: }
4305: my $display_part=&get_display_part($partid,$curRes->symb());
4306: my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
4307: $displayPts[0].=' <b>Part:</b> '.$display_part.' = '.
4308: (($oldstatus eq 'excused') ? 'excused' : $oldpts).
4309: ' <br />';
4310: $displayPts[1].=' <b>Part:</b> '.$display_part.' = '.
4311: (($score eq 'excused') ? 'excused' : $newpts).
4312: ' <br />';
4313: $question++;
4314: next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
4315:
4316: $newrecord{'resource.'.$partid.'.awarded'} = $partial if $partial ne '';
4317: $newrecord{'resource.'.$partid.'.solved'} = $score if $score ne '';
4318: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
4319: if (scalar(keys(%newrecord)) > 0);
4320:
4321: $changeflag++;
4322: }
4323: if (scalar(keys(%newrecord)) > 0) {
4324: my %record =
4325: &Apache::lonnet::restore($symbx,$env{'request.course.id'},
4326: $udom,$uname);
4327:
4328: if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
4329: $newrecord{'resource.CODE'} = $env{'form.CODE'};
4330: } elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
4331: $newrecord{'resource.CODE'} = '';
4332: }
4333: &Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
4334: $udom,$uname);
4335: %record = &Apache::lonnet::restore($symbx,
4336: $env{'request.course.id'},
4337: $udom,$uname);
4338: &check_and_remove_from_queue($parts,\%record,undef,$symbx,
4339: $cdom,$cnum,$udom,$uname);
4340: }
4341:
4342: if ($aggregateflag) {
4343: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
4344: $env{'course.'.$env{'request.course.id'}.'.domain'},
4345: $env{'course.'.$env{'request.course.id'}.'.num'});
4346: }
4347:
4348: $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
4349: '<td valign="top">'.$displayPts[1].'</td>'.
4350: '</tr>';
4351:
4352: $prob++;
4353: }
4354: $curRes = $iterator->next();
4355: }
4356:
4357: $studentTable.='</td></tr></table></td></tr></table>';
4358: $studentTable.=&show_grading_menu_form($env{'form.symb'});
4359: my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
4360: 'The scores were changed for '.
4361: $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
4362: $request->print($grademsg.$studentTable);
4363:
4364: return '';
4365: }
4366:
4367: #-------- end of section for handling grading by page/sequence ---------
4368: #
4369: #-------------------------------------------------------------------
4370:
4371: #--------------------Scantron Grading-----------------------------------
4372: #
4373: #------ start of section for handling grading by page/sequence ---------
4374:
4375: =pod
4376:
4377: =head1 Bubble sheet grading routines
4378:
4379: For this documentation:
4380:
4381: 'scanline' refers to the full line of characters
4382: from the file that we are parsing that represents one entire sheet
4383:
4384: 'bubble line' refers to the data
4385: representing the line of bubbles that are on the physical bubble sheet
4386:
4387:
4388: The overall process is that a scanned in bubble sheet data is uploaded
4389: into a course. When a user wants to grade, they select a
4390: sequence/folder of resources, a file of bubble sheet info, and pick
4391: one of the predefined configurations for what each scanline looks
4392: like.
4393:
4394: Next each scanline is checked for any errors of either 'missing
4395: bubbles' (it's an error because it may have been missed scanned
4396: because too light bubbling), 'double bubble' (each bubble line should
4397: have no more that one letter picked), invalid or duplicated CODE,
4398: invalid student ID
4399:
4400: If the CODE option is used that determines the randomization of the
4401: homework problems, either way the student ID is looked up into a
4402: username:domain.
4403:
4404: During the validation phase the instructor can choose to skip scanlines.
4405:
4406: After the validation phase, there is now 3 bubble sheet files
4407:
4408: scantron_original_filename (unmodified original file)
4409: scantron_corrected_filename (file where the corrected information has replaced the original information)
4410: scantron_skipped_filename (contains the exact text of scanlines that where skipped)
4411:
4412: Also there is a separate hash nohist_scantrondata that contains extra
4413: correction information that isn't representable in the bubble sheet
4414: file (see &scantron_getfile() for more information)
4415:
4416: After all scanlines are either valid, marked as valid or skipped, then
4417: foreach line foreach problem in the picked sequence, an ssi request is
4418: made that simulates a user submitting their selected letter(s) against
4419: the homework problem.
4420:
4421: =over 4
4422:
4423: =cut
4424:
4425:
4426: =pod
4427:
4428: =item defaultFormData
4429:
4430: Returns html hidden inputs used to hold context/default values.
4431:
4432: Arguments:
4433: $symb - $symb of the current resource
4434:
4435: =cut
4436:
4437: sub defaultFormData {
4438: my ($symb)=@_;
4439: return '
4440: <input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
4441: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
4442: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
4443: }
4444:
4445: =pod
4446:
4447: =item getSequenceDropDown
4448:
4449: Return html dropdown of possible sequences to grade
4450:
4451: Arguments:
4452: $symb - $symb of the current resource
4453:
4454: =cut
4455:
4456: sub getSequenceDropDown {
4457: my ($symb)=@_;
4458: my $result='<select name="selectpage">'."\n";
4459: my ($titles,$symbx) = &getSymbMap();
4460: my ($curpage)=&Apache::lonnet::decode_symb($symb);
4461: my $ctr=0;
4462: foreach (@$titles) {
4463: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4464: $result.='<option value="'.$$symbx{$_}.'" '.
4465: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
4466: '>'.$showtitle.'</option>'."\n";
4467: $ctr++;
4468: }
4469: $result.= '</select>';
4470: return $result;
4471: }
4472:
4473:
4474: =pod
4475:
4476: =item scantron_filenames
4477:
4478: Returns a list of the scantron files in the current course
4479:
4480: =cut
4481:
4482: sub scantron_filenames {
4483: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4484: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
4485: my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
4486: &propath($cdom,$cname));
4487: my @possiblenames;
4488: foreach my $filename (sort(@files)) {
4489: ($filename)=split(/&/,$filename);
4490: if ($filename!~/^scantron_orig_/) { next ; }
4491: $filename=~s/^scantron_orig_//;
4492: push(@possiblenames,$filename);
4493: }
4494: return @possiblenames;
4495: }
4496:
4497: =pod
4498:
4499: =item scantron_uploads
4500:
4501: Returns html drop-down list of scantron files in current course.
4502:
4503: Arguments:
4504: $file2grade - filename to set as selected in the dropdown
4505:
4506: =cut
4507:
4508: sub scantron_uploads {
4509: my ($file2grade) = @_;
4510: my $result= '<select name="scantron_selectfile">';
4511: $result.="<option></option>";
4512: foreach my $filename (sort(&scantron_filenames())) {
4513: $result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
4514: }
4515: $result.="</select>";
4516: return $result;
4517: }
4518:
4519: =pod
4520:
4521: =item scantron_scantab
4522:
4523: Returns html drop down of the scantron formats in the scantronformat.tab
4524: file.
4525:
4526: =cut
4527:
4528: sub scantron_scantab {
4529: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
4530: my $result='<select name="scantron_format">'."\n";
4531: $result.='<option></option>'."\n";
4532: foreach my $line (<$fh>) {
4533: my ($name,$descrip)=split(/:/,$line);
4534: if ($name =~ /^\#/) { next; }
4535: $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
4536: }
4537: $result.='</select>'."\n";
4538:
4539: return $result;
4540: }
4541:
4542: =pod
4543:
4544: =item scantron_CODElist
4545:
4546: Returns html drop down of the saved CODE lists from current course,
4547: generated from earlier printings.
4548:
4549: =cut
4550:
4551: sub scantron_CODElist {
4552: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4553: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4554: my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
4555: my $namechoice='<option></option>';
4556: foreach my $name (sort {uc($a) cmp uc($b)} @names) {
4557: if ($name =~ /^error: 2 /) { next; }
4558: if ($name =~ /^type\0/) { next; }
4559: $namechoice.='<option value="'.$name.'">'.$name.'</option>';
4560: }
4561: $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
4562: return $namechoice;
4563: }
4564:
4565: =pod
4566:
4567: =item scantron_CODEunique
4568:
4569: Returns the html for "Each CODE to be used once" radio.
4570:
4571: =cut
4572:
4573: sub scantron_CODEunique {
4574: my $result='<span style="white-space: nowrap;">
4575: <label><input type="radio" name="scantron_CODEunique"
4576: value="yes" checked="checked" />'.&mt('Yes').' </label>
4577: </span>
4578: <span style="white-space: nowrap;">
4579: <label><input type="radio" name="scantron_CODEunique"
4580: value="no" />'.&mt('No').' </label>
4581: </span>';
4582: return $result;
4583: }
4584:
4585: =pod
4586:
4587: =item scantron_selectphase
4588:
4589: Generates the initial screen to start the bubble sheet process.
4590: Allows for - starting a grading run.
4591: - downloading existing scan data (original, corrected
4592: or skipped info)
4593:
4594: - uploading new scan data
4595:
4596: Arguments:
4597: $r - The Apache request object
4598: $file2grade - name of the file that contain the scanned data to score
4599:
4600: =cut
4601:
4602: sub scantron_selectphase {
4603: my ($r,$file2grade) = @_;
4604: my ($symb)=&get_symb($r);
4605: if (!$symb) {return '';}
4606: my $sequence_selector=&getSequenceDropDown($symb);
4607: my $default_form_data=&defaultFormData($symb);
4608: my $grading_menu_button=&show_grading_menu_form($symb);
4609: my $file_selector=&scantron_uploads($file2grade);
4610: my $format_selector=&scantron_scantab();
4611: my $CODE_selector=&scantron_CODElist();
4612: my $CODE_unique=&scantron_CODEunique();
4613: my $result;
4614:
4615: # Chunk of form to prompt for a file to grade and how:
4616:
4617: $result.= <<SCANTRONFORM;
4618: <table width="100%" border="0">
4619: <tr>
4620: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
4621: <td bgcolor="#777777">
4622: <input type="hidden" name="command" value="scantron_warning" />
4623: $default_form_data
4624: <table width="100%" border="0">
4625: <tr bgcolor="#e6ffff">
4626: <td colspan="2">
4627: <b>Specify file and which Folder/Sequence to grade</b>
4628: </td>
4629: </tr>
4630: <tr bgcolor="#ffffe6">
4631: <td> Sequence to grade: </td><td> $sequence_selector </td>
4632: </tr>
4633: <tr bgcolor="#ffffe6">
4634: <td> Filename of scoring office file: </td><td> $file_selector </td>
4635: </tr>
4636: <tr bgcolor="#ffffe6">
4637: <td> Format of data file: </td><td> $format_selector </td>
4638: </tr>
4639: <tr bgcolor="#ffffe6">
4640: <td> Saved CODEs to validate against: </td><td> $CODE_selector</td>
4641: </tr>
4642: <tr bgcolor="#ffffe6">
4643: <td> Each CODE is only to be used once:</td><td> $CODE_unique </td>
4644: </tr>
4645: <tr bgcolor="#ffffe6">
4646: <td> Options: </td>
4647: <td>
4648: <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> Do only previously skipped records</label> <br />
4649: <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> Remove all existing corrections</label> <br />
4650: <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> Skip hidden resources when grading</label>
4651: </td>
4652: </tr>
4653: <tr bgcolor="#ffffe6">
4654: <td colspan="2">
4655: <input type="submit" value="Grading: Validate Scantron Records" />
4656: </td>
4657: </tr>
4658: </table>
4659: </td>
4660: </form>
4661: </tr>
4662: SCANTRONFORM
4663:
4664: $r->print($result);
4665:
4666: if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
4667: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
4668:
4669: # Chunk of form to prompt for a scantron file upload.
4670:
4671: $r->print(<<SCANTRONFORM);
4672: <tr>
4673: <td bgcolor="#777777">
4674: <table width="100%" border="0">
4675: <tr bgcolor="#e6ffff">
4676: <td>
4677: <b>Specify a Scantron data file to upload.</b>
4678: </td>
4679: </tr>
4680: <tr bgcolor="#ffffe6">
4681: <td>
4682: SCANTRONFORM
4683: my $default_form_data=&defaultFormData(&get_symb($r,1));
4684: my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
4685: my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
4686: $r->print(<<UPLOAD);
4687: <script type="text/javascript" language="javascript">
4688: function checkUpload(formname) {
4689: if (formname.upfile.value == "") {
4690: alert("Please use the browse button to select a file from your local directory.");
4691: return false;
4692: }
4693: formname.submit();
4694: }
4695: </script>
4696:
4697: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
4698: $default_form_data
4699: <input name='courseid' type='hidden' value='$cnum' />
4700: <input name='domainid' type='hidden' value='$cdom' />
4701: <input name='command' value='scantronupload_save' type='hidden' />
4702: File to upload:<input type="file" name="upfile" size="50" />
4703: <br />
4704: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
4705: </form>
4706: UPLOAD
4707:
4708: $r->print(<<SCANTRONFORM);
4709: </td>
4710: </tr>
4711: </table>
4712: </td>
4713: </tr>
4714: SCANTRONFORM
4715: }
4716:
4717: # Chunk of the form that prompts to view a scoring office file,
4718: # corrected file, skipped records in a file.
4719:
4720: $r->print(<<SCANTRONFORM);
4721: <tr>
4722: <form action='/adm/grades' name='scantron_download'>
4723: <td bgcolor="#777777">
4724: $default_form_data
4725: <input type="hidden" name="command" value="scantron_download" />
4726: <table width="100%" border="0">
4727: <tr bgcolor="#e6ffff">
4728: <td colspan="2">
4729: <b>Download a scoring office file</b>
4730: </td>
4731: </tr>
4732: <tr bgcolor="#ffffe6">
4733: <td> Filename of scoring office file: </td><td> $file_selector </td>
4734: </tr>
4735: <tr bgcolor="#ffffe6">
4736: <td colspan="2">
4737: <input type="submit" value="Download: Show List of Associated Files" />
4738: </td>
4739: </tr>
4740: </table>
4741: </td>
4742: </form>
4743: </tr>
4744: SCANTRONFORM
4745:
4746: $r->print(<<SCANTRONFORM);
4747: </table>
4748: $grading_menu_button
4749: SCANTRONFORM
4750:
4751: return
4752: }
4753:
4754: =pod
4755:
4756: =item get_scantron_config
4757:
4758: Parse and return the scantron configuration line selected as a
4759: hash of configuration file fields.
4760:
4761: Arguments:
4762: which - the name of the configuration to parse from the file.
4763:
4764:
4765: Returns:
4766: If the named configuration is not in the file, an empty
4767: hash is returned.
4768: a hash with the fields
4769: name - internal name for the this configuration setup
4770: description - text to display to operator that describes this config
4771: CODElocation - if 0 or the string 'none'
4772: - no CODE exists for this config
4773: if -1 || the string 'letter'
4774: - a CODE exists for this config and is
4775: a string of letters
4776: Unsupported value (but planned for future support)
4777: if a positive integer
4778: - The CODE exists as the first n items from
4779: the question section of the form
4780: if the string 'number'
4781: - The CODE exists for this config and is
4782: a string of numbers
4783: CODEstart - (only matter if a CODE exists) column in the line where
4784: the CODE starts
4785: CODElength - length of the CODE
4786: IDstart - column where the student ID number starts
4787: IDlength - length of the student ID info
4788: Qstart - column where the information from the bubbled
4789: 'questions' start
4790: Qlength - number of columns comprising a single bubble line from
4791: the sheet. (usually either 1 or 10)
4792: Qon - either a single character representing the character used
4793: to signal a bubble was chosen in the positional setup, or
4794: the string 'letter' if the letter of the chosen bubble is
4795: in the final, or 'number' if a number representing the
4796: chosen bubble is in the file (1->A 0->J)
4797: Qoff - the character used to represent that a bubble was
4798: left blank
4799: PaperID - if the scanning process generates a unique number for each
4800: sheet scanned the column that this ID number starts in
4801: PaperIDlength - number of columns that comprise the unique ID number
4802: for the sheet of paper
4803: FirstName - column that the first name starts in
4804: FirstNameLength - number of columns that the first name spans
4805:
4806: LastName - column that the last name starts in
4807: LastNameLength - number of columns that the last name spans
4808:
4809: =cut
4810:
4811: sub get_scantron_config {
4812: my ($which) = @_;
4813: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
4814: my %config;
4815: #FIXME probably should move to XML it has already gotten a bit much now
4816: foreach my $line (<$fh>) {
4817: my ($name,$descrip)=split(/:/,$line);
4818: if ($name ne $which ) { next; }
4819: chomp($line);
4820: my @config=split(/:/,$line);
4821: $config{'name'}=$config[0];
4822: $config{'description'}=$config[1];
4823: $config{'CODElocation'}=$config[2];
4824: $config{'CODEstart'}=$config[3];
4825: $config{'CODElength'}=$config[4];
4826: $config{'IDstart'}=$config[5];
4827: $config{'IDlength'}=$config[6];
4828: $config{'Qstart'}=$config[7];
4829: $config{'Qlength'}=$config[8];
4830: $config{'Qoff'}=$config[9];
4831: $config{'Qon'}=$config[10];
4832: $config{'PaperID'}=$config[11];
4833: $config{'PaperIDlength'}=$config[12];
4834: $config{'FirstName'}=$config[13];
4835: $config{'FirstNamelength'}=$config[14];
4836: $config{'LastName'}=$config[15];
4837: $config{'LastNamelength'}=$config[16];
4838: last;
4839: }
4840: return %config;
4841: }
4842:
4843: =pod
4844:
4845: =item username_to_idmap
4846:
4847: creates a hash keyed by student id with values of the corresponding
4848: student username:domain.
4849:
4850: Arguments:
4851:
4852: $classlist - reference to the class list hash. This is a hash
4853: keyed by student name:domain whose elements are references
4854: to arrays containing various chunks of information
4855: about the student. (See loncoursedata for more info).
4856:
4857: Returns
4858: %idmap - the constructed hash
4859:
4860: =cut
4861:
4862: sub username_to_idmap {
4863: my ($classlist)= @_;
4864: my %idmap;
4865: foreach my $student (keys(%$classlist)) {
4866: $idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
4867: $student;
4868: }
4869: return %idmap;
4870: }
4871:
4872: =pod
4873:
4874: =item scantron_fixup_scanline
4875:
4876: Process a requested correction to a scanline.
4877:
4878: Arguments:
4879: $scantron_config - hash from &get_scantron_config()
4880: $scan_data - hash of correction information
4881: (see &scantron_getfile())
4882: $line - existing scanline
4883: $whichline - line number of the passed in scanline
4884: $field - type of change to process
4885: (either
4886: 'ID' -> correct the student ID number
4887: 'CODE' -> correct the CODE
4888: 'answer' -> fixup the submitted answers)
4889:
4890: $args - hash of additional info,
4891: - 'ID'
4892: 'newid' -> studentID to use in replacement
4893: of existing one
4894: - 'CODE'
4895: 'CODE_ignore_dup' - set to true if duplicates
4896: should be ignored.
4897: 'CODE' - is new code or 'use_unfound'
4898: if the existing unfound code should
4899: be used as is
4900: - 'answer'
4901: 'response' - new answer or 'none' if blank
4902: 'question' - the bubble line to change
4903:
4904: Returns:
4905: $line - the modified scanline
4906:
4907: Side effects:
4908: $scan_data - may be updated
4909:
4910: =cut
4911:
4912:
4913: sub scantron_fixup_scanline {
4914: my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
4915:
4916: if ($field eq 'ID') {
4917: if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
4918: return ($line,1,'New value too large');
4919: }
4920: if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
4921: $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
4922: $args->{'newid'});
4923: }
4924: substr($line,$$scantron_config{'IDstart'}-1,
4925: $$scantron_config{'IDlength'})=$args->{'newid'};
4926: if ($args->{'newid'}=~/^\s*$/) {
4927: &scan_data($scan_data,"$whichline.user",
4928: $args->{'username'}.':'.$args->{'domain'});
4929: }
4930: } elsif ($field eq 'CODE') {
4931: if ($args->{'CODE_ignore_dup'}) {
4932: &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
4933: }
4934: &scan_data($scan_data,"$whichline.useCODE",'1');
4935: if ($args->{'CODE'} ne 'use_unfound') {
4936: if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
4937: return ($line,1,'New CODE value too large');
4938: }
4939: if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
4940: $args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
4941: }
4942: substr($line,$$scantron_config{'CODEstart'}-1,
4943: $$scantron_config{'CODElength'})=$args->{'CODE'};
4944: }
4945: } elsif ($field eq 'answer') {
4946: my $length=$scantron_config->{'Qlength'};
4947: my $off=$scantron_config->{'Qoff'};
4948: my $on=$scantron_config->{'Qon'};
4949: my $answer=${off}x$length;
4950: if ($args->{'response'} eq 'none') {
4951: &scan_data($scan_data,
4952: "$whichline.no_bubble.".$args->{'question'},'1');
4953: } else {
4954: if ($on eq 'letter') {
4955: my @alphabet=('A'..'Z');
4956: $answer=$alphabet[$args->{'response'}];
4957: } elsif ($on eq 'number') {
4958: $answer=$args->{'response'}+1;
4959: if ($answer == 10) { $answer = '0'; }
4960: } else {
4961: substr($answer,$args->{'response'},1)=$on;
4962: }
4963: &scan_data($scan_data,
4964: "$whichline.no_bubble.".$args->{'question'},undef,'1');
4965: }
4966: my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
4967: substr($line,$where-1,$length)=$answer;
4968: }
4969: return $line;
4970: }
4971:
4972: =pod
4973:
4974: =item scan_data
4975:
4976: Edit or look up an item in the scan_data hash.
4977:
4978: Arguments:
4979: $scan_data - The hash (see scantron_getfile)
4980: $key - shorthand of the key to edit (actual key is
4981: scantronfilename_key).
4982: $data - New value of the hash entry.
4983: $delete - If true, the entry is removed from the hash.
4984:
4985: Returns:
4986: The new value of the hash table field (undefined if deleted).
4987:
4988: =cut
4989:
4990:
4991: sub scan_data {
4992: my ($scan_data,$key,$value,$delete)=@_;
4993: my $filename=$env{'form.scantron_selectfile'};
4994: if (defined($value)) {
4995: $scan_data->{$filename.'_'.$key} = $value;
4996: }
4997: if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
4998: return $scan_data->{$filename.'_'.$key};
4999: }
5000:
5001: =pod
5002:
5003: =item scantron_parse_scanline
5004:
5005: Decodes a scanline from the selected scantron file
5006:
5007: Arguments:
5008: line - The text of the scantron file line to process
5009: whichline - Line number
5010: scantron_config - Hash describing the format of the scantron lines.
5011: scan_data - Hash of extra information about the scanline
5012: (see scantron_getfile for more information)
5013: just_header - True if should not process question answers but only
5014: the stuff to the left of the answers.
5015: Returns:
5016: Hash containing the result of parsing the scanline
5017:
5018: Keys are all proceeded by the string 'scantron.'
5019:
5020: CODE - the CODE in use for this scanline
5021: useCODE - 1 if the CODE is invalid but it usage has been forced
5022: by the operator
5023: CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
5024: CODEs were selected, but the usage has been
5025: forced by the operator
5026: ID - student ID
5027: PaperID - if used, the ID number printed on the sheet when the
5028: paper was scanned
5029: FirstName - first name from the sheet
5030: LastName - last name from the sheet
5031:
5032: if just_header was not true these key may also exist
5033:
5034: missingerror - a list of bubbled line numbers that had a blank bubble
5035: that is considered an error (if the operator had already
5036: okayed a blank bubble line as really being blank then
5037: that bubble line number won't appear here.
5038: doubleerror - a list of bubbled line numbers that had more than one
5039: bubble filled in and has not been corrected by the
5040: operator
5041: maxquest - the number of the last bubble line that was parsed
5042:
5043: (<number> starts at 1)
5044: <number>.answer - zero or more letters representing the selected
5045: letters from the scanline for the bubble line
5046: <number>.
5047: if blank there was either no bubble or there where
5048: multiple bubbles, (consult the keys missingerror and
5049: doubleerror if this is an error condition)
5050:
5051: =cut
5052:
5053: sub scantron_parse_scanline {
5054: my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
5055: my %record;
5056: my $questions=substr($line,$$scantron_config{'Qstart'}-1); # Answers
5057: my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # earlier stuff
5058: if (!($$scantron_config{'CODElocation'} eq 0 ||
5059: $$scantron_config{'CODElocation'} eq 'none')) {
5060: if ($$scantron_config{'CODElocation'} < 0 ||
5061: $$scantron_config{'CODElocation'} eq 'letter' ||
5062: $$scantron_config{'CODElocation'} eq 'number') {
5063: $record{'scantron.CODE'}=substr($data,
5064: $$scantron_config{'CODEstart'}-1,
5065: $$scantron_config{'CODElength'});
5066: if (&scan_data($scan_data,"$whichline.useCODE")) {
5067: $record{'scantron.useCODE'}=1;
5068: }
5069: if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
5070: $record{'scantron.CODE_ignore_dup'}=1;
5071: }
5072: } else {
5073: #FIXME interpret first N questions
5074: }
5075: }
5076: $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
5077: $$scantron_config{'IDlength'});
5078: $record{'scantron.PaperID'}=
5079: substr($data,$$scantron_config{'PaperID'}-1,
5080: $$scantron_config{'PaperIDlength'});
5081: $record{'scantron.FirstName'}=
5082: substr($data,$$scantron_config{'FirstName'}-1,
5083: $$scantron_config{'FirstNamelength'});
5084: $record{'scantron.LastName'}=
5085: substr($data,$$scantron_config{'LastName'}-1,
5086: $$scantron_config{'LastNamelength'});
5087: if ($just_header) { return \%record; }
5088:
5089: my @alphabet=('A'..'Z');
5090: my $questnum=0;
5091: while ($questions) {
5092: $questnum++;
5093: my $currentquest=substr($questions,0,$$scantron_config{'Qlength'});
5094: substr($questions,0,$$scantron_config{'Qlength'})='';
5095: if (length($currentquest) < $$scantron_config{'Qlength'}) { next; }
5096: if ($$scantron_config{'Qon'} eq 'letter') {
5097: if ($currentquest eq '?'
5098: || $currentquest eq '*') {
5099: push(@{$record{'scantron.doubleerror'}},$questnum);
5100: $record{"scantron.$questnum.answer"}='';
5101: } elsif (!defined($currentquest)
5102: || $currentquest eq $$scantron_config{'Qoff'}
5103: || $currentquest !~ /^[A-Z]$/) {
5104: $record{"scantron.$questnum.answer"}='';
5105: if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
5106: push(@{$record{"scantron.missingerror"}},$questnum);
5107: }
5108: } else {
5109: $record{"scantron.$questnum.answer"}=$currentquest;
5110: }
5111: } elsif ($$scantron_config{'Qon'} eq 'number') {
5112: if ($currentquest eq '?'
5113: || $currentquest eq '*') {
5114: push(@{$record{'scantron.doubleerror'}},$questnum);
5115: $record{"scantron.$questnum.answer"}='';
5116: } elsif (!defined($currentquest)
5117: || $currentquest eq $$scantron_config{'Qoff'}
5118: || $currentquest !~ /^\d$/) {
5119: $record{"scantron.$questnum.answer"}='';
5120: if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
5121: push(@{$record{"scantron.missingerror"}},$questnum);
5122: }
5123: } else {
5124: # wrap zero back to J
5125: if ($currentquest eq '0') {
5126: $record{"scantron.$questnum.answer"}=
5127: $alphabet[9];
5128: } else {
5129: $record{"scantron.$questnum.answer"}=
5130: $alphabet[$currentquest-1];
5131: }
5132: }
5133: } else {
5134: my @array=split($$scantron_config{'Qon'},$currentquest,-1);
5135: if (length($array[0]) eq $$scantron_config{'Qlength'}) {
5136: $record{"scantron.$questnum.answer"}='';
5137: if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
5138: push(@{$record{"scantron.missingerror"}},$questnum);
5139: }
5140: } else {
5141: $record{"scantron.$questnum.answer"}=
5142: $alphabet[length($array[0])];
5143: }
5144: if (scalar(@array) gt 2) {
5145: push(@{$record{'scantron.doubleerror'}},$questnum);
5146: my @ans=@array;
5147: my $i=length($ans[0]);shift(@ans);
5148: while ($#ans) {
5149: $i+=length($ans[0])+1;
5150: $record{"scantron.$questnum.answer"}.=$alphabet[$i];
5151: shift(@ans);
5152: }
5153: }
5154: }
5155: }
5156: $record{'scantron.maxquest'}=$questnum;
5157: return \%record;
5158: }
5159:
5160: =pod
5161:
5162: =item scantron_add_delay
5163:
5164: Adds an error message that occurred during the grading phase to a
5165: queue of messages to be shown after grading pass is complete
5166:
5167: Arguments:
5168: $delayqueue - arrary ref of hash ref of error messages
5169: $scanline - the scanline that caused the error
5170: $errormesage - the error message
5171: $errorcode - a numeric code for the error
5172:
5173: Side Effects:
5174: updates the $delayqueue to have a new hash ref of the error
5175:
5176: =cut
5177:
5178: sub scantron_add_delay {
5179: my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
5180: push(@$delayqueue,
5181: {'line' => $scanline, 'emsg' => $errormessage,
5182: 'ecode' => $errorcode }
5183: );
5184: }
5185:
5186: =pod
5187:
5188: =item scantron_find_student
5189:
5190: Finds the username for the current scanline
5191:
5192: Arguments:
5193: $scantron_record - hash result from scantron_parse_scanline
5194: $scan_data - hash of correction information
5195: (see &scantron_getfile() form more information)
5196: $idmap - hash from &username_to_idmap()
5197: $line - number of current scanline
5198:
5199: Returns:
5200: Either 'username:domain' or undef if unknown
5201:
5202: =cut
5203:
5204: sub scantron_find_student {
5205: my ($scantron_record,$scan_data,$idmap,$line)=@_;
5206: my $scanID=$$scantron_record{'scantron.ID'};
5207: if ($scanID =~ /^\s*$/) {
5208: return &scan_data($scan_data,"$line.user");
5209: }
5210: foreach my $id (keys(%$idmap)) {
5211: if (lc($id) eq lc($scanID)) {
5212: return $$idmap{$id};
5213: }
5214: }
5215: return undef;
5216: }
5217:
5218: =pod
5219:
5220: =item scantron_filter
5221:
5222: Filter sub for lonnavmaps, filters out hidden resources if ignore
5223: hidden resources was selected
5224:
5225: =cut
5226:
5227: sub scantron_filter {
5228: my ($curres)=@_;
5229:
5230: if (ref($curres) && $curres->is_problem()) {
5231: # if the user has asked to not have either hidden
5232: # or 'randomout' controlled resources to be graded
5233: # don't include them
5234: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
5235: && $curres->randomout) {
5236: return 0;
5237: }
5238: return 1;
5239: }
5240: return 0;
5241: }
5242:
5243: =pod
5244:
5245: =item scantron_process_corrections
5246:
5247: Gets correction information out of submitted form data and corrects
5248: the scanline
5249:
5250: =cut
5251:
5252: sub scantron_process_corrections {
5253: my ($r) = @_;
5254: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
5255: my ($scanlines,$scan_data)=&scantron_getfile();
5256: my $classlist=&Apache::loncoursedata::get_classlist();
5257: my $which=$env{'form.scantron_line'};
5258: my $line=&scantron_get_line($scanlines,$scan_data,$which);
5259: my ($skip,$err,$errmsg);
5260: if ($env{'form.scantron_skip_record'}) {
5261: $skip=1;
5262: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
5263: my $newstudent=$env{'form.scantron_username'}.':'.
5264: $env{'form.scantron_domain'};
5265: my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
5266: ($line,$err,$errmsg)=
5267: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
5268: 'ID',{'newid'=>$newid,
5269: 'username'=>$env{'form.scantron_username'},
5270: 'domain'=>$env{'form.scantron_domain'}});
5271: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
5272: my $resolution=$env{'form.scantron_CODE_resolution'};
5273: my $newCODE;
5274: my %args;
5275: if ($resolution eq 'use_unfound') {
5276: $newCODE='use_unfound';
5277: } elsif ($resolution eq 'use_found') {
5278: $newCODE=$env{'form.scantron_CODE_selectedvalue'};
5279: } elsif ($resolution eq 'use_typed') {
5280: $newCODE=$env{'form.scantron_CODE_newvalue'};
5281: } elsif ($resolution =~ /^use_closest_(\d+)/) {
5282: $newCODE=$env{"form.scantron_CODE_closest_$1"};
5283: }
5284: if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
5285: $args{'CODE_ignore_dup'}=1;
5286: }
5287: $args{'CODE'}=$newCODE;
5288: ($line,$err,$errmsg)=
5289: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
5290: 'CODE',\%args);
5291: } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
5292: foreach my $question (split(',',$env{'form.scantron_questions'})) {
5293: ($line,$err,$errmsg)=
5294: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
5295: $which,'answer',
5296: { 'question'=>$question,
5297: 'response'=>$env{"form.scantron_correct_Q_$question"}});
5298: if ($err) { last; }
5299: }
5300: }
5301: if ($err) {
5302: $r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
5303: } else {
5304: &scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
5305: &scantron_putfile($scanlines,$scan_data);
5306: }
5307: }
5308:
5309: =pod
5310:
5311: =item reset_skipping_status
5312:
5313: Forgets the current set of remember skipped scanlines (and thus
5314: reverts back to considering all lines in the
5315: scantron_skipped_<filename> file)
5316:
5317: =cut
5318:
5319: sub reset_skipping_status {
5320: my ($scanlines,$scan_data)=&scantron_getfile();
5321: &scan_data($scan_data,'remember_skipping',undef,1);
5322: &scantron_putfile(undef,$scan_data);
5323: }
5324:
5325: =pod
5326:
5327: =item start_skipping
5328:
5329: Marks a scanline to be skipped.
5330:
5331: =cut
5332:
5333: sub start_skipping {
5334: my ($scan_data,$i)=@_;
5335: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
5336: if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
5337: $remembered{$i}=2;
5338: } else {
5339: $remembered{$i}=1;
5340: }
5341: &scan_data($scan_data,'remember_skipping',join(':',%remembered));
5342: }
5343:
5344: =pod
5345:
5346: =item should_be_skipped
5347:
5348: Checks whether a scanline should be skipped.
5349:
5350: =cut
5351:
5352: sub should_be_skipped {
5353: my ($scanlines,$scan_data,$i)=@_;
5354: if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
5355: # not redoing old skips
5356: if ($scanlines->{'skipped'}[$i]) { return 1; }
5357: return 0;
5358: }
5359: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
5360:
5361: if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
5362: return 0;
5363: }
5364: return 1;
5365: }
5366:
5367: =pod
5368:
5369: =item remember_current_skipped
5370:
5371: Discovers what scanlines are in the scantron_skipped_<filename>
5372: file and remembers them into scan_data for later use.
5373:
5374: =cut
5375:
5376: sub remember_current_skipped {
5377: my ($scanlines,$scan_data)=&scantron_getfile();
5378: my %to_remember;
5379: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
5380: if ($scanlines->{'skipped'}[$i]) {
5381: $to_remember{$i}=1;
5382: }
5383: }
5384:
5385: &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
5386: &scantron_putfile(undef,$scan_data);
5387: }
5388:
5389: =pod
5390:
5391: =item check_for_error
5392:
5393: Checks if there was an error when attempting to remove a specific
5394: scantron_.. bubble sheet data file. Prints out an error if
5395: something went wrong.
5396:
5397: =cut
5398:
5399: sub check_for_error {
5400: my ($r,$result)=@_;
5401: if ($result ne 'ok' && $result ne 'not_found' ) {
5402: $r->print("An error occurred ($result) when trying to Remove the existing corrections.");
5403: }
5404: }
5405:
5406: =pod
5407:
5408: =item scantron_warning_screen
5409:
5410: Interstitial screen to make sure the operator has selected the
5411: correct options before we start the validation phase.
5412:
5413: =cut
5414:
5415: sub scantron_warning_screen {
5416: my ($button_text)=@_;
5417: my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
5418: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
5419: my $CODElist;
5420: if ($scantron_config{'CODElocation'} &&
5421: $scantron_config{'CODEstart'} &&
5422: $scantron_config{'CODElength'}) {
5423: $CODElist=$env{'form.scantron_CODElist'};
5424: if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
5425: $CODElist=
5426: '<tr><td><b>List of CODES to validate against:</b></td><td><tt>'.
5427: $env{'form.scantron_CODElist'}.'</tt></td></tr>';
5428: }
5429: return (<<STUFF);
5430: <p>
5431: <span class="LC_warning">Please double check the information
5432: below before clicking on '$button_text'</span>
5433: </p>
5434: <table>
5435: <tr><td><b>Sequence to be Graded:</b></td><td>$title</td></tr>
5436: <tr><td><b>Data File that will be used:</b></td><td><tt>$env{'form.scantron_selectfile'}</tt></td></tr>
5437: $CODElist
5438: </table>
5439: <br />
5440: <p> If this information is correct, please click on '$button_text'.</p>
5441: <p> If something is incorrect, please click the 'Grading Menu' button to start over.</p>
5442:
5443: <br />
5444: STUFF
5445: }
5446:
5447: =pod
5448:
5449: =item scantron_do_warning
5450:
5451: Check if the operator has picked something for all required
5452: fields. Error out if something is missing.
5453:
5454: =cut
5455:
5456: sub scantron_do_warning {
5457: my ($r)=@_;
5458: my ($symb)=&get_symb($r);
5459: if (!$symb) {return '';}
5460: my $default_form_data=&defaultFormData($symb);
5461: $r->print(&scantron_form_start().$default_form_data);
5462: if ( $env{'form.selectpage'} eq '' ||
5463: $env{'form.scantron_selectfile'} eq '' ||
5464: $env{'form.scantron_format'} eq '' ) {
5465: $r->print("<p>You have forgetten to specify some information. Please go Back and try again.</p>");
5466: if ( $env{'form.selectpage'} eq '') {
5467: $r->print('<p><span class="LC_error">You have not selected a Sequence to grade</span></p>');
5468: }
5469: if ( $env{'form.scantron_selectfile'} eq '') {
5470: $r->print('<p><span class="LC_error">You have not selected a file that contains the student\'s response data.</span></p>');
5471: }
5472: if ( $env{'form.scantron_format'} eq '') {
5473: $r->print('<p><span class="LC_error">You have not selected a the format of the student\'s response data.</span></p>');
5474: }
5475: } else {
5476: my $warning=&scantron_warning_screen('Grading: Validate Records');
5477: $r->print(<<STUFF);
5478: $warning
5479: <input type="submit" name="submit" value="Grading: Validate Records" />
5480: <input type="hidden" name="command" value="scantron_validate" />
5481: STUFF
5482: }
5483: $r->print("</form><br />".&show_grading_menu_form($symb));
5484: return '';
5485: }
5486:
5487: =pod
5488:
5489: =item scantron_form_start
5490:
5491: html hidden input for remembering all selected grading options
5492:
5493: =cut
5494:
5495: sub scantron_form_start {
5496: my ($max_bubble)=@_;
5497: my $result= <<SCANTRONFORM;
5498: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
5499: <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
5500: <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
5501: <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
5502: <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
5503: <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
5504: <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
5505: <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
5506: <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
5507: <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
5508: SCANTRONFORM
5509: return $result;
5510: }
5511:
5512: =pod
5513:
5514: =item scantron_validate_file
5515:
5516: Dispatch routine for doing validation of a bubble sheet data file.
5517:
5518: Also processes any necessary information resets that need to
5519: occur before validation begins (ignore previous corrections,
5520: restarting the skipped records processing)
5521:
5522: =cut
5523:
5524: sub scantron_validate_file {
5525: my ($r) = @_;
5526: my ($symb)=&get_symb($r);
5527: if (!$symb) {return '';}
5528: my $default_form_data=&defaultFormData($symb);
5529:
5530: # do the detection of only doing skipped records first befroe we delete
5531: # them when doing the corrections reset
5532: if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
5533: &reset_skipping_status();
5534: }
5535: if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
5536: &remember_current_skipped();
5537: $env{'form.scantron_options_redo'}='redo_skipped_ready';
5538: }
5539:
5540: if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
5541: &check_for_error($r,&scantron_remove_file('corrected'));
5542: &check_for_error($r,&scantron_remove_file('skipped'));
5543: &check_for_error($r,&scantron_remove_scan_data());
5544: $env{'form.scantron_options_ignore'}='done';
5545: }
5546:
5547: if ($env{'form.scantron_corrections'}) {
5548: &scantron_process_corrections($r);
5549: }
5550: $r->print("<p>Gathering necessary info.</p>");$r->rflush();
5551: #get the student pick code ready
5552: $r->print(&Apache::loncommon::studentbrowser_javascript());
5553: my $max_bubble=&scantron_get_maxbubble();
5554: my $result=&scantron_form_start($max_bubble).$default_form_data;
5555: $r->print($result);
5556:
5557: my @validate_phases=( 'sequence',
5558: 'ID',
5559: 'CODE',
5560: 'doublebubble',
5561: 'missingbubbles');
5562: if (!$env{'form.validatepass'}) {
5563: $env{'form.validatepass'} = 0;
5564: }
5565: my $currentphase=$env{'form.validatepass'};
5566:
5567: my $stop=0;
5568: while (!$stop && $currentphase < scalar(@validate_phases)) {
5569: $r->print("<p> Validating ".$validate_phases[$currentphase]."</p>");
5570: $r->rflush();
5571: my $which="scantron_validate_".$validate_phases[$currentphase];
5572: {
5573: no strict 'refs';
5574: ($stop,$currentphase)=&$which($r,$currentphase);
5575: }
5576: }
5577: if (!$stop) {
5578: my $warning=&scantron_warning_screen('Start Grading');
5579: $r->print(<<STUFF);
5580: Validation process complete.<br />
5581: $warning
5582: <input type="submit" name="submit" value="Start Grading" />
5583: <input type="hidden" name="command" value="scantron_process" />
5584: STUFF
5585:
5586: } else {
5587: $r->print('<input type="hidden" name="command" value="scantron_validate" />');
5588: $r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
5589: }
5590: if ($stop) {
5591: if ($validate_phases[$currentphase] eq 'sequence') {
5592: $r->print('<input type="submit" name="submit" value="Ignore -> " />');
5593: $r->print(' this error <br />');
5594:
5595: $r->print(" <p>Or click the 'Grading Menu' button to start over.</p>");
5596: } else {
5597: $r->print('<input type="submit" name="submit" value="Continue ->" />');
5598: $r->print(' using corrected info <br />');
5599: $r->print("<input type='submit' value='Skip' name='scantron_skip_record' />");
5600: $r->print(" this scanline saving it for later.");
5601: }
5602: }
5603: $r->print(" </form><br />".&show_grading_menu_form($symb));
5604: return '';
5605: }
5606:
5607:
5608: =pod
5609:
5610: =item scantron_remove_file
5611:
5612: Removes the requested bubble sheet data file, makes sure that
5613: scantron_original_<filename> is never removed
5614:
5615:
5616: =cut
5617:
5618: sub scantron_remove_file {
5619: my ($which)=@_;
5620: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5621: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5622: my $file='scantron_';
5623: if ($which eq 'corrected' || $which eq 'skipped') {
5624: $file.=$which.'_';
5625: } else {
5626: return 'refused';
5627: }
5628: $file.=$env{'form.scantron_selectfile'};
5629: return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
5630: }
5631:
5632:
5633: =pod
5634:
5635: =item scantron_remove_scan_data
5636:
5637: Removes all scan_data correction for the requested bubble sheet
5638: data file. (In the case that both the are doing skipped records we need
5639: to remember the old skipped lines for the time being so that element
5640: persists for a while.)
5641:
5642: =cut
5643:
5644: sub scantron_remove_scan_data {
5645: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5646: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5647: my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
5648: my @todelete;
5649: my $filename=$env{'form.scantron_selectfile'};
5650: foreach my $key (@keys) {
5651: if ($key=~/^\Q$filename\E_/) {
5652: if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
5653: $key=~/remember_skipping/) {
5654: next;
5655: }
5656: push(@todelete,$key);
5657: }
5658: }
5659: my $result;
5660: if (@todelete) {
5661: $result=&Apache::lonnet::del('nohist_scantrondata',\@todelete,$cdom,$cname);
5662: }
5663: return $result;
5664: }
5665:
5666:
5667: =pod
5668:
5669: =item scantron_getfile
5670:
5671: Fetches the requested bubble sheet data file (all 3 versions), and
5672: the scan_data hash
5673:
5674: Arguments:
5675: None
5676:
5677: Returns:
5678: 2 hash references
5679:
5680: - first one has
5681: orig -
5682: corrected -
5683: skipped - each of which points to an array ref of the specified
5684: file broken up into individual lines
5685: count - number of scanlines
5686:
5687: - second is the scan_data hash possible keys are
5688: ($number refers to scanline numbered $number and thus the key affects
5689: only that scanline
5690: $bubline refers to the specific bubble line element and the aspects
5691: refers to that specific bubble line element)
5692:
5693: $number.user - username:domain to use
5694: $number.CODE_ignore_dup
5695: - ignore the duplicate CODE error
5696: $number.useCODE
5697: - use the CODE in the scanline as is
5698: $number.no_bubble.$bubline
5699: - it is valid that there is no bubbled in bubble
5700: at $number $bubline
5701: remember_skipping
5702: - a frozen hash containing keys of $number and values
5703: of either
5704: 1 - we are on a 'do skipped records pass' and plan
5705: on processing this line
5706: 2 - we are on a 'do skipped records pass' and this
5707: scanline has been marked to skip yet again
5708:
5709: =cut
5710:
5711: sub scantron_getfile {
5712: #FIXME really would prefer a scantron directory
5713: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5714: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5715: my $lines;
5716: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
5717: 'scantron_orig_'.$env{'form.scantron_selectfile'});
5718: my %scanlines;
5719: $scanlines{'orig'}=[(split("\n",$lines,-1))];
5720: my $temp=$scanlines{'orig'};
5721: $scanlines{'count'}=$#$temp;
5722:
5723: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
5724: 'scantron_corrected_'.$env{'form.scantron_selectfile'});
5725: if ($lines eq '-1') {
5726: $scanlines{'corrected'}=[];
5727: } else {
5728: $scanlines{'corrected'}=[(split("\n",$lines,-1))];
5729: }
5730: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
5731: 'scantron_skipped_'.$env{'form.scantron_selectfile'});
5732: if ($lines eq '-1') {
5733: $scanlines{'skipped'}=[];
5734: } else {
5735: $scanlines{'skipped'}=[(split("\n",$lines,-1))];
5736: }
5737: my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
5738: if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
5739: my %scan_data = @tmp;
5740: return (\%scanlines,\%scan_data);
5741: }
5742:
5743: =pod
5744:
5745: =item lonnet_putfile
5746:
5747: Wrapper routine to call &Apache::lonnet::finishuserfileupload
5748:
5749: Arguments:
5750: $contents - data to store
5751: $filename - filename to store $contents into
5752:
5753: Returns:
5754: result value from &Apache::lonnet::finishuserfileupload
5755:
5756: =cut
5757:
5758: sub lonnet_putfile {
5759: my ($contents,$filename)=@_;
5760: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
5761: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5762: $env{'form.sillywaytopassafilearound'}=$contents;
5763: &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
5764:
5765: }
5766:
5767: =pod
5768:
5769: =item scantron_putfile
5770:
5771: Stores the current version of the bubble sheet data files, and the
5772: scan_data hash. (Does not modify the original version only the
5773: corrected and skipped versions.
5774:
5775: Arguments:
5776: $scanlines - hash ref that looks like the first return value from
5777: &scantron_getfile()
5778: $scan_data - hash ref that looks like the second return value from
5779: &scantron_getfile()
5780:
5781: =cut
5782:
5783: sub scantron_putfile {
5784: my ($scanlines,$scan_data) = @_;
5785: #FIXME really would prefer a scantron directory
5786: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5787: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5788: if ($scanlines) {
5789: my $prefix='scantron_';
5790: # no need to update orig, shouldn't change
5791: # &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
5792: # $env{'form.scantron_selectfile'});
5793: &lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
5794: $prefix.'corrected_'.
5795: $env{'form.scantron_selectfile'});
5796: &lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
5797: $prefix.'skipped_'.
5798: $env{'form.scantron_selectfile'});
5799: }
5800: &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
5801: }
5802:
5803: =pod
5804:
5805: =item scantron_get_line
5806:
5807: Returns the correct version of the scanline
5808:
5809: Arguments:
5810: $scanlines - hash ref that looks like the first return value from
5811: &scantron_getfile()
5812: $scan_data - hash ref that looks like the second return value from
5813: &scantron_getfile()
5814: $i - number of the requested line (starts at 0)
5815:
5816: Returns:
5817: A scanline, (either the original or the corrected one if it
5818: exists), or undef if the requested scanline should be
5819: skipped. (Either because it's an skipped scanline, or it's an
5820: unskipped scanline and we are not doing a 'do skipped scanlines'
5821: pass.
5822:
5823: =cut
5824:
5825: sub scantron_get_line {
5826: my ($scanlines,$scan_data,$i)=@_;
5827: if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
5828: #if ($scanlines->{'skipped'}[$i]) { return undef; }
5829: if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
5830: return $scanlines->{'orig'}[$i];
5831: }
5832:
5833: =pod
5834:
5835: =item scantron_todo_count
5836:
5837: Counts the number of scanlines that need processing.
5838:
5839: Arguments:
5840: $scanlines - hash ref that looks like the first return value from
5841: &scantron_getfile()
5842: $scan_data - hash ref that looks like the second return value from
5843: &scantron_getfile()
5844:
5845: Returns:
5846: $count - number of scanlines to process
5847:
5848: =cut
5849:
5850: sub get_todo_count {
5851: my ($scanlines,$scan_data)=@_;
5852: my $count=0;
5853: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
5854: my $line=&scantron_get_line($scanlines,$scan_data,$i);
5855: if ($line=~/^[\s\cz]*$/) { next; }
5856: $count++;
5857: }
5858: return $count;
5859: }
5860:
5861: =pod
5862:
5863: =item scantron_put_line
5864:
5865: Updates the 'corrected' or 'skipped' versions of the bubble sheet
5866: data file.
5867:
5868: Arguments:
5869: $scanlines - hash ref that looks like the first return value from
5870: &scantron_getfile()
5871: $scan_data - hash ref that looks like the second return value from
5872: &scantron_getfile()
5873: $i - line number to update
5874: $newline - contents of the updated scanline
5875: $skip - if true make the line for skipping and update the
5876: 'skipped' file
5877:
5878: =cut
5879:
5880: sub scantron_put_line {
5881: my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
5882: if ($skip) {
5883: $scanlines->{'skipped'}[$i]=$newline;
5884: &start_skipping($scan_data,$i);
5885: return;
5886: }
5887: $scanlines->{'corrected'}[$i]=$newline;
5888: }
5889:
5890: =pod
5891:
5892: =item scantron_clear_skip
5893:
5894: Remove a line from the 'skipped' file
5895:
5896: Arguments:
5897: $scanlines - hash ref that looks like the first return value from
5898: &scantron_getfile()
5899: $scan_data - hash ref that looks like the second return value from
5900: &scantron_getfile()
5901: $i - line number to update
5902:
5903: =cut
5904:
5905: sub scantron_clear_skip {
5906: my ($scanlines,$scan_data,$i)=@_;
5907: if (exists($scanlines->{'skipped'}[$i])) {
5908: undef($scanlines->{'skipped'}[$i]);
5909: return 1;
5910: }
5911: return 0;
5912: }
5913:
5914: =pod
5915:
5916: =item scantron_filter_not_exam
5917:
5918: Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
5919: filter out resources that are not marked as 'exam' mode
5920:
5921: =cut
5922:
5923: sub scantron_filter_not_exam {
5924: my ($curres)=@_;
5925:
5926: if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
5927: # if the user has asked to not have either hidden
5928: # or 'randomout' controlled resources to be graded
5929: # don't include them
5930: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
5931: && $curres->randomout) {
5932: return 0;
5933: }
5934: return 1;
5935: }
5936: return 0;
5937: }
5938:
5939: =pod
5940:
5941: =item scantron_validate_sequence
5942:
5943: Validates the selected sequence, checking for resource that are
5944: not set to exam mode.
5945:
5946: =cut
5947:
5948: sub scantron_validate_sequence {
5949: my ($r,$currentphase) = @_;
5950:
5951: my $navmap=Apache::lonnavmaps::navmap->new();
5952: my (undef,undef,$sequence)=
5953: &Apache::lonnet::decode_symb($env{'form.selectpage'});
5954:
5955: my $map=$navmap->getResourceByUrl($sequence);
5956:
5957: $r->print('<input type="hidden" name="validate_sequence_exam"
5958: value="ignore" />');
5959: if ($env{'form.validate_sequence_exam'} ne 'ignore') {
5960: my @resources=
5961: $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
5962: if (@resources) {
5963: $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>");
5964: return (1,$currentphase);
5965: }
5966: }
5967:
5968: return (0,$currentphase+1);
5969: }
5970:
5971: =pod
5972:
5973: =item scantron_validate_ID
5974:
5975: Validates all scanlines in the selected file to not have any
5976: invalid or underspecified student IDs
5977:
5978: =cut
5979:
5980: sub scantron_validate_ID {
5981: my ($r,$currentphase) = @_;
5982:
5983: #get student info
5984: my $classlist=&Apache::loncoursedata::get_classlist();
5985: my %idmap=&username_to_idmap($classlist);
5986:
5987: #get scantron line setup
5988: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
5989: my ($scanlines,$scan_data)=&scantron_getfile();
5990:
5991: my %found=('ids'=>{},'usernames'=>{});
5992: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
5993: my $line=&scantron_get_line($scanlines,$scan_data,$i);
5994: if ($line=~/^[\s\cz]*$/) { next; }
5995: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
5996: $scan_data);
5997: my $id=$$scan_record{'scantron.ID'};
5998: my $found;
5999: foreach my $checkid (keys(%idmap)) {
6000: if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
6001: }
6002: if ($found) {
6003: my $username=$idmap{$found};
6004: if ($found{'ids'}{$found}) {
6005: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6006: $line,'duplicateID',$found);
6007: return(1,$currentphase);
6008: } elsif ($found{'usernames'}{$username}) {
6009: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6010: $line,'duplicateID',$username);
6011: return(1,$currentphase);
6012: }
6013: #FIXME store away line we previously saw the ID on to use above
6014: $found{'ids'}{$found}++;
6015: $found{'usernames'}{$username}++;
6016: } else {
6017: if ($id =~ /^\s*$/) {
6018: my $username=&scan_data($scan_data,"$i.user");
6019: if (defined($username) && $found{'usernames'}{$username}) {
6020: &scantron_get_correction($r,$i,$scan_record,
6021: \%scantron_config,
6022: $line,'duplicateID',$username);
6023: return(1,$currentphase);
6024: } elsif (!defined($username)) {
6025: &scantron_get_correction($r,$i,$scan_record,
6026: \%scantron_config,
6027: $line,'incorrectID');
6028: return(1,$currentphase);
6029: }
6030: $found{'usernames'}{$username}++;
6031: } else {
6032: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6033: $line,'incorrectID');
6034: return(1,$currentphase);
6035: }
6036: }
6037: }
6038:
6039: return (0,$currentphase+1);
6040: }
6041:
6042: =pod
6043:
6044: =item scantron_get_correction
6045:
6046: Builds the interface screen to interact with the operator to fix a
6047: specific error condition in a specific scanline
6048:
6049: Arguments:
6050: $r - Apache request object
6051: $i - number of the current scanline
6052: $scan_record - hash ref as returned from &scantron_parse_scanline()
6053: $scan_config - hash ref as returned from &get_scantron_config()
6054: $line - full contents of the current scanline
6055: $error - error condition, valid values are
6056: 'incorrectCODE', 'duplicateCODE',
6057: 'doublebubble', 'missingbubble',
6058: 'duplicateID', 'incorrectID'
6059: $arg - extra information needed
6060: For errors:
6061: - duplicateID - paper number that this studentID was seen before on
6062: - duplicateCODE - array ref of the paper numbers this CODE was
6063: seen on before
6064: - incorrectCODE - current incorrect CODE
6065: - doublebubble - array ref of the bubble lines that have double
6066: bubble errors
6067: - missingbubble - array ref of the bubble lines that have missing
6068: bubble errors
6069:
6070: =cut
6071:
6072: sub scantron_get_correction {
6073: my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
6074:
6075: #FIXME in the case of a duplicated ID the previous line, probaly need
6076: #to show both the current line and the previous one and allow skipping
6077: #the previous one or the current one
6078:
6079: $r->print("<p><b>An error was detected ($error)</b>");
6080: if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
6081: $r->print(" for PaperID <tt>".
6082: $$scan_record{'scantron.PaperID'}."</tt> \n");
6083: } else {
6084: $r->print(" in scanline $i <pre>".
6085: $line."</pre> \n");
6086: }
6087: my $message="<p>The ID on the form is <tt>".
6088: $$scan_record{'scantron.ID'}."</tt><br />\n".
6089: "The name on the paper is ".
6090: $$scan_record{'scantron.LastName'}.",".
6091: $$scan_record{'scantron.FirstName'}."</p>";
6092:
6093: $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
6094: $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
6095: if ($error =~ /ID$/) {
6096: if ($error eq 'incorrectID') {
6097: $r->print("The encoded ID is not in the classlist</p>\n");
6098: } elsif ($error eq 'duplicateID') {
6099: $r->print("The encoded ID has also been used by a previous paper $arg</p>\n");
6100: }
6101: $r->print($message);
6102: $r->print("<p>How should I handle this? <br /> \n");
6103: $r->print("\n<ul><li> ");
6104: #FIXME it would be nice if this sent back the user ID and
6105: #could do partial userID matches
6106: $r->print(&Apache::loncommon::selectstudent_link('scantronupload',
6107: 'scantron_username','scantron_domain'));
6108: $r->print(": <input type='text' name='scantron_username' value='' />");
6109: $r->print("\n@".
6110: &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
6111:
6112: $r->print('</li>');
6113: } elsif ($error =~ /CODE$/) {
6114: if ($error eq 'incorrectCODE') {
6115: $r->print("</p><p>The encoded CODE is not in the list of possible CODEs</p>\n");
6116: } elsif ($error eq 'duplicateCODE') {
6117: $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");
6118: }
6119: $r->print("<p>The CODE on the form is <tt>'".
6120: $$scan_record{'scantron.CODE'}."'</tt><br />\n");
6121: $r->print($message);
6122: $r->print("<p>How should I handle this? <br /> \n");
6123: $r->print("\n<br /> ");
6124: my $i=0;
6125: if ($error eq 'incorrectCODE'
6126: && $$scan_record{'scantron.CODE'}=~/\S/ ) {
6127: my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
6128: if ($closest > 0) {
6129: foreach my $testcode (@{$closest}) {
6130: my $checked='';
6131: if (!$i) { $checked=' checked="checked" '; }
6132: $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' />");
6133: $r->print("\n<br />");
6134: $i++;
6135: }
6136: }
6137: }
6138: if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
6139: my $checked; if (!$i) { $checked=' checked="checked" '; }
6140: $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>");
6141: $r->print("\n<br />");
6142: }
6143:
6144: $r->print(<<ENDSCRIPT);
6145: <script type="text/javascript">
6146: function change_radio(field) {
6147: var slct=document.scantronupload.scantron_CODE_resolution;
6148: var i;
6149: for (i=0;i<slct.length;i++) {
6150: if (slct[i].value==field) { slct[i].checked=true; }
6151: }
6152: }
6153: </script>
6154: ENDSCRIPT
6155: my $href="/adm/pickcode?".
6156: "form=".&escape("scantronupload").
6157: "&scantron_format=".&escape($env{'form.scantron_format'}).
6158: "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
6159: "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
6160: "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
6161: if ($env{'form.scantron_CODElist'} =~ /\S/) {
6162: $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')\" />");
6163: $r->print("\n<br />");
6164: }
6165: $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.");
6166: $r->print("\n<br /><br />");
6167: } elsif ($error eq 'doublebubble') {
6168: $r->print("<p>There have been multiple bubbles scanned for a some question(s)</p>\n");
6169: $r->print('<input type="hidden" name="scantron_questions" value="'.
6170: join(',',@{$arg}).'" />');
6171: $r->print($message);
6172: $r->print("<p>Please indicate which bubble should be used for grading</p>");
6173: foreach my $question (@{$arg}) {
6174: my $selected=$$scan_record{"scantron.$question.answer"};
6175: &scantron_bubble_selector($r,$scan_config,$question,
6176: split('',$selected));
6177: }
6178: } elsif ($error eq 'missingbubble') {
6179: $r->print("<p>There have been <b>no</b> bubbles scanned for some question(s)</p>\n");
6180: $r->print($message);
6181: $r->print("<p>Please indicate which bubble should be used for grading</p>");
6182: $r->print("Some questions have no scanned bubbles\n");
6183: $r->print('<input type="hidden" name="scantron_questions" value="'.
6184: join(',',@{$arg}).'" />');
6185: foreach my $question (@{$arg}) {
6186: my $selected=$$scan_record{"scantron.$question.answer"};
6187: &scantron_bubble_selector($r,$scan_config,$question);
6188: }
6189: } else {
6190: $r->print("\n<ul>");
6191: }
6192: $r->print("\n</li></ul>");
6193:
6194: }
6195:
6196: =pod
6197:
6198: =item scantron_bubble_selector
6199:
6200: Generates the html radiobuttons to correct a single bubble line
6201: possibly showing the existing the selected bubbles if known
6202:
6203: Arguments:
6204: $r - Apache request object
6205: $scan_config - hash from &get_scantron_config()
6206: $quest - number of the bubble line to make a corrector for
6207: $selected - array of letters of previously selected bubbles
6208: $lines - if present, number of bubble lines to show
6209:
6210: =cut
6211:
6212: sub scantron_bubble_selector {
6213: my ($r,$scan_config,$quest,@selected, $lines)=@_;
6214: my $max=$$scan_config{'Qlength'};
6215:
6216: my $scmode=$$scan_config{'Qon'};
6217: if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }
6218:
6219:
6220: if (!defined($lines)) {
6221: $lines = 1;
6222: }
6223: my $total_lines = $lines*2;
6224: my @alphabet=('A'..'Z');
6225: $r->print("<table border='1'><tr><td rowspan='".$total_lines."'>$quest</td>");
6226:
6227: for (my $l = 0; $l < $lines; $l++) {
6228: if ($l != 0) {
6229: $r->print('<tr>');
6230: }
6231:
6232: # FIXME: This loop probably has to be considerably more clever for
6233: # multiline bubbles: User can multibubble by having bubbles in
6234: # several lines. User can skip lines legitimately etc. etc.
6235:
6236: for (my $i=0;$i<$max;$i++) {
6237: $r->print("\n".'<td align="center">');
6238: if ($selected[0] eq $alphabet[$i]) {
6239: $r->print('X');
6240: shift(@selected) ;
6241: } else {
6242: $r->print(' ');
6243: }
6244: $r->print('</td>');
6245:
6246: }
6247:
6248: if ($l == 0) {
6249: my $lspan = $total_lines * 2; # 2 table rows per bubble line.
6250:
6251: $r->print('<td rowspan='.$lspan.'><label><input type="radio" name="scantron_correct_Q_'.
6252: $quest.'" value="none" /> No bubble </label></td>');
6253:
6254: }
6255:
6256: $r->print('</tr><tr>');
6257:
6258: # FIXME: This may have to be a bit more clever for
6259: # multiline questions (different values e.g..).
6260:
6261: for (my $i=0;$i<$max;$i++) {
6262: $r->print("\n".
6263: '<td><label><input type="radio" name="scantron_correct_Q_'.
6264: $quest.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
6265: }
6266: $r->print('</tr>');
6267:
6268:
6269: }
6270: $r->print('</table>');
6271: }
6272:
6273: =pod
6274:
6275: =item num_matches
6276:
6277: Counts the number of characters that are the same between the two arguments.
6278:
6279: Arguments:
6280: $orig - CODE from the scanline
6281: $code - CODE to match against
6282:
6283: Returns:
6284: $count - integer count of the number of same characters between the
6285: two arguments
6286:
6287: =cut
6288:
6289: sub num_matches {
6290: my ($orig,$code) = @_;
6291: my @code=split(//,$code);
6292: my @orig=split(//,$orig);
6293: my $same=0;
6294: for (my $i=0;$i<scalar(@code);$i++) {
6295: if ($code[$i] eq $orig[$i]) { $same++; }
6296: }
6297: return $same;
6298: }
6299:
6300: =pod
6301:
6302: =item scantron_get_closely_matching_CODEs
6303:
6304: Cycles through all CODEs and finds the set that has the greatest
6305: number of same characters as the provided CODE
6306:
6307: Arguments:
6308: $allcodes - hash ref returned by &get_codes()
6309: $CODE - CODE from the current scanline
6310:
6311: Returns:
6312: 2 element list
6313: - first elements is number of how closely matching the best fit is
6314: (5 means best set has 5 matching characters)
6315: - second element is an arrary ref containing the set of valid CODEs
6316: that best fit the passed in CODE
6317:
6318: =cut
6319:
6320: sub scantron_get_closely_matching_CODEs {
6321: my ($allcodes,$CODE)=@_;
6322: my @CODEs;
6323: foreach my $testcode (sort(keys(%{$allcodes}))) {
6324: push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
6325: }
6326:
6327: return ($#CODEs,$CODEs[-1]);
6328: }
6329:
6330: =pod
6331:
6332: =item get_codes
6333:
6334: Builds a hash which has keys of all of the valid CODEs from the selected
6335: set of remembered CODEs.
6336:
6337: Arguments:
6338: $old_name - name of the set of remembered CODEs
6339: $cdom - domain of the course
6340: $cnum - internal course name
6341:
6342: Returns:
6343: %allcodes - keys are the valid CODEs, values are all 1
6344:
6345: =cut
6346:
6347: sub get_codes {
6348: my ($old_name, $cdom, $cnum) = @_;
6349: if (!$old_name) {
6350: $old_name=$env{'form.scantron_CODElist'};
6351: }
6352: if (!$cdom) {
6353: $cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
6354: }
6355: if (!$cnum) {
6356: $cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
6357: }
6358: my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
6359: $cdom,$cnum);
6360: my %allcodes;
6361: if ($result{"type\0$old_name"} eq 'number') {
6362: %allcodes=map {($_,1)} split(',',$result{$old_name});
6363: } else {
6364: %allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
6365: }
6366: return %allcodes;
6367: }
6368:
6369: =pod
6370:
6371: =item scantron_validate_CODE
6372:
6373: Validates all scanlines in the selected file to not have any
6374: invalid or underspecified CODEs and that none of the codes are
6375: duplicated if this was requested.
6376:
6377: =cut
6378:
6379: sub scantron_validate_CODE {
6380: my ($r,$currentphase) = @_;
6381: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6382: if ($scantron_config{'CODElocation'} &&
6383: $scantron_config{'CODEstart'} &&
6384: $scantron_config{'CODElength'}) {
6385: if (!defined($env{'form.scantron_CODElist'})) {
6386: &FIXME_blow_up()
6387: }
6388: } else {
6389: return (0,$currentphase+1);
6390: }
6391:
6392: my %usedCODEs;
6393:
6394: my %allcodes=&get_codes();
6395:
6396: my ($scanlines,$scan_data)=&scantron_getfile();
6397: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6398: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6399: if ($line=~/^[\s\cz]*$/) { next; }
6400: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6401: $scan_data);
6402: my $CODE=$$scan_record{'scantron.CODE'};
6403: my $error=0;
6404: if (!&Apache::lonnet::validCODE($CODE)) {
6405: &scantron_get_correction($r,$i,$scan_record,
6406: \%scantron_config,
6407: $line,'incorrectCODE',\%allcodes);
6408: return(1,$currentphase);
6409: }
6410: if (%allcodes && !exists($allcodes{$CODE})
6411: && !$$scan_record{'scantron.useCODE'}) {
6412: &scantron_get_correction($r,$i,$scan_record,
6413: \%scantron_config,
6414: $line,'incorrectCODE',\%allcodes);
6415: return(1,$currentphase);
6416: }
6417: if (exists($usedCODEs{$CODE})
6418: && $env{'form.scantron_CODEunique'} eq 'yes'
6419: && !$$scan_record{'scantron.CODE_ignore_dup'}) {
6420: &scantron_get_correction($r,$i,$scan_record,
6421: \%scantron_config,
6422: $line,'duplicateCODE',$usedCODEs{$CODE});
6423: return(1,$currentphase);
6424: }
6425: push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
6426: }
6427: return (0,$currentphase+1);
6428: }
6429:
6430: =pod
6431:
6432: =item scantron_validate_doublebubble
6433:
6434: Validates all scanlines in the selected file to not have any
6435: bubble lines with multiple bubbles marked.
6436:
6437: =cut
6438:
6439: sub scantron_validate_doublebubble {
6440: my ($r,$currentphase) = @_;
6441: #get student info
6442: my $classlist=&Apache::loncoursedata::get_classlist();
6443: my %idmap=&username_to_idmap($classlist);
6444:
6445: #get scantron line setup
6446: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6447: my ($scanlines,$scan_data)=&scantron_getfile();
6448: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6449: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6450: if ($line=~/^[\s\cz]*$/) { next; }
6451: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6452: $scan_data);
6453: if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
6454: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
6455: 'doublebubble',
6456: $$scan_record{'scantron.doubleerror'});
6457: return (1,$currentphase);
6458: }
6459: return (0,$currentphase+1);
6460: }
6461:
6462: =pod
6463:
6464: =item scantron_get_maxbubble
6465:
6466: Returns the maximum number of bubble lines that are expected to
6467: occur. Does this by walking the selected sequence rendering the
6468: resource and then checking &Apache::lonxml::get_problem_counter()
6469: for what the current value of the problem counter is.
6470:
6471: Caches the result to $env{'form.scantron_maxbubble'}
6472:
6473: =cut
6474:
6475: sub scantron_get_maxbubble {
6476: if (defined($env{'form.scantron_maxbubble'}) &&
6477: $env{'form.scantron_maxbubble'}) {
6478: return $env{'form.scantron_maxbubble'};
6479: }
6480:
6481: my $navmap=Apache::lonnavmaps::navmap->new();
6482: my (undef,undef,$sequence)=
6483: &Apache::lonnet::decode_symb($env{'form.selectpage'});
6484:
6485: my $map=$navmap->getResourceByUrl($sequence);
6486: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
6487:
6488: &Apache::lonxml::clear_problem_counter();
6489:
6490: foreach my $resource (@resources) {
6491: my $result=&Apache::lonnet::ssi($resource->src(),
6492: ('symb' => $resource->symb()));
6493: }
6494: &Apache::lonnet::delenv('scantron\.');
6495: $env{'form.scantron_maxbubble'} =
6496: &Apache::lonxml::get_problem_counter()-1;
6497:
6498: return $env{'form.scantron_maxbubble'};
6499: }
6500:
6501: =pod
6502:
6503: =item scantron_validate_missingbubbles
6504:
6505: Validates all scanlines in the selected file to not have any
6506: bubble lines with missing bubbles that haven't been verified as missing.
6507:
6508: =cut
6509:
6510: sub scantron_validate_missingbubbles {
6511: my ($r,$currentphase) = @_;
6512: #get student info
6513: my $classlist=&Apache::loncoursedata::get_classlist();
6514: my %idmap=&username_to_idmap($classlist);
6515:
6516: #get scantron line setup
6517: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6518: my ($scanlines,$scan_data)=&scantron_getfile();
6519: my $max_bubble=&scantron_get_maxbubble();
6520: if (!$max_bubble) { $max_bubble=2**31; }
6521: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6522: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6523: if ($line=~/^[\s\cz]*$/) { next; }
6524: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6525: $scan_data);
6526: if (!defined($$scan_record{'scantron.missingerror'})) { next; }
6527: my @to_correct;
6528: foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
6529: if ($missing > $max_bubble) { next; }
6530: push(@to_correct,$missing);
6531: }
6532: if (@to_correct) {
6533: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6534: $line,'missingbubble',\@to_correct);
6535: return (1,$currentphase);
6536: }
6537:
6538: }
6539: return (0,$currentphase+1);
6540: }
6541:
6542: =pod
6543:
6544: =item scantron_process_students
6545:
6546: Routine that does the actual grading of the bubble sheet information.
6547:
6548: The parsed scanline hash is added to %env
6549:
6550: Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
6551: foreach resource , with the form data of
6552:
6553: 'submitted' =>'scantron'
6554: 'grade_target' =>'grade',
6555: 'grade_username'=> username of student
6556: 'grade_domain' => domain of student
6557: 'grade_courseid'=> of course
6558: 'grade_symb' => symb of resource to grade
6559:
6560: This triggers a grading pass. The problem grading code takes care
6561: of converting the bubbled letter information (now in %env) into a
6562: valid submission.
6563:
6564: =cut
6565:
6566: sub scantron_process_students {
6567: my ($r) = @_;
6568: my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
6569: my ($symb)=&get_symb($r);
6570: if (!$symb) {return '';}
6571: my $default_form_data=&defaultFormData($symb);
6572:
6573: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6574: my ($scanlines,$scan_data)=&scantron_getfile();
6575: my $classlist=&Apache::loncoursedata::get_classlist();
6576: my %idmap=&username_to_idmap($classlist);
6577: my $navmap=Apache::lonnavmaps::navmap->new();
6578: my $map=$navmap->getResourceByUrl($sequence);
6579: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
6580: # $r->print("geto ".scalar(@resources)."<br />");
6581: my $result= <<SCANTRONFORM;
6582: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
6583: <input type="hidden" name="command" value="scantron_configphase" />
6584: $default_form_data
6585: SCANTRONFORM
6586: $r->print($result);
6587:
6588: my @delayqueue;
6589: my %completedstudents;
6590:
6591: my $count=&get_todo_count($scanlines,$scan_data);
6592: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
6593: 'Scantron Progress',$count,
6594: 'inline',undef,'scantronupload');
6595: &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
6596: 'Processing first student');
6597: my $start=&Time::HiRes::time();
6598: my $i=-1;
6599: my ($uname,$udom,$started);
6600: while ($i<$scanlines->{'count'}) {
6601: ($uname,$udom)=('','');
6602: $i++;
6603: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6604: if ($line=~/^[\s\cz]*$/) { next; }
6605: if ($started) {
6606: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
6607: 'last student');
6608: }
6609: $started=1;
6610: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6611: $scan_data);
6612: unless ($uname=&scantron_find_student($scan_record,$scan_data,
6613: \%idmap,$i)) {
6614: &scantron_add_delay(\@delayqueue,$line,
6615: 'Unable to find a student that matches',1);
6616: next;
6617: }
6618: if (exists $completedstudents{$uname}) {
6619: &scantron_add_delay(\@delayqueue,$line,
6620: 'Student '.$uname.' has multiple sheets',2);
6621: next;
6622: }
6623: ($uname,$udom)=split(/:/,$uname);
6624:
6625: &Apache::lonxml::clear_problem_counter();
6626: &Apache::lonnet::appenv(%$scan_record);
6627:
6628: if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
6629: &scantron_putfile($scanlines,$scan_data);
6630: }
6631:
6632: my $i=0;
6633: foreach my $resource (@resources) {
6634: $i++;
6635: my %form=('submitted' =>'scantron',
6636: 'grade_target' =>'grade',
6637: 'grade_username'=>$uname,
6638: 'grade_domain' =>$udom,
6639: 'grade_courseid'=>$env{'request.course.id'},
6640: 'grade_symb' =>$resource->symb());
6641: if (exists($scan_record->{'scantron.CODE'})
6642: &&
6643: &Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
6644: $form{'CODE'}=$scan_record->{'scantron.CODE'};
6645: } else {
6646: $form{'CODE'}='';
6647: }
6648: my $result=&Apache::lonnet::ssi($resource->src(),%form);
6649: if ($result ne '') {
6650: &Apache::lonnet::logthis("scantron grading error -> $result");
6651: &Apache::lonnet::logthis("scantron grading error info name $uname domain $udom course $env{'request.course.id'} url ".$resource->src());
6652: }
6653: if (&Apache::loncommon::connection_aborted($r)) { last; }
6654: }
6655: $completedstudents{$uname}={'line'=>$line};
6656: if (&Apache::loncommon::connection_aborted($r)) { last; }
6657: } continue {
6658: &Apache::lonxml::clear_problem_counter();
6659: &Apache::lonnet::delenv('scantron\.');
6660: }
6661: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
6662: # my $lasttime = &Time::HiRes::time()-$start;
6663: # $r->print("<p>took $lasttime</p>");
6664:
6665: $r->print("</form>");
6666: $r->print(&show_grading_menu_form($symb));
6667: return '';
6668: }
6669:
6670: =pod
6671:
6672: =item scantron_upload_scantron_data
6673:
6674: Creates the screen for adding a new bubble sheet data file to a course.
6675:
6676: =cut
6677:
6678: sub scantron_upload_scantron_data {
6679: my ($r)=@_;
6680: $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
6681: my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
6682: 'domainid',
6683: 'coursename');
6684: my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
6685: 'domainid');
6686: my $default_form_data=&defaultFormData(&get_symb($r,1));
6687: $r->print(<<UPLOAD);
6688: <script type="text/javascript" language="javascript">
6689: function checkUpload(formname) {
6690: if (formname.upfile.value == "") {
6691: alert("Please use the browse button to select a file from your local directory.");
6692: return false;
6693: }
6694: formname.submit();
6695: }
6696: </script>
6697:
6698: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
6699: $default_form_data
6700: <table>
6701: <tr><td>$select_link </td></tr>
6702: <tr><td>Course ID: </td><td><input name='courseid' type='text' /> </td></tr>
6703: <tr><td>Course Name: </td><td><input name='coursename' type='text' /></td></tr>
6704: <tr><td>Domain: </td><td>$domsel </td></tr>
6705: <tr><td>File to upload:</td><td><input type="file" name="upfile" size="50" /></td></tr>
6706: </table>
6707: <input name='command' value='scantronupload_save' type='hidden' />
6708: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
6709: </form>
6710: UPLOAD
6711: return '';
6712: }
6713:
6714: =pod
6715:
6716: =item scantron_upload_scantron_data_save
6717:
6718: Adds a provided bubble information data file to the course if user
6719: has the correct privileges to do so.
6720:
6721: =cut
6722:
6723: sub scantron_upload_scantron_data_save {
6724: my($r)=@_;
6725: my ($symb)=&get_symb($r,1);
6726: my $doanotherupload=
6727: '<br /><form action="/adm/grades" method="post">'."\n".
6728: '<input type="hidden" name="command" value="scantronupload" />'."\n".
6729: '<input type="submit" name="submit" value="Do Another Upload" />'."\n".
6730: '</form>'."\n";
6731: if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
6732: !&Apache::lonnet::allowed('usc',
6733: $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
6734: $r->print("You are not allowed to upload Scantron data to the requested course.<br />");
6735: if ($symb) {
6736: $r->print(&show_grading_menu_form($symb));
6737: } else {
6738: $r->print($doanotherupload);
6739: }
6740: return '';
6741: }
6742: my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
6743: $r->print("Doing upload to ".$coursedata{'description'}." <br />");
6744: my $fname=$env{'form.upfile.filename'};
6745: #FIXME
6746: #copied from lonnet::userfileupload()
6747: #make that function able to target a specified course
6748: # Replace Windows backslashes by forward slashes
6749: $fname=~s/\\/\//g;
6750: # Get rid of everything but the actual filename
6751: $fname=~s/^.*\/([^\/]+)$/$1/;
6752: # Replace spaces by underscores
6753: $fname=~s/\s+/\_/g;
6754: # Replace all other weird characters by nothing
6755: $fname=~s/[^\w\.\-]//g;
6756: # See if there is anything left
6757: unless ($fname) { return 'error: no uploaded file'; }
6758: my $uploadedfile=$fname;
6759: $fname='scantron_orig_'.$fname;
6760: if (length($env{'form.upfile'}) < 2) {
6761: $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.");
6762: } else {
6763: my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
6764: if ($result =~ m|^/uploaded/|) {
6765: $r->print("<span class=\"LC_success\">Success:</span> Successfully uploaded ".(length($env{'form.upfile'})-1)." bytes of data into location <tt>".$result."</tt>");
6766: } else {
6767: $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>");
6768: }
6769: }
6770: if ($symb) {
6771: $r->print(&scantron_selectphase($r,$uploadedfile));
6772: } else {
6773: $r->print($doanotherupload);
6774: }
6775: return '';
6776: }
6777:
6778: =pod
6779:
6780: =item valid_file
6781:
6782: Validates that the requested bubble data file exists in the course.
6783:
6784: =cut
6785:
6786: sub valid_file {
6787: my ($requested_file)=@_;
6788: foreach my $filename (sort(&scantron_filenames())) {
6789: if ($requested_file eq $filename) { return 1; }
6790: }
6791: return 0;
6792: }
6793:
6794: =pod
6795:
6796: =item scantron_download_scantron_data
6797:
6798: Shows a list of the three internal files (original, corrected,
6799: skipped) for a specific bubble sheet data file that exists in the
6800: course.
6801:
6802: =cut
6803:
6804: sub scantron_download_scantron_data {
6805: my ($r)=@_;
6806: my $default_form_data=&defaultFormData(&get_symb($r,1));
6807: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6808: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6809: my $file=$env{'form.scantron_selectfile'};
6810: if (! &valid_file($file)) {
6811: $r->print(<<ERROR);
6812: <p>
6813: The requested file name was invalid.
6814: </p>
6815: ERROR
6816: $r->print(&show_grading_menu_form(&get_symb($r,1)));
6817: return;
6818: }
6819: my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
6820: my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
6821: my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
6822: &Apache::lonnet::allowuploaded('/adm/grades',$orig);
6823: &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
6824: &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
6825: $r->print(<<DOWNLOAD);
6826: <p>
6827: <a href="$orig">Original</a> file as uploaded by the scantron office.
6828: </p>
6829: <p>
6830: <a href="$corrected">Corrections</a>, a file of corrected records that were used in grading.
6831: </p>
6832: <p>
6833: <a href="$skipped">Skipped</a>, a file of records that were skipped.
6834: </p>
6835: DOWNLOAD
6836: $r->print(&show_grading_menu_form(&get_symb($r,1)));
6837: return '';
6838: }
6839:
6840: =pod
6841:
6842: =back
6843:
6844: =cut
6845:
6846: #-------- end of section for handling grading scantron forms -------
6847: #
6848: #-------------------------------------------------------------------
6849:
6850: #-------------------------- Menu interface -------------------------
6851: #
6852: #--- Show a Grading Menu button - Calls the next routine ---
6853: sub show_grading_menu_form {
6854: my ($symb)=@_;
6855: my $result.='<br /><form action="/adm/grades" method="post">'."\n".
6856: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
6857: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
6858: '<input type="hidden" name="command" value="gradingmenu" />'."\n".
6859: '<input type="submit" name="submit" value="Grading Menu" />'."\n".
6860: '</form>'."\n";
6861: return $result;
6862: }
6863:
6864: # -- Retrieve choices for grading form
6865: sub savedState {
6866: my %savedState = ();
6867: if ($env{'form.saveState'}) {
6868: foreach (split(/:/,$env{'form.saveState'})) {
6869: my ($key,$value) = split(/=/,$_,2);
6870: $savedState{$key} = $value;
6871: }
6872: }
6873: return \%savedState;
6874: }
6875:
6876: #--- Displays the main menu page -------
6877: sub gradingmenu {
6878: my ($request) = @_;
6879: my ($symb)=&get_symb($request);
6880: if (!$symb) {return '';}
6881: my $probTitle = &Apache::lonnet::gettitle($symb);
6882:
6883: $request->print(<<GRADINGMENUJS);
6884: <script type="text/javascript" language="javascript">
6885: function checkChoice(formname,val,cmdx) {
6886: if (val <= 2) {
6887: var cmd = radioSelection(formname.radioChoice);
6888: var cmdsave = cmd;
6889: } else {
6890: cmd = cmdx;
6891: cmdsave = 'submission';
6892: }
6893: formname.command.value = cmd;
6894: formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
6895: ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
6896: if (val < 5) formname.submit();
6897: if (val == 5) {
6898: if (!checkReceiptNo(formname,'notOK')) { return false;}
6899: formname.submit();
6900: }
6901: if (val < 7) formname.submit();
6902: }
6903:
6904: function checkReceiptNo(formname,nospace) {
6905: var receiptNo = formname.receipt.value;
6906: var checkOpt = false;
6907: if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
6908: if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
6909: if (checkOpt) {
6910: alert("Please enter a receipt number given by a student in the receipt box.");
6911: formname.receipt.value = "";
6912: formname.receipt.focus();
6913: return false;
6914: }
6915: return true;
6916: }
6917: </script>
6918: GRADINGMENUJS
6919: &commonJSfunctions($request);
6920: my $result='<h3> <span class="LC_info">Manual Grading/View Submission</span></h3>';
6921: my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
6922: $result.=$table;
6923: my (undef,$sections) = &getclasslist('all','0');
6924: my $savedState = &savedState();
6925: my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
6926: my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
6927: my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
6928: my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
6929:
6930: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
6931: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
6932: '<input type="hidden" name="handgrade" value="'.$hdgrade.'" />'."\n".
6933: '<input type="hidden" name="probTitle" value="'.$probTitle.'" />'."\n".
6934: '<input type="hidden" name="command" value="" />'."\n".
6935: '<input type="hidden" name="saveState" value="" />'."\n".
6936: '<input type="hidden" name="gradingMenu" value="1" />'."\n".
6937: '<input type="hidden" name="showgrading" value="yes" />'."\n";
6938:
6939: $result.='<table width="100%" border="0"><tr><td bgcolor=#777777>'."\n".
6940: '<table width="100%" border="0"><tr bgcolor="#e6ffff"><td colspan="2">'."\n".
6941: ' <b>Select a Grading/Viewing Option</b></td></tr>'."\n".
6942: '<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
6943:
6944: $result.='<table width="100%" border="0">';
6945: $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
6946: ' '.&mt('Select Section').': <select name="section" multiple="multiple" size="3">'."\n";
6947: if (ref($sections)) {
6948: foreach (sort (@$sections)) {
6949: $result.='<option value="'.$_.'" '.
6950: ($saveSec eq $_ ? 'selected="selected"':'').'>'.$_.'</option>'."\n";
6951: }
6952: }
6953: $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> ';
6954:
6955: $result.=&mt('Student Status').':'.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,undef);
6956:
6957: $result.='</td></tr>';
6958:
6959: $result.='<tr bgcolor="#ffffe6"valign="top"><td><label>'.
6960: '<input type="radio" name="radioChoice" value="submission" '.
6961: ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.'<b>'.&mt('Current Resource').':</b> '.&mt('For one or more students').
6962: '</label> <select name="submitonly">'.
6963: '<option value="yes" '.
6964: ($saveSub eq 'yes' ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>'.
6965: '<option value="queued" '.
6966: ($saveSub eq 'queued' ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>'.
6967: '<option value="graded" '.
6968: ($saveSub eq 'graded' ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>'.
6969: '<option value="incorrect" '.
6970: ($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>'.
6971: '<option value="all" '.
6972: ($saveSub eq 'all' ? 'selected="selected"' : '').'>'.&mt('with any status').'</option></select></td></tr>'."\n";
6973:
6974: $result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
6975: '<label><input type="radio" name="radioChoice" value="viewgrades" '.
6976: ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
6977: '<b>Current Resource:</b> For all students in selected section or course</label></td></tr>'."\n";
6978:
6979: $result.='<tr bgcolor="#ffffe6" valign="top"><td>'.
6980: '<label><input type="radio" name="radioChoice" value="pickStudentPage" '.
6981: ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
6982: 'The <b>complete</b> set/page/sequence: For one student</label></td></tr>'."\n";
6983:
6984: $result.='<tr bgcolor="#ffffe6"><td><br />'.
6985: '<input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="Next->" />'.
6986: '</td></tr></table>'."\n";
6987:
6988: $result.='</td><td valign="top">';
6989:
6990: $result.='<table width="100%" border="0">';
6991: $result.='<tr bgcolor="#ffffe6"><td>'.
6992: '<input type="button" onClick="javascript:checkChoice(this.form,\'3\',\'csvform\');" value="'.&mt('Upload').'" />'.
6993: ' '.&mt('scores from file').' </td></tr>'."\n";
6994:
6995: $result.='<tr bgcolor="#ffffe6"><td>'.
6996: '<input type="button" onClick="javascript:checkChoice(this.form,\'6\',\'processclicker\');" value="'.&mt('Process').'" />'.
6997: ' '.&mt('clicker file').' </td></tr>'."\n";
6998:
6999: $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
7000: '<input type="button" onClick="javascript:checkChoice(this.form,\'4\',\'scantron_selectphase\');'.
7001: '" value="'.&mt('Grade').'" /> scantron forms</td></tr>'."\n";
7002:
7003: if ((&Apache::lonnet::allowed('mgr',$env{'request.course.id'})) && ($symb)) {
7004: $result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
7005: '<input type="button" onClick="javascript:checkChoice(this.form,\'5\',\'verify\');" value="'.&mt('Verify').'" />'.
7006: ' '.&mt('receipt').': '.
7007: &Apache::lonnet::recprefix($env{'request.course.id'}).
7008: '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />'.
7009: '</td></tr>'."\n";
7010: }
7011: $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
7012: '<input type="button" onClick="javascript:this.form.action=\'/adm/helper/resettimes.helper\';this.form.submit();'.
7013: '" value="'.&mt('Manage').'" /> access times.</td></tr>'."\n";
7014: $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
7015: '<input type="button" onClick="javascript:this.form.command.value=\'codelist\';this.form.action=\'/adm/pickcode\';this.form.submit();'.
7016: '" value="'.&mt('View').'" /> saved CODEs.</td></tr>'."\n";
7017:
7018: $result.='</table>'."\n".
7019: '</td></tr></table>'."\n".
7020: '</td></tr></table></form>'."\n";
7021: return $result;
7022: }
7023:
7024: sub reset_perm {
7025: undef(%perm);
7026: }
7027:
7028: sub init_perm {
7029: &reset_perm();
7030: foreach my $test_perm ('vgr','mgr','opa') {
7031:
7032: my $scope = $env{'request.course.id'};
7033: if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
7034:
7035: $scope .= '/'.$env{'request.course.sec'};
7036: if ( $perm{$test_perm}=
7037: &Apache::lonnet::allowed($test_perm,$scope)) {
7038: $perm{$test_perm.'_section'}=$env{'request.course.sec'};
7039: } else {
7040: delete($perm{$test_perm});
7041: }
7042: }
7043: }
7044: }
7045:
7046: sub gather_clicker_ids {
7047: my %clicker_ids;
7048:
7049: my $classlist = &Apache::loncoursedata::get_classlist();
7050:
7051: # Set up a couple variables.
7052: my $username_idx = &Apache::loncoursedata::CL_SNAME();
7053: my $domain_idx = &Apache::loncoursedata::CL_SDOM();
7054:
7055: foreach my $student (keys(%$classlist)) {
7056:
7057: my $username = $classlist->{$student}->[$username_idx];
7058: my $domain = $classlist->{$student}->[$domain_idx];
7059: my $clickers =
7060: (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
7061: foreach my $id (split(/\,/,$clickers)) {
7062: $id=~s/^[\#0]+//;
7063: $id=~s/[\-\:]//g;
7064: if (exists($clicker_ids{$id})) {
7065: $clicker_ids{$id}.=','.$username.':'.$domain;
7066: } else {
7067: $clicker_ids{$id}=$username.':'.$domain;
7068: }
7069: }
7070: }
7071: return %clicker_ids;
7072: }
7073:
7074: sub gather_adv_clicker_ids {
7075: my %clicker_ids;
7076: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
7077: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7078: my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
7079: foreach my $element (sort(keys(%coursepersonnel))) {
7080: foreach my $person (split(/\,/,$coursepersonnel{$element})) {
7081: my ($puname,$pudom)=split(/\:/,$person);
7082: my $clickers =
7083: (&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
7084: foreach my $id (split(/\,/,$clickers)) {
7085: $id=~s/^[\#0]+//;
7086: $id=~s/[\-\:]//g;
7087: if (exists($clicker_ids{$id})) {
7088: $clicker_ids{$id}.=','.$puname.':'.$pudom;
7089: } else {
7090: $clicker_ids{$id}=$puname.':'.$pudom;
7091: }
7092: }
7093: }
7094: }
7095: return %clicker_ids;
7096: }
7097:
7098: sub clicker_grading_parameters {
7099: return ('gradingmechanism' => 'scalar',
7100: 'upfiletype' => 'scalar',
7101: 'specificid' => 'scalar',
7102: 'pcorrect' => 'scalar',
7103: 'pincorrect' => 'scalar');
7104: }
7105:
7106: sub process_clicker {
7107: my ($r)=@_;
7108: my ($symb)=&get_symb($r);
7109: if (!$symb) {return '';}
7110: my $result=&checkforfile_js();
7111: $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
7112: my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
7113: $result.=$table;
7114: $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
7115: $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
7116: $result.=' <b>'.&mt('Specify a file containing the clicker information for this resource').
7117: '.</b></td></tr>'."\n";
7118: $result.='<tr bgcolor=#ffffe6><td>'."\n";
7119: # Attempt to restore parameters from last session, set defaults if not present
7120: my %Saveable_Parameters=&clicker_grading_parameters();
7121: &Apache::loncommon::restore_course_settings('grades_clicker',
7122: \%Saveable_Parameters);
7123: if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
7124: if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
7125: if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
7126: if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
7127:
7128: my %checked;
7129: foreach my $gradingmechanism ('attendance','personnel','specific') {
7130: if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
7131: $checked{$gradingmechanism}="checked='checked'";
7132: }
7133: }
7134:
7135: my $upload=&mt("Upload File");
7136: my $type=&mt("Type");
7137: my $attendance=&mt("Award points just for participation");
7138: my $personnel=&mt("Correctness determined from response by course personnel");
7139: my $specific=&mt("Correctness determined from response with clicker ID(s)");
7140: my $pcorrect=&mt("Percentage points for correct solution");
7141: my $pincorrect=&mt("Percentage points for incorrect solution");
7142: my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
7143: ('iclicker' => 'i>clicker',
7144: 'interwrite' => 'interwrite PRS'));
7145: $symb = &Apache::lonenc::check_encrypt($symb);
7146: $result.=<<ENDUPFORM;
7147: <script type="text/javascript">
7148: function sanitycheck() {
7149: // Accept only integer percentages
7150: document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
7151: document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
7152: // Find out grading choice
7153: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
7154: if (document.forms.gradesupload.gradingmechanism[i].checked) {
7155: gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
7156: }
7157: }
7158: // By default, new choice equals user selection
7159: newgradingchoice=gradingchoice;
7160: // Not good to give more points for false answers than correct ones
7161: if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
7162: document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
7163: }
7164: // If new choice is attendance only, and old choice was correctness-based, restore defaults
7165: if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
7166: document.forms.gradesupload.pcorrect.value=100;
7167: document.forms.gradesupload.pincorrect.value=100;
7168: }
7169: // If the values are different, cannot be attendance only
7170: if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
7171: (gradingchoice=='attendance')) {
7172: newgradingchoice='personnel';
7173: }
7174: // Change grading choice to new one
7175: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
7176: if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
7177: document.forms.gradesupload.gradingmechanism[i].checked=true;
7178: } else {
7179: document.forms.gradesupload.gradingmechanism[i].checked=false;
7180: }
7181: }
7182: // Remember the old state
7183: document.forms.gradesupload.waschecked.value=newgradingchoice;
7184: }
7185: </script>
7186: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
7187: <input type="hidden" name="symb" value="$symb" />
7188: <input type="hidden" name="command" value="processclickerfile" />
7189: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
7190: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
7191: <input type="file" name="upfile" size="50" />
7192: <br /><label>$type: $selectform</label>
7193: <br /><label>$attendance: <input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" /></label>
7194: <br /><label>$personnel: <input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" /></label>
7195: <br /><label>$specific: <input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" /></label>
7196: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
7197: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
7198: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
7199: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
7200: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
7201: </form>
7202: ENDUPFORM
7203: $result.='</td></tr></table>'."\n".
7204: '</td></tr></table><br /><br />'."\n";
7205: $result.=&show_grading_menu_form($symb);
7206: return $result;
7207: }
7208:
7209: sub process_clicker_file {
7210: my ($r)=@_;
7211: my ($symb)=&get_symb($r);
7212: if (!$symb) {return '';}
7213:
7214: my %Saveable_Parameters=&clicker_grading_parameters();
7215: &Apache::loncommon::store_course_settings('grades_clicker',
7216: \%Saveable_Parameters);
7217:
7218: my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
7219: if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
7220: $result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
7221: return $result.&show_grading_menu_form($symb);
7222: }
7223: my %clicker_ids=&gather_clicker_ids();
7224: my %correct_ids;
7225: if ($env{'form.gradingmechanism'} eq 'personnel') {
7226: %correct_ids=&gather_adv_clicker_ids();
7227: }
7228: if ($env{'form.gradingmechanism'} eq 'specific') {
7229: foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
7230: $correct_id=~tr/a-z/A-Z/;
7231: $correct_id=~s/\s//gs;
7232: $correct_id=~s/^[\#0]+//;
7233: $correct_id=~s/[\-\:]//g;
7234: if ($correct_id) {
7235: $correct_ids{$correct_id}='specified';
7236: }
7237: }
7238: }
7239: if ($env{'form.gradingmechanism'} eq 'attendance') {
7240: $result.=&mt('Score based on attendance only');
7241: } else {
7242: my $number=0;
7243: $result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
7244: foreach my $id (sort(keys(%correct_ids))) {
7245: $result.='<br /><tt>'.$id.'</tt> - ';
7246: if ($correct_ids{$id} eq 'specified') {
7247: $result.=&mt('specified');
7248: } else {
7249: my ($uname,$udom)=split(/\:/,$correct_ids{$id});
7250: $result.=&Apache::loncommon::plainname($uname,$udom);
7251: }
7252: $number++;
7253: }
7254: $result.="</p>\n";
7255: if ($number==0) {
7256: $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
7257: return $result.&show_grading_menu_form($symb);
7258: }
7259: }
7260: if (length($env{'form.upfile'}) < 2) {
7261: $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
7262: '<span class="LC_error">',
7263: '</span>',
7264: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
7265: return $result.&show_grading_menu_form($symb);
7266: }
7267:
7268: # Were able to get all the info needed, now analyze the file
7269:
7270: $result.=&Apache::loncommon::studentbrowser_javascript();
7271: $symb = &Apache::lonenc::check_encrypt($symb);
7272: my $heading=&mt('Scanning clicker file');
7273: $result.=(<<ENDHEADER);
7274: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
7275: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
7276: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
7277: <form method="post" action="/adm/grades" name="clickeranalysis">
7278: <input type="hidden" name="symb" value="$symb" />
7279: <input type="hidden" name="command" value="assignclickergrades" />
7280: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
7281: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
7282: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
7283: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
7284: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
7285: ENDHEADER
7286: my %responses;
7287: my @questiontitles;
7288: my $errormsg='';
7289: my $number=0;
7290: if ($env{'form.upfiletype'} eq 'iclicker') {
7291: ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
7292: }
7293: if ($env{'form.upfiletype'} eq 'interwrite') {
7294: ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
7295: }
7296: $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
7297: '<input type="hidden" name="number" value="'.$number.'" />'.
7298: &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
7299: $env{'form.pcorrect'},$env{'form.pincorrect'}).
7300: '<br />';
7301: # Remember Question Titles
7302: # FIXME: Possibly need delimiter other than ":"
7303: for (my $i=0;$i<$number;$i++) {
7304: $result.='<input type="hidden" name="question:'.$i.'" value="'.
7305: &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
7306: }
7307: my $correct_count=0;
7308: my $student_count=0;
7309: my $unknown_count=0;
7310: # Match answers with usernames
7311: # FIXME: Possibly need delimiter other than ":"
7312: foreach my $id (keys(%responses)) {
7313: if ($correct_ids{$id}) {
7314: $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
7315: $correct_count++;
7316: } elsif ($clicker_ids{$id}) {
7317: $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
7318: $student_count++;
7319: } else {
7320: $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
7321: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
7322: "\n".&mt("Username").": <input type='text' name='uname".$id."' /> ".
7323: "\n".&mt("Domain").": ".
7324: &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).' '.
7325: &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
7326: $unknown_count++;
7327: }
7328: }
7329: $result.='<hr />'.
7330: &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
7331: if ($env{'form.gradingmechanism'} ne 'attendance') {
7332: if ($correct_count==0) {
7333: $errormsg.="Found no correct answers answers for grading!";
7334: } elsif ($correct_count>1) {
7335: $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
7336: }
7337: }
7338: if ($number<1) {
7339: $errormsg.="Found no questions.";
7340: }
7341: if ($errormsg) {
7342: $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
7343: } else {
7344: $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
7345: }
7346: $result.='</form></td></tr></table>'."\n".
7347: '</td></tr></table><br /><br />'."\n";
7348: return $result.&show_grading_menu_form($symb);
7349: }
7350:
7351: sub iclicker_eval {
7352: my ($questiontitles,$responses)=@_;
7353: my $number=0;
7354: my $errormsg='';
7355: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
7356: my %components=&Apache::loncommon::record_sep($line);
7357: my @entries=map {$components{$_}} (sort(keys(%components)));
7358: if ($entries[0] eq 'Question') {
7359: for (my $i=3;$i<$#entries;$i+=6) {
7360: $$questiontitles[$number]=$entries[$i];
7361: $number++;
7362: }
7363: }
7364: if ($entries[0]=~/^\#/) {
7365: my $id=$entries[0];
7366: my @idresponses;
7367: $id=~s/^[\#0]+//;
7368: for (my $i=0;$i<$number;$i++) {
7369: my $idx=3+$i*6;
7370: push(@idresponses,$entries[$idx]);
7371: }
7372: $$responses{$id}=join(',',@idresponses);
7373: }
7374: }
7375: return ($errormsg,$number);
7376: }
7377:
7378: sub interwrite_eval {
7379: my ($questiontitles,$responses)=@_;
7380: my $number=0;
7381: my $errormsg='';
7382: my $skipline=1;
7383: my $questionnumber=0;
7384: my %idresponses=();
7385: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
7386: my %components=&Apache::loncommon::record_sep($line);
7387: my @entries=map {$components{$_}} (sort(keys(%components)));
7388: if ($entries[1] eq 'Time') { $skipline=0; next; }
7389: if ($entries[1] eq 'Response') { $skipline=1; }
7390: next if $skipline;
7391: if ($entries[0]!=$questionnumber) {
7392: $questionnumber=$entries[0];
7393: $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
7394: $number++;
7395: }
7396: my $id=$entries[4];
7397: $id=~s/^[\#0]+//;
7398: $id=~s/^v\d*\://i;
7399: $id=~s/[\-\:]//g;
7400: $idresponses{$id}[$number]=$entries[6];
7401: }
7402: foreach my $id (keys %idresponses) {
7403: $$responses{$id}=join(',',@{$idresponses{$id}});
7404: $$responses{$id}=~s/^\s*\,//;
7405: }
7406: return ($errormsg,$number);
7407: }
7408:
7409: sub assign_clicker_grades {
7410: my ($r)=@_;
7411: my ($symb)=&get_symb($r);
7412: if (!$symb) {return '';}
7413: # See which part we are saving to
7414: my ($partlist,$handgrade,$responseType) = &response_type($symb);
7415: # FIXME: This should probably look for the first handgradeable part
7416: my $part=$$partlist[0];
7417: # Start screen output
7418: my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
7419:
7420: my $heading=&mt('Assigning grades based on clicker file');
7421: $result.=(<<ENDHEADER);
7422: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
7423: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
7424: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
7425: ENDHEADER
7426: # Get correct result
7427: # FIXME: Possibly need delimiter other than ":"
7428: my @correct=();
7429: my $gradingmechanism=$env{'form.gradingmechanism'};
7430: my $number=$env{'form.number'};
7431: if ($gradingmechanism ne 'attendance') {
7432: foreach my $key (keys(%env)) {
7433: if ($key=~/^form\.correct\:/) {
7434: my @input=split(/\,/,$env{$key});
7435: for (my $i=0;$i<=$#input;$i++) {
7436: if (($correct[$i]) && ($input[$i]) &&
7437: ($correct[$i] ne $input[$i])) {
7438: $result.='<br /><span class="LC_warning">'.
7439: &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
7440: $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
7441: } elsif ($input[$i]) {
7442: $correct[$i]=$input[$i];
7443: }
7444: }
7445: }
7446: }
7447: for (my $i=0;$i<$number;$i++) {
7448: if (!$correct[$i]) {
7449: $result.='<br /><span class="LC_error">'.
7450: &mt('No correct result given for question "[_1]"!',
7451: $env{'form.question:'.$i}).'</span>';
7452: }
7453: }
7454: $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
7455: }
7456: # Start grading
7457: my $pcorrect=$env{'form.pcorrect'};
7458: my $pincorrect=$env{'form.pincorrect'};
7459: my $storecount=0;
7460: foreach my $key (keys(%env)) {
7461: my $user='';
7462: if ($key=~/^form\.student\:(.*)$/) {
7463: $user=$1;
7464: }
7465: if ($key=~/^form\.unknown\:(.*)$/) {
7466: my $id=$1;
7467: if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
7468: $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
7469: }
7470: }
7471: if ($user) {
7472: my @answer=split(/\,/,$env{$key});
7473: my $sum=0;
7474: for (my $i=0;$i<$number;$i++) {
7475: if ($answer[$i]) {
7476: if ($gradingmechanism eq 'attendance') {
7477: $sum+=$pcorrect;
7478: } else {
7479: if ($answer[$i] eq $correct[$i]) {
7480: $sum+=$pcorrect;
7481: } else {
7482: $sum+=$pincorrect;
7483: }
7484: }
7485: }
7486: }
7487: my $ave=$sum/(100*$number);
7488: # Store
7489: my ($username,$domain)=split(/\:/,$user);
7490: my %grades=();
7491: $grades{"resource.$part.solved"}='correct_by_override';
7492: $grades{"resource.$part.awarded"}=$ave;
7493: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
7494: my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
7495: $env{'request.course.id'},
7496: $domain,$username);
7497: if ($returncode ne 'ok') {
7498: $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
7499: } else {
7500: $storecount++;
7501: }
7502: }
7503: }
7504: # We are done
7505: $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
7506: '</td></tr></table>'."\n".
7507: '</td></tr></table><br /><br />'."\n";
7508: return $result.&show_grading_menu_form($symb);
7509: }
7510:
7511: sub handler {
7512: my $request=$_[0];
7513:
7514: &reset_perm();
7515: if ($env{'browser.mathml'}) {
7516: &Apache::loncommon::content_type($request,'text/xml');
7517: } else {
7518: &Apache::loncommon::content_type($request,'text/html');
7519: }
7520: $request->send_http_header;
7521: return '' if $request->header_only;
7522: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
7523: my $symb=&get_symb($request,1);
7524: my @commands=&Apache::loncommon::get_env_multiple('form.command');
7525: my $command=$commands[0];
7526: if ($#commands > 0) {
7527: &Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
7528: }
7529: $request->print(&Apache::loncommon::start_page('Grading'));
7530: if ($symb eq '' && $command eq '') {
7531: if ($env{'user.adv'}) {
7532: if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
7533: ($env{'form.codethree'})) {
7534: my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
7535: $env{'form.codethree'};
7536: my ($tsymb,$tuname,$tudom,$tcrsid)=
7537: &Apache::lonnet::checkin($token);
7538: if ($tsymb) {
7539: my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
7540: if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
7541: $request->print(&Apache::lonnet::ssi_body('/res/'.$url,
7542: ('grade_username' => $tuname,
7543: 'grade_domain' => $tudom,
7544: 'grade_courseid' => $tcrsid,
7545: 'grade_symb' => $tsymb)));
7546: } else {
7547: $request->print('<h3>Not authorized: '.$token.'</h3>');
7548: }
7549: } else {
7550: $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
7551: }
7552: } else {
7553: $request->print(&Apache::lonxml::tokeninputfield());
7554: }
7555: }
7556: } else {
7557: &init_perm();
7558: if ($command eq 'submission' && $perm{'vgr'}) {
7559: ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
7560: } elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
7561: &pickStudentPage($request);
7562: } elsif ($command eq 'displayPage' && $perm{'vgr'}) {
7563: &displayPage($request);
7564: } elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
7565: &updateGradeByPage($request);
7566: } elsif ($command eq 'processGroup' && $perm{'vgr'}) {
7567: &processGroup($request);
7568: } elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
7569: $request->print(&gradingmenu($request));
7570: } elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
7571: $request->print(&viewgrades($request));
7572: } elsif ($command eq 'handgrade' && $perm{'mgr'}) {
7573: $request->print(&processHandGrade($request));
7574: } elsif ($command eq 'editgrades' && $perm{'mgr'}) {
7575: $request->print(&editgrades($request));
7576: } elsif ($command eq 'verify' && $perm{'vgr'}) {
7577: $request->print(&verifyreceipt($request));
7578: } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
7579: $request->print(&process_clicker($request));
7580: } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
7581: $request->print(&process_clicker_file($request));
7582: } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
7583: $request->print(&assign_clicker_grades($request));
7584: } elsif ($command eq 'csvform' && $perm{'mgr'}) {
7585: $request->print(&upcsvScores_form($request));
7586: } elsif ($command eq 'csvupload' && $perm{'mgr'}) {
7587: $request->print(&csvupload($request));
7588: } elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
7589: $request->print(&csvuploadmap($request));
7590: } elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
7591: if ($env{'form.associate'} ne 'Reverse Association') {
7592: $request->print(&csvuploadoptions($request));
7593: } else {
7594: if ( $env{'form.upfile_associate'} ne 'reverse' ) {
7595: $env{'form.upfile_associate'} = 'reverse';
7596: } else {
7597: $env{'form.upfile_associate'} = 'forward';
7598: }
7599: $request->print(&csvuploadmap($request));
7600: }
7601: } elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
7602: $request->print(&csvuploadassign($request));
7603: } elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
7604: $request->print(&scantron_selectphase($request));
7605: } elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
7606: $request->print(&scantron_do_warning($request));
7607: } elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
7608: $request->print(&scantron_validate_file($request));
7609: } elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
7610: $request->print(&scantron_process_students($request));
7611: } elsif ($command eq 'scantronupload' &&
7612: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
7613: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
7614: $request->print(&scantron_upload_scantron_data($request));
7615: } elsif ($command eq 'scantronupload_save' &&
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_save($request));
7619: } elsif ($command eq 'scantron_download' &&
7620: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
7621: $request->print(&scantron_download_scantron_data($request));
7622: } elsif ($command) {
7623: $request->print("Access Denied ($command)");
7624: }
7625: }
7626: $request->print(&Apache::loncommon::end_page());
7627: return '';
7628: }
7629:
7630: 1;
7631:
7632: __END__;
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>