1: # The LearningOnline Network with CAPA
2: # The LON-CAPA Grading handler
3: #
4: # $Id: grades.pm,v 1.423 2007/07/24 21:21:31 albertel Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28:
29: package Apache::grades;
30: use strict;
31: use Apache::style;
32: use Apache::lonxml;
33: use Apache::lonnet;
34: use Apache::loncommon;
35: use Apache::lonhtmlcommon;
36: use Apache::lonnavmaps;
37: use Apache::lonhomework;
38: use Apache::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 %oldessays=();
49: my %perm=();
50:
51: # ----- These first few routines are general use routines.----
52: #
53: # --- Retrieve the parts from the metadata file.---
54: sub getpartlist {
55: my ($symb) = @_;
56: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
57: my $partorder = &Apache::lonnet::metadata($url, 'partorder');
58: my @parts;
59: if ($partorder) {
60: for my $part (split (/,/,$partorder)) {
61: if (!&Apache::loncommon::check_if_partid_hidden($part,$symb)) {
62: push(@parts, $part);
63: }
64: }
65: } else {
66: my $metadata = &Apache::lonnet::metadata($url, 'packages');
67: foreach (split(/\,/,$metadata)) {
68: if ($_ =~ /^part_(.*)$/) {
69: if (!&Apache::loncommon::check_if_partid_hidden($1,$symb)) {
70: push(@parts, $1);
71: }
72: }
73: }
74: }
75: my @stores;
76: foreach my $part (@parts) {
77: my (@metakeys) = split(/,/,&Apache::lonnet::metadata($url,'keys'));
78: foreach my $key (@metakeys) {
79: if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
80: }
81: }
82: return @stores;
83: }
84:
85: # --- Get the symbolic name of a problem and the url
86: sub get_symb {
87: my ($request,$silent) = @_;
88: (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
89: my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
90: if ($symb eq '') {
91: if (!$silent) {
92: $request->print("Unable to handle ambiguous references:$url:.");
93: return ();
94: }
95: }
96: &Apache::lonenc::check_decrypt(\$symb);
97: return ($symb);
98: }
99:
100: #--- Format fullname, username:domain if different for display
101: #--- Use anywhere where the student names are listed
102: sub nameUserString {
103: my ($type,$fullname,$uname,$udom) = @_;
104: if ($type eq 'header') {
105: return '<b> Fullname </b><span class="LC_internal_info">(Username)</span>';
106: } else {
107: return ' '.$fullname.'<span class="LC_internal_info"> ('.$uname.
108: ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
109: }
110: }
111:
112: #--- Get the partlist and the response type for a given problem. ---
113: #--- Indicate if a response type is coded handgraded or not. ---
114: sub response_type {
115: my ($symb) = shift;
116:
117: my $navmap = Apache::lonnavmaps::navmap->new();
118: my $res = $navmap->getBySymb($symb);
119: my $partlist = $res->parts();
120: my %vPart =
121: map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
122: my (%response_types,%handgrade);
123: foreach my $part (@{ $partlist }) {
124: next if (%vPart && !exists($vPart{$part}));
125:
126: my @types = $res->responseType($part);
127: my @ids = $res->responseIds($part);
128: for (my $i=0; $i < scalar(@ids); $i++) {
129: $response_types{$part}{$ids[$i]} = $types[$i];
130: $handgrade{$part.'_'.$ids[$i]} =
131: &Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
132: '.handgrade',$symb);
133: }
134: }
135: return ($partlist,\%handgrade,\%response_types);
136: }
137:
138: sub flatten_responseType {
139: my ($responseType) = @_;
140: my @part_response_id =
141: map {
142: my $part = $_;
143: map {
144: [$part,$_]
145: } sort(keys(%{ $responseType->{$part} }));
146: } sort(keys(%$responseType));
147: return @part_response_id;
148: }
149:
150: sub get_display_part {
151: my ($partID,$symb)=@_;
152: my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
153: if (defined($display) and $display ne '') {
154: $display.= " (<span class=\"LC_internal_info\">id $partID</span>)";
155: } else {
156: $display=$partID;
157: }
158: return $display;
159: }
160:
161: #--- Show resource title
162: #--- and parts and response type
163: sub showResourceInfo {
164: my ($symb,$probTitle,$checkboxes) = @_;
165: my $col=3;
166: if ($checkboxes) { $col=4; }
167: my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
168: $result .='<table border="0">';
169: my ($partlist,$handgrade,$responseType) = &response_type($symb);
170: my %resptype = ();
171: my $hdgrade='no';
172: my %partsseen;
173: foreach my $partID (sort keys(%$responseType)) {
174: foreach my $resID (sort keys(%{ $responseType->{$partID} })) {
175: my $handgrade=$$handgrade{$partID.'_'.$resID};
176: my $responsetype = $responseType->{$partID}->{$resID};
177: $hdgrade = $handgrade if ($handgrade eq 'yes');
178: $result.='<tr>';
179: if ($checkboxes) {
180: if (exists($partsseen{$partID})) {
181: $result.="<td> </td>";
182: } else {
183: $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
184: }
185: $partsseen{$partID}=1;
186: }
187: my $display_part=&get_display_part($partID,$symb);
188: $result.='<td><b>Part: </b>'.$display_part.' <span class="LC_internal_info">'.
189: $resID.'</span></td>'.
190: '<td><b>Type: </b>'.$responsetype.'</td></tr>';
191: # '<td><b>Handgrade: </b>'.$handgrade.'</td></tr>';
192: }
193: }
194: $result.='</table>'."\n";
195: return $result,$responseType,$hdgrade,$partlist,$handgrade;
196: }
197:
198:
199: sub get_order {
200: my ($partid,$respid,$symb,$uname,$udom)=@_;
201: my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
202: $url=&Apache::lonnet::clutter($url);
203: my $subresult=&Apache::lonnet::ssi($url,
204: ('grade_target' => 'analyze'),
205: ('grade_domain' => $udom),
206: ('grade_symb' => $symb),
207: ('grade_courseid' =>
208: $env{'request.course.id'}),
209: ('grade_username' => $uname));
210: (undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
211: my %analyze=&Apache::lonnet::str2hash($subresult);
212: return ($analyze{"$partid.$respid.shown"});
213: }
214: #--- Clean response type for display
215: #--- Currently filters option/rank/radiobutton/match/essay/Task
216: # response types only.
217: sub cleanRecord {
218: my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
219: $uname,$udom) = @_;
220: my $grayFont = '<span class="LC_internal_info">';
221: if ($response =~ /^(option|rank)$/) {
222: my %answer=&Apache::lonnet::str2hash($answer);
223: my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
224: my ($toprow,$bottomrow);
225: foreach my $foil (@$order) {
226: if ($grading{$foil} == 1) {
227: $toprow.='<td><b>'.$answer{$foil}.' </b></td>';
228: } else {
229: $toprow.='<td><i>'.$answer{$foil}.' </i></td>';
230: }
231: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
232: }
233: return '<blockquote><table border="1">'.
234: '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
235: '<tr valign="top"><td>'.$grayFont.'Option ID</span></td>'.
236: $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
237: } elsif ($response eq 'match') {
238: my %answer=&Apache::lonnet::str2hash($answer);
239: my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
240: my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
241: my ($toprow,$middlerow,$bottomrow);
242: foreach my $foil (@$order) {
243: my $item=shift(@items);
244: if ($grading{$foil} == 1) {
245: $toprow.='<td><b>'.$item.' </b></td>';
246: $middlerow.='<td><b>'.$grayFont.$answer{$foil}.' </span></b></td>';
247: } else {
248: $toprow.='<td><i>'.$item.' </i></td>';
249: $middlerow.='<td><i>'.$grayFont.$answer{$foil}.' </span></i></td>';
250: }
251: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
252: }
253: return '<blockquote><table border="1">'.
254: '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
255: '<tr valign="top"><td>'.$grayFont.'Item ID</span></td>'.
256: $middlerow.'</tr>'.
257: '<tr valign="top"><td>'.$grayFont.'Option ID</span></td>'.
258: $bottomrow.'</tr>'.'</table></blockquote>';
259: } elsif ($response eq 'radiobutton') {
260: my %answer=&Apache::lonnet::str2hash($answer);
261: my ($toprow,$bottomrow);
262: my $correct=($order->[0])+1;
263: for (my $i=1;$i<=$#$order;$i++) {
264: my $foil=$order->[$i];
265: if (exists($answer{$foil})) {
266: if ($i == $correct) {
267: $toprow.='<td><b>true</b></td>';
268: } else {
269: $toprow.='<td><i>true</i></td>';
270: }
271: } else {
272: $toprow.='<td>false</td>';
273: }
274: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
275: }
276: return '<blockquote><table border="1">'.
277: '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
278: '<tr valign="top"><td>'.$grayFont.'Option ID</span></td>'.
279: $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
280: } elsif ($response eq 'essay') {
281: if (! exists ($env{'form.'.$symb})) {
282: my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
283: $env{'course.'.$env{'request.course.id'}.'.domain'},
284: $env{'course.'.$env{'request.course.id'}.'.num'});
285:
286: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
287: $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
288: $env{'form.kwclr'} = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
289: $env{'form.kwsize'} = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
290: $env{'form.kwstyle'} = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
291: $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
292: }
293: $answer =~ s-\n-<br />-g;
294: return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
295: } elsif ( $response eq 'organic') {
296: my $result='Smile representation: "<tt>'.$answer.'</tt>"';
297: my $jme=$record->{$version."resource.$partid.$respid.molecule"};
298: $result.=&Apache::chemresponse::jme_img($jme,$answer,400);
299: return $result;
300: } elsif ( $response eq 'Task') {
301: if ( $answer eq 'SUBMITTED') {
302: my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
303: my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
304: return $result;
305: } elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
306: my @matches = grep(/^\Q$version\E.*?\.instance$/,
307: keys(%{$record}));
308: return join('<br />',($version,@matches));
309:
310:
311: } else {
312: my $result =
313: '<p>'
314: .&mt('Overall result: [_1]',
315: $record->{$version."resource.$respid.$partid.status"})
316: .'</p>';
317:
318: $result .= '<ul>';
319: my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
320: keys(%{$record}));
321: foreach my $grade (sort(@grade)) {
322: my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
323: $result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
324: $dim, $record->{$grade}).
325: '</li>';
326: }
327: $result.='</ul>';
328: return $result;
329: }
330:
331: }
332: return $answer;
333: }
334:
335: #-- A couple of common js functions
336: sub commonJSfunctions {
337: my $request = shift;
338: $request->print(<<COMMONJSFUNCTIONS);
339: <script type="text/javascript" language="javascript">
340: function radioSelection(radioButton) {
341: var selection=null;
342: if (radioButton.length > 1) {
343: for (var i=0; i<radioButton.length; i++) {
344: if (radioButton[i].checked) {
345: return radioButton[i].value;
346: }
347: }
348: } else {
349: if (radioButton.checked) return radioButton.value;
350: }
351: return selection;
352: }
353:
354: function pullDownSelection(selectOne) {
355: var selection="";
356: if (selectOne.length > 1) {
357: for (var i=0; i<selectOne.length; i++) {
358: if (selectOne[i].selected) {
359: return selectOne[i].value;
360: }
361: }
362: } else {
363: // only one value it must be the selected one
364: return selectOne.value;
365: }
366: }
367: </script>
368: COMMONJSFUNCTIONS
369: }
370:
371: #--- Dumps the class list with usernames,list of sections,
372: #--- section, ids and fullnames for each user.
373: sub getclasslist {
374: my ($getsec,$filterlist) = @_;
375: my @getsec;
376: if (!ref($getsec)) {
377: if ($getsec ne '' && $getsec ne 'all') {
378: @getsec=($getsec);
379: }
380: } else {
381: @getsec=@{$getsec};
382: }
383: if (grep(/^all$/,@getsec)) { undef(@getsec); }
384:
385: my $classlist=&Apache::loncoursedata::get_classlist();
386: # Bail out if we were unable to get the classlist
387: return if (! defined($classlist));
388: #
389: my %sections;
390: my %fullnames;
391: foreach my $student (keys(%$classlist)) {
392: my $end =
393: $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
394: my $start =
395: $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
396: my $id =
397: $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
398: my $section =
399: $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
400: my $fullname =
401: $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
402: my $status =
403: $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
404: # filter students according to status selected
405: if ($filterlist && $env{'form.Status'} ne 'Any') {
406: if ($env{'form.Status'} ne $status) {
407: delete ($classlist->{$student});
408: next;
409: }
410: }
411: $section = ($section ne '' ? $section : 'none');
412: if (&canview($section)) {
413: if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
414: $sections{$section}++;
415: $fullnames{$student}=$fullname;
416: } else {
417: delete($classlist->{$student});
418: }
419: } else {
420: delete($classlist->{$student});
421: }
422: }
423: my %seen = ();
424: my @sections = sort(keys(%sections));
425: return ($classlist,\@sections,\%fullnames);
426: }
427:
428: sub canmodify {
429: my ($sec)=@_;
430: if ($perm{'mgr'}) {
431: if (!defined($perm{'mgr_section'})) {
432: # can modify whole class
433: return 1;
434: } else {
435: if ($sec eq $perm{'mgr_section'}) {
436: #can modify the requested section
437: return 1;
438: } else {
439: # can't modify the request section
440: return 0;
441: }
442: }
443: }
444: #can't modify
445: return 0;
446: }
447:
448: sub canview {
449: my ($sec)=@_;
450: if ($perm{'vgr'}) {
451: if (!defined($perm{'vgr_section'})) {
452: # can modify whole class
453: return 1;
454: } else {
455: if ($sec eq $perm{'vgr_section'}) {
456: #can modify the requested section
457: return 1;
458: } else {
459: # can't modify the request section
460: return 0;
461: }
462: }
463: }
464: #can't modify
465: return 0;
466: }
467:
468: #--- Retrieve the grade status of a student for all the parts
469: sub student_gradeStatus {
470: my ($symb,$udom,$uname,$partlist) = @_;
471: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
472: my %partstatus = ();
473: foreach (@$partlist) {
474: my ($status,undef) = split(/_/,$record{"resource.$_.solved"},2);
475: $status = 'nothing' if ($status eq '');
476: $partstatus{$_} = $status;
477: my $subkey = "resource.$_.submitted_by";
478: $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
479: }
480: return %partstatus;
481: }
482:
483: # hidden form and javascript that calls the form
484: # Use by verifyscript and viewgrades
485: # Shows a student's view of problem and submission
486: sub jscriptNform {
487: my ($symb) = @_;
488: my $jscript='<script type="text/javascript" language="javascript">'."\n".
489: ' function viewOneStudent(user,domain) {'."\n".
490: ' document.onestudent.student.value = user;'."\n".
491: ' document.onestudent.userdom.value = domain;'."\n".
492: ' document.onestudent.submit();'."\n".
493: ' }'."\n".
494: '</script>'."\n";
495: $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
496: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
497: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
498: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
499: '<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n".
500: '<input type="hidden" name="command" value="submission" />'."\n".
501: '<input type="hidden" name="student" value="" />'."\n".
502: '<input type="hidden" name="userdom" value="" />'."\n".
503: '</form>'."\n";
504: return $jscript;
505: }
506:
507: # Given the score (as a number [0-1] and the weight) what is the final
508: # point value? This function will round to the nearest tenth, third,
509: # or quarter if one of those is within the tolerance of .00001.
510: sub compute_points {
511: my ($score, $weight) = @_;
512:
513: my $tolerance = .00001;
514: my $points = $score * $weight;
515:
516: # Check for nearness to 1/x.
517: my $check_for_nearness = sub {
518: my ($factor) = @_;
519: my $num = ($points * $factor) + $tolerance;
520: my $floored_num = floor($num);
521: if ($num - $floored_num < 2 * $tolerance * $factor) {
522: return $floored_num / $factor;
523: }
524: return $points;
525: };
526:
527: $points = $check_for_nearness->(10);
528: $points = $check_for_nearness->(3);
529: $points = $check_for_nearness->(4);
530:
531: return $points;
532: }
533:
534: #------------------ End of general use routines --------------------
535:
536: #
537: # Find most similar essay
538: #
539:
540: sub most_similar {
541: my ($uname,$udom,$uessay)=@_;
542:
543: # ignore spaces and punctuation
544:
545: $uessay=~s/\W+/ /gs;
546:
547: # ignore empty submissions (occuring when only files are sent)
548:
549: unless ($uessay=~/\w+/) { return ''; }
550:
551: # these will be returned. Do not care if not at least 50 percent similar
552: my $limit=0.6;
553: my $sname='';
554: my $sdom='';
555: my $scrsid='';
556: my $sessay='';
557: # go through all essays ...
558: foreach my $tkey (keys %oldessays) {
559: my ($tname,$tdom,$tcrsid)=split(/\./,$tkey);
560: # ... except the same student
561: if (($tname ne $uname) || ($tdom ne $udom)) {
562: my $tessay=$oldessays{$tkey};
563: $tessay=~s/\W+/ /gs;
564: # String similarity gives up if not even limit
565: my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
566: # Found one
567: if ($tsimilar>$limit) {
568: $limit=$tsimilar;
569: $sname=$tname;
570: $sdom=$tdom;
571: $scrsid=$tcrsid;
572: $sessay=$oldessays{$tkey};
573: }
574: }
575: }
576: if ($limit>0.6) {
577: return ($sname,$sdom,$scrsid,$sessay,$limit);
578: } else {
579: return ('','','','',0);
580: }
581: }
582:
583: #-------------------------------------------------------------------
584:
585: #------------------------------------ Receipt Verification Routines
586: #
587: #--- Check whether a receipt number is valid.---
588: sub verifyreceipt {
589: my $request = shift;
590:
591: my $courseid = $env{'request.course.id'};
592: my $receipt = &Apache::lonnet::recprefix($courseid).'-'.
593: $env{'form.receipt'};
594: $receipt =~ s/[^\-\d]//g;
595: my ($symb) = &get_symb($request);
596:
597: my $title.='<h3><span class="LC_info">Verifying Submission Receipt '.
598: $receipt.'</h3></span>'."\n".
599: '<h4><b>Resource: </b>'.$env{'form.probTitle'}.'</h4><br /><br />'."\n";
600:
601: my ($string,$contents,$matches) = ('','',0);
602: my (undef,undef,$fullname) = &getclasslist('all','0');
603:
604: my $receiptparts=0;
605: if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
606: $env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
607: my $parts=['0'];
608: if ($receiptparts) { ($parts)=&response_type($symb); }
609: foreach (sort
610: {
611: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
612: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
613: }
614: return $a cmp $b;
615: } (keys(%$fullname))) {
616: my ($uname,$udom)=split(/\:/);
617: foreach my $part (@$parts) {
618: if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
619: $contents.='<tr bgcolor="#ffffe6"><td> '."\n".
620: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
621: '\');" target="_self">'.$$fullname{$_}.'</a> </td>'."\n".
622: '<td> '.$uname.' </td>'.
623: '<td> '.$udom.' </td>';
624: if ($receiptparts) {
625: $contents.='<td> '.$part.' </td>';
626: }
627: $contents.='</tr>'."\n";
628:
629: $matches++;
630: }
631: }
632: }
633: if ($matches == 0) {
634: $string = $title.'No match found for the above receipt.';
635: } else {
636: $string = &jscriptNform($symb).$title.
637: 'The above receipt matches the following student'.
638: ($matches <= 1 ? '.' : 's.')."\n".
639: '<table border="0"><tr><td bgcolor="#777777">'."\n".
640: '<table border="0"><tr bgcolor="#e6ffff">'."\n".
641: '<td><b> Fullname </b></td>'."\n".
642: '<td><b> Username </b></td>'."\n".
643: '<td><b> Domain </b></td>';
644: if ($receiptparts) {
645: $string.='<td> Problem Part </td>';
646: }
647: $string.='</tr>'."\n".$contents.
648: '</table></td></tr></table>'."\n";
649: }
650: return $string.&show_grading_menu_form($symb);
651: }
652:
653: #--- This is called by a number of programs.
654: #--- Called from the Grading Menu - View/Grade an individual student
655: #--- Also called directly when one clicks on the subm button
656: # on the problem page.
657: sub listStudents {
658: my ($request) = shift;
659:
660: my ($symb) = &get_symb($request);
661: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
662: my $cnum = $env{"course.$env{'request.course.id'}.num"};
663: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
664: my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
665:
666: my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
667: $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ?
668: &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
669:
670: my $result='<h3><span class="LC_info"> '.$viewgrade.
671: ' Submissions for a Student or a Group of Students</span></h3>';
672:
673: my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
674:
675: $request->print(<<LISTJAVASCRIPT);
676: <script type="text/javascript" language="javascript">
677: function checkSelect(checkBox) {
678: var ctr=0;
679: var sense="";
680: if (checkBox.length > 1) {
681: for (var i=0; i<checkBox.length; i++) {
682: if (checkBox[i].checked) {
683: ctr++;
684: }
685: }
686: sense = "a student or group of students";
687: } else {
688: if (checkBox.checked) {
689: ctr = 1;
690: }
691: sense = "the student";
692: }
693: if (ctr == 0) {
694: alert("Please select "+sense+" before clicking on the Next button.");
695: return false;
696: }
697: document.gradesub.submit();
698: }
699:
700: function reLoadList(formname) {
701: if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
702: formname.command.value = 'submission';
703: formname.submit();
704: }
705: </script>
706: LISTJAVASCRIPT
707:
708: &commonJSfunctions($request);
709: $request->print($result);
710:
711: my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
712: my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
713: my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
714: "\n".$table.
715: ' <b>View Problem Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
716: '<label><input type="radio" name="vProb" value="yes" /> one student </label>'."\n".
717: '<label><input type="radio" name="vProb" value="all" /> all students </label><br />'."\n".
718: ' <b>View Answer: </b><label><input type="radio" name="vAns" value="no" /> no </label>'."\n".
719: '<label><input type="radio" name="vAns" value="yes" /> one student </label>'."\n".
720: '<label><input type="radio" name="vAns" value="all" checked="checked" /> all students </label><br />'."\n".
721: ' <b>Submissions: </b>'."\n";
722: if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
723: $gradeTable.='<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> essay part only </label>'."\n";
724: }
725:
726: my $saveStatus = $env{'form.Status'} eq '' ? 'Active' : $env{'form.Status'};
727: $env{'form.Status'} = $saveStatus;
728:
729: $gradeTable.='<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> last submission only </label>'."\n".
730: '<label><input type="radio" name="lastSub" value="last" /> last submission & parts info </label>'."\n".
731: '<label><input type="radio" name="lastSub" value="datesub" /> by dates and submissions </label>'."\n".
732: '<label><input type="radio" name="lastSub" value="all" /> all details</label><br />'."\n".
733: ' <b>Grading Increments:</b> <select name="increment">'.
734: '<option value="1">Whole Points</option>'.
735: '<option value=".5">Half Points</option>'.
736: '<option value=".25">Quarter Points</option>'.
737: '<option value=".1">Tenths of a Point</option>'.
738: '</select>'.
739:
740: '<input type="hidden" name="section" value="'.$getsec.'" />'."\n".
741: '<input type="hidden" name="submitonly" value="'.$submitonly.'" />'."\n".
742: '<input type="hidden" name="handgrade" value="'.$env{'form.handgrade'}.'" /><br />'."\n".
743: '<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
744: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
745: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
746: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
747: '<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
748:
749: if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
750: $gradeTable.='<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n";
751: } else {
752: $gradeTable.='<b>Student Status:</b> '.
753: &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);').'<br />';
754: }
755:
756: $gradeTable.='To '.lc($viewgrade).' a submission or a group of submissions, click on the check box(es) '.
757: 'next to the student\'s name(s). Then click on the Next button.<br />'."\n".
758: '<input type="hidden" name="command" value="processGroup" />'."\n";
759:
760: # checkall buttons
761: $gradeTable.=&check_script('gradesub', 'stuinfo');
762: $gradeTable.='<input type="button" '."\n".
763: 'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
764: 'value="Next->" /> <br />'."\n";
765: $gradeTable.=&check_buttons();
766: $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />Check For Plagiarism</label>';
767: my ($classlist, undef, $fullname) = &getclasslist($getsec,'1');
768: $gradeTable.='<table border="0"><tr><td bgcolor="#777777">'.
769: '<table border="0"><tr bgcolor="#e6ffff">';
770: my $loop = 0;
771: while ($loop < 2) {
772: $gradeTable.='<td><b> No.</b> </td><td><b> Select </b></td>'.
773: '<td>'.&nameUserString('header').' Section/Group</td>';
774: if ($env{'form.showgrading'} eq 'yes'
775: && $submitonly ne 'queued'
776: && $submitonly ne 'all') {
777: foreach (sort(@$partlist)) {
778: my $display_part=&get_display_part((split(/_/))[0],$symb);
779: $gradeTable.='<td><b> Part: '.$display_part.
780: ' Status </b></td>';
781: }
782: } elsif ($submitonly eq 'queued') {
783: $gradeTable.='<td><b> '.&mt('Queue Status').' </b></td>';
784: }
785: $loop++;
786: # $gradeTable.='<td></td>' if ($loop%2 ==1);
787: }
788: $gradeTable.='</tr>'."\n";
789:
790: my $ctr = 0;
791: foreach my $student (sort
792: {
793: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
794: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
795: }
796: return $a cmp $b;
797: }
798: (keys(%$fullname))) {
799: my ($uname,$udom) = split(/:/,$student);
800:
801: my %status = ();
802:
803: if ($submitonly eq 'queued') {
804: my %queue_status =
805: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
806: $udom,$uname);
807: next if (!defined($queue_status{'gradingqueue'}));
808: $status{'gradingqueue'} = $queue_status{'gradingqueue'};
809: }
810:
811: if ($env{'form.showgrading'} eq 'yes'
812: && $submitonly ne 'queued'
813: && $submitonly ne 'all') {
814: (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
815: my $submitted = 0;
816: my $graded = 0;
817: my $incorrect = 0;
818: foreach (keys(%status)) {
819: $submitted = 1 if ($status{$_} ne 'nothing');
820: $graded = 1 if ($status{$_} =~ /^ungraded/);
821: $incorrect = 1 if ($status{$_} =~ /^incorrect/);
822:
823: my ($foo,$partid,$foo1) = split(/\./,$_);
824: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
825: $submitted = 0;
826: my ($part)=split(/\./,$partid);
827: $gradeTable.='<input type="hidden" name="'.
828: $student.':'.$part.':submitted_by" value="'.
829: $status{'resource.'.$partid.'.submitted_by'}.'" />';
830: }
831: }
832:
833: next if (!$submitted && ($submitonly eq 'yes' ||
834: $submitonly eq 'incorrect' ||
835: $submitonly eq 'graded'));
836: next if (!$graded && ($submitonly eq 'graded'));
837: next if (!$incorrect && $submitonly eq 'incorrect');
838: }
839:
840: $ctr++;
841: my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
842:
843: if ( $perm{'vgr'} eq 'F' ) {
844: $gradeTable.='<tr bgcolor="#ffffe6">' if ($ctr%2 ==1);
845: $gradeTable.='<td align="right">'.$ctr.' </td>'.
846: '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
847: $student.':'.$$fullname{$student}.':::SECTION'.$section.
848: ') " /> </label></td>'."\n".'<td>'.
849: &nameUserString(undef,$$fullname{$student},$uname,$udom).
850: ' '.$section.'</td>'."\n";
851:
852: if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
853: foreach (sort keys(%status)) {
854: next if (/^resource.*?submitted_by$/);
855: $gradeTable.='<td align="center"> '.$status{$_}.' </td>'."\n";
856: }
857: }
858: # $gradeTable.='<td></td>' if ($ctr%2 ==1);
859: $gradeTable.='</tr>'."\n" if ($ctr%2 ==0);
860: }
861: }
862: if ($ctr%2 ==1) {
863: $gradeTable.='<td> </td><td> </td><td> </td>';
864: if ($env{'form.showgrading'} eq 'yes'
865: && $submitonly ne 'queued'
866: && $submitonly ne 'all') {
867: foreach (@$partlist) {
868: $gradeTable.='<td> </td>';
869: }
870: } elsif ($submitonly eq 'queued') {
871: $gradeTable.='<td> </td>';
872: }
873: $gradeTable.='</tr>';
874: }
875:
876: $gradeTable.='</table></td></tr></table>'."\n".
877: '<input type="button" '.
878: 'onClick="javascript:checkSelect(this.form.stuinfo);" '.
879: 'value="Next->" /></form>'."\n";
880: if ($ctr == 0) {
881: my $num_students=(scalar(keys(%$fullname)));
882: if ($num_students eq 0) {
883: $gradeTable='<br /> <span class="LC_warning">There are no students currently enrolled.</span>';
884: } else {
885: my $submissions='submissions';
886: if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
887: if ($submitonly eq 'graded' ) { $submissions = 'ungraded submissions'; }
888: if ($submitonly eq 'queued' ) { $submissions = 'queued submissions'; }
889: $gradeTable='<br /> <span class="LC_warning">'.
890: 'No '.$submissions.' found for this resource for any students. ('.$num_students.
891: ' students checked for '.$submissions.')</span><br />';
892: }
893: } elsif ($ctr == 1) {
894: $gradeTable =~ s/type=checkbox/type=checkbox checked/;
895: }
896: $gradeTable.=&show_grading_menu_form($symb);
897: $request->print($gradeTable);
898: return '';
899: }
900:
901: #---- Called from the listStudents routine
902:
903: sub check_script {
904: my ($form, $type)=@_;
905: my $chkallscript='<script type="text/javascript">
906: function checkall() {
907: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
908: ele = document.forms.'.$form.'.elements[i];
909: if (ele.name == "'.$type.'") {
910: document.forms.'.$form.'.elements[i].checked=true;
911: }
912: }
913: }
914:
915: function checksec() {
916: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
917: ele = document.forms.'.$form.'.elements[i];
918: string = document.forms.'.$form.'.chksec.value;
919: if
920: (ele.value.indexOf(":::SECTION"+string)>0) {
921: document.forms.'.$form.'.elements[i].checked=true;
922: }
923: }
924: }
925:
926:
927: function uncheckall() {
928: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
929: ele = document.forms.'.$form.'.elements[i];
930: if (ele.name == "'.$type.'") {
931: document.forms.'.$form.'.elements[i].checked=false;
932: }
933: }
934: }
935:
936: </script>'."\n";
937: return $chkallscript;
938: }
939:
940: sub check_buttons {
941: my $buttons.='<input type="button" onclick="checkall()" value="Check All" />';
942: $buttons.='<input type="button" onclick="uncheckall()" value="Uncheck All" /> ';
943: $buttons.='<input type="button" onclick="checksec()" value="Check Section/Group" />';
944: $buttons.='<input type="text" size="5" name="chksec" /> ';
945: return $buttons;
946: }
947:
948: # Displays the submissions for one student or a group of students
949: sub processGroup {
950: my ($request) = shift;
951: my $ctr = 0;
952: my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
953: my $total = scalar(@stuchecked)-1;
954:
955: foreach my $student (@stuchecked) {
956: my ($uname,$udom,$fullname) = split(/:/,$student);
957: $env{'form.student'} = $uname;
958: $env{'form.userdom'} = $udom;
959: $env{'form.fullname'} = $fullname;
960: &submission($request,$ctr,$total);
961: $ctr++;
962: }
963: return '';
964: }
965:
966: #------------------------------------------------------------------------------------
967: #
968: #-------------------------- Next few routines handles grading by student, essentially
969: # handles essay response type problem/part
970: #
971: #--- Javascript to handle the submission page functionality ---
972: sub sub_page_js {
973: my $request = shift;
974: $request->print(<<SUBJAVASCRIPT);
975: <script type="text/javascript" language="javascript">
976: function updateRadio(formname,id,weight) {
977: var gradeBox = formname["GD_BOX"+id];
978: var radioButton = formname["RADVAL"+id];
979: var oldpts = formname["oldpts"+id].value;
980: var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
981: gradeBox.value = pts;
982: var resetbox = false;
983: if (isNaN(pts) || pts < 0) {
984: alert("A number equal or greater than 0 is expected. Entered value = "+pts);
985: for (var i=0; i<radioButton.length; i++) {
986: if (radioButton[i].checked) {
987: gradeBox.value = i;
988: resetbox = true;
989: }
990: }
991: if (!resetbox) {
992: formtextbox.value = "";
993: }
994: return;
995: }
996:
997: if (pts > weight) {
998: var resp = confirm("You entered a value ("+pts+
999: ") greater than the weight for the part. Accept?");
1000: if (resp == false) {
1001: gradeBox.value = oldpts;
1002: return;
1003: }
1004: }
1005:
1006: for (var i=0; i<radioButton.length; i++) {
1007: radioButton[i].checked=false;
1008: if (pts == i && pts != "") {
1009: radioButton[i].checked=true;
1010: }
1011: }
1012: updateSelect(formname,id);
1013: formname["stores"+id].value = "0";
1014: }
1015:
1016: function writeBox(formname,id,pts) {
1017: var gradeBox = formname["GD_BOX"+id];
1018: if (checkSolved(formname,id) == 'update') {
1019: gradeBox.value = pts;
1020: } else {
1021: var oldpts = formname["oldpts"+id].value;
1022: gradeBox.value = oldpts;
1023: var radioButton = formname["RADVAL"+id];
1024: for (var i=0; i<radioButton.length; i++) {
1025: radioButton[i].checked=false;
1026: if (i == oldpts) {
1027: radioButton[i].checked=true;
1028: }
1029: }
1030: }
1031: formname["stores"+id].value = "0";
1032: updateSelect(formname,id);
1033: return;
1034: }
1035:
1036: function clearRadBox(formname,id) {
1037: if (checkSolved(formname,id) == 'noupdate') {
1038: updateSelect(formname,id);
1039: return;
1040: }
1041: gradeSelect = formname["GD_SEL"+id];
1042: for (var i=0; i<gradeSelect.length; i++) {
1043: if (gradeSelect[i].selected) {
1044: var selectx=i;
1045: }
1046: }
1047: var stores = formname["stores"+id];
1048: if (selectx == stores.value) { return };
1049: var gradeBox = formname["GD_BOX"+id];
1050: gradeBox.value = "";
1051: var radioButton = formname["RADVAL"+id];
1052: for (var i=0; i<radioButton.length; i++) {
1053: radioButton[i].checked=false;
1054: }
1055: stores.value = selectx;
1056: }
1057:
1058: function checkSolved(formname,id) {
1059: if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1060: var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
1061: if (!reply) {return "noupdate";}
1062: formname.overRideScore.value = 'yes';
1063: }
1064: return "update";
1065: }
1066:
1067: function updateSelect(formname,id) {
1068: formname["GD_SEL"+id][0].selected = true;
1069: return;
1070: }
1071:
1072: //=========== Check that a point is assigned for all the parts ============
1073: function checksubmit(formname,val,total,parttot) {
1074: formname.gradeOpt.value = val;
1075: if (val == "Save & Next") {
1076: for (i=0;i<=total;i++) {
1077: for (j=0;j<parttot;j++) {
1078: var partid = formname["partid"+i+"_"+j].value;
1079: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1080: var points = formname["GD_BOX"+i+"_"+partid].value;
1081: if (points == "") {
1082: var name = formname["name"+i].value;
1083: var studentID = (name != '' ? name : formname["unamedom"+i].value);
1084: var resp = confirm("You did not assign a score for "+studentID+
1085: ", part "+partid+". Continue?");
1086: if (resp == false) {
1087: formname["GD_BOX"+i+"_"+partid].focus();
1088: return false;
1089: }
1090: }
1091: }
1092:
1093: }
1094: }
1095:
1096: }
1097: if (val == "Grade Student") {
1098: formname.showgrading.value = "yes";
1099: if (formname.Status.value == "") {
1100: formname.Status.value = "Active";
1101: }
1102: formname.studentNo.value = total;
1103: }
1104: formname.submit();
1105: }
1106:
1107: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
1108: function checkSubmitPage(formname,total) {
1109: noscore = new Array(100);
1110: var ptr = 0;
1111: for (i=1;i<total;i++) {
1112: var partid = formname["q_"+i].value;
1113: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1114: var points = formname["GD_BOX"+i+"_"+partid].value;
1115: var status = formname["solved"+i+"_"+partid].value;
1116: if (points == "" && status != "correct_by_student") {
1117: noscore[ptr] = i;
1118: ptr++;
1119: }
1120: }
1121: }
1122: if (ptr != 0) {
1123: var sense = ptr == 1 ? ": " : "s: ";
1124: var prolist = "";
1125: if (ptr == 1) {
1126: prolist = noscore[0];
1127: } else {
1128: var i = 0;
1129: while (i < ptr-1) {
1130: prolist += noscore[i]+", ";
1131: i++;
1132: }
1133: prolist += "and "+noscore[i];
1134: }
1135: var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
1136: if (resp == false) {
1137: return false;
1138: }
1139: }
1140:
1141: formname.submit();
1142: }
1143: </script>
1144: SUBJAVASCRIPT
1145: }
1146:
1147: #--- javascript for essay type problem --
1148: sub sub_page_kw_js {
1149: my $request = shift;
1150: my $iconpath = $request->dir_config('lonIconsURL');
1151: &commonJSfunctions($request);
1152:
1153: my $inner_js_msg_central=<<INNERJS;
1154: <script text="text/javascript">
1155: function checkInput() {
1156: opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
1157: var nmsg = opener.document.SCORE.savemsgN.value;
1158: var usrctr = document.msgcenter.usrctr.value;
1159: var newval = opener.document.SCORE["newmsg"+usrctr];
1160: newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
1161:
1162: var msgchk = "";
1163: if (document.msgcenter.subchk.checked) {
1164: msgchk = "msgsub,";
1165: }
1166: var includemsg = 0;
1167: for (var i=1; i<=nmsg; i++) {
1168: var opnmsg = opener.document.SCORE["savemsg"+i];
1169: var frmmsg = document.msgcenter["msg"+i];
1170: opnmsg.value = opener.checkEntities(frmmsg.value);
1171: var showflg = opener.document.SCORE["shownOnce"+i];
1172: showflg.value = "1";
1173: var chkbox = document.msgcenter["msgn"+i];
1174: if (chkbox.checked) {
1175: msgchk += "savemsg"+i+",";
1176: includemsg = 1;
1177: }
1178: }
1179: if (document.msgcenter.newmsgchk.checked) {
1180: msgchk += "newmsg"+usrctr;
1181: includemsg = 1;
1182: }
1183: imgformname = opener.document.SCORE["mailicon"+usrctr];
1184: imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
1185: var includemsg = opener.document.SCORE["includemsg"+usrctr];
1186: includemsg.value = msgchk;
1187:
1188: self.close()
1189:
1190: }
1191: </script>
1192: INNERJS
1193:
1194: my $inner_js_highlight_central=<<INNERJS;
1195: <script type="text/javascript">
1196: function updateChoice(flag) {
1197: opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
1198: opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
1199: opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
1200: opener.document.SCORE.refresh.value = "on";
1201: if (opener.document.SCORE.keywords.value!=""){
1202: opener.document.SCORE.submit();
1203: }
1204: self.close()
1205: }
1206: </script>
1207: INNERJS
1208:
1209: my $start_page_msg_central =
1210: &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
1211: {'js_ready' => 1,
1212: 'only_body' => 1,
1213: 'bgcolor' =>'#FFFFFF',});
1214: my $end_page_msg_central =
1215: &Apache::loncommon::end_page({'js_ready' => 1});
1216:
1217:
1218: my $start_page_highlight_central =
1219: &Apache::loncommon::start_page('Highlight Central',
1220: $inner_js_highlight_central,
1221: {'js_ready' => 1,
1222: 'only_body' => 1,
1223: 'bgcolor' =>'#FFFFFF',});
1224: my $end_page_highlight_central =
1225: &Apache::loncommon::end_page({'js_ready' => 1});
1226:
1227: my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1228: $docopen=~s/^document\.//;
1229: $request->print(<<SUBJAVASCRIPT);
1230: <script type="text/javascript" language="javascript">
1231:
1232: //===================== Show list of keywords ====================
1233: function keywords(formname) {
1234: var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1235: if (nret==null) return;
1236: formname.keywords.value = nret;
1237:
1238: if (formname.keywords.value != "") {
1239: formname.refresh.value = "on";
1240: formname.submit();
1241: }
1242: return;
1243: }
1244:
1245: //===================== Script to view submitted by ==================
1246: function viewSubmitter(submitter) {
1247: document.SCORE.refresh.value = "on";
1248: document.SCORE.NCT.value = "1";
1249: document.SCORE.unamedom0.value = submitter;
1250: document.SCORE.submit();
1251: return;
1252: }
1253:
1254: //===================== Script to add keyword(s) ==================
1255: function getSel() {
1256: if (document.getSelection) txt = document.getSelection();
1257: else if (document.selection) txt = document.selection.createRange().text;
1258: else return;
1259: var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
1260: if (cleantxt=="") {
1261: alert("Please select a word or group of words from document and then click this link.");
1262: return;
1263: }
1264: var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
1265: if (nret==null) return;
1266: document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1267: if (document.SCORE.keywords.value != "") {
1268: document.SCORE.refresh.value = "on";
1269: document.SCORE.submit();
1270: }
1271: return;
1272: }
1273:
1274: //====================== Script for composing message ==============
1275: // preload images
1276: img1 = new Image();
1277: img1.src = "$iconpath/mailbkgrd.gif";
1278: img2 = new Image();
1279: img2.src = "$iconpath/mailto.gif";
1280:
1281: function msgCenter(msgform,usrctr,fullname) {
1282: var Nmsg = msgform.savemsgN.value;
1283: savedMsgHeader(Nmsg,usrctr,fullname);
1284: var subject = msgform.msgsub.value;
1285: var msgchk = document.SCORE["includemsg"+usrctr].value;
1286: re = /msgsub/;
1287: var shwsel = "";
1288: if (re.test(msgchk)) { shwsel = "checked" }
1289: subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
1290: displaySubject(checkEntities(subject),shwsel);
1291: for (var i=1; i<=Nmsg; i++) {
1292: var testmsg = "savemsg"+i+",";
1293: re = new RegExp(testmsg,"g");
1294: shwsel = "";
1295: if (re.test(msgchk)) { shwsel = "checked" }
1296: var message = document.SCORE["savemsg"+i].value;
1297: message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1298: displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
1299: //any < is already converted to <, etc. However, only once!!
1300: }
1301: newmsg = document.SCORE["newmsg"+usrctr].value;
1302: shwsel = "";
1303: re = /newmsg/;
1304: if (re.test(msgchk)) { shwsel = "checked" }
1305: newMsg(newmsg,shwsel);
1306: msgTail();
1307: return;
1308: }
1309:
1310: function checkEntities(strx) {
1311: if (strx.length == 0) return strx;
1312: var orgStr = ["&", "<", ">", '"'];
1313: var newStr = ["&", "<", ">", """];
1314: var counter = 0;
1315: while (counter < 4) {
1316: strx = strReplace(strx,orgStr[counter],newStr[counter]);
1317: counter++;
1318: }
1319: return strx;
1320: }
1321:
1322: function strReplace(strx, orgStr, newStr) {
1323: return strx.split(orgStr).join(newStr);
1324: }
1325:
1326: function savedMsgHeader(Nmsg,usrctr,fullname) {
1327: var height = 70*Nmsg+250;
1328: var scrollbar = "no";
1329: if (height > 600) {
1330: height = 600;
1331: scrollbar = "yes";
1332: }
1333: var xpos = (screen.width-600)/2;
1334: xpos = (xpos < 0) ? '0' : xpos;
1335: var ypos = (screen.height-height)/2-30;
1336: ypos = (ypos < 0) ? '0' : ypos;
1337:
1338: pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1339: pWin.focus();
1340: pDoc = pWin.document;
1341: pDoc.$docopen;
1342: pDoc.write('$start_page_msg_central');
1343:
1344: pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
1345: pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1346: pDoc.write("<h3><span class=\\"LC_info\\"> Compose Message for \"+fullname+\"</span></h3><br /><br />");
1347:
1348: pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
1349: pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
1350: pDoc.write("<td><b>Type</b></td><td><b>Include</b></td><td><b>Message</td></tr>");
1351: }
1352: function displaySubject(msg,shwsel) {
1353: pDoc = pWin.document;
1354: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1355: pDoc.write("<td>Subject</td>");
1356: pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
1357: pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"></td></tr>");
1358: }
1359:
1360: function displaySavedMsg(ctr,msg,shwsel) {
1361: pDoc = pWin.document;
1362: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1363: pDoc.write("<td align=\\"center\\">"+ctr+"</td>");
1364: pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"></td>");
1365: pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"</textarea></td></tr>");
1366: }
1367:
1368: function newMsg(newmsg,shwsel) {
1369: pDoc = pWin.document;
1370: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1371: pDoc.write("<td align=\\"center\\">New</td>");
1372: pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
1373: pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"</textarea></td></tr>");
1374: }
1375:
1376: function msgTail() {
1377: pDoc = pWin.document;
1378: pDoc.write("</table>");
1379: pDoc.write("</td></tr></table> ");
1380: pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\"> ");
1381: pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1382: pDoc.write("</form>");
1383: pDoc.write('$end_page_msg_central');
1384: pDoc.close();
1385: }
1386:
1387: //====================== Script for keyword highlight options ==============
1388: function kwhighlight() {
1389: var kwclr = document.SCORE.kwclr.value;
1390: var kwsize = document.SCORE.kwsize.value;
1391: var kwstyle = document.SCORE.kwstyle.value;
1392: var redsel = "";
1393: var grnsel = "";
1394: var blusel = "";
1395: if (kwclr=="red") {var redsel="checked"};
1396: if (kwclr=="green") {var grnsel="checked"};
1397: if (kwclr=="blue") {var blusel="checked"};
1398: var sznsel = "";
1399: var sz1sel = "";
1400: var sz2sel = "";
1401: if (kwsize=="0") {var sznsel="checked"};
1402: if (kwsize=="+1") {var sz1sel="checked"};
1403: if (kwsize=="+2") {var sz2sel="checked"};
1404: var synsel = "";
1405: var syisel = "";
1406: var sybsel = "";
1407: if (kwstyle=="") {var synsel="checked"};
1408: if (kwstyle=="<i>") {var syisel="checked"};
1409: if (kwstyle=="<b>") {var sybsel="checked"};
1410: highlightCentral();
1411: highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
1412: highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
1413: highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
1414: highlightend();
1415: return;
1416: }
1417:
1418: function highlightCentral() {
1419: // if (window.hwdWin) window.hwdWin.close();
1420: var xpos = (screen.width-400)/2;
1421: xpos = (xpos < 0) ? '0' : xpos;
1422: var ypos = (screen.height-330)/2-30;
1423: ypos = (ypos < 0) ? '0' : ypos;
1424:
1425: hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1426: hwdWin.focus();
1427: var hDoc = hwdWin.document;
1428: hDoc.$docopen;
1429: hDoc.write('$start_page_highlight_central');
1430: hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1431: hDoc.write("<h3><span class=\\"LC_info\\"> Keyword Highlight Options</span></h3><br /><br />");
1432:
1433: hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
1434: hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
1435: hDoc.write("<td><b>Text Color</b></td><td><b>Font Size</b></td><td><b>Font Style</td></tr>");
1436: }
1437:
1438: function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) {
1439: var hDoc = hwdWin.document;
1440: hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1441: hDoc.write("<td align=\\"left\\">");
1442: hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+"> "+clrtxt+"</td>");
1443: hDoc.write("<td align=\\"left\\">");
1444: hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+"> "+sztxt+"</td>");
1445: hDoc.write("<td align=\\"left\\">");
1446: hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+"> "+sytxt+"</td>");
1447: hDoc.write("</tr>");
1448: }
1449:
1450: function highlightend() {
1451: var hDoc = hwdWin.document;
1452: hDoc.write("</table>");
1453: hDoc.write("</td></tr></table> ");
1454: hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\"> ");
1455: hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1456: hDoc.write("</form>");
1457: hDoc.write('$end_page_highlight_central');
1458: hDoc.close();
1459: }
1460:
1461: </script>
1462: SUBJAVASCRIPT
1463: }
1464:
1465: sub get_increment {
1466: my $increment = $env{'form.increment'};
1467: if ($increment != 1 && $increment != .5 && $increment != .25 &&
1468: $increment != .1) {
1469: $increment = 1;
1470: }
1471: return $increment;
1472: }
1473:
1474: #--- displays the grading box, used in essay type problem and grading by page/sequence
1475: sub gradeBox {
1476: my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1477: my $checkIcon = '<img alt="'.&mt('Check Mark').
1478: '" src="'.$request->dir_config('lonIconsURL').
1479: '/check.gif" height="16" border="0" />';
1480: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1481: my $wgtmsg = ($wgt > 0 ? '(problem weight)' :
1482: '<span class="LC_info">problem weight assigned by computer</span>');
1483: $wgt = ($wgt > 0 ? $wgt : '1');
1484: my $score = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1485: '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1486: my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1487: my $display_part=&get_display_part($partid,$symb);
1488: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
1489: [$partid]);
1490: my $aggtries = $$record{'resource.'.$partid.'.tries'};
1491: if ($last_resets{$partid}) {
1492: $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
1493: }
1494: $result.='<table border="0"><tr><td>'.
1495: '<b>Part: </b>'.$display_part.' <b>Points: </b></td><td>'."\n";
1496: my $ctr = 0;
1497: my $thisweight = 0;
1498: my $increment = &get_increment();
1499: $result.='<table border="0"><tr>'."\n"; # display radio buttons in a nice table 10 across
1500: while ($thisweight<=$wgt) {
1501: $result.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1502: 'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1503: $thisweight.')" value="'.$thisweight.'" '.
1504: ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1505: $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1506: $thisweight += $increment;
1507: $ctr++;
1508: }
1509: $result.='</tr></table>';
1510: $result.='</td><td> <b>or</b> </td>'."\n";
1511: $result.='<td><input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1512: ($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1513: 'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1514: $wgt.')" /></td>'."\n";
1515: $result.='<td>/'.$wgt.' '.$wgtmsg.
1516: ($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? ' '.$checkIcon : '').
1517: ' </td><td>'."\n";
1518: $result.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
1519: 'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1520: if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1521: $result.='<option></option>'.
1522: '<option selected="selected">excused</option>';
1523: } else {
1524: $result.='<option selected="selected"></option>'.
1525: '<option>excused</option>';
1526: }
1527: $result.='<option>reset status</option></select>'."\n";
1528: $result.=" \n";
1529: $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
1530: '<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
1531: '<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1532: $$record{'resource.'.$partid.'.solved'}.'" />'."\n".
1533: '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
1534: $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
1535: '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
1536: $aggtries.'" />'."\n";
1537: $result.='</td></tr></table>'."\n";
1538: $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
1539: return $result;
1540: }
1541:
1542: sub handback_box {
1543: my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
1544: my ($partlist,$handgrade,$responseType) = &response_type($symb);
1545: my (@respids);
1546: my @part_response_id = &flatten_responseType($responseType);
1547: foreach my $part_response_id (@part_response_id) {
1548: my ($part,$resp) = @{ $part_response_id };
1549: if ($part eq $partid) {
1550: push(@respids,$resp);
1551: }
1552: }
1553: my $result;
1554: foreach my $respid (@respids) {
1555: my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
1556: my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
1557: next if (!@$files);
1558: my $file_counter = 1;
1559: foreach my $file (@$files) {
1560: if ($file =~ /\/portfolio\//) {
1561: my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1562: my ($name,$version,$ext) = &file_name_version_ext($file_disp);
1563: $file_disp = "$name.$ext";
1564: $file = $file_path.$file_disp;
1565: $result.=&mt('Return commented version of [_1] to student.',
1566: '<span class="LC_filename">'.$file_disp.'</span>');
1567: $result.='<input type="file" name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1568: $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1569: $result.='(File will be uploaded when you click on Save & Next below.)<br />';
1570: $file_counter++;
1571: }
1572: }
1573: }
1574: return $result;
1575: }
1576:
1577: sub show_problem {
1578: my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1579: my $rendered;
1580: my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1581: &Apache::lonxml::remember_problem_counter();
1582: if ($mode eq 'both' or $mode eq 'text') {
1583: $rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1584: $env{'request.course.id'},
1585: undef,\%form);
1586: }
1587: if ($removeform) {
1588: $rendered=~s|<form(.*?)>||g;
1589: $rendered=~s|</form>||g;
1590: $rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1591: }
1592: my $companswer;
1593: if ($mode eq 'both' or $mode eq 'answer') {
1594: &Apache::lonxml::restore_problem_counter();
1595: $companswer=
1596: &Apache::loncommon::get_student_answers($symb,$uname,$udom,
1597: $env{'request.course.id'},
1598: %form);
1599: }
1600: if ($removeform) {
1601: $companswer=~s|<form(.*?)>||g;
1602: $companswer=~s|</form>||g;
1603: $companswer=~s|name="submit"|name="would_have_been_submit"|g;
1604: }
1605: my $result.='<table border="0" width="100%"><tr><td bgcolor="#777777">';
1606: $result.='<table border="0" width="100%">';
1607: if ($viewon) {
1608: $result.='<tr><td bgcolor="#e6ffff"><b> ';
1609: if ($mode eq 'both' or $mode eq 'text') {
1610: $result.='View of the problem - ';
1611: } else {
1612: $result.='Correct answer: ';
1613: }
1614: $result.=$env{'form.fullname'}.'</b></td></tr>';
1615: }
1616: if ($mode eq 'both') {
1617: $result.='<tr><td bgcolor="#ffffff">'.$rendered.'<br />';
1618: $result.='<b>Correct answer:</b><br />'.$companswer;
1619: } elsif ($mode eq 'text') {
1620: $result.='<tr><td bgcolor="#ffffff">'.$rendered;
1621: } elsif ($mode eq 'answer') {
1622: $result.='<tr><td bgcolor="#ffffff">'.$companswer;
1623: }
1624: $result.='</td></tr></table>';
1625: $result.='</td></tr></table><br />';
1626: return $result;
1627: }
1628:
1629: sub files_exist {
1630: my ($r, $symb) = @_;
1631: my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1632:
1633: foreach my $student (@students) {
1634: my ($uname,$udom,$fullname) = split(/:/,$student);
1635: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
1636: $udom,$uname);
1637: my ($string,$timestamp)= &get_last_submission(\%record);
1638: foreach my $submission (@$string) {
1639: my ($partid,$respid) =
1640: ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1641: my $files=&get_submitted_files($udom,$uname,$partid,$respid,
1642: \%record);
1643: return 1 if (@$files);
1644: }
1645: }
1646: return 0;
1647: }
1648:
1649: sub download_all_link {
1650: my ($r,$symb) = @_;
1651: my $all_students =
1652: join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
1653:
1654: my $parts =
1655: join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
1656:
1657: my $identifier = &Apache::loncommon::get_cgi_id();
1658: &Apache::lonnet::appenv('cgi.'.$identifier.'.students' => $all_students,
1659: 'cgi.'.$identifier.'.symb' => $symb,
1660: 'cgi.'.$identifier.'.parts' => $parts,);
1661: $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
1662: &mt('Download All Submitted Documents').'</a>');
1663: return
1664: }
1665:
1666: # --------------------------- show submissions of a student, option to grade
1667: sub submission {
1668: my ($request,$counter,$total) = @_;
1669:
1670: my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
1671: $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
1672: my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
1673: $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1674:
1675: my $symb = &get_symb($request);
1676: if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1677:
1678: if (!&canview($usec)) {
1679: $request->print('<span class="LC_warning">Unable to view requested student.('.
1680: $uname.':'.$udom.' in section '.$usec.' in course id '.
1681: $env{'request.course.id'}.')</span>');
1682: $request->print(&show_grading_menu_form($symb));
1683: return;
1684: }
1685:
1686: if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
1687: if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
1688: if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
1689: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1690: my $checkIcon = '<img alt="'.&mt('Check Mark').
1691: '" src="'.$request->dir_config('lonIconsURL').
1692: '/check.gif" height="16" border="0" />';
1693:
1694: # header info
1695: if ($counter == 0) {
1696: &sub_page_js($request);
1697: &sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
1698: $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ?
1699: &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1700: if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1701: &download_all_link($request, $symb);
1702: }
1703: $request->print('<h3> <span class="LC_info">Submission Record</span></h3>'."\n".
1704: '<h4> <b>Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n");
1705:
1706: if ($env{'form.handgrade'} eq 'no') {
1707: my $checkMark='<br /><br /> <b>Note:</b> Part(s) graded correct by the computer is marked with a '.
1708: $checkIcon.' symbol.'."\n";
1709: $request->print($checkMark);
1710: }
1711:
1712: # option to display problem, only once else it cause problems
1713: # with the form later since the problem has a form.
1714: if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1715: my $mode;
1716: if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1717: $mode='both';
1718: } elsif ($env{'form.vProb'} eq 'yes') {
1719: $mode='text';
1720: } elsif ($env{'form.vAns'} eq 'yes') {
1721: $mode='answer';
1722: }
1723: &Apache::lonxml::clear_problem_counter();
1724: $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1725: }
1726:
1727: # kwclr is the only variable that is guaranteed to be non blank
1728: # if this subroutine has been called once.
1729: my %keyhash = ();
1730: if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1731: %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1732: $env{'course.'.$env{'request.course.id'}.'.domain'},
1733: $env{'course.'.$env{'request.course.id'}.'.num'});
1734:
1735: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1736: $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
1737: $env{'form.kwclr'} = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
1738: $env{'form.kwsize'} = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
1739: $env{'form.kwstyle'} = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
1740: $env{'form.msgsub'} = $keyhash{$symb.'_subject'} ne '' ?
1741: $keyhash{$symb.'_subject'} : $env{'form.probTitle'};
1742: $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1743: }
1744: my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1745:
1746: $request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1747: '<input type="hidden" name="command" value="handgrade" />'."\n".
1748: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1749: '<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n".
1750: '<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1751: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
1752: '<input type="hidden" name="refresh" value="off" />'."\n".
1753: '<input type="hidden" name="studentNo" value="" />'."\n".
1754: '<input type="hidden" name="gradeOpt" value="" />'."\n".
1755: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1756: '<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
1757: '<input type="hidden" name="vProb" value="'.$env{'form.vProb'}.'" />'."\n".
1758: '<input type="hidden" name="vAns" value="'.$env{'form.vAns'}.'" />'."\n".
1759: '<input type="hidden" name="lastSub" value="'.$env{'form.lastSub'}.'" />'."\n".
1760: '<input type="hidden" name="section" value="'.$env{'form.section'}.'" />'."\n".
1761: '<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1762: '<input type="hidden" name="handgrade" value="'.$env{'form.handgrade'}.'" />'."\n".
1763: '<input type="hidden" name="NCT"'.
1764: ' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1765: if ($env{'form.handgrade'} eq 'yes') {
1766: $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
1767: '<input type="hidden" name="kwclr" value="'.$env{'form.kwclr'}.'" />'."\n".
1768: '<input type="hidden" name="kwsize" value="'.$env{'form.kwsize'}.'" />'."\n".
1769: '<input type="hidden" name="kwstyle" value="'.$env{'form.kwstyle'}.'" />'."\n".
1770: '<input type="hidden" name="msgsub" value="'.$env{'form.msgsub'}.'" />'."\n".
1771: '<input type="hidden" name="shownSub" value="0" />'."\n".
1772: '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1773: foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
1774: $request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
1775: }
1776: }
1777:
1778: my ($cts,$prnmsg) = (1,'');
1779: while ($cts <= $env{'form.savemsgN'}) {
1780: $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1781: (!exists($keyhash{$symb.'_savemsg'.$cts}) ?
1782: &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1783: &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1784: '" />'."\n".
1785: '<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1786: $cts++;
1787: }
1788: $request->print($prnmsg);
1789:
1790: if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1791: #
1792: # Print out the keyword options line
1793: #
1794: $request->print(<<KEYWORDS);
1795: <b>Keyword Options:</b>
1796: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>
1797: <a href="#" onMouseDown="javascript:getSel(); return false"
1798: CLASS="page">Paste Selection to List</a>
1799: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1800: KEYWORDS
1801: #
1802: # Load the other essays for similarity check
1803: #
1804: my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1805: my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1806: $apath=&escape($apath);
1807: $apath=~s/\W/\_/gs;
1808: %oldessays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1809: }
1810: }
1811:
1812: if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1813: $request->print('<br /><br /><br />') if ($counter > 0);
1814: my $mode;
1815: if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1816: $mode='both';
1817: } elsif ($env{'form.vProb'} eq 'all' ) {
1818: $mode='text';
1819: } elsif ($env{'form.vAns'} eq 'all') {
1820: $mode='answer';
1821: }
1822: &Apache::lonxml::clear_problem_counter();
1823: $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode));
1824: }
1825:
1826: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1827: my ($partlist,$handgrade,$responseType) = &response_type($symb);
1828:
1829: # Display student info
1830: $request->print(($counter == 0 ? '' : '<br />'));
1831: my $result='<table border="0" width="100%"><tr><td bgcolor="#777777">'."\n".
1832: '<table border="0" width="100%"><tr bgcolor="#edffff"><td>'."\n";
1833:
1834: $result.='<b>Fullname: </b>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'<br />'."\n";
1835: $result.='<input type="hidden" name="name'.$counter.
1836: '" value="'.$env{'form.fullname'}.'" />'."\n";
1837:
1838: # If any part of the problem is an essay-response (handgraded), then check for collaborators
1839: my @col_fullnames;
1840: my ($classlist,$fullname);
1841: if ($env{'form.handgrade'} eq 'yes') {
1842: ($classlist,undef,$fullname) = &getclasslist('all','0');
1843: for (keys (%$handgrade)) {
1844: my $ncol = &Apache::lonnet::EXT('resource.'.$_.
1845: '.maxcollaborators',
1846: $symb,$udom,$uname);
1847: next if ($ncol <= 0);
1848: s/\_/\./g;
1849: next if ($record{'resource.'.$_.'.collaborators'} eq '');
1850: my @goodcollaborators = ();
1851: my @badcollaborators = ();
1852: foreach (split(/,?\s+/,$record{'resource.'.$_.'.collaborators'})) {
1853: $_ =~ s/[\$\^\(\)]//g;
1854: next if ($_ eq '');
1855: my ($co_name,$co_dom) = split /\@|:/,$_;
1856: $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
1857: next if ($co_name eq $uname && $co_dom eq $udom);
1858: # Doing this grep allows 'fuzzy' specification
1859: my @Matches = grep /^$co_name:$co_dom$/i,keys %$classlist;
1860: if (! scalar(@Matches)) {
1861: push @badcollaborators,$_;
1862: } else {
1863: push @goodcollaborators, @Matches;
1864: }
1865: }
1866: if (scalar(@goodcollaborators) != 0) {
1867: $result.='<b>Collaborators: </b>';
1868: foreach (@goodcollaborators) {
1869: my ($lastname,$givenn) = split(/,/,$$fullname{$_});
1870: push @col_fullnames, $givenn.' '.$lastname;
1871: $result.=$$fullname{$_}.' ';
1872: }
1873: $result.='<br />'."\n";
1874: my ($part)=split(/\./,$_);
1875: $result.='<input type="hidden" name="collaborator'.$counter.
1876: '" value="'.$part.':'.(join ':',@goodcollaborators).'" />'.
1877: "\n";
1878: }
1879: if (scalar(@badcollaborators) > 0) {
1880: $result.='<table border="0"><tr bgcolor="#ffbbbb"><td>';
1881: $result.='This student has submitted ';
1882: $result.=(scalar(@badcollaborators) == 1) ? 'an invalid collaborator' : 'invalid collaborators';
1883: $result .= ': '.join(', ',@badcollaborators);
1884: $result .= '</td></tr></table>';
1885: }
1886: if (scalar(@badcollaborators > $ncol)) {
1887: $result .= '<table border="0"><tr bgcolor="#ffbbbb"><td>';
1888: $result .= 'This student has submitted too many '.
1889: 'collaborators. Maximum is '.$ncol.'.';
1890: $result .= '</td></tr></table>';
1891: }
1892: }
1893: }
1894: $request->print($result."\n");
1895:
1896: # print student answer/submission
1897: # Options are (1) Handgaded submission only
1898: # (2) Last submission, includes submission that is not handgraded
1899: # (for multi-response type part)
1900: # (3) Last submission plus the parts info
1901: # (4) The whole record for this student
1902: if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1903: my ($string,$timestamp)= &get_last_submission(\%record);
1904: my $lastsubonly=''.
1905: ($$timestamp eq '' ? '' : '<b>Date Submitted:</b> '.
1906: $$timestamp)."</td></tr>\n";
1907: if ($$timestamp eq '') {
1908: $lastsubonly.='<tr><td bgcolor="#ffffe6">'.$$string[0];
1909: } else {
1910: my %seenparts;
1911: my @part_response_id = &flatten_responseType($responseType);
1912: foreach my $part (@part_response_id) {
1913: next if ($env{'form.lastSub'} eq 'hdgrade'
1914: && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
1915:
1916: my ($partid,$respid) = @{ $part };
1917: my $display_part=&get_display_part($partid,$symb);
1918: if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1919: if (exists($seenparts{$partid})) { next; }
1920: $seenparts{$partid}=1;
1921: my $submitby='<b>Part:</b> '.$display_part.
1922: ' <b>Collaborative submission by:</b> '.
1923: '<a href="javascript:viewSubmitter(\''.
1924: $env{"form.$uname:$udom:$partid:submitted_by"}.
1925: '\');" target="_self">'.
1926: $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1927: $request->print($submitby);
1928: next;
1929: }
1930: my $responsetype = $responseType->{$partid}->{$respid};
1931: if (!exists($record{"resource.$partid.$respid.submission"})) {
1932: $lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
1933: $display_part.' <span class="LC_internal_info">( ID '.$respid.
1934: ' )</span> '.
1935: '<span class="LC_warning">Nothing submitted - no attempts</span><br /><br />';
1936: next;
1937: }
1938: foreach (@$string) {
1939: my ($partid,$respid) = /^resource\.([^\.]*)\.([^\.]*)\.submission/;
1940: if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1941: my ($ressub,$subval) = split(/:/,$_,2);
1942: # Similarity check
1943: my $similar='';
1944: if($env{'form.checkPlag'}){
1945: my ($oname,$odom,$ocrsid,$oessay,$osim)=
1946: &most_similar($uname,$udom,$subval);
1947: if ($osim) {
1948: $osim=int($osim*100.0);
1949: $similar="<hr /><h3><span class=\"LC_warning\">Essay".
1950: " is $osim% similar to an essay by ".
1951: &Apache::loncommon::plainname($oname,$odom).
1952: '</span></h3><blockquote><i>'.
1953: &keywords_highlight($oessay).
1954: '</i></blockquote><hr />';
1955: }
1956: }
1957: my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1958: if ($env{'form.lastSub'} eq 'lastonly' ||
1959: ($env{'form.lastSub'} eq 'hdgrade' &&
1960: $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1961: my $display_part=&get_display_part($partid,$symb);
1962: $lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
1963: $display_part.' <span class="LC_internal_info">( ID '.$respid.
1964: ' )</span> ';
1965: my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
1966: if (@$files) {
1967: $lastsubonly.='<br /><span class="LC_warning">Like all files provided by users, this file may contain virusses</span><br />';
1968: my $file_counter = 0;
1969: foreach my $file (@$files) {
1970: $file_counter ++;
1971: &Apache::lonnet::allowuploaded('/adm/grades',$file);
1972: $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
1973: }
1974: $lastsubonly.='<br />';
1975: }
1976: $lastsubonly.='<b>Submitted Answer: </b>'.
1977: &cleanRecord($subval,$responsetype,$symb,$partid,
1978: $respid,\%record,$order);
1979: if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1980: }
1981: }
1982: }
1983: }
1984: $lastsubonly.='</td></tr><tr bgcolor="#ffffff"><td>'."\n";
1985: $request->print($lastsubonly);
1986: } elsif ($env{'form.lastSub'} eq 'datesub') {
1987: my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
1988: $request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1989: } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1990: $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1991: $env{'request.course.id'},
1992: $last,'.submission',
1993: 'Apache::grades::keywords_highlight'));
1994: }
1995:
1996: $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
1997: .$udom.'" />'."\n");
1998:
1999: # return if view submission with no grading option
2000: if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
2001: my $toGrade.='<input type="button" value="Grade Student" '.
2002: 'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
2003: .$counter.'\');" target="_self" /> '."\n" if (&canmodify($usec));
2004: $toGrade.='</td></tr></table></td></tr></table>'."\n";
2005: if (($env{'form.command'} eq 'submission') ||
2006: ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
2007: $toGrade.='</form>'.&show_grading_menu_form($symb);
2008: }
2009: $request->print($toGrade);
2010: return;
2011: } else {
2012: $request->print('</td></tr></table></td></tr></table>'."\n");
2013: }
2014:
2015: # essay grading message center
2016: if ($env{'form.handgrade'} eq 'yes') {
2017: my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
2018: my $msgfor = $givenn.' '.$lastname;
2019: if (scalar(@col_fullnames) > 0) {
2020: my $lastone = pop @col_fullnames;
2021: $msgfor .= ', '.(join ', ',@col_fullnames).' and '.$lastone.'.';
2022: }
2023: $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
2024: $result='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
2025: '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
2026: $result.=' <a href="javascript:msgCenter(document.SCORE,'.$counter.
2027: ',\''.$msgfor.'\');" target="_self">'.
2028: &mt('Compose message to student').(scalar(@col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
2029: &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
2030: '<img src="'.$request->dir_config('lonIconsURL').
2031: '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
2032: '<br /> ('.
2033: &mt('Message will be sent when you click on Save & Next below.').")\n";
2034: $request->print($result);
2035: }
2036: if ($perm{'vgr'}) {
2037: $request->print('<br />'.
2038: &Apache::loncommon::track_student_link(&mt('View recent activity'),
2039: $uname,$udom,'check'));
2040: }
2041: if ($perm{'opa'}) {
2042: $request->print('<br />'.
2043: &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
2044: $uname,$udom,$symb,'check'));
2045: }
2046:
2047: my %seen = ();
2048: my @partlist;
2049: my @gradePartRespid;
2050: my @part_response_id = &flatten_responseType($responseType);
2051: foreach my $part_response_id (@part_response_id) {
2052: my ($partid,$respid) = @{ $part_response_id };
2053: my $part_resp = join('_',@{ $part_response_id });
2054: next if ($seen{$partid} > 0);
2055: $seen{$partid}++;
2056: next if ($$handgrade{$part_resp} ne 'yes'
2057: && $env{'form.lastSub'} eq 'hdgrade');
2058: push @partlist,$partid;
2059: push @gradePartRespid,$partid.'.'.$respid;
2060: $request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
2061: }
2062: $result='<input type="hidden" name="partlist'.$counter.
2063: '" value="'.(join ":",@partlist).'" />'."\n";
2064: $result.='<input type="hidden" name="gradePartRespid'.
2065: '" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
2066: my $ctr = 0;
2067: while ($ctr < scalar(@partlist)) {
2068: $result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
2069: $partlist[$ctr].'" />'."\n";
2070: $ctr++;
2071: }
2072: $request->print($result.'</td></tr></table></td></tr></table>'."\n");
2073:
2074: # print end of form
2075: if ($counter == $total) {
2076: my $endform='<table border="0"><tr><td>'."\n";
2077: $endform.='<input type="button" value="Save & Next" '.
2078: 'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
2079: $total.','.scalar(@partlist).');" target="_self" /> '."\n";
2080: my $ntstu ='<select name="NTSTU">'.
2081: '<option>1</option><option>2</option>'.
2082: '<option>3</option><option>5</option>'.
2083: '<option>7</option><option>10</option></select>'."\n";
2084: my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
2085: $ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
2086: $endform.=$ntstu.'student(s) ';
2087: $endform.='<input type="button" value="Previous" '.
2088: 'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> '."\n".
2089: '<input type="button" value="Next" '.
2090: 'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> ';
2091: $endform.='(Next and Previous (student) do not save the scores.)'."\n" ;
2092: $endform.="<input type='hidden' value='".&get_increment().
2093: "' name='increment' />";
2094: $endform.='</td><tr></table></form>';
2095: $endform.=&show_grading_menu_form($symb);
2096: $request->print($endform);
2097: }
2098: return '';
2099: }
2100:
2101: #--- Retrieve the last submission for all the parts
2102: sub get_last_submission {
2103: my ($returnhash)=@_;
2104: my (@string,$timestamp);
2105: if ($$returnhash{'version'}) {
2106: my %lasthash=();
2107: my ($version);
2108: for ($version=1;$version<=$$returnhash{'version'};$version++) {
2109: foreach my $key (sort(split(/\:/,
2110: $$returnhash{$version.':keys'}))) {
2111: $lasthash{$key}=$$returnhash{$version.':'.$key};
2112: $timestamp =
2113: scalar(localtime($$returnhash{$version.':timestamp'}));
2114: }
2115: }
2116: foreach my $key (keys(%lasthash)) {
2117: next if ($key !~ /\.submission$/);
2118:
2119: my ($partid,$foo) = split(/submission$/,$key);
2120: my $draft = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
2121: '<span class="LC_warning">Draft Copy</span> ' : '';
2122: push(@string, join(':', $key, $draft.$lasthash{$key}));
2123: }
2124: }
2125: if (!@string) {
2126: $string[0] =
2127: '<span class="LC_warning">Nothing submitted - no attempts.</span>';
2128: }
2129: return (\@string,\$timestamp);
2130: }
2131:
2132: #--- High light keywords, with style choosen by user.
2133: sub keywords_highlight {
2134: my $string = shift;
2135: my $size = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
2136: my $styleon = $env{'form.kwstyle'} eq '' ? '' : $env{'form.kwstyle'};
2137: (my $styleoff = $styleon) =~ s/\</\<\//;
2138: my @keylist = split(/[,\s+]/,$env{'form.keywords'});
2139: foreach my $keyword (@keylist) {
2140: $string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
2141: }
2142: return $string;
2143: }
2144:
2145: #--- Called from submission routine
2146: sub processHandGrade {
2147: my ($request) = shift;
2148: my $symb = &get_symb($request);
2149: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
2150: my $button = $env{'form.gradeOpt'};
2151: my $ngrade = $env{'form.NCT'};
2152: my $ntstu = $env{'form.NTSTU'};
2153: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2154: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2155:
2156: if ($button eq 'Save & Next') {
2157: my $ctr = 0;
2158: while ($ctr < $ngrade) {
2159: my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
2160: my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
2161: if ($errorflag eq 'no_score') {
2162: $ctr++;
2163: next;
2164: }
2165: if ($errorflag eq 'not_allowed') {
2166: $request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
2167: $ctr++;
2168: next;
2169: }
2170: my $includemsg = $env{'form.includemsg'.$ctr};
2171: my ($subject,$message,$msgstatus) = ('','','');
2172: my $restitle = &Apache::lonnet::gettitle($symb);
2173: my ($feedurl,$showsymb) =
2174: &get_feedurl_and_symb($symb,$uname,$udom);
2175: my $messagetail;
2176: if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
2177: $subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
2178: unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
2179: $subject.=' ['.$restitle.']';
2180: my (@msgnum) = split(/,/,$includemsg);
2181: foreach (@msgnum) {
2182: $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
2183: }
2184: $message =&Apache::lonfeedback::clear_out_html($message);
2185: if ($env{'form.withgrades'.$ctr}) {
2186: $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
2187: $messagetail = " for <a href=\"".
2188: $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
2189: }
2190: $msgstatus =
2191: &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
2192: $message.$messagetail,
2193: undef,$feedurl,undef,
2194: undef,undef,$showsymb,
2195: $restitle);
2196: $request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
2197: $msgstatus);
2198: }
2199: if ($env{'form.collaborator'.$ctr}) {
2200: my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
2201: foreach my $collabstr (@collabstrs) {
2202: my ($part,@collaborators) = split(/:/,$collabstr);
2203: foreach my $collaborator (@collaborators) {
2204: my ($errorflag,$pts,$wgt) =
2205: &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
2206: $env{'form.unamedom'.$ctr},$part);
2207: if ($errorflag eq 'not_allowed') {
2208: $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
2209: next;
2210: } elsif ($message ne '') {
2211: my ($baseurl,$showsymb) =
2212: &get_feedurl_and_symb($symb,$collaborator,
2213: $udom);
2214: if ($env{'form.withgrades'.$ctr}) {
2215: $messagetail = " for <a href=\"".
2216: $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
2217: }
2218: $msgstatus =
2219: &Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
2220: }
2221: }
2222: }
2223: }
2224: $ctr++;
2225: }
2226: }
2227:
2228: if ($env{'form.handgrade'} eq 'yes') {
2229: # Keywords sorted in alphabatical order
2230: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
2231: my %keyhash = ();
2232: $env{'form.keywords'} =~ s/,\s{0,}|\s+/ /g;
2233: $env{'form.keywords'} =~ s/^\s+|\s+$//;
2234: my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
2235: $env{'form.keywords'} = join(' ',@keywords);
2236: $keyhash{$symb.'_keywords'} = $env{'form.keywords'};
2237: $keyhash{$symb.'_subject'} = $env{'form.msgsub'};
2238: $keyhash{$loginuser.'_kwclr'} = $env{'form.kwclr'};
2239: $keyhash{$loginuser.'_kwsize'} = $env{'form.kwsize'};
2240: $keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
2241:
2242: # message center - Order of message gets changed. Blank line is eliminated.
2243: # New messages are saved in env for the next student.
2244: # All messages are saved in nohist_handgrade.db
2245: my ($ctr,$idx) = (1,1);
2246: while ($ctr <= $env{'form.savemsgN'}) {
2247: if ($env{'form.savemsg'.$ctr} ne '') {
2248: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
2249: $idx++;
2250: }
2251: $ctr++;
2252: }
2253: $ctr = 0;
2254: while ($ctr < $ngrade) {
2255: if ($env{'form.newmsg'.$ctr} ne '') {
2256: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2257: $env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2258: $idx++;
2259: }
2260: $ctr++;
2261: }
2262: $env{'form.savemsgN'} = --$idx;
2263: $keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
2264: my $putresult = &Apache::lonnet::put
2265: ('nohist_handgrade',\%keyhash,$cdom,$cnum);
2266: }
2267: # Called by Save & Refresh from Highlight Attribute Window
2268: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
2269: if ($env{'form.refresh'} eq 'on') {
2270: my ($ctr,$total) = (0,0);
2271: while ($ctr < $ngrade) {
2272: $total++ if $env{'form.unamedom'.$ctr} ne '';
2273: $ctr++;
2274: }
2275: $env{'form.NTSTU'}=$ngrade;
2276: $ctr = 0;
2277: while ($ctr < $total) {
2278: my $processUser = $env{'form.unamedom'.$ctr};
2279: ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
2280: $env{'form.fullname'} = $$fullname{$processUser};
2281: &submission($request,$ctr,$total-1);
2282: $ctr++;
2283: }
2284: return '';
2285: }
2286:
2287: # Go directly to grade student - from submission or link from chart page
2288: if ($button eq 'Grade Student') {
2289: (undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
2290: my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
2291: ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
2292: $env{'form.fullname'} = $$fullname{$processUser};
2293: &submission($request,0,0);
2294: return '';
2295: }
2296:
2297: # Get the next/previous one or group of students
2298: my $firststu = $env{'form.unamedom0'};
2299: my $laststu = $env{'form.unamedom'.($ngrade-1)};
2300: my $ctr = 2;
2301: while ($laststu eq '') {
2302: $laststu = $env{'form.unamedom'.($ngrade-$ctr)};
2303: $ctr++;
2304: $laststu = $firststu if ($ctr > $ngrade);
2305: }
2306:
2307: my (@parsedlist,@nextlist);
2308: my ($nextflg) = 0;
2309: foreach (sort
2310: {
2311: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
2312: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
2313: }
2314: return $a cmp $b;
2315: } (keys(%$fullname))) {
2316: if ($nextflg == 1 && $button =~ /Next$/) {
2317: push @parsedlist,$_;
2318: }
2319: $nextflg = 1 if ($_ eq $laststu);
2320: if ($button eq 'Previous') {
2321: last if ($_ eq $firststu);
2322: push @parsedlist,$_;
2323: }
2324: }
2325: $ctr = 0;
2326: @parsedlist = reverse @parsedlist if ($button eq 'Previous');
2327: my ($partlist) = &response_type($symb);
2328: foreach my $student (@parsedlist) {
2329: my $submitonly=$env{'form.submitonly'};
2330: my ($uname,$udom) = split(/:/,$student);
2331:
2332: if ($submitonly eq 'queued') {
2333: my %queue_status =
2334: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
2335: $udom,$uname);
2336: next if (!defined($queue_status{'gradingqueue'}));
2337: }
2338:
2339: if ($submitonly =~ /^(yes|graded|incorrect)$/) {
2340: # my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
2341: my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
2342: my $submitted = 0;
2343: my $ungraded = 0;
2344: my $incorrect = 0;
2345: foreach (keys(%status)) {
2346: $submitted = 1 if ($status{$_} ne 'nothing');
2347: $ungraded = 1 if ($status{$_} =~ /^ungraded/);
2348: $incorrect = 1 if ($status{$_} =~ /^incorrect/);
2349: my ($foo,$partid,$foo1) = split(/\./,$_);
2350: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
2351: $submitted = 0;
2352: }
2353: }
2354: next if (!$submitted && ($submitonly eq 'yes' ||
2355: $submitonly eq 'incorrect' ||
2356: $submitonly eq 'graded'));
2357: next if (!$ungraded && ($submitonly eq 'graded'));
2358: next if (!$incorrect && $submitonly eq 'incorrect');
2359: }
2360: push @nextlist,$student if ($ctr < $ntstu);
2361: last if ($ctr == $ntstu);
2362: $ctr++;
2363: }
2364:
2365: $ctr = 0;
2366: my $total = scalar(@nextlist)-1;
2367:
2368: foreach (sort @nextlist) {
2369: my ($uname,$udom,$submitter) = split(/:/);
2370: $env{'form.student'} = $uname;
2371: $env{'form.userdom'} = $udom;
2372: $env{'form.fullname'} = $$fullname{$_};
2373: &submission($request,$ctr,$total);
2374: $ctr++;
2375: }
2376: if ($total < 0) {
2377: my $the_end = '<h3><span class="LC_info">LON-CAPA User Message</span></h3><br />'."\n";
2378: $the_end.='<b>Message: </b> No more students for this section or class.<br /><br />'."\n";
2379: $the_end.='Click on the button below to return to the grading menu.<br /><br />'."\n";
2380: $the_end.=&show_grading_menu_form($symb);
2381: $request->print($the_end);
2382: }
2383: return '';
2384: }
2385:
2386: #---- Save the score and award for each student, if changed
2387: sub saveHandGrade {
2388: my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
2389: my @version_parts;
2390: my $usec = &Apache::lonnet::getsection($domain,$stuname,
2391: $env{'request.course.id'});
2392: if (!&canmodify($usec)) { return('not_allowed'); }
2393: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
2394: my @parts_graded;
2395: my %newrecord = ();
2396: my ($pts,$wgt) = ('','');
2397: my %aggregate = ();
2398: my $aggregateflag = 0;
2399: my @parts = split(/:/,$env{'form.partlist'.$newflg});
2400: foreach my $new_part (@parts) {
2401: #collaborator ($submi may vary for different parts
2402: if ($submitter && $new_part ne $part) { next; }
2403: my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
2404: if ($dropMenu eq 'excused') {
2405: if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
2406: $newrecord{'resource.'.$new_part.'.solved'} = 'excused';
2407: if (exists($record{'resource.'.$new_part.'.awarded'})) {
2408: $newrecord{'resource.'.$new_part.'.awarded'} = '';
2409: }
2410: $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
2411: }
2412: } elsif ($dropMenu eq 'reset status'
2413: && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
2414: foreach my $key (keys (%record)) {
2415: if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
2416: }
2417: $newrecord{'resource.'.$new_part.'.regrader'}=
2418: "$env{'user.name'}:$env{'user.domain'}";
2419: my $totaltries = $record{'resource.'.$part.'.tries'};
2420:
2421: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
2422: [$new_part]);
2423: my $aggtries =$totaltries;
2424: if ($last_resets{$new_part}) {
2425: $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
2426: $new_part);
2427: }
2428:
2429: my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
2430: if ($aggtries > 0) {
2431: &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
2432: $aggregateflag = 1;
2433: }
2434: } elsif ($dropMenu eq '') {
2435: $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ?
2436: $env{'form.GD_BOX'.$newflg.'_'.$new_part} :
2437: $env{'form.RADVAL'.$newflg.'_'.$new_part});
2438: if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
2439: next;
2440: }
2441: $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 :
2442: $env{'form.WGT'.$newflg.'_'.$new_part};
2443: my $partial= $pts/$wgt;
2444: if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
2445: #do not update score for part if not changed.
2446: &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
2447: next;
2448: } else {
2449: push @parts_graded, $new_part;
2450: }
2451: if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
2452: $newrecord{'resource.'.$new_part.'.awarded'} = $partial;
2453: }
2454: my $reckey = 'resource.'.$new_part.'.solved';
2455: if ($partial == 0) {
2456: if ($record{$reckey} ne 'incorrect_by_override') {
2457: $newrecord{$reckey} = 'incorrect_by_override';
2458: }
2459: } else {
2460: if ($record{$reckey} ne 'correct_by_override') {
2461: $newrecord{$reckey} = 'correct_by_override';
2462: }
2463: }
2464: if ($submitter &&
2465: ($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
2466: $newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
2467: }
2468: $newrecord{'resource.'.$new_part.'.regrader'}=
2469: "$env{'user.name'}:$env{'user.domain'}";
2470: }
2471: # unless problem has been graded, set flag to version the submitted files
2472: unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/ ||
2473: $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
2474: $dropMenu eq 'reset status')
2475: {
2476: push (@version_parts,$new_part);
2477: }
2478: }
2479: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2480: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2481:
2482: if (%newrecord) {
2483: if (@version_parts) {
2484: my @changed_keys = &version_portfiles(\%record, \@parts_graded,
2485: $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
2486: @newrecord{@changed_keys} = @record{@changed_keys};
2487: foreach my $new_part (@version_parts) {
2488: &handback_files($request,$symb,$stuname,$domain,$newflg,
2489: $new_part,\%newrecord);
2490: }
2491: }
2492: &Apache::lonnet::cstore(\%newrecord,$symb,
2493: $env{'request.course.id'},$domain,$stuname);
2494: &check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
2495: $cdom,$cnum,$domain,$stuname);
2496: }
2497: if ($aggregateflag) {
2498: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
2499: $cdom,$cnum);
2500: }
2501: return ('',$pts,$wgt);
2502: }
2503:
2504: sub check_and_remove_from_queue {
2505: my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
2506: my @ungraded_parts;
2507: foreach my $part (@{$parts}) {
2508: if ( $record->{ 'resource.'.$part.'.awarded'} eq ''
2509: && $record->{ 'resource.'.$part.'.solved' } ne 'excused'
2510: && $newrecord->{'resource.'.$part.'.awarded'} eq ''
2511: && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
2512: ) {
2513: push(@ungraded_parts, $part);
2514: }
2515: }
2516: if ( !@ungraded_parts ) {
2517: &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
2518: $cnum,$domain,$stuname);
2519: }
2520: }
2521:
2522: sub handback_files {
2523: my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
2524: my $portfolio_root = &propath($domain,$stuname).'/userfiles/portfolio';
2525: my ($partlist,$handgrade,$responseType) = &response_type($symb);
2526:
2527: my @part_response_id = &flatten_responseType($responseType);
2528: foreach my $part_response_id (@part_response_id) {
2529: my ($part_id,$resp_id) = @{ $part_response_id };
2530: my $part_resp = join('_',@{ $part_response_id });
2531: if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
2532: # if multiple files are uploaded names will be 'returndoc2','returndoc3'
2533: my $file_counter = 1;
2534: my $file_msg;
2535: while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
2536: my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
2537: my ($directory,$answer_file) =
2538: ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
2539: my ($answer_name,$answer_ver,$answer_ext) =
2540: &file_name_version_ext($answer_file);
2541: my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
2542: my @dir_list = &Apache::lonnet::dirlist($portfolio_path,$domain,$stuname,$portfolio_root);
2543: my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
2544: # fix file name
2545: my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
2546: my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
2547: $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
2548: $save_file_name);
2549: if ($result !~ m|^/uploaded/|) {
2550: $request->print('<span class="LC_error">An error occurred ('.$result.
2551: ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</span><br />');
2552: } else {
2553: # mark the file as read only
2554: my @files = ($save_file_name);
2555: my @what = ($symb,$env{'request.course.id'},'handback');
2556: &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
2557: if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
2558: $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
2559: }
2560: $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
2561: $file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
2562:
2563: }
2564: $request->print("<br />".$fname." will be the uploaded file name");
2565: $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
2566: $file_counter++;
2567: }
2568: my $subject = "File Handed Back by Instructor ";
2569: my $message = "A file has been returned that was originally submitted in reponse to: <br />";
2570: $message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
2571: $message .= ' The returned file(s) are named: '. $file_msg;
2572: $message .= " and can be found in your portfolio space.";
2573: my ($feedurl,$showsymb) =
2574: &get_feedurl_and_symb($symb,$domain,$stuname);
2575: my $restitle = &Apache::lonnet::gettitle($symb);
2576: my $msgstatus =
2577: &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
2578: ' (File Returned) ['.$restitle.']',$message,undef,
2579: $feedurl,undef,undef,undef,$showsymb,$restitle);
2580: }
2581: }
2582: return;
2583: }
2584:
2585: sub get_feedurl_and_symb {
2586: my ($symb,$uname,$udom) = @_;
2587: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
2588: $url = &Apache::lonnet::clutter($url);
2589: my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
2590: $symb,$udom,$uname);
2591: if ($encrypturl =~ /^yes$/i) {
2592: &Apache::lonenc::encrypted(\$url,1);
2593: &Apache::lonenc::encrypted(\$symb,1);
2594: }
2595: return ($url,$symb);
2596: }
2597:
2598: sub get_submitted_files {
2599: my ($udom,$uname,$partid,$respid,$record) = @_;
2600: my @files;
2601: if ($$record{"resource.$partid.$respid.portfiles"}) {
2602: my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
2603: foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
2604: push(@files,$file_url.$file);
2605: }
2606: }
2607: if ($$record{"resource.$partid.$respid.uploadedurl"}) {
2608: push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
2609: }
2610: return (\@files);
2611: }
2612:
2613: # ----------- Provides number of tries since last reset.
2614: sub get_num_tries {
2615: my ($record,$last_reset,$part) = @_;
2616: my $timestamp = '';
2617: my $num_tries = 0;
2618: if ($$record{'version'}) {
2619: for (my $version=$$record{'version'};$version>=1;$version--) {
2620: if (exists($$record{$version.':resource.'.$part.'.solved'})) {
2621: $timestamp = $$record{$version.':timestamp'};
2622: if ($timestamp > $last_reset) {
2623: $num_tries ++;
2624: } else {
2625: last;
2626: }
2627: }
2628: }
2629: }
2630: return $num_tries;
2631: }
2632:
2633: # ----------- Determine decrements required in aggregate totals
2634: sub decrement_aggs {
2635: my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
2636: my %decrement = (
2637: attempts => 0,
2638: users => 0,
2639: correct => 0
2640: );
2641: $decrement{'attempts'} = $aggtries;
2642: if ($solvedstatus =~ /^correct/) {
2643: $decrement{'correct'} = 1;
2644: }
2645: if ($aggtries == $totaltries) {
2646: $decrement{'users'} = 1;
2647: }
2648: foreach my $type (keys (%decrement)) {
2649: $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
2650: }
2651: return;
2652: }
2653:
2654: # ----------- Determine timestamps for last reset of aggregate totals for parts
2655: sub get_last_resets {
2656: my ($symb,$courseid,$partids) =@_;
2657: my %last_resets;
2658: my $cdom = $env{'course.'.$courseid.'.domain'};
2659: my $cname = $env{'course.'.$courseid.'.num'};
2660: my @keys;
2661: foreach my $part (@{$partids}) {
2662: push(@keys,"$symb\0$part\0resettime");
2663: }
2664: my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
2665: $cdom,$cname);
2666: foreach my $part (@{$partids}) {
2667: $last_resets{$part}=$results{"$symb\0$part\0resettime"};
2668: }
2669: return %last_resets;
2670: }
2671:
2672: # ----------- Handles creating versions for portfolio files as answers
2673: sub version_portfiles {
2674: my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
2675: my $version_parts = join('|',@$v_flag);
2676: my @returned_keys;
2677: my $parts = join('|', @$parts_graded);
2678: my $portfolio_root = &propath($domain,$stu_name).
2679: '/userfiles/portfolio';
2680: foreach my $key (keys(%$record)) {
2681: my $new_portfiles;
2682: if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
2683: my @versioned_portfiles;
2684: my @portfiles = split(/\s*,\s*/,$$record{$key});
2685: foreach my $file (@portfiles) {
2686: &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
2687: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
2688: my ($answer_name,$answer_ver,$answer_ext) =
2689: &file_name_version_ext($answer_file);
2690: my @dir_list = &Apache::lonnet::dirlist($directory,$domain,$stu_name,$portfolio_root);
2691: my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
2692: my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
2693: if ($new_answer ne 'problem getting file') {
2694: push(@versioned_portfiles, $directory.$new_answer);
2695: &Apache::lonnet::mark_as_readonly($domain,$stu_name,
2696: [$directory.$new_answer],
2697: [$symb,$env{'request.course.id'},'graded']);
2698: }
2699: }
2700: $$record{$key} = join(',',@versioned_portfiles);
2701: push(@returned_keys,$key);
2702: }
2703: }
2704: return (@returned_keys);
2705: }
2706:
2707: sub get_next_version {
2708: my ($answer_name, $answer_ext, $dir_list) = @_;
2709: my $version;
2710: foreach my $row (@$dir_list) {
2711: my ($file) = split(/\&/,$row,2);
2712: my ($file_name,$file_version,$file_ext) =
2713: &file_name_version_ext($file);
2714: if (($file_name eq $answer_name) &&
2715: ($file_ext eq $answer_ext)) {
2716: # gets here if filename and extension match, regardless of version
2717: if ($file_version ne '') {
2718: # a versioned file is found so save it for later
2719: if ($file_version > $version) {
2720: $version = $file_version;
2721: }
2722: }
2723: }
2724: }
2725: $version ++;
2726: return($version);
2727: }
2728:
2729: sub version_selected_portfile {
2730: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
2731: my ($answer_name,$answer_ver,$answer_ext) =
2732: &file_name_version_ext($file_name);
2733: my $new_answer;
2734: $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
2735: if($env{'form.copy'} eq '-1') {
2736: &Apache::lonnet::logthis('problem getting file '.$file_name);
2737: $new_answer = 'problem getting file';
2738: } else {
2739: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
2740: my $copy_result = &Apache::lonnet::finishuserfileupload(
2741: $stu_name,$domain,'copy',
2742: '/portfolio'.$directory.$new_answer);
2743: }
2744: return ($new_answer);
2745: }
2746:
2747: sub file_name_version_ext {
2748: my ($file)=@_;
2749: my @file_parts = split(/\./, $file);
2750: my ($name,$version,$ext);
2751: if (@file_parts > 1) {
2752: $ext=pop(@file_parts);
2753: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
2754: $version=pop(@file_parts);
2755: }
2756: $name=join('.',@file_parts);
2757: } else {
2758: $name=join('.',@file_parts);
2759: }
2760: return($name,$version,$ext);
2761: }
2762:
2763: #--------------------------------------------------------------------------------------
2764: #
2765: #-------------------------- Next few routines handles grading by section or whole class
2766: #
2767: #--- Javascript to handle grading by section or whole class
2768: sub viewgrades_js {
2769: my ($request) = shift;
2770:
2771: $request->print(<<VIEWJAVASCRIPT);
2772: <script type="text/javascript" language="javascript">
2773: function writePoint(partid,weight,point) {
2774: var radioButton = document.classgrade["RADVAL_"+partid];
2775: var textbox = document.classgrade["TEXTVAL_"+partid];
2776: if (point == "textval") {
2777: point = document.classgrade["TEXTVAL_"+partid].value;
2778: if (isNaN(point) || parseFloat(point) < 0) {
2779: alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
2780: var resetbox = false;
2781: for (var i=0; i<radioButton.length; i++) {
2782: if (radioButton[i].checked) {
2783: textbox.value = i;
2784: resetbox = true;
2785: }
2786: }
2787: if (!resetbox) {
2788: textbox.value = "";
2789: }
2790: return;
2791: }
2792: if (parseFloat(point) > parseFloat(weight)) {
2793: var resp = confirm("You entered a value ("+parseFloat(point)+
2794: ") greater than the weight for the part. Accept?");
2795: if (resp == false) {
2796: textbox.value = "";
2797: return;
2798: }
2799: }
2800: for (var i=0; i<radioButton.length; i++) {
2801: radioButton[i].checked=false;
2802: if (parseFloat(point) == i) {
2803: radioButton[i].checked=true;
2804: }
2805: }
2806:
2807: } else {
2808: textbox.value = parseFloat(point);
2809: }
2810: for (i=0;i<document.classgrade.total.value;i++) {
2811: var user = document.classgrade["ctr"+i].value;
2812: user = user.replace(new RegExp(':', 'g'),"_");
2813: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
2814: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
2815: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
2816: if (saveval != "correct") {
2817: scorename.value = point;
2818: if (selname[0].selected != true) {
2819: selname[0].selected = true;
2820: }
2821: }
2822: }
2823: document.classgrade["SELVAL_"+partid][0].selected = true;
2824: }
2825:
2826: function writeRadText(partid,weight) {
2827: var selval = document.classgrade["SELVAL_"+partid];
2828: var radioButton = document.classgrade["RADVAL_"+partid];
2829: var override = document.classgrade["FORCE_"+partid].checked;
2830: var textbox = document.classgrade["TEXTVAL_"+partid];
2831: if (selval[1].selected || selval[2].selected) {
2832: for (var i=0; i<radioButton.length; i++) {
2833: radioButton[i].checked=false;
2834:
2835: }
2836: textbox.value = "";
2837:
2838: for (i=0;i<document.classgrade.total.value;i++) {
2839: var user = document.classgrade["ctr"+i].value;
2840: user = user.replace(new RegExp(':', 'g'),"_");
2841: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
2842: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
2843: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
2844: if ((saveval != "correct") || override) {
2845: scorename.value = "";
2846: if (selval[1].selected) {
2847: selname[1].selected = true;
2848: } else {
2849: selname[2].selected = true;
2850: if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value))
2851: {document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
2852: }
2853: }
2854: }
2855: } else {
2856: for (i=0;i<document.classgrade.total.value;i++) {
2857: var user = document.classgrade["ctr"+i].value;
2858: user = user.replace(new RegExp(':', 'g'),"_");
2859: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
2860: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
2861: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
2862: if ((saveval != "correct") || override) {
2863: scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
2864: selname[0].selected = true;
2865: }
2866: }
2867: }
2868: }
2869:
2870: function changeSelect(partid,user) {
2871: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
2872: var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
2873: var point = textbox.value;
2874: var weight = document.classgrade["weight_"+partid].value;
2875:
2876: if (isNaN(point) || parseFloat(point) < 0) {
2877: alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
2878: textbox.value = "";
2879: return;
2880: }
2881: if (parseFloat(point) > parseFloat(weight)) {
2882: var resp = confirm("You entered a value ("+parseFloat(point)+
2883: ") greater than the weight of the part. Accept?");
2884: if (resp == false) {
2885: textbox.value = "";
2886: return;
2887: }
2888: }
2889: selval[0].selected = true;
2890: }
2891:
2892: function changeOneScore(partid,user) {
2893: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
2894: if (selval[1].selected || selval[2].selected) {
2895: document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
2896: if (selval[2].selected) {
2897: document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
2898: }
2899: }
2900: }
2901:
2902: function resetEntry(numpart) {
2903: for (ctpart=0;ctpart<numpart;ctpart++) {
2904: var partid = document.classgrade["partid_"+ctpart].value;
2905: var radioButton = document.classgrade["RADVAL_"+partid];
2906: var textbox = document.classgrade["TEXTVAL_"+partid];
2907: var selval = document.classgrade["SELVAL_"+partid];
2908: for (var i=0; i<radioButton.length; i++) {
2909: radioButton[i].checked=false;
2910:
2911: }
2912: textbox.value = "";
2913: selval[0].selected = true;
2914:
2915: for (i=0;i<document.classgrade.total.value;i++) {
2916: var user = document.classgrade["ctr"+i].value;
2917: user = user.replace(new RegExp(':', 'g'),"_");
2918: var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
2919: resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
2920: var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
2921: resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
2922: var saveselval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
2923: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
2924: if (saveselval == "excused") {
2925: if (selname[1].selected == false) { selname[1].selected = true;}
2926: } else {
2927: if (selname[0].selected == false) {selname[0].selected = true};
2928: }
2929: }
2930: }
2931: }
2932:
2933: </script>
2934: VIEWJAVASCRIPT
2935: }
2936:
2937: #--- show scores for a section or whole class w/ option to change/update a score
2938: sub viewgrades {
2939: my ($request) = shift;
2940: &viewgrades_js($request);
2941:
2942: my ($symb) = &get_symb($request);
2943: #need to make sure we have the correct data for later EXT calls,
2944: #thus invalidate the cache
2945: &Apache::lonnet::devalidatecourseresdata(
2946: $env{'course.'.$env{'request.course.id'}.'.num'},
2947: $env{'course.'.$env{'request.course.id'}.'.domain'});
2948: &Apache::lonnet::clear_EXT_cache_status();
2949:
2950: my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
2951: $result.='<h4><b>Current Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n";
2952:
2953: #view individual student submission form - called using Javascript viewOneStudent
2954: $result.=&jscriptNform($symb);
2955:
2956: #beginning of class grading form
2957: $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
2958: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
2959: '<input type="hidden" name="command" value="editgrades" />'."\n".
2960: '<input type="hidden" name="section" value="'.$env{'form.section'}.'" />'."\n".
2961: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
2962: '<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n".
2963: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
2964:
2965: my $sectionClass;
2966: if ($env{'form.section'} eq 'all') {
2967: $sectionClass='Class </h3>';
2968: } elsif ($env{'form.section'} eq 'none') {
2969: $sectionClass='Students in no Section </h3>';
2970: } else {
2971: $sectionClass='Students in Section '.$env{'form.section'}.'</h3>';
2972: }
2973: $result.='<h3>Assign Common Grade To '.$sectionClass;
2974: $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
2975: '<table border=0><tr bgcolor="#ffffdd"><td>';
2976: #radio buttons/text box for assigning points for a section or class.
2977: #handles different parts of a problem
2978: my ($partlist,$handgrade,$responseType) = &response_type($symb);
2979: my %weight = ();
2980: my $ctsparts = 0;
2981: $result.='<table border="0">';
2982: my %seen = ();
2983: my @part_response_id = &flatten_responseType($responseType);
2984: foreach my $part_response_id (@part_response_id) {
2985: my ($partid,$respid) = @{ $part_response_id };
2986: my $part_resp = join('_',@{ $part_response_id });
2987: next if $seen{$partid};
2988: $seen{$partid}++;
2989: my $handgrade=$$handgrade{$part_resp};
2990: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
2991: $weight{$partid} = $wgt eq '' ? '1' : $wgt;
2992:
2993: $result.='<input type="hidden" name="partid_'.
2994: $ctsparts.'" value="'.$partid.'" />'."\n";
2995: $result.='<input type="hidden" name="weight_'.
2996: $partid.'" value="'.$weight{$partid}.'" />'."\n";
2997: my $display_part=&get_display_part($partid,$symb);
2998: $result.='<tr><td><b>Part:</b> '.$display_part.' <b>Point:</b> </td><td>';
2999: $result.='<table border="0"><tr>';
3000: my $ctr = 0;
3001: while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
3002: $result.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
3003: 'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
3004: ','.$ctr.')" />'.$ctr."</label></td>\n";
3005: $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
3006: $ctr++;
3007: }
3008: $result.='</tr></table>';
3009: $result.= '</td><td><b> or </b><input type="text" name="TEXTVAL_'.
3010: $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
3011: $partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
3012: $weight{$partid}.' (problem weight)</td>'."\n";
3013: $result.= '</td><td><select name="SELVAL_'.$partid.'"'.
3014: 'onChange="javascript:writeRadText(\''.$partid.'\','.
3015: $weight{$partid}.')"> '.
3016: '<option selected="selected"> </option>'.
3017: '<option>excused</option>'.
3018: '<option>reset status</option></select></td>'.
3019: '<td><label><input type="checkbox" name="FORCE_'.$partid.'" /> Override "Correct"</label></td></tr>'."\n";
3020: $ctsparts++;
3021: }
3022: $result.='</table>'.'</td></tr></table>'.'</td></tr></table>'."\n".
3023: '<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
3024: $result.='<input type="button" value="Revert to Default" '.
3025: 'onClick="javascript:resetEntry('.$ctsparts.');" target="_self" />';
3026:
3027: #table listing all the students in a section/class
3028: #header of table
3029: $result.= '<h3>Assign Grade to Specific Students in '.$sectionClass;
3030: $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
3031: '<table border=0><tr bgcolor="#deffff"><td> <b>No.</b> </td>'.
3032: '<td>'.&nameUserString('header')."</td>\n";
3033: my (@parts) = sort(&getpartlist($symb));
3034: my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
3035: my @partids = ();
3036: foreach my $part (@parts) {
3037: my $display=&Apache::lonnet::metadata($url,$part.'.display');
3038: $display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
3039: if (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
3040: my ($partid) = &split_part_type($part);
3041: push(@partids, $partid);
3042: my $display_part=&get_display_part($partid,$symb);
3043: if ($display =~ /^Partial Credit Factor/) {
3044: $result.='<td><b>Score Part:</b> '.$display_part.
3045: ' <br /><b>(weight = '.$weight{$partid}.')</b></td>'."\n";
3046: next;
3047: } else {
3048: $display =~s/\[Part: \Q$partid\E\]/Part:<\/b> $display_part/;
3049: }
3050: $display =~ s|Problem Status|Grade Status<br />|;
3051: $result.='<td><b>'.$display.'</td>'."\n";
3052: }
3053: $result.='</tr>';
3054:
3055: my %last_resets =
3056: &get_last_resets($symb,$env{'request.course.id'},\@partids);
3057:
3058: #get info for each student
3059: #list all the students - with points and grade status
3060: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
3061: my $ctr = 0;
3062: foreach (sort
3063: {
3064: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
3065: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
3066: }
3067: return $a cmp $b;
3068: } (keys(%$fullname))) {
3069: $ctr++;
3070: $result.=&viewstudentgrade($symb,$env{'request.course.id'},
3071: $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
3072: }
3073: $result.='</table></td></tr></table>';
3074: $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
3075: $result.='<input type="button" value="Save" '.
3076: 'onClick="javascript:submit();" target="_self" /></form>'."\n";
3077: if (scalar(%$fullname) eq 0) {
3078: my $colspan=3+scalar(@parts);
3079: $result='<span class="LC_warning">There are no students in section "'.$env{'form.section'}.
3080: '" with enrollment status "'.$env{'form.Status'}.'" to modify or grade.</span>';
3081: }
3082: $result.=&show_grading_menu_form($symb);
3083: return $result;
3084: }
3085:
3086: #--- call by previous routine to display each student
3087: sub viewstudentgrade {
3088: my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
3089: my ($uname,$udom) = split(/:/,$student);
3090: my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
3091: my %aggregates = ();
3092: my $result='<tr bgcolor="#ffffdd"><td align="right">'.
3093: '<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
3094: "\n".$ctr.' </td><td> '.
3095: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
3096: '\');" target="_self">'.$fullname.'</a> '.
3097: '<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
3098: $student=~s/:/_/; # colon doen't work in javascript for names
3099: foreach my $apart (@$parts) {
3100: my ($part,$type) = &split_part_type($apart);
3101: my $score=$record{"resource.$part.$type"};
3102: $result.='<td align="center">';
3103: my ($aggtries,$totaltries);
3104: unless (exists($aggregates{$part})) {
3105: $totaltries = $record{'resource.'.$part.'.tries'};
3106:
3107: $aggtries = $totaltries;
3108: if ($$last_resets{$part}) {
3109: $aggtries = &get_num_tries(\%record,$$last_resets{$part},
3110: $part);
3111: }
3112: $result.='<input type="hidden" name="'.
3113: 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
3114: $result.='<input type="hidden" name="'.
3115: 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
3116: $aggregates{$part} = 1;
3117: }
3118: if ($type eq 'awarded') {
3119: my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
3120: $result.='<input type="hidden" name="'.
3121: 'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
3122: $result.='<input type="text" name="'.
3123: 'GD_'.$student.'_'.$part.'_awarded" '.
3124: 'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
3125: '\')" value="'.$pts.'" size="4" /></td>'."\n";
3126: } elsif ($type eq 'solved') {
3127: my ($status,$foo)=split(/_/,$score,2);
3128: $status = 'nothing' if ($status eq '');
3129: $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
3130: $part.'_solved_s" value="'.$status.'" />'."\n";
3131: $result.=' <select name="'.
3132: 'GD_'.$student.'_'.$part.'_solved" '.
3133: 'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
3134: $result.= (($status eq 'excused') ? '<option> </option><option selected="selected">excused</option>'
3135: : '<option selected="selected"> </option><option>excused</option>')."\n";
3136: $result.='<option>reset status</option>';
3137: $result.="</select> </td>\n";
3138: } else {
3139: $result.='<input type="hidden" name="'.
3140: 'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
3141: "\n";
3142: $result.='<input type="text" name="'.
3143: 'GD_'.$student.'_'.$part.'_'.$type.'" '.
3144: 'value="'.$score.'" size="4" /></td>'."\n";
3145: }
3146: }
3147: $result.='</tr>';
3148: return $result;
3149: }
3150:
3151: #--- change scores for all the students in a section/class
3152: # record does not get update if unchanged
3153: sub editgrades {
3154: my ($request) = @_;
3155:
3156: my $symb=&get_symb($request);
3157: my $title='<h3><span class="LC_info">Current Grade Status</span></h3>';
3158: $title.='<h4><b>Current Resource: </b>'.$env{'form.probTitle'}.'</h4><br />'."\n";
3159: $title.='<h4><b>Section: </b>'.$env{'form.section'}.'</h4>'."\n";
3160:
3161: my $result= '<table border="0"><tr><td bgcolor="#777777">'."\n";
3162: $result.= '<table border="0"><tr bgcolor="#deffff">'.
3163: '<td rowspan=2 valign="center"> <b>No.</b> </td>'.
3164: '<td rowspan=2 valign="center">'.&nameUserString('header')."</td>\n";
3165:
3166: my %scoreptr = (
3167: 'correct' =>'correct_by_override',
3168: 'incorrect'=>'incorrect_by_override',
3169: 'excused' =>'excused',
3170: 'ungraded' =>'ungraded_attempted',
3171: 'nothing' => '',
3172: );
3173: my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
3174:
3175: my (@partid);
3176: my %weight = ();
3177: my %columns = ();
3178: my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
3179:
3180: my (@parts) = sort(&getpartlist($symb));
3181: my $header;
3182: while ($ctr < $env{'form.totalparts'}) {
3183: my $partid = $env{'form.partid_'.$ctr};
3184: push @partid,$partid;
3185: $weight{$partid} = $env{'form.weight_'.$partid};
3186: $ctr++;
3187: }
3188: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3189: foreach my $partid (@partid) {
3190: $header .= '<td align="center"> <b>Old Score</b> </td>'.
3191: '<td align="center"> <b>New Score</b> </td>';
3192: $columns{$partid}=2;
3193: foreach my $stores (@parts) {
3194: my ($part,$type) = &split_part_type($stores);
3195: if ($part !~ m/^\Q$partid\E/) { next;}
3196: if ($type eq 'awarded' || $type eq 'solved') { next; }
3197: my $display=&Apache::lonnet::metadata($url,$stores.'.display');
3198: $display =~ s/\[Part: (\w)+\]//;
3199: $display =~ s/Number of Attempts/Tries/;
3200: $header .= '<td align="center"> <b>Old '.$display.'</b> </td>'.
3201: '<td align="center"> <b>New '.$display.'</b> </td>';
3202: $columns{$partid}+=2;
3203: }
3204: }
3205: foreach my $partid (@partid) {
3206: my $display_part=&get_display_part($partid,$symb);
3207: $result .= '<td colspan="'.$columns{$partid}.
3208: '" align="center"><b>Part:</b> '.$display_part.
3209: ' (Weight = '.$weight{$partid}.')</td>';
3210:
3211: }
3212: $result .= '</tr><tr bgcolor="#deffff">';
3213: $result .= $header;
3214: $result .= '</tr>'."\n";
3215: my $noupdate;
3216: my ($updateCtr,$noupdateCtr) = (1,1);
3217: for ($i=0; $i<$env{'form.total'}; $i++) {
3218: my $line;
3219: my $user = $env{'form.ctr'.$i};
3220: my ($uname,$udom)=split(/:/,$user);
3221: my %newrecord;
3222: my $updateflag = 0;
3223: $line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
3224: my $usec=$classlist->{"$uname:$udom"}[5];
3225: if (!&canmodify($usec)) {
3226: my $numcols=scalar(@partid)*4+2;
3227: $noupdate.=$line."<td colspan=\"$numcols\"><span class=\"LC_warning\">Not allowed to modify student</span></td></tr>";
3228: next;
3229: }
3230: my %aggregate = ();
3231: my $aggregateflag = 0;
3232: $user=~s/:/_/; # colon doen't work in javascript for names
3233: foreach (@partid) {
3234: my $old_aw = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
3235: my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
3236: my $old_part = $old_aw eq '' ? '' : $old_part_pcr;
3237: my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
3238: my $awarded = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
3239: my $pcr = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
3240: my $partial = $awarded eq '' ? '' : $pcr;
3241: my $score;
3242: if ($partial eq '') {
3243: $score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
3244: } elsif ($partial > 0) {
3245: $score = 'correct_by_override';
3246: } elsif ($partial == 0) {
3247: $score = 'incorrect_by_override';
3248: }
3249: my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
3250: $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
3251:
3252: $newrecord{'resource.'.$_.'.regrader'}=
3253: "$env{'user.name'}:$env{'user.domain'}";
3254: if ($dropMenu eq 'reset status' &&
3255: $old_score ne '') { # ignore if no previous attempts => nothing to reset
3256: $newrecord{'resource.'.$_.'.tries'} = '';
3257: $newrecord{'resource.'.$_.'.solved'} = '';
3258: $newrecord{'resource.'.$_.'.award'} = '';
3259: $newrecord{'resource.'.$_.'.awarded'} = '';
3260: $updateflag = 1;
3261: if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
3262: my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
3263: my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
3264: my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
3265: &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
3266: $aggregateflag = 1;
3267: }
3268: } elsif (!($old_part eq $partial && $old_score eq $score)) {
3269: $updateflag = 1;
3270: $newrecord{'resource.'.$_.'.awarded'} = $partial if $partial ne '';
3271: $newrecord{'resource.'.$_.'.solved'} = $score;
3272: $rec_update++;
3273: }
3274:
3275: $line .= '<td align="center">'.$old_aw.' </td>'.
3276: '<td align="center">'.$awarded.
3277: ($score eq 'excused' ? $score : '').' </td>';
3278:
3279:
3280: my $partid=$_;
3281: foreach my $stores (@parts) {
3282: my ($part,$type) = &split_part_type($stores);
3283: if ($part !~ m/^\Q$partid\E/) { next;}
3284: if ($type eq 'awarded' || $type eq 'solved') { next; }
3285: my $old_aw = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
3286: my $awarded = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
3287: if ($awarded ne '' && $awarded ne $old_aw) {
3288: $newrecord{'resource.'.$part.'.'.$type}= $awarded;
3289: $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
3290: $updateflag=1;
3291: }
3292: $line .= '<td align="center">'.$old_aw.' </td>'.
3293: '<td align="center">'.$awarded.' </td>';
3294: }
3295: }
3296: $line.='</tr>'."\n";
3297:
3298: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3299: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3300:
3301: if ($updateflag) {
3302: $count++;
3303: &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
3304: $udom,$uname);
3305:
3306: if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
3307: $cnum,$udom,$uname)) {
3308: # need to figure out if should be in queue.
3309: my %record =
3310: &Apache::lonnet::restore($symb,$env{'request.course.id'},
3311: $udom,$uname);
3312: my $all_graded = 1;
3313: my $none_graded = 1;
3314: foreach my $part (@parts) {
3315: if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
3316: $all_graded = 0;
3317: } else {
3318: $none_graded = 0;
3319: }
3320: }
3321:
3322: if ($all_graded || $none_graded) {
3323: &Apache::bridgetask::remove_from_queue('gradingqueue',
3324: $symb,$cdom,$cnum,
3325: $udom,$uname);
3326: }
3327: }
3328:
3329: $result.='<tr bgcolor="#ffffde"><td align="right"> '.$updateCtr.' </td>'.$line;
3330: $updateCtr++;
3331: } else {
3332: $noupdate.='<tr bgcolor="#ffffde"><td align="right"> '.$noupdateCtr.' </td>'.$line;
3333: $noupdateCtr++;
3334: }
3335: if ($aggregateflag) {
3336: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
3337: $cdom,$cnum);
3338: }
3339: }
3340: if ($noupdate) {
3341: # my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
3342: my $numcols=scalar(@partid)*4+2;
3343: $result .= '<tr bgcolor="#ffffff"><td align="center" colspan="'.$numcols.'">No Changes Occurred For the Students Below</td></tr><tr bgcolor="#ffffde">'.$noupdate;
3344: }
3345: $result .= '</table></td></tr></table>'."\n".
3346: &show_grading_menu_form ($symb);
3347: my $msg = '<br /><b>Number of records updated = '.$rec_update.
3348: ' for '.$count.' student'.($count <= 1 ? '' : 's').'.</b><br />'.
3349: '<b>Total number of students = '.$env{'form.total'}.'</b><br />';
3350: return $title.$msg.$result;
3351: }
3352:
3353: sub split_part_type {
3354: my ($partstr) = @_;
3355: my ($temp,@allparts)=split(/_/,$partstr);
3356: my $type=pop(@allparts);
3357: my $part=join('.',@allparts);
3358: return ($part,$type);
3359: }
3360:
3361: #------------- end of section for handling grading by section/class ---------
3362: #
3363: #----------------------------------------------------------------------------
3364:
3365:
3366: #----------------------------------------------------------------------------
3367: #
3368: #-------------------------- Next few routines handles grading by csv upload
3369: #
3370: #--- Javascript to handle csv upload
3371: sub csvupload_javascript_reverse_associate {
3372: my $error1=&mt('You need to specify the username or ID');
3373: my $error2=&mt('You need to specify at least one grading field');
3374: return(<<ENDPICK);
3375: function verify(vf) {
3376: var foundsomething=0;
3377: var founduname=0;
3378: var foundID=0;
3379: for (i=0;i<=vf.nfields.value;i++) {
3380: tw=eval('vf.f'+i+'.selectedIndex');
3381: if (i==0 && tw!=0) { foundID=1; }
3382: if (i==1 && tw!=0) { founduname=1; }
3383: if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
3384: }
3385: if (founduname==0 && foundID==0) {
3386: alert('$error1');
3387: return;
3388: }
3389: if (foundsomething==0) {
3390: alert('$error2');
3391: return;
3392: }
3393: vf.submit();
3394: }
3395: function flip(vf,tf) {
3396: var nw=eval('vf.f'+tf+'.selectedIndex');
3397: var i;
3398: for (i=0;i<=vf.nfields.value;i++) {
3399: //can not pick the same destination field for both name and domain
3400: if (((i ==0)||(i ==1)) &&
3401: ((tf==0)||(tf==1)) &&
3402: (i!=tf) &&
3403: (eval('vf.f'+i+'.selectedIndex')==nw)) {
3404: eval('vf.f'+i+'.selectedIndex=0;')
3405: }
3406: }
3407: }
3408: ENDPICK
3409: }
3410:
3411: sub csvupload_javascript_forward_associate {
3412: my $error1=&mt('You need to specify the username or ID');
3413: my $error2=&mt('You need to specify at least one grading field');
3414: return(<<ENDPICK);
3415: function verify(vf) {
3416: var foundsomething=0;
3417: var founduname=0;
3418: var foundID=0;
3419: for (i=0;i<=vf.nfields.value;i++) {
3420: tw=eval('vf.f'+i+'.selectedIndex');
3421: if (tw==1) { foundID=1; }
3422: if (tw==2) { founduname=1; }
3423: if (tw>3) { foundsomething=1; }
3424: }
3425: if (founduname==0 && foundID==0) {
3426: alert('$error1');
3427: return;
3428: }
3429: if (foundsomething==0) {
3430: alert('$error2');
3431: return;
3432: }
3433: vf.submit();
3434: }
3435: function flip(vf,tf) {
3436: var nw=eval('vf.f'+tf+'.selectedIndex');
3437: var i;
3438: //can not pick the same destination field twice
3439: for (i=0;i<=vf.nfields.value;i++) {
3440: if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
3441: eval('vf.f'+i+'.selectedIndex=0;')
3442: }
3443: }
3444: }
3445: ENDPICK
3446: }
3447:
3448: sub csvuploadmap_header {
3449: my ($request,$symb,$datatoken,$distotal)= @_;
3450: my $javascript;
3451: if ($env{'form.upfile_associate'} eq 'reverse') {
3452: $javascript=&csvupload_javascript_reverse_associate();
3453: } else {
3454: $javascript=&csvupload_javascript_forward_associate();
3455: }
3456:
3457: my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
3458: my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
3459: my $ignore=&mt('Ignore First Line');
3460: $symb = &Apache::lonenc::check_encrypt($symb);
3461: $request->print(<<ENDPICK);
3462: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3463: <h3><span class="LC_info">Uploading Class Grades</span></h3>
3464: $result
3465: <hr />
3466: <h3>Identify fields</h3>
3467: Total number of records found in file: $distotal <hr />
3468: Enter as many fields as you can. The system will inform you and bring you back
3469: to this page if the data selected is insufficient to run your class.<hr />
3470: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
3471: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
3472: <input type="hidden" name="associate" value="" />
3473: <input type="hidden" name="phase" value="three" />
3474: <input type="hidden" name="datatoken" value="$datatoken" />
3475: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
3476: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
3477: <input type="hidden" name="upfile_associate"
3478: value="$env{'form.upfile_associate'}" />
3479: <input type="hidden" name="symb" value="$symb" />
3480: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
3481: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
3482: <input type="hidden" name="command" value="csvuploadoptions" />
3483: <hr />
3484: <script type="text/javascript" language="Javascript">
3485: $javascript
3486: </script>
3487: ENDPICK
3488: return '';
3489:
3490: }
3491:
3492: sub csvupload_fields {
3493: my ($symb) = @_;
3494: my (@parts) = &getpartlist($symb);
3495: my @fields=(['ID','Student ID'],
3496: ['username','Student Username'],
3497: ['domain','Student Domain']);
3498: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3499: foreach my $part (sort(@parts)) {
3500: my @datum;
3501: my $display=&Apache::lonnet::metadata($url,$part.'.display');
3502: my $name=$part;
3503: if (!$display) { $display = $name; }
3504: @datum=($name,$display);
3505: if ($name=~/^stores_(.*)_awarded/) {
3506: push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
3507: }
3508: push(@fields,\@datum);
3509: }
3510: return (@fields);
3511: }
3512:
3513: sub csvuploadmap_footer {
3514: my ($request,$i,$keyfields) =@_;
3515: $request->print(<<ENDPICK);
3516: </table>
3517: <input type="hidden" name="nfields" value="$i" />
3518: <input type="hidden" name="keyfields" value="$keyfields" />
3519: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
3520: </form>
3521: ENDPICK
3522: }
3523:
3524: sub checkforfile_js {
3525: my $result =<<CSVFORMJS;
3526: <script type="text/javascript" language="javascript">
3527: function checkUpload(formname) {
3528: if (formname.upfile.value == "") {
3529: alert("Please use the browse button to select a file from your local directory.");
3530: return false;
3531: }
3532: formname.submit();
3533: }
3534: </script>
3535: CSVFORMJS
3536: return $result;
3537: }
3538:
3539: sub upcsvScores_form {
3540: my ($request) = shift;
3541: my ($symb)=&get_symb($request);
3542: if (!$symb) {return '';}
3543: my $result=&checkforfile_js();
3544: $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
3545: my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
3546: $result.=$table;
3547: $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
3548: $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
3549: $result.=' <b>'.&mt('Specify a file containing the class scores for current resource').
3550: '.</b></td></tr>'."\n";
3551: $result.='<tr bgcolor=#ffffe6><td>'."\n";
3552: my $upload=&mt("Upload Scores");
3553: my $upfile_select=&Apache::loncommon::upfile_select_html();
3554: my $ignore=&mt('Ignore First Line');
3555: $symb = &Apache::lonenc::check_encrypt($symb);
3556: $result.=<<ENDUPFORM;
3557: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3558: <input type="hidden" name="symb" value="$symb" />
3559: <input type="hidden" name="command" value="csvuploadmap" />
3560: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
3561: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
3562: $upfile_select
3563: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
3564: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
3565: </form>
3566: ENDUPFORM
3567: $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
3568: &mt("How do I create a CSV file from a spreadsheet"))
3569: .'</td></tr></table>'."\n";
3570: $result.='</td></tr></table><br /><br />'."\n";
3571: $result.=&show_grading_menu_form($symb);
3572: return $result;
3573: }
3574:
3575:
3576: sub csvuploadmap {
3577: my ($request)= @_;
3578: my ($symb)=&get_symb($request);
3579: if (!$symb) {return '';}
3580:
3581: my $datatoken;
3582: if (!$env{'form.datatoken'}) {
3583: $datatoken=&Apache::loncommon::upfile_store($request);
3584: } else {
3585: $datatoken=$env{'form.datatoken'};
3586: &Apache::loncommon::load_tmp_file($request);
3587: }
3588: my @records=&Apache::loncommon::upfile_record_sep();
3589: if ($env{'form.noFirstLine'}) { shift(@records); }
3590: &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
3591: my ($i,$keyfields);
3592: if (@records) {
3593: my @fields=&csvupload_fields($symb);
3594:
3595: if ($env{'form.upfile_associate'} eq 'reverse') {
3596: &Apache::loncommon::csv_print_samples($request,\@records);
3597: $i=&Apache::loncommon::csv_print_select_table($request,\@records,
3598: \@fields);
3599: foreach (@fields) { $keyfields.=$_->[0].','; }
3600: chop($keyfields);
3601: } else {
3602: unshift(@fields,['none','']);
3603: $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
3604: \@fields);
3605: foreach my $rec (@records) {
3606: my %temp = &Apache::loncommon::record_sep($rec);
3607: if (%temp) {
3608: $keyfields=join(',',sort(keys(%temp)));
3609: last;
3610: }
3611: }
3612: }
3613: }
3614: &csvuploadmap_footer($request,$i,$keyfields);
3615: $request->print(&show_grading_menu_form($symb));
3616:
3617: return '';
3618: }
3619:
3620: sub csvuploadoptions {
3621: my ($request)= @_;
3622: my ($symb)=&get_symb($request);
3623: my $checked=(($env{'form.noFirstLine'})?'1':'0');
3624: my $ignore=&mt('Ignore First Line');
3625: $request->print(<<ENDPICK);
3626: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3627: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
3628: <input type="hidden" name="command" value="csvuploadassign" />
3629: <!--
3630: <p>
3631: <label>
3632: <input type="checkbox" name="show_full_results" />
3633: Show a table of all changes
3634: </label>
3635: </p>
3636: -->
3637: <p>
3638: <label>
3639: <input type="checkbox" name="overwite_scores" checked="checked" />
3640: Overwrite any existing score
3641: </label>
3642: </p>
3643: ENDPICK
3644: my %fields=&get_fields();
3645: if (!defined($fields{'domain'})) {
3646: my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
3647: $request->print("\n<p> Users are in domain: ".$domform."</p>\n");
3648: }
3649: foreach my $key (sort(keys(%env))) {
3650: if ($key !~ /^form\.(.*)$/) { next; }
3651: my $cleankey=$1;
3652: if ($cleankey eq 'command') { next; }
3653: $request->print('<input type="hidden" name="'.$cleankey.
3654: '" value="'.$env{$key}.'" />'."\n");
3655: }
3656: # FIXME do a check for any duplicated user ids...
3657: # FIXME do a check for any invalid user ids?...
3658: $request->print('<input type="submit" value="Assign Grades" /><br />
3659: <hr /></form>'."\n");
3660: $request->print(&show_grading_menu_form($symb));
3661: return '';
3662: }
3663:
3664: sub get_fields {
3665: my %fields;
3666: my @keyfields = split(/\,/,$env{'form.keyfields'});
3667: for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
3668: if ($env{'form.upfile_associate'} eq 'reverse') {
3669: if ($env{'form.f'.$i} ne 'none') {
3670: $fields{$keyfields[$i]}=$env{'form.f'.$i};
3671: }
3672: } else {
3673: if ($env{'form.f'.$i} ne 'none') {
3674: $fields{$env{'form.f'.$i}}=$keyfields[$i];
3675: }
3676: }
3677: }
3678: return %fields;
3679: }
3680:
3681: sub csvuploadassign {
3682: my ($request)= @_;
3683: my ($symb)=&get_symb($request);
3684: if (!$symb) {return '';}
3685: my $error_msg = '';
3686: &Apache::loncommon::load_tmp_file($request);
3687: my @gradedata = &Apache::loncommon::upfile_record_sep();
3688: if ($env{'form.noFirstLine'}) { shift(@gradedata); }
3689: my %fields=&get_fields();
3690: $request->print('<h3>Assigning Grades</h3>');
3691: my $courseid=$env{'request.course.id'};
3692: my ($classlist) = &getclasslist('all',0);
3693: my @notallowed;
3694: my @skipped;
3695: my $countdone=0;
3696: foreach my $grade (@gradedata) {
3697: my %entries=&Apache::loncommon::record_sep($grade);
3698: my $domain;
3699: if ($entries{$fields{'domain'}}) {
3700: $domain=$entries{$fields{'domain'}};
3701: } else {
3702: $domain=$env{'form.default_domain'};
3703: }
3704: $domain=~s/\s//g;
3705: my $username=$entries{$fields{'username'}};
3706: $username=~s/\s//g;
3707: if (!$username) {
3708: my $id=$entries{$fields{'ID'}};
3709: $id=~s/\s//g;
3710: my %ids=&Apache::lonnet::idget($domain,$id);
3711: $username=$ids{$id};
3712: }
3713: if (!exists($$classlist{"$username:$domain"})) {
3714: my $id=$entries{$fields{'ID'}};
3715: $id=~s/\s//g;
3716: if ($id) {
3717: push(@skipped,"$id:$domain");
3718: } else {
3719: push(@skipped,"$username:$domain");
3720: }
3721: next;
3722: }
3723: my $usec=$classlist->{"$username:$domain"}[5];
3724: if (!&canmodify($usec)) {
3725: push(@notallowed,"$username:$domain");
3726: next;
3727: }
3728: my %points;
3729: my %grades;
3730: foreach my $dest (keys(%fields)) {
3731: if ($dest eq 'ID' || $dest eq 'username' ||
3732: $dest eq 'domain') { next; }
3733: if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
3734: if ($dest=~/stores_(.*)_points/) {
3735: my $part=$1;
3736: my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
3737: $symb,$domain,$username);
3738: if ($wgt) {
3739: $entries{$fields{$dest}}=~s/\s//g;
3740: my $pcr=$entries{$fields{$dest}} / $wgt;
3741: my $award='correct_by_override';
3742: $grades{"resource.$part.awarded"}=$pcr;
3743: $grades{"resource.$part.solved"}=$award;
3744: $points{$part}=1;
3745: } else {
3746: $error_msg = "<br />" .
3747: &mt("Some point values were assigned"
3748: ." for problems with a weight "
3749: ."of zero. These values were "
3750: ."ignored.");
3751: }
3752: } else {
3753: if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
3754: if ($dest=~/stores_(.*)_solved/) { if ($points{$1}) {next;} }
3755: my $store_key=$dest;
3756: $store_key=~s/^stores/resource/;
3757: $store_key=~s/_/\./g;
3758: $grades{$store_key}=$entries{$fields{$dest}};
3759: }
3760: }
3761: if (! %grades) { push(@skipped,"$username:$domain no data to save"); }
3762: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
3763: # &Apache::lonnet::logthis(" storing ".(join('-',%grades)));
3764: my $result=&Apache::lonnet::cstore(\%grades,$symb,
3765: $env{'request.course.id'},
3766: $domain,$username);
3767: if ($result eq 'ok') {
3768: $request->print('.');
3769: } else {
3770: $request->print("<p>
3771: <span class=\"LC_error\">
3772: Failed to save student $username:$domain.
3773: Message when trying to save was ($result)
3774: </span>
3775: </p>" );
3776: }
3777: $request->rflush();
3778: $countdone++;
3779: }
3780: $request->print("<br />Saved $countdone students\n");
3781: if (@skipped) {
3782: $request->print('<p><h4><b>Skipped Students</b></h4></p>');
3783: foreach my $student (@skipped) { $request->print("$student<br />\n"); }
3784: }
3785: if (@notallowed) {
3786: $request->print('<p><span class="LC_error">Students Not Allowed to Modify</span></p>');
3787: foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
3788: }
3789: $request->print("<br />\n");
3790: $request->print(&show_grading_menu_form($symb));
3791: return $error_msg;
3792: }
3793: #------------- end of section for handling csv file upload ---------
3794: #
3795: #-------------------------------------------------------------------
3796: #
3797: #-------------- Next few routines handle grading by page/sequence
3798: #
3799: #--- Select a page/sequence and a student to grade
3800: sub pickStudentPage {
3801: my ($request) = shift;
3802:
3803: $request->print(<<LISTJAVASCRIPT);
3804: <script type="text/javascript" language="javascript">
3805:
3806: function checkPickOne(formname) {
3807: if (radioSelection(formname.student) == null) {
3808: alert("Please select the student you wish to grade.");
3809: return;
3810: }
3811: ptr = pullDownSelection(formname.selectpage);
3812: formname.page.value = formname["page"+ptr].value;
3813: formname.title.value = formname["title"+ptr].value;
3814: formname.submit();
3815: }
3816:
3817: </script>
3818: LISTJAVASCRIPT
3819: &commonJSfunctions($request);
3820: my ($symb) = &get_symb($request);
3821: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
3822: my $cnum = $env{"course.$env{'request.course.id'}.num"};
3823: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
3824:
3825: my $result='<h3><span class="LC_info"> '.
3826: 'Manual Grading by Page or Sequence</span></h3>';
3827:
3828: $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
3829: $result.=' <b>Problems from:</b> <select name="selectpage">'."\n";
3830: my ($titles,$symbx) = &getSymbMap();
3831: my ($curpage) =&Apache::lonnet::decode_symb($symb);
3832: # my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb);
3833: # my $type=($curpage =~ /\.(page|sequence)/);
3834: my $ctr=0;
3835: foreach (@$titles) {
3836: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
3837: $result.='<option value="'.$ctr.'" '.
3838: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
3839: '>'.$showtitle.'</option>'."\n";
3840: $ctr++;
3841: }
3842: $result.= '</select>'."<br />\n";
3843: $ctr=0;
3844: foreach (@$titles) {
3845: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
3846: $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
3847: $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
3848: $ctr++;
3849: }
3850: $result.='<input type="hidden" name="page" />'."\n".
3851: '<input type="hidden" name="title" />'."\n";
3852:
3853: $result.=' <b>View Problems Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
3854: '<label><input type="radio" name="vProb" value="yes" /> yes </label>'."<br />\n";
3855:
3856: $result.=' <b>Submission Details: </b>'.
3857: '<label><input type="radio" name="lastSub" value="none" /> none</label>'."\n".
3858: '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> by dates and submissions</label>'."\n".
3859: '<label><input type="radio" name="lastSub" value="all" /> all details</label>'."\n";
3860:
3861: $result.='<input type="hidden" name="section" value="'.$getsec.'" />'."\n".
3862: '<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n".
3863: '<input type="hidden" name="command" value="displayPage" />'."\n".
3864: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
3865: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
3866:
3867: $result.=' <b>'.&mt('Use CODE:').' </b>'.
3868: '<input type="text" name="CODE" value="" /><br />'."\n";
3869:
3870: $result.=' <input type="button" '.
3871: 'onClick="javascript:checkPickOne(this.form);"value="Next->" /><br />'."\n";
3872:
3873: $request->print($result);
3874:
3875: my $studentTable.=' <b>Select a student you wish to grade and then click on the Next button.</b><br />'.
3876: '<table border="0"><tr><td bgcolor="#777777">'.
3877: '<table border="0"><tr bgcolor="#e6ffff">'.
3878: '<td align="right"> <b>No.</b></td>'.
3879: '<td>'.&nameUserString('header').'</td>'.
3880: '<td align="right"> <b>No.</b></td>'.
3881: '<td>'.&nameUserString('header').'</td></tr>';
3882:
3883: my (undef,undef,$fullname) = &getclasslist($getsec,'1');
3884: my $ptr = 1;
3885: foreach my $student (sort
3886: {
3887: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
3888: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
3889: }
3890: return $a cmp $b;
3891: } (keys(%$fullname))) {
3892: my ($uname,$udom) = split(/:/,$student);
3893: $studentTable.=($ptr%2 == 1 ? '<tr bgcolor="#ffffe6">' : '</td>');
3894: $studentTable.='<td align="right">'.$ptr.' </td>';
3895: $studentTable.='<td> <label><input type="radio" name="student" value="'.$student.'" /> '
3896: .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
3897: $studentTable.=($ptr%2 == 0 ? '</td></tr>' : '');
3898: $ptr++;
3899: }
3900: $studentTable.='</td><td> </td><td> </td></tr>' if ($ptr%2 == 0);
3901: $studentTable.='</table></td></tr></table>'."\n";
3902: $studentTable.='<input type="button" '.
3903: 'onClick="javascript:checkPickOne(this.form);"value="Next->" /></form>'."\n";
3904:
3905: $studentTable.=&show_grading_menu_form($symb);
3906: $request->print($studentTable);
3907:
3908: return '';
3909: }
3910:
3911: sub getSymbMap {
3912: my $navmap = Apache::lonnavmaps::navmap->new();
3913:
3914: my %symbx = ();
3915: my @titles = ();
3916: my $minder = 0;
3917:
3918: # Gather every sequence that has problems.
3919: my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
3920: 1,0,1);
3921: for my $sequence ($navmap->getById('0.0'), @sequences) {
3922: if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
3923: my $title = $minder.'.'.
3924: &HTML::Entities::encode($sequence->compTitle(),'"\'&');
3925: push(@titles, $title); # minder in case two titles are identical
3926: $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
3927: $minder++;
3928: }
3929: }
3930: return \@titles,\%symbx;
3931: }
3932:
3933: #
3934: #--- Displays a page/sequence w/wo problems, w/wo submissions
3935: sub displayPage {
3936: my ($request) = shift;
3937:
3938: my ($symb) = &get_symb($request);
3939: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
3940: my $cnum = $env{"course.$env{'request.course.id'}.num"};
3941: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
3942: my $pageTitle = $env{'form.page'};
3943: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
3944: my ($uname,$udom) = split(/:/,$env{'form.student'});
3945: my $usec=$classlist->{$env{'form.student'}}[5];
3946:
3947: #need to make sure we have the correct data for later EXT calls,
3948: #thus invalidate the cache
3949: &Apache::lonnet::devalidatecourseresdata(
3950: $env{'course.'.$env{'request.course.id'}.'.num'},
3951: $env{'course.'.$env{'request.course.id'}.'.domain'});
3952: &Apache::lonnet::clear_EXT_cache_status();
3953:
3954: if (!&canview($usec)) {
3955: $request->print('<span class="LC_warning">Unable to view requested student.('.$env{'form.student'}.')</span>');
3956: $request->print(&show_grading_menu_form($symb));
3957: return;
3958: }
3959: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
3960: $result.='<h3> Student: '.&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom).
3961: '</h3>'."\n";
3962: if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
3963: $result.='<h3> CODE: '.$env{'form.CODE'}.'</h3>'."\n";
3964: } else {
3965: delete($env{'form.CODE'});
3966: }
3967: &sub_page_js($request);
3968: $request->print($result);
3969:
3970: my $navmap = Apache::lonnavmaps::navmap->new();
3971: my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
3972: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
3973: if (!$map) {
3974: $request->print('<span class="LC_warning">Unable to view requested sequence. ('.$resUrl.')</span>');
3975: $request->print(&show_grading_menu_form($symb));
3976: return;
3977: }
3978: my $iterator = $navmap->getIterator($map->map_start(),
3979: $map->map_finish());
3980:
3981: my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
3982: '<input type="hidden" name="command" value="gradeByPage" />'."\n".
3983: '<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
3984: '<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
3985: '<input type="hidden" name="page" value="'.$pageTitle.'" />'."\n".
3986: '<input type="hidden" name="title" value="'.$env{'form.title'}.'" />'."\n".
3987: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
3988: '<input type="hidden" name="overRideScore" value="no" />'."\n".
3989: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
3990:
3991: if (defined($env{'form.CODE'})) {
3992: $studentTable.=
3993: '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
3994: }
3995: my $checkIcon = '<img alt="'.&mt('Check Mark').
3996: '" src="'.$request->dir_config('lonIconsURL').
3997: '/check.gif" height="16" border="0" />';
3998:
3999: $studentTable.=' <b>Note:</b> Problems graded correct by the computer are marked with a '.$checkIcon.
4000: ' symbol.'."\n".
4001: '<table border="0"><tr><td bgcolor="#777777">'.
4002: '<table border="0"><tr bgcolor="#e6ffff">'.
4003: '<td align="center"><b> Prob. </b></td>'.
4004: '<td><b> '.($env{'form.vProb'} eq 'no' ? 'Title' : 'Problem Text').'/Grade</b></td></tr>';
4005:
4006: &Apache::lonxml::clear_problem_counter();
4007: my ($depth,$question,$prob) = (1,1,1);
4008: $iterator->next(); # skip the first BEGIN_MAP
4009: my $curRes = $iterator->next(); # for "current resource"
4010: while ($depth > 0) {
4011: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
4012: if($curRes == $iterator->END_MAP) { $depth--; }
4013:
4014: if (ref($curRes) && $curRes->is_problem()) {
4015: my $parts = $curRes->parts();
4016: my $title = $curRes->compTitle();
4017: my $symbx = $curRes->symb();
4018: $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
4019: (scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).' parts)').'</td>';
4020: $studentTable.='<td valign="top">';
4021: my %form = ('CODE' => $env{'form.CODE'},);
4022: if ($env{'form.vProb'} eq 'yes' ) {
4023: $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
4024: undef,'both',\%form);
4025: } else {
4026: my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
4027: $companswer =~ s|<form(.*?)>||g;
4028: $companswer =~ s|</form>||g;
4029: # while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
4030: # $companswer =~ s/$1/ /ms;
4031: # $request->print('match='.$1."<br />\n");
4032: # }
4033: # $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
4034: $studentTable.=' <b>'.$title.'</b> <br /> <b>Correct answer:</b><br />'.$companswer;
4035: }
4036:
4037: my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
4038:
4039: if ($env{'form.lastSub'} eq 'datesub') {
4040: if ($record{'version'} eq '') {
4041: $studentTable.='<br /> <span class="LC_warning">No recorded submission for this problem</span><br />';
4042: } else {
4043: my %responseType = ();
4044: foreach my $partid (@{$parts}) {
4045: my @responseIds =$curRes->responseIds($partid);
4046: my @responseType =$curRes->responseType($partid);
4047: my %responseIds;
4048: for (my $i=0;$i<=$#responseIds;$i++) {
4049: $responseIds{$responseIds[$i]}=$responseType[$i];
4050: }
4051: $responseType{$partid} = \%responseIds;
4052: }
4053: $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
4054:
4055: }
4056: } elsif ($env{'form.lastSub'} eq 'all') {
4057: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
4058: $studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
4059: $env{'request.course.id'},
4060: '','.submission');
4061:
4062: }
4063: if (&canmodify($usec)) {
4064: foreach my $partid (@{$parts}) {
4065: $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
4066: $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
4067: $question++;
4068: }
4069: $prob++;
4070: }
4071: $studentTable.='</td></tr>';
4072:
4073: }
4074: $curRes = $iterator->next();
4075: }
4076:
4077: $studentTable.='</table></td></tr></table>'."\n".
4078: '<input type="button" value="Save" '.
4079: 'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
4080: '</form>'."\n";
4081: $studentTable.=&show_grading_menu_form($symb);
4082: $request->print($studentTable);
4083:
4084: return '';
4085: }
4086:
4087: sub displaySubByDates {
4088: my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
4089: my $isCODE=0;
4090: my $isTask = ($symb =~/\.task$/);
4091: if (exists($record->{'resource.CODE'})) { $isCODE=1; }
4092: my $studentTable='<table border="0" width="100%"><tr><td bgcolor="#777777">'.
4093: '<table border="0" width="100%"><tr bgcolor="#e6ffff">'.
4094: '<td><b>Date/Time</b></td>'.
4095: ($isCODE?'<td><b>CODE</b></td>':'').
4096: '<td><b>Submission</b></td>'.
4097: '<td><b>Status </b></td></tr>';
4098: my ($version);
4099: my %mark;
4100: my %orders;
4101: $mark{'correct_by_student'} = $checkIcon;
4102: if (!exists($$record{'1:timestamp'})) {
4103: return '<br /> <span class="LC_warning">Nothing submitted - no attempts</span><br />';
4104: }
4105:
4106: my $interaction;
4107: for ($version=1;$version<=$$record{'version'};$version++) {
4108: my $timestamp = scalar(localtime($$record{$version.':timestamp'}));
4109: if (exists($$record{$version.':resource.0.version'})) {
4110: $interaction = $$record{$version.':resource.0.version'};
4111: }
4112:
4113: my $where = ($isTask ? "$version:resource.$interaction"
4114: : "$version:resource");
4115: #&Apache::lonnet::logthis(" got $where");
4116: $studentTable.='<tr bgcolor="#ffffff" valign="top"><td>'.$timestamp.'</td>';
4117: if ($isCODE) {
4118: $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
4119: }
4120: my @versionKeys = split(/\:/,$$record{$version.':keys'});
4121: my @displaySub = ();
4122: foreach my $partid (@{$parts}) {
4123: my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
4124: : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
4125:
4126:
4127: # next if ($$record{"$version:resource.$partid.solved"} eq '');
4128: my $display_part=&get_display_part($partid,$symb);
4129: foreach my $matchKey (@matchKey) {
4130: if (exists($$record{$version.':'.$matchKey}) &&
4131: $$record{$version.':'.$matchKey} ne '') {
4132:
4133: my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
4134: : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
4135: #&Apache::lonnet::logthis("match $matchKey $responseId (".$$record{$version.':'.$matchKey});
4136: $displaySub[0].='<b>Part:</b> '.$display_part.' ';
4137: $displaySub[0].='<span class="LC_internal_info">(ID '.
4138: $responseId.')</span> <b>';
4139: if ($$record{"$where.$partid.tries"} eq '') {
4140: $displaySub[0].='Trial not counted';
4141: } else {
4142: $displaySub[0].='Trial '.
4143: $$record{"$where.$partid.tries"};
4144: }
4145: my $responseType=($isTask ? 'Task'
4146: : $responseType->{$partid}->{$responseId});
4147: if (!exists($orders{$partid})) { $orders{$partid}={}; }
4148: if (!exists($orders{$partid}->{$responseId})) {
4149: $orders{$partid}->{$responseId}=
4150: &get_order($partid,$responseId,$symb,$uname,$udom);
4151: }
4152: $displaySub[0].='</b> '.
4153: &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
4154: }
4155: }
4156: if (exists($$record{"$where.$partid.checkedin"})) {
4157: $displaySub[1].='Checked in by '.
4158: $$record{"$where.$partid.checkedin"}.' into slot '.
4159: $$record{"$where.$partid.checkedin.slot"}.
4160: '<br />';
4161: }
4162: if (exists $$record{"$where.$partid.award"}) {
4163: $displaySub[1].='<b>Part:</b> '.$display_part.' '.
4164: lc($$record{"$where.$partid.award"}).' '.
4165: $mark{$$record{"$where.$partid.solved"}}.
4166: '<br />';
4167: }
4168: if (exists $$record{"$where.$partid.regrader"}) {
4169: $displaySub[2].=$$record{"$where.$partid.regrader"}.
4170: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
4171: } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
4172: $displaySub[2].=
4173: $$record{"$version:resource.$partid.regrader"}.
4174: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
4175: }
4176: }
4177: # needed because old essay regrader has not parts info
4178: if (exists $$record{"$version:resource.regrader"}) {
4179: $displaySub[2].=$$record{"$version:resource.regrader"};
4180: }
4181: $studentTable.='<td>'.$displaySub[0].' </td><td>'.$displaySub[1];
4182: if ($displaySub[2]) {
4183: $studentTable.='Manually graded by '.$displaySub[2];
4184: }
4185: $studentTable.=' </td></tr>';
4186:
4187: }
4188: $studentTable.='</table></td></tr></table>';
4189: return $studentTable;
4190: }
4191:
4192: sub updateGradeByPage {
4193: my ($request) = shift;
4194:
4195: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4196: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4197: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4198: my $pageTitle = $env{'form.page'};
4199: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
4200: my ($uname,$udom) = split(/:/,$env{'form.student'});
4201: my $usec=$classlist->{$env{'form.student'}}[5];
4202: if (!&canmodify($usec)) {
4203: $request->print('<span class="LC_warning">Unable to modify requested student.('.$env{'form.student'}.'</span>');
4204: $request->print(&show_grading_menu_form($env{'form.symb'}));
4205: return;
4206: }
4207: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
4208: $result.='<h3> Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
4209: '</h3>'."\n";
4210:
4211: $request->print($result);
4212:
4213: my $navmap = Apache::lonnavmaps::navmap->new();
4214: my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
4215: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
4216: if (!$map) {
4217: $request->print('<span class="LC_warning">Unable to grade requested sequence. ('.$resUrl.')</span>');
4218: my ($symb)=&get_symb($request);
4219: $request->print(&show_grading_menu_form($symb));
4220: return;
4221: }
4222: my $iterator = $navmap->getIterator($map->map_start(),
4223: $map->map_finish());
4224:
4225: my $studentTable='<table border="0"><tr><td bgcolor="#777777">'.
4226: '<table border="0"><tr bgcolor="#e6ffff">'.
4227: '<td align="center"><b> Prob. </b></td>'.
4228: '<td><b> Title </b></td>'.
4229: '<td><b> Previous Score </b></td>'.
4230: '<td><b> New Score </b></td></tr>';
4231:
4232: $iterator->next(); # skip the first BEGIN_MAP
4233: my $curRes = $iterator->next(); # for "current resource"
4234: my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
4235: while ($depth > 0) {
4236: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
4237: if($curRes == $iterator->END_MAP) { $depth--; }
4238:
4239: if (ref($curRes) && $curRes->is_problem()) {
4240: my $parts = $curRes->parts();
4241: my $title = $curRes->compTitle();
4242: my $symbx = $curRes->symb();
4243: $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
4244: (scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).' parts)').'</td>';
4245: $studentTable.='<td valign="top"> <b>'.$title.'</b> </td>';
4246:
4247: my %newrecord=();
4248: my @displayPts=();
4249: my %aggregate = ();
4250: my $aggregateflag = 0;
4251: foreach my $partid (@{$parts}) {
4252: my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
4253: my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
4254:
4255: my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ?
4256: $env{'form.WGT'.$question.'_'.$partid} : 1;
4257: my $partial = $newpts/$wgt;
4258: my $score;
4259: if ($partial > 0) {
4260: $score = 'correct_by_override';
4261: } elsif ($newpts ne '') { #empty is taken as 0
4262: $score = 'incorrect_by_override';
4263: }
4264: my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
4265: if ($dropMenu eq 'excused') {
4266: $partial = '';
4267: $score = 'excused';
4268: } elsif ($dropMenu eq 'reset status'
4269: && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
4270: $newrecord{'resource.'.$partid.'.tries'} = 0;
4271: $newrecord{'resource.'.$partid.'.solved'} = '';
4272: $newrecord{'resource.'.$partid.'.award'} = '';
4273: $newrecord{'resource.'.$partid.'.awarded'} = 0;
4274: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
4275: $changeflag++;
4276: $newpts = '';
4277:
4278: my $aggtries = $env{'form.aggtries'.$question.'_'.$partid};
4279: my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
4280: my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
4281: if ($aggtries > 0) {
4282: &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
4283: $aggregateflag = 1;
4284: }
4285: }
4286: my $display_part=&get_display_part($partid,$curRes->symb());
4287: my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
4288: $displayPts[0].=' <b>Part:</b> '.$display_part.' = '.
4289: (($oldstatus eq 'excused') ? 'excused' : $oldpts).
4290: ' <br />';
4291: $displayPts[1].=' <b>Part:</b> '.$display_part.' = '.
4292: (($score eq 'excused') ? 'excused' : $newpts).
4293: ' <br />';
4294: $question++;
4295: next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
4296:
4297: $newrecord{'resource.'.$partid.'.awarded'} = $partial if $partial ne '';
4298: $newrecord{'resource.'.$partid.'.solved'} = $score if $score ne '';
4299: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
4300: if (scalar(keys(%newrecord)) > 0);
4301:
4302: $changeflag++;
4303: }
4304: if (scalar(keys(%newrecord)) > 0) {
4305: my %record =
4306: &Apache::lonnet::restore($symbx,$env{'request.course.id'},
4307: $udom,$uname);
4308:
4309: if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
4310: $newrecord{'resource.CODE'} = $env{'form.CODE'};
4311: } elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
4312: $newrecord{'resource.CODE'} = '';
4313: }
4314: &Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
4315: $udom,$uname);
4316: %record = &Apache::lonnet::restore($symbx,
4317: $env{'request.course.id'},
4318: $udom,$uname);
4319: &check_and_remove_from_queue($parts,\%record,undef,$symbx,
4320: $cdom,$cnum,$udom,$uname);
4321: }
4322:
4323: if ($aggregateflag) {
4324: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
4325: $env{'course.'.$env{'request.course.id'}.'.domain'},
4326: $env{'course.'.$env{'request.course.id'}.'.num'});
4327: }
4328:
4329: $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
4330: '<td valign="top">'.$displayPts[1].'</td>'.
4331: '</tr>';
4332:
4333: $prob++;
4334: }
4335: $curRes = $iterator->next();
4336: }
4337:
4338: $studentTable.='</td></tr></table></td></tr></table>';
4339: $studentTable.=&show_grading_menu_form($env{'form.symb'});
4340: my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
4341: 'The scores were changed for '.
4342: $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
4343: $request->print($grademsg.$studentTable);
4344:
4345: return '';
4346: }
4347:
4348: #-------- end of section for handling grading by page/sequence ---------
4349: #
4350: #-------------------------------------------------------------------
4351:
4352: #--------------------Scantron Grading-----------------------------------
4353: #
4354: #------ start of section for handling grading by page/sequence ---------
4355:
4356: =pod
4357:
4358: =head1 Bubble sheet grading routines
4359:
4360: (For this documentation 'scanline' refers to the full line of characters
4361: from the file that we are parsing 'bubble line' refers to the data
4362: representing the line of bubbles that are on the physical bubble sheet)
4363:
4364: =over 4
4365:
4366: =cut
4367:
4368:
4369: =pod
4370:
4371: =item defaultFormData
4372:
4373: Returns html hidden inputs used to hold context/default values.
4374:
4375: Arguments:
4376: $symb - $symb of the current resource
4377:
4378: =cut
4379:
4380: sub defaultFormData {
4381: my ($symb)=@_;
4382: return '
4383: <input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
4384: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
4385: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
4386: }
4387:
4388: =pod
4389:
4390: =item getSequenceDropDown
4391:
4392: Return html dropdown of possible sequences to grade
4393:
4394: Arguments:
4395: $symb - $symb of the current resource
4396:
4397: =cut
4398:
4399: sub getSequenceDropDown {
4400: my ($symb)=@_;
4401: my $result='<select name="selectpage">'."\n";
4402: my ($titles,$symbx) = &getSymbMap();
4403: my ($curpage)=&Apache::lonnet::decode_symb($symb);
4404: my $ctr=0;
4405: foreach (@$titles) {
4406: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4407: $result.='<option value="'.$$symbx{$_}.'" '.
4408: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
4409: '>'.$showtitle.'</option>'."\n";
4410: $ctr++;
4411: }
4412: $result.= '</select>';
4413: return $result;
4414: }
4415:
4416:
4417: =pod
4418:
4419: =item scantron_filenames
4420:
4421: Returns a list of the scantron files in the current course
4422:
4423: =cut
4424:
4425: sub scantron_filenames {
4426: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4427: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
4428: my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
4429: &propath($cdom,$cname));
4430: my @possiblenames;
4431: foreach my $filename (sort(@files)) {
4432: ($filename)=split(/&/,$filename);
4433: if ($filename!~/^scantron_orig_/) { next ; }
4434: $filename=~s/^scantron_orig_//;
4435: push(@possiblenames,$filename);
4436: }
4437: return @possiblenames;
4438: }
4439:
4440: =pod
4441:
4442: =item scantron_uploads
4443:
4444: Returns html drop-down list of scantron files in current course.
4445:
4446: Arguments:
4447: $file2grade - filename to set as selected in the dropdown
4448:
4449: =cut
4450:
4451: sub scantron_uploads {
4452: my ($file2grade) = @_;
4453: my $result= '<select name="scantron_selectfile">';
4454: $result.="<option></option>";
4455: foreach my $filename (sort(&scantron_filenames())) {
4456: $result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
4457: }
4458: $result.="</select>";
4459: return $result;
4460: }
4461:
4462: =pod
4463:
4464: =item scantron_scantab
4465:
4466: Returns html drop down of the scantron formats in the scantronformat.tab
4467: file.
4468:
4469: =cut
4470:
4471: sub scantron_scantab {
4472: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
4473: my $result='<select name="scantron_format">'."\n";
4474: $result.='<option></option>'."\n";
4475: foreach my $line (<$fh>) {
4476: my ($name,$descrip)=split(/:/,$line);
4477: if ($name =~ /^\#/) { next; }
4478: $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
4479: }
4480: $result.='</select>'."\n";
4481:
4482: return $result;
4483: }
4484:
4485: =pod
4486:
4487: =item scantron_CODElist
4488:
4489: Returns html drop down of the saved CODE lists from current course,
4490: generated from earlier printings.
4491:
4492: =cut
4493:
4494: sub scantron_CODElist {
4495: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4496: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4497: my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
4498: my $namechoice='<option></option>';
4499: foreach my $name (sort {uc($a) cmp uc($b)} @names) {
4500: if ($name =~ /^error: 2 /) { next; }
4501: if ($name =~ /^type\0/) { next; }
4502: $namechoice.='<option value="'.$name.'">'.$name.'</option>';
4503: }
4504: $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
4505: return $namechoice;
4506: }
4507:
4508: =pod
4509:
4510: =item scantron_CODEunique
4511:
4512: Returns the html for "Each CODE to be used once" radio.
4513:
4514: =cut
4515:
4516: sub scantron_CODEunique {
4517: my $result='<span style="white-space: nowrap;">
4518: <label><input type="radio" name="scantron_CODEunique"
4519: value="yes" checked="checked" />'.&mt('Yes').' </label>
4520: </span>
4521: <span style="white-space: nowrap;">
4522: <label><input type="radio" name="scantron_CODEunique"
4523: value="no" />'.&mt('No').' </label>
4524: </span>';
4525: return $result;
4526: }
4527:
4528: =pod
4529:
4530: =item scantron_selectphase
4531:
4532: Generates the initial screen to start the bubble sheet process.
4533: Allows for - starting a grading run.
4534: - downloading exisiting scan data (original, corrected
4535: or skipped info)
4536:
4537: - uploading new scan data
4538:
4539: Arguments:
4540: $r - The Apache request object
4541: $file2grade - name of the file that contain the scanned data to score
4542:
4543: =cut
4544:
4545: sub scantron_selectphase {
4546: my ($r,$file2grade) = @_;
4547: my ($symb)=&get_symb($r);
4548: if (!$symb) {return '';}
4549: my $sequence_selector=&getSequenceDropDown($symb);
4550: my $default_form_data=&defaultFormData($symb);
4551: my $grading_menu_button=&show_grading_menu_form($symb);
4552: my $file_selector=&scantron_uploads($file2grade);
4553: my $format_selector=&scantron_scantab();
4554: my $CODE_selector=&scantron_CODElist();
4555: my $CODE_unique=&scantron_CODEunique();
4556: my $result;
4557:
4558: # Chunk of form to prompt for a file to grade and how:
4559:
4560: $result.= <<SCANTRONFORM;
4561: <table width="100%" border="0">
4562: <tr>
4563: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
4564: <td bgcolor="#777777">
4565: <input type="hidden" name="command" value="scantron_warning" />
4566: $default_form_data
4567: <table width="100%" border="0">
4568: <tr bgcolor="#e6ffff">
4569: <td colspan="2">
4570: <b>Specify file and which Folder/Sequence to grade</b>
4571: </td>
4572: </tr>
4573: <tr bgcolor="#ffffe6">
4574: <td> Sequence to grade: </td><td> $sequence_selector </td>
4575: </tr>
4576: <tr bgcolor="#ffffe6">
4577: <td> Filename of scoring office file: </td><td> $file_selector </td>
4578: </tr>
4579: <tr bgcolor="#ffffe6">
4580: <td> Format of data file: </td><td> $format_selector </td>
4581: </tr>
4582: <tr bgcolor="#ffffe6">
4583: <td> Saved CODEs to validate against: </td><td> $CODE_selector</td>
4584: </tr>
4585: <tr bgcolor="#ffffe6">
4586: <td> Each CODE is only to be used once:</td><td> $CODE_unique </td>
4587: </tr>
4588: <tr bgcolor="#ffffe6">
4589: <td> Options: </td>
4590: <td>
4591: <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> Do only previously skipped records</label> <br />
4592: <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> Remove all exisiting corrections</label> <br />
4593: <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> Skip hidden resources when grading</label>
4594: </td>
4595: </tr>
4596: <tr bgcolor="#ffffe6">
4597: <td colspan="2">
4598: <input type="submit" value="Grading: Validate Scantron Records" />
4599: </td>
4600: </tr>
4601: </table>
4602: </td>
4603: </form>
4604: </tr>
4605: SCANTRONFORM
4606:
4607: $r->print($result);
4608:
4609: if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
4610: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
4611:
4612: # Chunk of form to prompt for a scantron file upload.
4613:
4614: $r->print(<<SCANTRONFORM);
4615: <tr>
4616: <td bgcolor="#777777">
4617: <table width="100%" border="0">
4618: <tr bgcolor="#e6ffff">
4619: <td>
4620: <b>Specify a Scantron data file to upload.</b>
4621: </td>
4622: </tr>
4623: <tr bgcolor="#ffffe6">
4624: <td>
4625: SCANTRONFORM
4626: my $default_form_data=&defaultFormData(&get_symb($r,1));
4627: my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
4628: my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
4629: $r->print(<<UPLOAD);
4630: <script type="text/javascript" language="javascript">
4631: function checkUpload(formname) {
4632: if (formname.upfile.value == "") {
4633: alert("Please use the browse button to select a file from your local directory.");
4634: return false;
4635: }
4636: formname.submit();
4637: }
4638: </script>
4639:
4640: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
4641: $default_form_data
4642: <input name='courseid' type='hidden' value='$cnum' />
4643: <input name='domainid' type='hidden' value='$cdom' />
4644: <input name='command' value='scantronupload_save' type='hidden' />
4645: File to upload:<input type="file" name="upfile" size="50" />
4646: <br />
4647: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
4648: </form>
4649: UPLOAD
4650:
4651: $r->print(<<SCANTRONFORM);
4652: </td>
4653: </tr>
4654: </table>
4655: </td>
4656: </tr>
4657: SCANTRONFORM
4658: }
4659:
4660: # Chunk of the form that prompts to view a scoring office file,
4661: # corrected file, skipped records in a file.
4662:
4663: $r->print(<<SCANTRONFORM);
4664: <tr>
4665: <form action='/adm/grades' name='scantron_download'>
4666: <td bgcolor="#777777">
4667: $default_form_data
4668: <input type="hidden" name="command" value="scantron_download" />
4669: <table width="100%" border="0">
4670: <tr bgcolor="#e6ffff">
4671: <td colspan="2">
4672: <b>Download a scoring office file</b>
4673: </td>
4674: </tr>
4675: <tr bgcolor="#ffffe6">
4676: <td> Filename of scoring office file: </td><td> $file_selector </td>
4677: </tr>
4678: <tr bgcolor="#ffffe6">
4679: <td colspan="2">
4680: <input type="submit" value="Download: Show List of Associated Files" />
4681: </td>
4682: </tr>
4683: </table>
4684: </td>
4685: </form>
4686: </tr>
4687: SCANTRONFORM
4688:
4689: $r->print(<<SCANTRONFORM);
4690: </table>
4691: $grading_menu_button
4692: SCANTRONFORM
4693:
4694: return
4695: }
4696:
4697: =pod
4698:
4699: =item get_scantron_config
4700:
4701: Parse and return the scantron configuration line selected as a
4702: hash of configuration file fields.
4703:
4704: Arguments:
4705: which - the name of the configuration to parse from the file.
4706:
4707:
4708: Returns:
4709: If the named configuration is not in the file, an empty
4710: hash is returned.
4711: a hash with the fields
4712: name - internal name for the this configuration setup
4713: description - text to display to operator that describes this config
4714: CODElocation - if 0 or the string 'none'
4715: - no CODE exists for this config
4716: if -1 || the string 'letter'
4717: - a CODE exists for this config and is
4718: a string of letters
4719: Unsupported value (but planned for future support)
4720: if a positive integer
4721: - The CODE exists as the first n items from
4722: the question section of the form
4723: if the string 'number'
4724: - The CODE exists for this config and is
4725: a string of numbers
4726: CODEstart - (only matter if a CODE exists) column in the line where
4727: the CODE starts
4728: CODElength - length of the CODE
4729: IDstart - column where the student ID number starts
4730: IDlength - length of the student ID info
4731: Qstart - column where the information from the bubbled
4732: 'questions' start
4733: Qlength - number of columns comprising a single bubble line from
4734: the sheet. (usually either 1 or 10)
4735: Qon - either a single charater representing the character used
4736: to signal a bubble was chosen in the positional setup, or
4737: the string 'letter' if the letter of the chosen bubble is
4738: in the final, or 'number' if a number representing the
4739: chosen bubble is in the file (1->A 0->J)
4740: Qoff - the character used to represent that a buble was left blank
4741: PaperID - if the scanning process generates a unique number for each
4742: sheet scanned the column that this ID number starts in
4743: PaperIDlength - number of columns that comprise the unique ID number
4744: for the sheet of paper
4745: FirstName - column that the firs tname starts in
4746: FirstNameLength - number of columns that the first name spans
4747:
4748: LastName - column that the last name starts in
4749: LastNameLength - number of columns that the last name spans
4750:
4751: =cut
4752:
4753: sub get_scantron_config {
4754: my ($which) = @_;
4755: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
4756: my %config;
4757: #FIXME probably should move to XML it has already gotten a bit much now
4758: foreach my $line (<$fh>) {
4759: my ($name,$descrip)=split(/:/,$line);
4760: if ($name ne $which ) { next; }
4761: chomp($line);
4762: my @config=split(/:/,$line);
4763: $config{'name'}=$config[0];
4764: $config{'description'}=$config[1];
4765: $config{'CODElocation'}=$config[2];
4766: $config{'CODEstart'}=$config[3];
4767: $config{'CODElength'}=$config[4];
4768: $config{'IDstart'}=$config[5];
4769: $config{'IDlength'}=$config[6];
4770: $config{'Qstart'}=$config[7];
4771: $config{'Qlength'}=$config[8];
4772: $config{'Qoff'}=$config[9];
4773: $config{'Qon'}=$config[10];
4774: $config{'PaperID'}=$config[11];
4775: $config{'PaperIDlength'}=$config[12];
4776: $config{'FirstName'}=$config[13];
4777: $config{'FirstNamelength'}=$config[14];
4778: $config{'LastName'}=$config[15];
4779: $config{'LastNamelength'}=$config[16];
4780: last;
4781: }
4782: return %config;
4783: }
4784:
4785: =pod
4786:
4787: =item username_to_idmap
4788:
4789: creates a hash keyed by student id with values of the corresponding
4790: student username:domain.
4791:
4792: Arguments:
4793:
4794: $classlist - reference to the class list hash. This is a hash
4795: keyed by student name:domain whose elements are references
4796: to arrays containng various chunks of information
4797: about the student. (See loncoursedata for more info).
4798:
4799: Returns
4800: %idmap - the constructed hash
4801:
4802: =cut
4803:
4804: sub username_to_idmap {
4805: my ($classlist)= @_;
4806: my %idmap;
4807: foreach my $student (keys(%$classlist)) {
4808: $idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
4809: $student;
4810: }
4811: return %idmap;
4812: }
4813:
4814: =pod
4815:
4816: =item scatron_fixup_scanline
4817:
4818: Process a requested correction to a scanline.
4819:
4820: Arguments:
4821: $scantron_config - hash from &get_scantron_config()
4822: $scan_data - hash of correction information
4823: (see &scantron_getfile())
4824: $line - existing scanline
4825: $whichline - line number of the passed in scanline
4826: $field - type of change to process
4827: (either
4828: 'ID' -> correct the student ID number
4829: 'CODE' -> correct the CODE
4830: 'answer' -> fixup the submitted answers)
4831:
4832: $args - hash of additional info,
4833: - 'ID'
4834: 'newid' -> studentID to use in replacement
4835: of exisiting one
4836: - 'CODE'
4837: 'CODE_ignore_dup' - set to true if duplicates
4838: should be ignored.
4839: 'CODE' - is new code or 'use_unfound'
4840: if the exisitng unfound code should
4841: be used as is
4842: - 'answer'
4843: 'response' - new answer or 'none' if blank
4844: 'question' - the bubble line to change
4845:
4846: Returns:
4847: $line - the modified scanline
4848:
4849: Side effects:
4850: $scan_data - may be updated
4851:
4852: =cut
4853:
4854:
4855: sub scantron_fixup_scanline {
4856: my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
4857:
4858: if ($field eq 'ID') {
4859: if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
4860: return ($line,1,'New value too large');
4861: }
4862: if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
4863: $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
4864: $args->{'newid'});
4865: }
4866: substr($line,$$scantron_config{'IDstart'}-1,
4867: $$scantron_config{'IDlength'})=$args->{'newid'};
4868: if ($args->{'newid'}=~/^\s*$/) {
4869: &scan_data($scan_data,"$whichline.user",
4870: $args->{'username'}.':'.$args->{'domain'});
4871: }
4872: } elsif ($field eq 'CODE') {
4873: if ($args->{'CODE_ignore_dup'}) {
4874: &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
4875: }
4876: &scan_data($scan_data,"$whichline.useCODE",'1');
4877: if ($args->{'CODE'} ne 'use_unfound') {
4878: if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
4879: return ($line,1,'New CODE value too large');
4880: }
4881: if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
4882: $args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
4883: }
4884: substr($line,$$scantron_config{'CODEstart'}-1,
4885: $$scantron_config{'CODElength'})=$args->{'CODE'};
4886: }
4887: } elsif ($field eq 'answer') {
4888: my $length=$scantron_config->{'Qlength'};
4889: my $off=$scantron_config->{'Qoff'};
4890: my $on=$scantron_config->{'Qon'};
4891: my $answer=${off}x$length;
4892: if ($args->{'response'} eq 'none') {
4893: &scan_data($scan_data,
4894: "$whichline.no_bubble.".$args->{'question'},'1');
4895: } else {
4896: if ($on eq 'letter') {
4897: my @alphabet=('A'..'Z');
4898: $answer=$alphabet[$args->{'response'}];
4899: } elsif ($on eq 'number') {
4900: $answer=$args->{'response'}+1;
4901: if ($answer == 10) { $answer = '0'; }
4902: } else {
4903: substr($answer,$args->{'response'},1)=$on;
4904: }
4905: &scan_data($scan_data,
4906: "$whichline.no_bubble.".$args->{'question'},undef,'1');
4907: }
4908: my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
4909: substr($line,$where-1,$length)=$answer;
4910: }
4911: return $line;
4912: }
4913:
4914: =pod
4915:
4916: =item scan_data
4917:
4918: Edit or look up an item in the scan_data hash.
4919:
4920: Arguments:
4921: $scan_data - The hash (see scantron_getfile)
4922: $key - shorthand of the key to edit (actual key is
4923: scatronfilename_key).
4924: $data - New value of the hash entry.
4925: $delete - If true, the entry is removed from the hash.
4926:
4927: Returns:
4928: The new value of the hash table field (undefined if deleted).
4929:
4930: =cut
4931:
4932:
4933: sub scan_data {
4934: my ($scan_data,$key,$value,$delete)=@_;
4935: my $filename=$env{'form.scantron_selectfile'};
4936: if (defined($value)) {
4937: $scan_data->{$filename.'_'.$key} = $value;
4938: }
4939: if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
4940: return $scan_data->{$filename.'_'.$key};
4941: }
4942:
4943: =pod
4944:
4945: =item scantron_parse_scanline
4946:
4947: Decodes a scanline from the selected scantron file
4948:
4949: Arguments:
4950: line - The text of the scantron file line to process
4951: whichline - Line number
4952: scantron_config - Hash describing the format of the scantron lines.
4953: scan_data - Hash of extra information about the scanline
4954: (see scantron_getfile for more information)
4955: just_header - True if should not process question answers but only
4956: the stuff to the left of the answers.
4957: Returns:
4958: Hash containing the result of parsing the scanline
4959:
4960: Keys are all proceeded by the string 'scantron.'
4961:
4962: CODE - the CODE in use for this scanline
4963: useCODE - 1 if the CODE is invalid but it usage has been forced
4964: by the operator
4965: CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
4966: CODEs were selected, but the usage has been
4967: forced by the operator
4968: ID - student ID
4969: PaperID - if used, the ID number printed on the sheet when the
4970: paper was scanned
4971: FirstName - first name from the sheet
4972: LastName - last name from the sheet
4973:
4974: if just_header was not true these key may also exist
4975:
4976: missingerror - a list of bubbled line numbers that had a blank bubble
4977: that is considered an error (if the operator had already
4978: okayed a blank bubble line as really being blank then
4979: that bubble line number won't appear here.
4980: doubleerror - a list of bubbled line numbers that had more than one
4981: bubble filled in and has not been corrected by the
4982: operator
4983: maxquest - the number of the last bubble line that was parsed
4984:
4985: (<number> starts at 1)
4986: <number>.answer - zero or more letters representing the selected
4987: letters from the scanline for the bubble line
4988: <number>.
4989: if blank there was either no bubble or there where
4990: multiple bubbles, (consult the keys missingerror and
4991: doubleerror if this is an error condition)
4992:
4993: =cut
4994:
4995: sub scantron_parse_scanline {
4996: my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
4997: my %record;
4998: my $questions=substr($line,$$scantron_config{'Qstart'}-1); # Answers
4999: my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # earlier stuff
5000: if (!($$scantron_config{'CODElocation'} eq 0 ||
5001: $$scantron_config{'CODElocation'} eq 'none')) {
5002: if ($$scantron_config{'CODElocation'} < 0 ||
5003: $$scantron_config{'CODElocation'} eq 'letter' ||
5004: $$scantron_config{'CODElocation'} eq 'number') {
5005: $record{'scantron.CODE'}=substr($data,
5006: $$scantron_config{'CODEstart'}-1,
5007: $$scantron_config{'CODElength'});
5008: if (&scan_data($scan_data,"$whichline.useCODE")) {
5009: $record{'scantron.useCODE'}=1;
5010: }
5011: if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
5012: $record{'scantron.CODE_ignore_dup'}=1;
5013: }
5014: } else {
5015: #FIXME interpret first N questions
5016: }
5017: }
5018: $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
5019: $$scantron_config{'IDlength'});
5020: $record{'scantron.PaperID'}=
5021: substr($data,$$scantron_config{'PaperID'}-1,
5022: $$scantron_config{'PaperIDlength'});
5023: $record{'scantron.FirstName'}=
5024: substr($data,$$scantron_config{'FirstName'}-1,
5025: $$scantron_config{'FirstNamelength'});
5026: $record{'scantron.LastName'}=
5027: substr($data,$$scantron_config{'LastName'}-1,
5028: $$scantron_config{'LastNamelength'});
5029: if ($just_header) { return \%record; }
5030:
5031: my @alphabet=('A'..'Z');
5032: my $questnum=0;
5033: while ($questions) {
5034: $questnum++;
5035: my $currentquest=substr($questions,0,$$scantron_config{'Qlength'});
5036: substr($questions,0,$$scantron_config{'Qlength'})='';
5037: if (length($currentquest) < $$scantron_config{'Qlength'}) { next; }
5038: if ($$scantron_config{'Qon'} eq 'letter') {
5039: if ($currentquest eq '?'
5040: || $currentquest eq '*') {
5041: push(@{$record{'scantron.doubleerror'}},$questnum);
5042: $record{"scantron.$questnum.answer"}='';
5043: } elsif (!defined($currentquest)
5044: || $currentquest eq $$scantron_config{'Qoff'}
5045: || $currentquest !~ /^[A-Z]$/) {
5046: $record{"scantron.$questnum.answer"}='';
5047: if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
5048: push(@{$record{"scantron.missingerror"}},$questnum);
5049: }
5050: } else {
5051: $record{"scantron.$questnum.answer"}=$currentquest;
5052: }
5053: } elsif ($$scantron_config{'Qon'} eq 'number') {
5054: if ($currentquest eq '?'
5055: || $currentquest eq '*') {
5056: push(@{$record{'scantron.doubleerror'}},$questnum);
5057: $record{"scantron.$questnum.answer"}='';
5058: } elsif (!defined($currentquest)
5059: || $currentquest eq $$scantron_config{'Qoff'}
5060: || $currentquest !~ /^\d$/) {
5061: $record{"scantron.$questnum.answer"}='';
5062: if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
5063: push(@{$record{"scantron.missingerror"}},$questnum);
5064: }
5065: } else {
5066: # wrap zero back to J
5067: if ($currentquest eq '0') {
5068: $record{"scantron.$questnum.answer"}=
5069: $alphabet[9];
5070: } else {
5071: $record{"scantron.$questnum.answer"}=
5072: $alphabet[$currentquest-1];
5073: }
5074: }
5075: } else {
5076: my @array=split($$scantron_config{'Qon'},$currentquest,-1);
5077: if (length($array[0]) eq $$scantron_config{'Qlength'}) {
5078: $record{"scantron.$questnum.answer"}='';
5079: if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
5080: push(@{$record{"scantron.missingerror"}},$questnum);
5081: }
5082: } else {
5083: $record{"scantron.$questnum.answer"}=
5084: $alphabet[length($array[0])];
5085: }
5086: if (scalar(@array) gt 2) {
5087: push(@{$record{'scantron.doubleerror'}},$questnum);
5088: my @ans=@array;
5089: my $i=length($ans[0]);shift(@ans);
5090: while ($#ans) {
5091: $i+=length($ans[0])+1;
5092: $record{"scantron.$questnum.answer"}.=$alphabet[$i];
5093: shift(@ans);
5094: }
5095: }
5096: }
5097: }
5098: $record{'scantron.maxquest'}=$questnum;
5099: return \%record;
5100: }
5101:
5102: =pod
5103:
5104: =item scantron_add_delay
5105:
5106: Adds an error message that occurred during the grading phase to a
5107: queue of messages to be shown after grading pass is complete
5108:
5109: Arguments:
5110: $delayqueue - arrary ref of hash ref of erro messages
5111: $scanline - the scanline that caused the error
5112: $errormesage - the error message
5113: $errorcode - a numeric code for the error
5114:
5115: Side Effects:
5116: updates the $dealyqueue to have a new hash ref of the error
5117:
5118: =cut
5119:
5120: sub scantron_add_delay {
5121: my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
5122: push(@$delayqueue,
5123: {'line' => $scanline, 'emsg' => $errormessage,
5124: 'ecode' => $errorcode }
5125: );
5126: }
5127:
5128: =pod
5129:
5130: =item scantron_find_student
5131:
5132: =cut
5133:
5134: sub scantron_find_student {
5135: my ($scantron_record,$scan_data,$idmap,$line)=@_;
5136: my $scanID=$$scantron_record{'scantron.ID'};
5137: if ($scanID =~ /^\s*$/) {
5138: return &scan_data($scan_data,"$line.user");
5139: }
5140: foreach my $id (keys(%$idmap)) {
5141: if (lc($id) eq lc($scanID)) {
5142: return $$idmap{$id};
5143: }
5144: }
5145: return undef;
5146: }
5147:
5148: =pod
5149:
5150: =item scantron_filter
5151:
5152: =cut
5153:
5154: sub scantron_filter {
5155: my ($curres)=@_;
5156:
5157: if (ref($curres) && $curres->is_problem()) {
5158: # if the user has asked to not have either hidden
5159: # or 'randomout' controlled resources to be graded
5160: # don't include them
5161: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
5162: && $curres->randomout) {
5163: return 0;
5164: }
5165: return 1;
5166: }
5167: return 0;
5168: }
5169:
5170: =pod
5171:
5172: =item scantron_process_corrections
5173:
5174: =cut
5175:
5176: sub scantron_process_corrections {
5177: my ($r) = @_;
5178: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
5179: my ($scanlines,$scan_data)=&scantron_getfile();
5180: my $classlist=&Apache::loncoursedata::get_classlist();
5181: my $which=$env{'form.scantron_line'};
5182: my $line=&scantron_get_line($scanlines,$scan_data,$which);
5183: my ($skip,$err,$errmsg);
5184: if ($env{'form.scantron_skip_record'}) {
5185: $skip=1;
5186: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
5187: my $newstudent=$env{'form.scantron_username'}.':'.
5188: $env{'form.scantron_domain'};
5189: my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
5190: ($line,$err,$errmsg)=
5191: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
5192: 'ID',{'newid'=>$newid,
5193: 'username'=>$env{'form.scantron_username'},
5194: 'domain'=>$env{'form.scantron_domain'}});
5195: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
5196: my $resolution=$env{'form.scantron_CODE_resolution'};
5197: my $newCODE;
5198: my %args;
5199: if ($resolution eq 'use_unfound') {
5200: $newCODE='use_unfound';
5201: } elsif ($resolution eq 'use_found') {
5202: $newCODE=$env{'form.scantron_CODE_selectedvalue'};
5203: } elsif ($resolution eq 'use_typed') {
5204: $newCODE=$env{'form.scantron_CODE_newvalue'};
5205: } elsif ($resolution =~ /^use_closest_(\d+)/) {
5206: $newCODE=$env{"form.scantron_CODE_closest_$1"};
5207: }
5208: if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
5209: $args{'CODE_ignore_dup'}=1;
5210: }
5211: $args{'CODE'}=$newCODE;
5212: ($line,$err,$errmsg)=
5213: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
5214: 'CODE',\%args);
5215: } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
5216: foreach my $question (split(',',$env{'form.scantron_questions'})) {
5217: ($line,$err,$errmsg)=
5218: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
5219: $which,'answer',
5220: { 'question'=>$question,
5221: 'response'=>$env{"form.scantron_correct_Q_$question"}});
5222: if ($err) { last; }
5223: }
5224: }
5225: if ($err) {
5226: $r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
5227: } else {
5228: &scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
5229: &scantron_putfile($scanlines,$scan_data);
5230: }
5231: }
5232:
5233: =pod
5234:
5235: =item reset_skipping_status
5236:
5237: =cut
5238:
5239: sub reset_skipping_status {
5240: my ($scanlines,$scan_data)=&scantron_getfile();
5241: &scan_data($scan_data,'remember_skipping',undef,1);
5242: &scantron_putfile(undef,$scan_data);
5243: }
5244:
5245: =pod
5246:
5247: =item start_skipping
5248:
5249: =cut
5250:
5251: sub start_skipping {
5252: my ($scan_data,$i)=@_;
5253: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
5254: if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
5255: $remembered{$i}=2;
5256: } else {
5257: $remembered{$i}=1;
5258: }
5259: &scan_data($scan_data,'remember_skipping',join(':',%remembered));
5260: }
5261:
5262: =pod
5263:
5264: =item should_be_skipped
5265:
5266: =cut
5267:
5268: sub should_be_skipped {
5269: my ($scanlines,$scan_data,$i)=@_;
5270: if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
5271: # not redoing old skips
5272: if ($scanlines->{'skipped'}[$i]) { return 1; }
5273: return 0;
5274: }
5275: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
5276:
5277: if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
5278: return 0;
5279: }
5280: return 1;
5281: }
5282:
5283: =pod
5284:
5285: =item remember_current_skipped
5286:
5287: =cut
5288:
5289: sub remember_current_skipped {
5290: my ($scanlines,$scan_data)=&scantron_getfile();
5291: my %to_remember;
5292: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
5293: if ($scanlines->{'skipped'}[$i]) {
5294: $to_remember{$i}=1;
5295: }
5296: }
5297:
5298: &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
5299: &scantron_putfile(undef,$scan_data);
5300: }
5301:
5302: =pod
5303:
5304: =item check_for_error
5305:
5306: =cut
5307:
5308: sub check_for_error {
5309: my ($r,$result)=@_;
5310: if ($result ne 'ok' && $result ne 'not_found' ) {
5311: $r->print("An error occurred ($result) when trying to Remove the existing corrections.");
5312: }
5313: }
5314:
5315: =pod
5316:
5317: =item scantron_warning_screen
5318:
5319: =cut
5320:
5321: sub scantron_warning_screen {
5322: my ($button_text)=@_;
5323: my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
5324: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
5325: my $CODElist;
5326: if ($scantron_config{'CODElocation'} &&
5327: $scantron_config{'CODEstart'} &&
5328: $scantron_config{'CODElength'}) {
5329: $CODElist=$env{'form.scantron_CODElist'};
5330: if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
5331: $CODElist=
5332: '<tr><td><b>List of CODES to validate against:</b></td><td><tt>'.
5333: $env{'form.scantron_CODElist'}.'</tt></td></tr>';
5334: }
5335: return (<<STUFF);
5336: <p>
5337: <span class="LC_warning">Please double check the information
5338: below before clicking on '$button_text'</span>
5339: </p>
5340: <table>
5341: <tr><td><b>Sequence to be Graded:</b></td><td>$title</td></tr>
5342: <tr><td><b>Data File that will be used:</b></td><td><tt>$env{'form.scantron_selectfile'}</tt></td></tr>
5343: $CODElist
5344: </table>
5345: <br />
5346: <p> If this information is correct, please click on '$button_text'.</p>
5347: <p> If something is incorrect, please click the 'Grading Menu' button to start over.</p>
5348:
5349: <br />
5350: STUFF
5351: }
5352:
5353: =pod
5354:
5355: =item scantron_do_warning
5356:
5357: =cut
5358:
5359: sub scantron_do_warning {
5360: my ($r)=@_;
5361: my ($symb)=&get_symb($r);
5362: if (!$symb) {return '';}
5363: my $default_form_data=&defaultFormData($symb);
5364: $r->print(&scantron_form_start().$default_form_data);
5365: if ( $env{'form.selectpage'} eq '' ||
5366: $env{'form.scantron_selectfile'} eq '' ||
5367: $env{'form.scantron_format'} eq '' ) {
5368: $r->print("<p>You have forgetten to specify some information. Please go Back and try again.</p>");
5369: if ( $env{'form.selectpage'} eq '') {
5370: $r->print('<p><span class="LC_error">You have not selected a Sequence to grade</span></p>');
5371: }
5372: if ( $env{'form.scantron_selectfile'} eq '') {
5373: $r->print('<p><span class="LC_error">You have not selected a file that contains the student\'s response data.</span></p>');
5374: }
5375: if ( $env{'form.scantron_format'} eq '') {
5376: $r->print('<p><span class="LC_error">You have not selected a the format of the student\'s response data.</span></p>');
5377: }
5378: } else {
5379: my $warning=&scantron_warning_screen('Grading: Validate Records');
5380: $r->print(<<STUFF);
5381: $warning
5382: <input type="submit" name="submit" value="Grading: Validate Records" />
5383: <input type="hidden" name="command" value="scantron_validate" />
5384: STUFF
5385: }
5386: $r->print("</form><br />".&show_grading_menu_form($symb));
5387: return '';
5388: }
5389:
5390: =pod
5391:
5392: =item scantron_form_start
5393:
5394: =cut
5395:
5396: sub scantron_form_start {
5397: my ($max_bubble)=@_;
5398: my $result= <<SCANTRONFORM;
5399: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
5400: <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
5401: <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
5402: <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
5403: <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
5404: <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
5405: <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
5406: <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
5407: <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
5408: <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
5409: SCANTRONFORM
5410: return $result;
5411: }
5412:
5413: =pod
5414:
5415: =item scantron_validate_file
5416:
5417: =cut
5418:
5419: sub scantron_validate_file {
5420: my ($r) = @_;
5421: my ($symb)=&get_symb($r);
5422: if (!$symb) {return '';}
5423: my $default_form_data=&defaultFormData($symb);
5424:
5425: # do the detection of only doing skipped records first befroe we delete
5426: # them when doing the corrections reset
5427: if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
5428: &reset_skipping_status();
5429: }
5430: if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
5431: &remember_current_skipped();
5432: $env{'form.scantron_options_redo'}='redo_skipped_ready';
5433: }
5434:
5435: if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
5436: &check_for_error($r,&scantron_remove_file('corrected'));
5437: &check_for_error($r,&scantron_remove_file('skipped'));
5438: &check_for_error($r,&scantron_remove_scan_data());
5439: $env{'form.scantron_options_ignore'}='done';
5440: }
5441:
5442: if ($env{'form.scantron_corrections'}) {
5443: &scantron_process_corrections($r);
5444: }
5445: $r->print("<p>Gathering neccessary info.</p>");$r->rflush();
5446: #get the student pick code ready
5447: $r->print(&Apache::loncommon::studentbrowser_javascript());
5448: my $max_bubble=&scantron_get_maxbubble();
5449: my $result=&scantron_form_start($max_bubble).$default_form_data;
5450: $r->print($result);
5451:
5452: my @validate_phases=( 'sequence',
5453: 'ID',
5454: 'CODE',
5455: 'doublebubble',
5456: 'missingbubbles');
5457: if (!$env{'form.validatepass'}) {
5458: $env{'form.validatepass'} = 0;
5459: }
5460: my $currentphase=$env{'form.validatepass'};
5461:
5462: my $stop=0;
5463: while (!$stop && $currentphase < scalar(@validate_phases)) {
5464: $r->print("<p> Validating ".$validate_phases[$currentphase]."</p>");
5465: $r->rflush();
5466: my $which="scantron_validate_".$validate_phases[$currentphase];
5467: {
5468: no strict 'refs';
5469: ($stop,$currentphase)=&$which($r,$currentphase);
5470: }
5471: }
5472: if (!$stop) {
5473: my $warning=&scantron_warning_screen('Start Grading');
5474: $r->print(<<STUFF);
5475: Validation process complete.<br />
5476: $warning
5477: <input type="submit" name="submit" value="Start Grading" />
5478: <input type="hidden" name="command" value="scantron_process" />
5479: STUFF
5480:
5481: } else {
5482: $r->print('<input type="hidden" name="command" value="scantron_validate" />');
5483: $r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
5484: }
5485: if ($stop) {
5486: if ($validate_phases[$currentphase] eq 'sequence') {
5487: $r->print('<input type="submit" name="submit" value="Ignore -> " />');
5488: $r->print(' this error <br />');
5489:
5490: $r->print(" <p>Or click the 'Grading Menu' button to start over.</p>");
5491: } else {
5492: $r->print('<input type="submit" name="submit" value="Continue ->" />');
5493: $r->print(' using corrected info <br />');
5494: $r->print("<input type='submit' value='Skip' name='scantron_skip_record' />");
5495: $r->print(" this scanline saving it for later.");
5496: }
5497: }
5498: $r->print(" </form><br />".&show_grading_menu_form($symb));
5499: return '';
5500: }
5501:
5502:
5503: =pod
5504:
5505: =item scantron_remove_file
5506:
5507: =cut
5508:
5509: sub scantron_remove_file {
5510: my ($which)=@_;
5511: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5512: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5513: my $file='scantron_';
5514: if ($which eq 'corrected' || $which eq 'skipped') {
5515: $file.=$which.'_';
5516: } else {
5517: return 'refused';
5518: }
5519: $file.=$env{'form.scantron_selectfile'};
5520: return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
5521: }
5522:
5523:
5524: =pod
5525:
5526: =item scantron_remove_scan_data
5527:
5528: =cut
5529:
5530: sub scantron_remove_scan_data {
5531: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5532: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5533: my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
5534: my @todelete;
5535: my $filename=$env{'form.scantron_selectfile'};
5536: foreach my $key (@keys) {
5537: if ($key=~/^\Q$filename\E_/) {
5538: if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
5539: $key=~/remember_skipping/) {
5540: next;
5541: }
5542: push(@todelete,$key);
5543: }
5544: }
5545: my $result;
5546: if (@todelete) {
5547: $result=&Apache::lonnet::del('nohist_scantrondata',\@todelete,$cdom,$cname);
5548: }
5549: return $result;
5550: }
5551:
5552:
5553: =pod
5554:
5555: =item scantron_getfile
5556:
5557: =cut
5558:
5559: sub scantron_getfile {
5560: #FIXME really would prefer a scantron directory
5561: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5562: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5563: my $lines;
5564: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
5565: 'scantron_orig_'.$env{'form.scantron_selectfile'});
5566: my %scanlines;
5567: $scanlines{'orig'}=[(split("\n",$lines,-1))];
5568: my $temp=$scanlines{'orig'};
5569: $scanlines{'count'}=$#$temp;
5570:
5571: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
5572: 'scantron_corrected_'.$env{'form.scantron_selectfile'});
5573: if ($lines eq '-1') {
5574: $scanlines{'corrected'}=[];
5575: } else {
5576: $scanlines{'corrected'}=[(split("\n",$lines,-1))];
5577: }
5578: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
5579: 'scantron_skipped_'.$env{'form.scantron_selectfile'});
5580: if ($lines eq '-1') {
5581: $scanlines{'skipped'}=[];
5582: } else {
5583: $scanlines{'skipped'}=[(split("\n",$lines,-1))];
5584: }
5585: my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
5586: if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
5587: my %scan_data = @tmp;
5588: return (\%scanlines,\%scan_data);
5589: }
5590:
5591: =pod
5592:
5593: =item lonnet_putfile
5594:
5595: =cut
5596:
5597: sub lonnet_putfile {
5598: my ($contents,$filename)=@_;
5599: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
5600: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5601: $env{'form.sillywaytopassafilearound'}=$contents;
5602: &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
5603:
5604: }
5605:
5606: =pod
5607:
5608: =item scantron_putfile
5609:
5610: =cut
5611:
5612: sub scantron_putfile {
5613: my ($scanlines,$scan_data) = @_;
5614: #FIXME really would prefer a scantron directory
5615: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5616: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5617: if ($scanlines) {
5618: my $prefix='scantron_';
5619: # no need to update orig, shouldn't change
5620: # &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
5621: # $env{'form.scantron_selectfile'});
5622: &lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
5623: $prefix.'corrected_'.
5624: $env{'form.scantron_selectfile'});
5625: &lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
5626: $prefix.'skipped_'.
5627: $env{'form.scantron_selectfile'});
5628: }
5629: &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
5630: }
5631:
5632: =pod
5633:
5634: =item scantron_get_line
5635:
5636: =cut
5637:
5638: sub scantron_get_line {
5639: my ($scanlines,$scan_data,$i)=@_;
5640: if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
5641: #if ($scanlines->{'skipped'}[$i]) { return undef; }
5642: if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
5643: return $scanlines->{'orig'}[$i];
5644: }
5645:
5646: =pod
5647:
5648: =item scantron_todo_count
5649:
5650: =cut
5651:
5652: sub get_todo_count {
5653: my ($scanlines,$scan_data)=@_;
5654: my $count=0;
5655: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
5656: my $line=&scantron_get_line($scanlines,$scan_data,$i);
5657: if ($line=~/^[\s\cz]*$/) { next; }
5658: $count++;
5659: }
5660: return $count;
5661: }
5662:
5663: =pod
5664:
5665: =item scantron_put_line
5666:
5667: =cut
5668:
5669: sub scantron_put_line {
5670: my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
5671: if ($skip) {
5672: $scanlines->{'skipped'}[$i]=$newline;
5673: &start_skipping($scan_data,$i);
5674: return;
5675: }
5676: $scanlines->{'corrected'}[$i]=$newline;
5677: }
5678:
5679: =pod
5680:
5681: =item scantron_clear_skip
5682:
5683: =cut
5684:
5685: sub scantron_clear_skip {
5686: my ($scanlines,$scan_data,$i)=@_;
5687: if (exists($scanlines->{'skipped'}[$i])) {
5688: undef($scanlines->{'skipped'}[$i]);
5689: return 1;
5690: }
5691: return 0;
5692: }
5693:
5694: =pod
5695:
5696: =item scantron_filter_not_exam
5697:
5698: =cut
5699:
5700: sub scantron_filter_not_exam {
5701: my ($curres)=@_;
5702:
5703: if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
5704: # if the user has asked to not have either hidden
5705: # or 'randomout' controlled resources to be graded
5706: # don't include them
5707: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
5708: && $curres->randomout) {
5709: return 0;
5710: }
5711: return 1;
5712: }
5713: return 0;
5714: }
5715:
5716: =pod
5717:
5718: =item scantron_validate_sequence
5719:
5720: =cut
5721:
5722: sub scantron_validate_sequence {
5723: my ($r,$currentphase) = @_;
5724:
5725: my $navmap=Apache::lonnavmaps::navmap->new();
5726: my (undef,undef,$sequence)=
5727: &Apache::lonnet::decode_symb($env{'form.selectpage'});
5728:
5729: my $map=$navmap->getResourceByUrl($sequence);
5730:
5731: $r->print('<input type="hidden" name="validate_sequence_exam"
5732: value="ignore" />');
5733: if ($env{'form.validate_sequence_exam'} ne 'ignore') {
5734: my @resources=
5735: $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
5736: if (@resources) {
5737: $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>");
5738: return (1,$currentphase);
5739: }
5740: }
5741:
5742: return (0,$currentphase+1);
5743: }
5744:
5745: =pod
5746:
5747: =item scantron_validate_ID
5748:
5749: =cut
5750:
5751: sub scantron_validate_ID {
5752: my ($r,$currentphase) = @_;
5753:
5754: #get student info
5755: my $classlist=&Apache::loncoursedata::get_classlist();
5756: my %idmap=&username_to_idmap($classlist);
5757:
5758: #get scantron line setup
5759: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
5760: my ($scanlines,$scan_data)=&scantron_getfile();
5761:
5762: my %found=('ids'=>{},'usernames'=>{});
5763: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
5764: my $line=&scantron_get_line($scanlines,$scan_data,$i);
5765: if ($line=~/^[\s\cz]*$/) { next; }
5766: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
5767: $scan_data);
5768: my $id=$$scan_record{'scantron.ID'};
5769: my $found;
5770: foreach my $checkid (keys(%idmap)) {
5771: if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
5772: }
5773: if ($found) {
5774: my $username=$idmap{$found};
5775: if ($found{'ids'}{$found}) {
5776: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
5777: $line,'duplicateID',$found);
5778: return(1,$currentphase);
5779: } elsif ($found{'usernames'}{$username}) {
5780: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
5781: $line,'duplicateID',$username);
5782: return(1,$currentphase);
5783: }
5784: #FIXME store away line we previously saw the ID on to use above
5785: $found{'ids'}{$found}++;
5786: $found{'usernames'}{$username}++;
5787: } else {
5788: if ($id =~ /^\s*$/) {
5789: my $username=&scan_data($scan_data,"$i.user");
5790: if (defined($username) && $found{'usernames'}{$username}) {
5791: &scantron_get_correction($r,$i,$scan_record,
5792: \%scantron_config,
5793: $line,'duplicateID',$username);
5794: return(1,$currentphase);
5795: } elsif (!defined($username)) {
5796: &scantron_get_correction($r,$i,$scan_record,
5797: \%scantron_config,
5798: $line,'incorrectID');
5799: return(1,$currentphase);
5800: }
5801: $found{'usernames'}{$username}++;
5802: } else {
5803: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
5804: $line,'incorrectID');
5805: return(1,$currentphase);
5806: }
5807: }
5808: }
5809:
5810: return (0,$currentphase+1);
5811: }
5812:
5813: =pod
5814:
5815: =item scantron_get_correction
5816:
5817: =cut
5818:
5819: sub scantron_get_correction {
5820: my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
5821:
5822: #FIXME in the case of a duplicated ID the previous line, probaly need
5823: #to show both the current line and the previous one and allow skipping
5824: #the previous one or the current one
5825:
5826: $r->print("<p><b>An error was detected ($error)</b>");
5827: if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
5828: $r->print(" for PaperID <tt>".
5829: $$scan_record{'scantron.PaperID'}."</tt> \n");
5830: } else {
5831: $r->print(" in scanline $i <pre>".
5832: $line."</pre> \n");
5833: }
5834: my $message="<p>The ID on the form is <tt>".
5835: $$scan_record{'scantron.ID'}."</tt><br />\n".
5836: "The name on the paper is ".
5837: $$scan_record{'scantron.LastName'}.",".
5838: $$scan_record{'scantron.FirstName'}."</p>";
5839:
5840: $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
5841: $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
5842: if ($error =~ /ID$/) {
5843: if ($error eq 'incorrectID') {
5844: $r->print("The encoded ID is not in the classlist</p>\n");
5845: } elsif ($error eq 'duplicateID') {
5846: $r->print("The encoded ID has also been used by a previous paper $arg</p>\n");
5847: }
5848: $r->print($message);
5849: $r->print("<p>How should I handle this? <br /> \n");
5850: $r->print("\n<ul><li> ");
5851: #FIXME it would be nice if this sent back the user ID and
5852: #could do partial userID matches
5853: $r->print(&Apache::loncommon::selectstudent_link('scantronupload',
5854: 'scantron_username','scantron_domain'));
5855: $r->print(": <input type='text' name='scantron_username' value='' />");
5856: $r->print("\n@".
5857: &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
5858:
5859: $r->print('</li>');
5860: } elsif ($error =~ /CODE$/) {
5861: if ($error eq 'incorrectCODE') {
5862: $r->print("</p><p>The encoded CODE is not in the list of possible CODEs</p>\n");
5863: } elsif ($error eq 'duplicateCODE') {
5864: $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");
5865: }
5866: $r->print("<p>The CODE on the form is <tt>'".
5867: $$scan_record{'scantron.CODE'}."'</tt><br />\n");
5868: $r->print($message);
5869: $r->print("<p>How should I handle this? <br /> \n");
5870: $r->print("\n<br /> ");
5871: my $i=0;
5872: if ($error eq 'incorrectCODE'
5873: && $$scan_record{'scantron.CODE'}=~/\S/ ) {
5874: my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
5875: if ($closest > 0) {
5876: foreach my $testcode (@{$closest}) {
5877: my $checked='';
5878: if (!$i) { $checked=' checked="checked" '; }
5879: $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' />");
5880: $r->print("\n<br />");
5881: $i++;
5882: }
5883: }
5884: }
5885: if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
5886: my $checked; if (!$i) { $checked=' checked="checked" '; }
5887: $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>");
5888: $r->print("\n<br />");
5889: }
5890:
5891: $r->print(<<ENDSCRIPT);
5892: <script type="text/javascript">
5893: function change_radio(field) {
5894: var slct=document.scantronupload.scantron_CODE_resolution;
5895: var i;
5896: for (i=0;i<slct.length;i++) {
5897: if (slct[i].value==field) { slct[i].checked=true; }
5898: }
5899: }
5900: </script>
5901: ENDSCRIPT
5902: my $href="/adm/pickcode?".
5903: "form=".&escape("scantronupload").
5904: "&scantron_format=".&escape($env{'form.scantron_format'}).
5905: "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
5906: "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
5907: "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
5908: if ($env{'form.scantron_CODElist'} =~ /\S/) {
5909: $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')\" />");
5910: $r->print("\n<br />");
5911: }
5912: $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.");
5913: $r->print("\n<br /><br />");
5914: } elsif ($error eq 'doublebubble') {
5915: $r->print("<p>There have been multiple bubbles scanned for a some question(s)</p>\n");
5916: $r->print('<input type="hidden" name="scantron_questions" value="'.
5917: join(',',@{$arg}).'" />');
5918: $r->print($message);
5919: $r->print("<p>Please indicate which bubble should be used for grading</p>");
5920: foreach my $question (@{$arg}) {
5921: my $selected=$$scan_record{"scantron.$question.answer"};
5922: &scantron_bubble_selector($r,$scan_config,$question,
5923: split('',$selected));
5924: }
5925: } elsif ($error eq 'missingbubble') {
5926: $r->print("<p>There have been <b>no</b> bubbles scanned for some question(s)</p>\n");
5927: $r->print($message);
5928: $r->print("<p>Please indicate which bubble should be used for grading</p>");
5929: $r->print("Some questions have no scanned bubbles\n");
5930: $r->print('<input type="hidden" name="scantron_questions" value="'.
5931: join(',',@{$arg}).'" />');
5932: foreach my $question (@{$arg}) {
5933: my $selected=$$scan_record{"scantron.$question.answer"};
5934: &scantron_bubble_selector($r,$scan_config,$question);
5935: }
5936: } else {
5937: $r->print("\n<ul>");
5938: }
5939: $r->print("\n</li></ul>");
5940:
5941: }
5942:
5943: =pod
5944:
5945: =item scantron_bubble_selector
5946:
5947: Generates the html radiobuttons to correct a single bubble line
5948: possibly showing the exisiting the selected bubbles if known
5949:
5950: Arguments:
5951: $r - Apache request object
5952: $scan_config - hash from &get_scantron_config()
5953: $quest - number of the bubble line to make a corrector for
5954: $selected - array of letters of previously selected bubbles
5955: $lines - if present, number of bubble lines to show
5956:
5957: =cut
5958:
5959: sub scantron_bubble_selector {
5960: my ($r,$scan_config,$quest,@selected, $lines)=@_;
5961: my $max=$$scan_config{'Qlength'};
5962:
5963: my $scmode=$$scan_config{'Qon'};
5964: if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }
5965:
5966:
5967: if (!defined($lines)) {
5968: $lines = 1;
5969: }
5970: my $total_lines = $lines*2;
5971: my @alphabet=('A'..'Z');
5972: $r->print("<table border='1'><tr><td rowspan='".$total_lines."'>$quest</td>");
5973:
5974: for (my $l = 0; $l < $lines; $l++) {
5975: if ($l != 0) {
5976: $r->print('<tr>');
5977: }
5978:
5979: # FIXME: This loop probably has to be considerably more clever for
5980: # multiline bubbles: User can multibubble by having bubbles in
5981: # several lines. User can skip lines legitimately etc. etc.
5982:
5983: for (my $i=0;$i<$max;$i++) {
5984: $r->print("\n".'<td align="center">');
5985: if ($selected[0] eq $alphabet[$i]) {
5986: $r->print('X');
5987: shift(@selected) ;
5988: } else {
5989: $r->print(' ');
5990: }
5991: $r->print('</td>');
5992:
5993: }
5994:
5995: if ($l == 0) {
5996: my $lspan = $total_lines * 2; # 2 table rows per bubble line.
5997:
5998: $r->print('<td rowspan='.$lspan.'><label><input type="radio" name="scantron_correct_Q_'.
5999: $quest.'" value="none" /> No bubble </label></td>');
6000:
6001: }
6002:
6003: $r->print('</tr><tr>');
6004:
6005: # FIXME: This may have to be a bit more clever for
6006: # multiline questions (different values e.g..).
6007:
6008: for (my $i=0;$i<$max;$i++) {
6009: $r->print("\n".
6010: '<td><label><input type="radio" name="scantron_correct_Q_'.
6011: $quest.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
6012: }
6013: $r->print('</tr>');
6014:
6015:
6016: }
6017: $r->print('</table>');
6018: }
6019:
6020: =pod
6021:
6022: =item num_matches
6023:
6024: =cut
6025:
6026: sub num_matches {
6027: my ($orig,$code) = @_;
6028: my @code=split(//,$code);
6029: my @orig=split(//,$orig);
6030: my $same=0;
6031: for (my $i=0;$i<scalar(@code);$i++) {
6032: if ($code[$i] eq $orig[$i]) { $same++; }
6033: }
6034: return $same;
6035: }
6036:
6037: =pod
6038:
6039: =item scantron_get_closely_matching_CODEs
6040:
6041: =cut
6042:
6043: sub scantron_get_closely_matching_CODEs {
6044: my ($allcodes,$CODE)=@_;
6045: my @CODEs;
6046: foreach my $testcode (sort(keys(%{$allcodes}))) {
6047: push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
6048: }
6049:
6050: return ($#CODEs,$CODEs[-1]);
6051: }
6052:
6053: =pod
6054:
6055: =item get_codes
6056:
6057: =cut
6058:
6059: sub get_codes {
6060: my ($old_name, $cdom, $cnum) = @_;
6061: if (!$old_name) {
6062: $old_name=$env{'form.scantron_CODElist'};
6063: }
6064: if (!$cdom) {
6065: $cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
6066: }
6067: if (!$cnum) {
6068: $cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
6069: }
6070: my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
6071: $cdom,$cnum);
6072: my %allcodes;
6073: if ($result{"type\0$old_name"} eq 'number') {
6074: %allcodes=map {($_,1)} split(',',$result{$old_name});
6075: } else {
6076: %allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
6077: }
6078: return %allcodes;
6079: }
6080:
6081: =pod
6082:
6083: =item scantron_validate_CODE
6084:
6085: =cut
6086:
6087: sub scantron_validate_CODE {
6088: my ($r,$currentphase) = @_;
6089: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6090: if ($scantron_config{'CODElocation'} &&
6091: $scantron_config{'CODEstart'} &&
6092: $scantron_config{'CODElength'}) {
6093: if (!defined($env{'form.scantron_CODElist'})) {
6094: &FIXME_blow_up()
6095: }
6096: } else {
6097: return (0,$currentphase+1);
6098: }
6099:
6100: my %usedCODEs;
6101:
6102: my %allcodes=&get_codes();
6103:
6104: my ($scanlines,$scan_data)=&scantron_getfile();
6105: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6106: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6107: if ($line=~/^[\s\cz]*$/) { next; }
6108: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6109: $scan_data);
6110: my $CODE=$$scan_record{'scantron.CODE'};
6111: my $error=0;
6112: if (!&Apache::lonnet::validCODE($CODE)) {
6113: &scantron_get_correction($r,$i,$scan_record,
6114: \%scantron_config,
6115: $line,'incorrectCODE',\%allcodes);
6116: return(1,$currentphase);
6117: }
6118: if (%allcodes && !exists($allcodes{$CODE})
6119: && !$$scan_record{'scantron.useCODE'}) {
6120: &scantron_get_correction($r,$i,$scan_record,
6121: \%scantron_config,
6122: $line,'incorrectCODE',\%allcodes);
6123: return(1,$currentphase);
6124: }
6125: if (exists($usedCODEs{$CODE})
6126: && $env{'form.scantron_CODEunique'} eq 'yes'
6127: && !$$scan_record{'scantron.CODE_ignore_dup'}) {
6128: &scantron_get_correction($r,$i,$scan_record,
6129: \%scantron_config,
6130: $line,'duplicateCODE',$usedCODEs{$CODE});
6131: return(1,$currentphase);
6132: }
6133: push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
6134: }
6135: return (0,$currentphase+1);
6136: }
6137:
6138: =pod
6139:
6140: =item scantron_validate_doublebubble
6141:
6142: =cut
6143:
6144: sub scantron_validate_doublebubble {
6145: my ($r,$currentphase) = @_;
6146: #get student info
6147: my $classlist=&Apache::loncoursedata::get_classlist();
6148: my %idmap=&username_to_idmap($classlist);
6149:
6150: #get scantron line setup
6151: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6152: my ($scanlines,$scan_data)=&scantron_getfile();
6153: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6154: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6155: if ($line=~/^[\s\cz]*$/) { next; }
6156: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6157: $scan_data);
6158: if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
6159: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
6160: 'doublebubble',
6161: $$scan_record{'scantron.doubleerror'});
6162: return (1,$currentphase);
6163: }
6164: return (0,$currentphase+1);
6165: }
6166:
6167: =pod
6168:
6169: =item scantron_get_maxbubble
6170:
6171: =cut
6172:
6173: sub scantron_get_maxbubble {
6174: if (defined($env{'form.scantron_maxbubble'}) &&
6175: $env{'form.scantron_maxbubble'}) {
6176: return $env{'form.scantron_maxbubble'};
6177: }
6178:
6179: my $navmap=Apache::lonnavmaps::navmap->new();
6180: my (undef,undef,$sequence)=
6181: &Apache::lonnet::decode_symb($env{'form.selectpage'});
6182:
6183: my $map=$navmap->getResourceByUrl($sequence);
6184: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
6185:
6186: &Apache::lonxml::clear_problem_counter();
6187:
6188: foreach my $resource (@resources) {
6189: my $result=&Apache::lonnet::ssi($resource->src(),
6190: ('symb' => $resource->symb()));
6191: }
6192: &Apache::lonnet::delenv('scantron\.');
6193: $env{'form.scantron_maxbubble'} =
6194: &Apache::lonxml::get_problem_counter()-1;
6195:
6196: return $env{'form.scantron_maxbubble'};
6197: }
6198:
6199: =pod
6200:
6201: =item scantron_validate_missingbubbles
6202:
6203: =cut
6204:
6205: sub scantron_validate_missingbubbles {
6206: my ($r,$currentphase) = @_;
6207: #get student info
6208: my $classlist=&Apache::loncoursedata::get_classlist();
6209: my %idmap=&username_to_idmap($classlist);
6210:
6211: #get scantron line setup
6212: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6213: my ($scanlines,$scan_data)=&scantron_getfile();
6214: my $max_bubble=&scantron_get_maxbubble();
6215: if (!$max_bubble) { $max_bubble=2**31; }
6216: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6217: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6218: if ($line=~/^[\s\cz]*$/) { next; }
6219: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6220: $scan_data);
6221: if (!defined($$scan_record{'scantron.missingerror'})) { next; }
6222: my @to_correct;
6223: foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
6224: if ($missing > $max_bubble) { next; }
6225: push(@to_correct,$missing);
6226: }
6227: if (@to_correct) {
6228: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6229: $line,'missingbubble',\@to_correct);
6230: return (1,$currentphase);
6231: }
6232:
6233: }
6234: return (0,$currentphase+1);
6235: }
6236:
6237: =pod
6238:
6239: =item scantron_process_students
6240:
6241: Routine that does the actual grading of the bubble sheet information.
6242:
6243: The parsed scanline hash is added to %env
6244:
6245: Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
6246: foreach resource , with the form data of
6247:
6248: 'submitted' =>'scantron'
6249: 'grade_target' =>'grade',
6250: 'grade_username'=> username of student
6251: 'grade_domain' => domain of student
6252: 'grade_courseid'=> of course
6253: 'grade_symb' => symb of resource to grade
6254:
6255: This triggers a grading pass. The problem grading code takes care
6256: of converting the bubbled letter information (now in %env) into a
6257: valid submission.
6258:
6259: =cut
6260:
6261: sub scantron_process_students {
6262: my ($r) = @_;
6263: my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
6264: my ($symb)=&get_symb($r);
6265: if (!$symb) {return '';}
6266: my $default_form_data=&defaultFormData($symb);
6267:
6268: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6269: my ($scanlines,$scan_data)=&scantron_getfile();
6270: my $classlist=&Apache::loncoursedata::get_classlist();
6271: my %idmap=&username_to_idmap($classlist);
6272: my $navmap=Apache::lonnavmaps::navmap->new();
6273: my $map=$navmap->getResourceByUrl($sequence);
6274: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
6275: # $r->print("geto ".scalar(@resources)."<br />");
6276: my $result= <<SCANTRONFORM;
6277: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
6278: <input type="hidden" name="command" value="scantron_configphase" />
6279: $default_form_data
6280: SCANTRONFORM
6281: $r->print($result);
6282:
6283: my @delayqueue;
6284: my %completedstudents;
6285:
6286: my $count=&get_todo_count($scanlines,$scan_data);
6287: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
6288: 'Scantron Progress',$count,
6289: 'inline',undef,'scantronupload');
6290: &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
6291: 'Processing first student');
6292: my $start=&Time::HiRes::time();
6293: my $i=-1;
6294: my ($uname,$udom,$started);
6295: while ($i<$scanlines->{'count'}) {
6296: ($uname,$udom)=('','');
6297: $i++;
6298: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6299: if ($line=~/^[\s\cz]*$/) { next; }
6300: if ($started) {
6301: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
6302: 'last student');
6303: }
6304: $started=1;
6305: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6306: $scan_data);
6307: unless ($uname=&scantron_find_student($scan_record,$scan_data,
6308: \%idmap,$i)) {
6309: &scantron_add_delay(\@delayqueue,$line,
6310: 'Unable to find a student that matches',1);
6311: next;
6312: }
6313: if (exists $completedstudents{$uname}) {
6314: &scantron_add_delay(\@delayqueue,$line,
6315: 'Student '.$uname.' has multiple sheets',2);
6316: next;
6317: }
6318: ($uname,$udom)=split(/:/,$uname);
6319:
6320: &Apache::lonxml::clear_problem_counter();
6321: &Apache::lonnet::appenv(%$scan_record);
6322:
6323: if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
6324: &scantron_putfile($scanlines,$scan_data);
6325: }
6326:
6327: my $i=0;
6328: foreach my $resource (@resources) {
6329: $i++;
6330: my %form=('submitted' =>'scantron',
6331: 'grade_target' =>'grade',
6332: 'grade_username'=>$uname,
6333: 'grade_domain' =>$udom,
6334: 'grade_courseid'=>$env{'request.course.id'},
6335: 'grade_symb' =>$resource->symb());
6336: if (exists($scan_record->{'scantron.CODE'})
6337: &&
6338: &Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
6339: $form{'CODE'}=$scan_record->{'scantron.CODE'};
6340: } else {
6341: $form{'CODE'}='';
6342: }
6343: my $result=&Apache::lonnet::ssi($resource->src(),%form);
6344: if ($result ne '') {
6345: &Apache::lonnet::logthis("scantron grading error -> $result");
6346: &Apache::lonnet::logthis("scantron grading error info name $uname domain $udom course $env{'request.course.id'} url ".$resource->src());
6347: }
6348: if (&Apache::loncommon::connection_aborted($r)) { last; }
6349: }
6350: $completedstudents{$uname}={'line'=>$line};
6351: if (&Apache::loncommon::connection_aborted($r)) { last; }
6352: } continue {
6353: &Apache::lonxml::clear_problem_counter();
6354: &Apache::lonnet::delenv('scantron\.');
6355: }
6356: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
6357: # my $lasttime = &Time::HiRes::time()-$start;
6358: # $r->print("<p>took $lasttime</p>");
6359:
6360: $r->print("</form>");
6361: $r->print(&show_grading_menu_form($symb));
6362: return '';
6363: }
6364:
6365: =pod
6366:
6367: =item scantron_upload_scantron_data
6368:
6369: Creates the screen for adding a new bubble sheet data file to a course.
6370:
6371: =cut
6372:
6373: sub scantron_upload_scantron_data {
6374: my ($r)=@_;
6375: $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
6376: my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
6377: 'domainid',
6378: 'coursename');
6379: my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
6380: 'domainid');
6381: my $default_form_data=&defaultFormData(&get_symb($r,1));
6382: $r->print(<<UPLOAD);
6383: <script type="text/javascript" language="javascript">
6384: function checkUpload(formname) {
6385: if (formname.upfile.value == "") {
6386: alert("Please use the browse button to select a file from your local directory.");
6387: return false;
6388: }
6389: formname.submit();
6390: }
6391: </script>
6392:
6393: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
6394: $default_form_data
6395: <table>
6396: <tr><td>$select_link </td></tr>
6397: <tr><td>Course ID: </td><td><input name='courseid' type='text' /> </td></tr>
6398: <tr><td>Course Name: </td><td><input name='coursename' type='text' /></td></tr>
6399: <tr><td>Domain: </td><td>$domsel </td></tr>
6400: <tr><td>File to upload:</td><td><input type="file" name="upfile" size="50" /></td></tr>
6401: </table>
6402: <input name='command' value='scantronupload_save' type='hidden' />
6403: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
6404: </form>
6405: UPLOAD
6406: return '';
6407: }
6408:
6409: =pod
6410:
6411: =item scantron_upload_scantron_data_save
6412:
6413: Adds a provided bubble information data file to the course if user
6414: has the correct privileges to do so.
6415:
6416: =cut
6417:
6418: sub scantron_upload_scantron_data_save {
6419: my($r)=@_;
6420: my ($symb)=&get_symb($r,1);
6421: my $doanotherupload=
6422: '<br /><form action="/adm/grades" method="post">'."\n".
6423: '<input type="hidden" name="command" value="scantronupload" />'."\n".
6424: '<input type="submit" name="submit" value="Do Another Upload" />'."\n".
6425: '</form>'."\n";
6426: if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
6427: !&Apache::lonnet::allowed('usc',
6428: $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
6429: $r->print("You are not allowed to upload Scantron data to the requested course.<br />");
6430: if ($symb) {
6431: $r->print(&show_grading_menu_form($symb));
6432: } else {
6433: $r->print($doanotherupload);
6434: }
6435: return '';
6436: }
6437: my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
6438: $r->print("Doing upload to ".$coursedata{'description'}." <br />");
6439: my $fname=$env{'form.upfile.filename'};
6440: #FIXME
6441: #copied from lonnet::userfileupload()
6442: #make that function able to target a specified course
6443: # Replace Windows backslashes by forward slashes
6444: $fname=~s/\\/\//g;
6445: # Get rid of everything but the actual filename
6446: $fname=~s/^.*\/([^\/]+)$/$1/;
6447: # Replace spaces by underscores
6448: $fname=~s/\s+/\_/g;
6449: # Replace all other weird characters by nothing
6450: $fname=~s/[^\w\.\-]//g;
6451: # See if there is anything left
6452: unless ($fname) { return 'error: no uploaded file'; }
6453: my $uploadedfile=$fname;
6454: $fname='scantron_orig_'.$fname;
6455: if (length($env{'form.upfile'}) < 2) {
6456: $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.");
6457: } else {
6458: my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
6459: if ($result =~ m|^/uploaded/|) {
6460: $r->print("<span class=\"LC_success\">Success:</span> Successfully uploaded ".(length($env{'form.upfile'})-1)." bytes of data into location <tt>".$result."</tt>");
6461: } else {
6462: $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>");
6463: }
6464: }
6465: if ($symb) {
6466: $r->print(&scantron_selectphase($r,$uploadedfile));
6467: } else {
6468: $r->print($doanotherupload);
6469: }
6470: return '';
6471: }
6472:
6473: =pod
6474:
6475: =item valid_file
6476:
6477: Vaildates that the requested bubble data file has exists in the course.
6478:
6479: =cut
6480:
6481: sub valid_file {
6482: my ($requested_file)=@_;
6483: foreach my $filename (sort(&scantron_filenames())) {
6484: if ($requested_file eq $filename) { return 1; }
6485: }
6486: return 0;
6487: }
6488:
6489: =pod
6490:
6491: =item scantron_download_scantron_data
6492:
6493: Shows a list of the three internal files (original, corrected,
6494: skipped) for a specific bubble sheet data file that exists in the
6495: course.
6496:
6497: =cut
6498:
6499: sub scantron_download_scantron_data {
6500: my ($r)=@_;
6501: my $default_form_data=&defaultFormData(&get_symb($r,1));
6502: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6503: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6504: my $file=$env{'form.scantron_selectfile'};
6505: if (! &valid_file($file)) {
6506: $r->print(<<ERROR);
6507: <p>
6508: The requested file name was invalid.
6509: </p>
6510: ERROR
6511: $r->print(&show_grading_menu_form(&get_symb($r,1)));
6512: return;
6513: }
6514: my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
6515: my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
6516: my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
6517: &Apache::lonnet::allowuploaded('/adm/grades',$orig);
6518: &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
6519: &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
6520: $r->print(<<DOWNLOAD);
6521: <p>
6522: <a href="$orig">Original</a> file as uploaded by the scantron office.
6523: </p>
6524: <p>
6525: <a href="$corrected">Corrections</a>, a file of corrected records that were used in grading.
6526: </p>
6527: <p>
6528: <a href="$skipped">Skipped</a>, a file of records that were skipped.
6529: </p>
6530: DOWNLOAD
6531: $r->print(&show_grading_menu_form(&get_symb($r,1)));
6532: return '';
6533: }
6534:
6535: =pod
6536:
6537: =back
6538:
6539: =cut
6540:
6541: #-------- end of section for handling grading scantron forms -------
6542: #
6543: #-------------------------------------------------------------------
6544:
6545: #-------------------------- Menu interface -------------------------
6546: #
6547: #--- Show a Grading Menu button - Calls the next routine ---
6548: sub show_grading_menu_form {
6549: my ($symb)=@_;
6550: my $result.='<br /><form action="/adm/grades" method="post">'."\n".
6551: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
6552: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
6553: '<input type="hidden" name="command" value="gradingmenu" />'."\n".
6554: '<input type="submit" name="submit" value="Grading Menu" />'."\n".
6555: '</form>'."\n";
6556: return $result;
6557: }
6558:
6559: # -- Retrieve choices for grading form
6560: sub savedState {
6561: my %savedState = ();
6562: if ($env{'form.saveState'}) {
6563: foreach (split(/:/,$env{'form.saveState'})) {
6564: my ($key,$value) = split(/=/,$_,2);
6565: $savedState{$key} = $value;
6566: }
6567: }
6568: return \%savedState;
6569: }
6570:
6571: #--- Displays the main menu page -------
6572: sub gradingmenu {
6573: my ($request) = @_;
6574: my ($symb)=&get_symb($request);
6575: if (!$symb) {return '';}
6576: my $probTitle = &Apache::lonnet::gettitle($symb);
6577:
6578: $request->print(<<GRADINGMENUJS);
6579: <script type="text/javascript" language="javascript">
6580: function checkChoice(formname,val,cmdx) {
6581: if (val <= 2) {
6582: var cmd = radioSelection(formname.radioChoice);
6583: var cmdsave = cmd;
6584: } else {
6585: cmd = cmdx;
6586: cmdsave = 'submission';
6587: }
6588: formname.command.value = cmd;
6589: formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
6590: ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
6591: if (val < 5) formname.submit();
6592: if (val == 5) {
6593: if (!checkReceiptNo(formname,'notOK')) { return false;}
6594: formname.submit();
6595: }
6596: if (val < 7) formname.submit();
6597: }
6598:
6599: function checkReceiptNo(formname,nospace) {
6600: var receiptNo = formname.receipt.value;
6601: var checkOpt = false;
6602: if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
6603: if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
6604: if (checkOpt) {
6605: alert("Please enter a receipt number given by a student in the receipt box.");
6606: formname.receipt.value = "";
6607: formname.receipt.focus();
6608: return false;
6609: }
6610: return true;
6611: }
6612: </script>
6613: GRADINGMENUJS
6614: &commonJSfunctions($request);
6615: my $result='<h3> <span class="LC_info">Manual Grading/View Submission</span></h3>';
6616: my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
6617: $result.=$table;
6618: my (undef,$sections) = &getclasslist('all','0');
6619: my $savedState = &savedState();
6620: my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
6621: my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
6622: my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
6623: my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
6624:
6625: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
6626: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
6627: '<input type="hidden" name="handgrade" value="'.$hdgrade.'" />'."\n".
6628: '<input type="hidden" name="probTitle" value="'.$probTitle.'" />'."\n".
6629: '<input type="hidden" name="command" value="" />'."\n".
6630: '<input type="hidden" name="saveState" value="" />'."\n".
6631: '<input type="hidden" name="gradingMenu" value="1" />'."\n".
6632: '<input type="hidden" name="showgrading" value="yes" />'."\n";
6633:
6634: $result.='<table width="100%" border="0"><tr><td bgcolor=#777777>'."\n".
6635: '<table width="100%" border="0"><tr bgcolor="#e6ffff"><td colspan="2">'."\n".
6636: ' <b>Select a Grading/Viewing Option</b></td></tr>'."\n".
6637: '<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
6638:
6639: $result.='<table width="100%" border="0">';
6640: $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
6641: ' '.&mt('Select Section').': <select name="section">'."\n";
6642: if (ref($sections)) {
6643: foreach (sort (@$sections)) {
6644: $result.='<option value="'.$_.'" '.
6645: ($saveSec eq $_ ? 'selected="selected"':'').'>'.$_.'</option>'."\n";
6646: }
6647: }
6648: $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> ';
6649:
6650: $result.=&mt('Student Status').':'.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,undef);
6651:
6652: $result.='</td></tr>';
6653:
6654: $result.='<tr bgcolor="#ffffe6"valign="top"><td><label>'.
6655: '<input type="radio" name="radioChoice" value="submission" '.
6656: ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.'<b>'.&mt('Current Resource').':</b> '.&mt('For one or more students').
6657: '</label> <select name="submitonly">'.
6658: '<option value="yes" '.
6659: ($saveSub eq 'yes' ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>'.
6660: '<option value="queued" '.
6661: ($saveSub eq 'queued' ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>'.
6662: '<option value="graded" '.
6663: ($saveSub eq 'graded' ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>'.
6664: '<option value="incorrect" '.
6665: ($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>'.
6666: '<option value="all" '.
6667: ($saveSub eq 'all' ? 'selected="selected"' : '').'>'.&mt('with any status').'</option></select></td></tr>'."\n";
6668:
6669: $result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
6670: '<label><input type="radio" name="radioChoice" value="viewgrades" '.
6671: ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
6672: '<b>Current Resource:</b> For all students in selected section or course</label></td></tr>'."\n";
6673:
6674: $result.='<tr bgcolor="#ffffe6" valign="top"><td>'.
6675: '<label><input type="radio" name="radioChoice" value="pickStudentPage" '.
6676: ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
6677: 'The <b>complete</b> set/page/sequence: For one student</label></td></tr>'."\n";
6678:
6679: $result.='<tr bgcolor="#ffffe6"><td><br />'.
6680: '<input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="Next->" />'.
6681: '</td></tr></table>'."\n";
6682:
6683: $result.='</td><td valign="top">';
6684:
6685: $result.='<table width="100%" border="0">';
6686: $result.='<tr bgcolor="#ffffe6"><td>'.
6687: '<input type="button" onClick="javascript:checkChoice(this.form,\'3\',\'csvform\');" value="'.&mt('Upload').'" />'.
6688: ' '.&mt('scores from file').' </td></tr>'."\n";
6689:
6690: $result.='<tr bgcolor="#ffffe6"><td>'.
6691: '<input type="button" onClick="javascript:checkChoice(this.form,\'6\',\'processclicker\');" value="'.&mt('Process').'" />'.
6692: ' '.&mt('clicker file').' </td></tr>'."\n";
6693:
6694: $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
6695: '<input type="button" onClick="javascript:checkChoice(this.form,\'4\',\'scantron_selectphase\');'.
6696: '" value="'.&mt('Grade').'" /> scantron forms</td></tr>'."\n";
6697:
6698: if ((&Apache::lonnet::allowed('mgr',$env{'request.course.id'})) && ($symb)) {
6699: $result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
6700: '<input type="button" onClick="javascript:checkChoice(this.form,\'5\',\'verify\');" value="'.&mt('Verify').'" />'.
6701: ' '.&mt('receipt').': '.
6702: &Apache::lonnet::recprefix($env{'request.course.id'}).
6703: '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />'.
6704: '</td></tr>'."\n";
6705: }
6706: $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
6707: '<input type="button" onClick="javascript:this.form.action=\'/adm/helper/resettimes.helper\';this.form.submit();'.
6708: '" value="'.&mt('Manage').'" /> access times.</td></tr>'."\n";
6709: $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
6710: '<input type="button" onClick="javascript:this.form.command.value=\'codelist\';this.form.action=\'/adm/pickcode\';this.form.submit();'.
6711: '" value="'.&mt('View').'" /> saved CODEs.</td></tr>'."\n";
6712:
6713: $result.='</table>'."\n".
6714: '</td></tr></table>'."\n".
6715: '</td></tr></table></form>'."\n";
6716: return $result;
6717: }
6718:
6719: sub reset_perm {
6720: undef(%perm);
6721: }
6722:
6723: sub init_perm {
6724: &reset_perm();
6725: foreach my $test_perm ('vgr','mgr','opa') {
6726:
6727: my $scope = $env{'request.course.id'};
6728: if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
6729:
6730: $scope .= '/'.$env{'request.course.sec'};
6731: if ( $perm{$test_perm}=
6732: &Apache::lonnet::allowed($test_perm,$scope)) {
6733: $perm{$test_perm.'_section'}=$env{'request.course.sec'};
6734: } else {
6735: delete($perm{$test_perm});
6736: }
6737: }
6738: }
6739: }
6740:
6741: sub gather_clicker_ids {
6742: my %clicker_ids;
6743:
6744: my $classlist = &Apache::loncoursedata::get_classlist();
6745:
6746: # Set up a couple variables.
6747: my $username_idx = &Apache::loncoursedata::CL_SNAME();
6748: my $domain_idx = &Apache::loncoursedata::CL_SDOM();
6749:
6750: foreach my $student (keys(%$classlist)) {
6751:
6752: my $username = $classlist->{$student}->[$username_idx];
6753: my $domain = $classlist->{$student}->[$domain_idx];
6754: my $clickers =
6755: (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
6756: foreach my $id (split(/\,/,$clickers)) {
6757: $id=~s/^[\#0]+//;
6758: $id=~s/[\-\:]//g;
6759: if (exists($clicker_ids{$id})) {
6760: $clicker_ids{$id}.=','.$username.':'.$domain;
6761: } else {
6762: $clicker_ids{$id}=$username.':'.$domain;
6763: }
6764: }
6765: }
6766: return %clicker_ids;
6767: }
6768:
6769: sub gather_adv_clicker_ids {
6770: my %clicker_ids;
6771: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
6772: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6773: my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
6774: foreach my $element (sort(keys(%coursepersonnel))) {
6775: foreach my $person (split(/\,/,$coursepersonnel{$element})) {
6776: my ($puname,$pudom)=split(/\:/,$person);
6777: my $clickers =
6778: (&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
6779: foreach my $id (split(/\,/,$clickers)) {
6780: $id=~s/^[\#0]+//;
6781: $id=~s/[\-\:]//g;
6782: if (exists($clicker_ids{$id})) {
6783: $clicker_ids{$id}.=','.$puname.':'.$pudom;
6784: } else {
6785: $clicker_ids{$id}=$puname.':'.$pudom;
6786: }
6787: }
6788: }
6789: }
6790: return %clicker_ids;
6791: }
6792:
6793: sub clicker_grading_parameters {
6794: return ('gradingmechanism' => 'scalar',
6795: 'upfiletype' => 'scalar',
6796: 'specificid' => 'scalar',
6797: 'pcorrect' => 'scalar',
6798: 'pincorrect' => 'scalar');
6799: }
6800:
6801: sub process_clicker {
6802: my ($r)=@_;
6803: my ($symb)=&get_symb($r);
6804: if (!$symb) {return '';}
6805: my $result=&checkforfile_js();
6806: $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
6807: my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
6808: $result.=$table;
6809: $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
6810: $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
6811: $result.=' <b>'.&mt('Specify a file containing the clicker information for this resource').
6812: '.</b></td></tr>'."\n";
6813: $result.='<tr bgcolor=#ffffe6><td>'."\n";
6814: # Attempt to restore parameters from last session, set defaults if not present
6815: my %Saveable_Parameters=&clicker_grading_parameters();
6816: &Apache::loncommon::restore_course_settings('grades_clicker',
6817: \%Saveable_Parameters);
6818: if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
6819: if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
6820: if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
6821: if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
6822:
6823: my %checked;
6824: foreach my $gradingmechanism ('attendance','personnel','specific') {
6825: if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
6826: $checked{$gradingmechanism}="checked='checked'";
6827: }
6828: }
6829:
6830: my $upload=&mt("Upload File");
6831: my $type=&mt("Type");
6832: my $attendance=&mt("Award points just for participation");
6833: my $personnel=&mt("Correctness determined from response by course personnel");
6834: my $specific=&mt("Correctness determined from response with clicker ID(s)");
6835: my $pcorrect=&mt("Percentage points for correct solution");
6836: my $pincorrect=&mt("Percentage points for incorrect solution");
6837: my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
6838: ('iclicker' => 'i>clicker',
6839: 'interwrite' => 'interwrite PRS'));
6840: $symb = &Apache::lonenc::check_encrypt($symb);
6841: $result.=<<ENDUPFORM;
6842: <script type="text/javascript">
6843: function sanitycheck() {
6844: // Accept only integer percentages
6845: document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
6846: document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
6847: // Find out grading choice
6848: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
6849: if (document.forms.gradesupload.gradingmechanism[i].checked) {
6850: gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
6851: }
6852: }
6853: // By default, new choice equals user selection
6854: newgradingchoice=gradingchoice;
6855: // Not good to give more points for false answers than correct ones
6856: if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
6857: document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
6858: }
6859: // If new choice is attendance only, and old choice was correctness-based, restore defaults
6860: if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
6861: document.forms.gradesupload.pcorrect.value=100;
6862: document.forms.gradesupload.pincorrect.value=100;
6863: }
6864: // If the values are different, cannot be attendance only
6865: if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
6866: (gradingchoice=='attendance')) {
6867: newgradingchoice='personnel';
6868: }
6869: // Change grading choice to new one
6870: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
6871: if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
6872: document.forms.gradesupload.gradingmechanism[i].checked=true;
6873: } else {
6874: document.forms.gradesupload.gradingmechanism[i].checked=false;
6875: }
6876: }
6877: // Remember the old state
6878: document.forms.gradesupload.waschecked.value=newgradingchoice;
6879: }
6880: </script>
6881: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
6882: <input type="hidden" name="symb" value="$symb" />
6883: <input type="hidden" name="command" value="processclickerfile" />
6884: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
6885: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
6886: <input type="file" name="upfile" size="50" />
6887: <br /><label>$type: $selectform</label>
6888: <br /><label>$attendance: <input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" /></label>
6889: <br /><label>$personnel: <input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" /></label>
6890: <br /><label>$specific: <input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" /></label>
6891: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
6892: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
6893: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
6894: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
6895: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
6896: </form>
6897: ENDUPFORM
6898: $result.='</td></tr></table>'."\n".
6899: '</td></tr></table><br /><br />'."\n";
6900: $result.=&show_grading_menu_form($symb);
6901: return $result;
6902: }
6903:
6904: sub process_clicker_file {
6905: my ($r)=@_;
6906: my ($symb)=&get_symb($r);
6907: if (!$symb) {return '';}
6908:
6909: my %Saveable_Parameters=&clicker_grading_parameters();
6910: &Apache::loncommon::store_course_settings('grades_clicker',
6911: \%Saveable_Parameters);
6912:
6913: my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
6914: if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
6915: $result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
6916: return $result.&show_grading_menu_form($symb);
6917: }
6918: my %clicker_ids=&gather_clicker_ids();
6919: my %correct_ids;
6920: if ($env{'form.gradingmechanism'} eq 'personnel') {
6921: %correct_ids=&gather_adv_clicker_ids();
6922: }
6923: if ($env{'form.gradingmechanism'} eq 'specific') {
6924: foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
6925: $correct_id=~tr/a-z/A-Z/;
6926: $correct_id=~s/\s//gs;
6927: $correct_id=~s/^[\#0]+//;
6928: $correct_id=~s/[\-\:]//g;
6929: if ($correct_id) {
6930: $correct_ids{$correct_id}='specified';
6931: }
6932: }
6933: }
6934: if ($env{'form.gradingmechanism'} eq 'attendance') {
6935: $result.=&mt('Score based on attendance only');
6936: } else {
6937: my $number=0;
6938: $result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
6939: foreach my $id (sort(keys(%correct_ids))) {
6940: $result.='<br /><tt>'.$id.'</tt> - ';
6941: if ($correct_ids{$id} eq 'specified') {
6942: $result.=&mt('specified');
6943: } else {
6944: my ($uname,$udom)=split(/\:/,$correct_ids{$id});
6945: $result.=&Apache::loncommon::plainname($uname,$udom);
6946: }
6947: $number++;
6948: }
6949: $result.="</p>\n";
6950: if ($number==0) {
6951: $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
6952: return $result.&show_grading_menu_form($symb);
6953: }
6954: }
6955: if (length($env{'form.upfile'}) < 2) {
6956: $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
6957: '<span class="LC_error">',
6958: '</span>',
6959: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
6960: return $result.&show_grading_menu_form($symb);
6961: }
6962:
6963: # Were able to get all the info needed, now analyze the file
6964:
6965: $result.=&Apache::loncommon::studentbrowser_javascript();
6966: $symb = &Apache::lonenc::check_encrypt($symb);
6967: my $heading=&mt('Scanning clicker file');
6968: $result.=(<<ENDHEADER);
6969: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
6970: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
6971: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
6972: <form method="post" action="/adm/grades" name="clickeranalysis">
6973: <input type="hidden" name="symb" value="$symb" />
6974: <input type="hidden" name="command" value="assignclickergrades" />
6975: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
6976: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
6977: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
6978: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
6979: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
6980: ENDHEADER
6981: my %responses;
6982: my @questiontitles;
6983: my $errormsg='';
6984: my $number=0;
6985: if ($env{'form.upfiletype'} eq 'iclicker') {
6986: ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
6987: }
6988: if ($env{'form.upfiletype'} eq 'interwrite') {
6989: ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
6990: }
6991: $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
6992: '<input type="hidden" name="number" value="'.$number.'" />'.
6993: &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
6994: $env{'form.pcorrect'},$env{'form.pincorrect'}).
6995: '<br />';
6996: # Remember Question Titles
6997: # FIXME: Possibly need delimiter other than ":"
6998: for (my $i=0;$i<$number;$i++) {
6999: $result.='<input type="hidden" name="question:'.$i.'" value="'.
7000: &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
7001: }
7002: my $correct_count=0;
7003: my $student_count=0;
7004: my $unknown_count=0;
7005: # Match answers with usernames
7006: # FIXME: Possibly need delimiter other than ":"
7007: foreach my $id (keys(%responses)) {
7008: if ($correct_ids{$id}) {
7009: $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
7010: $correct_count++;
7011: } elsif ($clicker_ids{$id}) {
7012: $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
7013: $student_count++;
7014: } else {
7015: $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
7016: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
7017: "\n".&mt("Username").": <input type='text' name='uname".$id."' /> ".
7018: "\n".&mt("Domain").": ".
7019: &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).' '.
7020: &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
7021: $unknown_count++;
7022: }
7023: }
7024: $result.='<hr />'.
7025: &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
7026: if ($env{'form.gradingmechanism'} ne 'attendance') {
7027: if ($correct_count==0) {
7028: $errormsg.="Found no correct answers answers for grading!";
7029: } elsif ($correct_count>1) {
7030: $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
7031: }
7032: }
7033: if ($errormsg) {
7034: $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
7035: } else {
7036: $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
7037: }
7038: $result.='</form></td></tr></table>'."\n".
7039: '</td></tr></table><br /><br />'."\n";
7040: return $result.&show_grading_menu_form($symb);
7041: }
7042:
7043: sub iclicker_eval {
7044: my ($questiontitles,$responses)=@_;
7045: my $number=0;
7046: my $errormsg='';
7047: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
7048: my %components=&Apache::loncommon::record_sep($line);
7049: my @entries=map {$components{$_}} (sort(keys(%components)));
7050: if ($entries[0] eq 'Question') {
7051: for (my $i=3;$i<$#entries;$i+=6) {
7052: $$questiontitles[$number]=$entries[$i];
7053: $number++;
7054: }
7055: }
7056: if ($entries[0]=~/^\#/) {
7057: my $id=$entries[0];
7058: my @idresponses;
7059: $id=~s/^[\#0]+//;
7060: for (my $i=0;$i<$number;$i++) {
7061: my $idx=3+$i*6;
7062: push(@idresponses,$entries[$idx]);
7063: }
7064: $$responses{$id}=join(',',@idresponses);
7065: }
7066: }
7067: return ($errormsg,$number);
7068: }
7069:
7070: sub interwrite_eval {
7071: my ($questiontitles,$responses)=@_;
7072: my $number=0;
7073: my $errormsg='';
7074: my $skipline=1;
7075: my $questionnumber=0;
7076: my %idresponses=();
7077: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
7078: my %components=&Apache::loncommon::record_sep($line);
7079: my @entries=map {$components{$_}} (sort(keys(%components)));
7080: if ($entries[1] eq 'Time') { $skipline=0; next; }
7081: if ($entries[1] eq 'Response') { $skipline=1; }
7082: next if $skipline;
7083: if ($entries[0]!=$questionnumber) {
7084: $questionnumber=$entries[0];
7085: $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
7086: $number++;
7087: }
7088: my $id=$entries[4];
7089: $id=~s/^[\#0]+//;
7090: $id=~s/^v\d*\://i;
7091: $id=~s/[\-\:]//g;
7092: $idresponses{$id}[$number]=$entries[6];
7093: }
7094: foreach my $id (keys %idresponses) {
7095: $$responses{$id}=join(',',@{$idresponses{$id}});
7096: $$responses{$id}=~s/^\s*\,//;
7097: }
7098: return ($errormsg,$number);
7099: }
7100:
7101: sub assign_clicker_grades {
7102: my ($r)=@_;
7103: my ($symb)=&get_symb($r);
7104: if (!$symb) {return '';}
7105: # See which part we are saving to
7106: my ($partlist,$handgrade,$responseType) = &response_type($symb);
7107: # FIXME: This should probably look for the first handgradeable part
7108: my $part=$$partlist[0];
7109: # Start screen output
7110: my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
7111:
7112: my $heading=&mt('Assigning grades based on clicker file');
7113: $result.=(<<ENDHEADER);
7114: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
7115: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
7116: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
7117: ENDHEADER
7118: # Get correct result
7119: # FIXME: Possibly need delimiter other than ":"
7120: my @correct=();
7121: my $gradingmechanism=$env{'form.gradingmechanism'};
7122: my $number=$env{'form.number'};
7123: if ($gradingmechanism ne 'attendance') {
7124: foreach my $key (keys(%env)) {
7125: if ($key=~/^form\.correct\:/) {
7126: my @input=split(/\,/,$env{$key});
7127: for (my $i=0;$i<=$#input;$i++) {
7128: if (($correct[$i]) && ($input[$i]) &&
7129: ($correct[$i] ne $input[$i])) {
7130: $result.='<br /><span class="LC_warning">'.
7131: &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
7132: $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
7133: } elsif ($input[$i]) {
7134: $correct[$i]=$input[$i];
7135: }
7136: }
7137: }
7138: }
7139: for (my $i=0;$i<$number;$i++) {
7140: if (!$correct[$i]) {
7141: $result.='<br /><span class="LC_error">'.
7142: &mt('No correct result given for question "[_1]"!',
7143: $env{'form.question:'.$i}).'</span>';
7144: }
7145: }
7146: $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
7147: }
7148: # Start grading
7149: my $pcorrect=$env{'form.pcorrect'};
7150: my $pincorrect=$env{'form.pincorrect'};
7151: my $storecount=0;
7152: foreach my $key (keys(%env)) {
7153: my $user='';
7154: if ($key=~/^form\.student\:(.*)$/) {
7155: $user=$1;
7156: }
7157: if ($key=~/^form\.unknown\:(.*)$/) {
7158: my $id=$1;
7159: if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
7160: $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
7161: }
7162: }
7163: if ($user) {
7164: my @answer=split(/\,/,$env{$key});
7165: my $sum=0;
7166: for (my $i=0;$i<$number;$i++) {
7167: if ($answer[$i]) {
7168: if ($gradingmechanism eq 'attendance') {
7169: $sum+=$pcorrect;
7170: } else {
7171: if ($answer[$i] eq $correct[$i]) {
7172: $sum+=$pcorrect;
7173: } else {
7174: $sum+=$pincorrect;
7175: }
7176: }
7177: }
7178: }
7179: my $ave=$sum/(100*$number);
7180: # Store
7181: my ($username,$domain)=split(/\:/,$user);
7182: my %grades=();
7183: $grades{"resource.$part.solved"}='correct_by_override';
7184: $grades{"resource.$part.awarded"}=$ave;
7185: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
7186: my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
7187: $env{'request.course.id'},
7188: $domain,$username);
7189: if ($returncode ne 'ok') {
7190: $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
7191: } else {
7192: $storecount++;
7193: }
7194: }
7195: }
7196: # We are done
7197: $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
7198: '</td></tr></table>'."\n".
7199: '</td></tr></table><br /><br />'."\n";
7200: return $result.&show_grading_menu_form($symb);
7201: }
7202:
7203: sub handler {
7204: my $request=$_[0];
7205:
7206: &reset_perm();
7207: if ($env{'browser.mathml'}) {
7208: &Apache::loncommon::content_type($request,'text/xml');
7209: } else {
7210: &Apache::loncommon::content_type($request,'text/html');
7211: }
7212: $request->send_http_header;
7213: return '' if $request->header_only;
7214: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
7215: my $symb=&get_symb($request,1);
7216: my @commands=&Apache::loncommon::get_env_multiple('form.command');
7217: my $command=$commands[0];
7218: if ($#commands > 0) {
7219: &Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
7220: }
7221: $request->print(&Apache::loncommon::start_page('Grading'));
7222: if ($symb eq '' && $command eq '') {
7223: if ($env{'user.adv'}) {
7224: if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
7225: ($env{'form.codethree'})) {
7226: my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
7227: $env{'form.codethree'};
7228: my ($tsymb,$tuname,$tudom,$tcrsid)=
7229: &Apache::lonnet::checkin($token);
7230: if ($tsymb) {
7231: my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
7232: if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
7233: $request->print(&Apache::lonnet::ssi_body('/res/'.$url,
7234: ('grade_username' => $tuname,
7235: 'grade_domain' => $tudom,
7236: 'grade_courseid' => $tcrsid,
7237: 'grade_symb' => $tsymb)));
7238: } else {
7239: $request->print('<h3>Not authorized: '.$token.'</h3>');
7240: }
7241: } else {
7242: $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
7243: }
7244: } else {
7245: $request->print(&Apache::lonxml::tokeninputfield());
7246: }
7247: }
7248: } else {
7249: &init_perm();
7250: if ($command eq 'submission' && $perm{'vgr'}) {
7251: ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
7252: } elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
7253: &pickStudentPage($request);
7254: } elsif ($command eq 'displayPage' && $perm{'vgr'}) {
7255: &displayPage($request);
7256: } elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
7257: &updateGradeByPage($request);
7258: } elsif ($command eq 'processGroup' && $perm{'vgr'}) {
7259: &processGroup($request);
7260: } elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
7261: $request->print(&gradingmenu($request));
7262: } elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
7263: $request->print(&viewgrades($request));
7264: } elsif ($command eq 'handgrade' && $perm{'mgr'}) {
7265: $request->print(&processHandGrade($request));
7266: } elsif ($command eq 'editgrades' && $perm{'mgr'}) {
7267: $request->print(&editgrades($request));
7268: } elsif ($command eq 'verify' && $perm{'vgr'}) {
7269: $request->print(&verifyreceipt($request));
7270: } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
7271: $request->print(&process_clicker($request));
7272: } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
7273: $request->print(&process_clicker_file($request));
7274: } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
7275: $request->print(&assign_clicker_grades($request));
7276: } elsif ($command eq 'csvform' && $perm{'mgr'}) {
7277: $request->print(&upcsvScores_form($request));
7278: } elsif ($command eq 'csvupload' && $perm{'mgr'}) {
7279: $request->print(&csvupload($request));
7280: } elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
7281: $request->print(&csvuploadmap($request));
7282: } elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
7283: if ($env{'form.associate'} ne 'Reverse Association') {
7284: $request->print(&csvuploadoptions($request));
7285: } else {
7286: if ( $env{'form.upfile_associate'} ne 'reverse' ) {
7287: $env{'form.upfile_associate'} = 'reverse';
7288: } else {
7289: $env{'form.upfile_associate'} = 'forward';
7290: }
7291: $request->print(&csvuploadmap($request));
7292: }
7293: } elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
7294: $request->print(&csvuploadassign($request));
7295: } elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
7296: $request->print(&scantron_selectphase($request));
7297: } elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
7298: $request->print(&scantron_do_warning($request));
7299: } elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
7300: $request->print(&scantron_validate_file($request));
7301: } elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
7302: $request->print(&scantron_process_students($request));
7303: } elsif ($command eq 'scantronupload' &&
7304: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
7305: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
7306: $request->print(&scantron_upload_scantron_data($request));
7307: } elsif ($command eq 'scantronupload_save' &&
7308: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
7309: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
7310: $request->print(&scantron_upload_scantron_data_save($request));
7311: } elsif ($command eq 'scantron_download' &&
7312: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
7313: $request->print(&scantron_download_scantron_data($request));
7314: } elsif ($command) {
7315: $request->print("Access Denied ($command)");
7316: }
7317: }
7318: $request->print(&Apache::loncommon::end_page());
7319: return '';
7320: }
7321:
7322: 1;
7323:
7324: __END__;
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>