1: # The LearningOnline Network with CAPA
2: # The LON-CAPA Grading handler
3: #
4: # $Id: grades.pm,v 1.434 2007/08/24 00:32:00 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 %perm;
49:
50: # ----- These first few routines are general use routines.----
51: #
52: # --- Retrieve the parts from the metadata file.---
53: sub getpartlist {
54: my ($symb) = @_;
55: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
56: my $partorder = &Apache::lonnet::metadata($url, 'partorder');
57: my @parts;
58: if ($partorder) {
59: for my $part (split (/,/,$partorder)) {
60: if (!&Apache::loncommon::check_if_partid_hidden($part,$symb)) {
61: push(@parts, $part);
62: }
63: }
64: } else {
65: my $metadata = &Apache::lonnet::metadata($url, 'packages');
66: foreach (split(/\,/,$metadata)) {
67: if ($_ =~ /^part_(.*)$/) {
68: if (!&Apache::loncommon::check_if_partid_hidden($1,$symb)) {
69: push(@parts, $1);
70: }
71: }
72: }
73: }
74: my @stores;
75: foreach my $part (@parts) {
76: my (@metakeys) = split(/,/,&Apache::lonnet::metadata($url,'keys'));
77: foreach my $key (@metakeys) {
78: if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
79: }
80: }
81: return @stores;
82: }
83:
84: # --- Get the symbolic name of a problem and the url
85: sub get_symb {
86: my ($request,$silent) = @_;
87: (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
88: my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
89: if ($symb eq '') {
90: if (!$silent) {
91: $request->print("Unable to handle ambiguous references:$url:.");
92: return ();
93: }
94: }
95: &Apache::lonenc::check_decrypt(\$symb);
96: return ($symb);
97: }
98:
99: #--- Format fullname, username:domain if different for display
100: #--- Use anywhere where the student names are listed
101: sub nameUserString {
102: my ($type,$fullname,$uname,$udom) = @_;
103: if ($type eq 'header') {
104: return '<b> Fullname </b><span class="LC_internal_info">(Username)</span>';
105: } else {
106: return ' '.$fullname.'<span class="LC_internal_info"> ('.$uname.
107: ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
108: }
109: }
110:
111: #--- Get the partlist and the response type for a given problem. ---
112: #--- Indicate if a response type is coded handgraded or not. ---
113: sub response_type {
114: my ($symb) = shift;
115:
116: my $navmap = Apache::lonnavmaps::navmap->new();
117: my $res = $navmap->getBySymb($symb);
118: my $partlist = $res->parts();
119: my %vPart =
120: map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
121: my (%response_types,%handgrade);
122: foreach my $part (@{ $partlist }) {
123: next if (%vPart && !exists($vPart{$part}));
124:
125: my @types = $res->responseType($part);
126: my @ids = $res->responseIds($part);
127: for (my $i=0; $i < scalar(@ids); $i++) {
128: $response_types{$part}{$ids[$i]} = $types[$i];
129: $handgrade{$part.'_'.$ids[$i]} =
130: &Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
131: '.handgrade',$symb);
132: }
133: }
134: return ($partlist,\%handgrade,\%response_types);
135: }
136:
137: sub flatten_responseType {
138: my ($responseType) = @_;
139: my @part_response_id =
140: map {
141: my $part = $_;
142: map {
143: [$part,$_]
144: } sort(keys(%{ $responseType->{$part} }));
145: } sort(keys(%$responseType));
146: return @part_response_id;
147: }
148:
149: sub get_display_part {
150: my ($partID,$symb)=@_;
151: my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
152: if (defined($display) and $display ne '') {
153: $display.= " (<span class=\"LC_internal_info\">id $partID</span>)";
154: } else {
155: $display=$partID;
156: }
157: return $display;
158: }
159:
160: #--- Show resource title
161: #--- and parts and response type
162: sub showResourceInfo {
163: my ($symb,$probTitle,$checkboxes) = @_;
164: my $col=3;
165: if ($checkboxes) { $col=4; }
166: my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
167: $result .='<table border="0">';
168: my ($partlist,$handgrade,$responseType) = &response_type($symb);
169: my %resptype = ();
170: my $hdgrade='no';
171: my %partsseen;
172: foreach my $partID (sort keys(%$responseType)) {
173: foreach my $resID (sort keys(%{ $responseType->{$partID} })) {
174: my $handgrade=$$handgrade{$partID.'_'.$resID};
175: my $responsetype = $responseType->{$partID}->{$resID};
176: $hdgrade = $handgrade if ($handgrade eq 'yes');
177: $result.='<tr>';
178: if ($checkboxes) {
179: if (exists($partsseen{$partID})) {
180: $result.="<td> </td>";
181: } else {
182: $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
183: }
184: $partsseen{$partID}=1;
185: }
186: my $display_part=&get_display_part($partID,$symb);
187: $result.='<td><b>Part: </b>'.$display_part.' <span class="LC_internal_info">'.
188: $resID.'</span></td>'.
189: '<td><b>Type: </b>'.$responsetype.'</td></tr>';
190: # '<td><b>Handgrade: </b>'.$handgrade.'</td></tr>';
191: }
192: }
193: $result.='</table>'."\n";
194: return $result,$responseType,$hdgrade,$partlist,$handgrade;
195: }
196:
197: sub reset_caches {
198: &reset_analyze_cache();
199: &reset_perm();
200: }
201:
202: {
203: my %analyze_cache;
204:
205: sub reset_analyze_cache {
206: undef(%analyze_cache);
207: }
208:
209: sub get_analyze {
210: my ($symb,$uname,$udom)=@_;
211: my $key = "$symb\0$uname\0$udom";
212: return $analyze_cache{$key} if (exists($analyze_cache{$key}));
213:
214: my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
215: $url=&Apache::lonnet::clutter($url);
216: my $subresult=&Apache::lonnet::ssi($url,
217: ('grade_target' => 'analyze'),
218: ('grade_domain' => $udom),
219: ('grade_symb' => $symb),
220: ('grade_courseid' =>
221: $env{'request.course.id'}),
222: ('grade_username' => $uname));
223: (undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
224: my %analyze=&Apache::lonnet::str2hash($subresult);
225: return $analyze_cache{$key} = \%analyze;
226: }
227:
228: sub get_order {
229: my ($partid,$respid,$symb,$uname,$udom)=@_;
230: my $analyze = &get_analyze($symb,$uname,$udom);
231: return $analyze->{"$partid.$respid.shown"};
232: }
233:
234: sub get_radiobutton_correct_foil {
235: my ($partid,$respid,$symb,$uname,$udom)=@_;
236: my $analyze = &get_analyze($symb,$uname,$udom);
237: foreach my $foil (@{&get_order($partid,$respid,$symb,$uname,$udom)}) {
238: if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
239: return $foil;
240: }
241: }
242: }
243: }
244:
245: #--- Clean response type for display
246: #--- Currently filters option/rank/radiobutton/match/essay/Task
247: # response types only.
248: sub cleanRecord {
249: my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
250: $uname,$udom) = @_;
251: my $grayFont = '<span class="LC_internal_info">';
252: if ($response =~ /^(option|rank)$/) {
253: my %answer=&Apache::lonnet::str2hash($answer);
254: my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
255: my ($toprow,$bottomrow);
256: foreach my $foil (@$order) {
257: if ($grading{$foil} == 1) {
258: $toprow.='<td><b>'.$answer{$foil}.' </b></td>';
259: } else {
260: $toprow.='<td><i>'.$answer{$foil}.' </i></td>';
261: }
262: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
263: }
264: return '<blockquote><table border="1">'.
265: '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
266: '<tr valign="top"><td>'.$grayFont.'Option ID</span></td>'.
267: $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
268: } elsif ($response eq 'match') {
269: my %answer=&Apache::lonnet::str2hash($answer);
270: my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
271: my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
272: my ($toprow,$middlerow,$bottomrow);
273: foreach my $foil (@$order) {
274: my $item=shift(@items);
275: if ($grading{$foil} == 1) {
276: $toprow.='<td><b>'.$item.' </b></td>';
277: $middlerow.='<td><b>'.$grayFont.$answer{$foil}.' </span></b></td>';
278: } else {
279: $toprow.='<td><i>'.$item.' </i></td>';
280: $middlerow.='<td><i>'.$grayFont.$answer{$foil}.' </span></i></td>';
281: }
282: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
283: }
284: return '<blockquote><table border="1">'.
285: '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
286: '<tr valign="top"><td>'.$grayFont.'Item ID</span></td>'.
287: $middlerow.'</tr>'.
288: '<tr valign="top"><td>'.$grayFont.'Option ID</span></td>'.
289: $bottomrow.'</tr>'.'</table></blockquote>';
290: } elsif ($response eq 'radiobutton') {
291: my %answer=&Apache::lonnet::str2hash($answer);
292: my ($toprow,$bottomrow);
293: my $correct =
294: &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
295: foreach my $foil (@$order) {
296: if (exists($answer{$foil})) {
297: if ($foil eq $correct) {
298: $toprow.='<td><b>true</b></td>';
299: } else {
300: $toprow.='<td><i>true</i></td>';
301: }
302: } else {
303: $toprow.='<td>false</td>';
304: }
305: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
306: }
307: return '<blockquote><table border="1">'.
308: '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
309: '<tr valign="top"><td>'.$grayFont.'Option ID</span></td>'.
310: $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
311: } elsif ($response eq 'essay') {
312: if (! exists ($env{'form.'.$symb})) {
313: my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
314: $env{'course.'.$env{'request.course.id'}.'.domain'},
315: $env{'course.'.$env{'request.course.id'}.'.num'});
316:
317: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
318: $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
319: $env{'form.kwclr'} = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
320: $env{'form.kwsize'} = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
321: $env{'form.kwstyle'} = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
322: $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
323: }
324: $answer =~ s-\n-<br />-g;
325: return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
326: } elsif ( $response eq 'organic') {
327: my $result='Smile representation: "<tt>'.$answer.'</tt>"';
328: my $jme=$record->{$version."resource.$partid.$respid.molecule"};
329: $result.=&Apache::chemresponse::jme_img($jme,$answer,400);
330: return $result;
331: } elsif ( $response eq 'Task') {
332: if ( $answer eq 'SUBMITTED') {
333: my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
334: my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
335: return $result;
336: } elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
337: my @matches = grep(/^\Q$version\E.*?\.instance$/,
338: keys(%{$record}));
339: return join('<br />',($version,@matches));
340:
341:
342: } else {
343: my $result =
344: '<p>'
345: .&mt('Overall result: [_1]',
346: $record->{$version."resource.$respid.$partid.status"})
347: .'</p>';
348:
349: $result .= '<ul>';
350: my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
351: keys(%{$record}));
352: foreach my $grade (sort(@grade)) {
353: my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
354: $result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
355: $dim, $record->{$grade}).
356: '</li>';
357: }
358: $result.='</ul>';
359: return $result;
360: }
361:
362: }
363: return $answer;
364: }
365:
366: #-- A couple of common js functions
367: sub commonJSfunctions {
368: my $request = shift;
369: $request->print(<<COMMONJSFUNCTIONS);
370: <script type="text/javascript" language="javascript">
371: function radioSelection(radioButton) {
372: var selection=null;
373: if (radioButton.length > 1) {
374: for (var i=0; i<radioButton.length; i++) {
375: if (radioButton[i].checked) {
376: return radioButton[i].value;
377: }
378: }
379: } else {
380: if (radioButton.checked) return radioButton.value;
381: }
382: return selection;
383: }
384:
385: function pullDownSelection(selectOne) {
386: var selection="";
387: if (selectOne.length > 1) {
388: for (var i=0; i<selectOne.length; i++) {
389: if (selectOne[i].selected) {
390: return selectOne[i].value;
391: }
392: }
393: } else {
394: // only one value it must be the selected one
395: return selectOne.value;
396: }
397: }
398: </script>
399: COMMONJSFUNCTIONS
400: }
401:
402: #--- Dumps the class list with usernames,list of sections,
403: #--- section, ids and fullnames for each user.
404: sub getclasslist {
405: my ($getsec,$filterlist) = @_;
406: my @getsec;
407: if (!ref($getsec)) {
408: if ($getsec ne '' && $getsec ne 'all') {
409: @getsec=($getsec);
410: }
411: } else {
412: @getsec=@{$getsec};
413: }
414: if (grep(/^all$/,@getsec)) { undef(@getsec); }
415:
416: my $classlist=&Apache::loncoursedata::get_classlist();
417: # Bail out if we were unable to get the classlist
418: return if (! defined($classlist));
419: #
420: my %sections;
421: my %fullnames;
422: foreach my $student (keys(%$classlist)) {
423: my $end =
424: $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
425: my $start =
426: $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
427: my $id =
428: $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
429: my $section =
430: $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
431: my $fullname =
432: $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
433: my $status =
434: $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
435: # filter students according to status selected
436: if ($filterlist && $env{'form.Status'} ne 'Any') {
437: if ($env{'form.Status'} ne $status) {
438: delete ($classlist->{$student});
439: next;
440: }
441: }
442: $section = ($section ne '' ? $section : 'none');
443: if (&canview($section)) {
444: if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
445: $sections{$section}++;
446: $fullnames{$student}=$fullname;
447: } else {
448: delete($classlist->{$student});
449: }
450: } else {
451: delete($classlist->{$student});
452: }
453: }
454: my %seen = ();
455: my @sections = sort(keys(%sections));
456: return ($classlist,\@sections,\%fullnames);
457: }
458:
459: sub canmodify {
460: my ($sec)=@_;
461: if ($perm{'mgr'}) {
462: if (!defined($perm{'mgr_section'})) {
463: # can modify whole class
464: return 1;
465: } else {
466: if ($sec eq $perm{'mgr_section'}) {
467: #can modify the requested section
468: return 1;
469: } else {
470: # can't modify the request section
471: return 0;
472: }
473: }
474: }
475: #can't modify
476: return 0;
477: }
478:
479: sub canview {
480: my ($sec)=@_;
481: if ($perm{'vgr'}) {
482: if (!defined($perm{'vgr_section'})) {
483: # can modify whole class
484: return 1;
485: } else {
486: if ($sec eq $perm{'vgr_section'}) {
487: #can modify the requested section
488: return 1;
489: } else {
490: # can't modify the request section
491: return 0;
492: }
493: }
494: }
495: #can't modify
496: return 0;
497: }
498:
499: #--- Retrieve the grade status of a student for all the parts
500: sub student_gradeStatus {
501: my ($symb,$udom,$uname,$partlist) = @_;
502: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
503: my %partstatus = ();
504: foreach (@$partlist) {
505: my ($status,undef) = split(/_/,$record{"resource.$_.solved"},2);
506: $status = 'nothing' if ($status eq '');
507: $partstatus{$_} = $status;
508: my $subkey = "resource.$_.submitted_by";
509: $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
510: }
511: return %partstatus;
512: }
513:
514: # hidden form and javascript that calls the form
515: # Use by verifyscript and viewgrades
516: # Shows a student's view of problem and submission
517: sub jscriptNform {
518: my ($symb) = @_;
519: my $jscript='<script type="text/javascript" language="javascript">'."\n".
520: ' function viewOneStudent(user,domain) {'."\n".
521: ' document.onestudent.student.value = user;'."\n".
522: ' document.onestudent.userdom.value = domain;'."\n".
523: ' document.onestudent.submit();'."\n".
524: ' }'."\n".
525: '</script>'."\n";
526: $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
527: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
528: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
529: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
530: '<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n".
531: '<input type="hidden" name="command" value="submission" />'."\n".
532: '<input type="hidden" name="student" value="" />'."\n".
533: '<input type="hidden" name="userdom" value="" />'."\n".
534: '</form>'."\n";
535: return $jscript;
536: }
537:
538: # Given the score (as a number [0-1] and the weight) what is the final
539: # point value? This function will round to the nearest tenth, third,
540: # or quarter if one of those is within the tolerance of .00001.
541: sub compute_points {
542: my ($score, $weight) = @_;
543:
544: my $tolerance = .00001;
545: my $points = $score * $weight;
546:
547: # Check for nearness to 1/x.
548: my $check_for_nearness = sub {
549: my ($factor) = @_;
550: my $num = ($points * $factor) + $tolerance;
551: my $floored_num = floor($num);
552: if ($num - $floored_num < 2 * $tolerance * $factor) {
553: return $floored_num / $factor;
554: }
555: return $points;
556: };
557:
558: $points = $check_for_nearness->(10);
559: $points = $check_for_nearness->(3);
560: $points = $check_for_nearness->(4);
561:
562: return $points;
563: }
564:
565: #------------------ End of general use routines --------------------
566:
567: #
568: # Find most similar essay
569: #
570:
571: sub most_similar {
572: my ($uname,$udom,$uessay,$old_essays)=@_;
573:
574: # ignore spaces and punctuation
575:
576: $uessay=~s/\W+/ /gs;
577:
578: # ignore empty submissions (occuring when only files are sent)
579:
580: unless ($uessay=~/\w+/) { return ''; }
581:
582: # these will be returned. Do not care if not at least 50 percent similar
583: my $limit=0.6;
584: my $sname='';
585: my $sdom='';
586: my $scrsid='';
587: my $sessay='';
588: # go through all essays ...
589: foreach my $tkey (keys(%$old_essays)) {
590: my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
591: # ... except the same student
592: next if (($tname eq $uname) && ($tdom eq $udom));
593: my $tessay=$old_essays->{$tkey};
594: $tessay=~s/\W+/ /gs;
595: # String similarity gives up if not even limit
596: my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
597: # Found one
598: if ($tsimilar>$limit) {
599: $limit=$tsimilar;
600: $sname=$tname;
601: $sdom=$tdom;
602: $scrsid=$tcrsid;
603: $sessay=$old_essays->{$tkey};
604: }
605: }
606: if ($limit>0.6) {
607: return ($sname,$sdom,$scrsid,$sessay,$limit);
608: } else {
609: return ('','','','',0);
610: }
611: }
612:
613: #-------------------------------------------------------------------
614:
615: #------------------------------------ Receipt Verification Routines
616: #
617: #--- Check whether a receipt number is valid.---
618: sub verifyreceipt {
619: my $request = shift;
620:
621: my $courseid = $env{'request.course.id'};
622: my $receipt = &Apache::lonnet::recprefix($courseid).'-'.
623: $env{'form.receipt'};
624: $receipt =~ s/[^\-\d]//g;
625: my ($symb) = &get_symb($request);
626:
627: my $title.='<h3><span class="LC_info">Verifying Submission Receipt '.
628: $receipt.'</h3></span>'."\n".
629: '<h4><b>Resource: </b>'.$env{'form.probTitle'}.'</h4><br /><br />'."\n";
630:
631: my ($string,$contents,$matches) = ('','',0);
632: my (undef,undef,$fullname) = &getclasslist('all','0');
633:
634: my $receiptparts=0;
635: if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
636: $env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
637: my $parts=['0'];
638: if ($receiptparts) { ($parts)=&response_type($symb); }
639: foreach (sort
640: {
641: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
642: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
643: }
644: return $a cmp $b;
645: } (keys(%$fullname))) {
646: my ($uname,$udom)=split(/\:/);
647: foreach my $part (@$parts) {
648: if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
649: $contents.='<tr bgcolor="#ffffe6"><td> '."\n".
650: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
651: '\');" target="_self">'.$$fullname{$_}.'</a> </td>'."\n".
652: '<td> '.$uname.' </td>'.
653: '<td> '.$udom.' </td>';
654: if ($receiptparts) {
655: $contents.='<td> '.$part.' </td>';
656: }
657: $contents.='</tr>'."\n";
658:
659: $matches++;
660: }
661: }
662: }
663: if ($matches == 0) {
664: $string = $title.'No match found for the above receipt.';
665: } else {
666: $string = &jscriptNform($symb).$title.
667: 'The above receipt matches the following student'.
668: ($matches <= 1 ? '.' : 's.')."\n".
669: '<table border="0"><tr><td bgcolor="#777777">'."\n".
670: '<table border="0"><tr bgcolor="#e6ffff">'."\n".
671: '<td><b> Fullname </b></td>'."\n".
672: '<td><b> Username </b></td>'."\n".
673: '<td><b> Domain </b></td>';
674: if ($receiptparts) {
675: $string.='<td> Problem Part </td>';
676: }
677: $string.='</tr>'."\n".$contents.
678: '</table></td></tr></table>'."\n";
679: }
680: return $string.&show_grading_menu_form($symb);
681: }
682:
683: #--- This is called by a number of programs.
684: #--- Called from the Grading Menu - View/Grade an individual student
685: #--- Also called directly when one clicks on the subm button
686: # on the problem page.
687: sub listStudents {
688: my ($request) = shift;
689:
690: my ($symb) = &get_symb($request);
691: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
692: my $cnum = $env{"course.$env{'request.course.id'}.num"};
693: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
694: my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
695:
696: my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
697: $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ?
698: &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
699:
700: my $result='<h3><span class="LC_info"> '.$viewgrade.
701: ' Submissions for a Student or a Group of Students</span></h3>';
702:
703: my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
704:
705: $request->print(<<LISTJAVASCRIPT);
706: <script type="text/javascript" language="javascript">
707: function checkSelect(checkBox) {
708: var ctr=0;
709: var sense="";
710: if (checkBox.length > 1) {
711: for (var i=0; i<checkBox.length; i++) {
712: if (checkBox[i].checked) {
713: ctr++;
714: }
715: }
716: sense = "a student or group of students";
717: } else {
718: if (checkBox.checked) {
719: ctr = 1;
720: }
721: sense = "the student";
722: }
723: if (ctr == 0) {
724: alert("Please select "+sense+" before clicking on the Next button.");
725: return false;
726: }
727: document.gradesub.submit();
728: }
729:
730: function reLoadList(formname) {
731: if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
732: formname.command.value = 'submission';
733: formname.submit();
734: }
735: </script>
736: LISTJAVASCRIPT
737:
738: &commonJSfunctions($request);
739: $request->print($result);
740:
741: my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
742: my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
743: my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
744: "\n".$table.
745: ' <b>View Problem Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
746: '<label><input type="radio" name="vProb" value="yes" /> one student </label>'."\n".
747: '<label><input type="radio" name="vProb" value="all" /> all students </label><br />'."\n".
748: ' <b>View Answer: </b><label><input type="radio" name="vAns" value="no" /> no </label>'."\n".
749: '<label><input type="radio" name="vAns" value="yes" /> one student </label>'."\n".
750: '<label><input type="radio" name="vAns" value="all" checked="checked" /> all students </label><br />'."\n".
751: ' <b>Submissions: </b>'."\n";
752: if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
753: $gradeTable.='<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> essay part only </label>'."\n";
754: }
755:
756: my $saveStatus = $env{'form.Status'} eq '' ? 'Active' : $env{'form.Status'};
757: $env{'form.Status'} = $saveStatus;
758: $gradeTable.='<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> last submission only </label>'."\n".
759: '<label><input type="radio" name="lastSub" value="last" /> last submission & parts info </label>'."\n".
760: '<label><input type="radio" name="lastSub" value="datesub" /> by dates and submissions </label>'."\n".
761: '<label><input type="radio" name="lastSub" value="all" /> all details</label><br />'."\n".
762: ' <b>Grading Increments:</b> <select name="increment">'.
763: '<option value="1">Whole Points</option>'.
764: '<option value=".5">Half Points</option>'.
765: '<option value=".25">Quarter Points</option>'.
766: '<option value=".1">Tenths of a Point</option>'.
767: '</select>'.
768: &build_section_inputs().
769: '<input type="hidden" name="submitonly" value="'.$submitonly.'" />'."\n".
770: '<input type="hidden" name="handgrade" value="'.$env{'form.handgrade'}.'" /><br />'."\n".
771: '<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
772: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
773: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
774: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
775: '<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
776:
777: if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
778: $gradeTable.='<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n";
779: } else {
780: $gradeTable.='<b>Student Status:</b> '.
781: &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);').'<br />';
782: }
783:
784: $gradeTable.='To '.lc($viewgrade).' a submission or a group of submissions, click on the check box(es) '.
785: 'next to the student\'s name(s). Then click on the Next button.<br />'."\n".
786: '<input type="hidden" name="command" value="processGroup" />'."\n";
787:
788: # checkall buttons
789: $gradeTable.=&check_script('gradesub', 'stuinfo');
790: $gradeTable.='<input type="button" '."\n".
791: 'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
792: 'value="Next->" /> <br />'."\n";
793: $gradeTable.=&check_buttons();
794: $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />Check For Plagiarism</label>';
795: my ($classlist, undef, $fullname) = &getclasslist($getsec,'1');
796: $gradeTable.='<table border="0"><tr><td bgcolor="#777777">'.
797: '<table border="0"><tr bgcolor="#e6ffff">';
798: my $loop = 0;
799: while ($loop < 2) {
800: $gradeTable.='<td><b> No.</b> </td><td><b> Select </b></td>'.
801: '<td>'.&nameUserString('header').' Section/Group</td>';
802: if ($env{'form.showgrading'} eq 'yes'
803: && $submitonly ne 'queued'
804: && $submitonly ne 'all') {
805: foreach (sort(@$partlist)) {
806: my $display_part=&get_display_part((split(/_/))[0],$symb);
807: $gradeTable.='<td><b> Part: '.$display_part.
808: ' Status </b></td>';
809: }
810: } elsif ($submitonly eq 'queued') {
811: $gradeTable.='<td><b> '.&mt('Queue Status').' </b></td>';
812: }
813: $loop++;
814: # $gradeTable.='<td></td>' if ($loop%2 ==1);
815: }
816: $gradeTable.='</tr>'."\n";
817:
818: my $ctr = 0;
819: foreach my $student (sort
820: {
821: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
822: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
823: }
824: return $a cmp $b;
825: }
826: (keys(%$fullname))) {
827: my ($uname,$udom) = split(/:/,$student);
828:
829: my %status = ();
830:
831: if ($submitonly eq 'queued') {
832: my %queue_status =
833: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
834: $udom,$uname);
835: next if (!defined($queue_status{'gradingqueue'}));
836: $status{'gradingqueue'} = $queue_status{'gradingqueue'};
837: }
838:
839: if ($env{'form.showgrading'} eq 'yes'
840: && $submitonly ne 'queued'
841: && $submitonly ne 'all') {
842: (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
843: my $submitted = 0;
844: my $graded = 0;
845: my $incorrect = 0;
846: foreach (keys(%status)) {
847: $submitted = 1 if ($status{$_} ne 'nothing');
848: $graded = 1 if ($status{$_} =~ /^ungraded/);
849: $incorrect = 1 if ($status{$_} =~ /^incorrect/);
850:
851: my ($foo,$partid,$foo1) = split(/\./,$_);
852: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
853: $submitted = 0;
854: my ($part)=split(/\./,$partid);
855: $gradeTable.='<input type="hidden" name="'.
856: $student.':'.$part.':submitted_by" value="'.
857: $status{'resource.'.$partid.'.submitted_by'}.'" />';
858: }
859: }
860:
861: next if (!$submitted && ($submitonly eq 'yes' ||
862: $submitonly eq 'incorrect' ||
863: $submitonly eq 'graded'));
864: next if (!$graded && ($submitonly eq 'graded'));
865: next if (!$incorrect && $submitonly eq 'incorrect');
866: }
867:
868: $ctr++;
869: my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
870:
871: if ( $perm{'vgr'} eq 'F' ) {
872: $gradeTable.='<tr bgcolor="#ffffe6">' if ($ctr%2 ==1);
873: $gradeTable.='<td align="right">'.$ctr.' </td>'.
874: '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
875: $student.':'.$$fullname{$student}.':::SECTION'.$section.
876: ') " /> </label></td>'."\n".'<td>'.
877: &nameUserString(undef,$$fullname{$student},$uname,$udom).
878: ' '.$section.'</td>'."\n";
879:
880: if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
881: foreach (sort keys(%status)) {
882: next if (/^resource.*?submitted_by$/);
883: $gradeTable.='<td align="center"> '.$status{$_}.' </td>'."\n";
884: }
885: }
886: # $gradeTable.='<td></td>' if ($ctr%2 ==1);
887: $gradeTable.='</tr>'."\n" if ($ctr%2 ==0);
888: }
889: }
890: if ($ctr%2 ==1) {
891: $gradeTable.='<td> </td><td> </td><td> </td>';
892: if ($env{'form.showgrading'} eq 'yes'
893: && $submitonly ne 'queued'
894: && $submitonly ne 'all') {
895: foreach (@$partlist) {
896: $gradeTable.='<td> </td>';
897: }
898: } elsif ($submitonly eq 'queued') {
899: $gradeTable.='<td> </td>';
900: }
901: $gradeTable.='</tr>';
902: }
903:
904: $gradeTable.='</table></td></tr></table>'."\n".
905: '<input type="button" '.
906: 'onClick="javascript:checkSelect(this.form.stuinfo);" '.
907: 'value="Next->" /></form>'."\n";
908: if ($ctr == 0) {
909: my $num_students=(scalar(keys(%$fullname)));
910: if ($num_students eq 0) {
911: $gradeTable='<br /> <span class="LC_warning">There are no students currently enrolled.</span>';
912: } else {
913: my $submissions='submissions';
914: if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
915: if ($submitonly eq 'graded' ) { $submissions = 'ungraded submissions'; }
916: if ($submitonly eq 'queued' ) { $submissions = 'queued submissions'; }
917: $gradeTable='<br /> <span class="LC_warning">'.
918: 'No '.$submissions.' found for this resource for any students. ('.$num_students.
919: ' students checked for '.$submissions.')</span><br />';
920: }
921: } elsif ($ctr == 1) {
922: $gradeTable =~ s/type=checkbox/type=checkbox checked/;
923: }
924: $gradeTable.=&show_grading_menu_form($symb);
925: $request->print($gradeTable);
926: return '';
927: }
928:
929: #---- Called from the listStudents routine
930:
931: sub check_script {
932: my ($form, $type)=@_;
933: my $chkallscript='<script type="text/javascript">
934: function checkall() {
935: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
936: ele = document.forms.'.$form.'.elements[i];
937: if (ele.name == "'.$type.'") {
938: document.forms.'.$form.'.elements[i].checked=true;
939: }
940: }
941: }
942:
943: function checksec() {
944: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
945: ele = document.forms.'.$form.'.elements[i];
946: string = document.forms.'.$form.'.chksec.value;
947: if
948: (ele.value.indexOf(":::SECTION"+string)>0) {
949: document.forms.'.$form.'.elements[i].checked=true;
950: }
951: }
952: }
953:
954:
955: function uncheckall() {
956: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
957: ele = document.forms.'.$form.'.elements[i];
958: if (ele.name == "'.$type.'") {
959: document.forms.'.$form.'.elements[i].checked=false;
960: }
961: }
962: }
963:
964: </script>'."\n";
965: return $chkallscript;
966: }
967:
968: sub check_buttons {
969: my $buttons.='<input type="button" onclick="checkall()" value="Check All" />';
970: $buttons.='<input type="button" onclick="uncheckall()" value="Uncheck All" /> ';
971: $buttons.='<input type="button" onclick="checksec()" value="Check Section/Group" />';
972: $buttons.='<input type="text" size="5" name="chksec" /> ';
973: return $buttons;
974: }
975:
976: # Displays the submissions for one student or a group of students
977: sub processGroup {
978: my ($request) = shift;
979: my $ctr = 0;
980: my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
981: my $total = scalar(@stuchecked)-1;
982:
983: foreach my $student (@stuchecked) {
984: my ($uname,$udom,$fullname) = split(/:/,$student);
985: $env{'form.student'} = $uname;
986: $env{'form.userdom'} = $udom;
987: $env{'form.fullname'} = $fullname;
988: &submission($request,$ctr,$total);
989: $ctr++;
990: }
991: return '';
992: }
993:
994: #------------------------------------------------------------------------------------
995: #
996: #-------------------------- Next few routines handles grading by student, essentially
997: # handles essay response type problem/part
998: #
999: #--- Javascript to handle the submission page functionality ---
1000: sub sub_page_js {
1001: my $request = shift;
1002: $request->print(<<SUBJAVASCRIPT);
1003: <script type="text/javascript" language="javascript">
1004: function updateRadio(formname,id,weight) {
1005: var gradeBox = formname["GD_BOX"+id];
1006: var radioButton = formname["RADVAL"+id];
1007: var oldpts = formname["oldpts"+id].value;
1008: var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1009: gradeBox.value = pts;
1010: var resetbox = false;
1011: if (isNaN(pts) || pts < 0) {
1012: alert("A number equal or greater than 0 is expected. Entered value = "+pts);
1013: for (var i=0; i<radioButton.length; i++) {
1014: if (radioButton[i].checked) {
1015: gradeBox.value = i;
1016: resetbox = true;
1017: }
1018: }
1019: if (!resetbox) {
1020: formtextbox.value = "";
1021: }
1022: return;
1023: }
1024:
1025: if (pts > weight) {
1026: var resp = confirm("You entered a value ("+pts+
1027: ") greater than the weight for the part. Accept?");
1028: if (resp == false) {
1029: gradeBox.value = oldpts;
1030: return;
1031: }
1032: }
1033:
1034: for (var i=0; i<radioButton.length; i++) {
1035: radioButton[i].checked=false;
1036: if (pts == i && pts != "") {
1037: radioButton[i].checked=true;
1038: }
1039: }
1040: updateSelect(formname,id);
1041: formname["stores"+id].value = "0";
1042: }
1043:
1044: function writeBox(formname,id,pts) {
1045: var gradeBox = formname["GD_BOX"+id];
1046: if (checkSolved(formname,id) == 'update') {
1047: gradeBox.value = pts;
1048: } else {
1049: var oldpts = formname["oldpts"+id].value;
1050: gradeBox.value = oldpts;
1051: var radioButton = formname["RADVAL"+id];
1052: for (var i=0; i<radioButton.length; i++) {
1053: radioButton[i].checked=false;
1054: if (i == oldpts) {
1055: radioButton[i].checked=true;
1056: }
1057: }
1058: }
1059: formname["stores"+id].value = "0";
1060: updateSelect(formname,id);
1061: return;
1062: }
1063:
1064: function clearRadBox(formname,id) {
1065: if (checkSolved(formname,id) == 'noupdate') {
1066: updateSelect(formname,id);
1067: return;
1068: }
1069: gradeSelect = formname["GD_SEL"+id];
1070: for (var i=0; i<gradeSelect.length; i++) {
1071: if (gradeSelect[i].selected) {
1072: var selectx=i;
1073: }
1074: }
1075: var stores = formname["stores"+id];
1076: if (selectx == stores.value) { return };
1077: var gradeBox = formname["GD_BOX"+id];
1078: gradeBox.value = "";
1079: var radioButton = formname["RADVAL"+id];
1080: for (var i=0; i<radioButton.length; i++) {
1081: radioButton[i].checked=false;
1082: }
1083: stores.value = selectx;
1084: }
1085:
1086: function checkSolved(formname,id) {
1087: if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1088: var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
1089: if (!reply) {return "noupdate";}
1090: formname.overRideScore.value = 'yes';
1091: }
1092: return "update";
1093: }
1094:
1095: function updateSelect(formname,id) {
1096: formname["GD_SEL"+id][0].selected = true;
1097: return;
1098: }
1099:
1100: //=========== Check that a point is assigned for all the parts ============
1101: function checksubmit(formname,val,total,parttot) {
1102: formname.gradeOpt.value = val;
1103: if (val == "Save & Next") {
1104: for (i=0;i<=total;i++) {
1105: for (j=0;j<parttot;j++) {
1106: var partid = formname["partid"+i+"_"+j].value;
1107: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1108: var points = formname["GD_BOX"+i+"_"+partid].value;
1109: if (points == "") {
1110: var name = formname["name"+i].value;
1111: var studentID = (name != '' ? name : formname["unamedom"+i].value);
1112: var resp = confirm("You did not assign a score for "+studentID+
1113: ", part "+partid+". Continue?");
1114: if (resp == false) {
1115: formname["GD_BOX"+i+"_"+partid].focus();
1116: return false;
1117: }
1118: }
1119: }
1120:
1121: }
1122: }
1123:
1124: }
1125: if (val == "Grade Student") {
1126: formname.showgrading.value = "yes";
1127: if (formname.Status.value == "") {
1128: formname.Status.value = "Active";
1129: }
1130: formname.studentNo.value = total;
1131: }
1132: formname.submit();
1133: }
1134:
1135: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
1136: function checkSubmitPage(formname,total) {
1137: noscore = new Array(100);
1138: var ptr = 0;
1139: for (i=1;i<total;i++) {
1140: var partid = formname["q_"+i].value;
1141: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1142: var points = formname["GD_BOX"+i+"_"+partid].value;
1143: var status = formname["solved"+i+"_"+partid].value;
1144: if (points == "" && status != "correct_by_student") {
1145: noscore[ptr] = i;
1146: ptr++;
1147: }
1148: }
1149: }
1150: if (ptr != 0) {
1151: var sense = ptr == 1 ? ": " : "s: ";
1152: var prolist = "";
1153: if (ptr == 1) {
1154: prolist = noscore[0];
1155: } else {
1156: var i = 0;
1157: while (i < ptr-1) {
1158: prolist += noscore[i]+", ";
1159: i++;
1160: }
1161: prolist += "and "+noscore[i];
1162: }
1163: var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
1164: if (resp == false) {
1165: return false;
1166: }
1167: }
1168:
1169: formname.submit();
1170: }
1171: </script>
1172: SUBJAVASCRIPT
1173: }
1174:
1175: #--- javascript for essay type problem --
1176: sub sub_page_kw_js {
1177: my $request = shift;
1178: my $iconpath = $request->dir_config('lonIconsURL');
1179: &commonJSfunctions($request);
1180:
1181: my $inner_js_msg_central=<<INNERJS;
1182: <script text="text/javascript">
1183: function checkInput() {
1184: opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
1185: var nmsg = opener.document.SCORE.savemsgN.value;
1186: var usrctr = document.msgcenter.usrctr.value;
1187: var newval = opener.document.SCORE["newmsg"+usrctr];
1188: newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
1189:
1190: var msgchk = "";
1191: if (document.msgcenter.subchk.checked) {
1192: msgchk = "msgsub,";
1193: }
1194: var includemsg = 0;
1195: for (var i=1; i<=nmsg; i++) {
1196: var opnmsg = opener.document.SCORE["savemsg"+i];
1197: var frmmsg = document.msgcenter["msg"+i];
1198: opnmsg.value = opener.checkEntities(frmmsg.value);
1199: var showflg = opener.document.SCORE["shownOnce"+i];
1200: showflg.value = "1";
1201: var chkbox = document.msgcenter["msgn"+i];
1202: if (chkbox.checked) {
1203: msgchk += "savemsg"+i+",";
1204: includemsg = 1;
1205: }
1206: }
1207: if (document.msgcenter.newmsgchk.checked) {
1208: msgchk += "newmsg"+usrctr;
1209: includemsg = 1;
1210: }
1211: imgformname = opener.document.SCORE["mailicon"+usrctr];
1212: imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
1213: var includemsg = opener.document.SCORE["includemsg"+usrctr];
1214: includemsg.value = msgchk;
1215:
1216: self.close()
1217:
1218: }
1219: </script>
1220: INNERJS
1221:
1222: my $inner_js_highlight_central=<<INNERJS;
1223: <script type="text/javascript">
1224: function updateChoice(flag) {
1225: opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
1226: opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
1227: opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
1228: opener.document.SCORE.refresh.value = "on";
1229: if (opener.document.SCORE.keywords.value!=""){
1230: opener.document.SCORE.submit();
1231: }
1232: self.close()
1233: }
1234: </script>
1235: INNERJS
1236:
1237: my $start_page_msg_central =
1238: &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
1239: {'js_ready' => 1,
1240: 'only_body' => 1,
1241: 'bgcolor' =>'#FFFFFF',});
1242: my $end_page_msg_central =
1243: &Apache::loncommon::end_page({'js_ready' => 1});
1244:
1245:
1246: my $start_page_highlight_central =
1247: &Apache::loncommon::start_page('Highlight Central',
1248: $inner_js_highlight_central,
1249: {'js_ready' => 1,
1250: 'only_body' => 1,
1251: 'bgcolor' =>'#FFFFFF',});
1252: my $end_page_highlight_central =
1253: &Apache::loncommon::end_page({'js_ready' => 1});
1254:
1255: my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1256: $docopen=~s/^document\.//;
1257: $request->print(<<SUBJAVASCRIPT);
1258: <script type="text/javascript" language="javascript">
1259:
1260: //===================== Show list of keywords ====================
1261: function keywords(formname) {
1262: var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1263: if (nret==null) return;
1264: formname.keywords.value = nret;
1265:
1266: if (formname.keywords.value != "") {
1267: formname.refresh.value = "on";
1268: formname.submit();
1269: }
1270: return;
1271: }
1272:
1273: //===================== Script to view submitted by ==================
1274: function viewSubmitter(submitter) {
1275: document.SCORE.refresh.value = "on";
1276: document.SCORE.NCT.value = "1";
1277: document.SCORE.unamedom0.value = submitter;
1278: document.SCORE.submit();
1279: return;
1280: }
1281:
1282: //===================== Script to add keyword(s) ==================
1283: function getSel() {
1284: if (document.getSelection) txt = document.getSelection();
1285: else if (document.selection) txt = document.selection.createRange().text;
1286: else return;
1287: var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
1288: if (cleantxt=="") {
1289: alert("Please select a word or group of words from document and then click this link.");
1290: return;
1291: }
1292: var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
1293: if (nret==null) return;
1294: document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1295: if (document.SCORE.keywords.value != "") {
1296: document.SCORE.refresh.value = "on";
1297: document.SCORE.submit();
1298: }
1299: return;
1300: }
1301:
1302: //====================== Script for composing message ==============
1303: // preload images
1304: img1 = new Image();
1305: img1.src = "$iconpath/mailbkgrd.gif";
1306: img2 = new Image();
1307: img2.src = "$iconpath/mailto.gif";
1308:
1309: function msgCenter(msgform,usrctr,fullname) {
1310: var Nmsg = msgform.savemsgN.value;
1311: savedMsgHeader(Nmsg,usrctr,fullname);
1312: var subject = msgform.msgsub.value;
1313: var msgchk = document.SCORE["includemsg"+usrctr].value;
1314: re = /msgsub/;
1315: var shwsel = "";
1316: if (re.test(msgchk)) { shwsel = "checked" }
1317: subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
1318: displaySubject(checkEntities(subject),shwsel);
1319: for (var i=1; i<=Nmsg; i++) {
1320: var testmsg = "savemsg"+i+",";
1321: re = new RegExp(testmsg,"g");
1322: shwsel = "";
1323: if (re.test(msgchk)) { shwsel = "checked" }
1324: var message = document.SCORE["savemsg"+i].value;
1325: message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1326: displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
1327: //any < is already converted to <, etc. However, only once!!
1328: }
1329: newmsg = document.SCORE["newmsg"+usrctr].value;
1330: shwsel = "";
1331: re = /newmsg/;
1332: if (re.test(msgchk)) { shwsel = "checked" }
1333: newMsg(newmsg,shwsel);
1334: msgTail();
1335: return;
1336: }
1337:
1338: function checkEntities(strx) {
1339: if (strx.length == 0) return strx;
1340: var orgStr = ["&", "<", ">", '"'];
1341: var newStr = ["&", "<", ">", """];
1342: var counter = 0;
1343: while (counter < 4) {
1344: strx = strReplace(strx,orgStr[counter],newStr[counter]);
1345: counter++;
1346: }
1347: return strx;
1348: }
1349:
1350: function strReplace(strx, orgStr, newStr) {
1351: return strx.split(orgStr).join(newStr);
1352: }
1353:
1354: function savedMsgHeader(Nmsg,usrctr,fullname) {
1355: var height = 70*Nmsg+250;
1356: var scrollbar = "no";
1357: if (height > 600) {
1358: height = 600;
1359: scrollbar = "yes";
1360: }
1361: var xpos = (screen.width-600)/2;
1362: xpos = (xpos < 0) ? '0' : xpos;
1363: var ypos = (screen.height-height)/2-30;
1364: ypos = (ypos < 0) ? '0' : ypos;
1365:
1366: pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1367: pWin.focus();
1368: pDoc = pWin.document;
1369: pDoc.$docopen;
1370: pDoc.write('$start_page_msg_central');
1371:
1372: pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
1373: pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1374: pDoc.write("<h3><span class=\\"LC_info\\"> Compose Message for \"+fullname+\"</span></h3><br /><br />");
1375:
1376: pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
1377: pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
1378: pDoc.write("<td><b>Type</b></td><td><b>Include</b></td><td><b>Message</td></tr>");
1379: }
1380: function displaySubject(msg,shwsel) {
1381: pDoc = pWin.document;
1382: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1383: pDoc.write("<td>Subject</td>");
1384: pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
1385: pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"></td></tr>");
1386: }
1387:
1388: function displaySavedMsg(ctr,msg,shwsel) {
1389: pDoc = pWin.document;
1390: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1391: pDoc.write("<td align=\\"center\\">"+ctr+"</td>");
1392: pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"></td>");
1393: pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"</textarea></td></tr>");
1394: }
1395:
1396: function newMsg(newmsg,shwsel) {
1397: pDoc = pWin.document;
1398: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1399: pDoc.write("<td align=\\"center\\">New</td>");
1400: pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
1401: pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"</textarea></td></tr>");
1402: }
1403:
1404: function msgTail() {
1405: pDoc = pWin.document;
1406: pDoc.write("</table>");
1407: pDoc.write("</td></tr></table> ");
1408: pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\"> ");
1409: pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1410: pDoc.write("</form>");
1411: pDoc.write('$end_page_msg_central');
1412: pDoc.close();
1413: }
1414:
1415: //====================== Script for keyword highlight options ==============
1416: function kwhighlight() {
1417: var kwclr = document.SCORE.kwclr.value;
1418: var kwsize = document.SCORE.kwsize.value;
1419: var kwstyle = document.SCORE.kwstyle.value;
1420: var redsel = "";
1421: var grnsel = "";
1422: var blusel = "";
1423: if (kwclr=="red") {var redsel="checked"};
1424: if (kwclr=="green") {var grnsel="checked"};
1425: if (kwclr=="blue") {var blusel="checked"};
1426: var sznsel = "";
1427: var sz1sel = "";
1428: var sz2sel = "";
1429: if (kwsize=="0") {var sznsel="checked"};
1430: if (kwsize=="+1") {var sz1sel="checked"};
1431: if (kwsize=="+2") {var sz2sel="checked"};
1432: var synsel = "";
1433: var syisel = "";
1434: var sybsel = "";
1435: if (kwstyle=="") {var synsel="checked"};
1436: if (kwstyle=="<i>") {var syisel="checked"};
1437: if (kwstyle=="<b>") {var sybsel="checked"};
1438: highlightCentral();
1439: highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
1440: highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
1441: highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
1442: highlightend();
1443: return;
1444: }
1445:
1446: function highlightCentral() {
1447: // if (window.hwdWin) window.hwdWin.close();
1448: var xpos = (screen.width-400)/2;
1449: xpos = (xpos < 0) ? '0' : xpos;
1450: var ypos = (screen.height-330)/2-30;
1451: ypos = (ypos < 0) ? '0' : ypos;
1452:
1453: hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1454: hwdWin.focus();
1455: var hDoc = hwdWin.document;
1456: hDoc.$docopen;
1457: hDoc.write('$start_page_highlight_central');
1458: hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1459: hDoc.write("<h3><span class=\\"LC_info\\"> Keyword Highlight Options</span></h3><br /><br />");
1460:
1461: hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
1462: hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
1463: hDoc.write("<td><b>Text Color</b></td><td><b>Font Size</b></td><td><b>Font Style</td></tr>");
1464: }
1465:
1466: function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) {
1467: var hDoc = hwdWin.document;
1468: hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1469: hDoc.write("<td align=\\"left\\">");
1470: hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+"> "+clrtxt+"</td>");
1471: hDoc.write("<td align=\\"left\\">");
1472: hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+"> "+sztxt+"</td>");
1473: hDoc.write("<td align=\\"left\\">");
1474: hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+"> "+sytxt+"</td>");
1475: hDoc.write("</tr>");
1476: }
1477:
1478: function highlightend() {
1479: var hDoc = hwdWin.document;
1480: hDoc.write("</table>");
1481: hDoc.write("</td></tr></table> ");
1482: hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\"> ");
1483: hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1484: hDoc.write("</form>");
1485: hDoc.write('$end_page_highlight_central');
1486: hDoc.close();
1487: }
1488:
1489: </script>
1490: SUBJAVASCRIPT
1491: }
1492:
1493: sub get_increment {
1494: my $increment = $env{'form.increment'};
1495: if ($increment != 1 && $increment != .5 && $increment != .25 &&
1496: $increment != .1) {
1497: $increment = 1;
1498: }
1499: return $increment;
1500: }
1501:
1502: #--- displays the grading box, used in essay type problem and grading by page/sequence
1503: sub gradeBox {
1504: my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1505: my $checkIcon = '<img alt="'.&mt('Check Mark').
1506: '" src="'.$request->dir_config('lonIconsURL').
1507: '/check.gif" height="16" border="0" />';
1508: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1509: my $wgtmsg = ($wgt > 0 ? '(problem weight)' :
1510: '<span class="LC_info">problem weight assigned by computer</span>');
1511: $wgt = ($wgt > 0 ? $wgt : '1');
1512: my $score = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1513: '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1514: my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1515: my $display_part=&get_display_part($partid,$symb);
1516: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
1517: [$partid]);
1518: my $aggtries = $$record{'resource.'.$partid.'.tries'};
1519: if ($last_resets{$partid}) {
1520: $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
1521: }
1522: $result.='<table border="0"><tr><td>'.
1523: '<b>Part: </b>'.$display_part.' <b>Points: </b></td><td>'."\n";
1524: my $ctr = 0;
1525: my $thisweight = 0;
1526: my $increment = &get_increment();
1527: $result.='<table border="0"><tr>'."\n"; # display radio buttons in a nice table 10 across
1528: while ($thisweight<=$wgt) {
1529: $result.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1530: 'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1531: $thisweight.')" value="'.$thisweight.'" '.
1532: ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1533: $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1534: $thisweight += $increment;
1535: $ctr++;
1536: }
1537: $result.='</tr></table>';
1538: $result.='</td><td> <b>or</b> </td>'."\n";
1539: $result.='<td><input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1540: ($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1541: 'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1542: $wgt.')" /></td>'."\n";
1543: $result.='<td>/'.$wgt.' '.$wgtmsg.
1544: ($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? ' '.$checkIcon : '').
1545: ' </td><td>'."\n";
1546: $result.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
1547: 'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1548: if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1549: $result.='<option></option>'.
1550: '<option selected="selected">excused</option>';
1551: } else {
1552: $result.='<option selected="selected"></option>'.
1553: '<option>excused</option>';
1554: }
1555: $result.='<option>reset status</option></select>'."\n";
1556: $result.=" \n";
1557: $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
1558: '<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
1559: '<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1560: $$record{'resource.'.$partid.'.solved'}.'" />'."\n".
1561: '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
1562: $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
1563: '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
1564: $aggtries.'" />'."\n";
1565: $result.='</td></tr></table>'."\n";
1566: $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
1567: return $result;
1568: }
1569:
1570: sub handback_box {
1571: my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
1572: my ($partlist,$handgrade,$responseType) = &response_type($symb);
1573: my (@respids);
1574: my @part_response_id = &flatten_responseType($responseType);
1575: foreach my $part_response_id (@part_response_id) {
1576: my ($part,$resp) = @{ $part_response_id };
1577: if ($part eq $partid) {
1578: push(@respids,$resp);
1579: }
1580: }
1581: my $result;
1582: foreach my $respid (@respids) {
1583: my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
1584: my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
1585: next if (!@$files);
1586: my $file_counter = 1;
1587: foreach my $file (@$files) {
1588: if ($file =~ /\/portfolio\//) {
1589: my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1590: my ($name,$version,$ext) = &file_name_version_ext($file_disp);
1591: $file_disp = "$name.$ext";
1592: $file = $file_path.$file_disp;
1593: $result.=&mt('Return commented version of [_1] to student.',
1594: '<span class="LC_filename">'.$file_disp.'</span>');
1595: $result.='<input type="file" name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1596: $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1597: $result.='(File will be uploaded when you click on Save & Next below.)<br />';
1598: $file_counter++;
1599: }
1600: }
1601: }
1602: return $result;
1603: }
1604:
1605: sub show_problem {
1606: my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1607: my $rendered;
1608: my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1609: &Apache::lonxml::remember_problem_counter();
1610: if ($mode eq 'both' or $mode eq 'text') {
1611: $rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1612: $env{'request.course.id'},
1613: undef,\%form);
1614: }
1615: if ($removeform) {
1616: $rendered=~s|<form(.*?)>||g;
1617: $rendered=~s|</form>||g;
1618: $rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1619: }
1620: my $companswer;
1621: if ($mode eq 'both' or $mode eq 'answer') {
1622: &Apache::lonxml::restore_problem_counter();
1623: $companswer=
1624: &Apache::loncommon::get_student_answers($symb,$uname,$udom,
1625: $env{'request.course.id'},
1626: %form);
1627: }
1628: if ($removeform) {
1629: $companswer=~s|<form(.*?)>||g;
1630: $companswer=~s|</form>||g;
1631: $companswer=~s|name="submit"|name="would_have_been_submit"|g;
1632: }
1633: my $result.='<table border="0" width="100%"><tr><td bgcolor="#777777">';
1634: $result.='<table border="0" width="100%">';
1635: if ($viewon) {
1636: $result.='<tr><td bgcolor="#e6ffff"><b> ';
1637: if ($mode eq 'both' or $mode eq 'text') {
1638: $result.='View of the problem - ';
1639: } else {
1640: $result.='Correct answer: ';
1641: }
1642: $result.=$env{'form.fullname'}.'</b></td></tr>';
1643: }
1644: if ($mode eq 'both') {
1645: $result.='<tr><td bgcolor="#ffffff">'.$rendered.'<br />';
1646: $result.='<b>Correct answer:</b><br />'.$companswer;
1647: } elsif ($mode eq 'text') {
1648: $result.='<tr><td bgcolor="#ffffff">'.$rendered;
1649: } elsif ($mode eq 'answer') {
1650: $result.='<tr><td bgcolor="#ffffff">'.$companswer;
1651: }
1652: $result.='</td></tr></table>';
1653: $result.='</td></tr></table><br />';
1654: return $result;
1655: }
1656:
1657: sub files_exist {
1658: my ($r, $symb) = @_;
1659: my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1660:
1661: foreach my $student (@students) {
1662: my ($uname,$udom,$fullname) = split(/:/,$student);
1663: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
1664: $udom,$uname);
1665: my ($string,$timestamp)= &get_last_submission(\%record);
1666: foreach my $submission (@$string) {
1667: my ($partid,$respid) =
1668: ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1669: my $files=&get_submitted_files($udom,$uname,$partid,$respid,
1670: \%record);
1671: return 1 if (@$files);
1672: }
1673: }
1674: return 0;
1675: }
1676:
1677: sub download_all_link {
1678: my ($r,$symb) = @_;
1679: my $all_students =
1680: join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
1681:
1682: my $parts =
1683: join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
1684:
1685: my $identifier = &Apache::loncommon::get_cgi_id();
1686: &Apache::lonnet::appenv('cgi.'.$identifier.'.students' => $all_students,
1687: 'cgi.'.$identifier.'.symb' => $symb,
1688: 'cgi.'.$identifier.'.parts' => $parts,);
1689: $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
1690: &mt('Download All Submitted Documents').'</a>');
1691: return
1692: }
1693:
1694: sub build_section_inputs {
1695: my $section_inputs;
1696: if ($env{'form.section'} eq '') {
1697: $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
1698: } else {
1699: my @sections = &Apache::loncommon::get_env_multiple('form.section');
1700: foreach my $section (@sections) {
1701: $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
1702: }
1703: }
1704: return $section_inputs;
1705: }
1706:
1707: # --------------------------- show submissions of a student, option to grade
1708: sub submission {
1709: my ($request,$counter,$total) = @_;
1710:
1711: my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
1712: $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
1713: my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
1714: $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1715:
1716: my $symb = &get_symb($request);
1717: if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1718:
1719: if (!&canview($usec)) {
1720: $request->print('<span class="LC_warning">Unable to view requested student.('.
1721: $uname.':'.$udom.' in section '.$usec.' in course id '.
1722: $env{'request.course.id'}.')</span>');
1723: $request->print(&show_grading_menu_form($symb));
1724: return;
1725: }
1726:
1727: if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
1728: if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
1729: if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
1730: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1731: my $checkIcon = '<img alt="'.&mt('Check Mark').
1732: '" src="'.$request->dir_config('lonIconsURL').
1733: '/check.gif" height="16" border="0" />';
1734:
1735: my %old_essays;
1736: # header info
1737: if ($counter == 0) {
1738: &sub_page_js($request);
1739: &sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
1740: $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ?
1741: &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1742: if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1743: &download_all_link($request, $symb);
1744: }
1745: $request->print('<h3> <span class="LC_info">Submission Record</span></h3>'."\n".
1746: '<h4> <b>Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n");
1747:
1748: if ($env{'form.handgrade'} eq 'no') {
1749: my $checkMark='<br /><br /> <b>Note:</b> Part(s) graded correct by the computer is marked with a '.
1750: $checkIcon.' symbol.'."\n";
1751: $request->print($checkMark);
1752: }
1753:
1754: # option to display problem, only once else it cause problems
1755: # with the form later since the problem has a form.
1756: if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1757: my $mode;
1758: if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1759: $mode='both';
1760: } elsif ($env{'form.vProb'} eq 'yes') {
1761: $mode='text';
1762: } elsif ($env{'form.vAns'} eq 'yes') {
1763: $mode='answer';
1764: }
1765: &Apache::lonxml::clear_problem_counter();
1766: $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1767: }
1768:
1769: # kwclr is the only variable that is guaranteed to be non blank
1770: # if this subroutine has been called once.
1771: my %keyhash = ();
1772: if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1773: %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1774: $env{'course.'.$env{'request.course.id'}.'.domain'},
1775: $env{'course.'.$env{'request.course.id'}.'.num'});
1776:
1777: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1778: $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
1779: $env{'form.kwclr'} = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
1780: $env{'form.kwsize'} = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
1781: $env{'form.kwstyle'} = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
1782: $env{'form.msgsub'} = $keyhash{$symb.'_subject'} ne '' ?
1783: $keyhash{$symb.'_subject'} : $env{'form.probTitle'};
1784: $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1785: }
1786: my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1787: $request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1788: '<input type="hidden" name="command" value="handgrade" />'."\n".
1789: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1790: '<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n".
1791: '<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1792: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
1793: '<input type="hidden" name="refresh" value="off" />'."\n".
1794: '<input type="hidden" name="studentNo" value="" />'."\n".
1795: '<input type="hidden" name="gradeOpt" value="" />'."\n".
1796: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1797: '<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
1798: '<input type="hidden" name="vProb" value="'.$env{'form.vProb'}.'" />'."\n".
1799: '<input type="hidden" name="vAns" value="'.$env{'form.vAns'}.'" />'."\n".
1800: '<input type="hidden" name="lastSub" value="'.$env{'form.lastSub'}.'" />'."\n".
1801: &build_section_inputs().
1802: '<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1803: '<input type="hidden" name="handgrade" value="'.$env{'form.handgrade'}.'" />'."\n".
1804: '<input type="hidden" name="NCT"'.
1805: ' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1806: if ($env{'form.handgrade'} eq 'yes') {
1807: $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
1808: '<input type="hidden" name="kwclr" value="'.$env{'form.kwclr'}.'" />'."\n".
1809: '<input type="hidden" name="kwsize" value="'.$env{'form.kwsize'}.'" />'."\n".
1810: '<input type="hidden" name="kwstyle" value="'.$env{'form.kwstyle'}.'" />'."\n".
1811: '<input type="hidden" name="msgsub" value="'.$env{'form.msgsub'}.'" />'."\n".
1812: '<input type="hidden" name="shownSub" value="0" />'."\n".
1813: '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1814: foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
1815: $request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
1816: }
1817: }
1818:
1819: my ($cts,$prnmsg) = (1,'');
1820: while ($cts <= $env{'form.savemsgN'}) {
1821: $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1822: (!exists($keyhash{$symb.'_savemsg'.$cts}) ?
1823: &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1824: &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1825: '" />'."\n".
1826: '<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1827: $cts++;
1828: }
1829: $request->print($prnmsg);
1830:
1831: if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1832: #
1833: # Print out the keyword options line
1834: #
1835: $request->print(<<KEYWORDS);
1836: <b>Keyword Options:</b>
1837: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>
1838: <a href="#" onMouseDown="javascript:getSel(); return false"
1839: CLASS="page">Paste Selection to List</a>
1840: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1841: KEYWORDS
1842: #
1843: # Load the other essays for similarity check
1844: #
1845: my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1846: my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1847: $apath=&escape($apath);
1848: $apath=~s/\W/\_/gs;
1849: %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1850: }
1851: }
1852:
1853: if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1854: $request->print('<br /><br /><br />') if ($counter > 0);
1855: my $mode;
1856: if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1857: $mode='both';
1858: } elsif ($env{'form.vProb'} eq 'all' ) {
1859: $mode='text';
1860: } elsif ($env{'form.vAns'} eq 'all') {
1861: $mode='answer';
1862: }
1863: &Apache::lonxml::clear_problem_counter();
1864: $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode));
1865: }
1866:
1867: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1868: my ($partlist,$handgrade,$responseType) = &response_type($symb);
1869:
1870: # Display student info
1871: $request->print(($counter == 0 ? '' : '<br />'));
1872: my $result='<table border="0" width="100%"><tr><td bgcolor="#777777">'."\n".
1873: '<table border="0" width="100%"><tr bgcolor="#edffff"><td>'."\n";
1874:
1875: $result.='<b>Fullname: </b>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'<br />'."\n";
1876: $result.='<input type="hidden" name="name'.$counter.
1877: '" value="'.$env{'form.fullname'}.'" />'."\n";
1878:
1879: # If any part of the problem is an essay-response (handgraded), then check for collaborators
1880: my @col_fullnames;
1881: my ($classlist,$fullname);
1882: if ($env{'form.handgrade'} eq 'yes') {
1883: ($classlist,undef,$fullname) = &getclasslist('all','0');
1884: for (keys (%$handgrade)) {
1885: my $ncol = &Apache::lonnet::EXT('resource.'.$_.
1886: '.maxcollaborators',
1887: $symb,$udom,$uname);
1888: next if ($ncol <= 0);
1889: s/\_/\./g;
1890: next if ($record{'resource.'.$_.'.collaborators'} eq '');
1891: my @goodcollaborators = ();
1892: my @badcollaborators = ();
1893: foreach (split(/,?\s+/,$record{'resource.'.$_.'.collaborators'})) {
1894: $_ =~ s/[\$\^\(\)]//g;
1895: next if ($_ eq '');
1896: my ($co_name,$co_dom) = split /\@|:/,$_;
1897: $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
1898: next if ($co_name eq $uname && $co_dom eq $udom);
1899: # Doing this grep allows 'fuzzy' specification
1900: my @Matches = grep /^$co_name:$co_dom$/i,keys %$classlist;
1901: if (! scalar(@Matches)) {
1902: push @badcollaborators,$_;
1903: } else {
1904: push @goodcollaborators, @Matches;
1905: }
1906: }
1907: if (scalar(@goodcollaborators) != 0) {
1908: $result.='<b>Collaborators: </b>';
1909: foreach (@goodcollaborators) {
1910: my ($lastname,$givenn) = split(/,/,$$fullname{$_});
1911: push @col_fullnames, $givenn.' '.$lastname;
1912: $result.=$$fullname{$_}.' ';
1913: }
1914: $result.='<br />'."\n";
1915: my ($part)=split(/\./,$_);
1916: $result.='<input type="hidden" name="collaborator'.$counter.
1917: '" value="'.$part.':'.(join ':',@goodcollaborators).'" />'.
1918: "\n";
1919: }
1920: if (scalar(@badcollaborators) > 0) {
1921: $result.='<table border="0"><tr bgcolor="#ffbbbb"><td>';
1922: $result.='This student has submitted ';
1923: $result.=(scalar(@badcollaborators) == 1) ? 'an invalid collaborator' : 'invalid collaborators';
1924: $result .= ': '.join(', ',@badcollaborators);
1925: $result .= '</td></tr></table>';
1926: }
1927: if (scalar(@badcollaborators > $ncol)) {
1928: $result .= '<table border="0"><tr bgcolor="#ffbbbb"><td>';
1929: $result .= 'This student has submitted too many '.
1930: 'collaborators. Maximum is '.$ncol.'.';
1931: $result .= '</td></tr></table>';
1932: }
1933: }
1934: }
1935: $request->print($result."\n");
1936:
1937: # print student answer/submission
1938: # Options are (1) Handgaded submission only
1939: # (2) Last submission, includes submission that is not handgraded
1940: # (for multi-response type part)
1941: # (3) Last submission plus the parts info
1942: # (4) The whole record for this student
1943: if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1944: my ($string,$timestamp)= &get_last_submission(\%record);
1945: my $lastsubonly=''.
1946: ($$timestamp eq '' ? '' : '<b>Date Submitted:</b> '.
1947: $$timestamp)."</td></tr>\n";
1948: if ($$timestamp eq '') {
1949: $lastsubonly.='<tr><td bgcolor="#ffffe6">'.$$string[0];
1950: } else {
1951: my %seenparts;
1952: my @part_response_id = &flatten_responseType($responseType);
1953: foreach my $part (@part_response_id) {
1954: next if ($env{'form.lastSub'} eq 'hdgrade'
1955: && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
1956:
1957: my ($partid,$respid) = @{ $part };
1958: my $display_part=&get_display_part($partid,$symb);
1959: if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1960: if (exists($seenparts{$partid})) { next; }
1961: $seenparts{$partid}=1;
1962: my $submitby='<b>Part:</b> '.$display_part.
1963: ' <b>Collaborative submission by:</b> '.
1964: '<a href="javascript:viewSubmitter(\''.
1965: $env{"form.$uname:$udom:$partid:submitted_by"}.
1966: '\');" target="_self">'.
1967: $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1968: $request->print($submitby);
1969: next;
1970: }
1971: my $responsetype = $responseType->{$partid}->{$respid};
1972: if (!exists($record{"resource.$partid.$respid.submission"})) {
1973: $lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
1974: $display_part.' <span class="LC_internal_info">( ID '.$respid.
1975: ' )</span> '.
1976: '<span class="LC_warning">Nothing submitted - no attempts</span><br /><br />';
1977: next;
1978: }
1979: foreach (@$string) {
1980: my ($partid,$respid) = /^resource\.([^\.]*)\.([^\.]*)\.submission/;
1981: if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1982: my ($ressub,$subval) = split(/:/,$_,2);
1983: # Similarity check
1984: my $similar='';
1985: if($env{'form.checkPlag'}){
1986: my ($oname,$odom,$ocrsid,$oessay,$osim)=
1987: &most_similar($uname,$udom,$subval,\%old_essays);
1988: if ($osim) {
1989: $osim=int($osim*100.0);
1990: my %old_course_desc =
1991: &Apache::lonnet::coursedescription($ocrsid,
1992: {'one_time' => 1});
1993:
1994: $similar="<hr /><h3><span class=\"LC_warning\">".
1995: &mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
1996: $osim,
1997: &Apache::loncommon::plainname($oname,$odom),
1998: $oname,$odom,
1999: $old_course_desc{'description'},
2000: $old_course_desc{'num'},
2001: $old_course_desc{'domain'}).
2002: '</span></h3><blockquote><i>'.
2003: &keywords_highlight($oessay).
2004: '</i></blockquote><hr />';
2005: }
2006: }
2007: my $order=&get_order($partid,$respid,$symb,$uname,$udom);
2008: if ($env{'form.lastSub'} eq 'lastonly' ||
2009: ($env{'form.lastSub'} eq 'hdgrade' &&
2010: $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
2011: my $display_part=&get_display_part($partid,$symb);
2012: $lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
2013: $display_part.' <span class="LC_internal_info">( ID '.$respid.
2014: ' )</span> ';
2015: my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
2016: if (@$files) {
2017: $lastsubonly.='<br /><span class="LC_warning">Like all files provided by users, this file may contain virusses</span><br />';
2018: my $file_counter = 0;
2019: foreach my $file (@$files) {
2020: $file_counter ++;
2021: &Apache::lonnet::allowuploaded('/adm/grades',$file);
2022: $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
2023: }
2024: $lastsubonly.='<br />';
2025: }
2026: $lastsubonly.='<b>Submitted Answer: </b>'.
2027: &cleanRecord($subval,$responsetype,$symb,$partid,
2028: $respid,\%record,$order);
2029: if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
2030: }
2031: }
2032: }
2033: }
2034: $lastsubonly.='</td></tr><tr bgcolor="#ffffff"><td>'."\n";
2035: $request->print($lastsubonly);
2036: } elsif ($env{'form.lastSub'} eq 'datesub') {
2037: my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
2038: $request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
2039: } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
2040: $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
2041: $env{'request.course.id'},
2042: $last,'.submission',
2043: 'Apache::grades::keywords_highlight'));
2044: }
2045:
2046: $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
2047: .$udom.'" />'."\n");
2048:
2049: # return if view submission with no grading option
2050: if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
2051: my $toGrade.='<input type="button" value="Grade Student" '.
2052: 'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
2053: .$counter.'\');" target="_self" /> '."\n" if (&canmodify($usec));
2054: $toGrade.='</td></tr></table></td></tr></table>'."\n";
2055: if (($env{'form.command'} eq 'submission') ||
2056: ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
2057: $toGrade.='</form>'.&show_grading_menu_form($symb);
2058: }
2059: $request->print($toGrade);
2060: return;
2061: } else {
2062: $request->print('</td></tr></table></td></tr></table>'."\n");
2063: }
2064:
2065: # essay grading message center
2066: if ($env{'form.handgrade'} eq 'yes') {
2067: my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
2068: my $msgfor = $givenn.' '.$lastname;
2069: if (scalar(@col_fullnames) > 0) {
2070: my $lastone = pop @col_fullnames;
2071: $msgfor .= ', '.(join ', ',@col_fullnames).' and '.$lastone.'.';
2072: }
2073: $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
2074: $result='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
2075: '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
2076: $result.=' <a href="javascript:msgCenter(document.SCORE,'.$counter.
2077: ',\''.$msgfor.'\');" target="_self">'.
2078: &mt('Compose message to student').(scalar(@col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
2079: &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
2080: '<img src="'.$request->dir_config('lonIconsURL').
2081: '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
2082: '<br /> ('.
2083: &mt('Message will be sent when you click on Save & Next below.').")\n";
2084: $request->print($result);
2085: }
2086: if ($perm{'vgr'}) {
2087: $request->print('<br />'.
2088: &Apache::loncommon::track_student_link(&mt('View recent activity'),
2089: $uname,$udom,'check'));
2090: }
2091: if ($perm{'opa'}) {
2092: $request->print('<br />'.
2093: &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
2094: $uname,$udom,$symb,'check'));
2095: }
2096:
2097: my %seen = ();
2098: my @partlist;
2099: my @gradePartRespid;
2100: my @part_response_id = &flatten_responseType($responseType);
2101: foreach my $part_response_id (@part_response_id) {
2102: my ($partid,$respid) = @{ $part_response_id };
2103: my $part_resp = join('_',@{ $part_response_id });
2104: next if ($seen{$partid} > 0);
2105: $seen{$partid}++;
2106: next if ($$handgrade{$part_resp} ne 'yes'
2107: && $env{'form.lastSub'} eq 'hdgrade');
2108: push @partlist,$partid;
2109: push @gradePartRespid,$partid.'.'.$respid;
2110: $request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
2111: }
2112: $result='<input type="hidden" name="partlist'.$counter.
2113: '" value="'.(join ":",@partlist).'" />'."\n";
2114: $result.='<input type="hidden" name="gradePartRespid'.
2115: '" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
2116: my $ctr = 0;
2117: while ($ctr < scalar(@partlist)) {
2118: $result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
2119: $partlist[$ctr].'" />'."\n";
2120: $ctr++;
2121: }
2122: $request->print($result.'</td></tr></table></td></tr></table>'."\n");
2123:
2124: # print end of form
2125: if ($counter == $total) {
2126: my $endform='<table border="0"><tr><td>'."\n";
2127: $endform.='<input type="button" value="Save & Next" '.
2128: 'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
2129: $total.','.scalar(@partlist).');" target="_self" /> '."\n";
2130: my $ntstu ='<select name="NTSTU">'.
2131: '<option>1</option><option>2</option>'.
2132: '<option>3</option><option>5</option>'.
2133: '<option>7</option><option>10</option></select>'."\n";
2134: my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
2135: $ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
2136: $endform.=$ntstu.'student(s) ';
2137: $endform.='<input type="button" value="Previous" '.
2138: 'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> '."\n".
2139: '<input type="button" value="Next" '.
2140: 'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> ';
2141: $endform.='(Next and Previous (student) do not save the scores.)'."\n" ;
2142: $endform.="<input type='hidden' value='".&get_increment().
2143: "' name='increment' />";
2144: $endform.='</td><tr></table></form>';
2145: $endform.=&show_grading_menu_form($symb);
2146: $request->print($endform);
2147: }
2148: return '';
2149: }
2150:
2151: #--- Retrieve the last submission for all the parts
2152: sub get_last_submission {
2153: my ($returnhash)=@_;
2154: my (@string,$timestamp);
2155: if ($$returnhash{'version'}) {
2156: my %lasthash=();
2157: my ($version);
2158: for ($version=1;$version<=$$returnhash{'version'};$version++) {
2159: foreach my $key (sort(split(/\:/,
2160: $$returnhash{$version.':keys'}))) {
2161: $lasthash{$key}=$$returnhash{$version.':'.$key};
2162: $timestamp =
2163: scalar(localtime($$returnhash{$version.':timestamp'}));
2164: }
2165: }
2166: foreach my $key (keys(%lasthash)) {
2167: next if ($key !~ /\.submission$/);
2168:
2169: my ($partid,$foo) = split(/submission$/,$key);
2170: my $draft = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
2171: '<span class="LC_warning">Draft Copy</span> ' : '';
2172: push(@string, join(':', $key, $draft.$lasthash{$key}));
2173: }
2174: }
2175: if (!@string) {
2176: $string[0] =
2177: '<span class="LC_warning">Nothing submitted - no attempts.</span>';
2178: }
2179: return (\@string,\$timestamp);
2180: }
2181:
2182: #--- High light keywords, with style choosen by user.
2183: sub keywords_highlight {
2184: my $string = shift;
2185: my $size = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
2186: my $styleon = $env{'form.kwstyle'} eq '' ? '' : $env{'form.kwstyle'};
2187: (my $styleoff = $styleon) =~ s/\</\<\//;
2188: my @keylist = split(/[,\s+]/,$env{'form.keywords'});
2189: foreach my $keyword (@keylist) {
2190: $string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
2191: }
2192: return $string;
2193: }
2194:
2195: #--- Called from submission routine
2196: sub processHandGrade {
2197: my ($request) = shift;
2198: my $symb = &get_symb($request);
2199: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
2200: my $button = $env{'form.gradeOpt'};
2201: my $ngrade = $env{'form.NCT'};
2202: my $ntstu = $env{'form.NTSTU'};
2203: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2204: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2205:
2206: if ($button eq 'Save & Next') {
2207: my $ctr = 0;
2208: while ($ctr < $ngrade) {
2209: my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
2210: my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
2211: if ($errorflag eq 'no_score') {
2212: $ctr++;
2213: next;
2214: }
2215: if ($errorflag eq 'not_allowed') {
2216: $request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
2217: $ctr++;
2218: next;
2219: }
2220: my $includemsg = $env{'form.includemsg'.$ctr};
2221: my ($subject,$message,$msgstatus) = ('','','');
2222: my $restitle = &Apache::lonnet::gettitle($symb);
2223: my ($feedurl,$showsymb) =
2224: &get_feedurl_and_symb($symb,$uname,$udom);
2225: my $messagetail;
2226: if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
2227: $subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
2228: unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
2229: $subject.=' ['.$restitle.']';
2230: my (@msgnum) = split(/,/,$includemsg);
2231: foreach (@msgnum) {
2232: $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
2233: }
2234: $message =&Apache::lonfeedback::clear_out_html($message);
2235: if ($env{'form.withgrades'.$ctr}) {
2236: $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
2237: $messagetail = " for <a href=\"".
2238: $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
2239: }
2240: $msgstatus =
2241: &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
2242: $message.$messagetail,
2243: undef,$feedurl,undef,
2244: undef,undef,$showsymb,
2245: $restitle);
2246: $request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
2247: $msgstatus);
2248: }
2249: if ($env{'form.collaborator'.$ctr}) {
2250: my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
2251: foreach my $collabstr (@collabstrs) {
2252: my ($part,@collaborators) = split(/:/,$collabstr);
2253: foreach my $collaborator (@collaborators) {
2254: my ($errorflag,$pts,$wgt) =
2255: &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
2256: $env{'form.unamedom'.$ctr},$part);
2257: if ($errorflag eq 'not_allowed') {
2258: $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
2259: next;
2260: } elsif ($message ne '') {
2261: my ($baseurl,$showsymb) =
2262: &get_feedurl_and_symb($symb,$collaborator,
2263: $udom);
2264: if ($env{'form.withgrades'.$ctr}) {
2265: $messagetail = " for <a href=\"".
2266: $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
2267: }
2268: $msgstatus =
2269: &Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
2270: }
2271: }
2272: }
2273: }
2274: $ctr++;
2275: }
2276: }
2277:
2278: if ($env{'form.handgrade'} eq 'yes') {
2279: # Keywords sorted in alphabatical order
2280: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
2281: my %keyhash = ();
2282: $env{'form.keywords'} =~ s/,\s{0,}|\s+/ /g;
2283: $env{'form.keywords'} =~ s/^\s+|\s+$//;
2284: my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
2285: $env{'form.keywords'} = join(' ',@keywords);
2286: $keyhash{$symb.'_keywords'} = $env{'form.keywords'};
2287: $keyhash{$symb.'_subject'} = $env{'form.msgsub'};
2288: $keyhash{$loginuser.'_kwclr'} = $env{'form.kwclr'};
2289: $keyhash{$loginuser.'_kwsize'} = $env{'form.kwsize'};
2290: $keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
2291:
2292: # message center - Order of message gets changed. Blank line is eliminated.
2293: # New messages are saved in env for the next student.
2294: # All messages are saved in nohist_handgrade.db
2295: my ($ctr,$idx) = (1,1);
2296: while ($ctr <= $env{'form.savemsgN'}) {
2297: if ($env{'form.savemsg'.$ctr} ne '') {
2298: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
2299: $idx++;
2300: }
2301: $ctr++;
2302: }
2303: $ctr = 0;
2304: while ($ctr < $ngrade) {
2305: if ($env{'form.newmsg'.$ctr} ne '') {
2306: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2307: $env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2308: $idx++;
2309: }
2310: $ctr++;
2311: }
2312: $env{'form.savemsgN'} = --$idx;
2313: $keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
2314: my $putresult = &Apache::lonnet::put
2315: ('nohist_handgrade',\%keyhash,$cdom,$cnum);
2316: }
2317: # Called by Save & Refresh from Highlight Attribute Window
2318: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
2319: if ($env{'form.refresh'} eq 'on') {
2320: my ($ctr,$total) = (0,0);
2321: while ($ctr < $ngrade) {
2322: $total++ if $env{'form.unamedom'.$ctr} ne '';
2323: $ctr++;
2324: }
2325: $env{'form.NTSTU'}=$ngrade;
2326: $ctr = 0;
2327: while ($ctr < $total) {
2328: my $processUser = $env{'form.unamedom'.$ctr};
2329: ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
2330: $env{'form.fullname'} = $$fullname{$processUser};
2331: &submission($request,$ctr,$total-1);
2332: $ctr++;
2333: }
2334: return '';
2335: }
2336:
2337: # Go directly to grade student - from submission or link from chart page
2338: if ($button eq 'Grade Student') {
2339: (undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
2340: my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
2341: ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
2342: $env{'form.fullname'} = $$fullname{$processUser};
2343: &submission($request,0,0);
2344: return '';
2345: }
2346:
2347: # Get the next/previous one or group of students
2348: my $firststu = $env{'form.unamedom0'};
2349: my $laststu = $env{'form.unamedom'.($ngrade-1)};
2350: my $ctr = 2;
2351: while ($laststu eq '') {
2352: $laststu = $env{'form.unamedom'.($ngrade-$ctr)};
2353: $ctr++;
2354: $laststu = $firststu if ($ctr > $ngrade);
2355: }
2356:
2357: my (@parsedlist,@nextlist);
2358: my ($nextflg) = 0;
2359: foreach (sort
2360: {
2361: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
2362: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
2363: }
2364: return $a cmp $b;
2365: } (keys(%$fullname))) {
2366: if ($nextflg == 1 && $button =~ /Next$/) {
2367: push @parsedlist,$_;
2368: }
2369: $nextflg = 1 if ($_ eq $laststu);
2370: if ($button eq 'Previous') {
2371: last if ($_ eq $firststu);
2372: push @parsedlist,$_;
2373: }
2374: }
2375: $ctr = 0;
2376: @parsedlist = reverse @parsedlist if ($button eq 'Previous');
2377: my ($partlist) = &response_type($symb);
2378: foreach my $student (@parsedlist) {
2379: my $submitonly=$env{'form.submitonly'};
2380: my ($uname,$udom) = split(/:/,$student);
2381:
2382: if ($submitonly eq 'queued') {
2383: my %queue_status =
2384: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
2385: $udom,$uname);
2386: next if (!defined($queue_status{'gradingqueue'}));
2387: }
2388:
2389: if ($submitonly =~ /^(yes|graded|incorrect)$/) {
2390: # my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
2391: my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
2392: my $submitted = 0;
2393: my $ungraded = 0;
2394: my $incorrect = 0;
2395: foreach (keys(%status)) {
2396: $submitted = 1 if ($status{$_} ne 'nothing');
2397: $ungraded = 1 if ($status{$_} =~ /^ungraded/);
2398: $incorrect = 1 if ($status{$_} =~ /^incorrect/);
2399: my ($foo,$partid,$foo1) = split(/\./,$_);
2400: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
2401: $submitted = 0;
2402: }
2403: }
2404: next if (!$submitted && ($submitonly eq 'yes' ||
2405: $submitonly eq 'incorrect' ||
2406: $submitonly eq 'graded'));
2407: next if (!$ungraded && ($submitonly eq 'graded'));
2408: next if (!$incorrect && $submitonly eq 'incorrect');
2409: }
2410: push @nextlist,$student if ($ctr < $ntstu);
2411: last if ($ctr == $ntstu);
2412: $ctr++;
2413: }
2414:
2415: $ctr = 0;
2416: my $total = scalar(@nextlist)-1;
2417:
2418: foreach (sort @nextlist) {
2419: my ($uname,$udom,$submitter) = split(/:/);
2420: $env{'form.student'} = $uname;
2421: $env{'form.userdom'} = $udom;
2422: $env{'form.fullname'} = $$fullname{$_};
2423: &submission($request,$ctr,$total);
2424: $ctr++;
2425: }
2426: if ($total < 0) {
2427: my $the_end = '<h3><span class="LC_info">LON-CAPA User Message</span></h3><br />'."\n";
2428: $the_end.='<b>Message: </b> No more students for this section or class.<br /><br />'."\n";
2429: $the_end.='Click on the button below to return to the grading menu.<br /><br />'."\n";
2430: $the_end.=&show_grading_menu_form($symb);
2431: $request->print($the_end);
2432: }
2433: return '';
2434: }
2435:
2436: #---- Save the score and award for each student, if changed
2437: sub saveHandGrade {
2438: my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
2439: my @version_parts;
2440: my $usec = &Apache::lonnet::getsection($domain,$stuname,
2441: $env{'request.course.id'});
2442: if (!&canmodify($usec)) { return('not_allowed'); }
2443: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
2444: my @parts_graded;
2445: my %newrecord = ();
2446: my ($pts,$wgt) = ('','');
2447: my %aggregate = ();
2448: my $aggregateflag = 0;
2449: my @parts = split(/:/,$env{'form.partlist'.$newflg});
2450: foreach my $new_part (@parts) {
2451: #collaborator ($submi may vary for different parts
2452: if ($submitter && $new_part ne $part) { next; }
2453: my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
2454: if ($dropMenu eq 'excused') {
2455: if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
2456: $newrecord{'resource.'.$new_part.'.solved'} = 'excused';
2457: if (exists($record{'resource.'.$new_part.'.awarded'})) {
2458: $newrecord{'resource.'.$new_part.'.awarded'} = '';
2459: }
2460: $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
2461: }
2462: } elsif ($dropMenu eq 'reset status'
2463: && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
2464: foreach my $key (keys (%record)) {
2465: if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
2466: }
2467: $newrecord{'resource.'.$new_part.'.regrader'}=
2468: "$env{'user.name'}:$env{'user.domain'}";
2469: my $totaltries = $record{'resource.'.$part.'.tries'};
2470:
2471: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
2472: [$new_part]);
2473: my $aggtries =$totaltries;
2474: if ($last_resets{$new_part}) {
2475: $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
2476: $new_part);
2477: }
2478:
2479: my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
2480: if ($aggtries > 0) {
2481: &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
2482: $aggregateflag = 1;
2483: }
2484: } elsif ($dropMenu eq '') {
2485: $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ?
2486: $env{'form.GD_BOX'.$newflg.'_'.$new_part} :
2487: $env{'form.RADVAL'.$newflg.'_'.$new_part});
2488: if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
2489: next;
2490: }
2491: $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 :
2492: $env{'form.WGT'.$newflg.'_'.$new_part};
2493: my $partial= $pts/$wgt;
2494: if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
2495: #do not update score for part if not changed.
2496: &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
2497: next;
2498: } else {
2499: push @parts_graded, $new_part;
2500: }
2501: if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
2502: $newrecord{'resource.'.$new_part.'.awarded'} = $partial;
2503: }
2504: my $reckey = 'resource.'.$new_part.'.solved';
2505: if ($partial == 0) {
2506: if ($record{$reckey} ne 'incorrect_by_override') {
2507: $newrecord{$reckey} = 'incorrect_by_override';
2508: }
2509: } else {
2510: if ($record{$reckey} ne 'correct_by_override') {
2511: $newrecord{$reckey} = 'correct_by_override';
2512: }
2513: }
2514: if ($submitter &&
2515: ($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
2516: $newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
2517: }
2518: $newrecord{'resource.'.$new_part.'.regrader'}=
2519: "$env{'user.name'}:$env{'user.domain'}";
2520: }
2521: # unless problem has been graded, set flag to version the submitted files
2522: unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/ ||
2523: $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
2524: $dropMenu eq 'reset status')
2525: {
2526: push (@version_parts,$new_part);
2527: }
2528: }
2529: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2530: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2531:
2532: if (%newrecord) {
2533: if (@version_parts) {
2534: my @changed_keys = &version_portfiles(\%record, \@parts_graded,
2535: $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
2536: @newrecord{@changed_keys} = @record{@changed_keys};
2537: foreach my $new_part (@version_parts) {
2538: &handback_files($request,$symb,$stuname,$domain,$newflg,
2539: $new_part,\%newrecord);
2540: }
2541: }
2542: &Apache::lonnet::cstore(\%newrecord,$symb,
2543: $env{'request.course.id'},$domain,$stuname);
2544: &check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
2545: $cdom,$cnum,$domain,$stuname);
2546: }
2547: if ($aggregateflag) {
2548: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
2549: $cdom,$cnum);
2550: }
2551: return ('',$pts,$wgt);
2552: }
2553:
2554: sub check_and_remove_from_queue {
2555: my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
2556: my @ungraded_parts;
2557: foreach my $part (@{$parts}) {
2558: if ( $record->{ 'resource.'.$part.'.awarded'} eq ''
2559: && $record->{ 'resource.'.$part.'.solved' } ne 'excused'
2560: && $newrecord->{'resource.'.$part.'.awarded'} eq ''
2561: && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
2562: ) {
2563: push(@ungraded_parts, $part);
2564: }
2565: }
2566: if ( !@ungraded_parts ) {
2567: &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
2568: $cnum,$domain,$stuname);
2569: }
2570: }
2571:
2572: sub handback_files {
2573: my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
2574: my $portfolio_root = &propath($domain,$stuname).'/userfiles/portfolio';
2575: my ($partlist,$handgrade,$responseType) = &response_type($symb);
2576:
2577: my @part_response_id = &flatten_responseType($responseType);
2578: foreach my $part_response_id (@part_response_id) {
2579: my ($part_id,$resp_id) = @{ $part_response_id };
2580: my $part_resp = join('_',@{ $part_response_id });
2581: if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
2582: # if multiple files are uploaded names will be 'returndoc2','returndoc3'
2583: my $file_counter = 1;
2584: my $file_msg;
2585: while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
2586: my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
2587: my ($directory,$answer_file) =
2588: ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
2589: my ($answer_name,$answer_ver,$answer_ext) =
2590: &file_name_version_ext($answer_file);
2591: my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
2592: my @dir_list = &Apache::lonnet::dirlist($portfolio_path,$domain,$stuname,$portfolio_root);
2593: my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
2594: # fix file name
2595: my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
2596: my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
2597: $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
2598: $save_file_name);
2599: if ($result !~ m|^/uploaded/|) {
2600: $request->print('<span class="LC_error">An error occurred ('.$result.
2601: ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</span><br />');
2602: } else {
2603: # mark the file as read only
2604: my @files = ($save_file_name);
2605: my @what = ($symb,$env{'request.course.id'},'handback');
2606: &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
2607: if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
2608: $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
2609: }
2610: $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
2611: $file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
2612:
2613: }
2614: $request->print("<br />".$fname." will be the uploaded file name");
2615: $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
2616: $file_counter++;
2617: }
2618: my $subject = "File Handed Back by Instructor ";
2619: my $message = "A file has been returned that was originally submitted in reponse to: <br />";
2620: $message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
2621: $message .= ' The returned file(s) are named: '. $file_msg;
2622: $message .= " and can be found in your portfolio space.";
2623: my ($feedurl,$showsymb) =
2624: &get_feedurl_and_symb($symb,$domain,$stuname);
2625: my $restitle = &Apache::lonnet::gettitle($symb);
2626: my $msgstatus =
2627: &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
2628: ' (File Returned) ['.$restitle.']',$message,undef,
2629: $feedurl,undef,undef,undef,$showsymb,$restitle);
2630: }
2631: }
2632: return;
2633: }
2634:
2635: sub get_feedurl_and_symb {
2636: my ($symb,$uname,$udom) = @_;
2637: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
2638: $url = &Apache::lonnet::clutter($url);
2639: my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
2640: $symb,$udom,$uname);
2641: if ($encrypturl =~ /^yes$/i) {
2642: &Apache::lonenc::encrypted(\$url,1);
2643: &Apache::lonenc::encrypted(\$symb,1);
2644: }
2645: return ($url,$symb);
2646: }
2647:
2648: sub get_submitted_files {
2649: my ($udom,$uname,$partid,$respid,$record) = @_;
2650: my @files;
2651: if ($$record{"resource.$partid.$respid.portfiles"}) {
2652: my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
2653: foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
2654: push(@files,$file_url.$file);
2655: }
2656: }
2657: if ($$record{"resource.$partid.$respid.uploadedurl"}) {
2658: push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
2659: }
2660: return (\@files);
2661: }
2662:
2663: # ----------- Provides number of tries since last reset.
2664: sub get_num_tries {
2665: my ($record,$last_reset,$part) = @_;
2666: my $timestamp = '';
2667: my $num_tries = 0;
2668: if ($$record{'version'}) {
2669: for (my $version=$$record{'version'};$version>=1;$version--) {
2670: if (exists($$record{$version.':resource.'.$part.'.solved'})) {
2671: $timestamp = $$record{$version.':timestamp'};
2672: if ($timestamp > $last_reset) {
2673: $num_tries ++;
2674: } else {
2675: last;
2676: }
2677: }
2678: }
2679: }
2680: return $num_tries;
2681: }
2682:
2683: # ----------- Determine decrements required in aggregate totals
2684: sub decrement_aggs {
2685: my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
2686: my %decrement = (
2687: attempts => 0,
2688: users => 0,
2689: correct => 0
2690: );
2691: $decrement{'attempts'} = $aggtries;
2692: if ($solvedstatus =~ /^correct/) {
2693: $decrement{'correct'} = 1;
2694: }
2695: if ($aggtries == $totaltries) {
2696: $decrement{'users'} = 1;
2697: }
2698: foreach my $type (keys (%decrement)) {
2699: $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
2700: }
2701: return;
2702: }
2703:
2704: # ----------- Determine timestamps for last reset of aggregate totals for parts
2705: sub get_last_resets {
2706: my ($symb,$courseid,$partids) =@_;
2707: my %last_resets;
2708: my $cdom = $env{'course.'.$courseid.'.domain'};
2709: my $cname = $env{'course.'.$courseid.'.num'};
2710: my @keys;
2711: foreach my $part (@{$partids}) {
2712: push(@keys,"$symb\0$part\0resettime");
2713: }
2714: my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
2715: $cdom,$cname);
2716: foreach my $part (@{$partids}) {
2717: $last_resets{$part}=$results{"$symb\0$part\0resettime"};
2718: }
2719: return %last_resets;
2720: }
2721:
2722: # ----------- Handles creating versions for portfolio files as answers
2723: sub version_portfiles {
2724: my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
2725: my $version_parts = join('|',@$v_flag);
2726: my @returned_keys;
2727: my $parts = join('|', @$parts_graded);
2728: my $portfolio_root = &propath($domain,$stu_name).
2729: '/userfiles/portfolio';
2730: foreach my $key (keys(%$record)) {
2731: my $new_portfiles;
2732: if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
2733: my @versioned_portfiles;
2734: my @portfiles = split(/\s*,\s*/,$$record{$key});
2735: foreach my $file (@portfiles) {
2736: &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
2737: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
2738: my ($answer_name,$answer_ver,$answer_ext) =
2739: &file_name_version_ext($answer_file);
2740: my @dir_list = &Apache::lonnet::dirlist($directory,$domain,$stu_name,$portfolio_root);
2741: my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
2742: my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
2743: if ($new_answer ne 'problem getting file') {
2744: push(@versioned_portfiles, $directory.$new_answer);
2745: &Apache::lonnet::mark_as_readonly($domain,$stu_name,
2746: [$directory.$new_answer],
2747: [$symb,$env{'request.course.id'},'graded']);
2748: }
2749: }
2750: $$record{$key} = join(',',@versioned_portfiles);
2751: push(@returned_keys,$key);
2752: }
2753: }
2754: return (@returned_keys);
2755: }
2756:
2757: sub get_next_version {
2758: my ($answer_name, $answer_ext, $dir_list) = @_;
2759: my $version;
2760: foreach my $row (@$dir_list) {
2761: my ($file) = split(/\&/,$row,2);
2762: my ($file_name,$file_version,$file_ext) =
2763: &file_name_version_ext($file);
2764: if (($file_name eq $answer_name) &&
2765: ($file_ext eq $answer_ext)) {
2766: # gets here if filename and extension match, regardless of version
2767: if ($file_version ne '') {
2768: # a versioned file is found so save it for later
2769: if ($file_version > $version) {
2770: $version = $file_version;
2771: }
2772: }
2773: }
2774: }
2775: $version ++;
2776: return($version);
2777: }
2778:
2779: sub version_selected_portfile {
2780: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
2781: my ($answer_name,$answer_ver,$answer_ext) =
2782: &file_name_version_ext($file_name);
2783: my $new_answer;
2784: $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
2785: if($env{'form.copy'} eq '-1') {
2786: &Apache::lonnet::logthis('problem getting file '.$file_name);
2787: $new_answer = 'problem getting file';
2788: } else {
2789: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
2790: my $copy_result = &Apache::lonnet::finishuserfileupload(
2791: $stu_name,$domain,'copy',
2792: '/portfolio'.$directory.$new_answer);
2793: }
2794: return ($new_answer);
2795: }
2796:
2797: sub file_name_version_ext {
2798: my ($file)=@_;
2799: my @file_parts = split(/\./, $file);
2800: my ($name,$version,$ext);
2801: if (@file_parts > 1) {
2802: $ext=pop(@file_parts);
2803: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
2804: $version=pop(@file_parts);
2805: }
2806: $name=join('.',@file_parts);
2807: } else {
2808: $name=join('.',@file_parts);
2809: }
2810: return($name,$version,$ext);
2811: }
2812:
2813: #--------------------------------------------------------------------------------------
2814: #
2815: #-------------------------- Next few routines handles grading by section or whole class
2816: #
2817: #--- Javascript to handle grading by section or whole class
2818: sub viewgrades_js {
2819: my ($request) = shift;
2820:
2821: $request->print(<<VIEWJAVASCRIPT);
2822: <script type="text/javascript" language="javascript">
2823: function writePoint(partid,weight,point) {
2824: var radioButton = document.classgrade["RADVAL_"+partid];
2825: var textbox = document.classgrade["TEXTVAL_"+partid];
2826: if (point == "textval") {
2827: point = document.classgrade["TEXTVAL_"+partid].value;
2828: if (isNaN(point) || parseFloat(point) < 0) {
2829: alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
2830: var resetbox = false;
2831: for (var i=0; i<radioButton.length; i++) {
2832: if (radioButton[i].checked) {
2833: textbox.value = i;
2834: resetbox = true;
2835: }
2836: }
2837: if (!resetbox) {
2838: textbox.value = "";
2839: }
2840: return;
2841: }
2842: if (parseFloat(point) > parseFloat(weight)) {
2843: var resp = confirm("You entered a value ("+parseFloat(point)+
2844: ") greater than the weight for the part. Accept?");
2845: if (resp == false) {
2846: textbox.value = "";
2847: return;
2848: }
2849: }
2850: for (var i=0; i<radioButton.length; i++) {
2851: radioButton[i].checked=false;
2852: if (parseFloat(point) == i) {
2853: radioButton[i].checked=true;
2854: }
2855: }
2856:
2857: } else {
2858: textbox.value = parseFloat(point);
2859: }
2860: for (i=0;i<document.classgrade.total.value;i++) {
2861: var user = document.classgrade["ctr"+i].value;
2862: user = user.replace(new RegExp(':', 'g'),"_");
2863: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
2864: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
2865: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
2866: if (saveval != "correct") {
2867: scorename.value = point;
2868: if (selname[0].selected != true) {
2869: selname[0].selected = true;
2870: }
2871: }
2872: }
2873: document.classgrade["SELVAL_"+partid][0].selected = true;
2874: }
2875:
2876: function writeRadText(partid,weight) {
2877: var selval = document.classgrade["SELVAL_"+partid];
2878: var radioButton = document.classgrade["RADVAL_"+partid];
2879: var override = document.classgrade["FORCE_"+partid].checked;
2880: var textbox = document.classgrade["TEXTVAL_"+partid];
2881: if (selval[1].selected || selval[2].selected) {
2882: for (var i=0; i<radioButton.length; i++) {
2883: radioButton[i].checked=false;
2884:
2885: }
2886: textbox.value = "";
2887:
2888: for (i=0;i<document.classgrade.total.value;i++) {
2889: var user = document.classgrade["ctr"+i].value;
2890: user = user.replace(new RegExp(':', 'g'),"_");
2891: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
2892: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
2893: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
2894: if ((saveval != "correct") || override) {
2895: scorename.value = "";
2896: if (selval[1].selected) {
2897: selname[1].selected = true;
2898: } else {
2899: selname[2].selected = true;
2900: if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value))
2901: {document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
2902: }
2903: }
2904: }
2905: } else {
2906: for (i=0;i<document.classgrade.total.value;i++) {
2907: var user = document.classgrade["ctr"+i].value;
2908: user = user.replace(new RegExp(':', 'g'),"_");
2909: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
2910: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
2911: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
2912: if ((saveval != "correct") || override) {
2913: scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
2914: selname[0].selected = true;
2915: }
2916: }
2917: }
2918: }
2919:
2920: function changeSelect(partid,user) {
2921: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
2922: var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
2923: var point = textbox.value;
2924: var weight = document.classgrade["weight_"+partid].value;
2925:
2926: if (isNaN(point) || parseFloat(point) < 0) {
2927: alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
2928: textbox.value = "";
2929: return;
2930: }
2931: if (parseFloat(point) > parseFloat(weight)) {
2932: var resp = confirm("You entered a value ("+parseFloat(point)+
2933: ") greater than the weight of the part. Accept?");
2934: if (resp == false) {
2935: textbox.value = "";
2936: return;
2937: }
2938: }
2939: selval[0].selected = true;
2940: }
2941:
2942: function changeOneScore(partid,user) {
2943: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
2944: if (selval[1].selected || selval[2].selected) {
2945: document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
2946: if (selval[2].selected) {
2947: document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
2948: }
2949: }
2950: }
2951:
2952: function resetEntry(numpart) {
2953: for (ctpart=0;ctpart<numpart;ctpart++) {
2954: var partid = document.classgrade["partid_"+ctpart].value;
2955: var radioButton = document.classgrade["RADVAL_"+partid];
2956: var textbox = document.classgrade["TEXTVAL_"+partid];
2957: var selval = document.classgrade["SELVAL_"+partid];
2958: for (var i=0; i<radioButton.length; i++) {
2959: radioButton[i].checked=false;
2960:
2961: }
2962: textbox.value = "";
2963: selval[0].selected = true;
2964:
2965: for (i=0;i<document.classgrade.total.value;i++) {
2966: var user = document.classgrade["ctr"+i].value;
2967: user = user.replace(new RegExp(':', 'g'),"_");
2968: var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
2969: resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
2970: var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
2971: resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
2972: var saveselval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
2973: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
2974: if (saveselval == "excused") {
2975: if (selname[1].selected == false) { selname[1].selected = true;}
2976: } else {
2977: if (selname[0].selected == false) {selname[0].selected = true};
2978: }
2979: }
2980: }
2981: }
2982:
2983: </script>
2984: VIEWJAVASCRIPT
2985: }
2986:
2987: #--- show scores for a section or whole class w/ option to change/update a score
2988: sub viewgrades {
2989: my ($request) = shift;
2990: &viewgrades_js($request);
2991:
2992: my ($symb) = &get_symb($request);
2993: #need to make sure we have the correct data for later EXT calls,
2994: #thus invalidate the cache
2995: &Apache::lonnet::devalidatecourseresdata(
2996: $env{'course.'.$env{'request.course.id'}.'.num'},
2997: $env{'course.'.$env{'request.course.id'}.'.domain'});
2998: &Apache::lonnet::clear_EXT_cache_status();
2999:
3000: my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
3001: $result.='<h4><b>Current Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n";
3002:
3003: #view individual student submission form - called using Javascript viewOneStudent
3004: $result.=&jscriptNform($symb);
3005:
3006: #beginning of class grading form
3007: $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
3008: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
3009: '<input type="hidden" name="command" value="editgrades" />'."\n".
3010: &build_section_inputs().
3011: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
3012: '<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n".
3013: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
3014:
3015: my $sectionClass;
3016: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3017: if ($env{'form.section'} eq 'all') {
3018: $sectionClass='Class </h3>';
3019: } elsif ($env{'form.section'} eq 'none') {
3020: $sectionClass=&mt('Students in no Section').'</h3>';
3021: } else {
3022: $sectionClass=&mt('Students in Section(s) [_1]',$section_display).'</h3>';
3023: }
3024: $result.='<h3>'.&mt('Assign Common Grade To [_1]',$sectionClass);
3025: $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
3026: '<table border=0><tr bgcolor="#ffffdd"><td>';
3027: #radio buttons/text box for assigning points for a section or class.
3028: #handles different parts of a problem
3029: my ($partlist,$handgrade,$responseType) = &response_type($symb);
3030: my %weight = ();
3031: my $ctsparts = 0;
3032: $result.='<table border="0">';
3033: my %seen = ();
3034: my @part_response_id = &flatten_responseType($responseType);
3035: foreach my $part_response_id (@part_response_id) {
3036: my ($partid,$respid) = @{ $part_response_id };
3037: my $part_resp = join('_',@{ $part_response_id });
3038: next if $seen{$partid};
3039: $seen{$partid}++;
3040: my $handgrade=$$handgrade{$part_resp};
3041: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
3042: $weight{$partid} = $wgt eq '' ? '1' : $wgt;
3043:
3044: $result.='<input type="hidden" name="partid_'.
3045: $ctsparts.'" value="'.$partid.'" />'."\n";
3046: $result.='<input type="hidden" name="weight_'.
3047: $partid.'" value="'.$weight{$partid}.'" />'."\n";
3048: my $display_part=&get_display_part($partid,$symb);
3049: $result.='<tr><td><b>Part:</b> '.$display_part.' <b>Point:</b> </td><td>';
3050: $result.='<table border="0"><tr>';
3051: my $ctr = 0;
3052: while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
3053: $result.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
3054: 'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
3055: ','.$ctr.')" />'.$ctr."</label></td>\n";
3056: $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
3057: $ctr++;
3058: }
3059: $result.='</tr></table>';
3060: $result.= '</td><td><b> or </b><input type="text" name="TEXTVAL_'.
3061: $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
3062: $partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
3063: $weight{$partid}.' (problem weight)</td>'."\n";
3064: $result.= '</td><td><select name="SELVAL_'.$partid.'"'.
3065: 'onChange="javascript:writeRadText(\''.$partid.'\','.
3066: $weight{$partid}.')"> '.
3067: '<option selected="selected"> </option>'.
3068: '<option>excused</option>'.
3069: '<option>reset status</option></select></td>'.
3070: '<td><label><input type="checkbox" name="FORCE_'.$partid.'" /> Override "Correct"</label></td></tr>'."\n";
3071: $ctsparts++;
3072: }
3073: $result.='</table>'.'</td></tr></table>'.'</td></tr></table>'."\n".
3074: '<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
3075: $result.='<input type="button" value="Revert to Default" '.
3076: 'onClick="javascript:resetEntry('.$ctsparts.');" target="_self" />';
3077:
3078: #table listing all the students in a section/class
3079: #header of table
3080: $result.= '<h3>Assign Grade to Specific Students in '.$sectionClass;
3081: $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
3082: '<table border=0><tr bgcolor="#deffff"><td> <b>No.</b> </td>'.
3083: '<td>'.&nameUserString('header')."</td>\n";
3084: my (@parts) = sort(&getpartlist($symb));
3085: my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
3086: my @partids = ();
3087: foreach my $part (@parts) {
3088: my $display=&Apache::lonnet::metadata($url,$part.'.display');
3089: $display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
3090: if (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
3091: my ($partid) = &split_part_type($part);
3092: push(@partids, $partid);
3093: my $display_part=&get_display_part($partid,$symb);
3094: if ($display =~ /^Partial Credit Factor/) {
3095: $result.='<td><b>Score Part:</b> '.$display_part.
3096: ' <br /><b>(weight = '.$weight{$partid}.')</b></td>'."\n";
3097: next;
3098: } else {
3099: $display =~s/\[Part: \Q$partid\E\]/Part:<\/b> $display_part/;
3100: }
3101: $display =~ s|Problem Status|Grade Status<br />|;
3102: $result.='<td><b>'.$display.'</td>'."\n";
3103: }
3104: $result.='</tr>';
3105:
3106: my %last_resets =
3107: &get_last_resets($symb,$env{'request.course.id'},\@partids);
3108:
3109: #get info for each student
3110: #list all the students - with points and grade status
3111: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
3112: my $ctr = 0;
3113: foreach (sort
3114: {
3115: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
3116: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
3117: }
3118: return $a cmp $b;
3119: } (keys(%$fullname))) {
3120: $ctr++;
3121: $result.=&viewstudentgrade($symb,$env{'request.course.id'},
3122: $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
3123: }
3124: $result.='</table></td></tr></table>';
3125: $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
3126: $result.='<input type="button" value="Save" '.
3127: 'onClick="javascript:submit();" target="_self" /></form>'."\n";
3128: if (scalar(%$fullname) eq 0) {
3129: my $colspan=3+scalar(@parts);
3130: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3131: $result='<span class="LC_warning">'.
3132: &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade',
3133: $section_display, $env{'form.Status'}).
3134: '</span>';
3135: }
3136: $result.=&show_grading_menu_form($symb);
3137: return $result;
3138: }
3139:
3140: #--- call by previous routine to display each student
3141: sub viewstudentgrade {
3142: my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
3143: my ($uname,$udom) = split(/:/,$student);
3144: my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
3145: my %aggregates = ();
3146: my $result='<tr bgcolor="#ffffdd"><td align="right">'.
3147: '<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
3148: "\n".$ctr.' </td><td> '.
3149: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
3150: '\');" target="_self">'.$fullname.'</a> '.
3151: '<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
3152: $student=~s/:/_/; # colon doen't work in javascript for names
3153: foreach my $apart (@$parts) {
3154: my ($part,$type) = &split_part_type($apart);
3155: my $score=$record{"resource.$part.$type"};
3156: $result.='<td align="center">';
3157: my ($aggtries,$totaltries);
3158: unless (exists($aggregates{$part})) {
3159: $totaltries = $record{'resource.'.$part.'.tries'};
3160:
3161: $aggtries = $totaltries;
3162: if ($$last_resets{$part}) {
3163: $aggtries = &get_num_tries(\%record,$$last_resets{$part},
3164: $part);
3165: }
3166: $result.='<input type="hidden" name="'.
3167: 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
3168: $result.='<input type="hidden" name="'.
3169: 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
3170: $aggregates{$part} = 1;
3171: }
3172: if ($type eq 'awarded') {
3173: my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
3174: $result.='<input type="hidden" name="'.
3175: 'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
3176: $result.='<input type="text" name="'.
3177: 'GD_'.$student.'_'.$part.'_awarded" '.
3178: 'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
3179: '\')" value="'.$pts.'" size="4" /></td>'."\n";
3180: } elsif ($type eq 'solved') {
3181: my ($status,$foo)=split(/_/,$score,2);
3182: $status = 'nothing' if ($status eq '');
3183: $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
3184: $part.'_solved_s" value="'.$status.'" />'."\n";
3185: $result.=' <select name="'.
3186: 'GD_'.$student.'_'.$part.'_solved" '.
3187: 'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
3188: $result.= (($status eq 'excused') ? '<option> </option><option selected="selected">excused</option>'
3189: : '<option selected="selected"> </option><option>excused</option>')."\n";
3190: $result.='<option>reset status</option>';
3191: $result.="</select> </td>\n";
3192: } else {
3193: $result.='<input type="hidden" name="'.
3194: 'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
3195: "\n";
3196: $result.='<input type="text" name="'.
3197: 'GD_'.$student.'_'.$part.'_'.$type.'" '.
3198: 'value="'.$score.'" size="4" /></td>'."\n";
3199: }
3200: }
3201: $result.='</tr>';
3202: return $result;
3203: }
3204:
3205: #--- change scores for all the students in a section/class
3206: # record does not get update if unchanged
3207: sub editgrades {
3208: my ($request) = @_;
3209:
3210: my $symb=&get_symb($request);
3211: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3212: my $title='<h3><span class="LC_info">'.&mt('Current Grade Status').'</span></h3>';
3213: $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4><br />'."\n";
3214: $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
3215:
3216: my $result= '<table border="0"><tr><td bgcolor="#777777">'."\n";
3217: $result.= '<table border="0"><tr bgcolor="#deffff">'.
3218: '<td rowspan=2 valign="center"> <b>No.</b> </td>'.
3219: '<td rowspan=2 valign="center">'.&nameUserString('header')."</td>\n";
3220:
3221: my %scoreptr = (
3222: 'correct' =>'correct_by_override',
3223: 'incorrect'=>'incorrect_by_override',
3224: 'excused' =>'excused',
3225: 'ungraded' =>'ungraded_attempted',
3226: 'nothing' => '',
3227: );
3228: my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
3229:
3230: my (@partid);
3231: my %weight = ();
3232: my %columns = ();
3233: my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
3234:
3235: my (@parts) = sort(&getpartlist($symb));
3236: my $header;
3237: while ($ctr < $env{'form.totalparts'}) {
3238: my $partid = $env{'form.partid_'.$ctr};
3239: push @partid,$partid;
3240: $weight{$partid} = $env{'form.weight_'.$partid};
3241: $ctr++;
3242: }
3243: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3244: foreach my $partid (@partid) {
3245: $header .= '<td align="center"> <b>Old Score</b> </td>'.
3246: '<td align="center"> <b>New Score</b> </td>';
3247: $columns{$partid}=2;
3248: foreach my $stores (@parts) {
3249: my ($part,$type) = &split_part_type($stores);
3250: if ($part !~ m/^\Q$partid\E/) { next;}
3251: if ($type eq 'awarded' || $type eq 'solved') { next; }
3252: my $display=&Apache::lonnet::metadata($url,$stores.'.display');
3253: $display =~ s/\[Part: (\w)+\]//;
3254: $display =~ s/Number of Attempts/Tries/;
3255: $header .= '<td align="center"> <b>Old '.$display.'</b> </td>'.
3256: '<td align="center"> <b>New '.$display.'</b> </td>';
3257: $columns{$partid}+=2;
3258: }
3259: }
3260: foreach my $partid (@partid) {
3261: my $display_part=&get_display_part($partid,$symb);
3262: $result .= '<td colspan="'.$columns{$partid}.
3263: '" align="center"><b>Part:</b> '.$display_part.
3264: ' (Weight = '.$weight{$partid}.')</td>';
3265:
3266: }
3267: $result .= '</tr><tr bgcolor="#deffff">';
3268: $result .= $header;
3269: $result .= '</tr>'."\n";
3270: my $noupdate;
3271: my ($updateCtr,$noupdateCtr) = (1,1);
3272: for ($i=0; $i<$env{'form.total'}; $i++) {
3273: my $line;
3274: my $user = $env{'form.ctr'.$i};
3275: my ($uname,$udom)=split(/:/,$user);
3276: my %newrecord;
3277: my $updateflag = 0;
3278: $line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
3279: my $usec=$classlist->{"$uname:$udom"}[5];
3280: if (!&canmodify($usec)) {
3281: my $numcols=scalar(@partid)*4+2;
3282: $noupdate.=$line."<td colspan=\"$numcols\"><span class=\"LC_warning\">Not allowed to modify student</span></td></tr>";
3283: next;
3284: }
3285: my %aggregate = ();
3286: my $aggregateflag = 0;
3287: $user=~s/:/_/; # colon doen't work in javascript for names
3288: foreach (@partid) {
3289: my $old_aw = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
3290: my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
3291: my $old_part = $old_aw eq '' ? '' : $old_part_pcr;
3292: my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
3293: my $awarded = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
3294: my $pcr = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
3295: my $partial = $awarded eq '' ? '' : $pcr;
3296: my $score;
3297: if ($partial eq '') {
3298: $score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
3299: } elsif ($partial > 0) {
3300: $score = 'correct_by_override';
3301: } elsif ($partial == 0) {
3302: $score = 'incorrect_by_override';
3303: }
3304: my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
3305: $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
3306:
3307: $newrecord{'resource.'.$_.'.regrader'}=
3308: "$env{'user.name'}:$env{'user.domain'}";
3309: if ($dropMenu eq 'reset status' &&
3310: $old_score ne '') { # ignore if no previous attempts => nothing to reset
3311: $newrecord{'resource.'.$_.'.tries'} = '';
3312: $newrecord{'resource.'.$_.'.solved'} = '';
3313: $newrecord{'resource.'.$_.'.award'} = '';
3314: $newrecord{'resource.'.$_.'.awarded'} = '';
3315: $updateflag = 1;
3316: if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
3317: my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
3318: my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
3319: my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
3320: &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
3321: $aggregateflag = 1;
3322: }
3323: } elsif (!($old_part eq $partial && $old_score eq $score)) {
3324: $updateflag = 1;
3325: $newrecord{'resource.'.$_.'.awarded'} = $partial if $partial ne '';
3326: $newrecord{'resource.'.$_.'.solved'} = $score;
3327: $rec_update++;
3328: }
3329:
3330: $line .= '<td align="center">'.$old_aw.' </td>'.
3331: '<td align="center">'.$awarded.
3332: ($score eq 'excused' ? $score : '').' </td>';
3333:
3334:
3335: my $partid=$_;
3336: foreach my $stores (@parts) {
3337: my ($part,$type) = &split_part_type($stores);
3338: if ($part !~ m/^\Q$partid\E/) { next;}
3339: if ($type eq 'awarded' || $type eq 'solved') { next; }
3340: my $old_aw = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
3341: my $awarded = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
3342: if ($awarded ne '' && $awarded ne $old_aw) {
3343: $newrecord{'resource.'.$part.'.'.$type}= $awarded;
3344: $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
3345: $updateflag=1;
3346: }
3347: $line .= '<td align="center">'.$old_aw.' </td>'.
3348: '<td align="center">'.$awarded.' </td>';
3349: }
3350: }
3351: $line.='</tr>'."\n";
3352:
3353: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3354: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3355:
3356: if ($updateflag) {
3357: $count++;
3358: &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
3359: $udom,$uname);
3360:
3361: if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
3362: $cnum,$udom,$uname)) {
3363: # need to figure out if should be in queue.
3364: my %record =
3365: &Apache::lonnet::restore($symb,$env{'request.course.id'},
3366: $udom,$uname);
3367: my $all_graded = 1;
3368: my $none_graded = 1;
3369: foreach my $part (@parts) {
3370: if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
3371: $all_graded = 0;
3372: } else {
3373: $none_graded = 0;
3374: }
3375: }
3376:
3377: if ($all_graded || $none_graded) {
3378: &Apache::bridgetask::remove_from_queue('gradingqueue',
3379: $symb,$cdom,$cnum,
3380: $udom,$uname);
3381: }
3382: }
3383:
3384: $result.='<tr bgcolor="#ffffde"><td align="right"> '.$updateCtr.' </td>'.$line;
3385: $updateCtr++;
3386: } else {
3387: $noupdate.='<tr bgcolor="#ffffde"><td align="right"> '.$noupdateCtr.' </td>'.$line;
3388: $noupdateCtr++;
3389: }
3390: if ($aggregateflag) {
3391: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
3392: $cdom,$cnum);
3393: }
3394: }
3395: if ($noupdate) {
3396: # my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
3397: my $numcols=scalar(@partid)*4+2;
3398: $result .= '<tr bgcolor="#ffffff"><td align="center" colspan="'.$numcols.'">No Changes Occurred For the Students Below</td></tr><tr bgcolor="#ffffde">'.$noupdate;
3399: }
3400: $result .= '</table></td></tr></table>'."\n".
3401: &show_grading_menu_form ($symb);
3402: my $msg = '<br /><b>Number of records updated = '.$rec_update.
3403: ' for '.$count.' student'.($count <= 1 ? '' : 's').'.</b><br />'.
3404: '<b>Total number of students = '.$env{'form.total'}.'</b><br />';
3405: return $title.$msg.$result;
3406: }
3407:
3408: sub split_part_type {
3409: my ($partstr) = @_;
3410: my ($temp,@allparts)=split(/_/,$partstr);
3411: my $type=pop(@allparts);
3412: my $part=join('.',@allparts);
3413: return ($part,$type);
3414: }
3415:
3416: #------------- end of section for handling grading by section/class ---------
3417: #
3418: #----------------------------------------------------------------------------
3419:
3420:
3421: #----------------------------------------------------------------------------
3422: #
3423: #-------------------------- Next few routines handles grading by csv upload
3424: #
3425: #--- Javascript to handle csv upload
3426: sub csvupload_javascript_reverse_associate {
3427: my $error1=&mt('You need to specify the username or ID');
3428: my $error2=&mt('You need to specify at least one grading field');
3429: return(<<ENDPICK);
3430: function verify(vf) {
3431: var foundsomething=0;
3432: var founduname=0;
3433: var foundID=0;
3434: for (i=0;i<=vf.nfields.value;i++) {
3435: tw=eval('vf.f'+i+'.selectedIndex');
3436: if (i==0 && tw!=0) { foundID=1; }
3437: if (i==1 && tw!=0) { founduname=1; }
3438: if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
3439: }
3440: if (founduname==0 && foundID==0) {
3441: alert('$error1');
3442: return;
3443: }
3444: if (foundsomething==0) {
3445: alert('$error2');
3446: return;
3447: }
3448: vf.submit();
3449: }
3450: function flip(vf,tf) {
3451: var nw=eval('vf.f'+tf+'.selectedIndex');
3452: var i;
3453: for (i=0;i<=vf.nfields.value;i++) {
3454: //can not pick the same destination field for both name and domain
3455: if (((i ==0)||(i ==1)) &&
3456: ((tf==0)||(tf==1)) &&
3457: (i!=tf) &&
3458: (eval('vf.f'+i+'.selectedIndex')==nw)) {
3459: eval('vf.f'+i+'.selectedIndex=0;')
3460: }
3461: }
3462: }
3463: ENDPICK
3464: }
3465:
3466: sub csvupload_javascript_forward_associate {
3467: my $error1=&mt('You need to specify the username or ID');
3468: my $error2=&mt('You need to specify at least one grading field');
3469: return(<<ENDPICK);
3470: function verify(vf) {
3471: var foundsomething=0;
3472: var founduname=0;
3473: var foundID=0;
3474: for (i=0;i<=vf.nfields.value;i++) {
3475: tw=eval('vf.f'+i+'.selectedIndex');
3476: if (tw==1) { foundID=1; }
3477: if (tw==2) { founduname=1; }
3478: if (tw>3) { foundsomething=1; }
3479: }
3480: if (founduname==0 && foundID==0) {
3481: alert('$error1');
3482: return;
3483: }
3484: if (foundsomething==0) {
3485: alert('$error2');
3486: return;
3487: }
3488: vf.submit();
3489: }
3490: function flip(vf,tf) {
3491: var nw=eval('vf.f'+tf+'.selectedIndex');
3492: var i;
3493: //can not pick the same destination field twice
3494: for (i=0;i<=vf.nfields.value;i++) {
3495: if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
3496: eval('vf.f'+i+'.selectedIndex=0;')
3497: }
3498: }
3499: }
3500: ENDPICK
3501: }
3502:
3503: sub csvuploadmap_header {
3504: my ($request,$symb,$datatoken,$distotal)= @_;
3505: my $javascript;
3506: if ($env{'form.upfile_associate'} eq 'reverse') {
3507: $javascript=&csvupload_javascript_reverse_associate();
3508: } else {
3509: $javascript=&csvupload_javascript_forward_associate();
3510: }
3511:
3512: my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
3513: my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
3514: my $ignore=&mt('Ignore First Line');
3515: $symb = &Apache::lonenc::check_encrypt($symb);
3516: $request->print(<<ENDPICK);
3517: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3518: <h3><span class="LC_info">Uploading Class Grades</span></h3>
3519: $result
3520: <hr />
3521: <h3>Identify fields</h3>
3522: Total number of records found in file: $distotal <hr />
3523: Enter as many fields as you can. The system will inform you and bring you back
3524: to this page if the data selected is insufficient to run your class.<hr />
3525: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
3526: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
3527: <input type="hidden" name="associate" value="" />
3528: <input type="hidden" name="phase" value="three" />
3529: <input type="hidden" name="datatoken" value="$datatoken" />
3530: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
3531: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
3532: <input type="hidden" name="upfile_associate"
3533: value="$env{'form.upfile_associate'}" />
3534: <input type="hidden" name="symb" value="$symb" />
3535: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
3536: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
3537: <input type="hidden" name="command" value="csvuploadoptions" />
3538: <hr />
3539: <script type="text/javascript" language="Javascript">
3540: $javascript
3541: </script>
3542: ENDPICK
3543: return '';
3544:
3545: }
3546:
3547: sub csvupload_fields {
3548: my ($symb) = @_;
3549: my (@parts) = &getpartlist($symb);
3550: my @fields=(['ID','Student ID'],
3551: ['username','Student Username'],
3552: ['domain','Student Domain']);
3553: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3554: foreach my $part (sort(@parts)) {
3555: my @datum;
3556: my $display=&Apache::lonnet::metadata($url,$part.'.display');
3557: my $name=$part;
3558: if (!$display) { $display = $name; }
3559: @datum=($name,$display);
3560: if ($name=~/^stores_(.*)_awarded/) {
3561: push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
3562: }
3563: push(@fields,\@datum);
3564: }
3565: return (@fields);
3566: }
3567:
3568: sub csvuploadmap_footer {
3569: my ($request,$i,$keyfields) =@_;
3570: $request->print(<<ENDPICK);
3571: </table>
3572: <input type="hidden" name="nfields" value="$i" />
3573: <input type="hidden" name="keyfields" value="$keyfields" />
3574: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
3575: </form>
3576: ENDPICK
3577: }
3578:
3579: sub checkforfile_js {
3580: my $result =<<CSVFORMJS;
3581: <script type="text/javascript" language="javascript">
3582: function checkUpload(formname) {
3583: if (formname.upfile.value == "") {
3584: alert("Please use the browse button to select a file from your local directory.");
3585: return false;
3586: }
3587: formname.submit();
3588: }
3589: </script>
3590: CSVFORMJS
3591: return $result;
3592: }
3593:
3594: sub upcsvScores_form {
3595: my ($request) = shift;
3596: my ($symb)=&get_symb($request);
3597: if (!$symb) {return '';}
3598: my $result=&checkforfile_js();
3599: $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
3600: my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
3601: $result.=$table;
3602: $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
3603: $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
3604: $result.=' <b>'.&mt('Specify a file containing the class scores for current resource').
3605: '.</b></td></tr>'."\n";
3606: $result.='<tr bgcolor=#ffffe6><td>'."\n";
3607: my $upload=&mt("Upload Scores");
3608: my $upfile_select=&Apache::loncommon::upfile_select_html();
3609: my $ignore=&mt('Ignore First Line');
3610: $symb = &Apache::lonenc::check_encrypt($symb);
3611: $result.=<<ENDUPFORM;
3612: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3613: <input type="hidden" name="symb" value="$symb" />
3614: <input type="hidden" name="command" value="csvuploadmap" />
3615: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
3616: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
3617: $upfile_select
3618: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
3619: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
3620: </form>
3621: ENDUPFORM
3622: $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
3623: &mt("How do I create a CSV file from a spreadsheet"))
3624: .'</td></tr></table>'."\n";
3625: $result.='</td></tr></table><br /><br />'."\n";
3626: $result.=&show_grading_menu_form($symb);
3627: return $result;
3628: }
3629:
3630:
3631: sub csvuploadmap {
3632: my ($request)= @_;
3633: my ($symb)=&get_symb($request);
3634: if (!$symb) {return '';}
3635:
3636: my $datatoken;
3637: if (!$env{'form.datatoken'}) {
3638: $datatoken=&Apache::loncommon::upfile_store($request);
3639: } else {
3640: $datatoken=$env{'form.datatoken'};
3641: &Apache::loncommon::load_tmp_file($request);
3642: }
3643: my @records=&Apache::loncommon::upfile_record_sep();
3644: if ($env{'form.noFirstLine'}) { shift(@records); }
3645: &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
3646: my ($i,$keyfields);
3647: if (@records) {
3648: my @fields=&csvupload_fields($symb);
3649:
3650: if ($env{'form.upfile_associate'} eq 'reverse') {
3651: &Apache::loncommon::csv_print_samples($request,\@records);
3652: $i=&Apache::loncommon::csv_print_select_table($request,\@records,
3653: \@fields);
3654: foreach (@fields) { $keyfields.=$_->[0].','; }
3655: chop($keyfields);
3656: } else {
3657: unshift(@fields,['none','']);
3658: $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
3659: \@fields);
3660: foreach my $rec (@records) {
3661: my %temp = &Apache::loncommon::record_sep($rec);
3662: if (%temp) {
3663: $keyfields=join(',',sort(keys(%temp)));
3664: last;
3665: }
3666: }
3667: }
3668: }
3669: &csvuploadmap_footer($request,$i,$keyfields);
3670: $request->print(&show_grading_menu_form($symb));
3671:
3672: return '';
3673: }
3674:
3675: sub csvuploadoptions {
3676: my ($request)= @_;
3677: my ($symb)=&get_symb($request);
3678: my $checked=(($env{'form.noFirstLine'})?'1':'0');
3679: my $ignore=&mt('Ignore First Line');
3680: $request->print(<<ENDPICK);
3681: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3682: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
3683: <input type="hidden" name="command" value="csvuploadassign" />
3684: <!--
3685: <p>
3686: <label>
3687: <input type="checkbox" name="show_full_results" />
3688: Show a table of all changes
3689: </label>
3690: </p>
3691: -->
3692: <p>
3693: <label>
3694: <input type="checkbox" name="overwite_scores" checked="checked" />
3695: Overwrite any existing score
3696: </label>
3697: </p>
3698: ENDPICK
3699: my %fields=&get_fields();
3700: if (!defined($fields{'domain'})) {
3701: my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
3702: $request->print("\n<p> Users are in domain: ".$domform."</p>\n");
3703: }
3704: foreach my $key (sort(keys(%env))) {
3705: if ($key !~ /^form\.(.*)$/) { next; }
3706: my $cleankey=$1;
3707: if ($cleankey eq 'command') { next; }
3708: $request->print('<input type="hidden" name="'.$cleankey.
3709: '" value="'.$env{$key}.'" />'."\n");
3710: }
3711: # FIXME do a check for any duplicated user ids...
3712: # FIXME do a check for any invalid user ids?...
3713: $request->print('<input type="submit" value="Assign Grades" /><br />
3714: <hr /></form>'."\n");
3715: $request->print(&show_grading_menu_form($symb));
3716: return '';
3717: }
3718:
3719: sub get_fields {
3720: my %fields;
3721: my @keyfields = split(/\,/,$env{'form.keyfields'});
3722: for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
3723: if ($env{'form.upfile_associate'} eq 'reverse') {
3724: if ($env{'form.f'.$i} ne 'none') {
3725: $fields{$keyfields[$i]}=$env{'form.f'.$i};
3726: }
3727: } else {
3728: if ($env{'form.f'.$i} ne 'none') {
3729: $fields{$env{'form.f'.$i}}=$keyfields[$i];
3730: }
3731: }
3732: }
3733: return %fields;
3734: }
3735:
3736: sub csvuploadassign {
3737: my ($request)= @_;
3738: my ($symb)=&get_symb($request);
3739: if (!$symb) {return '';}
3740: my $error_msg = '';
3741: &Apache::loncommon::load_tmp_file($request);
3742: my @gradedata = &Apache::loncommon::upfile_record_sep();
3743: if ($env{'form.noFirstLine'}) { shift(@gradedata); }
3744: my %fields=&get_fields();
3745: $request->print('<h3>Assigning Grades</h3>');
3746: my $courseid=$env{'request.course.id'};
3747: my ($classlist) = &getclasslist('all',0);
3748: my @notallowed;
3749: my @skipped;
3750: my $countdone=0;
3751: foreach my $grade (@gradedata) {
3752: my %entries=&Apache::loncommon::record_sep($grade);
3753: my $domain;
3754: if ($entries{$fields{'domain'}}) {
3755: $domain=$entries{$fields{'domain'}};
3756: } else {
3757: $domain=$env{'form.default_domain'};
3758: }
3759: $domain=~s/\s//g;
3760: my $username=$entries{$fields{'username'}};
3761: $username=~s/\s//g;
3762: if (!$username) {
3763: my $id=$entries{$fields{'ID'}};
3764: $id=~s/\s//g;
3765: my %ids=&Apache::lonnet::idget($domain,$id);
3766: $username=$ids{$id};
3767: }
3768: if (!exists($$classlist{"$username:$domain"})) {
3769: my $id=$entries{$fields{'ID'}};
3770: $id=~s/\s//g;
3771: if ($id) {
3772: push(@skipped,"$id:$domain");
3773: } else {
3774: push(@skipped,"$username:$domain");
3775: }
3776: next;
3777: }
3778: my $usec=$classlist->{"$username:$domain"}[5];
3779: if (!&canmodify($usec)) {
3780: push(@notallowed,"$username:$domain");
3781: next;
3782: }
3783: my %points;
3784: my %grades;
3785: foreach my $dest (keys(%fields)) {
3786: if ($dest eq 'ID' || $dest eq 'username' ||
3787: $dest eq 'domain') { next; }
3788: if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
3789: if ($dest=~/stores_(.*)_points/) {
3790: my $part=$1;
3791: my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
3792: $symb,$domain,$username);
3793: if ($wgt) {
3794: $entries{$fields{$dest}}=~s/\s//g;
3795: my $pcr=$entries{$fields{$dest}} / $wgt;
3796: my $award='correct_by_override';
3797: $grades{"resource.$part.awarded"}=$pcr;
3798: $grades{"resource.$part.solved"}=$award;
3799: $points{$part}=1;
3800: } else {
3801: $error_msg = "<br />" .
3802: &mt("Some point values were assigned"
3803: ." for problems with a weight "
3804: ."of zero. These values were "
3805: ."ignored.");
3806: }
3807: } else {
3808: if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
3809: if ($dest=~/stores_(.*)_solved/) { if ($points{$1}) {next;} }
3810: my $store_key=$dest;
3811: $store_key=~s/^stores/resource/;
3812: $store_key=~s/_/\./g;
3813: $grades{$store_key}=$entries{$fields{$dest}};
3814: }
3815: }
3816: if (! %grades) { push(@skipped,"$username:$domain no data to save"); }
3817: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
3818: # &Apache::lonnet::logthis(" storing ".(join('-',%grades)));
3819: my $result=&Apache::lonnet::cstore(\%grades,$symb,
3820: $env{'request.course.id'},
3821: $domain,$username);
3822: if ($result eq 'ok') {
3823: $request->print('.');
3824: } else {
3825: $request->print("<p>
3826: <span class=\"LC_error\">
3827: Failed to save student $username:$domain.
3828: Message when trying to save was ($result)
3829: </span>
3830: </p>" );
3831: }
3832: $request->rflush();
3833: $countdone++;
3834: }
3835: $request->print("<br />Saved $countdone students\n");
3836: if (@skipped) {
3837: $request->print('<p><h4><b>Skipped Students</b></h4></p>');
3838: foreach my $student (@skipped) { $request->print("$student<br />\n"); }
3839: }
3840: if (@notallowed) {
3841: $request->print('<p><span class="LC_error">Students Not Allowed to Modify</span></p>');
3842: foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
3843: }
3844: $request->print("<br />\n");
3845: $request->print(&show_grading_menu_form($symb));
3846: return $error_msg;
3847: }
3848: #------------- end of section for handling csv file upload ---------
3849: #
3850: #-------------------------------------------------------------------
3851: #
3852: #-------------- Next few routines handle grading by page/sequence
3853: #
3854: #--- Select a page/sequence and a student to grade
3855: sub pickStudentPage {
3856: my ($request) = shift;
3857:
3858: $request->print(<<LISTJAVASCRIPT);
3859: <script type="text/javascript" language="javascript">
3860:
3861: function checkPickOne(formname) {
3862: if (radioSelection(formname.student) == null) {
3863: alert("Please select the student you wish to grade.");
3864: return;
3865: }
3866: ptr = pullDownSelection(formname.selectpage);
3867: formname.page.value = formname["page"+ptr].value;
3868: formname.title.value = formname["title"+ptr].value;
3869: formname.submit();
3870: }
3871:
3872: </script>
3873: LISTJAVASCRIPT
3874: &commonJSfunctions($request);
3875: my ($symb) = &get_symb($request);
3876: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
3877: my $cnum = $env{"course.$env{'request.course.id'}.num"};
3878: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
3879:
3880: my $result='<h3><span class="LC_info"> '.
3881: 'Manual Grading by Page or Sequence</span></h3>';
3882:
3883: $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
3884: $result.=' <b>Problems from:</b> <select name="selectpage">'."\n";
3885: my ($titles,$symbx) = &getSymbMap();
3886: my ($curpage) =&Apache::lonnet::decode_symb($symb);
3887: # my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb);
3888: # my $type=($curpage =~ /\.(page|sequence)/);
3889: my $ctr=0;
3890: foreach (@$titles) {
3891: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
3892: $result.='<option value="'.$ctr.'" '.
3893: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
3894: '>'.$showtitle.'</option>'."\n";
3895: $ctr++;
3896: }
3897: $result.= '</select>'."<br />\n";
3898: $ctr=0;
3899: foreach (@$titles) {
3900: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
3901: $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
3902: $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
3903: $ctr++;
3904: }
3905: $result.='<input type="hidden" name="page" />'."\n".
3906: '<input type="hidden" name="title" />'."\n";
3907:
3908: $result.=' <b>View Problems Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
3909: '<label><input type="radio" name="vProb" value="yes" /> yes </label>'."<br />\n";
3910:
3911: $result.=' <b>Submission Details: </b>'.
3912: '<label><input type="radio" name="lastSub" value="none" /> none</label>'."\n".
3913: '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> by dates and submissions</label>'."\n".
3914: '<label><input type="radio" name="lastSub" value="all" /> all details</label>'."\n";
3915:
3916: $result.=&build_section_inputs();
3917: $result.='<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n".
3918: '<input type="hidden" name="command" value="displayPage" />'."\n".
3919: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
3920: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
3921:
3922: $result.=' <b>'.&mt('Use CODE:').' </b>'.
3923: '<input type="text" name="CODE" value="" /><br />'."\n";
3924:
3925: $result.=' <input type="button" '.
3926: 'onClick="javascript:checkPickOne(this.form);"value="Next->" /><br />'."\n";
3927:
3928: $request->print($result);
3929:
3930: my $studentTable.=' <b>Select a student you wish to grade and then click on the Next button.</b><br />'.
3931: '<table border="0"><tr><td bgcolor="#777777">'.
3932: '<table border="0"><tr bgcolor="#e6ffff">'.
3933: '<td align="right"> <b>No.</b></td>'.
3934: '<td>'.&nameUserString('header').'</td>'.
3935: '<td align="right"> <b>No.</b></td>'.
3936: '<td>'.&nameUserString('header').'</td></tr>';
3937:
3938: my (undef,undef,$fullname) = &getclasslist($getsec,'1');
3939: my $ptr = 1;
3940: foreach my $student (sort
3941: {
3942: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
3943: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
3944: }
3945: return $a cmp $b;
3946: } (keys(%$fullname))) {
3947: my ($uname,$udom) = split(/:/,$student);
3948: $studentTable.=($ptr%2 == 1 ? '<tr bgcolor="#ffffe6">' : '</td>');
3949: $studentTable.='<td align="right">'.$ptr.' </td>';
3950: $studentTable.='<td> <label><input type="radio" name="student" value="'.$student.'" /> '
3951: .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
3952: $studentTable.=($ptr%2 == 0 ? '</td></tr>' : '');
3953: $ptr++;
3954: }
3955: $studentTable.='</td><td> </td><td> </td></tr>' if ($ptr%2 == 0);
3956: $studentTable.='</table></td></tr></table>'."\n";
3957: $studentTable.='<input type="button" '.
3958: 'onClick="javascript:checkPickOne(this.form);"value="Next->" /></form>'."\n";
3959:
3960: $studentTable.=&show_grading_menu_form($symb);
3961: $request->print($studentTable);
3962:
3963: return '';
3964: }
3965:
3966: sub getSymbMap {
3967: my $navmap = Apache::lonnavmaps::navmap->new();
3968:
3969: my %symbx = ();
3970: my @titles = ();
3971: my $minder = 0;
3972:
3973: # Gather every sequence that has problems.
3974: my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
3975: 1,0,1);
3976: for my $sequence ($navmap->getById('0.0'), @sequences) {
3977: if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
3978: my $title = $minder.'.'.
3979: &HTML::Entities::encode($sequence->compTitle(),'"\'&');
3980: push(@titles, $title); # minder in case two titles are identical
3981: $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
3982: $minder++;
3983: }
3984: }
3985: return \@titles,\%symbx;
3986: }
3987:
3988: #
3989: #--- Displays a page/sequence w/wo problems, w/wo submissions
3990: sub displayPage {
3991: my ($request) = shift;
3992:
3993: my ($symb) = &get_symb($request);
3994: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
3995: my $cnum = $env{"course.$env{'request.course.id'}.num"};
3996: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
3997: my $pageTitle = $env{'form.page'};
3998: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
3999: my ($uname,$udom) = split(/:/,$env{'form.student'});
4000: my $usec=$classlist->{$env{'form.student'}}[5];
4001:
4002: #need to make sure we have the correct data for later EXT calls,
4003: #thus invalidate the cache
4004: &Apache::lonnet::devalidatecourseresdata(
4005: $env{'course.'.$env{'request.course.id'}.'.num'},
4006: $env{'course.'.$env{'request.course.id'}.'.domain'});
4007: &Apache::lonnet::clear_EXT_cache_status();
4008:
4009: if (!&canview($usec)) {
4010: $request->print('<span class="LC_warning">Unable to view requested student.('.$env{'form.student'}.')</span>');
4011: $request->print(&show_grading_menu_form($symb));
4012: return;
4013: }
4014: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
4015: $result.='<h3> Student: '.&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom).
4016: '</h3>'."\n";
4017: if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
4018: $result.='<h3> CODE: '.$env{'form.CODE'}.'</h3>'."\n";
4019: } else {
4020: delete($env{'form.CODE'});
4021: }
4022: &sub_page_js($request);
4023: $request->print($result);
4024:
4025: my $navmap = Apache::lonnavmaps::navmap->new();
4026: my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
4027: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
4028: if (!$map) {
4029: $request->print('<span class="LC_warning">Unable to view requested sequence. ('.$resUrl.')</span>');
4030: $request->print(&show_grading_menu_form($symb));
4031: return;
4032: }
4033: my $iterator = $navmap->getIterator($map->map_start(),
4034: $map->map_finish());
4035:
4036: my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
4037: '<input type="hidden" name="command" value="gradeByPage" />'."\n".
4038: '<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
4039: '<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
4040: '<input type="hidden" name="page" value="'.$pageTitle.'" />'."\n".
4041: '<input type="hidden" name="title" value="'.$env{'form.title'}.'" />'."\n".
4042: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
4043: '<input type="hidden" name="overRideScore" value="no" />'."\n".
4044: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
4045:
4046: if (defined($env{'form.CODE'})) {
4047: $studentTable.=
4048: '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
4049: }
4050: my $checkIcon = '<img alt="'.&mt('Check Mark').
4051: '" src="'.$request->dir_config('lonIconsURL').
4052: '/check.gif" height="16" border="0" />';
4053:
4054: $studentTable.=' <b>Note:</b> Problems graded correct by the computer are marked with a '.$checkIcon.
4055: ' symbol.'."\n".
4056: '<table border="0"><tr><td bgcolor="#777777">'.
4057: '<table border="0"><tr bgcolor="#e6ffff">'.
4058: '<td align="center"><b> Prob. </b></td>'.
4059: '<td><b> '.($env{'form.vProb'} eq 'no' ? 'Title' : 'Problem Text').'/Grade</b></td></tr>';
4060:
4061: &Apache::lonxml::clear_problem_counter();
4062: my ($depth,$question,$prob) = (1,1,1);
4063: $iterator->next(); # skip the first BEGIN_MAP
4064: my $curRes = $iterator->next(); # for "current resource"
4065: while ($depth > 0) {
4066: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
4067: if($curRes == $iterator->END_MAP) { $depth--; }
4068:
4069: if (ref($curRes) && $curRes->is_problem()) {
4070: my $parts = $curRes->parts();
4071: my $title = $curRes->compTitle();
4072: my $symbx = $curRes->symb();
4073: $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
4074: (scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).' parts)').'</td>';
4075: $studentTable.='<td valign="top">';
4076: my %form = ('CODE' => $env{'form.CODE'},);
4077: if ($env{'form.vProb'} eq 'yes' ) {
4078: $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
4079: undef,'both',\%form);
4080: } else {
4081: my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
4082: $companswer =~ s|<form(.*?)>||g;
4083: $companswer =~ s|</form>||g;
4084: # while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
4085: # $companswer =~ s/$1/ /ms;
4086: # $request->print('match='.$1."<br />\n");
4087: # }
4088: # $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
4089: $studentTable.=' <b>'.$title.'</b> <br /> <b>Correct answer:</b><br />'.$companswer;
4090: }
4091:
4092: my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
4093:
4094: if ($env{'form.lastSub'} eq 'datesub') {
4095: if ($record{'version'} eq '') {
4096: $studentTable.='<br /> <span class="LC_warning">No recorded submission for this problem</span><br />';
4097: } else {
4098: my %responseType = ();
4099: foreach my $partid (@{$parts}) {
4100: my @responseIds =$curRes->responseIds($partid);
4101: my @responseType =$curRes->responseType($partid);
4102: my %responseIds;
4103: for (my $i=0;$i<=$#responseIds;$i++) {
4104: $responseIds{$responseIds[$i]}=$responseType[$i];
4105: }
4106: $responseType{$partid} = \%responseIds;
4107: }
4108: $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
4109:
4110: }
4111: } elsif ($env{'form.lastSub'} eq 'all') {
4112: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
4113: $studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
4114: $env{'request.course.id'},
4115: '','.submission');
4116:
4117: }
4118: if (&canmodify($usec)) {
4119: foreach my $partid (@{$parts}) {
4120: $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
4121: $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
4122: $question++;
4123: }
4124: $prob++;
4125: }
4126: $studentTable.='</td></tr>';
4127:
4128: }
4129: $curRes = $iterator->next();
4130: }
4131:
4132: $studentTable.='</table></td></tr></table>'."\n".
4133: '<input type="button" value="Save" '.
4134: 'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
4135: '</form>'."\n";
4136: $studentTable.=&show_grading_menu_form($symb);
4137: $request->print($studentTable);
4138:
4139: return '';
4140: }
4141:
4142: sub displaySubByDates {
4143: my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
4144: my $isCODE=0;
4145: my $isTask = ($symb =~/\.task$/);
4146: if (exists($record->{'resource.CODE'})) { $isCODE=1; }
4147: my $studentTable='<table border="0" width="100%"><tr><td bgcolor="#777777">'.
4148: '<table border="0" width="100%"><tr bgcolor="#e6ffff">'.
4149: '<td><b>Date/Time</b></td>'.
4150: ($isCODE?'<td><b>CODE</b></td>':'').
4151: '<td><b>Submission</b></td>'.
4152: '<td><b>Status </b></td></tr>';
4153: my ($version);
4154: my %mark;
4155: my %orders;
4156: $mark{'correct_by_student'} = $checkIcon;
4157: if (!exists($$record{'1:timestamp'})) {
4158: return '<br /> <span class="LC_warning">Nothing submitted - no attempts</span><br />';
4159: }
4160:
4161: my $interaction;
4162: for ($version=1;$version<=$$record{'version'};$version++) {
4163: my $timestamp = scalar(localtime($$record{$version.':timestamp'}));
4164: if (exists($$record{$version.':resource.0.version'})) {
4165: $interaction = $$record{$version.':resource.0.version'};
4166: }
4167:
4168: my $where = ($isTask ? "$version:resource.$interaction"
4169: : "$version:resource");
4170: #&Apache::lonnet::logthis(" got $where");
4171: $studentTable.='<tr bgcolor="#ffffff" valign="top"><td>'.$timestamp.'</td>';
4172: if ($isCODE) {
4173: $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
4174: }
4175: my @versionKeys = split(/\:/,$$record{$version.':keys'});
4176: my @displaySub = ();
4177: foreach my $partid (@{$parts}) {
4178: my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
4179: : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
4180:
4181:
4182: # next if ($$record{"$version:resource.$partid.solved"} eq '');
4183: my $display_part=&get_display_part($partid,$symb);
4184: foreach my $matchKey (@matchKey) {
4185: if (exists($$record{$version.':'.$matchKey}) &&
4186: $$record{$version.':'.$matchKey} ne '') {
4187:
4188: my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
4189: : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
4190: #&Apache::lonnet::logthis("match $matchKey $responseId (".$$record{$version.':'.$matchKey});
4191: $displaySub[0].='<b>Part:</b> '.$display_part.' ';
4192: $displaySub[0].='<span class="LC_internal_info">(ID '.
4193: $responseId.')</span> <b>';
4194: if ($$record{"$where.$partid.tries"} eq '') {
4195: $displaySub[0].='Trial not counted';
4196: } else {
4197: $displaySub[0].='Trial '.
4198: $$record{"$where.$partid.tries"};
4199: }
4200: my $responseType=($isTask ? 'Task'
4201: : $responseType->{$partid}->{$responseId});
4202: if (!exists($orders{$partid})) { $orders{$partid}={}; }
4203: if (!exists($orders{$partid}->{$responseId})) {
4204: $orders{$partid}->{$responseId}=
4205: &get_order($partid,$responseId,$symb,$uname,$udom);
4206: }
4207: $displaySub[0].='</b> '.
4208: &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
4209: }
4210: }
4211: if (exists($$record{"$where.$partid.checkedin"})) {
4212: $displaySub[1].='Checked in by '.
4213: $$record{"$where.$partid.checkedin"}.' into slot '.
4214: $$record{"$where.$partid.checkedin.slot"}.
4215: '<br />';
4216: }
4217: if (exists $$record{"$where.$partid.award"}) {
4218: $displaySub[1].='<b>Part:</b> '.$display_part.' '.
4219: lc($$record{"$where.$partid.award"}).' '.
4220: $mark{$$record{"$where.$partid.solved"}}.
4221: '<br />';
4222: }
4223: if (exists $$record{"$where.$partid.regrader"}) {
4224: $displaySub[2].=$$record{"$where.$partid.regrader"}.
4225: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
4226: } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
4227: $displaySub[2].=
4228: $$record{"$version:resource.$partid.regrader"}.
4229: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
4230: }
4231: }
4232: # needed because old essay regrader has not parts info
4233: if (exists $$record{"$version:resource.regrader"}) {
4234: $displaySub[2].=$$record{"$version:resource.regrader"};
4235: }
4236: $studentTable.='<td>'.$displaySub[0].' </td><td>'.$displaySub[1];
4237: if ($displaySub[2]) {
4238: $studentTable.='Manually graded by '.$displaySub[2];
4239: }
4240: $studentTable.=' </td></tr>';
4241:
4242: }
4243: $studentTable.='</table></td></tr></table>';
4244: return $studentTable;
4245: }
4246:
4247: sub updateGradeByPage {
4248: my ($request) = shift;
4249:
4250: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4251: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4252: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4253: my $pageTitle = $env{'form.page'};
4254: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
4255: my ($uname,$udom) = split(/:/,$env{'form.student'});
4256: my $usec=$classlist->{$env{'form.student'}}[5];
4257: if (!&canmodify($usec)) {
4258: $request->print('<span class="LC_warning">Unable to modify requested student.('.$env{'form.student'}.'</span>');
4259: $request->print(&show_grading_menu_form($env{'form.symb'}));
4260: return;
4261: }
4262: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
4263: $result.='<h3> Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
4264: '</h3>'."\n";
4265:
4266: $request->print($result);
4267:
4268: my $navmap = Apache::lonnavmaps::navmap->new();
4269: my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
4270: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
4271: if (!$map) {
4272: $request->print('<span class="LC_warning">Unable to grade requested sequence. ('.$resUrl.')</span>');
4273: my ($symb)=&get_symb($request);
4274: $request->print(&show_grading_menu_form($symb));
4275: return;
4276: }
4277: my $iterator = $navmap->getIterator($map->map_start(),
4278: $map->map_finish());
4279:
4280: my $studentTable='<table border="0"><tr><td bgcolor="#777777">'.
4281: '<table border="0"><tr bgcolor="#e6ffff">'.
4282: '<td align="center"><b> Prob. </b></td>'.
4283: '<td><b> Title </b></td>'.
4284: '<td><b> Previous Score </b></td>'.
4285: '<td><b> New Score </b></td></tr>';
4286:
4287: $iterator->next(); # skip the first BEGIN_MAP
4288: my $curRes = $iterator->next(); # for "current resource"
4289: my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
4290: while ($depth > 0) {
4291: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
4292: if($curRes == $iterator->END_MAP) { $depth--; }
4293:
4294: if (ref($curRes) && $curRes->is_problem()) {
4295: my $parts = $curRes->parts();
4296: my $title = $curRes->compTitle();
4297: my $symbx = $curRes->symb();
4298: $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
4299: (scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).' parts)').'</td>';
4300: $studentTable.='<td valign="top"> <b>'.$title.'</b> </td>';
4301:
4302: my %newrecord=();
4303: my @displayPts=();
4304: my %aggregate = ();
4305: my $aggregateflag = 0;
4306: foreach my $partid (@{$parts}) {
4307: my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
4308: my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
4309:
4310: my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ?
4311: $env{'form.WGT'.$question.'_'.$partid} : 1;
4312: my $partial = $newpts/$wgt;
4313: my $score;
4314: if ($partial > 0) {
4315: $score = 'correct_by_override';
4316: } elsif ($newpts ne '') { #empty is taken as 0
4317: $score = 'incorrect_by_override';
4318: }
4319: my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
4320: if ($dropMenu eq 'excused') {
4321: $partial = '';
4322: $score = 'excused';
4323: } elsif ($dropMenu eq 'reset status'
4324: && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
4325: $newrecord{'resource.'.$partid.'.tries'} = 0;
4326: $newrecord{'resource.'.$partid.'.solved'} = '';
4327: $newrecord{'resource.'.$partid.'.award'} = '';
4328: $newrecord{'resource.'.$partid.'.awarded'} = 0;
4329: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
4330: $changeflag++;
4331: $newpts = '';
4332:
4333: my $aggtries = $env{'form.aggtries'.$question.'_'.$partid};
4334: my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
4335: my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
4336: if ($aggtries > 0) {
4337: &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
4338: $aggregateflag = 1;
4339: }
4340: }
4341: my $display_part=&get_display_part($partid,$curRes->symb());
4342: my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
4343: $displayPts[0].=' <b>Part:</b> '.$display_part.' = '.
4344: (($oldstatus eq 'excused') ? 'excused' : $oldpts).
4345: ' <br />';
4346: $displayPts[1].=' <b>Part:</b> '.$display_part.' = '.
4347: (($score eq 'excused') ? 'excused' : $newpts).
4348: ' <br />';
4349: $question++;
4350: next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
4351:
4352: $newrecord{'resource.'.$partid.'.awarded'} = $partial if $partial ne '';
4353: $newrecord{'resource.'.$partid.'.solved'} = $score if $score ne '';
4354: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
4355: if (scalar(keys(%newrecord)) > 0);
4356:
4357: $changeflag++;
4358: }
4359: if (scalar(keys(%newrecord)) > 0) {
4360: my %record =
4361: &Apache::lonnet::restore($symbx,$env{'request.course.id'},
4362: $udom,$uname);
4363:
4364: if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
4365: $newrecord{'resource.CODE'} = $env{'form.CODE'};
4366: } elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
4367: $newrecord{'resource.CODE'} = '';
4368: }
4369: &Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
4370: $udom,$uname);
4371: %record = &Apache::lonnet::restore($symbx,
4372: $env{'request.course.id'},
4373: $udom,$uname);
4374: &check_and_remove_from_queue($parts,\%record,undef,$symbx,
4375: $cdom,$cnum,$udom,$uname);
4376: }
4377:
4378: if ($aggregateflag) {
4379: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
4380: $env{'course.'.$env{'request.course.id'}.'.domain'},
4381: $env{'course.'.$env{'request.course.id'}.'.num'});
4382: }
4383:
4384: $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
4385: '<td valign="top">'.$displayPts[1].'</td>'.
4386: '</tr>';
4387:
4388: $prob++;
4389: }
4390: $curRes = $iterator->next();
4391: }
4392:
4393: $studentTable.='</td></tr></table></td></tr></table>';
4394: $studentTable.=&show_grading_menu_form($env{'form.symb'});
4395: my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
4396: 'The scores were changed for '.
4397: $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
4398: $request->print($grademsg.$studentTable);
4399:
4400: return '';
4401: }
4402:
4403: #-------- end of section for handling grading by page/sequence ---------
4404: #
4405: #-------------------------------------------------------------------
4406:
4407: #--------------------Scantron Grading-----------------------------------
4408: #
4409: #------ start of section for handling grading by page/sequence ---------
4410:
4411: =pod
4412:
4413: =head1 Bubble sheet grading routines
4414:
4415: For this documentation:
4416:
4417: 'scanline' refers to the full line of characters
4418: from the file that we are parsing that represents one entire sheet
4419:
4420: 'bubble line' refers to the data
4421: representing the line of bubbles that are on the physical bubble sheet
4422:
4423:
4424: The overall process is that a scanned in bubble sheet data is uploaded
4425: into a course. When a user wants to grade, they select a
4426: sequence/folder of resources, a file of bubble sheet info, and pick
4427: one of the predefined configurations for what each scanline looks
4428: like.
4429:
4430: Next each scanline is checked for any errors of either 'missing
4431: bubbles' (it's an error because it may have been missed scanned
4432: because too light bubbling), 'double bubble' (each bubble line should
4433: have no more that one letter picked), invalid or duplicated CODE,
4434: invalid student ID
4435:
4436: If the CODE option is used that determines the randomization of the
4437: homework problems, either way the student ID is looked up into a
4438: username:domain.
4439:
4440: During the validation phase the instructor can choose to skip scanlines.
4441:
4442: After the validation phase, there is now 3 bubble sheet files
4443:
4444: scantron_original_filename (unmodified original file)
4445: scantron_corrected_filename (file where the corrected information has replaced the original information)
4446: scantron_skipped_filename (contains the exact text of scanlines that where skipped)
4447:
4448: Also there is a separate hash nohist_scantrondata that contains extra
4449: correction information that isn't representable in the bubble sheet
4450: file (see &scantron_getfile() for more information)
4451:
4452: After all scanlines are either valid, marked as valid or skipped, then
4453: foreach line foreach problem in the picked sequence, an ssi request is
4454: made that simulates a user submitting their selected letter(s) against
4455: the homework problem.
4456:
4457: =over 4
4458:
4459: =cut
4460:
4461:
4462: =pod
4463:
4464: =item defaultFormData
4465:
4466: Returns html hidden inputs used to hold context/default values.
4467:
4468: Arguments:
4469: $symb - $symb of the current resource
4470:
4471: =cut
4472:
4473: sub defaultFormData {
4474: my ($symb)=@_;
4475: return '
4476: <input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
4477: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
4478: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
4479: }
4480:
4481: =pod
4482:
4483: =item getSequenceDropDown
4484:
4485: Return html dropdown of possible sequences to grade
4486:
4487: Arguments:
4488: $symb - $symb of the current resource
4489:
4490: =cut
4491:
4492: sub getSequenceDropDown {
4493: my ($symb)=@_;
4494: my $result='<select name="selectpage">'."\n";
4495: my ($titles,$symbx) = &getSymbMap();
4496: my ($curpage)=&Apache::lonnet::decode_symb($symb);
4497: my $ctr=0;
4498: foreach (@$titles) {
4499: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4500: $result.='<option value="'.$$symbx{$_}.'" '.
4501: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
4502: '>'.$showtitle.'</option>'."\n";
4503: $ctr++;
4504: }
4505: $result.= '</select>';
4506: return $result;
4507: }
4508:
4509:
4510: =pod
4511:
4512: =item scantron_filenames
4513:
4514: Returns a list of the scantron files in the current course
4515:
4516: =cut
4517:
4518: sub scantron_filenames {
4519: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4520: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
4521: my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
4522: &propath($cdom,$cname));
4523: my @possiblenames;
4524: foreach my $filename (sort(@files)) {
4525: ($filename)=split(/&/,$filename);
4526: if ($filename!~/^scantron_orig_/) { next ; }
4527: $filename=~s/^scantron_orig_//;
4528: push(@possiblenames,$filename);
4529: }
4530: return @possiblenames;
4531: }
4532:
4533: =pod
4534:
4535: =item scantron_uploads
4536:
4537: Returns html drop-down list of scantron files in current course.
4538:
4539: Arguments:
4540: $file2grade - filename to set as selected in the dropdown
4541:
4542: =cut
4543:
4544: sub scantron_uploads {
4545: my ($file2grade) = @_;
4546: my $result= '<select name="scantron_selectfile">';
4547: $result.="<option></option>";
4548: foreach my $filename (sort(&scantron_filenames())) {
4549: $result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
4550: }
4551: $result.="</select>";
4552: return $result;
4553: }
4554:
4555: =pod
4556:
4557: =item scantron_scantab
4558:
4559: Returns html drop down of the scantron formats in the scantronformat.tab
4560: file.
4561:
4562: =cut
4563:
4564: sub scantron_scantab {
4565: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
4566: my $result='<select name="scantron_format">'."\n";
4567: $result.='<option></option>'."\n";
4568: foreach my $line (<$fh>) {
4569: my ($name,$descrip)=split(/:/,$line);
4570: if ($name =~ /^\#/) { next; }
4571: $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
4572: }
4573: $result.='</select>'."\n";
4574:
4575: return $result;
4576: }
4577:
4578: =pod
4579:
4580: =item scantron_CODElist
4581:
4582: Returns html drop down of the saved CODE lists from current course,
4583: generated from earlier printings.
4584:
4585: =cut
4586:
4587: sub scantron_CODElist {
4588: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4589: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4590: my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
4591: my $namechoice='<option></option>';
4592: foreach my $name (sort {uc($a) cmp uc($b)} @names) {
4593: if ($name =~ /^error: 2 /) { next; }
4594: if ($name =~ /^type\0/) { next; }
4595: $namechoice.='<option value="'.$name.'">'.$name.'</option>';
4596: }
4597: $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
4598: return $namechoice;
4599: }
4600:
4601: =pod
4602:
4603: =item scantron_CODEunique
4604:
4605: Returns the html for "Each CODE to be used once" radio.
4606:
4607: =cut
4608:
4609: sub scantron_CODEunique {
4610: my $result='<span style="white-space: nowrap;">
4611: <label><input type="radio" name="scantron_CODEunique"
4612: value="yes" checked="checked" />'.&mt('Yes').' </label>
4613: </span>
4614: <span style="white-space: nowrap;">
4615: <label><input type="radio" name="scantron_CODEunique"
4616: value="no" />'.&mt('No').' </label>
4617: </span>';
4618: return $result;
4619: }
4620:
4621: =pod
4622:
4623: =item scantron_selectphase
4624:
4625: Generates the initial screen to start the bubble sheet process.
4626: Allows for - starting a grading run.
4627: - downloading existing scan data (original, corrected
4628: or skipped info)
4629:
4630: - uploading new scan data
4631:
4632: Arguments:
4633: $r - The Apache request object
4634: $file2grade - name of the file that contain the scanned data to score
4635:
4636: =cut
4637:
4638: sub scantron_selectphase {
4639: my ($r,$file2grade) = @_;
4640: my ($symb)=&get_symb($r);
4641: if (!$symb) {return '';}
4642: my $sequence_selector=&getSequenceDropDown($symb);
4643: my $default_form_data=&defaultFormData($symb);
4644: my $grading_menu_button=&show_grading_menu_form($symb);
4645: my $file_selector=&scantron_uploads($file2grade);
4646: my $format_selector=&scantron_scantab();
4647: my $CODE_selector=&scantron_CODElist();
4648: my $CODE_unique=&scantron_CODEunique();
4649: my $result;
4650:
4651: # Chunk of form to prompt for a file to grade and how:
4652:
4653: $result.= <<SCANTRONFORM;
4654: <table width="100%" border="0">
4655: <tr>
4656: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
4657: <td bgcolor="#777777">
4658: <input type="hidden" name="command" value="scantron_warning" />
4659: $default_form_data
4660: <table width="100%" border="0">
4661: <tr bgcolor="#e6ffff">
4662: <td colspan="2">
4663: <b>Specify file and which Folder/Sequence to grade</b>
4664: </td>
4665: </tr>
4666: <tr bgcolor="#ffffe6">
4667: <td> Sequence to grade: </td><td> $sequence_selector </td>
4668: </tr>
4669: <tr bgcolor="#ffffe6">
4670: <td> Filename of scoring office file: </td><td> $file_selector </td>
4671: </tr>
4672: <tr bgcolor="#ffffe6">
4673: <td> Format of data file: </td><td> $format_selector </td>
4674: </tr>
4675: <tr bgcolor="#ffffe6">
4676: <td> Saved CODEs to validate against: </td><td> $CODE_selector</td>
4677: </tr>
4678: <tr bgcolor="#ffffe6">
4679: <td> Each CODE is only to be used once:</td><td> $CODE_unique </td>
4680: </tr>
4681: <tr bgcolor="#ffffe6">
4682: <td> Options: </td>
4683: <td>
4684: <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> Do only previously skipped records</label> <br />
4685: <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> Remove all existing corrections</label> <br />
4686: <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> Skip hidden resources when grading</label>
4687: </td>
4688: </tr>
4689: <tr bgcolor="#ffffe6">
4690: <td colspan="2">
4691: <input type="submit" value="Grading: Validate Scantron Records" />
4692: </td>
4693: </tr>
4694: </table>
4695: </td>
4696: </form>
4697: </tr>
4698: SCANTRONFORM
4699:
4700: $r->print($result);
4701:
4702: if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
4703: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
4704:
4705: # Chunk of form to prompt for a scantron file upload.
4706:
4707: $r->print(<<SCANTRONFORM);
4708: <tr>
4709: <td bgcolor="#777777">
4710: <table width="100%" border="0">
4711: <tr bgcolor="#e6ffff">
4712: <td>
4713: <b>Specify a Scantron data file to upload.</b>
4714: </td>
4715: </tr>
4716: <tr bgcolor="#ffffe6">
4717: <td>
4718: SCANTRONFORM
4719: my $default_form_data=&defaultFormData(&get_symb($r,1));
4720: my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
4721: my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
4722: $r->print(<<UPLOAD);
4723: <script type="text/javascript" language="javascript">
4724: function checkUpload(formname) {
4725: if (formname.upfile.value == "") {
4726: alert("Please use the browse button to select a file from your local directory.");
4727: return false;
4728: }
4729: formname.submit();
4730: }
4731: </script>
4732:
4733: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
4734: $default_form_data
4735: <input name='courseid' type='hidden' value='$cnum' />
4736: <input name='domainid' type='hidden' value='$cdom' />
4737: <input name='command' value='scantronupload_save' type='hidden' />
4738: File to upload:<input type="file" name="upfile" size="50" />
4739: <br />
4740: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
4741: </form>
4742: UPLOAD
4743:
4744: $r->print(<<SCANTRONFORM);
4745: </td>
4746: </tr>
4747: </table>
4748: </td>
4749: </tr>
4750: SCANTRONFORM
4751: }
4752:
4753: # Chunk of the form that prompts to view a scoring office file,
4754: # corrected file, skipped records in a file.
4755:
4756: $r->print(<<SCANTRONFORM);
4757: <tr>
4758: <form action='/adm/grades' name='scantron_download'>
4759: <td bgcolor="#777777">
4760: $default_form_data
4761: <input type="hidden" name="command" value="scantron_download" />
4762: <table width="100%" border="0">
4763: <tr bgcolor="#e6ffff">
4764: <td colspan="2">
4765: <b>Download a scoring office file</b>
4766: </td>
4767: </tr>
4768: <tr bgcolor="#ffffe6">
4769: <td> Filename of scoring office file: </td><td> $file_selector </td>
4770: </tr>
4771: <tr bgcolor="#ffffe6">
4772: <td colspan="2">
4773: <input type="submit" value="Download: Show List of Associated Files" />
4774: </td>
4775: </tr>
4776: </table>
4777: </td>
4778: </form>
4779: </tr>
4780: SCANTRONFORM
4781:
4782: $r->print(<<SCANTRONFORM);
4783: </table>
4784: $grading_menu_button
4785: SCANTRONFORM
4786:
4787: return
4788: }
4789:
4790: =pod
4791:
4792: =item get_scantron_config
4793:
4794: Parse and return the scantron configuration line selected as a
4795: hash of configuration file fields.
4796:
4797: Arguments:
4798: which - the name of the configuration to parse from the file.
4799:
4800:
4801: Returns:
4802: If the named configuration is not in the file, an empty
4803: hash is returned.
4804: a hash with the fields
4805: name - internal name for the this configuration setup
4806: description - text to display to operator that describes this config
4807: CODElocation - if 0 or the string 'none'
4808: - no CODE exists for this config
4809: if -1 || the string 'letter'
4810: - a CODE exists for this config and is
4811: a string of letters
4812: Unsupported value (but planned for future support)
4813: if a positive integer
4814: - The CODE exists as the first n items from
4815: the question section of the form
4816: if the string 'number'
4817: - The CODE exists for this config and is
4818: a string of numbers
4819: CODEstart - (only matter if a CODE exists) column in the line where
4820: the CODE starts
4821: CODElength - length of the CODE
4822: IDstart - column where the student ID number starts
4823: IDlength - length of the student ID info
4824: Qstart - column where the information from the bubbled
4825: 'questions' start
4826: Qlength - number of columns comprising a single bubble line from
4827: the sheet. (usually either 1 or 10)
4828: Qon - either a single character representing the character used
4829: to signal a bubble was chosen in the positional setup, or
4830: the string 'letter' if the letter of the chosen bubble is
4831: in the final, or 'number' if a number representing the
4832: chosen bubble is in the file (1->A 0->J)
4833: Qoff - the character used to represent that a bubble was
4834: left blank
4835: PaperID - if the scanning process generates a unique number for each
4836: sheet scanned the column that this ID number starts in
4837: PaperIDlength - number of columns that comprise the unique ID number
4838: for the sheet of paper
4839: FirstName - column that the first name starts in
4840: FirstNameLength - number of columns that the first name spans
4841:
4842: LastName - column that the last name starts in
4843: LastNameLength - number of columns that the last name spans
4844:
4845: =cut
4846:
4847: sub get_scantron_config {
4848: my ($which) = @_;
4849: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
4850: my %config;
4851: #FIXME probably should move to XML it has already gotten a bit much now
4852: foreach my $line (<$fh>) {
4853: my ($name,$descrip)=split(/:/,$line);
4854: if ($name ne $which ) { next; }
4855: chomp($line);
4856: my @config=split(/:/,$line);
4857: $config{'name'}=$config[0];
4858: $config{'description'}=$config[1];
4859: $config{'CODElocation'}=$config[2];
4860: $config{'CODEstart'}=$config[3];
4861: $config{'CODElength'}=$config[4];
4862: $config{'IDstart'}=$config[5];
4863: $config{'IDlength'}=$config[6];
4864: $config{'Qstart'}=$config[7];
4865: $config{'Qlength'}=$config[8];
4866: $config{'Qoff'}=$config[9];
4867: $config{'Qon'}=$config[10];
4868: $config{'PaperID'}=$config[11];
4869: $config{'PaperIDlength'}=$config[12];
4870: $config{'FirstName'}=$config[13];
4871: $config{'FirstNamelength'}=$config[14];
4872: $config{'LastName'}=$config[15];
4873: $config{'LastNamelength'}=$config[16];
4874: last;
4875: }
4876: return %config;
4877: }
4878:
4879: =pod
4880:
4881: =item username_to_idmap
4882:
4883: creates a hash keyed by student id with values of the corresponding
4884: student username:domain.
4885:
4886: Arguments:
4887:
4888: $classlist - reference to the class list hash. This is a hash
4889: keyed by student name:domain whose elements are references
4890: to arrays containing various chunks of information
4891: about the student. (See loncoursedata for more info).
4892:
4893: Returns
4894: %idmap - the constructed hash
4895:
4896: =cut
4897:
4898: sub username_to_idmap {
4899: my ($classlist)= @_;
4900: my %idmap;
4901: foreach my $student (keys(%$classlist)) {
4902: $idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
4903: $student;
4904: }
4905: return %idmap;
4906: }
4907:
4908: =pod
4909:
4910: =item scantron_fixup_scanline
4911:
4912: Process a requested correction to a scanline.
4913:
4914: Arguments:
4915: $scantron_config - hash from &get_scantron_config()
4916: $scan_data - hash of correction information
4917: (see &scantron_getfile())
4918: $line - existing scanline
4919: $whichline - line number of the passed in scanline
4920: $field - type of change to process
4921: (either
4922: 'ID' -> correct the student ID number
4923: 'CODE' -> correct the CODE
4924: 'answer' -> fixup the submitted answers)
4925:
4926: $args - hash of additional info,
4927: - 'ID'
4928: 'newid' -> studentID to use in replacement
4929: of existing one
4930: - 'CODE'
4931: 'CODE_ignore_dup' - set to true if duplicates
4932: should be ignored.
4933: 'CODE' - is new code or 'use_unfound'
4934: if the existing unfound code should
4935: be used as is
4936: - 'answer'
4937: 'response' - new answer or 'none' if blank
4938: 'question' - the bubble line to change
4939:
4940: Returns:
4941: $line - the modified scanline
4942:
4943: Side effects:
4944: $scan_data - may be updated
4945:
4946: =cut
4947:
4948:
4949: sub scantron_fixup_scanline {
4950: my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
4951:
4952: if ($field eq 'ID') {
4953: if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
4954: return ($line,1,'New value too large');
4955: }
4956: if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
4957: $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
4958: $args->{'newid'});
4959: }
4960: substr($line,$$scantron_config{'IDstart'}-1,
4961: $$scantron_config{'IDlength'})=$args->{'newid'};
4962: if ($args->{'newid'}=~/^\s*$/) {
4963: &scan_data($scan_data,"$whichline.user",
4964: $args->{'username'}.':'.$args->{'domain'});
4965: }
4966: } elsif ($field eq 'CODE') {
4967: if ($args->{'CODE_ignore_dup'}) {
4968: &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
4969: }
4970: &scan_data($scan_data,"$whichline.useCODE",'1');
4971: if ($args->{'CODE'} ne 'use_unfound') {
4972: if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
4973: return ($line,1,'New CODE value too large');
4974: }
4975: if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
4976: $args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
4977: }
4978: substr($line,$$scantron_config{'CODEstart'}-1,
4979: $$scantron_config{'CODElength'})=$args->{'CODE'};
4980: }
4981: } elsif ($field eq 'answer') {
4982: my $length=$scantron_config->{'Qlength'};
4983: my $off=$scantron_config->{'Qoff'};
4984: my $on=$scantron_config->{'Qon'};
4985: my $answer=${off}x$length;
4986: if ($args->{'response'} eq 'none') {
4987: &scan_data($scan_data,
4988: "$whichline.no_bubble.".$args->{'question'},'1');
4989: } else {
4990: if ($on eq 'letter') {
4991: my @alphabet=('A'..'Z');
4992: $answer=$alphabet[$args->{'response'}];
4993: } elsif ($on eq 'number') {
4994: $answer=$args->{'response'}+1;
4995: if ($answer == 10) { $answer = '0'; }
4996: } else {
4997: substr($answer,$args->{'response'},1)=$on;
4998: }
4999: &scan_data($scan_data,
5000: "$whichline.no_bubble.".$args->{'question'},undef,'1');
5001: }
5002: my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
5003: substr($line,$where-1,$length)=$answer;
5004: }
5005: return $line;
5006: }
5007:
5008: =pod
5009:
5010: =item scan_data
5011:
5012: Edit or look up an item in the scan_data hash.
5013:
5014: Arguments:
5015: $scan_data - The hash (see scantron_getfile)
5016: $key - shorthand of the key to edit (actual key is
5017: scantronfilename_key).
5018: $data - New value of the hash entry.
5019: $delete - If true, the entry is removed from the hash.
5020:
5021: Returns:
5022: The new value of the hash table field (undefined if deleted).
5023:
5024: =cut
5025:
5026:
5027: sub scan_data {
5028: my ($scan_data,$key,$value,$delete)=@_;
5029: my $filename=$env{'form.scantron_selectfile'};
5030: if (defined($value)) {
5031: $scan_data->{$filename.'_'.$key} = $value;
5032: }
5033: if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
5034: return $scan_data->{$filename.'_'.$key};
5035: }
5036:
5037: =pod
5038:
5039: =item scantron_parse_scanline
5040:
5041: Decodes a scanline from the selected scantron file
5042:
5043: Arguments:
5044: line - The text of the scantron file line to process
5045: whichline - Line number
5046: scantron_config - Hash describing the format of the scantron lines.
5047: scan_data - Hash of extra information about the scanline
5048: (see scantron_getfile for more information)
5049: just_header - True if should not process question answers but only
5050: the stuff to the left of the answers.
5051: Returns:
5052: Hash containing the result of parsing the scanline
5053:
5054: Keys are all proceeded by the string 'scantron.'
5055:
5056: CODE - the CODE in use for this scanline
5057: useCODE - 1 if the CODE is invalid but it usage has been forced
5058: by the operator
5059: CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
5060: CODEs were selected, but the usage has been
5061: forced by the operator
5062: ID - student ID
5063: PaperID - if used, the ID number printed on the sheet when the
5064: paper was scanned
5065: FirstName - first name from the sheet
5066: LastName - last name from the sheet
5067:
5068: if just_header was not true these key may also exist
5069:
5070: missingerror - a list of bubbled line numbers that had a blank bubble
5071: that is considered an error (if the operator had already
5072: okayed a blank bubble line as really being blank then
5073: that bubble line number won't appear here.
5074: doubleerror - a list of bubbled line numbers that had more than one
5075: bubble filled in and has not been corrected by the
5076: operator
5077: maxquest - the number of the last bubble line that was parsed
5078:
5079: (<number> starts at 1)
5080: <number>.answer - zero or more letters representing the selected
5081: letters from the scanline for the bubble line
5082: <number>.
5083: if blank there was either no bubble or there where
5084: multiple bubbles, (consult the keys missingerror and
5085: doubleerror if this is an error condition)
5086:
5087: =cut
5088:
5089: sub scantron_parse_scanline {
5090: my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
5091: my %record;
5092: my $questions=substr($line,$$scantron_config{'Qstart'}-1); # Answers
5093: my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # earlier stuff
5094: if (!($$scantron_config{'CODElocation'} eq 0 ||
5095: $$scantron_config{'CODElocation'} eq 'none')) {
5096: if ($$scantron_config{'CODElocation'} < 0 ||
5097: $$scantron_config{'CODElocation'} eq 'letter' ||
5098: $$scantron_config{'CODElocation'} eq 'number') {
5099: $record{'scantron.CODE'}=substr($data,
5100: $$scantron_config{'CODEstart'}-1,
5101: $$scantron_config{'CODElength'});
5102: if (&scan_data($scan_data,"$whichline.useCODE")) {
5103: $record{'scantron.useCODE'}=1;
5104: }
5105: if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
5106: $record{'scantron.CODE_ignore_dup'}=1;
5107: }
5108: } else {
5109: #FIXME interpret first N questions
5110: }
5111: }
5112: $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
5113: $$scantron_config{'IDlength'});
5114: $record{'scantron.PaperID'}=
5115: substr($data,$$scantron_config{'PaperID'}-1,
5116: $$scantron_config{'PaperIDlength'});
5117: $record{'scantron.FirstName'}=
5118: substr($data,$$scantron_config{'FirstName'}-1,
5119: $$scantron_config{'FirstNamelength'});
5120: $record{'scantron.LastName'}=
5121: substr($data,$$scantron_config{'LastName'}-1,
5122: $$scantron_config{'LastNamelength'});
5123: if ($just_header) { return \%record; }
5124:
5125: my @alphabet=('A'..'Z');
5126: my $questnum=0;
5127: while ($questions) {
5128: $questnum++;
5129: my $currentquest=substr($questions,0,$$scantron_config{'Qlength'});
5130: substr($questions,0,$$scantron_config{'Qlength'})='';
5131: if (length($currentquest) < $$scantron_config{'Qlength'}) { next; }
5132: if ($$scantron_config{'Qon'} eq 'letter') {
5133: if ($currentquest eq '?'
5134: || $currentquest eq '*') {
5135: push(@{$record{'scantron.doubleerror'}},$questnum);
5136: $record{"scantron.$questnum.answer"}='';
5137: } elsif (!defined($currentquest)
5138: || $currentquest eq $$scantron_config{'Qoff'}
5139: || $currentquest !~ /^[A-Z]$/) {
5140: $record{"scantron.$questnum.answer"}='';
5141: if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
5142: push(@{$record{"scantron.missingerror"}},$questnum);
5143: }
5144: } else {
5145: $record{"scantron.$questnum.answer"}=$currentquest;
5146: }
5147: } elsif ($$scantron_config{'Qon'} eq 'number') {
5148: if ($currentquest eq '?'
5149: || $currentquest eq '*') {
5150: push(@{$record{'scantron.doubleerror'}},$questnum);
5151: $record{"scantron.$questnum.answer"}='';
5152: } elsif (!defined($currentquest)
5153: || $currentquest eq $$scantron_config{'Qoff'}
5154: || $currentquest !~ /^\d$/) {
5155: $record{"scantron.$questnum.answer"}='';
5156: if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
5157: push(@{$record{"scantron.missingerror"}},$questnum);
5158: }
5159: } else {
5160: # wrap zero back to J
5161: if ($currentquest eq '0') {
5162: $record{"scantron.$questnum.answer"}=
5163: $alphabet[9];
5164: } else {
5165: $record{"scantron.$questnum.answer"}=
5166: $alphabet[$currentquest-1];
5167: }
5168: }
5169: } else {
5170: my @array=split($$scantron_config{'Qon'},$currentquest,-1);
5171: if (length($array[0]) eq $$scantron_config{'Qlength'}) {
5172: $record{"scantron.$questnum.answer"}='';
5173: if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
5174: push(@{$record{"scantron.missingerror"}},$questnum);
5175: }
5176: } else {
5177: $record{"scantron.$questnum.answer"}=
5178: $alphabet[length($array[0])];
5179: }
5180: if (scalar(@array) gt 2) {
5181: push(@{$record{'scantron.doubleerror'}},$questnum);
5182: my @ans=@array;
5183: my $i=length($ans[0]);shift(@ans);
5184: while ($#ans) {
5185: $i+=length($ans[0])+1;
5186: $record{"scantron.$questnum.answer"}.=$alphabet[$i];
5187: shift(@ans);
5188: }
5189: }
5190: }
5191: }
5192: $record{'scantron.maxquest'}=$questnum;
5193: return \%record;
5194: }
5195:
5196: =pod
5197:
5198: =item scantron_add_delay
5199:
5200: Adds an error message that occurred during the grading phase to a
5201: queue of messages to be shown after grading pass is complete
5202:
5203: Arguments:
5204: $delayqueue - arrary ref of hash ref of error messages
5205: $scanline - the scanline that caused the error
5206: $errormesage - the error message
5207: $errorcode - a numeric code for the error
5208:
5209: Side Effects:
5210: updates the $delayqueue to have a new hash ref of the error
5211:
5212: =cut
5213:
5214: sub scantron_add_delay {
5215: my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
5216: push(@$delayqueue,
5217: {'line' => $scanline, 'emsg' => $errormessage,
5218: 'ecode' => $errorcode }
5219: );
5220: }
5221:
5222: =pod
5223:
5224: =item scantron_find_student
5225:
5226: Finds the username for the current scanline
5227:
5228: Arguments:
5229: $scantron_record - hash result from scantron_parse_scanline
5230: $scan_data - hash of correction information
5231: (see &scantron_getfile() form more information)
5232: $idmap - hash from &username_to_idmap()
5233: $line - number of current scanline
5234:
5235: Returns:
5236: Either 'username:domain' or undef if unknown
5237:
5238: =cut
5239:
5240: sub scantron_find_student {
5241: my ($scantron_record,$scan_data,$idmap,$line)=@_;
5242: my $scanID=$$scantron_record{'scantron.ID'};
5243: if ($scanID =~ /^\s*$/) {
5244: return &scan_data($scan_data,"$line.user");
5245: }
5246: foreach my $id (keys(%$idmap)) {
5247: if (lc($id) eq lc($scanID)) {
5248: return $$idmap{$id};
5249: }
5250: }
5251: return undef;
5252: }
5253:
5254: =pod
5255:
5256: =item scantron_filter
5257:
5258: Filter sub for lonnavmaps, filters out hidden resources if ignore
5259: hidden resources was selected
5260:
5261: =cut
5262:
5263: sub scantron_filter {
5264: my ($curres)=@_;
5265:
5266: if (ref($curres) && $curres->is_problem()) {
5267: # if the user has asked to not have either hidden
5268: # or 'randomout' controlled resources to be graded
5269: # don't include them
5270: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
5271: && $curres->randomout) {
5272: return 0;
5273: }
5274: return 1;
5275: }
5276: return 0;
5277: }
5278:
5279: =pod
5280:
5281: =item scantron_process_corrections
5282:
5283: Gets correction information out of submitted form data and corrects
5284: the scanline
5285:
5286: =cut
5287:
5288: sub scantron_process_corrections {
5289: my ($r) = @_;
5290: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
5291: my ($scanlines,$scan_data)=&scantron_getfile();
5292: my $classlist=&Apache::loncoursedata::get_classlist();
5293: my $which=$env{'form.scantron_line'};
5294: my $line=&scantron_get_line($scanlines,$scan_data,$which);
5295: my ($skip,$err,$errmsg);
5296: if ($env{'form.scantron_skip_record'}) {
5297: $skip=1;
5298: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
5299: my $newstudent=$env{'form.scantron_username'}.':'.
5300: $env{'form.scantron_domain'};
5301: my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
5302: ($line,$err,$errmsg)=
5303: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
5304: 'ID',{'newid'=>$newid,
5305: 'username'=>$env{'form.scantron_username'},
5306: 'domain'=>$env{'form.scantron_domain'}});
5307: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
5308: my $resolution=$env{'form.scantron_CODE_resolution'};
5309: my $newCODE;
5310: my %args;
5311: if ($resolution eq 'use_unfound') {
5312: $newCODE='use_unfound';
5313: } elsif ($resolution eq 'use_found') {
5314: $newCODE=$env{'form.scantron_CODE_selectedvalue'};
5315: } elsif ($resolution eq 'use_typed') {
5316: $newCODE=$env{'form.scantron_CODE_newvalue'};
5317: } elsif ($resolution =~ /^use_closest_(\d+)/) {
5318: $newCODE=$env{"form.scantron_CODE_closest_$1"};
5319: }
5320: if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
5321: $args{'CODE_ignore_dup'}=1;
5322: }
5323: $args{'CODE'}=$newCODE;
5324: ($line,$err,$errmsg)=
5325: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
5326: 'CODE',\%args);
5327: } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
5328: foreach my $question (split(',',$env{'form.scantron_questions'})) {
5329: ($line,$err,$errmsg)=
5330: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
5331: $which,'answer',
5332: { 'question'=>$question,
5333: 'response'=>$env{"form.scantron_correct_Q_$question"}});
5334: if ($err) { last; }
5335: }
5336: }
5337: if ($err) {
5338: $r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
5339: } else {
5340: &scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
5341: &scantron_putfile($scanlines,$scan_data);
5342: }
5343: }
5344:
5345: =pod
5346:
5347: =item reset_skipping_status
5348:
5349: Forgets the current set of remember skipped scanlines (and thus
5350: reverts back to considering all lines in the
5351: scantron_skipped_<filename> file)
5352:
5353: =cut
5354:
5355: sub reset_skipping_status {
5356: my ($scanlines,$scan_data)=&scantron_getfile();
5357: &scan_data($scan_data,'remember_skipping',undef,1);
5358: &scantron_putfile(undef,$scan_data);
5359: }
5360:
5361: =pod
5362:
5363: =item start_skipping
5364:
5365: Marks a scanline to be skipped.
5366:
5367: =cut
5368:
5369: sub start_skipping {
5370: my ($scan_data,$i)=@_;
5371: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
5372: if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
5373: $remembered{$i}=2;
5374: } else {
5375: $remembered{$i}=1;
5376: }
5377: &scan_data($scan_data,'remember_skipping',join(':',%remembered));
5378: }
5379:
5380: =pod
5381:
5382: =item should_be_skipped
5383:
5384: Checks whether a scanline should be skipped.
5385:
5386: =cut
5387:
5388: sub should_be_skipped {
5389: my ($scanlines,$scan_data,$i)=@_;
5390: if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
5391: # not redoing old skips
5392: if ($scanlines->{'skipped'}[$i]) { return 1; }
5393: return 0;
5394: }
5395: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
5396:
5397: if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
5398: return 0;
5399: }
5400: return 1;
5401: }
5402:
5403: =pod
5404:
5405: =item remember_current_skipped
5406:
5407: Discovers what scanlines are in the scantron_skipped_<filename>
5408: file and remembers them into scan_data for later use.
5409:
5410: =cut
5411:
5412: sub remember_current_skipped {
5413: my ($scanlines,$scan_data)=&scantron_getfile();
5414: my %to_remember;
5415: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
5416: if ($scanlines->{'skipped'}[$i]) {
5417: $to_remember{$i}=1;
5418: }
5419: }
5420:
5421: &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
5422: &scantron_putfile(undef,$scan_data);
5423: }
5424:
5425: =pod
5426:
5427: =item check_for_error
5428:
5429: Checks if there was an error when attempting to remove a specific
5430: scantron_.. bubble sheet data file. Prints out an error if
5431: something went wrong.
5432:
5433: =cut
5434:
5435: sub check_for_error {
5436: my ($r,$result)=@_;
5437: if ($result ne 'ok' && $result ne 'not_found' ) {
5438: $r->print("An error occurred ($result) when trying to Remove the existing corrections.");
5439: }
5440: }
5441:
5442: =pod
5443:
5444: =item scantron_warning_screen
5445:
5446: Interstitial screen to make sure the operator has selected the
5447: correct options before we start the validation phase.
5448:
5449: =cut
5450:
5451: sub scantron_warning_screen {
5452: my ($button_text)=@_;
5453: my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
5454: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
5455: my $CODElist;
5456: if ($scantron_config{'CODElocation'} &&
5457: $scantron_config{'CODEstart'} &&
5458: $scantron_config{'CODElength'}) {
5459: $CODElist=$env{'form.scantron_CODElist'};
5460: if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
5461: $CODElist=
5462: '<tr><td><b>List of CODES to validate against:</b></td><td><tt>'.
5463: $env{'form.scantron_CODElist'}.'</tt></td></tr>';
5464: }
5465: return (<<STUFF);
5466: <p>
5467: <span class="LC_warning">Please double check the information
5468: below before clicking on '$button_text'</span>
5469: </p>
5470: <table>
5471: <tr><td><b>Sequence to be Graded:</b></td><td>$title</td></tr>
5472: <tr><td><b>Data File that will be used:</b></td><td><tt>$env{'form.scantron_selectfile'}</tt></td></tr>
5473: $CODElist
5474: </table>
5475: <br />
5476: <p> If this information is correct, please click on '$button_text'.</p>
5477: <p> If something is incorrect, please click the 'Grading Menu' button to start over.</p>
5478:
5479: <br />
5480: STUFF
5481: }
5482:
5483: =pod
5484:
5485: =item scantron_do_warning
5486:
5487: Check if the operator has picked something for all required
5488: fields. Error out if something is missing.
5489:
5490: =cut
5491:
5492: sub scantron_do_warning {
5493: my ($r)=@_;
5494: my ($symb)=&get_symb($r);
5495: if (!$symb) {return '';}
5496: my $default_form_data=&defaultFormData($symb);
5497: $r->print(&scantron_form_start().$default_form_data);
5498: if ( $env{'form.selectpage'} eq '' ||
5499: $env{'form.scantron_selectfile'} eq '' ||
5500: $env{'form.scantron_format'} eq '' ) {
5501: $r->print("<p>You have forgetten to specify some information. Please go Back and try again.</p>");
5502: if ( $env{'form.selectpage'} eq '') {
5503: $r->print('<p><span class="LC_error">You have not selected a Sequence to grade</span></p>');
5504: }
5505: if ( $env{'form.scantron_selectfile'} eq '') {
5506: $r->print('<p><span class="LC_error">You have not selected a file that contains the student\'s response data.</span></p>');
5507: }
5508: if ( $env{'form.scantron_format'} eq '') {
5509: $r->print('<p><span class="LC_error">You have not selected a the format of the student\'s response data.</span></p>');
5510: }
5511: } else {
5512: my $warning=&scantron_warning_screen('Grading: Validate Records');
5513: $r->print(<<STUFF);
5514: $warning
5515: <input type="submit" name="submit" value="Grading: Validate Records" />
5516: <input type="hidden" name="command" value="scantron_validate" />
5517: STUFF
5518: }
5519: $r->print("</form><br />".&show_grading_menu_form($symb));
5520: return '';
5521: }
5522:
5523: =pod
5524:
5525: =item scantron_form_start
5526:
5527: html hidden input for remembering all selected grading options
5528:
5529: =cut
5530:
5531: sub scantron_form_start {
5532: my ($max_bubble)=@_;
5533: my $result= <<SCANTRONFORM;
5534: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
5535: <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
5536: <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
5537: <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
5538: <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
5539: <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
5540: <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
5541: <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
5542: <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
5543: <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
5544: SCANTRONFORM
5545: return $result;
5546: }
5547:
5548: =pod
5549:
5550: =item scantron_validate_file
5551:
5552: Dispatch routine for doing validation of a bubble sheet data file.
5553:
5554: Also processes any necessary information resets that need to
5555: occur before validation begins (ignore previous corrections,
5556: restarting the skipped records processing)
5557:
5558: =cut
5559:
5560: sub scantron_validate_file {
5561: my ($r) = @_;
5562: my ($symb)=&get_symb($r);
5563: if (!$symb) {return '';}
5564: my $default_form_data=&defaultFormData($symb);
5565:
5566: # do the detection of only doing skipped records first befroe we delete
5567: # them when doing the corrections reset
5568: if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
5569: &reset_skipping_status();
5570: }
5571: if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
5572: &remember_current_skipped();
5573: $env{'form.scantron_options_redo'}='redo_skipped_ready';
5574: }
5575:
5576: if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
5577: &check_for_error($r,&scantron_remove_file('corrected'));
5578: &check_for_error($r,&scantron_remove_file('skipped'));
5579: &check_for_error($r,&scantron_remove_scan_data());
5580: $env{'form.scantron_options_ignore'}='done';
5581: }
5582:
5583: if ($env{'form.scantron_corrections'}) {
5584: &scantron_process_corrections($r);
5585: }
5586: $r->print("<p>Gathering necessary info.</p>");$r->rflush();
5587: #get the student pick code ready
5588: $r->print(&Apache::loncommon::studentbrowser_javascript());
5589: my $max_bubble=&scantron_get_maxbubble();
5590: my $result=&scantron_form_start($max_bubble).$default_form_data;
5591: $r->print($result);
5592:
5593: my @validate_phases=( 'sequence',
5594: 'ID',
5595: 'CODE',
5596: 'doublebubble',
5597: 'missingbubbles');
5598: if (!$env{'form.validatepass'}) {
5599: $env{'form.validatepass'} = 0;
5600: }
5601: my $currentphase=$env{'form.validatepass'};
5602:
5603: my $stop=0;
5604: while (!$stop && $currentphase < scalar(@validate_phases)) {
5605: $r->print("<p> Validating ".$validate_phases[$currentphase]."</p>");
5606: $r->rflush();
5607: my $which="scantron_validate_".$validate_phases[$currentphase];
5608: {
5609: no strict 'refs';
5610: ($stop,$currentphase)=&$which($r,$currentphase);
5611: }
5612: }
5613: if (!$stop) {
5614: my $warning=&scantron_warning_screen('Start Grading');
5615: $r->print(<<STUFF);
5616: Validation process complete.<br />
5617: $warning
5618: <input type="submit" name="submit" value="Start Grading" />
5619: <input type="hidden" name="command" value="scantron_process" />
5620: STUFF
5621:
5622: } else {
5623: $r->print('<input type="hidden" name="command" value="scantron_validate" />');
5624: $r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
5625: }
5626: if ($stop) {
5627: if ($validate_phases[$currentphase] eq 'sequence') {
5628: $r->print('<input type="submit" name="submit" value="Ignore -> " />');
5629: $r->print(' this error <br />');
5630:
5631: $r->print(" <p>Or click the 'Grading Menu' button to start over.</p>");
5632: } else {
5633: $r->print('<input type="submit" name="submit" value="Continue ->" />');
5634: $r->print(' using corrected info <br />');
5635: $r->print("<input type='submit' value='Skip' name='scantron_skip_record' />");
5636: $r->print(" this scanline saving it for later.");
5637: }
5638: }
5639: $r->print(" </form><br />".&show_grading_menu_form($symb));
5640: return '';
5641: }
5642:
5643:
5644: =pod
5645:
5646: =item scantron_remove_file
5647:
5648: Removes the requested bubble sheet data file, makes sure that
5649: scantron_original_<filename> is never removed
5650:
5651:
5652: =cut
5653:
5654: sub scantron_remove_file {
5655: my ($which)=@_;
5656: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5657: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5658: my $file='scantron_';
5659: if ($which eq 'corrected' || $which eq 'skipped') {
5660: $file.=$which.'_';
5661: } else {
5662: return 'refused';
5663: }
5664: $file.=$env{'form.scantron_selectfile'};
5665: return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
5666: }
5667:
5668:
5669: =pod
5670:
5671: =item scantron_remove_scan_data
5672:
5673: Removes all scan_data correction for the requested bubble sheet
5674: data file. (In the case that both the are doing skipped records we need
5675: to remember the old skipped lines for the time being so that element
5676: persists for a while.)
5677:
5678: =cut
5679:
5680: sub scantron_remove_scan_data {
5681: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5682: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5683: my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
5684: my @todelete;
5685: my $filename=$env{'form.scantron_selectfile'};
5686: foreach my $key (@keys) {
5687: if ($key=~/^\Q$filename\E_/) {
5688: if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
5689: $key=~/remember_skipping/) {
5690: next;
5691: }
5692: push(@todelete,$key);
5693: }
5694: }
5695: my $result;
5696: if (@todelete) {
5697: $result=&Apache::lonnet::del('nohist_scantrondata',\@todelete,$cdom,$cname);
5698: }
5699: return $result;
5700: }
5701:
5702:
5703: =pod
5704:
5705: =item scantron_getfile
5706:
5707: Fetches the requested bubble sheet data file (all 3 versions), and
5708: the scan_data hash
5709:
5710: Arguments:
5711: None
5712:
5713: Returns:
5714: 2 hash references
5715:
5716: - first one has
5717: orig -
5718: corrected -
5719: skipped - each of which points to an array ref of the specified
5720: file broken up into individual lines
5721: count - number of scanlines
5722:
5723: - second is the scan_data hash possible keys are
5724: ($number refers to scanline numbered $number and thus the key affects
5725: only that scanline
5726: $bubline refers to the specific bubble line element and the aspects
5727: refers to that specific bubble line element)
5728:
5729: $number.user - username:domain to use
5730: $number.CODE_ignore_dup
5731: - ignore the duplicate CODE error
5732: $number.useCODE
5733: - use the CODE in the scanline as is
5734: $number.no_bubble.$bubline
5735: - it is valid that there is no bubbled in bubble
5736: at $number $bubline
5737: remember_skipping
5738: - a frozen hash containing keys of $number and values
5739: of either
5740: 1 - we are on a 'do skipped records pass' and plan
5741: on processing this line
5742: 2 - we are on a 'do skipped records pass' and this
5743: scanline has been marked to skip yet again
5744:
5745: =cut
5746:
5747: sub scantron_getfile {
5748: #FIXME really would prefer a scantron directory
5749: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5750: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5751: my $lines;
5752: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
5753: 'scantron_orig_'.$env{'form.scantron_selectfile'});
5754: my %scanlines;
5755: $scanlines{'orig'}=[(split("\n",$lines,-1))];
5756: my $temp=$scanlines{'orig'};
5757: $scanlines{'count'}=$#$temp;
5758:
5759: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
5760: 'scantron_corrected_'.$env{'form.scantron_selectfile'});
5761: if ($lines eq '-1') {
5762: $scanlines{'corrected'}=[];
5763: } else {
5764: $scanlines{'corrected'}=[(split("\n",$lines,-1))];
5765: }
5766: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
5767: 'scantron_skipped_'.$env{'form.scantron_selectfile'});
5768: if ($lines eq '-1') {
5769: $scanlines{'skipped'}=[];
5770: } else {
5771: $scanlines{'skipped'}=[(split("\n",$lines,-1))];
5772: }
5773: my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
5774: if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
5775: my %scan_data = @tmp;
5776: return (\%scanlines,\%scan_data);
5777: }
5778:
5779: =pod
5780:
5781: =item lonnet_putfile
5782:
5783: Wrapper routine to call &Apache::lonnet::finishuserfileupload
5784:
5785: Arguments:
5786: $contents - data to store
5787: $filename - filename to store $contents into
5788:
5789: Returns:
5790: result value from &Apache::lonnet::finishuserfileupload
5791:
5792: =cut
5793:
5794: sub lonnet_putfile {
5795: my ($contents,$filename)=@_;
5796: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
5797: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5798: $env{'form.sillywaytopassafilearound'}=$contents;
5799: &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
5800:
5801: }
5802:
5803: =pod
5804:
5805: =item scantron_putfile
5806:
5807: Stores the current version of the bubble sheet data files, and the
5808: scan_data hash. (Does not modify the original version only the
5809: corrected and skipped versions.
5810:
5811: Arguments:
5812: $scanlines - hash ref that looks like the first return value from
5813: &scantron_getfile()
5814: $scan_data - hash ref that looks like the second return value from
5815: &scantron_getfile()
5816:
5817: =cut
5818:
5819: sub scantron_putfile {
5820: my ($scanlines,$scan_data) = @_;
5821: #FIXME really would prefer a scantron directory
5822: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5823: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5824: if ($scanlines) {
5825: my $prefix='scantron_';
5826: # no need to update orig, shouldn't change
5827: # &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
5828: # $env{'form.scantron_selectfile'});
5829: &lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
5830: $prefix.'corrected_'.
5831: $env{'form.scantron_selectfile'});
5832: &lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
5833: $prefix.'skipped_'.
5834: $env{'form.scantron_selectfile'});
5835: }
5836: &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
5837: }
5838:
5839: =pod
5840:
5841: =item scantron_get_line
5842:
5843: Returns the correct version of the scanline
5844:
5845: Arguments:
5846: $scanlines - hash ref that looks like the first return value from
5847: &scantron_getfile()
5848: $scan_data - hash ref that looks like the second return value from
5849: &scantron_getfile()
5850: $i - number of the requested line (starts at 0)
5851:
5852: Returns:
5853: A scanline, (either the original or the corrected one if it
5854: exists), or undef if the requested scanline should be
5855: skipped. (Either because it's an skipped scanline, or it's an
5856: unskipped scanline and we are not doing a 'do skipped scanlines'
5857: pass.
5858:
5859: =cut
5860:
5861: sub scantron_get_line {
5862: my ($scanlines,$scan_data,$i)=@_;
5863: if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
5864: #if ($scanlines->{'skipped'}[$i]) { return undef; }
5865: if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
5866: return $scanlines->{'orig'}[$i];
5867: }
5868:
5869: =pod
5870:
5871: =item scantron_todo_count
5872:
5873: Counts the number of scanlines that need processing.
5874:
5875: Arguments:
5876: $scanlines - hash ref that looks like the first return value from
5877: &scantron_getfile()
5878: $scan_data - hash ref that looks like the second return value from
5879: &scantron_getfile()
5880:
5881: Returns:
5882: $count - number of scanlines to process
5883:
5884: =cut
5885:
5886: sub get_todo_count {
5887: my ($scanlines,$scan_data)=@_;
5888: my $count=0;
5889: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
5890: my $line=&scantron_get_line($scanlines,$scan_data,$i);
5891: if ($line=~/^[\s\cz]*$/) { next; }
5892: $count++;
5893: }
5894: return $count;
5895: }
5896:
5897: =pod
5898:
5899: =item scantron_put_line
5900:
5901: Updates the 'corrected' or 'skipped' versions of the bubble sheet
5902: data file.
5903:
5904: Arguments:
5905: $scanlines - hash ref that looks like the first return value from
5906: &scantron_getfile()
5907: $scan_data - hash ref that looks like the second return value from
5908: &scantron_getfile()
5909: $i - line number to update
5910: $newline - contents of the updated scanline
5911: $skip - if true make the line for skipping and update the
5912: 'skipped' file
5913:
5914: =cut
5915:
5916: sub scantron_put_line {
5917: my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
5918: if ($skip) {
5919: $scanlines->{'skipped'}[$i]=$newline;
5920: &start_skipping($scan_data,$i);
5921: return;
5922: }
5923: $scanlines->{'corrected'}[$i]=$newline;
5924: }
5925:
5926: =pod
5927:
5928: =item scantron_clear_skip
5929:
5930: Remove a line from the 'skipped' file
5931:
5932: Arguments:
5933: $scanlines - hash ref that looks like the first return value from
5934: &scantron_getfile()
5935: $scan_data - hash ref that looks like the second return value from
5936: &scantron_getfile()
5937: $i - line number to update
5938:
5939: =cut
5940:
5941: sub scantron_clear_skip {
5942: my ($scanlines,$scan_data,$i)=@_;
5943: if (exists($scanlines->{'skipped'}[$i])) {
5944: undef($scanlines->{'skipped'}[$i]);
5945: return 1;
5946: }
5947: return 0;
5948: }
5949:
5950: =pod
5951:
5952: =item scantron_filter_not_exam
5953:
5954: Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
5955: filter out resources that are not marked as 'exam' mode
5956:
5957: =cut
5958:
5959: sub scantron_filter_not_exam {
5960: my ($curres)=@_;
5961:
5962: if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
5963: # if the user has asked to not have either hidden
5964: # or 'randomout' controlled resources to be graded
5965: # don't include them
5966: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
5967: && $curres->randomout) {
5968: return 0;
5969: }
5970: return 1;
5971: }
5972: return 0;
5973: }
5974:
5975: =pod
5976:
5977: =item scantron_validate_sequence
5978:
5979: Validates the selected sequence, checking for resource that are
5980: not set to exam mode.
5981:
5982: =cut
5983:
5984: sub scantron_validate_sequence {
5985: my ($r,$currentphase) = @_;
5986:
5987: my $navmap=Apache::lonnavmaps::navmap->new();
5988: my (undef,undef,$sequence)=
5989: &Apache::lonnet::decode_symb($env{'form.selectpage'});
5990:
5991: my $map=$navmap->getResourceByUrl($sequence);
5992:
5993: $r->print('<input type="hidden" name="validate_sequence_exam"
5994: value="ignore" />');
5995: if ($env{'form.validate_sequence_exam'} ne 'ignore') {
5996: my @resources=
5997: $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
5998: if (@resources) {
5999: $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>");
6000: return (1,$currentphase);
6001: }
6002: }
6003:
6004: return (0,$currentphase+1);
6005: }
6006:
6007: =pod
6008:
6009: =item scantron_validate_ID
6010:
6011: Validates all scanlines in the selected file to not have any
6012: invalid or underspecified student IDs
6013:
6014: =cut
6015:
6016: sub scantron_validate_ID {
6017: my ($r,$currentphase) = @_;
6018:
6019: #get student info
6020: my $classlist=&Apache::loncoursedata::get_classlist();
6021: my %idmap=&username_to_idmap($classlist);
6022:
6023: #get scantron line setup
6024: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6025: my ($scanlines,$scan_data)=&scantron_getfile();
6026:
6027: my %found=('ids'=>{},'usernames'=>{});
6028: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6029: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6030: if ($line=~/^[\s\cz]*$/) { next; }
6031: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6032: $scan_data);
6033: my $id=$$scan_record{'scantron.ID'};
6034: my $found;
6035: foreach my $checkid (keys(%idmap)) {
6036: if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
6037: }
6038: if ($found) {
6039: my $username=$idmap{$found};
6040: if ($found{'ids'}{$found}) {
6041: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6042: $line,'duplicateID',$found);
6043: return(1,$currentphase);
6044: } elsif ($found{'usernames'}{$username}) {
6045: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6046: $line,'duplicateID',$username);
6047: return(1,$currentphase);
6048: }
6049: #FIXME store away line we previously saw the ID on to use above
6050: $found{'ids'}{$found}++;
6051: $found{'usernames'}{$username}++;
6052: } else {
6053: if ($id =~ /^\s*$/) {
6054: my $username=&scan_data($scan_data,"$i.user");
6055: if (defined($username) && $found{'usernames'}{$username}) {
6056: &scantron_get_correction($r,$i,$scan_record,
6057: \%scantron_config,
6058: $line,'duplicateID',$username);
6059: return(1,$currentphase);
6060: } elsif (!defined($username)) {
6061: &scantron_get_correction($r,$i,$scan_record,
6062: \%scantron_config,
6063: $line,'incorrectID');
6064: return(1,$currentphase);
6065: }
6066: $found{'usernames'}{$username}++;
6067: } else {
6068: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6069: $line,'incorrectID');
6070: return(1,$currentphase);
6071: }
6072: }
6073: }
6074:
6075: return (0,$currentphase+1);
6076: }
6077:
6078: =pod
6079:
6080: =item scantron_get_correction
6081:
6082: Builds the interface screen to interact with the operator to fix a
6083: specific error condition in a specific scanline
6084:
6085: Arguments:
6086: $r - Apache request object
6087: $i - number of the current scanline
6088: $scan_record - hash ref as returned from &scantron_parse_scanline()
6089: $scan_config - hash ref as returned from &get_scantron_config()
6090: $line - full contents of the current scanline
6091: $error - error condition, valid values are
6092: 'incorrectCODE', 'duplicateCODE',
6093: 'doublebubble', 'missingbubble',
6094: 'duplicateID', 'incorrectID'
6095: $arg - extra information needed
6096: For errors:
6097: - duplicateID - paper number that this studentID was seen before on
6098: - duplicateCODE - array ref of the paper numbers this CODE was
6099: seen on before
6100: - incorrectCODE - current incorrect CODE
6101: - doublebubble - array ref of the bubble lines that have double
6102: bubble errors
6103: - missingbubble - array ref of the bubble lines that have missing
6104: bubble errors
6105:
6106: =cut
6107:
6108: sub scantron_get_correction {
6109: my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
6110:
6111: #FIXME in the case of a duplicated ID the previous line, probaly need
6112: #to show both the current line and the previous one and allow skipping
6113: #the previous one or the current one
6114:
6115: $r->print("<p><b>An error was detected ($error)</b>");
6116: if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
6117: $r->print(" for PaperID <tt>".
6118: $$scan_record{'scantron.PaperID'}."</tt> \n");
6119: } else {
6120: $r->print(" in scanline $i <pre>".
6121: $line."</pre> \n");
6122: }
6123: my $message="<p>The ID on the form is <tt>".
6124: $$scan_record{'scantron.ID'}."</tt><br />\n".
6125: "The name on the paper is ".
6126: $$scan_record{'scantron.LastName'}.",".
6127: $$scan_record{'scantron.FirstName'}."</p>";
6128:
6129: $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
6130: $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
6131: if ($error =~ /ID$/) {
6132: if ($error eq 'incorrectID') {
6133: $r->print("The encoded ID is not in the classlist</p>\n");
6134: } elsif ($error eq 'duplicateID') {
6135: $r->print("The encoded ID has also been used by a previous paper $arg</p>\n");
6136: }
6137: $r->print($message);
6138: $r->print("<p>How should I handle this? <br /> \n");
6139: $r->print("\n<ul><li> ");
6140: #FIXME it would be nice if this sent back the user ID and
6141: #could do partial userID matches
6142: $r->print(&Apache::loncommon::selectstudent_link('scantronupload',
6143: 'scantron_username','scantron_domain'));
6144: $r->print(": <input type='text' name='scantron_username' value='' />");
6145: $r->print("\n@".
6146: &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
6147:
6148: $r->print('</li>');
6149: } elsif ($error =~ /CODE$/) {
6150: if ($error eq 'incorrectCODE') {
6151: $r->print("</p><p>The encoded CODE is not in the list of possible CODEs</p>\n");
6152: } elsif ($error eq 'duplicateCODE') {
6153: $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");
6154: }
6155: $r->print("<p>The CODE on the form is <tt>'".
6156: $$scan_record{'scantron.CODE'}."'</tt><br />\n");
6157: $r->print($message);
6158: $r->print("<p>How should I handle this? <br /> \n");
6159: $r->print("\n<br /> ");
6160: my $i=0;
6161: if ($error eq 'incorrectCODE'
6162: && $$scan_record{'scantron.CODE'}=~/\S/ ) {
6163: my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
6164: if ($closest > 0) {
6165: foreach my $testcode (@{$closest}) {
6166: my $checked='';
6167: if (!$i) { $checked=' checked="checked" '; }
6168: $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' />");
6169: $r->print("\n<br />");
6170: $i++;
6171: }
6172: }
6173: }
6174: if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
6175: my $checked; if (!$i) { $checked=' checked="checked" '; }
6176: $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>");
6177: $r->print("\n<br />");
6178: }
6179:
6180: $r->print(<<ENDSCRIPT);
6181: <script type="text/javascript">
6182: function change_radio(field) {
6183: var slct=document.scantronupload.scantron_CODE_resolution;
6184: var i;
6185: for (i=0;i<slct.length;i++) {
6186: if (slct[i].value==field) { slct[i].checked=true; }
6187: }
6188: }
6189: </script>
6190: ENDSCRIPT
6191: my $href="/adm/pickcode?".
6192: "form=".&escape("scantronupload").
6193: "&scantron_format=".&escape($env{'form.scantron_format'}).
6194: "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
6195: "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
6196: "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
6197: if ($env{'form.scantron_CODElist'} =~ /\S/) {
6198: $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')\" />");
6199: $r->print("\n<br />");
6200: }
6201: $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.");
6202: $r->print("\n<br /><br />");
6203: } elsif ($error eq 'doublebubble') {
6204: $r->print("<p>There have been multiple bubbles scanned for a some question(s)</p>\n");
6205: $r->print('<input type="hidden" name="scantron_questions" value="'.
6206: join(',',@{$arg}).'" />');
6207: $r->print($message);
6208: $r->print("<p>Please indicate which bubble should be used for grading</p>");
6209: foreach my $question (@{$arg}) {
6210: my $selected=$$scan_record{"scantron.$question.answer"};
6211: &scantron_bubble_selector($r,$scan_config,$question,
6212: split('',$selected));
6213: }
6214: } elsif ($error eq 'missingbubble') {
6215: $r->print("<p>There have been <b>no</b> bubbles scanned for some question(s)</p>\n");
6216: $r->print($message);
6217: $r->print("<p>Please indicate which bubble should be used for grading</p>");
6218: $r->print("Some questions have no scanned bubbles\n");
6219: $r->print('<input type="hidden" name="scantron_questions" value="'.
6220: join(',',@{$arg}).'" />');
6221: foreach my $question (@{$arg}) {
6222: my $selected=$$scan_record{"scantron.$question.answer"};
6223: &scantron_bubble_selector($r,$scan_config,$question);
6224: }
6225: } else {
6226: $r->print("\n<ul>");
6227: }
6228: $r->print("\n</li></ul>");
6229:
6230: }
6231:
6232: =pod
6233:
6234: =item scantron_bubble_selector
6235:
6236: Generates the html radiobuttons to correct a single bubble line
6237: possibly showing the existing the selected bubbles if known
6238:
6239: Arguments:
6240: $r - Apache request object
6241: $scan_config - hash from &get_scantron_config()
6242: $quest - number of the bubble line to make a corrector for
6243: $selected - array of letters of previously selected bubbles
6244: $lines - if present, number of bubble lines to show
6245:
6246: =cut
6247:
6248: sub scantron_bubble_selector {
6249: my ($r,$scan_config,$quest,@selected, $lines)=@_;
6250: my $max=$$scan_config{'Qlength'};
6251:
6252: my $scmode=$$scan_config{'Qon'};
6253: if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }
6254:
6255:
6256: if (!defined($lines)) {
6257: $lines = 1;
6258: }
6259: my $total_lines = $lines*2;
6260: my @alphabet=('A'..'Z');
6261: $r->print("<table border='1'><tr><td rowspan='".$total_lines."'>$quest</td>");
6262:
6263: for (my $l = 0; $l < $lines; $l++) {
6264: if ($l != 0) {
6265: $r->print('<tr>');
6266: }
6267:
6268: # FIXME: This loop probably has to be considerably more clever for
6269: # multiline bubbles: User can multibubble by having bubbles in
6270: # several lines. User can skip lines legitimately etc. etc.
6271:
6272: for (my $i=0;$i<$max;$i++) {
6273: $r->print("\n".'<td align="center">');
6274: if ($selected[0] eq $alphabet[$i]) {
6275: $r->print('X');
6276: shift(@selected) ;
6277: } else {
6278: $r->print(' ');
6279: }
6280: $r->print('</td>');
6281:
6282: }
6283:
6284: if ($l == 0) {
6285: my $lspan = $total_lines * 2; # 2 table rows per bubble line.
6286:
6287: $r->print('<td rowspan='.$lspan.'><label><input type="radio" name="scantron_correct_Q_'.
6288: $quest.'" value="none" /> No bubble </label></td>');
6289:
6290: }
6291:
6292: $r->print('</tr><tr>');
6293:
6294: # FIXME: This may have to be a bit more clever for
6295: # multiline questions (different values e.g..).
6296:
6297: for (my $i=0;$i<$max;$i++) {
6298: $r->print("\n".
6299: '<td><label><input type="radio" name="scantron_correct_Q_'.
6300: $quest.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
6301: }
6302: $r->print('</tr>');
6303:
6304:
6305: }
6306: $r->print('</table>');
6307: }
6308:
6309: =pod
6310:
6311: =item num_matches
6312:
6313: Counts the number of characters that are the same between the two arguments.
6314:
6315: Arguments:
6316: $orig - CODE from the scanline
6317: $code - CODE to match against
6318:
6319: Returns:
6320: $count - integer count of the number of same characters between the
6321: two arguments
6322:
6323: =cut
6324:
6325: sub num_matches {
6326: my ($orig,$code) = @_;
6327: my @code=split(//,$code);
6328: my @orig=split(//,$orig);
6329: my $same=0;
6330: for (my $i=0;$i<scalar(@code);$i++) {
6331: if ($code[$i] eq $orig[$i]) { $same++; }
6332: }
6333: return $same;
6334: }
6335:
6336: =pod
6337:
6338: =item scantron_get_closely_matching_CODEs
6339:
6340: Cycles through all CODEs and finds the set that has the greatest
6341: number of same characters as the provided CODE
6342:
6343: Arguments:
6344: $allcodes - hash ref returned by &get_codes()
6345: $CODE - CODE from the current scanline
6346:
6347: Returns:
6348: 2 element list
6349: - first elements is number of how closely matching the best fit is
6350: (5 means best set has 5 matching characters)
6351: - second element is an arrary ref containing the set of valid CODEs
6352: that best fit the passed in CODE
6353:
6354: =cut
6355:
6356: sub scantron_get_closely_matching_CODEs {
6357: my ($allcodes,$CODE)=@_;
6358: my @CODEs;
6359: foreach my $testcode (sort(keys(%{$allcodes}))) {
6360: push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
6361: }
6362:
6363: return ($#CODEs,$CODEs[-1]);
6364: }
6365:
6366: =pod
6367:
6368: =item get_codes
6369:
6370: Builds a hash which has keys of all of the valid CODEs from the selected
6371: set of remembered CODEs.
6372:
6373: Arguments:
6374: $old_name - name of the set of remembered CODEs
6375: $cdom - domain of the course
6376: $cnum - internal course name
6377:
6378: Returns:
6379: %allcodes - keys are the valid CODEs, values are all 1
6380:
6381: =cut
6382:
6383: sub get_codes {
6384: my ($old_name, $cdom, $cnum) = @_;
6385: if (!$old_name) {
6386: $old_name=$env{'form.scantron_CODElist'};
6387: }
6388: if (!$cdom) {
6389: $cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
6390: }
6391: if (!$cnum) {
6392: $cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
6393: }
6394: my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
6395: $cdom,$cnum);
6396: my %allcodes;
6397: if ($result{"type\0$old_name"} eq 'number') {
6398: %allcodes=map {($_,1)} split(',',$result{$old_name});
6399: } else {
6400: %allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
6401: }
6402: return %allcodes;
6403: }
6404:
6405: =pod
6406:
6407: =item scantron_validate_CODE
6408:
6409: Validates all scanlines in the selected file to not have any
6410: invalid or underspecified CODEs and that none of the codes are
6411: duplicated if this was requested.
6412:
6413: =cut
6414:
6415: sub scantron_validate_CODE {
6416: my ($r,$currentphase) = @_;
6417: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6418: if ($scantron_config{'CODElocation'} &&
6419: $scantron_config{'CODEstart'} &&
6420: $scantron_config{'CODElength'}) {
6421: if (!defined($env{'form.scantron_CODElist'})) {
6422: &FIXME_blow_up()
6423: }
6424: } else {
6425: return (0,$currentphase+1);
6426: }
6427:
6428: my %usedCODEs;
6429:
6430: my %allcodes=&get_codes();
6431:
6432: my ($scanlines,$scan_data)=&scantron_getfile();
6433: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6434: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6435: if ($line=~/^[\s\cz]*$/) { next; }
6436: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6437: $scan_data);
6438: my $CODE=$$scan_record{'scantron.CODE'};
6439: my $error=0;
6440: if (!&Apache::lonnet::validCODE($CODE)) {
6441: &scantron_get_correction($r,$i,$scan_record,
6442: \%scantron_config,
6443: $line,'incorrectCODE',\%allcodes);
6444: return(1,$currentphase);
6445: }
6446: if (%allcodes && !exists($allcodes{$CODE})
6447: && !$$scan_record{'scantron.useCODE'}) {
6448: &scantron_get_correction($r,$i,$scan_record,
6449: \%scantron_config,
6450: $line,'incorrectCODE',\%allcodes);
6451: return(1,$currentphase);
6452: }
6453: if (exists($usedCODEs{$CODE})
6454: && $env{'form.scantron_CODEunique'} eq 'yes'
6455: && !$$scan_record{'scantron.CODE_ignore_dup'}) {
6456: &scantron_get_correction($r,$i,$scan_record,
6457: \%scantron_config,
6458: $line,'duplicateCODE',$usedCODEs{$CODE});
6459: return(1,$currentphase);
6460: }
6461: push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
6462: }
6463: return (0,$currentphase+1);
6464: }
6465:
6466: =pod
6467:
6468: =item scantron_validate_doublebubble
6469:
6470: Validates all scanlines in the selected file to not have any
6471: bubble lines with multiple bubbles marked.
6472:
6473: =cut
6474:
6475: sub scantron_validate_doublebubble {
6476: my ($r,$currentphase) = @_;
6477: #get student info
6478: my $classlist=&Apache::loncoursedata::get_classlist();
6479: my %idmap=&username_to_idmap($classlist);
6480:
6481: #get scantron line setup
6482: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6483: my ($scanlines,$scan_data)=&scantron_getfile();
6484: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6485: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6486: if ($line=~/^[\s\cz]*$/) { next; }
6487: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6488: $scan_data);
6489: if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
6490: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
6491: 'doublebubble',
6492: $$scan_record{'scantron.doubleerror'});
6493: return (1,$currentphase);
6494: }
6495: return (0,$currentphase+1);
6496: }
6497:
6498: =pod
6499:
6500: =item scantron_get_maxbubble
6501:
6502: Returns the maximum number of bubble lines that are expected to
6503: occur. Does this by walking the selected sequence rendering the
6504: resource and then checking &Apache::lonxml::get_problem_counter()
6505: for what the current value of the problem counter is.
6506:
6507: Caches the result to $env{'form.scantron_maxbubble'}
6508:
6509: =cut
6510:
6511: sub scantron_get_maxbubble {
6512: if (defined($env{'form.scantron_maxbubble'}) &&
6513: $env{'form.scantron_maxbubble'}) {
6514: return $env{'form.scantron_maxbubble'};
6515: }
6516:
6517: my $navmap=Apache::lonnavmaps::navmap->new();
6518: my (undef,undef,$sequence)=
6519: &Apache::lonnet::decode_symb($env{'form.selectpage'});
6520:
6521: my $map=$navmap->getResourceByUrl($sequence);
6522: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
6523:
6524: &Apache::lonxml::clear_problem_counter();
6525:
6526: foreach my $resource (@resources) {
6527: my $result=&Apache::lonnet::ssi($resource->src(),
6528: ('symb' => $resource->symb()));
6529: }
6530: &Apache::lonnet::delenv('scantron\.');
6531: $env{'form.scantron_maxbubble'} =
6532: &Apache::lonxml::get_problem_counter()-1;
6533:
6534: return $env{'form.scantron_maxbubble'};
6535: }
6536:
6537: =pod
6538:
6539: =item scantron_validate_missingbubbles
6540:
6541: Validates all scanlines in the selected file to not have any
6542: bubble lines with missing bubbles that haven't been verified as missing.
6543:
6544: =cut
6545:
6546: sub scantron_validate_missingbubbles {
6547: my ($r,$currentphase) = @_;
6548: #get student info
6549: my $classlist=&Apache::loncoursedata::get_classlist();
6550: my %idmap=&username_to_idmap($classlist);
6551:
6552: #get scantron line setup
6553: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6554: my ($scanlines,$scan_data)=&scantron_getfile();
6555: my $max_bubble=&scantron_get_maxbubble();
6556: if (!$max_bubble) { $max_bubble=2**31; }
6557: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6558: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6559: if ($line=~/^[\s\cz]*$/) { next; }
6560: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6561: $scan_data);
6562: if (!defined($$scan_record{'scantron.missingerror'})) { next; }
6563: my @to_correct;
6564: foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
6565: if ($missing > $max_bubble) { next; }
6566: push(@to_correct,$missing);
6567: }
6568: if (@to_correct) {
6569: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6570: $line,'missingbubble',\@to_correct);
6571: return (1,$currentphase);
6572: }
6573:
6574: }
6575: return (0,$currentphase+1);
6576: }
6577:
6578: =pod
6579:
6580: =item scantron_process_students
6581:
6582: Routine that does the actual grading of the bubble sheet information.
6583:
6584: The parsed scanline hash is added to %env
6585:
6586: Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
6587: foreach resource , with the form data of
6588:
6589: 'submitted' =>'scantron'
6590: 'grade_target' =>'grade',
6591: 'grade_username'=> username of student
6592: 'grade_domain' => domain of student
6593: 'grade_courseid'=> of course
6594: 'grade_symb' => symb of resource to grade
6595:
6596: This triggers a grading pass. The problem grading code takes care
6597: of converting the bubbled letter information (now in %env) into a
6598: valid submission.
6599:
6600: =cut
6601:
6602: sub scantron_process_students {
6603: my ($r) = @_;
6604: my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
6605: my ($symb)=&get_symb($r);
6606: if (!$symb) {return '';}
6607: my $default_form_data=&defaultFormData($symb);
6608:
6609: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6610: my ($scanlines,$scan_data)=&scantron_getfile();
6611: my $classlist=&Apache::loncoursedata::get_classlist();
6612: my %idmap=&username_to_idmap($classlist);
6613: my $navmap=Apache::lonnavmaps::navmap->new();
6614: my $map=$navmap->getResourceByUrl($sequence);
6615: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
6616: # $r->print("geto ".scalar(@resources)."<br />");
6617: my $result= <<SCANTRONFORM;
6618: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
6619: <input type="hidden" name="command" value="scantron_configphase" />
6620: $default_form_data
6621: SCANTRONFORM
6622: $r->print($result);
6623:
6624: my @delayqueue;
6625: my %completedstudents;
6626:
6627: my $count=&get_todo_count($scanlines,$scan_data);
6628: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
6629: 'Scantron Progress',$count,
6630: 'inline',undef,'scantronupload');
6631: &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
6632: 'Processing first student');
6633: my $start=&Time::HiRes::time();
6634: my $i=-1;
6635: my ($uname,$udom,$started);
6636: while ($i<$scanlines->{'count'}) {
6637: ($uname,$udom)=('','');
6638: $i++;
6639: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6640: if ($line=~/^[\s\cz]*$/) { next; }
6641: if ($started) {
6642: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
6643: 'last student');
6644: }
6645: $started=1;
6646: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6647: $scan_data);
6648: unless ($uname=&scantron_find_student($scan_record,$scan_data,
6649: \%idmap,$i)) {
6650: &scantron_add_delay(\@delayqueue,$line,
6651: 'Unable to find a student that matches',1);
6652: next;
6653: }
6654: if (exists $completedstudents{$uname}) {
6655: &scantron_add_delay(\@delayqueue,$line,
6656: 'Student '.$uname.' has multiple sheets',2);
6657: next;
6658: }
6659: ($uname,$udom)=split(/:/,$uname);
6660:
6661: &Apache::lonxml::clear_problem_counter();
6662: &Apache::lonnet::appenv(%$scan_record);
6663:
6664: if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
6665: &scantron_putfile($scanlines,$scan_data);
6666: }
6667:
6668: my $i=0;
6669: foreach my $resource (@resources) {
6670: $i++;
6671: my %form=('submitted' =>'scantron',
6672: 'grade_target' =>'grade',
6673: 'grade_username'=>$uname,
6674: 'grade_domain' =>$udom,
6675: 'grade_courseid'=>$env{'request.course.id'},
6676: 'grade_symb' =>$resource->symb());
6677: if (exists($scan_record->{'scantron.CODE'})
6678: &&
6679: &Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
6680: $form{'CODE'}=$scan_record->{'scantron.CODE'};
6681: } else {
6682: $form{'CODE'}='';
6683: }
6684: my $result=&Apache::lonnet::ssi($resource->src(),%form);
6685: if ($result ne '') {
6686: &Apache::lonnet::logthis("scantron grading error -> $result");
6687: &Apache::lonnet::logthis("scantron grading error info name $uname domain $udom course $env{'request.course.id'} url ".$resource->src());
6688: }
6689: if (&Apache::loncommon::connection_aborted($r)) { last; }
6690: }
6691: $completedstudents{$uname}={'line'=>$line};
6692: if (&Apache::loncommon::connection_aborted($r)) { last; }
6693: } continue {
6694: &Apache::lonxml::clear_problem_counter();
6695: &Apache::lonnet::delenv('scantron\.');
6696: }
6697: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
6698: # my $lasttime = &Time::HiRes::time()-$start;
6699: # $r->print("<p>took $lasttime</p>");
6700:
6701: $r->print("</form>");
6702: $r->print(&show_grading_menu_form($symb));
6703: return '';
6704: }
6705:
6706: =pod
6707:
6708: =item scantron_upload_scantron_data
6709:
6710: Creates the screen for adding a new bubble sheet data file to a course.
6711:
6712: =cut
6713:
6714: sub scantron_upload_scantron_data {
6715: my ($r)=@_;
6716: $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
6717: my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
6718: 'domainid',
6719: 'coursename');
6720: my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
6721: 'domainid');
6722: my $default_form_data=&defaultFormData(&get_symb($r,1));
6723: $r->print(<<UPLOAD);
6724: <script type="text/javascript" language="javascript">
6725: function checkUpload(formname) {
6726: if (formname.upfile.value == "") {
6727: alert("Please use the browse button to select a file from your local directory.");
6728: return false;
6729: }
6730: formname.submit();
6731: }
6732: </script>
6733:
6734: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
6735: $default_form_data
6736: <table>
6737: <tr><td>$select_link </td></tr>
6738: <tr><td>Course ID: </td><td><input name='courseid' type='text' /> </td></tr>
6739: <tr><td>Course Name: </td><td><input name='coursename' type='text' /></td></tr>
6740: <tr><td>Domain: </td><td>$domsel </td></tr>
6741: <tr><td>File to upload:</td><td><input type="file" name="upfile" size="50" /></td></tr>
6742: </table>
6743: <input name='command' value='scantronupload_save' type='hidden' />
6744: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
6745: </form>
6746: UPLOAD
6747: return '';
6748: }
6749:
6750: =pod
6751:
6752: =item scantron_upload_scantron_data_save
6753:
6754: Adds a provided bubble information data file to the course if user
6755: has the correct privileges to do so.
6756:
6757: =cut
6758:
6759: sub scantron_upload_scantron_data_save {
6760: my($r)=@_;
6761: my ($symb)=&get_symb($r,1);
6762: my $doanotherupload=
6763: '<br /><form action="/adm/grades" method="post">'."\n".
6764: '<input type="hidden" name="command" value="scantronupload" />'."\n".
6765: '<input type="submit" name="submit" value="Do Another Upload" />'."\n".
6766: '</form>'."\n";
6767: if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
6768: !&Apache::lonnet::allowed('usc',
6769: $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
6770: $r->print("You are not allowed to upload Scantron data to the requested course.<br />");
6771: if ($symb) {
6772: $r->print(&show_grading_menu_form($symb));
6773: } else {
6774: $r->print($doanotherupload);
6775: }
6776: return '';
6777: }
6778: my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
6779: $r->print("Doing upload to ".$coursedata{'description'}." <br />");
6780: my $fname=$env{'form.upfile.filename'};
6781: #FIXME
6782: #copied from lonnet::userfileupload()
6783: #make that function able to target a specified course
6784: # Replace Windows backslashes by forward slashes
6785: $fname=~s/\\/\//g;
6786: # Get rid of everything but the actual filename
6787: $fname=~s/^.*\/([^\/]+)$/$1/;
6788: # Replace spaces by underscores
6789: $fname=~s/\s+/\_/g;
6790: # Replace all other weird characters by nothing
6791: $fname=~s/[^\w\.\-]//g;
6792: # See if there is anything left
6793: unless ($fname) { return 'error: no uploaded file'; }
6794: my $uploadedfile=$fname;
6795: $fname='scantron_orig_'.$fname;
6796: if (length($env{'form.upfile'}) < 2) {
6797: $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.");
6798: } else {
6799: my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
6800: if ($result =~ m|^/uploaded/|) {
6801: $r->print("<span class=\"LC_success\">Success:</span> Successfully uploaded ".(length($env{'form.upfile'})-1)." bytes of data into location <tt>".$result."</tt>");
6802: } else {
6803: $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>");
6804: }
6805: }
6806: if ($symb) {
6807: $r->print(&scantron_selectphase($r,$uploadedfile));
6808: } else {
6809: $r->print($doanotherupload);
6810: }
6811: return '';
6812: }
6813:
6814: =pod
6815:
6816: =item valid_file
6817:
6818: Validates that the requested bubble data file exists in the course.
6819:
6820: =cut
6821:
6822: sub valid_file {
6823: my ($requested_file)=@_;
6824: foreach my $filename (sort(&scantron_filenames())) {
6825: if ($requested_file eq $filename) { return 1; }
6826: }
6827: return 0;
6828: }
6829:
6830: =pod
6831:
6832: =item scantron_download_scantron_data
6833:
6834: Shows a list of the three internal files (original, corrected,
6835: skipped) for a specific bubble sheet data file that exists in the
6836: course.
6837:
6838: =cut
6839:
6840: sub scantron_download_scantron_data {
6841: my ($r)=@_;
6842: my $default_form_data=&defaultFormData(&get_symb($r,1));
6843: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6844: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6845: my $file=$env{'form.scantron_selectfile'};
6846: if (! &valid_file($file)) {
6847: $r->print(<<ERROR);
6848: <p>
6849: The requested file name was invalid.
6850: </p>
6851: ERROR
6852: $r->print(&show_grading_menu_form(&get_symb($r,1)));
6853: return;
6854: }
6855: my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
6856: my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
6857: my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
6858: &Apache::lonnet::allowuploaded('/adm/grades',$orig);
6859: &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
6860: &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
6861: $r->print(<<DOWNLOAD);
6862: <p>
6863: <a href="$orig">Original</a> file as uploaded by the scantron office.
6864: </p>
6865: <p>
6866: <a href="$corrected">Corrections</a>, a file of corrected records that were used in grading.
6867: </p>
6868: <p>
6869: <a href="$skipped">Skipped</a>, a file of records that were skipped.
6870: </p>
6871: DOWNLOAD
6872: $r->print(&show_grading_menu_form(&get_symb($r,1)));
6873: return '';
6874: }
6875:
6876: =pod
6877:
6878: =back
6879:
6880: =cut
6881:
6882: #-------- end of section for handling grading scantron forms -------
6883: #
6884: #-------------------------------------------------------------------
6885:
6886: #-------------------------- Menu interface -------------------------
6887: #
6888: #--- Show a Grading Menu button - Calls the next routine ---
6889: sub show_grading_menu_form {
6890: my ($symb)=@_;
6891: my $result.='<br /><form action="/adm/grades" method="post">'."\n".
6892: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
6893: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
6894: '<input type="hidden" name="command" value="gradingmenu" />'."\n".
6895: '<input type="submit" name="submit" value="Grading Menu" />'."\n".
6896: '</form>'."\n";
6897: return $result;
6898: }
6899:
6900: # -- Retrieve choices for grading form
6901: sub savedState {
6902: my %savedState = ();
6903: if ($env{'form.saveState'}) {
6904: foreach (split(/:/,$env{'form.saveState'})) {
6905: my ($key,$value) = split(/=/,$_,2);
6906: $savedState{$key} = $value;
6907: }
6908: }
6909: return \%savedState;
6910: }
6911:
6912: #--- Displays the main menu page -------
6913: sub gradingmenu {
6914: my ($request) = @_;
6915: my ($symb)=&get_symb($request);
6916: if (!$symb) {return '';}
6917: my $probTitle = &Apache::lonnet::gettitle($symb);
6918:
6919: $request->print(<<GRADINGMENUJS);
6920: <script type="text/javascript" language="javascript">
6921: function checkChoice(formname,val,cmdx) {
6922: if (val <= 2) {
6923: var cmd = radioSelection(formname.radioChoice);
6924: var cmdsave = cmd;
6925: } else {
6926: cmd = cmdx;
6927: cmdsave = 'submission';
6928: }
6929: formname.command.value = cmd;
6930: formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
6931: ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
6932: if (val < 5) formname.submit();
6933: if (val == 5) {
6934: if (!checkReceiptNo(formname,'notOK')) { return false;}
6935: formname.submit();
6936: }
6937: if (val < 7) formname.submit();
6938: }
6939:
6940: function checkReceiptNo(formname,nospace) {
6941: var receiptNo = formname.receipt.value;
6942: var checkOpt = false;
6943: if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
6944: if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
6945: if (checkOpt) {
6946: alert("Please enter a receipt number given by a student in the receipt box.");
6947: formname.receipt.value = "";
6948: formname.receipt.focus();
6949: return false;
6950: }
6951: return true;
6952: }
6953: </script>
6954: GRADINGMENUJS
6955: &commonJSfunctions($request);
6956: my $result='<h3> <span class="LC_info">Manual Grading/View Submission</span></h3>';
6957: my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
6958: $result.=$table;
6959: my (undef,$sections) = &getclasslist('all','0');
6960: my $savedState = &savedState();
6961: my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
6962: my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
6963: my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
6964: my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
6965:
6966: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
6967: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
6968: '<input type="hidden" name="handgrade" value="'.$hdgrade.'" />'."\n".
6969: '<input type="hidden" name="probTitle" value="'.$probTitle.'" />'."\n".
6970: '<input type="hidden" name="command" value="" />'."\n".
6971: '<input type="hidden" name="saveState" value="" />'."\n".
6972: '<input type="hidden" name="gradingMenu" value="1" />'."\n".
6973: '<input type="hidden" name="showgrading" value="yes" />'."\n";
6974:
6975: $result.='<table width="100%" border="0"><tr><td bgcolor=#777777>'."\n".
6976: '<table width="100%" border="0"><tr bgcolor="#e6ffff"><td colspan="2">'."\n".
6977: ' <b>Select a Grading/Viewing Option</b></td></tr>'."\n".
6978: '<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
6979:
6980: $result.='<table width="100%" border="0">';
6981: $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
6982: ' '.&mt('Select Section').': <select name="section" multiple="multiple" size="3">'."\n";
6983: if (ref($sections)) {
6984: foreach (sort (@$sections)) {
6985: $result.='<option value="'.$_.'" '.
6986: ($saveSec eq $_ ? 'selected="selected"':'').'>'.$_.'</option>'."\n";
6987: }
6988: }
6989: $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> ';
6990:
6991: $result.=&mt('Student Status').':'.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,undef);
6992:
6993: $result.='</td></tr>';
6994:
6995: $result.='<tr bgcolor="#ffffe6"valign="top"><td><label>'.
6996: '<input type="radio" name="radioChoice" value="submission" '.
6997: ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.'<b>'.&mt('Current Resource').':</b> '.&mt('For one or more students').
6998: '</label> <select name="submitonly">'.
6999: '<option value="yes" '.
7000: ($saveSub eq 'yes' ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>'.
7001: '<option value="queued" '.
7002: ($saveSub eq 'queued' ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>'.
7003: '<option value="graded" '.
7004: ($saveSub eq 'graded' ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>'.
7005: '<option value="incorrect" '.
7006: ($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>'.
7007: '<option value="all" '.
7008: ($saveSub eq 'all' ? 'selected="selected"' : '').'>'.&mt('with any status').'</option></select></td></tr>'."\n";
7009:
7010: $result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
7011: '<label><input type="radio" name="radioChoice" value="viewgrades" '.
7012: ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
7013: '<b>Current Resource:</b> For all students in selected section or course</label></td></tr>'."\n";
7014:
7015: $result.='<tr bgcolor="#ffffe6" valign="top"><td>'.
7016: '<label><input type="radio" name="radioChoice" value="pickStudentPage" '.
7017: ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
7018: 'The <b>complete</b> set/page/sequence: For one student</label></td></tr>'."\n";
7019:
7020: $result.='<tr bgcolor="#ffffe6"><td><br />'.
7021: '<input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="Next->" />'.
7022: '</td></tr></table>'."\n";
7023:
7024: $result.='</td><td valign="top">';
7025:
7026: $result.='<table width="100%" border="0">';
7027: $result.='<tr bgcolor="#ffffe6"><td>'.
7028: '<input type="button" onClick="javascript:checkChoice(this.form,\'3\',\'csvform\');" value="'.&mt('Upload').'" />'.
7029: ' '.&mt('scores from file').' </td></tr>'."\n";
7030:
7031: $result.='<tr bgcolor="#ffffe6"><td>'.
7032: '<input type="button" onClick="javascript:checkChoice(this.form,\'6\',\'processclicker\');" value="'.&mt('Process').'" />'.
7033: ' '.&mt('clicker file').' </td></tr>'."\n";
7034:
7035: $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
7036: '<input type="button" onClick="javascript:checkChoice(this.form,\'4\',\'scantron_selectphase\');'.
7037: '" value="'.&mt('Grade').'" /> scantron forms</td></tr>'."\n";
7038:
7039: if ((&Apache::lonnet::allowed('mgr',$env{'request.course.id'})) && ($symb)) {
7040: $result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
7041: '<input type="button" onClick="javascript:checkChoice(this.form,\'5\',\'verify\');" value="'.&mt('Verify').'" />'.
7042: ' '.&mt('receipt').': '.
7043: &Apache::lonnet::recprefix($env{'request.course.id'}).
7044: '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />'.
7045: '</td></tr>'."\n";
7046: }
7047: $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
7048: '<input type="button" onClick="javascript:this.form.action=\'/adm/helper/resettimes.helper\';this.form.submit();'.
7049: '" value="'.&mt('Manage').'" /> access times.</td></tr>'."\n";
7050: $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
7051: '<input type="button" onClick="javascript:this.form.command.value=\'codelist\';this.form.action=\'/adm/pickcode\';this.form.submit();'.
7052: '" value="'.&mt('View').'" /> saved CODEs.</td></tr>'."\n";
7053:
7054: $result.='</table>'."\n".
7055: '</td></tr></table>'."\n".
7056: '</td></tr></table></form>'."\n";
7057: return $result;
7058: }
7059:
7060: sub reset_perm {
7061: undef(%perm);
7062: }
7063:
7064: sub init_perm {
7065: &reset_perm();
7066: foreach my $test_perm ('vgr','mgr','opa') {
7067:
7068: my $scope = $env{'request.course.id'};
7069: if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
7070:
7071: $scope .= '/'.$env{'request.course.sec'};
7072: if ( $perm{$test_perm}=
7073: &Apache::lonnet::allowed($test_perm,$scope)) {
7074: $perm{$test_perm.'_section'}=$env{'request.course.sec'};
7075: } else {
7076: delete($perm{$test_perm});
7077: }
7078: }
7079: }
7080: }
7081:
7082: sub gather_clicker_ids {
7083: my %clicker_ids;
7084:
7085: my $classlist = &Apache::loncoursedata::get_classlist();
7086:
7087: # Set up a couple variables.
7088: my $username_idx = &Apache::loncoursedata::CL_SNAME();
7089: my $domain_idx = &Apache::loncoursedata::CL_SDOM();
7090:
7091: foreach my $student (keys(%$classlist)) {
7092:
7093: my $username = $classlist->{$student}->[$username_idx];
7094: my $domain = $classlist->{$student}->[$domain_idx];
7095: my $clickers =
7096: (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
7097: foreach my $id (split(/\,/,$clickers)) {
7098: $id=~s/^[\#0]+//;
7099: $id=~s/[\-\:]//g;
7100: if (exists($clicker_ids{$id})) {
7101: $clicker_ids{$id}.=','.$username.':'.$domain;
7102: } else {
7103: $clicker_ids{$id}=$username.':'.$domain;
7104: }
7105: }
7106: }
7107: return %clicker_ids;
7108: }
7109:
7110: sub gather_adv_clicker_ids {
7111: my %clicker_ids;
7112: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
7113: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7114: my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
7115: foreach my $element (sort(keys(%coursepersonnel))) {
7116: foreach my $person (split(/\,/,$coursepersonnel{$element})) {
7117: my ($puname,$pudom)=split(/\:/,$person);
7118: my $clickers =
7119: (&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
7120: foreach my $id (split(/\,/,$clickers)) {
7121: $id=~s/^[\#0]+//;
7122: $id=~s/[\-\:]//g;
7123: if (exists($clicker_ids{$id})) {
7124: $clicker_ids{$id}.=','.$puname.':'.$pudom;
7125: } else {
7126: $clicker_ids{$id}=$puname.':'.$pudom;
7127: }
7128: }
7129: }
7130: }
7131: return %clicker_ids;
7132: }
7133:
7134: sub clicker_grading_parameters {
7135: return ('gradingmechanism' => 'scalar',
7136: 'upfiletype' => 'scalar',
7137: 'specificid' => 'scalar',
7138: 'pcorrect' => 'scalar',
7139: 'pincorrect' => 'scalar');
7140: }
7141:
7142: sub process_clicker {
7143: my ($r)=@_;
7144: my ($symb)=&get_symb($r);
7145: if (!$symb) {return '';}
7146: my $result=&checkforfile_js();
7147: $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
7148: my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
7149: $result.=$table;
7150: $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
7151: $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
7152: $result.=' <b>'.&mt('Specify a file containing the clicker information for this resource').
7153: '.</b></td></tr>'."\n";
7154: $result.='<tr bgcolor=#ffffe6><td>'."\n";
7155: # Attempt to restore parameters from last session, set defaults if not present
7156: my %Saveable_Parameters=&clicker_grading_parameters();
7157: &Apache::loncommon::restore_course_settings('grades_clicker',
7158: \%Saveable_Parameters);
7159: if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
7160: if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
7161: if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
7162: if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
7163:
7164: my %checked;
7165: foreach my $gradingmechanism ('attendance','personnel','specific') {
7166: if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
7167: $checked{$gradingmechanism}="checked='checked'";
7168: }
7169: }
7170:
7171: my $upload=&mt("Upload File");
7172: my $type=&mt("Type");
7173: my $attendance=&mt("Award points just for participation");
7174: my $personnel=&mt("Correctness determined from response by course personnel");
7175: my $specific=&mt("Correctness determined from response with clicker ID(s)");
7176: my $pcorrect=&mt("Percentage points for correct solution");
7177: my $pincorrect=&mt("Percentage points for incorrect solution");
7178: my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
7179: ('iclicker' => 'i>clicker',
7180: 'interwrite' => 'interwrite PRS'));
7181: $symb = &Apache::lonenc::check_encrypt($symb);
7182: $result.=<<ENDUPFORM;
7183: <script type="text/javascript">
7184: function sanitycheck() {
7185: // Accept only integer percentages
7186: document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
7187: document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
7188: // Find out grading choice
7189: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
7190: if (document.forms.gradesupload.gradingmechanism[i].checked) {
7191: gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
7192: }
7193: }
7194: // By default, new choice equals user selection
7195: newgradingchoice=gradingchoice;
7196: // Not good to give more points for false answers than correct ones
7197: if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
7198: document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
7199: }
7200: // If new choice is attendance only, and old choice was correctness-based, restore defaults
7201: if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
7202: document.forms.gradesupload.pcorrect.value=100;
7203: document.forms.gradesupload.pincorrect.value=100;
7204: }
7205: // If the values are different, cannot be attendance only
7206: if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
7207: (gradingchoice=='attendance')) {
7208: newgradingchoice='personnel';
7209: }
7210: // Change grading choice to new one
7211: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
7212: if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
7213: document.forms.gradesupload.gradingmechanism[i].checked=true;
7214: } else {
7215: document.forms.gradesupload.gradingmechanism[i].checked=false;
7216: }
7217: }
7218: // Remember the old state
7219: document.forms.gradesupload.waschecked.value=newgradingchoice;
7220: }
7221: </script>
7222: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
7223: <input type="hidden" name="symb" value="$symb" />
7224: <input type="hidden" name="command" value="processclickerfile" />
7225: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
7226: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
7227: <input type="file" name="upfile" size="50" />
7228: <br /><label>$type: $selectform</label>
7229: <br /><label>$attendance: <input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" /></label>
7230: <br /><label>$personnel: <input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" /></label>
7231: <br /><label>$specific: <input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" /></label>
7232: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
7233: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
7234: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
7235: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
7236: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
7237: </form>
7238: ENDUPFORM
7239: $result.='</td></tr></table>'."\n".
7240: '</td></tr></table><br /><br />'."\n";
7241: $result.=&show_grading_menu_form($symb);
7242: return $result;
7243: }
7244:
7245: sub process_clicker_file {
7246: my ($r)=@_;
7247: my ($symb)=&get_symb($r);
7248: if (!$symb) {return '';}
7249:
7250: my %Saveable_Parameters=&clicker_grading_parameters();
7251: &Apache::loncommon::store_course_settings('grades_clicker',
7252: \%Saveable_Parameters);
7253:
7254: my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
7255: if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
7256: $result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
7257: return $result.&show_grading_menu_form($symb);
7258: }
7259: my %clicker_ids=&gather_clicker_ids();
7260: my %correct_ids;
7261: if ($env{'form.gradingmechanism'} eq 'personnel') {
7262: %correct_ids=&gather_adv_clicker_ids();
7263: }
7264: if ($env{'form.gradingmechanism'} eq 'specific') {
7265: foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
7266: $correct_id=~tr/a-z/A-Z/;
7267: $correct_id=~s/\s//gs;
7268: $correct_id=~s/^[\#0]+//;
7269: $correct_id=~s/[\-\:]//g;
7270: if ($correct_id) {
7271: $correct_ids{$correct_id}='specified';
7272: }
7273: }
7274: }
7275: if ($env{'form.gradingmechanism'} eq 'attendance') {
7276: $result.=&mt('Score based on attendance only');
7277: } else {
7278: my $number=0;
7279: $result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
7280: foreach my $id (sort(keys(%correct_ids))) {
7281: $result.='<br /><tt>'.$id.'</tt> - ';
7282: if ($correct_ids{$id} eq 'specified') {
7283: $result.=&mt('specified');
7284: } else {
7285: my ($uname,$udom)=split(/\:/,$correct_ids{$id});
7286: $result.=&Apache::loncommon::plainname($uname,$udom);
7287: }
7288: $number++;
7289: }
7290: $result.="</p>\n";
7291: if ($number==0) {
7292: $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
7293: return $result.&show_grading_menu_form($symb);
7294: }
7295: }
7296: if (length($env{'form.upfile'}) < 2) {
7297: $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
7298: '<span class="LC_error">',
7299: '</span>',
7300: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
7301: return $result.&show_grading_menu_form($symb);
7302: }
7303:
7304: # Were able to get all the info needed, now analyze the file
7305:
7306: $result.=&Apache::loncommon::studentbrowser_javascript();
7307: $symb = &Apache::lonenc::check_encrypt($symb);
7308: my $heading=&mt('Scanning clicker file');
7309: $result.=(<<ENDHEADER);
7310: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
7311: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
7312: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
7313: <form method="post" action="/adm/grades" name="clickeranalysis">
7314: <input type="hidden" name="symb" value="$symb" />
7315: <input type="hidden" name="command" value="assignclickergrades" />
7316: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
7317: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
7318: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
7319: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
7320: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
7321: ENDHEADER
7322: my %responses;
7323: my @questiontitles;
7324: my $errormsg='';
7325: my $number=0;
7326: if ($env{'form.upfiletype'} eq 'iclicker') {
7327: ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
7328: }
7329: if ($env{'form.upfiletype'} eq 'interwrite') {
7330: ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
7331: }
7332: $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
7333: '<input type="hidden" name="number" value="'.$number.'" />'.
7334: &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
7335: $env{'form.pcorrect'},$env{'form.pincorrect'}).
7336: '<br />';
7337: # Remember Question Titles
7338: # FIXME: Possibly need delimiter other than ":"
7339: for (my $i=0;$i<$number;$i++) {
7340: $result.='<input type="hidden" name="question:'.$i.'" value="'.
7341: &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
7342: }
7343: my $correct_count=0;
7344: my $student_count=0;
7345: my $unknown_count=0;
7346: # Match answers with usernames
7347: # FIXME: Possibly need delimiter other than ":"
7348: foreach my $id (keys(%responses)) {
7349: if ($correct_ids{$id}) {
7350: $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
7351: $correct_count++;
7352: } elsif ($clicker_ids{$id}) {
7353: $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
7354: $student_count++;
7355: } else {
7356: $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
7357: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
7358: "\n".&mt("Username").": <input type='text' name='uname".$id."' /> ".
7359: "\n".&mt("Domain").": ".
7360: &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).' '.
7361: &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
7362: $unknown_count++;
7363: }
7364: }
7365: $result.='<hr />'.
7366: &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
7367: if ($env{'form.gradingmechanism'} ne 'attendance') {
7368: if ($correct_count==0) {
7369: $errormsg.="Found no correct answers answers for grading!";
7370: } elsif ($correct_count>1) {
7371: $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
7372: }
7373: }
7374: if ($number<1) {
7375: $errormsg.="Found no questions.";
7376: }
7377: if ($errormsg) {
7378: $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
7379: } else {
7380: $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
7381: }
7382: $result.='</form></td></tr></table>'."\n".
7383: '</td></tr></table><br /><br />'."\n";
7384: return $result.&show_grading_menu_form($symb);
7385: }
7386:
7387: sub iclicker_eval {
7388: my ($questiontitles,$responses)=@_;
7389: my $number=0;
7390: my $errormsg='';
7391: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
7392: my %components=&Apache::loncommon::record_sep($line);
7393: my @entries=map {$components{$_}} (sort(keys(%components)));
7394: if ($entries[0] eq 'Question') {
7395: for (my $i=3;$i<$#entries;$i+=6) {
7396: $$questiontitles[$number]=$entries[$i];
7397: $number++;
7398: }
7399: }
7400: if ($entries[0]=~/^\#/) {
7401: my $id=$entries[0];
7402: my @idresponses;
7403: $id=~s/^[\#0]+//;
7404: for (my $i=0;$i<$number;$i++) {
7405: my $idx=3+$i*6;
7406: push(@idresponses,$entries[$idx]);
7407: }
7408: $$responses{$id}=join(',',@idresponses);
7409: }
7410: }
7411: return ($errormsg,$number);
7412: }
7413:
7414: sub interwrite_eval {
7415: my ($questiontitles,$responses)=@_;
7416: my $number=0;
7417: my $errormsg='';
7418: my $skipline=1;
7419: my $questionnumber=0;
7420: my %idresponses=();
7421: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
7422: my %components=&Apache::loncommon::record_sep($line);
7423: my @entries=map {$components{$_}} (sort(keys(%components)));
7424: if ($entries[1] eq 'Time') { $skipline=0; next; }
7425: if ($entries[1] eq 'Response') { $skipline=1; }
7426: next if $skipline;
7427: if ($entries[0]!=$questionnumber) {
7428: $questionnumber=$entries[0];
7429: $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
7430: $number++;
7431: }
7432: my $id=$entries[4];
7433: $id=~s/^[\#0]+//;
7434: $id=~s/^v\d*\://i;
7435: $id=~s/[\-\:]//g;
7436: $idresponses{$id}[$number]=$entries[6];
7437: }
7438: foreach my $id (keys %idresponses) {
7439: $$responses{$id}=join(',',@{$idresponses{$id}});
7440: $$responses{$id}=~s/^\s*\,//;
7441: }
7442: return ($errormsg,$number);
7443: }
7444:
7445: sub assign_clicker_grades {
7446: my ($r)=@_;
7447: my ($symb)=&get_symb($r);
7448: if (!$symb) {return '';}
7449: # See which part we are saving to
7450: my ($partlist,$handgrade,$responseType) = &response_type($symb);
7451: # FIXME: This should probably look for the first handgradeable part
7452: my $part=$$partlist[0];
7453: # Start screen output
7454: my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
7455:
7456: my $heading=&mt('Assigning grades based on clicker file');
7457: $result.=(<<ENDHEADER);
7458: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
7459: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
7460: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
7461: ENDHEADER
7462: # Get correct result
7463: # FIXME: Possibly need delimiter other than ":"
7464: my @correct=();
7465: my $gradingmechanism=$env{'form.gradingmechanism'};
7466: my $number=$env{'form.number'};
7467: if ($gradingmechanism ne 'attendance') {
7468: foreach my $key (keys(%env)) {
7469: if ($key=~/^form\.correct\:/) {
7470: my @input=split(/\,/,$env{$key});
7471: for (my $i=0;$i<=$#input;$i++) {
7472: if (($correct[$i]) && ($input[$i]) &&
7473: ($correct[$i] ne $input[$i])) {
7474: $result.='<br /><span class="LC_warning">'.
7475: &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
7476: $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
7477: } elsif ($input[$i]) {
7478: $correct[$i]=$input[$i];
7479: }
7480: }
7481: }
7482: }
7483: for (my $i=0;$i<$number;$i++) {
7484: if (!$correct[$i]) {
7485: $result.='<br /><span class="LC_error">'.
7486: &mt('No correct result given for question "[_1]"!',
7487: $env{'form.question:'.$i}).'</span>';
7488: }
7489: }
7490: $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
7491: }
7492: # Start grading
7493: my $pcorrect=$env{'form.pcorrect'};
7494: my $pincorrect=$env{'form.pincorrect'};
7495: my $storecount=0;
7496: foreach my $key (keys(%env)) {
7497: my $user='';
7498: if ($key=~/^form\.student\:(.*)$/) {
7499: $user=$1;
7500: }
7501: if ($key=~/^form\.unknown\:(.*)$/) {
7502: my $id=$1;
7503: if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
7504: $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
7505: }
7506: }
7507: if ($user) {
7508: my @answer=split(/\,/,$env{$key});
7509: my $sum=0;
7510: for (my $i=0;$i<$number;$i++) {
7511: if ($answer[$i]) {
7512: if ($gradingmechanism eq 'attendance') {
7513: $sum+=$pcorrect;
7514: } else {
7515: if ($answer[$i] eq $correct[$i]) {
7516: $sum+=$pcorrect;
7517: } else {
7518: $sum+=$pincorrect;
7519: }
7520: }
7521: }
7522: }
7523: my $ave=$sum/(100*$number);
7524: # Store
7525: my ($username,$domain)=split(/\:/,$user);
7526: my %grades=();
7527: $grades{"resource.$part.solved"}='correct_by_override';
7528: $grades{"resource.$part.awarded"}=$ave;
7529: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
7530: my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
7531: $env{'request.course.id'},
7532: $domain,$username);
7533: if ($returncode ne 'ok') {
7534: $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
7535: } else {
7536: $storecount++;
7537: }
7538: }
7539: }
7540: # We are done
7541: $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
7542: '</td></tr></table>'."\n".
7543: '</td></tr></table><br /><br />'."\n";
7544: return $result.&show_grading_menu_form($symb);
7545: }
7546:
7547: sub handler {
7548: my $request=$_[0];
7549:
7550: &reset_caches();
7551: if ($env{'browser.mathml'}) {
7552: &Apache::loncommon::content_type($request,'text/xml');
7553: } else {
7554: &Apache::loncommon::content_type($request,'text/html');
7555: }
7556: $request->send_http_header;
7557: return '' if $request->header_only;
7558: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
7559: my $symb=&get_symb($request,1);
7560: my @commands=&Apache::loncommon::get_env_multiple('form.command');
7561: my $command=$commands[0];
7562: if ($#commands > 0) {
7563: &Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
7564: }
7565: $request->print(&Apache::loncommon::start_page('Grading'));
7566: if ($symb eq '' && $command eq '') {
7567: if ($env{'user.adv'}) {
7568: if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
7569: ($env{'form.codethree'})) {
7570: my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
7571: $env{'form.codethree'};
7572: my ($tsymb,$tuname,$tudom,$tcrsid)=
7573: &Apache::lonnet::checkin($token);
7574: if ($tsymb) {
7575: my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
7576: if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
7577: $request->print(&Apache::lonnet::ssi_body('/res/'.$url,
7578: ('grade_username' => $tuname,
7579: 'grade_domain' => $tudom,
7580: 'grade_courseid' => $tcrsid,
7581: 'grade_symb' => $tsymb)));
7582: } else {
7583: $request->print('<h3>Not authorized: '.$token.'</h3>');
7584: }
7585: } else {
7586: $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
7587: }
7588: } else {
7589: $request->print(&Apache::lonxml::tokeninputfield());
7590: }
7591: }
7592: } else {
7593: &init_perm();
7594: if ($command eq 'submission' && $perm{'vgr'}) {
7595: ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
7596: } elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
7597: &pickStudentPage($request);
7598: } elsif ($command eq 'displayPage' && $perm{'vgr'}) {
7599: &displayPage($request);
7600: } elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
7601: &updateGradeByPage($request);
7602: } elsif ($command eq 'processGroup' && $perm{'vgr'}) {
7603: &processGroup($request);
7604: } elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
7605: $request->print(&gradingmenu($request));
7606: } elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
7607: $request->print(&viewgrades($request));
7608: } elsif ($command eq 'handgrade' && $perm{'mgr'}) {
7609: $request->print(&processHandGrade($request));
7610: } elsif ($command eq 'editgrades' && $perm{'mgr'}) {
7611: $request->print(&editgrades($request));
7612: } elsif ($command eq 'verify' && $perm{'vgr'}) {
7613: $request->print(&verifyreceipt($request));
7614: } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
7615: $request->print(&process_clicker($request));
7616: } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
7617: $request->print(&process_clicker_file($request));
7618: } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
7619: $request->print(&assign_clicker_grades($request));
7620: } elsif ($command eq 'csvform' && $perm{'mgr'}) {
7621: $request->print(&upcsvScores_form($request));
7622: } elsif ($command eq 'csvupload' && $perm{'mgr'}) {
7623: $request->print(&csvupload($request));
7624: } elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
7625: $request->print(&csvuploadmap($request));
7626: } elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
7627: if ($env{'form.associate'} ne 'Reverse Association') {
7628: $request->print(&csvuploadoptions($request));
7629: } else {
7630: if ( $env{'form.upfile_associate'} ne 'reverse' ) {
7631: $env{'form.upfile_associate'} = 'reverse';
7632: } else {
7633: $env{'form.upfile_associate'} = 'forward';
7634: }
7635: $request->print(&csvuploadmap($request));
7636: }
7637: } elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
7638: $request->print(&csvuploadassign($request));
7639: } elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
7640: $request->print(&scantron_selectphase($request));
7641: } elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
7642: $request->print(&scantron_do_warning($request));
7643: } elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
7644: $request->print(&scantron_validate_file($request));
7645: } elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
7646: $request->print(&scantron_process_students($request));
7647: } elsif ($command eq 'scantronupload' &&
7648: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
7649: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
7650: $request->print(&scantron_upload_scantron_data($request));
7651: } elsif ($command eq 'scantronupload_save' &&
7652: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
7653: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
7654: $request->print(&scantron_upload_scantron_data_save($request));
7655: } elsif ($command eq 'scantron_download' &&
7656: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
7657: $request->print(&scantron_download_scantron_data($request));
7658: } elsif ($command) {
7659: $request->print("Access Denied ($command)");
7660: }
7661: }
7662: $request->print(&Apache::loncommon::end_page());
7663: &reset_caches();
7664: return '';
7665: }
7666:
7667: 1;
7668:
7669: __END__;
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>