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