1: # The LearningOnline Network with CAPA
2: # The LON-CAPA Grading handler
3: #
4: # $Id: grades.pm,v 1.408 2007/06/15 22:12:49 albertel Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28:
29: package Apache::grades;
30: use strict;
31: use Apache::style;
32: use Apache::lonxml;
33: use Apache::lonnet;
34: use Apache::loncommon;
35: use Apache::lonhtmlcommon;
36: use Apache::lonnavmaps;
37: use Apache::lonhomework;
38: use Apache::loncoursedata;
39: use Apache::lonmsg();
40: use Apache::Constants qw(:common);
41: use Apache::lonlocal;
42: use Apache::lonenc;
43: use String::Similarity;
44: use LONCAPA;
45:
46: use POSIX qw(floor);
47:
48: my %oldessays=();
49: my %perm=();
50:
51: # ----- These first few routines are general use routines.----
52: #
53: # --- Retrieve the parts from the metadata file.---
54: sub getpartlist {
55: my ($symb) = @_;
56: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
57: my $partorder = &Apache::lonnet::metadata($url, 'partorder');
58: my @parts;
59: if ($partorder) {
60: for my $part (split (/,/,$partorder)) {
61: if (!&Apache::loncommon::check_if_partid_hidden($part,$symb)) {
62: push(@parts, $part);
63: }
64: }
65: } else {
66: my $metadata = &Apache::lonnet::metadata($url, 'packages');
67: foreach (split(/\,/,$metadata)) {
68: if ($_ =~ /^part_(.*)$/) {
69: if (!&Apache::loncommon::check_if_partid_hidden($1,$symb)) {
70: push(@parts, $1);
71: }
72: }
73: }
74: }
75: my @stores;
76: foreach my $part (@parts) {
77: my (@metakeys) = split(/,/,&Apache::lonnet::metadata($url,'keys'));
78: foreach my $key (@metakeys) {
79: if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
80: }
81: }
82: return @stores;
83: }
84:
85: # --- Get the symbolic name of a problem and the url
86: sub get_symb {
87: my ($request,$silent) = @_;
88: (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
89: my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
90: if ($symb eq '') {
91: if (!$silent) {
92: $request->print("Unable to handle ambiguous references:$url:.");
93: return ();
94: }
95: }
96: return ($symb);
97: }
98:
99: #--- Format fullname, username:domain if different for display
100: #--- Use anywhere where the student names are listed
101: sub nameUserString {
102: my ($type,$fullname,$uname,$udom) = @_;
103: if ($type eq 'header') {
104: return '<b> Fullname </b><span class="LC_internal_info">(Username)</span>';
105: } else {
106: return ' '.$fullname.'<span class="LC_internal_info"> ('.$uname.
107: ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
108: }
109: }
110:
111: #--- Get the partlist and the response type for a given problem. ---
112: #--- Indicate if a response type is coded handgraded or not. ---
113: sub response_type {
114: my ($symb) = shift;
115:
116: my $navmap = Apache::lonnavmaps::navmap->new();
117: my $res = $navmap->getBySymb($symb);
118: my $partlist = $res->parts();
119: my %vPart =
120: map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
121: my (%response_types,%handgrade);
122: foreach my $part (@{ $partlist }) {
123: next if (%vPart && !exists($vPart{$part}));
124:
125: my @types = $res->responseType($part);
126: my @ids = $res->responseIds($part);
127: for (my $i=0; $i < scalar(@ids); $i++) {
128: $response_types{$part}{$ids[$i]} = $types[$i];
129: $handgrade{$part.'_'.$ids[$i]} =
130: &Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
131: '.handgrade',$symb);
132: }
133: }
134: return ($partlist,\%handgrade,\%response_types);
135: }
136:
137: sub flatten_responseType {
138: my ($responseType) = @_;
139: my @part_response_id =
140: map {
141: my $part = $_;
142: map {
143: [$part,$_]
144: } sort(keys(%{ $responseType->{$part} }));
145: } sort(keys(%$responseType));
146: return @part_response_id;
147: }
148:
149: sub get_display_part {
150: my ($partID,$symb)=@_;
151: my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
152: if (defined($display) and $display ne '') {
153: $display.= " (<span class=\"LC_internal_info\">id $partID</span>)";
154: } else {
155: $display=$partID;
156: }
157: return $display;
158: }
159:
160: #--- Show resource title
161: #--- and parts and response type
162: sub showResourceInfo {
163: my ($symb,$probTitle,$checkboxes) = @_;
164: my $col=3;
165: if ($checkboxes) { $col=4; }
166: my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
167: $result .='<table border="0">';
168: my ($partlist,$handgrade,$responseType) = &response_type($symb);
169: my %resptype = ();
170: my $hdgrade='no';
171: my %partsseen;
172: foreach my $partID (sort keys(%$responseType)) {
173: foreach my $resID (sort keys(%{ $responseType->{$partID} })) {
174: my $handgrade=$$handgrade{$partID.'_'.$resID};
175: my $responsetype = $responseType->{$partID}->{$resID};
176: $hdgrade = $handgrade if ($handgrade eq 'yes');
177: $result.='<tr>';
178: if ($checkboxes) {
179: if (exists($partsseen{$partID})) {
180: $result.="<td> </td>";
181: } else {
182: $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
183: }
184: $partsseen{$partID}=1;
185: }
186: my $display_part=&get_display_part($partID,$symb);
187: $result.='<td><b>Part: </b>'.$display_part.' <span class="LC_internal_info">'.
188: $resID.'</span></td>'.
189: '<td><b>Type: </b>'.$responsetype.'</td></tr>';
190: # '<td><b>Handgrade: </b>'.$handgrade.'</td></tr>';
191: }
192: }
193: $result.='</table>'."\n";
194: return $result,$responseType,$hdgrade,$partlist,$handgrade;
195: }
196:
197:
198: sub get_order {
199: my ($partid,$respid,$symb,$uname,$udom)=@_;
200: my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
201: $url=&Apache::lonnet::clutter($url);
202: my $subresult=&Apache::lonnet::ssi($url,
203: ('grade_target' => 'analyze'),
204: ('grade_domain' => $udom),
205: ('grade_symb' => $symb),
206: ('grade_courseid' =>
207: $env{'request.course.id'}),
208: ('grade_username' => $uname));
209: (undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
210: my %analyze=&Apache::lonnet::str2hash($subresult);
211: return ($analyze{"$partid.$respid.shown"});
212: }
213: #--- Clean response type for display
214: #--- Currently filters option/rank/radiobutton/match/essay/Task
215: # response types only.
216: sub cleanRecord {
217: my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
218: $uname,$udom) = @_;
219: my $grayFont = '<span class="LC_internal_info">';
220: if ($response =~ /^(option|rank)$/) {
221: my %answer=&Apache::lonnet::str2hash($answer);
222: my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
223: my ($toprow,$bottomrow);
224: foreach my $foil (@$order) {
225: if ($grading{$foil} == 1) {
226: $toprow.='<td><b>'.$answer{$foil}.' </b></td>';
227: } else {
228: $toprow.='<td><i>'.$answer{$foil}.' </i></td>';
229: }
230: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
231: }
232: return '<blockquote><table border="1">'.
233: '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
234: '<tr valign="top"><td>'.$grayFont.'Option ID</span></td>'.
235: $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
236: } elsif ($response eq 'match') {
237: my %answer=&Apache::lonnet::str2hash($answer);
238: my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
239: my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
240: my ($toprow,$middlerow,$bottomrow);
241: foreach my $foil (@$order) {
242: my $item=shift(@items);
243: if ($grading{$foil} == 1) {
244: $toprow.='<td><b>'.$item.' </b></td>';
245: $middlerow.='<td><b>'.$grayFont.$answer{$foil}.' </span></b></td>';
246: } else {
247: $toprow.='<td><i>'.$item.' </i></td>';
248: $middlerow.='<td><i>'.$grayFont.$answer{$foil}.' </span></i></td>';
249: }
250: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
251: }
252: return '<blockquote><table border="1">'.
253: '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
254: '<tr valign="top"><td>'.$grayFont.'Item ID</span></td>'.
255: $middlerow.'</tr>'.
256: '<tr valign="top"><td>'.$grayFont.'Option ID</span></td>'.
257: $bottomrow.'</tr>'.'</table></blockquote>';
258: } elsif ($response eq 'radiobutton') {
259: my %answer=&Apache::lonnet::str2hash($answer);
260: my ($toprow,$bottomrow);
261: my $correct=($order->[0])+1;
262: for (my $i=1;$i<=$#$order;$i++) {
263: my $foil=$order->[$i];
264: if (exists($answer{$foil})) {
265: if ($i == $correct) {
266: $toprow.='<td><b>true</b></td>';
267: } else {
268: $toprow.='<td><i>true</i></td>';
269: }
270: } else {
271: $toprow.='<td>false</td>';
272: }
273: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
274: }
275: return '<blockquote><table border="1">'.
276: '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
277: '<tr valign="top"><td>'.$grayFont.'Option ID</span></td>'.
278: $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
279: } elsif ($response eq 'essay') {
280: if (! exists ($env{'form.'.$symb})) {
281: my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
282: $env{'course.'.$env{'request.course.id'}.'.domain'},
283: $env{'course.'.$env{'request.course.id'}.'.num'});
284:
285: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
286: $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
287: $env{'form.kwclr'} = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
288: $env{'form.kwsize'} = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
289: $env{'form.kwstyle'} = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
290: $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
291: }
292: $answer =~ s-\n-<br />-g;
293: return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
294: } elsif ( $response eq 'organic') {
295: my $result='Smile representation: "<tt>'.$answer.'</tt>"';
296: my $jme=$record->{$version."resource.$partid.$respid.molecule"};
297: $result.=&Apache::chemresponse::jme_img($jme,$answer,400);
298: return $result;
299: } elsif ( $response eq 'Task') {
300: if ( $answer eq 'SUBMITTED') {
301: my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
302: my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
303: return $result;
304: } elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
305: my @matches = grep(/^\Q$version\E.*?\.instance$/,
306: keys(%{$record}));
307: return join('<br />',($version,@matches));
308:
309:
310: } else {
311: my $result =
312: '<p>'
313: .&mt('Overall result: [_1]',
314: $record->{$version."resource.$respid.$partid.status"})
315: .'</p>';
316:
317: $result .= '<ul>';
318: my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
319: keys(%{$record}));
320: foreach my $grade (sort(@grade)) {
321: my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
322: $result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
323: $dim, $record->{$grade}).
324: '</li>';
325: }
326: $result.='</ul>';
327: return $result;
328: }
329:
330: }
331: return $answer;
332: }
333:
334: #-- A couple of common js functions
335: sub commonJSfunctions {
336: my $request = shift;
337: $request->print(<<COMMONJSFUNCTIONS);
338: <script type="text/javascript" language="javascript">
339: function radioSelection(radioButton) {
340: var selection=null;
341: if (radioButton.length > 1) {
342: for (var i=0; i<radioButton.length; i++) {
343: if (radioButton[i].checked) {
344: return radioButton[i].value;
345: }
346: }
347: } else {
348: if (radioButton.checked) return radioButton.value;
349: }
350: return selection;
351: }
352:
353: function pullDownSelection(selectOne) {
354: var selection="";
355: if (selectOne.length > 1) {
356: for (var i=0; i<selectOne.length; i++) {
357: if (selectOne[i].selected) {
358: return selectOne[i].value;
359: }
360: }
361: } else {
362: // only one value it must be the selected one
363: return selectOne.value;
364: }
365: }
366: </script>
367: COMMONJSFUNCTIONS
368: }
369:
370: #--- Dumps the class list with usernames,list of sections,
371: #--- section, ids and fullnames for each user.
372: sub getclasslist {
373: my ($getsec,$filterlist) = @_;
374: my @getsec;
375: if (!ref($getsec)) {
376: if ($getsec ne '' && $getsec ne 'all') {
377: @getsec=($getsec);
378: }
379: } else {
380: @getsec=@{$getsec};
381: }
382: if (grep(/^all$/,@getsec)) { undef(@getsec); }
383:
384: my $classlist=&Apache::loncoursedata::get_classlist();
385: # Bail out if we were unable to get the classlist
386: return if (! defined($classlist));
387: #
388: my %sections;
389: my %fullnames;
390: foreach my $student (keys(%$classlist)) {
391: my $end =
392: $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
393: my $start =
394: $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
395: my $id =
396: $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
397: my $section =
398: $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
399: my $fullname =
400: $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
401: my $status =
402: $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
403: # filter students according to status selected
404: if ($filterlist && $env{'form.Status'} ne 'Any') {
405: if ($env{'form.Status'} ne $status) {
406: delete ($classlist->{$student});
407: next;
408: }
409: }
410: $section = ($section ne '' ? $section : 'none');
411: if (&canview($section)) {
412: if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
413: $sections{$section}++;
414: $fullnames{$student}=$fullname;
415: } else {
416: delete($classlist->{$student});
417: }
418: } else {
419: delete($classlist->{$student});
420: }
421: }
422: my %seen = ();
423: my @sections = sort(keys(%sections));
424: return ($classlist,\@sections,\%fullnames);
425: }
426:
427: sub canmodify {
428: my ($sec)=@_;
429: if ($perm{'mgr'}) {
430: if (!defined($perm{'mgr_section'})) {
431: # can modify whole class
432: return 1;
433: } else {
434: if ($sec eq $perm{'mgr_section'}) {
435: #can modify the requested section
436: return 1;
437: } else {
438: # can't modify the request section
439: return 0;
440: }
441: }
442: }
443: #can't modify
444: return 0;
445: }
446:
447: sub canview {
448: my ($sec)=@_;
449: if ($perm{'vgr'}) {
450: if (!defined($perm{'vgr_section'})) {
451: # can modify whole class
452: return 1;
453: } else {
454: if ($sec eq $perm{'vgr_section'}) {
455: #can modify the requested section
456: return 1;
457: } else {
458: # can't modify the request section
459: return 0;
460: }
461: }
462: }
463: #can't modify
464: return 0;
465: }
466:
467: #--- Retrieve the grade status of a student for all the parts
468: sub student_gradeStatus {
469: my ($symb,$udom,$uname,$partlist) = @_;
470: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
471: my %partstatus = ();
472: foreach (@$partlist) {
473: my ($status,undef) = split(/_/,$record{"resource.$_.solved"},2);
474: $status = 'nothing' if ($status eq '');
475: $partstatus{$_} = $status;
476: my $subkey = "resource.$_.submitted_by";
477: $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
478: }
479: return %partstatus;
480: }
481:
482: # hidden form and javascript that calls the form
483: # Use by verifyscript and viewgrades
484: # Shows a student's view of problem and submission
485: sub jscriptNform {
486: my ($symb) = @_;
487: my $jscript='<script type="text/javascript" language="javascript">'."\n".
488: ' function viewOneStudent(user,domain) {'."\n".
489: ' document.onestudent.student.value = user;'."\n".
490: ' document.onestudent.userdom.value = domain;'."\n".
491: ' document.onestudent.submit();'."\n".
492: ' }'."\n".
493: '</script>'."\n";
494: $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
495: '<input type="hidden" name="symb" value="'.$symb.'" />'."\n".
496: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
497: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
498: '<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n".
499: '<input type="hidden" name="command" value="submission" />'."\n".
500: '<input type="hidden" name="student" value="" />'."\n".
501: '<input type="hidden" name="userdom" value="" />'."\n".
502: '</form>'."\n";
503: return $jscript;
504: }
505:
506: # Given the score (as a number [0-1] and the weight) what is the final
507: # point value? This function will round to the nearest tenth, third,
508: # or quarter if one of those is within the tolerance of .00001.
509: sub compute_points {
510: my ($score, $weight) = @_;
511:
512: my $tolerance = .00001;
513: my $points = $score * $weight;
514:
515: # Check for nearness to 1/x.
516: my $check_for_nearness = sub {
517: my ($factor) = @_;
518: my $num = ($points * $factor) + $tolerance;
519: my $floored_num = floor($num);
520: if ($num - $floored_num < 2 * $tolerance * $factor) {
521: return $floored_num / $factor;
522: }
523: return $points;
524: };
525:
526: $points = $check_for_nearness->(10);
527: $points = $check_for_nearness->(3);
528: $points = $check_for_nearness->(4);
529:
530: return $points;
531: }
532:
533: #------------------ End of general use routines --------------------
534:
535: #
536: # Find most similar essay
537: #
538:
539: sub most_similar {
540: my ($uname,$udom,$uessay)=@_;
541:
542: # ignore spaces and punctuation
543:
544: $uessay=~s/\W+/ /gs;
545:
546: # ignore empty submissions (occuring when only files are sent)
547:
548: unless ($uessay=~/\w+/) { return ''; }
549:
550: # these will be returned. Do not care if not at least 50 percent similar
551: my $limit=0.6;
552: my $sname='';
553: my $sdom='';
554: my $scrsid='';
555: my $sessay='';
556: # go through all essays ...
557: foreach my $tkey (keys %oldessays) {
558: my ($tname,$tdom,$tcrsid)=split(/\./,$tkey);
559: # ... except the same student
560: if (($tname ne $uname) || ($tdom ne $udom)) {
561: my $tessay=$oldessays{$tkey};
562: $tessay=~s/\W+/ /gs;
563: # String similarity gives up if not even limit
564: my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
565: # Found one
566: if ($tsimilar>$limit) {
567: $limit=$tsimilar;
568: $sname=$tname;
569: $sdom=$tdom;
570: $scrsid=$tcrsid;
571: $sessay=$oldessays{$tkey};
572: }
573: }
574: }
575: if ($limit>0.6) {
576: return ($sname,$sdom,$scrsid,$sessay,$limit);
577: } else {
578: return ('','','','',0);
579: }
580: }
581:
582: #-------------------------------------------------------------------
583:
584: #------------------------------------ Receipt Verification Routines
585: #
586: #--- Check whether a receipt number is valid.---
587: sub verifyreceipt {
588: my $request = shift;
589:
590: my $courseid = $env{'request.course.id'};
591: my $receipt = &Apache::lonnet::recprefix($courseid).'-'.
592: $env{'form.receipt'};
593: $receipt =~ s/[^\-\d]//g;
594: my ($symb) = &get_symb($request);
595:
596: my $title.='<h3><span class="LC_info">Verifying Submission Receipt '.
597: $receipt.'</h3></span>'."\n".
598: '<h4><b>Resource: </b>'.$env{'form.probTitle'}.'</h4><br /><br />'."\n";
599:
600: my ($string,$contents,$matches) = ('','',0);
601: my (undef,undef,$fullname) = &getclasslist('all','0');
602:
603: my $receiptparts=0;
604: if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
605: $env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
606: my $parts=['0'];
607: if ($receiptparts) { ($parts)=&response_type($symb); }
608: foreach (sort
609: {
610: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
611: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
612: }
613: return $a cmp $b;
614: } (keys(%$fullname))) {
615: my ($uname,$udom)=split(/\:/);
616: foreach my $part (@$parts) {
617: if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
618: $contents.='<tr bgcolor="#ffffe6"><td> '."\n".
619: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
620: '\')"; TARGET=_self>'.$$fullname{$_}.'</a> </td>'."\n".
621: '<td> '.$uname.' </td>'.
622: '<td> '.$udom.' </td>';
623: if ($receiptparts) {
624: $contents.='<td> '.$part.' </td>';
625: }
626: $contents.='</tr>'."\n";
627:
628: $matches++;
629: }
630: }
631: }
632: if ($matches == 0) {
633: $string = $title.'No match found for the above receipt.';
634: } else {
635: $string = &jscriptNform($symb).$title.
636: 'The above receipt matches the following student'.
637: ($matches <= 1 ? '.' : 's.')."\n".
638: '<table border="0"><tr><td bgcolor="#777777">'."\n".
639: '<table border="0"><tr bgcolor="#e6ffff">'."\n".
640: '<td><b> Fullname </b></td>'."\n".
641: '<td><b> Username </b></td>'."\n".
642: '<td><b> Domain </b></td>';
643: if ($receiptparts) {
644: $string.='<td> Problem Part </td>';
645: }
646: $string.='</tr>'."\n".$contents.
647: '</table></td></tr></table>'."\n";
648: }
649: return $string.&show_grading_menu_form($symb);
650: }
651:
652: #--- This is called by a number of programs.
653: #--- Called from the Grading Menu - View/Grade an individual student
654: #--- Also called directly when one clicks on the subm button
655: # on the problem page.
656: sub listStudents {
657: my ($request) = shift;
658:
659: my ($symb) = &get_symb($request);
660: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
661: my $cnum = $env{"course.$env{'request.course.id'}.num"};
662: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
663: my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
664:
665: my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
666: $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ?
667: &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
668:
669: my $result='<h3><span class="LC_info"> '.$viewgrade.
670: ' Submissions for a Student or a Group of Students</span></h3>';
671:
672: my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
673:
674: $request->print(<<LISTJAVASCRIPT);
675: <script type="text/javascript" language="javascript">
676: function checkSelect(checkBox) {
677: var ctr=0;
678: var sense="";
679: if (checkBox.length > 1) {
680: for (var i=0; i<checkBox.length; i++) {
681: if (checkBox[i].checked) {
682: ctr++;
683: }
684: }
685: sense = "a student or group of students";
686: } else {
687: if (checkBox.checked) {
688: ctr = 1;
689: }
690: sense = "the student";
691: }
692: if (ctr == 0) {
693: alert("Please select "+sense+" before clicking on the Next button.");
694: return false;
695: }
696: document.gradesub.submit();
697: }
698:
699: function reLoadList(formname) {
700: if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
701: formname.command.value = 'submission';
702: formname.submit();
703: }
704: </script>
705: LISTJAVASCRIPT
706:
707: &commonJSfunctions($request);
708: $request->print($result);
709:
710: my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
711: my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
712: my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
713: "\n".$table.
714: ' <b>View Problem Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
715: '<label><input type="radio" name="vProb" value="yes" /> one student </label>'."\n".
716: '<label><input type="radio" name="vProb" value="all" /> all students </label><br />'."\n".
717: ' <b>View Answer: </b><label><input type="radio" name="vAns" value="no" /> no </label>'."\n".
718: '<label><input type="radio" name="vAns" value="yes" /> one student </label>'."\n".
719: '<label><input type="radio" name="vAns" value="all" checked="checked" /> all students </label><br />'."\n".
720: ' <b>Submissions: </b>'."\n";
721: if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
722: $gradeTable.='<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> essay part only </label>'."\n";
723: }
724:
725: my $saveStatus = $env{'form.Status'} eq '' ? 'Active' : $env{'form.Status'};
726: $env{'form.Status'} = $saveStatus;
727:
728: $gradeTable.='<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> last submission only </label>'."\n".
729: '<label><input type="radio" name="lastSub" value="last" /> last submission & parts info </label>'."\n".
730: '<label><input type="radio" name="lastSub" value="datesub" /> by dates and submissions </label>'."\n".
731: '<label><input type="radio" name="lastSub" value="all" /> all details</label><br />'."\n".
732: ' <b>Grading Increments:</b> <select name="increment">'.
733: '<option value="1">Whole Points</option>'.
734: '<option value=".5">Half Points</option>'.
735: '<option value=".25">Quarter Points</option>'.
736: '<option value=".1">Tenths of a Point</option>'.
737: '</select>'.
738:
739: '<input type="hidden" name="section" value="'.$getsec.'" />'."\n".
740: '<input type="hidden" name="submitonly" value="'.$submitonly.'" />'."\n".
741: '<input type="hidden" name="handgrade" value="'.$env{'form.handgrade'}.'" /><br />'."\n".
742: '<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
743: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
744: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
745: '<input type="hidden" name="symb" value="'.$symb.'" />'."\n".
746: '<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
747:
748: if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
749: $gradeTable.='<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n";
750: } else {
751: $gradeTable.='<b>Student Status:</b> '.
752: &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);').'<br />';
753: }
754:
755: $gradeTable.='To '.lc($viewgrade).' a submission or a group of submissions, click on the check box(es) '.
756: 'next to the student\'s name(s). Then click on the Next button.<br />'."\n".
757: '<input type="hidden" name="command" value="processGroup" />'."\n";
758:
759: # checkall buttons
760: $gradeTable.=&check_script('gradesub', 'stuinfo');
761: $gradeTable.='<input type="button" '."\n".
762: 'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
763: 'value="Next->" /> <br />'."\n";
764: $gradeTable.=&check_buttons();
765: $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />Check For Plagiarism</label>';
766: my ($classlist, undef, $fullname) = &getclasslist($getsec,'1');
767: $gradeTable.='<table border="0"><tr><td bgcolor="#777777">'.
768: '<table border="0"><tr bgcolor="#e6ffff">';
769: my $loop = 0;
770: while ($loop < 2) {
771: $gradeTable.='<td><b> No.</b> </td><td><b> Select </b></td>'.
772: '<td>'.&nameUserString('header').' Section/Group</td>';
773: if ($env{'form.showgrading'} eq 'yes'
774: && $submitonly ne 'queued'
775: && $submitonly ne 'all') {
776: foreach (sort(@$partlist)) {
777: my $display_part=&get_display_part((split(/_/))[0],$symb);
778: $gradeTable.='<td><b> Part: '.$display_part.
779: ' Status </b></td>';
780: }
781: } elsif ($submitonly eq 'queued') {
782: $gradeTable.='<td><b> '.&mt('Queue Status').' </b></td>';
783: }
784: $loop++;
785: # $gradeTable.='<td></td>' if ($loop%2 ==1);
786: }
787: $gradeTable.='</tr>'."\n";
788:
789: my $ctr = 0;
790: foreach my $student (sort
791: {
792: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
793: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
794: }
795: return $a cmp $b;
796: }
797: (keys(%$fullname))) {
798: my ($uname,$udom) = split(/:/,$student);
799:
800: my %status = ();
801:
802: if ($submitonly eq 'queued') {
803: my %queue_status =
804: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
805: $udom,$uname);
806: next if (!defined($queue_status{'gradingqueue'}));
807: $status{'gradingqueue'} = $queue_status{'gradingqueue'};
808: }
809:
810: if ($env{'form.showgrading'} eq 'yes'
811: && $submitonly ne 'queued'
812: && $submitonly ne 'all') {
813: (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
814: my $submitted = 0;
815: my $graded = 0;
816: my $incorrect = 0;
817: foreach (keys(%status)) {
818: $submitted = 1 if ($status{$_} ne 'nothing');
819: $graded = 1 if ($status{$_} =~ /^ungraded/);
820: $incorrect = 1 if ($status{$_} =~ /^incorrect/);
821:
822: my ($foo,$partid,$foo1) = split(/\./,$_);
823: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
824: $submitted = 0;
825: my ($part)=split(/\./,$partid);
826: $gradeTable.='<input type="hidden" name="'.
827: $student.':'.$part.':submitted_by" value="'.
828: $status{'resource.'.$partid.'.submitted_by'}.'" />';
829: }
830: }
831:
832: next if (!$submitted && ($submitonly eq 'yes' ||
833: $submitonly eq 'incorrect' ||
834: $submitonly eq 'graded'));
835: next if (!$graded && ($submitonly eq 'graded'));
836: next if (!$incorrect && $submitonly eq 'incorrect');
837: }
838:
839: $ctr++;
840: my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
841:
842: if ( $perm{'vgr'} eq 'F' ) {
843: $gradeTable.='<tr bgcolor="#ffffe6">' if ($ctr%2 ==1);
844: $gradeTable.='<td align="right">'.$ctr.' </td>'.
845: '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
846: $student.':'.$$fullname{$student}.':::SECTION'.$section.
847: ') " /> </label></td>'."\n".'<td>'.
848: &nameUserString(undef,$$fullname{$student},$uname,$udom).
849: ' '.$section.'</td>'."\n";
850:
851: if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
852: foreach (sort keys(%status)) {
853: next if (/^resource.*?submitted_by$/);
854: $gradeTable.='<td align="center"> '.$status{$_}.' </td>'."\n";
855: }
856: }
857: # $gradeTable.='<td></td>' if ($ctr%2 ==1);
858: $gradeTable.='</tr>'."\n" if ($ctr%2 ==0);
859: }
860: }
861: if ($ctr%2 ==1) {
862: $gradeTable.='<td> </td><td> </td><td> </td>';
863: if ($env{'form.showgrading'} eq 'yes'
864: && $submitonly ne 'queued'
865: && $submitonly ne 'all') {
866: foreach (@$partlist) {
867: $gradeTable.='<td> </td>';
868: }
869: } elsif ($submitonly eq 'queued') {
870: $gradeTable.='<td> </td>';
871: }
872: $gradeTable.='</tr>';
873: }
874:
875: $gradeTable.='</table></td></tr></table>'."\n".
876: '<input type="button" '.
877: 'onClick="javascript:checkSelect(this.form.stuinfo);" '.
878: 'value="Next->" /></form>'."\n";
879: if ($ctr == 0) {
880: my $num_students=(scalar(keys(%$fullname)));
881: if ($num_students eq 0) {
882: $gradeTable='<br /> <span class="LC_warning">There are no students currently enrolled.</span>';
883: } else {
884: my $submissions='submissions';
885: if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
886: if ($submitonly eq 'graded' ) { $submissions = 'ungraded submissions'; }
887: if ($submitonly eq 'queued' ) { $submissions = 'queued submissions'; }
888: $gradeTable='<br /> <span class="LC_warning">'.
889: 'No '.$submissions.' found for this resource for any students. ('.$num_students.
890: ' students checked for '.$submissions.')</span><br />';
891: }
892: } elsif ($ctr == 1) {
893: $gradeTable =~ s/type=checkbox/type=checkbox checked/;
894: }
895: $gradeTable.=&show_grading_menu_form($symb);
896: $request->print($gradeTable);
897: return '';
898: }
899:
900: #---- Called from the listStudents routine
901:
902: sub check_script {
903: my ($form, $type)=@_;
904: my $chkallscript='<script type="text/javascript">
905: function checkall() {
906: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
907: ele = document.forms.'.$form.'.elements[i];
908: if (ele.name == "'.$type.'") {
909: document.forms.'.$form.'.elements[i].checked=true;
910: }
911: }
912: }
913:
914: function checksec() {
915: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
916: ele = document.forms.'.$form.'.elements[i];
917: string = document.forms.'.$form.'.chksec.value;
918: if
919: (ele.value.indexOf(":::SECTION"+string)>0) {
920: document.forms.'.$form.'.elements[i].checked=true;
921: }
922: }
923: }
924:
925:
926: function uncheckall() {
927: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
928: ele = document.forms.'.$form.'.elements[i];
929: if (ele.name == "'.$type.'") {
930: document.forms.'.$form.'.elements[i].checked=false;
931: }
932: }
933: }
934:
935: </script>'."\n";
936: return $chkallscript;
937: }
938:
939: sub check_buttons {
940: my $buttons.='<input type="button" onclick="checkall()" value="Check All" />';
941: $buttons.='<input type="button" onclick="uncheckall()" value="Uncheck All" /> ';
942: $buttons.='<input type="button" onclick="checksec()" value="Check Section/Group" />';
943: $buttons.='<input type="text" size="5" name="chksec" /> ';
944: return $buttons;
945: }
946:
947: # Displays the submissions for one student or a group of students
948: sub processGroup {
949: my ($request) = shift;
950: my $ctr = 0;
951: my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
952: my $total = scalar(@stuchecked)-1;
953:
954: foreach my $student (@stuchecked) {
955: my ($uname,$udom,$fullname) = split(/:/,$student);
956: $env{'form.student'} = $uname;
957: $env{'form.userdom'} = $udom;
958: $env{'form.fullname'} = $fullname;
959: &submission($request,$ctr,$total);
960: $ctr++;
961: }
962: return '';
963: }
964:
965: #------------------------------------------------------------------------------------
966: #
967: #-------------------------- Next few routines handles grading by student, essentially
968: # handles essay response type problem/part
969: #
970: #--- Javascript to handle the submission page functionality ---
971: sub sub_page_js {
972: my $request = shift;
973: $request->print(<<SUBJAVASCRIPT);
974: <script type="text/javascript" language="javascript">
975: function updateRadio(formname,id,weight) {
976: var gradeBox = formname["GD_BOX"+id];
977: var radioButton = formname["RADVAL"+id];
978: var oldpts = formname["oldpts"+id].value;
979: var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
980: gradeBox.value = pts;
981: var resetbox = false;
982: if (isNaN(pts) || pts < 0) {
983: alert("A number equal or greater than 0 is expected. Entered value = "+pts);
984: for (var i=0; i<radioButton.length; i++) {
985: if (radioButton[i].checked) {
986: gradeBox.value = i;
987: resetbox = true;
988: }
989: }
990: if (!resetbox) {
991: formtextbox.value = "";
992: }
993: return;
994: }
995:
996: if (pts > weight) {
997: var resp = confirm("You entered a value ("+pts+
998: ") greater than the weight for the part. Accept?");
999: if (resp == false) {
1000: gradeBox.value = oldpts;
1001: return;
1002: }
1003: }
1004:
1005: for (var i=0; i<radioButton.length; i++) {
1006: radioButton[i].checked=false;
1007: if (pts == i && pts != "") {
1008: radioButton[i].checked=true;
1009: }
1010: }
1011: updateSelect(formname,id);
1012: formname["stores"+id].value = "0";
1013: }
1014:
1015: function writeBox(formname,id,pts) {
1016: var gradeBox = formname["GD_BOX"+id];
1017: if (checkSolved(formname,id) == 'update') {
1018: gradeBox.value = pts;
1019: } else {
1020: var oldpts = formname["oldpts"+id].value;
1021: gradeBox.value = oldpts;
1022: var radioButton = formname["RADVAL"+id];
1023: for (var i=0; i<radioButton.length; i++) {
1024: radioButton[i].checked=false;
1025: if (i == oldpts) {
1026: radioButton[i].checked=true;
1027: }
1028: }
1029: }
1030: formname["stores"+id].value = "0";
1031: updateSelect(formname,id);
1032: return;
1033: }
1034:
1035: function clearRadBox(formname,id) {
1036: if (checkSolved(formname,id) == 'noupdate') {
1037: updateSelect(formname,id);
1038: return;
1039: }
1040: gradeSelect = formname["GD_SEL"+id];
1041: for (var i=0; i<gradeSelect.length; i++) {
1042: if (gradeSelect[i].selected) {
1043: var selectx=i;
1044: }
1045: }
1046: var stores = formname["stores"+id];
1047: if (selectx == stores.value) { return };
1048: var gradeBox = formname["GD_BOX"+id];
1049: gradeBox.value = "";
1050: var radioButton = formname["RADVAL"+id];
1051: for (var i=0; i<radioButton.length; i++) {
1052: radioButton[i].checked=false;
1053: }
1054: stores.value = selectx;
1055: }
1056:
1057: function checkSolved(formname,id) {
1058: if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1059: var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
1060: if (!reply) {return "noupdate";}
1061: formname.overRideScore.value = 'yes';
1062: }
1063: return "update";
1064: }
1065:
1066: function updateSelect(formname,id) {
1067: formname["GD_SEL"+id][0].selected = true;
1068: return;
1069: }
1070:
1071: //=========== Check that a point is assigned for all the parts ============
1072: function checksubmit(formname,val,total,parttot) {
1073: formname.gradeOpt.value = val;
1074: if (val == "Save & Next") {
1075: for (i=0;i<=total;i++) {
1076: for (j=0;j<parttot;j++) {
1077: var partid = formname["partid"+i+"_"+j].value;
1078: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1079: var points = formname["GD_BOX"+i+"_"+partid].value;
1080: if (points == "") {
1081: var name = formname["name"+i].value;
1082: var studentID = (name != '' ? name : formname["unamedom"+i].value);
1083: var resp = confirm("You did not assign a score for "+studentID+
1084: ", part "+partid+". Continue?");
1085: if (resp == false) {
1086: formname["GD_BOX"+i+"_"+partid].focus();
1087: return false;
1088: }
1089: }
1090: }
1091:
1092: }
1093: }
1094:
1095: }
1096: if (val == "Grade Student") {
1097: formname.showgrading.value = "yes";
1098: if (formname.Status.value == "") {
1099: formname.Status.value = "Active";
1100: }
1101: formname.studentNo.value = total;
1102: }
1103: formname.submit();
1104: }
1105:
1106: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
1107: function checkSubmitPage(formname,total) {
1108: noscore = new Array(100);
1109: var ptr = 0;
1110: for (i=1;i<total;i++) {
1111: var partid = formname["q_"+i].value;
1112: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1113: var points = formname["GD_BOX"+i+"_"+partid].value;
1114: var status = formname["solved"+i+"_"+partid].value;
1115: if (points == "" && status != "correct_by_student") {
1116: noscore[ptr] = i;
1117: ptr++;
1118: }
1119: }
1120: }
1121: if (ptr != 0) {
1122: var sense = ptr == 1 ? ": " : "s: ";
1123: var prolist = "";
1124: if (ptr == 1) {
1125: prolist = noscore[0];
1126: } else {
1127: var i = 0;
1128: while (i < ptr-1) {
1129: prolist += noscore[i]+", ";
1130: i++;
1131: }
1132: prolist += "and "+noscore[i];
1133: }
1134: var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
1135: if (resp == false) {
1136: return false;
1137: }
1138: }
1139:
1140: formname.submit();
1141: }
1142: </script>
1143: SUBJAVASCRIPT
1144: }
1145:
1146: #--- javascript for essay type problem --
1147: sub sub_page_kw_js {
1148: my $request = shift;
1149: my $iconpath = $request->dir_config('lonIconsURL');
1150: &commonJSfunctions($request);
1151:
1152: my $inner_js_msg_central=<<INNERJS;
1153: <script text="text/javascript">
1154: function checkInput() {
1155: opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
1156: var nmsg = opener.document.SCORE.savemsgN.value;
1157: var usrctr = document.msgcenter.usrctr.value;
1158: var newval = opener.document.SCORE["newmsg"+usrctr];
1159: newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
1160:
1161: var msgchk = "";
1162: if (document.msgcenter.subchk.checked) {
1163: msgchk = "msgsub,";
1164: }
1165: var includemsg = 0;
1166: for (var i=1; i<=nmsg; i++) {
1167: var opnmsg = opener.document.SCORE["savemsg"+i];
1168: var frmmsg = document.msgcenter["msg"+i];
1169: opnmsg.value = opener.checkEntities(frmmsg.value);
1170: var showflg = opener.document.SCORE["shownOnce"+i];
1171: showflg.value = "1";
1172: var chkbox = document.msgcenter["msgn"+i];
1173: if (chkbox.checked) {
1174: msgchk += "savemsg"+i+",";
1175: includemsg = 1;
1176: }
1177: }
1178: if (document.msgcenter.newmsgchk.checked) {
1179: msgchk += "newmsg"+usrctr;
1180: includemsg = 1;
1181: }
1182: imgformname = opener.document.SCORE["mailicon"+usrctr];
1183: imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
1184: var includemsg = opener.document.SCORE["includemsg"+usrctr];
1185: includemsg.value = msgchk;
1186:
1187: self.close()
1188:
1189: }
1190: </script>
1191: INNERJS
1192:
1193: my $inner_js_highlight_central=<<INNERJS;
1194: <script type="text/javascript">
1195: function updateChoice(flag) {
1196: opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
1197: opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
1198: opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
1199: opener.document.SCORE.refresh.value = "on";
1200: if (opener.document.SCORE.keywords.value!=""){
1201: opener.document.SCORE.submit();
1202: }
1203: self.close()
1204: }
1205: </script>
1206: INNERJS
1207:
1208: my $start_page_msg_central =
1209: &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
1210: {'js_ready' => 1,
1211: 'only_body' => 1,
1212: 'bgcolor' =>'#FFFFFF',});
1213: my $end_page_msg_central =
1214: &Apache::loncommon::end_page({'js_ready' => 1});
1215:
1216:
1217: my $start_page_highlight_central =
1218: &Apache::loncommon::start_page('Highlight Central',
1219: $inner_js_highlight_central,
1220: {'js_ready' => 1,
1221: 'only_body' => 1,
1222: 'bgcolor' =>'#FFFFFF',});
1223: my $end_page_highlight_central =
1224: &Apache::loncommon::end_page({'js_ready' => 1});
1225:
1226: my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1227: $docopen=~s/^document\.//;
1228: $request->print(<<SUBJAVASCRIPT);
1229: <script type="text/javascript" language="javascript">
1230:
1231: //===================== Show list of keywords ====================
1232: function keywords(formname) {
1233: var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1234: if (nret==null) return;
1235: formname.keywords.value = nret;
1236:
1237: if (formname.keywords.value != "") {
1238: formname.refresh.value = "on";
1239: formname.submit();
1240: }
1241: return;
1242: }
1243:
1244: //===================== Script to view submitted by ==================
1245: function viewSubmitter(submitter) {
1246: document.SCORE.refresh.value = "on";
1247: document.SCORE.NCT.value = "1";
1248: document.SCORE.unamedom0.value = submitter;
1249: document.SCORE.submit();
1250: return;
1251: }
1252:
1253: //===================== Script to add keyword(s) ==================
1254: function getSel() {
1255: if (document.getSelection) txt = document.getSelection();
1256: else if (document.selection) txt = document.selection.createRange().text;
1257: else return;
1258: var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
1259: if (cleantxt=="") {
1260: alert("Please select a word or group of words from document and then click this link.");
1261: return;
1262: }
1263: var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
1264: if (nret==null) return;
1265: document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1266: if (document.SCORE.keywords.value != "") {
1267: document.SCORE.refresh.value = "on";
1268: document.SCORE.submit();
1269: }
1270: return;
1271: }
1272:
1273: //====================== Script for composing message ==============
1274: // preload images
1275: img1 = new Image();
1276: img1.src = "$iconpath/mailbkgrd.gif";
1277: img2 = new Image();
1278: img2.src = "$iconpath/mailto.gif";
1279:
1280: function msgCenter(msgform,usrctr,fullname) {
1281: var Nmsg = msgform.savemsgN.value;
1282: savedMsgHeader(Nmsg,usrctr,fullname);
1283: var subject = msgform.msgsub.value;
1284: var msgchk = document.SCORE["includemsg"+usrctr].value;
1285: re = /msgsub/;
1286: var shwsel = "";
1287: if (re.test(msgchk)) { shwsel = "checked" }
1288: subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
1289: displaySubject(checkEntities(subject),shwsel);
1290: for (var i=1; i<=Nmsg; i++) {
1291: var testmsg = "savemsg"+i+",";
1292: re = new RegExp(testmsg,"g");
1293: shwsel = "";
1294: if (re.test(msgchk)) { shwsel = "checked" }
1295: var message = document.SCORE["savemsg"+i].value;
1296: message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1297: displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
1298: //any < is already converted to <, etc. However, only once!!
1299: }
1300: newmsg = document.SCORE["newmsg"+usrctr].value;
1301: shwsel = "";
1302: re = /newmsg/;
1303: if (re.test(msgchk)) { shwsel = "checked" }
1304: newMsg(newmsg,shwsel);
1305: msgTail();
1306: return;
1307: }
1308:
1309: function checkEntities(strx) {
1310: if (strx.length == 0) return strx;
1311: var orgStr = ["&", "<", ">", '"'];
1312: var newStr = ["&", "<", ">", """];
1313: var counter = 0;
1314: while (counter < 4) {
1315: strx = strReplace(strx,orgStr[counter],newStr[counter]);
1316: counter++;
1317: }
1318: return strx;
1319: }
1320:
1321: function strReplace(strx, orgStr, newStr) {
1322: return strx.split(orgStr).join(newStr);
1323: }
1324:
1325: function savedMsgHeader(Nmsg,usrctr,fullname) {
1326: var height = 70*Nmsg+250;
1327: var scrollbar = "no";
1328: if (height > 600) {
1329: height = 600;
1330: scrollbar = "yes";
1331: }
1332: var xpos = (screen.width-600)/2;
1333: xpos = (xpos < 0) ? '0' : xpos;
1334: var ypos = (screen.height-height)/2-30;
1335: ypos = (ypos < 0) ? '0' : ypos;
1336:
1337: pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1338: pWin.focus();
1339: pDoc = pWin.document;
1340: pDoc.$docopen;
1341: pDoc.write('$start_page_msg_central');
1342:
1343: pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
1344: pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1345: pDoc.write("<h3><span class=\\"LC_info\\"> Compose Message for \"+fullname+\"</span></h3><br /><br />");
1346:
1347: pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
1348: pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
1349: pDoc.write("<td><b>Type</b></td><td><b>Include</b></td><td><b>Message</td></tr>");
1350: }
1351: function displaySubject(msg,shwsel) {
1352: pDoc = pWin.document;
1353: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1354: pDoc.write("<td>Subject</td>");
1355: pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
1356: pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"></td></tr>");
1357: }
1358:
1359: function displaySavedMsg(ctr,msg,shwsel) {
1360: pDoc = pWin.document;
1361: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1362: pDoc.write("<td align=\\"center\\">"+ctr+"</td>");
1363: pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"></td>");
1364: pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"</textarea></td></tr>");
1365: }
1366:
1367: function newMsg(newmsg,shwsel) {
1368: pDoc = pWin.document;
1369: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1370: pDoc.write("<td align=\\"center\\">New</td>");
1371: pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
1372: pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"</textarea></td></tr>");
1373: }
1374:
1375: function msgTail() {
1376: pDoc = pWin.document;
1377: pDoc.write("</table>");
1378: pDoc.write("</td></tr></table> ");
1379: pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\"> ");
1380: pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1381: pDoc.write("</form>");
1382: pDoc.write('$end_page_msg_central');
1383: pDoc.close();
1384: }
1385:
1386: //====================== Script for keyword highlight options ==============
1387: function kwhighlight() {
1388: var kwclr = document.SCORE.kwclr.value;
1389: var kwsize = document.SCORE.kwsize.value;
1390: var kwstyle = document.SCORE.kwstyle.value;
1391: var redsel = "";
1392: var grnsel = "";
1393: var blusel = "";
1394: if (kwclr=="red") {var redsel="checked"};
1395: if (kwclr=="green") {var grnsel="checked"};
1396: if (kwclr=="blue") {var blusel="checked"};
1397: var sznsel = "";
1398: var sz1sel = "";
1399: var sz2sel = "";
1400: if (kwsize=="0") {var sznsel="checked"};
1401: if (kwsize=="+1") {var sz1sel="checked"};
1402: if (kwsize=="+2") {var sz2sel="checked"};
1403: var synsel = "";
1404: var syisel = "";
1405: var sybsel = "";
1406: if (kwstyle=="") {var synsel="checked"};
1407: if (kwstyle=="<i>") {var syisel="checked"};
1408: if (kwstyle=="<b>") {var sybsel="checked"};
1409: highlightCentral();
1410: highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
1411: highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
1412: highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
1413: highlightend();
1414: return;
1415: }
1416:
1417: function highlightCentral() {
1418: // if (window.hwdWin) window.hwdWin.close();
1419: var xpos = (screen.width-400)/2;
1420: xpos = (xpos < 0) ? '0' : xpos;
1421: var ypos = (screen.height-330)/2-30;
1422: ypos = (ypos < 0) ? '0' : ypos;
1423:
1424: hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1425: hwdWin.focus();
1426: var hDoc = hwdWin.document;
1427: hDoc.$docopen;
1428: hDoc.write('$start_page_highlight_central');
1429: hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1430: hDoc.write("<h3><span class=\\"LC_info\\"> Keyword Highlight Options</span></h3><br /><br />");
1431:
1432: hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
1433: hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
1434: hDoc.write("<td><b>Text Color</b></td><td><b>Font Size</b></td><td><b>Font Style</td></tr>");
1435: }
1436:
1437: function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) {
1438: var hDoc = hwdWin.document;
1439: hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1440: hDoc.write("<td align=\\"left\\">");
1441: hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+"> "+clrtxt+"</td>");
1442: hDoc.write("<td align=\\"left\\">");
1443: hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+"> "+sztxt+"</td>");
1444: hDoc.write("<td align=\\"left\\">");
1445: hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+"> "+sytxt+"</td>");
1446: hDoc.write("</tr>");
1447: }
1448:
1449: function highlightend() {
1450: var hDoc = hwdWin.document;
1451: hDoc.write("</table>");
1452: hDoc.write("</td></tr></table> ");
1453: hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\"> ");
1454: hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1455: hDoc.write("</form>");
1456: hDoc.write('$end_page_highlight_central');
1457: hDoc.close();
1458: }
1459:
1460: </script>
1461: SUBJAVASCRIPT
1462: }
1463:
1464: sub get_increment {
1465: my $increment = $env{'form.increment'};
1466: if ($increment != 1 && $increment != .5 && $increment != .25 &&
1467: $increment != .1) {
1468: $increment = 1;
1469: }
1470: return $increment;
1471: }
1472:
1473: #--- displays the grading box, used in essay type problem and grading by page/sequence
1474: sub gradeBox {
1475: my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1476: my $checkIcon = '<img alt="'.&mt('Check Mark').
1477: '" src="'.$request->dir_config('lonIconsURL').
1478: '/check.gif" height="16" border="0" />';
1479: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1480: my $wgtmsg = ($wgt > 0 ? '(problem weight)' :
1481: '<span class="LC_info">problem weight assigned by computer</span>');
1482: $wgt = ($wgt > 0 ? $wgt : '1');
1483: my $score = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1484: '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1485: my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1486: my $display_part=&get_display_part($partid,$symb);
1487: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
1488: [$partid]);
1489: my $aggtries = $$record{'resource.'.$partid.'.tries'};
1490: if ($last_resets{$partid}) {
1491: $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
1492: }
1493: $result.='<table border="0"><tr><td>'.
1494: '<b>Part: </b>'.$display_part.' <b>Points: </b></td><td>'."\n";
1495: my $ctr = 0;
1496: my $thisweight = 0;
1497: my $increment = &get_increment();
1498: $result.='<table border="0"><tr>'."\n"; # display radio buttons in a nice table 10 across
1499: while ($thisweight<=$wgt) {
1500: $result.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1501: 'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1502: $thisweight.')" value="'.$thisweight.'" '.
1503: ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1504: $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1505: $thisweight += $increment;
1506: $ctr++;
1507: }
1508: $result.='</tr></table>';
1509: $result.='</td><td> <b>or</b> </td>'."\n";
1510: $result.='<td><input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1511: ($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1512: 'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1513: $wgt.')" /></td>'."\n";
1514: $result.='<td>/'.$wgt.' '.$wgtmsg.
1515: ($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? ' '.$checkIcon : '').
1516: ' </td><td>'."\n";
1517: $result.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
1518: 'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1519: if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1520: $result.='<option></option>'.
1521: '<option selected="selected">excused</option>';
1522: } else {
1523: $result.='<option selected="selected"></option>'.
1524: '<option>excused</option>';
1525: }
1526: $result.='<option>reset status</option></select>'."\n";
1527: $result.=" \n";
1528: $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
1529: '<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
1530: '<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1531: $$record{'resource.'.$partid.'.solved'}.'" />'."\n".
1532: '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
1533: $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
1534: '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
1535: $aggtries.'" />'."\n";
1536: $result.='</td></tr></table>'."\n";
1537: $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
1538: return $result;
1539: }
1540:
1541: sub handback_box {
1542: my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
1543: my ($partlist,$handgrade,$responseType) = &response_type($symb);
1544: my (@respids);
1545: my @part_response_id = &flatten_responseType($responseType);
1546: foreach my $part_response_id (@part_response_id) {
1547: my ($part,$resp) = @{ $part_response_id };
1548: if ($part eq $partid) {
1549: push(@respids,$resp);
1550: }
1551: }
1552: my $result;
1553: foreach my $respid (@respids) {
1554: my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
1555: my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
1556: next if (!@$files);
1557: my $file_counter = 1;
1558: foreach my $file (@$files) {
1559: if ($file =~ /\/portfolio\//) {
1560: my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1561: my ($name,$version,$ext) = &file_name_version_ext($file_disp);
1562: $file_disp = "$name.$ext";
1563: $file = $file_path.$file_disp;
1564: $result.=&mt('Return commented version of [_1] to student.',
1565: '<span class="LC_filename">'.$file_disp.'</span>');
1566: $result.='<input type="file" name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1567: $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1568: $result.='(File will be uploaded when you click on Save & Next below.)<br />';
1569: $file_counter++;
1570: }
1571: }
1572: }
1573: return $result;
1574: }
1575:
1576: sub show_problem {
1577: my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1578: my $rendered;
1579: my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1580: &Apache::lonxml::remember_problem_counter();
1581: if ($mode eq 'both' or $mode eq 'text') {
1582: $rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1583: $env{'request.course.id'},
1584: undef,\%form);
1585: }
1586: if ($removeform) {
1587: $rendered=~s|<form(.*?)>||g;
1588: $rendered=~s|</form>||g;
1589: $rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1590: }
1591: my $companswer;
1592: if ($mode eq 'both' or $mode eq 'answer') {
1593: &Apache::lonxml::restore_problem_counter();
1594: $companswer=
1595: &Apache::loncommon::get_student_answers($symb,$uname,$udom,
1596: $env{'request.course.id'},
1597: %form);
1598: }
1599: if ($removeform) {
1600: $companswer=~s|<form(.*?)>||g;
1601: $companswer=~s|</form>||g;
1602: $companswer=~s|name="submit"|name="would_have_been_submit"|g;
1603: }
1604: my $result.='<table border="0" width="100%"><tr><td bgcolor="#777777">';
1605: $result.='<table border="0" width="100%">';
1606: if ($viewon) {
1607: $result.='<tr><td bgcolor="#e6ffff"><b> ';
1608: if ($mode eq 'both' or $mode eq 'text') {
1609: $result.='View of the problem - ';
1610: } else {
1611: $result.='Correct answer: ';
1612: }
1613: $result.=$env{'form.fullname'}.'</b></td></tr>';
1614: }
1615: if ($mode eq 'both') {
1616: $result.='<tr><td bgcolor="#ffffff">'.$rendered.'<br />';
1617: $result.='<b>Correct answer:</b><br />'.$companswer;
1618: } elsif ($mode eq 'text') {
1619: $result.='<tr><td bgcolor="#ffffff">'.$rendered;
1620: } elsif ($mode eq 'answer') {
1621: $result.='<tr><td bgcolor="#ffffff">'.$companswer;
1622: }
1623: $result.='</td></tr></table>';
1624: $result.='</td></tr></table><br />';
1625: return $result;
1626: }
1627:
1628: sub files_exist {
1629: my ($r, $symb) = @_;
1630: my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1631:
1632: foreach my $student (@students) {
1633: my ($uname,$udom,$fullname) = split(/:/,$student);
1634: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
1635: $udom,$uname);
1636: my ($string,$timestamp)= &get_last_submission(\%record);
1637: foreach my $submission (@$string) {
1638: my ($partid,$respid) =
1639: ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1640: my $files=&get_submitted_files($udom,$uname,$partid,$respid,
1641: \%record);
1642: return 1 if (@$files);
1643: }
1644: }
1645: return 0;
1646: }
1647:
1648: sub download_all_link {
1649: my ($r,$symb) = @_;
1650: my $all_students =
1651: join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
1652:
1653: my $parts =
1654: join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
1655:
1656: my $identifier = &Apache::loncommon::get_cgi_id();
1657: &Apache::lonnet::appenv('cgi.'.$identifier.'.students' => $all_students,
1658: 'cgi.'.$identifier.'.symb' => $symb,
1659: 'cgi.'.$identifier.'.parts' => $parts,);
1660: $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
1661: &mt('Download All Submitted Documents').'</a>');
1662: return
1663: }
1664:
1665: # --------------------------- show submissions of a student, option to grade
1666: sub submission {
1667: my ($request,$counter,$total) = @_;
1668:
1669: my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
1670: $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
1671: my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
1672: $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1673:
1674: my $symb = &get_symb($request);
1675: if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1676:
1677: if (!&canview($usec)) {
1678: $request->print('<span class="LC_warning">Unable to view requested student.('.
1679: $uname.':'.$udom.' in section '.$usec.' in course id '.
1680: $env{'request.course.id'}.')</span>');
1681: $request->print(&show_grading_menu_form($symb));
1682: return;
1683: }
1684:
1685: if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
1686: if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
1687: if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
1688: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1689: my $checkIcon = '<img alt="'.&mt('Check Mark').
1690: '" src="'.$request->dir_config('lonIconsURL').
1691: '/check.gif" height="16" border="0" />';
1692:
1693: # header info
1694: if ($counter == 0) {
1695: &sub_page_js($request);
1696: &sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
1697: $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ?
1698: &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1699: if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1700: &download_all_link($request, $symb);
1701: }
1702: $request->print('<h3> <span class="LC_info">Submission Record</span></h3>'."\n".
1703: '<h4> <b>Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n");
1704:
1705: if ($env{'form.handgrade'} eq 'no') {
1706: my $checkMark='<br /><br /> <b>Note:</b> Part(s) graded correct by the computer is marked with a '.
1707: $checkIcon.' symbol.'."\n";
1708: $request->print($checkMark);
1709: }
1710:
1711: # option to display problem, only once else it cause problems
1712: # with the form later since the problem has a form.
1713: if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1714: my $mode;
1715: if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1716: $mode='both';
1717: } elsif ($env{'form.vProb'} eq 'yes') {
1718: $mode='text';
1719: } elsif ($env{'form.vAns'} eq 'yes') {
1720: $mode='answer';
1721: }
1722: &Apache::lonxml::clear_problem_counter();
1723: $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1724: }
1725:
1726: # kwclr is the only variable that is guaranteed to be non blank
1727: # if this subroutine has been called once.
1728: my %keyhash = ();
1729: if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1730: %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1731: $env{'course.'.$env{'request.course.id'}.'.domain'},
1732: $env{'course.'.$env{'request.course.id'}.'.num'});
1733:
1734: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1735: $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
1736: $env{'form.kwclr'} = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
1737: $env{'form.kwsize'} = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
1738: $env{'form.kwstyle'} = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
1739: $env{'form.msgsub'} = $keyhash{$symb.'_subject'} ne '' ?
1740: $keyhash{$symb.'_subject'} : $env{'form.probTitle'};
1741: $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1742: }
1743: my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1744:
1745: $request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1746: '<input type="hidden" name="command" value="handgrade" />'."\n".
1747: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1748: '<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n".
1749: '<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1750: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
1751: '<input type="hidden" name="refresh" value="off" />'."\n".
1752: '<input type="hidden" name="studentNo" value="" />'."\n".
1753: '<input type="hidden" name="gradeOpt" value="" />'."\n".
1754: '<input type="hidden" name="symb" value="'.$symb.'" />'."\n".
1755: '<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
1756: '<input type="hidden" name="vProb" value="'.$env{'form.vProb'}.'" />'."\n".
1757: '<input type="hidden" name="vAns" value="'.$env{'form.vAns'}.'" />'."\n".
1758: '<input type="hidden" name="lastSub" value="'.$env{'form.lastSub'}.'" />'."\n".
1759: '<input type="hidden" name="section" value="'.$env{'form.section'}.'" />'."\n".
1760: '<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1761: '<input type="hidden" name="handgrade" value="'.$env{'form.handgrade'}.'" />'."\n".
1762: '<input type="hidden" name="NCT"'.
1763: ' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1764: if ($env{'form.handgrade'} eq 'yes') {
1765: $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
1766: '<input type="hidden" name="kwclr" value="'.$env{'form.kwclr'}.'" />'."\n".
1767: '<input type="hidden" name="kwsize" value="'.$env{'form.kwsize'}.'" />'."\n".
1768: '<input type="hidden" name="kwstyle" value="'.$env{'form.kwstyle'}.'" />'."\n".
1769: '<input type="hidden" name="msgsub" value="'.$env{'form.msgsub'}.'" />'."\n".
1770: '<input type="hidden" name="shownSub" value="0" />'."\n".
1771: '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1772: foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
1773: $request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
1774: }
1775: }
1776:
1777: my ($cts,$prnmsg) = (1,'');
1778: while ($cts <= $env{'form.savemsgN'}) {
1779: $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1780: (!exists($keyhash{$symb.'_savemsg'.$cts}) ?
1781: &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1782: &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1783: '" />'."\n".
1784: '<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1785: $cts++;
1786: }
1787: $request->print($prnmsg);
1788:
1789: if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1790: #
1791: # Print out the keyword options line
1792: #
1793: $request->print(<<KEYWORDS);
1794: <b>Keyword Options:</b>
1795: <a href="javascript:keywords(document.SCORE)"; TARGET=_self>List</a>
1796: <a href="#" onMouseDown="javascript:getSel(); return false"
1797: CLASS="page">Paste Selection to List</a>
1798: <a href="javascript:kwhighlight()"; TARGET=_self>Highlight Attribute</a><br /><br />
1799: KEYWORDS
1800: #
1801: # Load the other essays for similarity check
1802: #
1803: my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1804: my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1805: $apath=&escape($apath);
1806: $apath=~s/\W/\_/gs;
1807: %oldessays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1808: }
1809: }
1810:
1811: if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1812: $request->print('<br /><br /><br />') if ($counter > 0);
1813: my $mode;
1814: if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1815: $mode='both';
1816: } elsif ($env{'form.vProb'} eq 'all' ) {
1817: $mode='text';
1818: } elsif ($env{'form.vAns'} eq 'all') {
1819: $mode='answer';
1820: }
1821: &Apache::lonxml::clear_problem_counter();
1822: $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode));
1823: }
1824:
1825: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1826: my ($partlist,$handgrade,$responseType) = &response_type($symb);
1827:
1828: # Display student info
1829: $request->print(($counter == 0 ? '' : '<br />'));
1830: my $result='<table border="0" width="100%"><tr><td bgcolor="#777777">'."\n".
1831: '<table border="0" width="100%"><tr bgcolor="#edffff"><td>'."\n";
1832:
1833: $result.='<b>Fullname: </b>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'<br />'."\n";
1834: $result.='<input type="hidden" name="name'.$counter.
1835: '" value="'.$env{'form.fullname'}.'" />'."\n";
1836:
1837: # If any part of the problem is an essay-response (handgraded), then check for collaborators
1838: my @col_fullnames;
1839: my ($classlist,$fullname);
1840: if ($env{'form.handgrade'} eq 'yes') {
1841: ($classlist,undef,$fullname) = &getclasslist('all','0');
1842: for (keys (%$handgrade)) {
1843: my $ncol = &Apache::lonnet::EXT('resource.'.$_.
1844: '.maxcollaborators',
1845: $symb,$udom,$uname);
1846: next if ($ncol <= 0);
1847: s/\_/\./g;
1848: next if ($record{'resource.'.$_.'.collaborators'} eq '');
1849: my @goodcollaborators = ();
1850: my @badcollaborators = ();
1851: foreach (split(/,?\s+/,$record{'resource.'.$_.'.collaborators'})) {
1852: $_ =~ s/[\$\^\(\)]//g;
1853: next if ($_ eq '');
1854: my ($co_name,$co_dom) = split /\@|:/,$_;
1855: $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
1856: next if ($co_name eq $uname && $co_dom eq $udom);
1857: # Doing this grep allows 'fuzzy' specification
1858: my @Matches = grep /^$co_name:$co_dom$/i,keys %$classlist;
1859: if (! scalar(@Matches)) {
1860: push @badcollaborators,$_;
1861: } else {
1862: push @goodcollaborators, @Matches;
1863: }
1864: }
1865: if (scalar(@goodcollaborators) != 0) {
1866: $result.='<b>Collaborators: </b>';
1867: foreach (@goodcollaborators) {
1868: my ($lastname,$givenn) = split(/,/,$$fullname{$_});
1869: push @col_fullnames, $givenn.' '.$lastname;
1870: $result.=$$fullname{$_}.' ';
1871: }
1872: $result.='<br />'."\n";
1873: my ($part)=split(/\./,$_);
1874: $result.='<input type="hidden" name="collaborator'.$counter.
1875: '" value="'.$part.':'.(join ':',@goodcollaborators).'" />'.
1876: "\n";
1877: }
1878: if (scalar(@badcollaborators) > 0) {
1879: $result.='<table border="0"><tr bgcolor="#ffbbbb"><td>';
1880: $result.='This student has submitted ';
1881: $result.=(scalar(@badcollaborators) == 1) ? 'an invalid collaborator' : 'invalid collaborators';
1882: $result .= ': '.join(', ',@badcollaborators);
1883: $result .= '</td></tr></table>';
1884: }
1885: if (scalar(@badcollaborators > $ncol)) {
1886: $result .= '<table border="0"><tr bgcolor="#ffbbbb"><td>';
1887: $result .= 'This student has submitted too many '.
1888: 'collaborators. Maximum is '.$ncol.'.';
1889: $result .= '</td></tr></table>';
1890: }
1891: }
1892: }
1893: $request->print($result."\n");
1894:
1895: # print student answer/submission
1896: # Options are (1) Handgaded submission only
1897: # (2) Last submission, includes submission that is not handgraded
1898: # (for multi-response type part)
1899: # (3) Last submission plus the parts info
1900: # (4) The whole record for this student
1901: if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1902: my ($string,$timestamp)= &get_last_submission(\%record);
1903: my $lastsubonly=''.
1904: ($$timestamp eq '' ? '' : '<b>Date Submitted:</b> '.
1905: $$timestamp)."</td></tr>\n";
1906: if ($$timestamp eq '') {
1907: $lastsubonly.='<tr><td bgcolor="#ffffe6">'.$$string[0];
1908: } else {
1909: my %seenparts;
1910: my @part_response_id = &flatten_responseType($responseType);
1911: foreach my $part (@part_response_id) {
1912: next if ($env{'form.lastSub'} eq 'hdgrade'
1913: && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
1914:
1915: my ($partid,$respid) = @{ $part };
1916: my $display_part=&get_display_part($partid,$symb);
1917: if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1918: if (exists($seenparts{$partid})) { next; }
1919: $seenparts{$partid}=1;
1920: my $submitby='<b>Part:</b> '.$display_part.
1921: ' <b>Collaborative submission by:</b> '.
1922: '<a href="javascript:viewSubmitter(\''.
1923: $env{"form.$uname:$udom:$partid:submitted_by"}.
1924: '\')"; TARGET=_self>'.
1925: $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1926: $request->print($submitby);
1927: next;
1928: }
1929: my $responsetype = $responseType->{$partid}->{$respid};
1930: if (!exists($record{"resource.$partid.$respid.submission"})) {
1931: $lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
1932: $display_part.' <span class="LC_internal_info">( ID '.$respid.
1933: ' )</span> '.
1934: '<span class="LC_warning">Nothing submitted - no attempts</span><br /><br />';
1935: next;
1936: }
1937: foreach (@$string) {
1938: my ($partid,$respid) = /^resource\.([^\.]*)\.([^\.]*)\.submission/;
1939: if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1940: my ($ressub,$subval) = split(/:/,$_,2);
1941: # Similarity check
1942: my $similar='';
1943: if($env{'form.checkPlag'}){
1944: my ($oname,$odom,$ocrsid,$oessay,$osim)=
1945: &most_similar($uname,$udom,$subval);
1946: if ($osim) {
1947: $osim=int($osim*100.0);
1948: $similar="<hr /><h3><span class=\"LC_warning\">Essay".
1949: " is $osim% similar to an essay by ".
1950: &Apache::loncommon::plainname($oname,$odom).
1951: '</span></h3><blockquote><i>'.
1952: &keywords_highlight($oessay).
1953: '</i></blockquote><hr />';
1954: }
1955: }
1956: my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1957: if ($env{'form.lastSub'} eq 'lastonly' ||
1958: ($env{'form.lastSub'} eq 'hdgrade' &&
1959: $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1960: my $display_part=&get_display_part($partid,$symb);
1961: $lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
1962: $display_part.' <span class="LC_internal_info">( ID '.$respid.
1963: ' )</span> ';
1964: my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
1965: if (@$files) {
1966: $lastsubonly.='<br /><span class="LC_warning">Like all files provided by users, this file may contain virusses</span><br />';
1967: my $file_counter = 0;
1968: foreach my $file (@$files) {
1969: $file_counter ++;
1970: &Apache::lonnet::allowuploaded('/adm/grades',$file);
1971: $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
1972: }
1973: $lastsubonly.='<br />';
1974: }
1975: $lastsubonly.='<b>Submitted Answer: </b>'.
1976: &cleanRecord($subval,$responsetype,$symb,$partid,
1977: $respid,\%record,$order);
1978: if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1979: }
1980: }
1981: }
1982: }
1983: $lastsubonly.='</td></tr><tr bgcolor="#ffffff"><td>'."\n";
1984: $request->print($lastsubonly);
1985: } elsif ($env{'form.lastSub'} eq 'datesub') {
1986: my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
1987: $request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1988: } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1989: $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1990: $env{'request.course.id'},
1991: $last,'.submission',
1992: 'Apache::grades::keywords_highlight'));
1993: }
1994:
1995: $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
1996: .$udom.'" />'."\n");
1997:
1998: # return if view submission with no grading option
1999: if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
2000: my $toGrade.='<input type="button" value="Grade Student" '.
2001: 'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
2002: .$counter.'\');" TARGET=_self> '."\n" if (&canmodify($usec));
2003: $toGrade.='</td></tr></table></td></tr></table>'."\n";
2004: if (($env{'form.command'} eq 'submission') ||
2005: ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
2006: $toGrade.='</form>'.&show_grading_menu_form($symb);
2007: }
2008: $request->print($toGrade);
2009: return;
2010: } else {
2011: $request->print('</td></tr></table></td></tr></table>'."\n");
2012: }
2013:
2014: # essay grading message center
2015: if ($env{'form.handgrade'} eq 'yes') {
2016: my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
2017: my $msgfor = $givenn.' '.$lastname;
2018: if (scalar(@col_fullnames) > 0) {
2019: my $lastone = pop @col_fullnames;
2020: $msgfor .= ', '.(join ', ',@col_fullnames).' and '.$lastone.'.';
2021: }
2022: $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
2023: $result='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
2024: '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
2025: $result.=' <a href="javascript:msgCenter(document.SCORE,'.$counter.
2026: ',\''.$msgfor.'\')"; TARGET=_self>'.
2027: &mt('Compose message to student').(scalar(@col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
2028: &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
2029: '<img src="'.$request->dir_config('lonIconsURL').
2030: '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
2031: '<br /> ('.
2032: &mt('Message will be sent when you click on Save & Next below.').")\n";
2033: $request->print($result);
2034: }
2035: if ($perm{'vgr'}) {
2036: $request->print('<br />'.
2037: &Apache::loncommon::track_student_link(&mt('View recent activity'),
2038: $uname,$udom,'check'));
2039: }
2040: if ($perm{'opa'}) {
2041: $request->print('<br />'.
2042: &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
2043: $uname,$udom,$symb,'check'));
2044: }
2045:
2046: my %seen = ();
2047: my @partlist;
2048: my @gradePartRespid;
2049: my @part_response_id = &flatten_responseType($responseType);
2050: foreach my $part_response_id (@part_response_id) {
2051: my ($partid,$respid) = @{ $part_response_id };
2052: my $part_resp = join('_',@{ $part_response_id });
2053: next if ($seen{$partid} > 0);
2054: $seen{$partid}++;
2055: next if ($$handgrade{$part_resp} ne 'yes'
2056: && $env{'form.lastSub'} eq 'hdgrade');
2057: push @partlist,$partid;
2058: push @gradePartRespid,$partid.'.'.$respid;
2059: $request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
2060: }
2061: $result='<input type="hidden" name="partlist'.$counter.
2062: '" value="'.(join ":",@partlist).'" />'."\n";
2063: $result.='<input type="hidden" name="gradePartRespid'.
2064: '" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
2065: my $ctr = 0;
2066: while ($ctr < scalar(@partlist)) {
2067: $result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
2068: $partlist[$ctr].'" />'."\n";
2069: $ctr++;
2070: }
2071: $request->print($result.'</td></tr></table></td></tr></table>'."\n");
2072:
2073: # print end of form
2074: if ($counter == $total) {
2075: my $endform='<table border="0"><tr><td>'."\n";
2076: $endform.='<input type="button" value="Save & Next" '.
2077: 'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
2078: $total.','.scalar(@partlist).');" TARGET=_self> '."\n";
2079: my $ntstu ='<select name="NTSTU">'.
2080: '<option>1</option><option>2</option>'.
2081: '<option>3</option><option>5</option>'.
2082: '<option>7</option><option>10</option></select>'."\n";
2083: my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
2084: $ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
2085: $endform.=$ntstu.'student(s) ';
2086: $endform.='<input type="button" value="Previous" '.
2087: 'onClick="javascript:checksubmit(this.form,\'Previous\');" TARGET=_self> '."\n".
2088: '<input type="button" value="Next" '.
2089: 'onClick="javascript:checksubmit(this.form,\'Next\');" TARGET=_self> ';
2090: $endform.='(Next and Previous (student) do not save the scores.)'."\n" ;
2091: $endform.="<input type='hidden' value='".&get_increment().
2092: "' name='increment' />";
2093: $endform.='</td><tr></table></form>';
2094: $endform.=&show_grading_menu_form($symb);
2095: $request->print($endform);
2096: }
2097: return '';
2098: }
2099:
2100: #--- Retrieve the last submission for all the parts
2101: sub get_last_submission {
2102: my ($returnhash)=@_;
2103: my (@string,$timestamp);
2104: if ($$returnhash{'version'}) {
2105: my %lasthash=();
2106: my ($version);
2107: for ($version=1;$version<=$$returnhash{'version'};$version++) {
2108: foreach my $key (sort(split(/\:/,
2109: $$returnhash{$version.':keys'}))) {
2110: $lasthash{$key}=$$returnhash{$version.':'.$key};
2111: $timestamp =
2112: scalar(localtime($$returnhash{$version.':timestamp'}));
2113: }
2114: }
2115: foreach my $key (keys(%lasthash)) {
2116: next if ($key !~ /\.submission$/);
2117:
2118: my ($partid,$foo) = split(/submission$/,$key);
2119: my $draft = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
2120: '<span class="LC_warning">Draft Copy</span> ' : '';
2121: push(@string, join(':', $key, $draft.$lasthash{$key}));
2122: }
2123: }
2124: if (!@string) {
2125: $string[0] =
2126: '<span class="LC_warning">Nothing submitted - no attempts.</span>';
2127: }
2128: return (\@string,\$timestamp);
2129: }
2130:
2131: #--- High light keywords, with style choosen by user.
2132: sub keywords_highlight {
2133: my $string = shift;
2134: my $size = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
2135: my $styleon = $env{'form.kwstyle'} eq '' ? '' : $env{'form.kwstyle'};
2136: (my $styleoff = $styleon) =~ s/\</\<\//;
2137: my @keylist = split(/[,\s+]/,$env{'form.keywords'});
2138: foreach my $keyword (@keylist) {
2139: $string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
2140: }
2141: return $string;
2142: }
2143:
2144: #--- Called from submission routine
2145: sub processHandGrade {
2146: my ($request) = shift;
2147: my $symb = &get_symb($request);
2148: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
2149: my $button = $env{'form.gradeOpt'};
2150: my $ngrade = $env{'form.NCT'};
2151: my $ntstu = $env{'form.NTSTU'};
2152: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2153: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2154:
2155: if ($button eq 'Save & Next') {
2156: my $ctr = 0;
2157: while ($ctr < $ngrade) {
2158: my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
2159: my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
2160: if ($errorflag eq 'no_score') {
2161: $ctr++;
2162: next;
2163: }
2164: if ($errorflag eq 'not_allowed') {
2165: $request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
2166: $ctr++;
2167: next;
2168: }
2169: my $includemsg = $env{'form.includemsg'.$ctr};
2170: my ($subject,$message,$msgstatus) = ('','','');
2171: my $restitle = &Apache::lonnet::gettitle($symb);
2172: my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
2173: $symb,$udom,$uname);
2174: my ($feedurl,$baseurl,$showsymb,$messagetail);
2175: $feedurl = &Apache::lonnet::clutter($url);
2176: if ($encrypturl =~ /^yes$/i) {
2177: $baseurl = &Apache::lonenc::encrypted($feedurl,1);
2178: $showsymb = &Apache::lonenc::encrypted($symb,1);
2179: } else {
2180: $baseurl = $feedurl;
2181: $showsymb = $symb;
2182: }
2183: if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
2184: $subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
2185: unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
2186: $subject.=' ['.$restitle.']';
2187: my (@msgnum) = split(/,/,$includemsg);
2188: foreach (@msgnum) {
2189: $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
2190: }
2191: $message =&Apache::lonfeedback::clear_out_html($message);
2192: if ($env{'form.withgrades'.$ctr}) {
2193: $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
2194: $messagetail = " for <a href=\"".
2195: $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
2196: }
2197: $msgstatus =
2198: &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
2199: $message.$messagetail,
2200: undef,$baseurl,undef,
2201: undef,undef,$showsymb,
2202: $restitle);
2203: $request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
2204: $msgstatus);
2205: }
2206: if ($env{'form.collaborator'.$ctr}) {
2207: my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
2208: foreach my $collabstr (@collabstrs) {
2209: my ($part,@collaborators) = split(/:/,$collabstr);
2210: foreach my $collaborator (@collaborators) {
2211: my ($errorflag,$pts,$wgt) =
2212: &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
2213: $env{'form.unamedom'.$ctr},$part);
2214: if ($errorflag eq 'not_allowed') {
2215: $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
2216: next;
2217: } else {
2218: if ($message ne '') {
2219: $encrypturl=
2220: &Apache::lonnet::EXT('resource.0.encrypturl',
2221: $symb,$udom,$collaborator);
2222: if ($encrypturl =~ /^yes$/i) {
2223: $baseurl = &Apache::lonenc::encrypted($feedurl,1);
2224: $showsymb = &Apache::lonenc::encrypted($symb,1);
2225: } else {
2226: $baseurl = $feedurl;
2227: $showsymb = $symb;
2228: }
2229: if ($env{'form.withgrades'.$ctr}) {
2230: $messagetail = " for <a href=\"".
2231: $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
2232:
2233: }
2234: $msgstatus =
2235: &Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
2236: }
2237: }
2238: }
2239: }
2240: }
2241: $ctr++;
2242: }
2243: }
2244:
2245: if ($env{'form.handgrade'} eq 'yes') {
2246: # Keywords sorted in alphabatical order
2247: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
2248: my %keyhash = ();
2249: $env{'form.keywords'} =~ s/,\s{0,}|\s+/ /g;
2250: $env{'form.keywords'} =~ s/^\s+|\s+$//;
2251: my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
2252: $env{'form.keywords'} = join(' ',@keywords);
2253: $keyhash{$symb.'_keywords'} = $env{'form.keywords'};
2254: $keyhash{$symb.'_subject'} = $env{'form.msgsub'};
2255: $keyhash{$loginuser.'_kwclr'} = $env{'form.kwclr'};
2256: $keyhash{$loginuser.'_kwsize'} = $env{'form.kwsize'};
2257: $keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
2258:
2259: # message center - Order of message gets changed. Blank line is eliminated.
2260: # New messages are saved in env for the next student.
2261: # All messages are saved in nohist_handgrade.db
2262: my ($ctr,$idx) = (1,1);
2263: while ($ctr <= $env{'form.savemsgN'}) {
2264: if ($env{'form.savemsg'.$ctr} ne '') {
2265: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
2266: $idx++;
2267: }
2268: $ctr++;
2269: }
2270: $ctr = 0;
2271: while ($ctr < $ngrade) {
2272: if ($env{'form.newmsg'.$ctr} ne '') {
2273: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2274: $env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2275: $idx++;
2276: }
2277: $ctr++;
2278: }
2279: $env{'form.savemsgN'} = --$idx;
2280: $keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
2281: my $putresult = &Apache::lonnet::put
2282: ('nohist_handgrade',\%keyhash,$cdom,$cnum);
2283: }
2284: # Called by Save & Refresh from Highlight Attribute Window
2285: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
2286: if ($env{'form.refresh'} eq 'on') {
2287: my ($ctr,$total) = (0,0);
2288: while ($ctr < $ngrade) {
2289: $total++ if $env{'form.unamedom'.$ctr} ne '';
2290: $ctr++;
2291: }
2292: $env{'form.NTSTU'}=$ngrade;
2293: $ctr = 0;
2294: while ($ctr < $total) {
2295: my $processUser = $env{'form.unamedom'.$ctr};
2296: ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
2297: $env{'form.fullname'} = $$fullname{$processUser};
2298: &submission($request,$ctr,$total-1);
2299: $ctr++;
2300: }
2301: return '';
2302: }
2303:
2304: # Go directly to grade student - from submission or link from chart page
2305: if ($button eq 'Grade Student') {
2306: (undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
2307: my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
2308: ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
2309: $env{'form.fullname'} = $$fullname{$processUser};
2310: &submission($request,0,0);
2311: return '';
2312: }
2313:
2314: # Get the next/previous one or group of students
2315: my $firststu = $env{'form.unamedom0'};
2316: my $laststu = $env{'form.unamedom'.($ngrade-1)};
2317: my $ctr = 2;
2318: while ($laststu eq '') {
2319: $laststu = $env{'form.unamedom'.($ngrade-$ctr)};
2320: $ctr++;
2321: $laststu = $firststu if ($ctr > $ngrade);
2322: }
2323:
2324: my (@parsedlist,@nextlist);
2325: my ($nextflg) = 0;
2326: foreach (sort
2327: {
2328: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
2329: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
2330: }
2331: return $a cmp $b;
2332: } (keys(%$fullname))) {
2333: if ($nextflg == 1 && $button =~ /Next$/) {
2334: push @parsedlist,$_;
2335: }
2336: $nextflg = 1 if ($_ eq $laststu);
2337: if ($button eq 'Previous') {
2338: last if ($_ eq $firststu);
2339: push @parsedlist,$_;
2340: }
2341: }
2342: $ctr = 0;
2343: @parsedlist = reverse @parsedlist if ($button eq 'Previous');
2344: my ($partlist) = &response_type($symb);
2345: foreach my $student (@parsedlist) {
2346: my $submitonly=$env{'form.submitonly'};
2347: my ($uname,$udom) = split(/:/,$student);
2348:
2349: if ($submitonly eq 'queued') {
2350: my %queue_status =
2351: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
2352: $udom,$uname);
2353: next if (!defined($queue_status{'gradingqueue'}));
2354: }
2355:
2356: if ($submitonly =~ /^(yes|graded|incorrect)$/) {
2357: # my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
2358: my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
2359: my $submitted = 0;
2360: my $ungraded = 0;
2361: my $incorrect = 0;
2362: foreach (keys(%status)) {
2363: $submitted = 1 if ($status{$_} ne 'nothing');
2364: $ungraded = 1 if ($status{$_} =~ /^ungraded/);
2365: $incorrect = 1 if ($status{$_} =~ /^incorrect/);
2366: my ($foo,$partid,$foo1) = split(/\./,$_);
2367: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
2368: $submitted = 0;
2369: }
2370: }
2371: next if (!$submitted && ($submitonly eq 'yes' ||
2372: $submitonly eq 'incorrect' ||
2373: $submitonly eq 'graded'));
2374: next if (!$ungraded && ($submitonly eq 'graded'));
2375: next if (!$incorrect && $submitonly eq 'incorrect');
2376: }
2377: push @nextlist,$student if ($ctr < $ntstu);
2378: last if ($ctr == $ntstu);
2379: $ctr++;
2380: }
2381:
2382: $ctr = 0;
2383: my $total = scalar(@nextlist)-1;
2384:
2385: foreach (sort @nextlist) {
2386: my ($uname,$udom,$submitter) = split(/:/);
2387: $env{'form.student'} = $uname;
2388: $env{'form.userdom'} = $udom;
2389: $env{'form.fullname'} = $$fullname{$_};
2390: &submission($request,$ctr,$total);
2391: $ctr++;
2392: }
2393: if ($total < 0) {
2394: my $the_end = '<h3><span class="LC_info">LON-CAPA User Message</span></h3><br />'."\n";
2395: $the_end.='<b>Message: </b> No more students for this section or class.<br /><br />'."\n";
2396: $the_end.='Click on the button below to return to the grading menu.<br /><br />'."\n";
2397: $the_end.=&show_grading_menu_form($symb);
2398: $request->print($the_end);
2399: }
2400: return '';
2401: }
2402:
2403: #---- Save the score and award for each student, if changed
2404: sub saveHandGrade {
2405: my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
2406: my @version_parts;
2407: my $usec = &Apache::lonnet::getsection($domain,$stuname,
2408: $env{'request.course.id'});
2409: if (!&canmodify($usec)) { return('not_allowed'); }
2410: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
2411: my @parts_graded;
2412: my %newrecord = ();
2413: my ($pts,$wgt) = ('','');
2414: my %aggregate = ();
2415: my $aggregateflag = 0;
2416: my @parts = split(/:/,$env{'form.partlist'.$newflg});
2417: foreach my $new_part (@parts) {
2418: #collaborator ($submi may vary for different parts
2419: if ($submitter && $new_part ne $part) { next; }
2420: my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
2421: if ($dropMenu eq 'excused') {
2422: if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
2423: $newrecord{'resource.'.$new_part.'.solved'} = 'excused';
2424: if (exists($record{'resource.'.$new_part.'.awarded'})) {
2425: $newrecord{'resource.'.$new_part.'.awarded'} = '';
2426: }
2427: $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
2428: }
2429: } elsif ($dropMenu eq 'reset status'
2430: && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
2431: foreach my $key (keys (%record)) {
2432: if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
2433: }
2434: $newrecord{'resource.'.$new_part.'.regrader'}=
2435: "$env{'user.name'}:$env{'user.domain'}";
2436: my $totaltries = $record{'resource.'.$part.'.tries'};
2437:
2438: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
2439: [$new_part]);
2440: my $aggtries =$totaltries;
2441: if ($last_resets{$new_part}) {
2442: $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
2443: $new_part);
2444: }
2445:
2446: my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
2447: if ($aggtries > 0) {
2448: &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
2449: $aggregateflag = 1;
2450: }
2451: } elsif ($dropMenu eq '') {
2452: $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ?
2453: $env{'form.GD_BOX'.$newflg.'_'.$new_part} :
2454: $env{'form.RADVAL'.$newflg.'_'.$new_part});
2455: if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
2456: next;
2457: }
2458: $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 :
2459: $env{'form.WGT'.$newflg.'_'.$new_part};
2460: my $partial= $pts/$wgt;
2461: if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
2462: #do not update score for part if not changed.
2463: &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
2464: next;
2465: } else {
2466: push @parts_graded, $new_part;
2467: }
2468: if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
2469: $newrecord{'resource.'.$new_part.'.awarded'} = $partial;
2470: }
2471: my $reckey = 'resource.'.$new_part.'.solved';
2472: if ($partial == 0) {
2473: if ($record{$reckey} ne 'incorrect_by_override') {
2474: $newrecord{$reckey} = 'incorrect_by_override';
2475: }
2476: } else {
2477: if ($record{$reckey} ne 'correct_by_override') {
2478: $newrecord{$reckey} = 'correct_by_override';
2479: }
2480: }
2481: if ($submitter &&
2482: ($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
2483: $newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
2484: }
2485: $newrecord{'resource.'.$new_part.'.regrader'}=
2486: "$env{'user.name'}:$env{'user.domain'}";
2487: }
2488: # unless problem has been graded, set flag to version the submitted files
2489: unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/ ||
2490: $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
2491: $dropMenu eq 'reset status')
2492: {
2493: push (@version_parts,$new_part);
2494: }
2495: }
2496: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2497: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2498:
2499: if (%newrecord) {
2500: if (@version_parts) {
2501: my @changed_keys = &version_portfiles(\%record, \@parts_graded,
2502: $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
2503: @newrecord{@changed_keys} = @record{@changed_keys};
2504: foreach my $new_part (@version_parts) {
2505: &handback_files($request,$symb,$stuname,$domain,$newflg,
2506: $new_part,\%newrecord);
2507: }
2508: }
2509: &Apache::lonnet::cstore(\%newrecord,$symb,
2510: $env{'request.course.id'},$domain,$stuname);
2511: &check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
2512: $cdom,$cnum,$domain,$stuname);
2513: }
2514: if ($aggregateflag) {
2515: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
2516: $cdom,$cnum);
2517: }
2518: return ('',$pts,$wgt);
2519: }
2520:
2521: sub check_and_remove_from_queue {
2522: my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
2523: my @ungraded_parts;
2524: foreach my $part (@{$parts}) {
2525: if ( $record->{ 'resource.'.$part.'.awarded'} eq ''
2526: && $record->{ 'resource.'.$part.'.solved' } ne 'excused'
2527: && $newrecord->{'resource.'.$part.'.awarded'} eq ''
2528: && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
2529: ) {
2530: push(@ungraded_parts, $part);
2531: }
2532: }
2533: if ( !@ungraded_parts ) {
2534: &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
2535: $cnum,$domain,$stuname);
2536: }
2537: }
2538:
2539: sub handback_files {
2540: my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
2541: my $portfolio_root = &propath($domain,$stuname).'/userfiles/portfolio';
2542: my ($partlist,$handgrade,$responseType) = &response_type($symb);
2543:
2544: my @part_response_id = &flatten_responseType($responseType);
2545: foreach my $part_response_id (@part_response_id) {
2546: my ($part_id,$resp_id) = @{ $part_response_id };
2547: my $part_resp = join('_',@{ $part_response_id });
2548: if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
2549: # if multiple files are uploaded names will be 'returndoc2','returndoc3'
2550: my $file_counter = 1;
2551: my $file_msg;
2552: while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
2553: my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
2554: my ($directory,$answer_file) =
2555: ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
2556: my ($answer_name,$answer_ver,$answer_ext) =
2557: &file_name_version_ext($answer_file);
2558: my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
2559: my @dir_list = &Apache::lonnet::dirlist($portfolio_path,$domain,$stuname,$portfolio_root);
2560: my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
2561: # fix file name
2562: my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
2563: my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
2564: $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
2565: $save_file_name);
2566: if ($result !~ m|^/uploaded/|) {
2567: $request->print('<span class="LC_error">An error occurred ('.$result.
2568: ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</span><br />');
2569: } else {
2570: # mark the file as read only
2571: my @files = ($save_file_name);
2572: my @what = ($symb,$env{'request.course.id'},'handback');
2573: &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
2574: if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
2575: $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
2576: }
2577: $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
2578: $file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
2579:
2580: }
2581: $request->print("<br />".$fname." will be the uploaded file name");
2582: $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
2583: $file_counter++;
2584: }
2585: my $subject = "File Handed Back by Instructor ";
2586: my $message = "A file has been returned that was originally submitted in reponse to: <br />";
2587: $message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
2588: $message .= ' The returned file(s) are named: '. $file_msg;
2589: $message .= " and can be found in your portfolio space.";
2590: my $url = (&Apache::lonnet::decode_symb($symb))[2];
2591: my $feedurl = &Apache::lonnet::clutter($url);
2592: my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
2593: $symb,$domain,$stuname);
2594: my ($baseurl,$showsymb);
2595: if ($encrypturl =~ /^yes$/i) {
2596: $baseurl = &Apache::lonenc::encrypted($feedurl,1);
2597: $showsymb = &Apache::lonenc::encrypted($symb,1);
2598: } else {
2599: $baseurl = $feedurl;
2600: $showsymb = $symb;
2601: }
2602: my $restitle = &Apache::lonnet::gettitle($symb);
2603: my $msgstatus =
2604: &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
2605: ' (File Returned) ['.$restitle.']',$message,undef,
2606: $baseurl,undef,undef,undef,$showsymb,$restitle);
2607: }
2608: }
2609: return;
2610: }
2611:
2612: sub get_submitted_files {
2613: my ($udom,$uname,$partid,$respid,$record) = @_;
2614: my @files;
2615: if ($$record{"resource.$partid.$respid.portfiles"}) {
2616: my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
2617: foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
2618: push(@files,$file_url.$file);
2619: }
2620: }
2621: if ($$record{"resource.$partid.$respid.uploadedurl"}) {
2622: push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
2623: }
2624: return (\@files);
2625: }
2626:
2627: # ----------- Provides number of tries since last reset.
2628: sub get_num_tries {
2629: my ($record,$last_reset,$part) = @_;
2630: my $timestamp = '';
2631: my $num_tries = 0;
2632: if ($$record{'version'}) {
2633: for (my $version=$$record{'version'};$version>=1;$version--) {
2634: if (exists($$record{$version.':resource.'.$part.'.solved'})) {
2635: $timestamp = $$record{$version.':timestamp'};
2636: if ($timestamp > $last_reset) {
2637: $num_tries ++;
2638: } else {
2639: last;
2640: }
2641: }
2642: }
2643: }
2644: return $num_tries;
2645: }
2646:
2647: # ----------- Determine decrements required in aggregate totals
2648: sub decrement_aggs {
2649: my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
2650: my %decrement = (
2651: attempts => 0,
2652: users => 0,
2653: correct => 0
2654: );
2655: $decrement{'attempts'} = $aggtries;
2656: if ($solvedstatus =~ /^correct/) {
2657: $decrement{'correct'} = 1;
2658: }
2659: if ($aggtries == $totaltries) {
2660: $decrement{'users'} = 1;
2661: }
2662: foreach my $type (keys (%decrement)) {
2663: $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
2664: }
2665: return;
2666: }
2667:
2668: # ----------- Determine timestamps for last reset of aggregate totals for parts
2669: sub get_last_resets {
2670: my ($symb,$courseid,$partids) =@_;
2671: my %last_resets;
2672: my $cdom = $env{'course.'.$courseid.'.domain'};
2673: my $cname = $env{'course.'.$courseid.'.num'};
2674: my @keys;
2675: foreach my $part (@{$partids}) {
2676: push(@keys,"$symb\0$part\0resettime");
2677: }
2678: my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
2679: $cdom,$cname);
2680: foreach my $part (@{$partids}) {
2681: $last_resets{$part}=$results{"$symb\0$part\0resettime"};
2682: }
2683: return %last_resets;
2684: }
2685:
2686: # ----------- Handles creating versions for portfolio files as answers
2687: sub version_portfiles {
2688: my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
2689: my $version_parts = join('|',@$v_flag);
2690: my @returned_keys;
2691: my $parts = join('|', @$parts_graded);
2692: my $portfolio_root = &propath($domain,$stu_name).
2693: '/userfiles/portfolio';
2694: foreach my $key (keys(%$record)) {
2695: my $new_portfiles;
2696: if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
2697: my @versioned_portfiles;
2698: my @portfiles = split(/\s*,\s*/,$$record{$key});
2699: foreach my $file (@portfiles) {
2700: &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
2701: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
2702: my ($answer_name,$answer_ver,$answer_ext) =
2703: &file_name_version_ext($answer_file);
2704: my @dir_list = &Apache::lonnet::dirlist($directory,$domain,$stu_name,$portfolio_root);
2705: my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
2706: my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
2707: if ($new_answer ne 'problem getting file') {
2708: push(@versioned_portfiles, $directory.$new_answer);
2709: &Apache::lonnet::mark_as_readonly($domain,$stu_name,
2710: [$directory.$new_answer],
2711: [$symb,$env{'request.course.id'},'graded']);
2712: }
2713: }
2714: $$record{$key} = join(',',@versioned_portfiles);
2715: push(@returned_keys,$key);
2716: }
2717: }
2718: return (@returned_keys);
2719: }
2720:
2721: sub get_next_version {
2722: my ($answer_name, $answer_ext, $dir_list) = @_;
2723: my $version;
2724: foreach my $row (@$dir_list) {
2725: my ($file) = split(/\&/,$row,2);
2726: my ($file_name,$file_version,$file_ext) =
2727: &file_name_version_ext($file);
2728: if (($file_name eq $answer_name) &&
2729: ($file_ext eq $answer_ext)) {
2730: # gets here if filename and extension match, regardless of version
2731: if ($file_version ne '') {
2732: # a versioned file is found so save it for later
2733: if ($file_version > $version) {
2734: $version = $file_version;
2735: }
2736: }
2737: }
2738: }
2739: $version ++;
2740: return($version);
2741: }
2742:
2743: sub version_selected_portfile {
2744: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
2745: my ($answer_name,$answer_ver,$answer_ext) =
2746: &file_name_version_ext($file_name);
2747: my $new_answer;
2748: $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
2749: if($env{'form.copy'} eq '-1') {
2750: &Apache::lonnet::logthis('problem getting file '.$file_name);
2751: $new_answer = 'problem getting file';
2752: } else {
2753: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
2754: my $copy_result = &Apache::lonnet::finishuserfileupload(
2755: $stu_name,$domain,'copy',
2756: '/portfolio'.$directory.$new_answer);
2757: }
2758: return ($new_answer);
2759: }
2760:
2761: sub file_name_version_ext {
2762: my ($file)=@_;
2763: my @file_parts = split(/\./, $file);
2764: my ($name,$version,$ext);
2765: if (@file_parts > 1) {
2766: $ext=pop(@file_parts);
2767: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
2768: $version=pop(@file_parts);
2769: }
2770: $name=join('.',@file_parts);
2771: } else {
2772: $name=join('.',@file_parts);
2773: }
2774: return($name,$version,$ext);
2775: }
2776:
2777: #--------------------------------------------------------------------------------------
2778: #
2779: #-------------------------- Next few routines handles grading by section or whole class
2780: #
2781: #--- Javascript to handle grading by section or whole class
2782: sub viewgrades_js {
2783: my ($request) = shift;
2784:
2785: $request->print(<<VIEWJAVASCRIPT);
2786: <script type="text/javascript" language="javascript">
2787: function writePoint(partid,weight,point) {
2788: var radioButton = document.classgrade["RADVAL_"+partid];
2789: var textbox = document.classgrade["TEXTVAL_"+partid];
2790: if (point == "textval") {
2791: point = document.classgrade["TEXTVAL_"+partid].value;
2792: if (isNaN(point) || parseFloat(point) < 0) {
2793: alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
2794: var resetbox = false;
2795: for (var i=0; i<radioButton.length; i++) {
2796: if (radioButton[i].checked) {
2797: textbox.value = i;
2798: resetbox = true;
2799: }
2800: }
2801: if (!resetbox) {
2802: textbox.value = "";
2803: }
2804: return;
2805: }
2806: if (parseFloat(point) > parseFloat(weight)) {
2807: var resp = confirm("You entered a value ("+parseFloat(point)+
2808: ") greater than the weight for the part. Accept?");
2809: if (resp == false) {
2810: textbox.value = "";
2811: return;
2812: }
2813: }
2814: for (var i=0; i<radioButton.length; i++) {
2815: radioButton[i].checked=false;
2816: if (parseFloat(point) == i) {
2817: radioButton[i].checked=true;
2818: }
2819: }
2820:
2821: } else {
2822: textbox.value = parseFloat(point);
2823: }
2824: for (i=0;i<document.classgrade.total.value;i++) {
2825: var user = document.classgrade["ctr"+i].value;
2826: user = user.replace(new RegExp(':', 'g'),"_");
2827: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
2828: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
2829: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
2830: if (saveval != "correct") {
2831: scorename.value = point;
2832: if (selname[0].selected != true) {
2833: selname[0].selected = true;
2834: }
2835: }
2836: }
2837: document.classgrade["SELVAL_"+partid][0].selected = true;
2838: }
2839:
2840: function writeRadText(partid,weight) {
2841: var selval = document.classgrade["SELVAL_"+partid];
2842: var radioButton = document.classgrade["RADVAL_"+partid];
2843: var override = document.classgrade["FORCE_"+partid].checked;
2844: var textbox = document.classgrade["TEXTVAL_"+partid];
2845: if (selval[1].selected || selval[2].selected) {
2846: for (var i=0; i<radioButton.length; i++) {
2847: radioButton[i].checked=false;
2848:
2849: }
2850: textbox.value = "";
2851:
2852: for (i=0;i<document.classgrade.total.value;i++) {
2853: var user = document.classgrade["ctr"+i].value;
2854: user = user.replace(new RegExp(':', 'g'),"_");
2855: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
2856: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
2857: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
2858: if ((saveval != "correct") || override) {
2859: scorename.value = "";
2860: if (selval[1].selected) {
2861: selname[1].selected = true;
2862: } else {
2863: selname[2].selected = true;
2864: if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value))
2865: {document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
2866: }
2867: }
2868: }
2869: } else {
2870: for (i=0;i<document.classgrade.total.value;i++) {
2871: var user = document.classgrade["ctr"+i].value;
2872: user = user.replace(new RegExp(':', 'g'),"_");
2873: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
2874: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
2875: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
2876: if ((saveval != "correct") || override) {
2877: scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
2878: selname[0].selected = true;
2879: }
2880: }
2881: }
2882: }
2883:
2884: function changeSelect(partid,user) {
2885: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
2886: var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
2887: var point = textbox.value;
2888: var weight = document.classgrade["weight_"+partid].value;
2889:
2890: if (isNaN(point) || parseFloat(point) < 0) {
2891: alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
2892: textbox.value = "";
2893: return;
2894: }
2895: if (parseFloat(point) > parseFloat(weight)) {
2896: var resp = confirm("You entered a value ("+parseFloat(point)+
2897: ") greater than the weight of the part. Accept?");
2898: if (resp == false) {
2899: textbox.value = "";
2900: return;
2901: }
2902: }
2903: selval[0].selected = true;
2904: }
2905:
2906: function changeOneScore(partid,user) {
2907: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
2908: if (selval[1].selected || selval[2].selected) {
2909: document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
2910: if (selval[2].selected) {
2911: document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
2912: }
2913: }
2914: }
2915:
2916: function resetEntry(numpart) {
2917: for (ctpart=0;ctpart<numpart;ctpart++) {
2918: var partid = document.classgrade["partid_"+ctpart].value;
2919: var radioButton = document.classgrade["RADVAL_"+partid];
2920: var textbox = document.classgrade["TEXTVAL_"+partid];
2921: var selval = document.classgrade["SELVAL_"+partid];
2922: for (var i=0; i<radioButton.length; i++) {
2923: radioButton[i].checked=false;
2924:
2925: }
2926: textbox.value = "";
2927: selval[0].selected = true;
2928:
2929: for (i=0;i<document.classgrade.total.value;i++) {
2930: var user = document.classgrade["ctr"+i].value;
2931: user = user.replace(new RegExp(':', 'g'),"_");
2932: var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
2933: resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
2934: var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
2935: resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
2936: var saveselval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
2937: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
2938: if (saveselval == "excused") {
2939: if (selname[1].selected == false) { selname[1].selected = true;}
2940: } else {
2941: if (selname[0].selected == false) {selname[0].selected = true};
2942: }
2943: }
2944: }
2945: }
2946:
2947: </script>
2948: VIEWJAVASCRIPT
2949: }
2950:
2951: #--- show scores for a section or whole class w/ option to change/update a score
2952: sub viewgrades {
2953: my ($request) = shift;
2954: &viewgrades_js($request);
2955:
2956: my ($symb) = &get_symb($request);
2957: #need to make sure we have the correct data for later EXT calls,
2958: #thus invalidate the cache
2959: &Apache::lonnet::devalidatecourseresdata(
2960: $env{'course.'.$env{'request.course.id'}.'.num'},
2961: $env{'course.'.$env{'request.course.id'}.'.domain'});
2962: &Apache::lonnet::clear_EXT_cache_status();
2963:
2964: my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
2965: $result.='<h4><b>Current Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n";
2966:
2967: #view individual student submission form - called using Javascript viewOneStudent
2968: $result.=&jscriptNform($symb);
2969:
2970: #beginning of class grading form
2971: $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
2972: '<input type="hidden" name="symb" value="'.$symb.'" />'."\n".
2973: '<input type="hidden" name="command" value="editgrades" />'."\n".
2974: '<input type="hidden" name="section" value="'.$env{'form.section'}.'" />'."\n".
2975: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
2976: '<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n".
2977: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
2978:
2979: my $sectionClass;
2980: if ($env{'form.section'} eq 'all') {
2981: $sectionClass='Class </h3>';
2982: } elsif ($env{'form.section'} eq 'none') {
2983: $sectionClass='Students in no Section </h3>';
2984: } else {
2985: $sectionClass='Students in Section '.$env{'form.section'}.'</h3>';
2986: }
2987: $result.='<h3>Assign Common Grade To '.$sectionClass;
2988: $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
2989: '<table border=0><tr bgcolor="#ffffdd"><td>';
2990: #radio buttons/text box for assigning points for a section or class.
2991: #handles different parts of a problem
2992: my ($partlist,$handgrade,$responseType) = &response_type($symb);
2993: my %weight = ();
2994: my $ctsparts = 0;
2995: $result.='<table border="0">';
2996: my %seen = ();
2997: my @part_response_id = &flatten_responseType($responseType);
2998: foreach my $part_response_id (@part_response_id) {
2999: my ($partid,$respid) = @{ $part_response_id };
3000: my $part_resp = join('_',@{ $part_response_id });
3001: next if $seen{$partid};
3002: $seen{$partid}++;
3003: my $handgrade=$$handgrade{$part_resp};
3004: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
3005: $weight{$partid} = $wgt eq '' ? '1' : $wgt;
3006:
3007: $result.='<input type="hidden" name="partid_'.
3008: $ctsparts.'" value="'.$partid.'" />'."\n";
3009: $result.='<input type="hidden" name="weight_'.
3010: $partid.'" value="'.$weight{$partid}.'" />'."\n";
3011: my $display_part=&get_display_part($partid,$symb);
3012: $result.='<tr><td><b>Part:</b> '.$display_part.' <b>Point:</b> </td><td>';
3013: $result.='<table border="0"><tr>';
3014: my $ctr = 0;
3015: while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
3016: $result.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
3017: 'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
3018: ','.$ctr.')" />'.$ctr."</label></td>\n";
3019: $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
3020: $ctr++;
3021: }
3022: $result.='</tr></table>';
3023: $result.= '</td><td><b> or </b><input type="text" name="TEXTVAL_'.
3024: $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
3025: $partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
3026: $weight{$partid}.' (problem weight)</td>'."\n";
3027: $result.= '</td><td><select name="SELVAL_'.$partid.'"'.
3028: 'onChange="javascript:writeRadText(\''.$partid.'\','.
3029: $weight{$partid}.')"> '.
3030: '<option selected="selected"> </option>'.
3031: '<option>excused</option>'.
3032: '<option>reset status</option></select></td>'.
3033: '<td><label><input type="checkbox" name="FORCE_'.$partid.'" /> Override "Correct"</label></td></tr>'."\n";
3034: $ctsparts++;
3035: }
3036: $result.='</table>'.'</td></tr></table>'.'</td></tr></table>'."\n".
3037: '<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
3038: $result.='<input type="button" value="Revert to Default" '.
3039: 'onClick="javascript:resetEntry('.$ctsparts.');" TARGET=_self>';
3040:
3041: #table listing all the students in a section/class
3042: #header of table
3043: $result.= '<h3>Assign Grade to Specific Students in '.$sectionClass;
3044: $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
3045: '<table border=0><tr bgcolor="#deffff"><td> <b>No.</b> </td>'.
3046: '<td>'.&nameUserString('header')."</td>\n";
3047: my (@parts) = sort(&getpartlist($symb));
3048: my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
3049: my @partids = ();
3050: foreach my $part (@parts) {
3051: my $display=&Apache::lonnet::metadata($url,$part.'.display');
3052: $display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
3053: if (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
3054: my ($partid) = &split_part_type($part);
3055: push(@partids, $partid);
3056: my $display_part=&get_display_part($partid,$symb);
3057: if ($display =~ /^Partial Credit Factor/) {
3058: $result.='<td><b>Score Part:</b> '.$display_part.
3059: ' <br /><b>(weight = '.$weight{$partid}.')</b></td>'."\n";
3060: next;
3061: } else {
3062: $display =~s/\[Part: \Q$partid\E\]/Part:<\/b> $display_part/;
3063: }
3064: $display =~ s|Problem Status|Grade Status<br />|;
3065: $result.='<td><b>'.$display.'</td>'."\n";
3066: }
3067: $result.='</tr>';
3068:
3069: my %last_resets =
3070: &get_last_resets($symb,$env{'request.course.id'},\@partids);
3071:
3072: #get info for each student
3073: #list all the students - with points and grade status
3074: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
3075: my $ctr = 0;
3076: foreach (sort
3077: {
3078: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
3079: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
3080: }
3081: return $a cmp $b;
3082: } (keys(%$fullname))) {
3083: $ctr++;
3084: $result.=&viewstudentgrade($symb,$env{'request.course.id'},
3085: $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
3086: }
3087: $result.='</table></td></tr></table>';
3088: $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
3089: $result.='<input type="button" value="Save" '.
3090: 'onClick="javascript:submit();" TARGET=_self /></form>'."\n";
3091: if (scalar(%$fullname) eq 0) {
3092: my $colspan=3+scalar(@parts);
3093: $result='<span class="LC_warning">There are no students in section "'.$env{'form.section'}.
3094: '" with enrollment status "'.$env{'form.Status'}.'" to modify or grade.</span>';
3095: }
3096: $result.=&show_grading_menu_form($symb);
3097: return $result;
3098: }
3099:
3100: #--- call by previous routine to display each student
3101: sub viewstudentgrade {
3102: my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
3103: my ($uname,$udom) = split(/:/,$student);
3104: my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
3105: my %aggregates = ();
3106: my $result='<tr bgcolor="#ffffdd"><td align="right">'.
3107: '<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
3108: "\n".$ctr.' </td><td> '.
3109: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
3110: '\')"; TARGET=_self>'.$fullname.'</a> '.
3111: '<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
3112: $student=~s/:/_/; # colon doen't work in javascript for names
3113: foreach my $apart (@$parts) {
3114: my ($part,$type) = &split_part_type($apart);
3115: my $score=$record{"resource.$part.$type"};
3116: $result.='<td align="center">';
3117: my ($aggtries,$totaltries);
3118: unless (exists($aggregates{$part})) {
3119: $totaltries = $record{'resource.'.$part.'.tries'};
3120:
3121: $aggtries = $totaltries;
3122: if ($$last_resets{$part}) {
3123: $aggtries = &get_num_tries(\%record,$$last_resets{$part},
3124: $part);
3125: }
3126: $result.='<input type="hidden" name="'.
3127: 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
3128: $result.='<input type="hidden" name="'.
3129: 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
3130: $aggregates{$part} = 1;
3131: }
3132: if ($type eq 'awarded') {
3133: my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
3134: $result.='<input type="hidden" name="'.
3135: 'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
3136: $result.='<input type="text" name="'.
3137: 'GD_'.$student.'_'.$part.'_awarded" '.
3138: 'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
3139: '\')" value="'.$pts.'" size="4" /></td>'."\n";
3140: } elsif ($type eq 'solved') {
3141: my ($status,$foo)=split(/_/,$score,2);
3142: $status = 'nothing' if ($status eq '');
3143: $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
3144: $part.'_solved_s" value="'.$status.'" />'."\n";
3145: $result.=' <select name="'.
3146: 'GD_'.$student.'_'.$part.'_solved" '.
3147: 'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
3148: $result.= (($status eq 'excused') ? '<option> </option><option selected="selected">excused</option>'
3149: : '<option selected="selected"> </option><option>excused</option>')."\n";
3150: $result.='<option>reset status</option>';
3151: $result.="</select> </td>\n";
3152: } else {
3153: $result.='<input type="hidden" name="'.
3154: 'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
3155: "\n";
3156: $result.='<input type="text" name="'.
3157: 'GD_'.$student.'_'.$part.'_'.$type.'" '.
3158: 'value="'.$score.'" size="4" /></td>'."\n";
3159: }
3160: }
3161: $result.='</tr>';
3162: return $result;
3163: }
3164:
3165: #--- change scores for all the students in a section/class
3166: # record does not get update if unchanged
3167: sub editgrades {
3168: my ($request) = @_;
3169:
3170: my $symb=&get_symb($request);
3171: my $title='<h3><span class="LC_info">Current Grade Status</span></h3>';
3172: $title.='<h4><b>Current Resource: </b>'.$env{'form.probTitle'}.'</h4><br />'."\n";
3173: $title.='<h4><b>Section: </b>'.$env{'form.section'}.'</h4>'."\n";
3174:
3175: my $result= '<table border="0"><tr><td bgcolor="#777777">'."\n";
3176: $result.= '<table border="0"><tr bgcolor="#deffff">'.
3177: '<td rowspan=2 valign="center"> <b>No.</b> </td>'.
3178: '<td rowspan=2 valign="center">'.&nameUserString('header')."</td>\n";
3179:
3180: my %scoreptr = (
3181: 'correct' =>'correct_by_override',
3182: 'incorrect'=>'incorrect_by_override',
3183: 'excused' =>'excused',
3184: 'ungraded' =>'ungraded_attempted',
3185: 'nothing' => '',
3186: );
3187: my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
3188:
3189: my (@partid);
3190: my %weight = ();
3191: my %columns = ();
3192: my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
3193:
3194: my (@parts) = sort(&getpartlist($symb));
3195: my $header;
3196: while ($ctr < $env{'form.totalparts'}) {
3197: my $partid = $env{'form.partid_'.$ctr};
3198: push @partid,$partid;
3199: $weight{$partid} = $env{'form.weight_'.$partid};
3200: $ctr++;
3201: }
3202: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3203: foreach my $partid (@partid) {
3204: $header .= '<td align="center"> <b>Old Score</b> </td>'.
3205: '<td align="center"> <b>New Score</b> </td>';
3206: $columns{$partid}=2;
3207: foreach my $stores (@parts) {
3208: my ($part,$type) = &split_part_type($stores);
3209: if ($part !~ m/^\Q$partid\E/) { next;}
3210: if ($type eq 'awarded' || $type eq 'solved') { next; }
3211: my $display=&Apache::lonnet::metadata($url,$stores.'.display');
3212: $display =~ s/\[Part: (\w)+\]//;
3213: $display =~ s/Number of Attempts/Tries/;
3214: $header .= '<td align="center"> <b>Old '.$display.'</b> </td>'.
3215: '<td align="center"> <b>New '.$display.'</b> </td>';
3216: $columns{$partid}+=2;
3217: }
3218: }
3219: foreach my $partid (@partid) {
3220: my $display_part=&get_display_part($partid,$symb);
3221: $result .= '<td colspan="'.$columns{$partid}.
3222: '" align="center"><b>Part:</b> '.$display_part.
3223: ' (Weight = '.$weight{$partid}.')</td>';
3224:
3225: }
3226: $result .= '</tr><tr bgcolor="#deffff">';
3227: $result .= $header;
3228: $result .= '</tr>'."\n";
3229: my $noupdate;
3230: my ($updateCtr,$noupdateCtr) = (1,1);
3231: for ($i=0; $i<$env{'form.total'}; $i++) {
3232: my $line;
3233: my $user = $env{'form.ctr'.$i};
3234: my ($uname,$udom)=split(/:/,$user);
3235: my %newrecord;
3236: my $updateflag = 0;
3237: $line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
3238: my $usec=$classlist->{"$uname:$udom"}[5];
3239: if (!&canmodify($usec)) {
3240: my $numcols=scalar(@partid)*4+2;
3241: $noupdate.=$line."<td colspan=\"$numcols\"><span class=\"LC_warning\">Not allowed to modify student</span></td></tr>";
3242: next;
3243: }
3244: my %aggregate = ();
3245: my $aggregateflag = 0;
3246: $user=~s/:/_/; # colon doen't work in javascript for names
3247: foreach (@partid) {
3248: my $old_aw = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
3249: my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
3250: my $old_part = $old_aw eq '' ? '' : $old_part_pcr;
3251: my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
3252: my $awarded = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
3253: my $pcr = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
3254: my $partial = $awarded eq '' ? '' : $pcr;
3255: my $score;
3256: if ($partial eq '') {
3257: $score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
3258: } elsif ($partial > 0) {
3259: $score = 'correct_by_override';
3260: } elsif ($partial == 0) {
3261: $score = 'incorrect_by_override';
3262: }
3263: my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
3264: $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
3265:
3266: $newrecord{'resource.'.$_.'.regrader'}=
3267: "$env{'user.name'}:$env{'user.domain'}";
3268: if ($dropMenu eq 'reset status' &&
3269: $old_score ne '') { # ignore if no previous attempts => nothing to reset
3270: $newrecord{'resource.'.$_.'.tries'} = '';
3271: $newrecord{'resource.'.$_.'.solved'} = '';
3272: $newrecord{'resource.'.$_.'.award'} = '';
3273: $newrecord{'resource.'.$_.'.awarded'} = '';
3274: $updateflag = 1;
3275: if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
3276: my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
3277: my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
3278: my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
3279: &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
3280: $aggregateflag = 1;
3281: }
3282: } elsif (!($old_part eq $partial && $old_score eq $score)) {
3283: $updateflag = 1;
3284: $newrecord{'resource.'.$_.'.awarded'} = $partial if $partial ne '';
3285: $newrecord{'resource.'.$_.'.solved'} = $score;
3286: $rec_update++;
3287: }
3288:
3289: $line .= '<td align="center">'.$old_aw.' </td>'.
3290: '<td align="center">'.$awarded.
3291: ($score eq 'excused' ? $score : '').' </td>';
3292:
3293:
3294: my $partid=$_;
3295: foreach my $stores (@parts) {
3296: my ($part,$type) = &split_part_type($stores);
3297: if ($part !~ m/^\Q$partid\E/) { next;}
3298: if ($type eq 'awarded' || $type eq 'solved') { next; }
3299: my $old_aw = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
3300: my $awarded = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
3301: if ($awarded ne '' && $awarded ne $old_aw) {
3302: $newrecord{'resource.'.$part.'.'.$type}= $awarded;
3303: $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
3304: $updateflag=1;
3305: }
3306: $line .= '<td align="center">'.$old_aw.' </td>'.
3307: '<td align="center">'.$awarded.' </td>';
3308: }
3309: }
3310: $line.='</tr>'."\n";
3311:
3312: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3313: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3314:
3315: if ($updateflag) {
3316: $count++;
3317: &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
3318: $udom,$uname);
3319:
3320: if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
3321: $cnum,$udom,$uname)) {
3322: # need to figure out if should be in queue.
3323: my %record =
3324: &Apache::lonnet::restore($symb,$env{'request.course.id'},
3325: $udom,$uname);
3326: my $all_graded = 1;
3327: my $none_graded = 1;
3328: foreach my $part (@parts) {
3329: if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
3330: $all_graded = 0;
3331: } else {
3332: $none_graded = 0;
3333: }
3334: }
3335:
3336: if ($all_graded || $none_graded) {
3337: &Apache::bridgetask::remove_from_queue('gradingqueue',
3338: $symb,$cdom,$cnum,
3339: $udom,$uname);
3340: }
3341: }
3342:
3343: $result.='<tr bgcolor="#ffffde"><td align="right"> '.$updateCtr.' </td>'.$line;
3344: $updateCtr++;
3345: } else {
3346: $noupdate.='<tr bgcolor="#ffffde"><td align="right"> '.$noupdateCtr.' </td>'.$line;
3347: $noupdateCtr++;
3348: }
3349: if ($aggregateflag) {
3350: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
3351: $cdom,$cnum);
3352: }
3353: }
3354: if ($noupdate) {
3355: # my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
3356: my $numcols=scalar(@partid)*4+2;
3357: $result .= '<tr bgcolor="#ffffff"><td align="center" colspan="'.$numcols.'">No Changes Occurred For the Students Below</td></tr><tr bgcolor="#ffffde">'.$noupdate;
3358: }
3359: $result .= '</table></td></tr></table>'."\n".
3360: &show_grading_menu_form ($symb);
3361: my $msg = '<br /><b>Number of records updated = '.$rec_update.
3362: ' for '.$count.' student'.($count <= 1 ? '' : 's').'.</b><br />'.
3363: '<b>Total number of students = '.$env{'form.total'}.'</b><br />';
3364: return $title.$msg.$result;
3365: }
3366:
3367: sub split_part_type {
3368: my ($partstr) = @_;
3369: my ($temp,@allparts)=split(/_/,$partstr);
3370: my $type=pop(@allparts);
3371: my $part=join('.',@allparts);
3372: return ($part,$type);
3373: }
3374:
3375: #------------- end of section for handling grading by section/class ---------
3376: #
3377: #----------------------------------------------------------------------------
3378:
3379:
3380: #----------------------------------------------------------------------------
3381: #
3382: #-------------------------- Next few routines handles grading by csv upload
3383: #
3384: #--- Javascript to handle csv upload
3385: sub csvupload_javascript_reverse_associate {
3386: my $error1=&mt('You need to specify the username or ID');
3387: my $error2=&mt('You need to specify at least one grading field');
3388: return(<<ENDPICK);
3389: function verify(vf) {
3390: var foundsomething=0;
3391: var founduname=0;
3392: var foundID=0;
3393: for (i=0;i<=vf.nfields.value;i++) {
3394: tw=eval('vf.f'+i+'.selectedIndex');
3395: if (i==0 && tw!=0) { foundID=1; }
3396: if (i==1 && tw!=0) { founduname=1; }
3397: if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
3398: }
3399: if (founduname==0 && foundID==0) {
3400: alert('$error1');
3401: return;
3402: }
3403: if (foundsomething==0) {
3404: alert('$error2');
3405: return;
3406: }
3407: vf.submit();
3408: }
3409: function flip(vf,tf) {
3410: var nw=eval('vf.f'+tf+'.selectedIndex');
3411: var i;
3412: for (i=0;i<=vf.nfields.value;i++) {
3413: //can not pick the same destination field for both name and domain
3414: if (((i ==0)||(i ==1)) &&
3415: ((tf==0)||(tf==1)) &&
3416: (i!=tf) &&
3417: (eval('vf.f'+i+'.selectedIndex')==nw)) {
3418: eval('vf.f'+i+'.selectedIndex=0;')
3419: }
3420: }
3421: }
3422: ENDPICK
3423: }
3424:
3425: sub csvupload_javascript_forward_associate {
3426: my $error1=&mt('You need to specify the username or ID');
3427: my $error2=&mt('You need to specify at least one grading field');
3428: return(<<ENDPICK);
3429: function verify(vf) {
3430: var foundsomething=0;
3431: var founduname=0;
3432: var foundID=0;
3433: for (i=0;i<=vf.nfields.value;i++) {
3434: tw=eval('vf.f'+i+'.selectedIndex');
3435: if (tw==1) { foundID=1; }
3436: if (tw==2) { founduname=1; }
3437: if (tw>3) { foundsomething=1; }
3438: }
3439: if (founduname==0 && foundID==0) {
3440: alert('$error1');
3441: return;
3442: }
3443: if (foundsomething==0) {
3444: alert('$error2');
3445: return;
3446: }
3447: vf.submit();
3448: }
3449: function flip(vf,tf) {
3450: var nw=eval('vf.f'+tf+'.selectedIndex');
3451: var i;
3452: //can not pick the same destination field twice
3453: for (i=0;i<=vf.nfields.value;i++) {
3454: if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
3455: eval('vf.f'+i+'.selectedIndex=0;')
3456: }
3457: }
3458: }
3459: ENDPICK
3460: }
3461:
3462: sub csvuploadmap_header {
3463: my ($request,$symb,$datatoken,$distotal)= @_;
3464: my $javascript;
3465: if ($env{'form.upfile_associate'} eq 'reverse') {
3466: $javascript=&csvupload_javascript_reverse_associate();
3467: } else {
3468: $javascript=&csvupload_javascript_forward_associate();
3469: }
3470:
3471: my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
3472: my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
3473: my $ignore=&mt('Ignore First Line');
3474: $request->print(<<ENDPICK);
3475: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3476: <h3><span class="LC_info">Uploading Class Grades</span></h3>
3477: $result
3478: <hr />
3479: <h3>Identify fields</h3>
3480: Total number of records found in file: $distotal <hr />
3481: Enter as many fields as you can. The system will inform you and bring you back
3482: to this page if the data selected is insufficient to run your class.<hr />
3483: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
3484: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
3485: <input type="hidden" name="associate" value="" />
3486: <input type="hidden" name="phase" value="three" />
3487: <input type="hidden" name="datatoken" value="$datatoken" />
3488: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
3489: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
3490: <input type="hidden" name="upfile_associate"
3491: value="$env{'form.upfile_associate'}" />
3492: <input type="hidden" name="symb" value="$symb" />
3493: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
3494: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
3495: <input type="hidden" name="command" value="csvuploadoptions" />
3496: <hr />
3497: <script type="text/javascript" language="Javascript">
3498: $javascript
3499: </script>
3500: ENDPICK
3501: return '';
3502:
3503: }
3504:
3505: sub csvupload_fields {
3506: my ($symb) = @_;
3507: my (@parts) = &getpartlist($symb);
3508: my @fields=(['ID','Student ID'],
3509: ['username','Student Username'],
3510: ['domain','Student Domain']);
3511: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3512: foreach my $part (sort(@parts)) {
3513: my @datum;
3514: my $display=&Apache::lonnet::metadata($url,$part.'.display');
3515: my $name=$part;
3516: if (!$display) { $display = $name; }
3517: @datum=($name,$display);
3518: if ($name=~/^stores_(.*)_awarded/) {
3519: push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
3520: }
3521: push(@fields,\@datum);
3522: }
3523: return (@fields);
3524: }
3525:
3526: sub csvuploadmap_footer {
3527: my ($request,$i,$keyfields) =@_;
3528: $request->print(<<ENDPICK);
3529: </table>
3530: <input type="hidden" name="nfields" value="$i" />
3531: <input type="hidden" name="keyfields" value="$keyfields" />
3532: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
3533: </form>
3534: ENDPICK
3535: }
3536:
3537: sub checkforfile_js {
3538: my $result =<<CSVFORMJS;
3539: <script type="text/javascript" language="javascript">
3540: function checkUpload(formname) {
3541: if (formname.upfile.value == "") {
3542: alert("Please use the browse button to select a file from your local directory.");
3543: return false;
3544: }
3545: formname.submit();
3546: }
3547: </script>
3548: CSVFORMJS
3549: return $result;
3550: }
3551:
3552: sub upcsvScores_form {
3553: my ($request) = shift;
3554: my ($symb)=&get_symb($request);
3555: if (!$symb) {return '';}
3556: my $result=&checkforfile_js();
3557: $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
3558: my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
3559: $result.=$table;
3560: $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
3561: $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
3562: $result.=' <b>'.&mt('Specify a file containing the class scores for current resource').
3563: '.</b></td></tr>'."\n";
3564: $result.='<tr bgcolor=#ffffe6><td>'."\n";
3565: my $upload=&mt("Upload Scores");
3566: my $upfile_select=&Apache::loncommon::upfile_select_html();
3567: my $ignore=&mt('Ignore First Line');
3568: $result.=<<ENDUPFORM;
3569: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3570: <input type="hidden" name="symb" value="$symb" />
3571: <input type="hidden" name="command" value="csvuploadmap" />
3572: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
3573: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
3574: $upfile_select
3575: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
3576: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
3577: </form>
3578: ENDUPFORM
3579: $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
3580: &mt("How do I create a CSV file from a spreadsheet"))
3581: .'</td></tr></table>'."\n";
3582: $result.='</td></tr></table><br /><br />'."\n";
3583: $result.=&show_grading_menu_form($symb);
3584: return $result;
3585: }
3586:
3587:
3588: sub csvuploadmap {
3589: my ($request)= @_;
3590: my ($symb)=&get_symb($request);
3591: if (!$symb) {return '';}
3592:
3593: my $datatoken;
3594: if (!$env{'form.datatoken'}) {
3595: $datatoken=&Apache::loncommon::upfile_store($request);
3596: } else {
3597: $datatoken=$env{'form.datatoken'};
3598: &Apache::loncommon::load_tmp_file($request);
3599: }
3600: my @records=&Apache::loncommon::upfile_record_sep();
3601: if ($env{'form.noFirstLine'}) { shift(@records); }
3602: &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
3603: my ($i,$keyfields);
3604: if (@records) {
3605: my @fields=&csvupload_fields($symb);
3606:
3607: if ($env{'form.upfile_associate'} eq 'reverse') {
3608: &Apache::loncommon::csv_print_samples($request,\@records);
3609: $i=&Apache::loncommon::csv_print_select_table($request,\@records,
3610: \@fields);
3611: foreach (@fields) { $keyfields.=$_->[0].','; }
3612: chop($keyfields);
3613: } else {
3614: unshift(@fields,['none','']);
3615: $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
3616: \@fields);
3617: foreach my $rec (@records) {
3618: my %temp = &Apache::loncommon::record_sep($rec);
3619: if (%temp) {
3620: $keyfields=join(',',sort(keys(%temp)));
3621: last;
3622: }
3623: }
3624: }
3625: }
3626: &csvuploadmap_footer($request,$i,$keyfields);
3627: $request->print(&show_grading_menu_form($symb));
3628:
3629: return '';
3630: }
3631:
3632: sub csvuploadoptions {
3633: my ($request)= @_;
3634: my ($symb)=&get_symb($request);
3635: my $checked=(($env{'form.noFirstLine'})?'1':'0');
3636: my $ignore=&mt('Ignore First Line');
3637: $request->print(<<ENDPICK);
3638: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3639: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
3640: <input type="hidden" name="command" value="csvuploadassign" />
3641: <!--
3642: <p>
3643: <label>
3644: <input type="checkbox" name="show_full_results" />
3645: Show a table of all changes
3646: </label>
3647: </p>
3648: -->
3649: <p>
3650: <label>
3651: <input type="checkbox" name="overwite_scores" checked="checked" />
3652: Overwrite any existing score
3653: </label>
3654: </p>
3655: ENDPICK
3656: my %fields=&get_fields();
3657: if (!defined($fields{'domain'})) {
3658: my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
3659: $request->print("\n<p> Users are in domain: ".$domform."</p>\n");
3660: }
3661: foreach my $key (sort(keys(%env))) {
3662: if ($key !~ /^form\.(.*)$/) { next; }
3663: my $cleankey=$1;
3664: if ($cleankey eq 'command') { next; }
3665: $request->print('<input type="hidden" name="'.$cleankey.
3666: '" value="'.$env{$key}.'" />'."\n");
3667: }
3668: # FIXME do a check for any duplicated user ids...
3669: # FIXME do a check for any invalid user ids?...
3670: $request->print('<input type="submit" value="Assign Grades" /><br />
3671: <hr /></form>'."\n");
3672: $request->print(&show_grading_menu_form($symb));
3673: return '';
3674: }
3675:
3676: sub get_fields {
3677: my %fields;
3678: my @keyfields = split(/\,/,$env{'form.keyfields'});
3679: for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
3680: if ($env{'form.upfile_associate'} eq 'reverse') {
3681: if ($env{'form.f'.$i} ne 'none') {
3682: $fields{$keyfields[$i]}=$env{'form.f'.$i};
3683: }
3684: } else {
3685: if ($env{'form.f'.$i} ne 'none') {
3686: $fields{$env{'form.f'.$i}}=$keyfields[$i];
3687: }
3688: }
3689: }
3690: return %fields;
3691: }
3692:
3693: sub csvuploadassign {
3694: my ($request)= @_;
3695: my ($symb)=&get_symb($request);
3696: if (!$symb) {return '';}
3697: my $error_msg = '';
3698: &Apache::loncommon::load_tmp_file($request);
3699: my @gradedata = &Apache::loncommon::upfile_record_sep();
3700: if ($env{'form.noFirstLine'}) { shift(@gradedata); }
3701: my %fields=&get_fields();
3702: $request->print('<h3>Assigning Grades</h3>');
3703: my $courseid=$env{'request.course.id'};
3704: my ($classlist) = &getclasslist('all',0);
3705: my @notallowed;
3706: my @skipped;
3707: my $countdone=0;
3708: foreach my $grade (@gradedata) {
3709: my %entries=&Apache::loncommon::record_sep($grade);
3710: my $domain;
3711: if ($entries{$fields{'domain'}}) {
3712: $domain=$entries{$fields{'domain'}};
3713: } else {
3714: $domain=$env{'form.default_domain'};
3715: }
3716: $domain=~s/\s//g;
3717: my $username=$entries{$fields{'username'}};
3718: $username=~s/\s//g;
3719: if (!$username) {
3720: my $id=$entries{$fields{'ID'}};
3721: $id=~s/\s//g;
3722: my %ids=&Apache::lonnet::idget($domain,$id);
3723: $username=$ids{$id};
3724: }
3725: if (!exists($$classlist{"$username:$domain"})) {
3726: my $id=$entries{$fields{'ID'}};
3727: $id=~s/\s//g;
3728: if ($id) {
3729: push(@skipped,"$id:$domain");
3730: } else {
3731: push(@skipped,"$username:$domain");
3732: }
3733: next;
3734: }
3735: my $usec=$classlist->{"$username:$domain"}[5];
3736: if (!&canmodify($usec)) {
3737: push(@notallowed,"$username:$domain");
3738: next;
3739: }
3740: my %points;
3741: my %grades;
3742: foreach my $dest (keys(%fields)) {
3743: if ($dest eq 'ID' || $dest eq 'username' ||
3744: $dest eq 'domain') { next; }
3745: if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
3746: if ($dest=~/stores_(.*)_points/) {
3747: my $part=$1;
3748: my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
3749: $symb,$domain,$username);
3750: if ($wgt) {
3751: $entries{$fields{$dest}}=~s/\s//g;
3752: my $pcr=$entries{$fields{$dest}} / $wgt;
3753: my $award='correct_by_override';
3754: $grades{"resource.$part.awarded"}=$pcr;
3755: $grades{"resource.$part.solved"}=$award;
3756: $points{$part}=1;
3757: } else {
3758: $error_msg = "<br />" .
3759: &mt("Some point values were assigned"
3760: ." for problems with a weight "
3761: ."of zero. These values were "
3762: ."ignored.");
3763: }
3764: } else {
3765: if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
3766: if ($dest=~/stores_(.*)_solved/) { if ($points{$1}) {next;} }
3767: my $store_key=$dest;
3768: $store_key=~s/^stores/resource/;
3769: $store_key=~s/_/\./g;
3770: $grades{$store_key}=$entries{$fields{$dest}};
3771: }
3772: }
3773: if (! %grades) { push(@skipped,"$username:$domain no data to save"); }
3774: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
3775: # &Apache::lonnet::logthis(" storing ".(join('-',%grades)));
3776: my $result=&Apache::lonnet::cstore(\%grades,$symb,
3777: $env{'request.course.id'},
3778: $domain,$username);
3779: if ($result eq 'ok') {
3780: $request->print('.');
3781: } else {
3782: $request->print("<p>
3783: <span class=\"LC_error\">
3784: Failed to save student $username:$domain.
3785: Message when trying to save was ($result)
3786: </span>
3787: </p>" );
3788: }
3789: $request->rflush();
3790: $countdone++;
3791: }
3792: $request->print("<br />Saved $countdone students\n");
3793: if (@skipped) {
3794: $request->print('<p><h4><b>Skipped Students</b></h4></p>');
3795: foreach my $student (@skipped) { $request->print("$student<br />\n"); }
3796: }
3797: if (@notallowed) {
3798: $request->print('<p><span class="LC_error">Students Not Allowed to Modify</span></p>');
3799: foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
3800: }
3801: $request->print("<br />\n");
3802: $request->print(&show_grading_menu_form($symb));
3803: return $error_msg;
3804: }
3805: #------------- end of section for handling csv file upload ---------
3806: #
3807: #-------------------------------------------------------------------
3808: #
3809: #-------------- Next few routines handle grading by page/sequence
3810: #
3811: #--- Select a page/sequence and a student to grade
3812: sub pickStudentPage {
3813: my ($request) = shift;
3814:
3815: $request->print(<<LISTJAVASCRIPT);
3816: <script type="text/javascript" language="javascript">
3817:
3818: function checkPickOne(formname) {
3819: if (radioSelection(formname.student) == null) {
3820: alert("Please select the student you wish to grade.");
3821: return;
3822: }
3823: ptr = pullDownSelection(formname.selectpage);
3824: formname.page.value = formname["page"+ptr].value;
3825: formname.title.value = formname["title"+ptr].value;
3826: formname.submit();
3827: }
3828:
3829: </script>
3830: LISTJAVASCRIPT
3831: &commonJSfunctions($request);
3832: my ($symb) = &get_symb($request);
3833: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
3834: my $cnum = $env{"course.$env{'request.course.id'}.num"};
3835: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
3836:
3837: my $result='<h3><span class="LC_info"> '.
3838: 'Manual Grading by Page or Sequence</span></h3>';
3839:
3840: $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
3841: $result.=' <b>Problems from:</b> <select name="selectpage">'."\n";
3842: my ($titles,$symbx) = &getSymbMap($request);
3843: my ($curpage) =&Apache::lonnet::decode_symb($symb);
3844: # my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb);
3845: # my $type=($curpage =~ /\.(page|sequence)/);
3846: my $ctr=0;
3847: foreach (@$titles) {
3848: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
3849: $result.='<option value="'.$ctr.'" '.
3850: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
3851: '>'.$showtitle.'</option>'."\n";
3852: $ctr++;
3853: }
3854: $result.= '</select>'."<br />\n";
3855: $ctr=0;
3856: foreach (@$titles) {
3857: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
3858: $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
3859: $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
3860: $ctr++;
3861: }
3862: $result.='<input type="hidden" name="page" />'."\n".
3863: '<input type="hidden" name="title" />'."\n";
3864:
3865: $result.=' <b>View Problems Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
3866: '<label><input type="radio" name="vProb" value="yes" /> yes </label>'."<br />\n";
3867:
3868: $result.=' <b>Submission Details: </b>'.
3869: '<label><input type="radio" name="lastSub" value="none" /> none</label>'."\n".
3870: '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> by dates and submissions</label>'."\n".
3871: '<label><input type="radio" name="lastSub" value="all" /> all details</label>'."\n";
3872:
3873: $result.='<input type="hidden" name="section" value="'.$getsec.'" />'."\n".
3874: '<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n".
3875: '<input type="hidden" name="command" value="displayPage" />'."\n".
3876: '<input type="hidden" name="symb" value="'.$symb.'" />'."\n".
3877: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
3878:
3879: $result.=' <b>'.&mt('Use CODE:').' </b>'.
3880: '<input type="text" name="CODE" value="" /><br />'."\n";
3881:
3882: $result.=' <input type="button" '.
3883: 'onClick="javascript:checkPickOne(this.form);"value="Next->" /><br />'."\n";
3884:
3885: $request->print($result);
3886:
3887: my $studentTable.=' <b>Select a student you wish to grade and then click on the Next button.</b><br />'.
3888: '<table border="0"><tr><td bgcolor="#777777">'.
3889: '<table border="0"><tr bgcolor="#e6ffff">'.
3890: '<td align="right"> <b>No.</b></td>'.
3891: '<td>'.&nameUserString('header').'</td>'.
3892: '<td align="right"> <b>No.</b></td>'.
3893: '<td>'.&nameUserString('header').'</td></tr>';
3894:
3895: my (undef,undef,$fullname) = &getclasslist($getsec,'1');
3896: my $ptr = 1;
3897: foreach my $student (sort
3898: {
3899: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
3900: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
3901: }
3902: return $a cmp $b;
3903: } (keys(%$fullname))) {
3904: my ($uname,$udom) = split(/:/,$student);
3905: $studentTable.=($ptr%2 == 1 ? '<tr bgcolor="#ffffe6">' : '</td>');
3906: $studentTable.='<td align="right">'.$ptr.' </td>';
3907: $studentTable.='<td> <label><input type="radio" name="student" value="'.$student.'" /> '
3908: .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
3909: $studentTable.=($ptr%2 == 0 ? '</td></tr>' : '');
3910: $ptr++;
3911: }
3912: $studentTable.='</td><td> </td><td> </td></tr>' if ($ptr%2 == 0);
3913: $studentTable.='</table></td></tr></table>'."\n";
3914: $studentTable.='<input type="button" '.
3915: 'onClick="javascript:checkPickOne(this.form);"value="Next->" /></form>'."\n";
3916:
3917: $studentTable.=&show_grading_menu_form($symb);
3918: $request->print($studentTable);
3919:
3920: return '';
3921: }
3922:
3923: sub getSymbMap {
3924: my ($request) = @_;
3925: my $navmap = Apache::lonnavmaps::navmap->new();
3926:
3927: my %symbx = ();
3928: my @titles = ();
3929: my $minder = 0;
3930:
3931: # Gather every sequence that has problems.
3932: my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
3933: 1,0,1);
3934: for my $sequence ($navmap->getById('0.0'), @sequences) {
3935: if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
3936: my $title = $minder.'.'.
3937: &HTML::Entities::encode($sequence->compTitle(),'"\'&');
3938: push(@titles, $title); # minder in case two titles are identical
3939: $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
3940: $minder++;
3941: }
3942: }
3943: return \@titles,\%symbx;
3944: }
3945:
3946: #
3947: #--- Displays a page/sequence w/wo problems, w/wo submissions
3948: sub displayPage {
3949: my ($request) = shift;
3950:
3951: my ($symb) = &get_symb($request);
3952: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
3953: my $cnum = $env{"course.$env{'request.course.id'}.num"};
3954: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
3955: my $pageTitle = $env{'form.page'};
3956: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
3957: my ($uname,$udom) = split(/:/,$env{'form.student'});
3958: my $usec=$classlist->{$env{'form.student'}}[5];
3959:
3960: #need to make sure we have the correct data for later EXT calls,
3961: #thus invalidate the cache
3962: &Apache::lonnet::devalidatecourseresdata(
3963: $env{'course.'.$env{'request.course.id'}.'.num'},
3964: $env{'course.'.$env{'request.course.id'}.'.domain'});
3965: &Apache::lonnet::clear_EXT_cache_status();
3966:
3967: if (!&canview($usec)) {
3968: $request->print('<span class="LC_warning">Unable to view requested student.('.$env{'form.student'}.')</span>');
3969: $request->print(&show_grading_menu_form($symb));
3970: return;
3971: }
3972: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
3973: $result.='<h3> Student: '.&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom).
3974: '</h3>'."\n";
3975: if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
3976: $result.='<h3> CODE: '.$env{'form.CODE'}.'</h3>'."\n";
3977: } else {
3978: delete($env{'form.CODE'});
3979: }
3980: &sub_page_js($request);
3981: $request->print($result);
3982:
3983: my $navmap = Apache::lonnavmaps::navmap->new();
3984: my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
3985: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
3986: if (!$map) {
3987: $request->print('<span class="LC_warning">Unable to view requested sequence. ('.$resUrl.')</span>');
3988: $request->print(&show_grading_menu_form($symb));
3989: return;
3990: }
3991: my $iterator = $navmap->getIterator($map->map_start(),
3992: $map->map_finish());
3993:
3994: my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
3995: '<input type="hidden" name="command" value="gradeByPage" />'."\n".
3996: '<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
3997: '<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
3998: '<input type="hidden" name="page" value="'.$pageTitle.'" />'."\n".
3999: '<input type="hidden" name="title" value="'.$env{'form.title'}.'" />'."\n".
4000: '<input type="hidden" name="symb" value="'.$symb.'" />'."\n".
4001: '<input type="hidden" name="overRideScore" value="no" />'."\n".
4002: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
4003:
4004: if (defined($env{'form.CODE'})) {
4005: $studentTable.=
4006: '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
4007: }
4008: my $checkIcon = '<img alt="'.&mt('Check Mark').
4009: '" src="'.$request->dir_config('lonIconsURL').
4010: '/check.gif" height="16" border="0" />';
4011:
4012: $studentTable.=' <b>Note:</b> Problems graded correct by the computer are marked with a '.$checkIcon.
4013: ' symbol.'."\n".
4014: '<table border="0"><tr><td bgcolor="#777777">'.
4015: '<table border="0"><tr bgcolor="#e6ffff">'.
4016: '<td align="center"><b> Prob. </b></td>'.
4017: '<td><b> '.($env{'form.vProb'} eq 'no' ? 'Title' : 'Problem Text').'/Grade</b></td></tr>';
4018:
4019: &Apache::lonxml::clear_problem_counter();
4020: my ($depth,$question,$prob) = (1,1,1);
4021: $iterator->next(); # skip the first BEGIN_MAP
4022: my $curRes = $iterator->next(); # for "current resource"
4023: while ($depth > 0) {
4024: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
4025: if($curRes == $iterator->END_MAP) { $depth--; }
4026:
4027: if (ref($curRes) && $curRes->is_problem()) {
4028: my $parts = $curRes->parts();
4029: my $title = $curRes->compTitle();
4030: my $symbx = $curRes->symb();
4031: $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
4032: (scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).' parts)').'</td>';
4033: $studentTable.='<td valign="top">';
4034: my %form = ('CODE' => $env{'form.CODE'},);
4035: if ($env{'form.vProb'} eq 'yes' ) {
4036: $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
4037: undef,'both',\%form);
4038: } else {
4039: my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
4040: $companswer =~ s|<form(.*?)>||g;
4041: $companswer =~ s|</form>||g;
4042: # while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
4043: # $companswer =~ s/$1/ /ms;
4044: # $request->print('match='.$1."<br />\n");
4045: # }
4046: # $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
4047: $studentTable.=' <b>'.$title.'</b> <br /> <b>Correct answer:</b><br />'.$companswer;
4048: }
4049:
4050: my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
4051:
4052: if ($env{'form.lastSub'} eq 'datesub') {
4053: if ($record{'version'} eq '') {
4054: $studentTable.='<br /> <span class="LC_warning">No recorded submission for this problem</span><br />';
4055: } else {
4056: my %responseType = ();
4057: foreach my $partid (@{$parts}) {
4058: my @responseIds =$curRes->responseIds($partid);
4059: my @responseType =$curRes->responseType($partid);
4060: my %responseIds;
4061: for (my $i=0;$i<=$#responseIds;$i++) {
4062: $responseIds{$responseIds[$i]}=$responseType[$i];
4063: }
4064: $responseType{$partid} = \%responseIds;
4065: }
4066: $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
4067:
4068: }
4069: } elsif ($env{'form.lastSub'} eq 'all') {
4070: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
4071: $studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
4072: $env{'request.course.id'},
4073: '','.submission');
4074:
4075: }
4076: if (&canmodify($usec)) {
4077: foreach my $partid (@{$parts}) {
4078: $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
4079: $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
4080: $question++;
4081: }
4082: $prob++;
4083: }
4084: $studentTable.='</td></tr>';
4085:
4086: }
4087: $curRes = $iterator->next();
4088: }
4089:
4090: $studentTable.='</table></td></tr></table>'."\n".
4091: '<input type="button" value="Save" '.
4092: 'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
4093: '</form>'."\n";
4094: $studentTable.=&show_grading_menu_form($symb);
4095: $request->print($studentTable);
4096:
4097: return '';
4098: }
4099:
4100: sub displaySubByDates {
4101: my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
4102: my $isCODE=0;
4103: my $isTask = ($symb =~/\.task$/);
4104: if (exists($record->{'resource.CODE'})) { $isCODE=1; }
4105: my $studentTable='<table border="0" width="100%"><tr><td bgcolor="#777777">'.
4106: '<table border="0" width="100%"><tr bgcolor="#e6ffff">'.
4107: '<td><b>Date/Time</b></td>'.
4108: ($isCODE?'<td><b>CODE</b></td>':'').
4109: '<td><b>Submission</b></td>'.
4110: '<td><b>Status </b></td></tr>';
4111: my ($version);
4112: my %mark;
4113: my %orders;
4114: $mark{'correct_by_student'} = $checkIcon;
4115: if (!exists($$record{'1:timestamp'})) {
4116: return '<br /> <span class="LC_warning">Nothing submitted - no attempts</span><br />';
4117: }
4118:
4119: my $interaction;
4120: for ($version=1;$version<=$$record{'version'};$version++) {
4121: my $timestamp = scalar(localtime($$record{$version.':timestamp'}));
4122: if (exists($$record{$version.':resource.0.version'})) {
4123: $interaction = $$record{$version.':resource.0.version'};
4124: }
4125:
4126: my $where = ($isTask ? "$version:resource.$interaction"
4127: : "$version:resource");
4128: #&Apache::lonnet::logthis(" got $where");
4129: $studentTable.='<tr bgcolor="#ffffff" valign="top"><td>'.$timestamp.'</td>';
4130: if ($isCODE) {
4131: $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
4132: }
4133: my @versionKeys = split(/\:/,$$record{$version.':keys'});
4134: my @displaySub = ();
4135: foreach my $partid (@{$parts}) {
4136: my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
4137: : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
4138:
4139:
4140: # next if ($$record{"$version:resource.$partid.solved"} eq '');
4141: my $display_part=&get_display_part($partid,$symb);
4142: foreach my $matchKey (@matchKey) {
4143: if (exists($$record{$version.':'.$matchKey}) &&
4144: $$record{$version.':'.$matchKey} ne '') {
4145:
4146: my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
4147: : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
4148: #&Apache::lonnet::logthis("match $matchKey $responseId (".$$record{$version.':'.$matchKey});
4149: $displaySub[0].='<b>Part:</b> '.$display_part.' ';
4150: $displaySub[0].='<span class="LC_internal_info">(ID '.
4151: $responseId.')</span> <b>';
4152: if ($$record{"$where.$partid.tries"} eq '') {
4153: $displaySub[0].='Trial not counted';
4154: } else {
4155: $displaySub[0].='Trial '.
4156: $$record{"$where.$partid.tries"};
4157: }
4158: my $responseType=($isTask ? 'Task'
4159: : $responseType->{$partid}->{$responseId});
4160: if (!exists($orders{$partid})) { $orders{$partid}={}; }
4161: if (!exists($orders{$partid}->{$responseId})) {
4162: $orders{$partid}->{$responseId}=
4163: &get_order($partid,$responseId,$symb,$uname,$udom);
4164: }
4165: $displaySub[0].='</b> '.
4166: &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
4167: }
4168: }
4169: if (exists($$record{"$where.$partid.checkedin"})) {
4170: $displaySub[1].='Checked in by '.
4171: $$record{"$where.$partid.checkedin"}.' into slot '.
4172: $$record{"$where.$partid.checkedin.slot"}.
4173: '<br />';
4174: }
4175: if (exists $$record{"$where.$partid.award"}) {
4176: $displaySub[1].='<b>Part:</b> '.$display_part.' '.
4177: lc($$record{"$where.$partid.award"}).' '.
4178: $mark{$$record{"$where.$partid.solved"}}.
4179: '<br />';
4180: }
4181: if (exists $$record{"$where.$partid.regrader"}) {
4182: $displaySub[2].=$$record{"$where.$partid.regrader"}.
4183: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
4184: } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
4185: $displaySub[2].=
4186: $$record{"$version:resource.$partid.regrader"}.
4187: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
4188: }
4189: }
4190: # needed because old essay regrader has not parts info
4191: if (exists $$record{"$version:resource.regrader"}) {
4192: $displaySub[2].=$$record{"$version:resource.regrader"};
4193: }
4194: $studentTable.='<td>'.$displaySub[0].' </td><td>'.$displaySub[1];
4195: if ($displaySub[2]) {
4196: $studentTable.='Manually graded by '.$displaySub[2];
4197: }
4198: $studentTable.=' </td></tr>';
4199:
4200: }
4201: $studentTable.='</table></td></tr></table>';
4202: return $studentTable;
4203: }
4204:
4205: sub updateGradeByPage {
4206: my ($request) = shift;
4207:
4208: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4209: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4210: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4211: my $pageTitle = $env{'form.page'};
4212: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
4213: my ($uname,$udom) = split(/:/,$env{'form.student'});
4214: my $usec=$classlist->{$env{'form.student'}}[5];
4215: if (!&canmodify($usec)) {
4216: $request->print('<span class="LC_warning">Unable to modify requested student.('.$env{'form.student'}.'</span>');
4217: $request->print(&show_grading_menu_form($env{'form.symb'}));
4218: return;
4219: }
4220: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
4221: $result.='<h3> Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
4222: '</h3>'."\n";
4223:
4224: $request->print($result);
4225:
4226: my $navmap = Apache::lonnavmaps::navmap->new();
4227: my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
4228: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
4229: if (!$map) {
4230: $request->print('<span class="LC_warning">Unable to grade requested sequence. ('.$resUrl.')</span>');
4231: my ($symb)=&get_symb($request);
4232: $request->print(&show_grading_menu_form($symb));
4233: return;
4234: }
4235: my $iterator = $navmap->getIterator($map->map_start(),
4236: $map->map_finish());
4237:
4238: my $studentTable='<table border="0"><tr><td bgcolor="#777777">'.
4239: '<table border="0"><tr bgcolor="#e6ffff">'.
4240: '<td align="center"><b> Prob. </b></td>'.
4241: '<td><b> Title </b></td>'.
4242: '<td><b> Previous Score </b></td>'.
4243: '<td><b> New Score </b></td></tr>';
4244:
4245: $iterator->next(); # skip the first BEGIN_MAP
4246: my $curRes = $iterator->next(); # for "current resource"
4247: my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
4248: while ($depth > 0) {
4249: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
4250: if($curRes == $iterator->END_MAP) { $depth--; }
4251:
4252: if (ref($curRes) && $curRes->is_problem()) {
4253: my $parts = $curRes->parts();
4254: my $title = $curRes->compTitle();
4255: my $symbx = $curRes->symb();
4256: $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
4257: (scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).' parts)').'</td>';
4258: $studentTable.='<td valign="top"> <b>'.$title.'</b> </td>';
4259:
4260: my %newrecord=();
4261: my @displayPts=();
4262: my %aggregate = ();
4263: my $aggregateflag = 0;
4264: foreach my $partid (@{$parts}) {
4265: my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
4266: my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
4267:
4268: my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ?
4269: $env{'form.WGT'.$question.'_'.$partid} : 1;
4270: my $partial = $newpts/$wgt;
4271: my $score;
4272: if ($partial > 0) {
4273: $score = 'correct_by_override';
4274: } elsif ($newpts ne '') { #empty is taken as 0
4275: $score = 'incorrect_by_override';
4276: }
4277: my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
4278: if ($dropMenu eq 'excused') {
4279: $partial = '';
4280: $score = 'excused';
4281: } elsif ($dropMenu eq 'reset status'
4282: && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
4283: $newrecord{'resource.'.$partid.'.tries'} = 0;
4284: $newrecord{'resource.'.$partid.'.solved'} = '';
4285: $newrecord{'resource.'.$partid.'.award'} = '';
4286: $newrecord{'resource.'.$partid.'.awarded'} = 0;
4287: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
4288: $changeflag++;
4289: $newpts = '';
4290:
4291: my $aggtries = $env{'form.aggtries'.$question.'_'.$partid};
4292: my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
4293: my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
4294: if ($aggtries > 0) {
4295: &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
4296: $aggregateflag = 1;
4297: }
4298: }
4299: my $display_part=&get_display_part($partid,$curRes->symb());
4300: my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
4301: $displayPts[0].=' <b>Part:</b> '.$display_part.' = '.
4302: (($oldstatus eq 'excused') ? 'excused' : $oldpts).
4303: ' <br />';
4304: $displayPts[1].=' <b>Part:</b> '.$display_part.' = '.
4305: (($score eq 'excused') ? 'excused' : $newpts).
4306: ' <br />';
4307: $question++;
4308: next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
4309:
4310: $newrecord{'resource.'.$partid.'.awarded'} = $partial if $partial ne '';
4311: $newrecord{'resource.'.$partid.'.solved'} = $score if $score ne '';
4312: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
4313: if (scalar(keys(%newrecord)) > 0);
4314:
4315: $changeflag++;
4316: }
4317: if (scalar(keys(%newrecord)) > 0) {
4318: my %record =
4319: &Apache::lonnet::restore($symbx,$env{'request.course.id'},
4320: $udom,$uname);
4321:
4322: if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
4323: $newrecord{'resource.CODE'} = $env{'form.CODE'};
4324: } elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
4325: $newrecord{'resource.CODE'} = '';
4326: }
4327: &Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
4328: $udom,$uname);
4329: %record = &Apache::lonnet::restore($symbx,
4330: $env{'request.course.id'},
4331: $udom,$uname);
4332: &check_and_remove_from_queue($parts,\%record,undef,$symbx,
4333: $cdom,$cnum,$udom,$uname);
4334: }
4335:
4336: if ($aggregateflag) {
4337: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
4338: $env{'course.'.$env{'request.course.id'}.'.domain'},
4339: $env{'course.'.$env{'request.course.id'}.'.num'});
4340: }
4341:
4342: $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
4343: '<td valign="top">'.$displayPts[1].'</td>'.
4344: '</tr>';
4345:
4346: $prob++;
4347: }
4348: $curRes = $iterator->next();
4349: }
4350:
4351: $studentTable.='</td></tr></table></td></tr></table>';
4352: $studentTable.=&show_grading_menu_form($env{'form.symb'});
4353: my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
4354: 'The scores were changed for '.
4355: $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
4356: $request->print($grademsg.$studentTable);
4357:
4358: return '';
4359: }
4360:
4361: #-------- end of section for handling grading by page/sequence ---------
4362: #
4363: #-------------------------------------------------------------------
4364:
4365: #--------------------Scantron Grading-----------------------------------
4366: #
4367: #------ start of section for handling grading by page/sequence ---------
4368:
4369: sub defaultFormData {
4370: my ($symb)=@_;
4371: return '
4372: <input type="hidden" name="symb" value="'.$symb.'" />'."\n".
4373: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
4374: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
4375: }
4376:
4377: sub getSequenceDropDown {
4378: my ($request,$symb)=@_;
4379: my $result='<select name="selectpage">'."\n";
4380: my ($titles,$symbx) = &getSymbMap($request);
4381: my ($curpage)=&Apache::lonnet::decode_symb($symb);
4382: my $ctr=0;
4383: foreach (@$titles) {
4384: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4385: $result.='<option value="'.$$symbx{$_}.'" '.
4386: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
4387: '>'.$showtitle.'</option>'."\n";
4388: $ctr++;
4389: }
4390: $result.= '</select>';
4391: return $result;
4392: }
4393:
4394: sub scantron_filenames {
4395: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4396: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
4397: my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
4398: &propath($cdom,$cname));
4399: my @possiblenames;
4400: foreach my $filename (sort(@files)) {
4401: ($filename)=split(/&/,$filename);
4402: if ($filename!~/^scantron_orig_/) { next ; }
4403: $filename=~s/^scantron_orig_//;
4404: push(@possiblenames,$filename);
4405: }
4406: return @possiblenames;
4407: }
4408:
4409: sub scantron_uploads {
4410: my ($file2grade) = @_;
4411: my $result= '<select name="scantron_selectfile">';
4412: $result.="<option></option>";
4413: foreach my $filename (sort(&scantron_filenames())) {
4414: $result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
4415: }
4416: $result.="</select>";
4417: return $result;
4418: }
4419:
4420: sub scantron_scantab {
4421: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
4422: my $result='<select name="scantron_format">'."\n";
4423: $result.='<option></option>'."\n";
4424: foreach my $line (<$fh>) {
4425: my ($name,$descrip)=split(/:/,$line);
4426: if ($name =~ /^\#/) { next; }
4427: $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
4428: }
4429: $result.='</select>'."\n";
4430:
4431: return $result;
4432: }
4433:
4434: sub scantron_CODElist {
4435: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4436: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4437: my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
4438: my $namechoice='<option></option>';
4439: foreach my $name (sort {uc($a) cmp uc($b)} @names) {
4440: if ($name =~ /^error: 2 /) { next; }
4441: if ($name =~ /^type\0/) { next; }
4442: $namechoice.='<option value="'.$name.'">'.$name.'</option>';
4443: }
4444: $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
4445: return $namechoice;
4446: }
4447:
4448: sub scantron_CODEunique {
4449: my $result='<span style="white-space: nowrap;">
4450: <label><input type="radio" name="scantron_CODEunique"
4451: value="yes" checked="checked" /> Yes </label>
4452: </span>
4453: <span style="white-space: nowrap;">
4454: <label><input type="radio" name="scantron_CODEunique"
4455: value="no" /> No </label>
4456: </span>';
4457: return $result;
4458: }
4459:
4460: sub scantron_selectphase {
4461: my ($r,$file2grade) = @_;
4462: my ($symb)=&get_symb($r);
4463: if (!$symb) {return '';}
4464: my $sequence_selector=&getSequenceDropDown($r,$symb);
4465: my $default_form_data=&defaultFormData($symb);
4466: my $grading_menu_button=&show_grading_menu_form($symb);
4467: my $file_selector=&scantron_uploads($file2grade);
4468: my $format_selector=&scantron_scantab();
4469: my $CODE_selector=&scantron_CODElist();
4470: my $CODE_unique=&scantron_CODEunique();
4471: my $result;
4472: #FIXME allow instructor to be able to download the scantron file
4473: # and to upload it,
4474: $result.= <<SCANTRONFORM;
4475: <table width="100%" border="0">
4476: <tr>
4477: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
4478: <td bgcolor="#777777">
4479: <input type="hidden" name="command" value="scantron_warning" />
4480: $default_form_data
4481: <table width="100%" border="0">
4482: <tr bgcolor="#e6ffff">
4483: <td colspan="2">
4484: <b>Specify file and which Folder/Sequence to grade</b>
4485: </td>
4486: </tr>
4487: <tr bgcolor="#ffffe6">
4488: <td> Sequence to grade: </td><td> $sequence_selector </td>
4489: </tr>
4490: <tr bgcolor="#ffffe6">
4491: <td> Filename of scoring office file: </td><td> $file_selector </td>
4492: </tr>
4493: <tr bgcolor="#ffffe6">
4494: <td> Format of data file: </td><td> $format_selector </td>
4495: </tr>
4496: <tr bgcolor="#ffffe6">
4497: <td> Saved CODEs to validate against: </td><td> $CODE_selector</td>
4498: </tr>
4499: <tr bgcolor="#ffffe6">
4500: <td> Each CODE is only to be used once:</td><td> $CODE_unique </td>
4501: </tr>
4502: <tr bgcolor="#ffffe6">
4503: <td> Options: </td>
4504: <td>
4505: <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> Do only previously skipped records</label> <br />
4506: <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> Remove all exisiting corrections</label> <br />
4507: <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> Skip hidden resources when grading</label>
4508: </td>
4509: </tr>
4510: <tr bgcolor="#ffffe6">
4511: <td colspan="2">
4512: <input type="submit" value="Grading: Validate Scantron Records" />
4513: </td>
4514: </tr>
4515: </table>
4516: </td>
4517: </form>
4518: </tr>
4519: SCANTRONFORM
4520:
4521: $r->print($result);
4522:
4523: if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
4524: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
4525:
4526: $r->print(<<SCANTRONFORM);
4527: <tr>
4528: <td bgcolor="#777777">
4529: <table width="100%" border="0">
4530: <tr bgcolor="#e6ffff">
4531: <td>
4532: <b>Specify a Scantron data file to upload.</b>
4533: </td>
4534: </tr>
4535: <tr bgcolor="#ffffe6">
4536: <td>
4537: SCANTRONFORM
4538: my $default_form_data=&defaultFormData(&get_symb($r,1));
4539: my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
4540: my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
4541: $r->print(<<UPLOAD);
4542: <script type="text/javascript" language="javascript">
4543: function checkUpload(formname) {
4544: if (formname.upfile.value == "") {
4545: alert("Please use the browse button to select a file from your local directory.");
4546: return false;
4547: }
4548: formname.submit();
4549: }
4550: </script>
4551:
4552: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
4553: $default_form_data
4554: <input name='courseid' type='hidden' value='$cnum' />
4555: <input name='domainid' type='hidden' value='$cdom' />
4556: <input name='command' value='scantronupload_save' type='hidden' />
4557: File to upload:<input type="file" name="upfile" size="50" />
4558: <br />
4559: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
4560: </form>
4561: UPLOAD
4562:
4563: $r->print(<<SCANTRONFORM);
4564: </td>
4565: </tr>
4566: </table>
4567: </td>
4568: </tr>
4569: SCANTRONFORM
4570: }
4571: $r->print(<<SCANTRONFORM);
4572: <tr>
4573: <form action='/adm/grades' name='scantron_download'>
4574: <td bgcolor="#777777">
4575: $default_form_data
4576: <input type="hidden" name="command" value="scantron_download" />
4577: <table width="100%" border="0">
4578: <tr bgcolor="#e6ffff">
4579: <td colspan="2">
4580: <b>Download a scoring office file</b>
4581: </td>
4582: </tr>
4583: <tr bgcolor="#ffffe6">
4584: <td> Filename of scoring office file: </td><td> $file_selector </td>
4585: </tr>
4586: <tr bgcolor="#ffffe6">
4587: <td colspan="2">
4588: <input type="submit" value="Download: Show List of Associated Files" />
4589: </td>
4590: </tr>
4591: </table>
4592: </td>
4593: </form>
4594: </tr>
4595: SCANTRONFORM
4596:
4597: $r->print(<<SCANTRONFORM);
4598: </table>
4599: $grading_menu_button
4600: SCANTRONFORM
4601:
4602: return
4603: }
4604:
4605: sub get_scantron_config {
4606: my ($which) = @_;
4607: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
4608: my %config;
4609: #FIXME probably should move to XML it has already gotten a bit much now
4610: foreach my $line (<$fh>) {
4611: my ($name,$descrip)=split(/:/,$line);
4612: if ($name ne $which ) { next; }
4613: chomp($line);
4614: my @config=split(/:/,$line);
4615: $config{'name'}=$config[0];
4616: $config{'description'}=$config[1];
4617: $config{'CODElocation'}=$config[2];
4618: $config{'CODEstart'}=$config[3];
4619: $config{'CODElength'}=$config[4];
4620: $config{'IDstart'}=$config[5];
4621: $config{'IDlength'}=$config[6];
4622: $config{'Qstart'}=$config[7];
4623: $config{'Qlength'}=$config[8];
4624: $config{'Qoff'}=$config[9];
4625: $config{'Qon'}=$config[10];
4626: $config{'PaperID'}=$config[11];
4627: $config{'PaperIDlength'}=$config[12];
4628: $config{'FirstName'}=$config[13];
4629: $config{'FirstNamelength'}=$config[14];
4630: $config{'LastName'}=$config[15];
4631: $config{'LastNamelength'}=$config[16];
4632: last;
4633: }
4634: return %config;
4635: }
4636:
4637: sub username_to_idmap {
4638: my ($classlist)= @_;
4639: my %idmap;
4640: foreach my $student (keys(%$classlist)) {
4641: $idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
4642: $student;
4643: }
4644: return %idmap;
4645: }
4646:
4647: sub scantron_fixup_scanline {
4648: my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
4649: if ($field eq 'ID') {
4650: if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
4651: return ($line,1,'New value too large');
4652: }
4653: if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
4654: $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
4655: $args->{'newid'});
4656: }
4657: substr($line,$$scantron_config{'IDstart'}-1,
4658: $$scantron_config{'IDlength'})=$args->{'newid'};
4659: if ($args->{'newid'}=~/^\s*$/) {
4660: &scan_data($scan_data,"$whichline.user",
4661: $args->{'username'}.':'.$args->{'domain'});
4662: }
4663: } elsif ($field eq 'CODE') {
4664: if ($args->{'CODE_ignore_dup'}) {
4665: &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
4666: }
4667: &scan_data($scan_data,"$whichline.useCODE",'1');
4668: if ($args->{'CODE'} ne 'use_unfound') {
4669: if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
4670: return ($line,1,'New CODE value too large');
4671: }
4672: if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
4673: $args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
4674: }
4675: substr($line,$$scantron_config{'CODEstart'}-1,
4676: $$scantron_config{'CODElength'})=$args->{'CODE'};
4677: }
4678: } elsif ($field eq 'answer') {
4679: my $length=$scantron_config->{'Qlength'};
4680: my $off=$scantron_config->{'Qoff'};
4681: my $on=$scantron_config->{'Qon'};
4682: my $answer=${off}x$length;
4683: if ($args->{'response'} eq 'none') {
4684: &scan_data($scan_data,
4685: "$whichline.no_bubble.".$args->{'question'},'1');
4686: } else {
4687: if ($on eq 'letter') {
4688: my @alphabet=('A'..'Z');
4689: $answer=$alphabet[$args->{'response'}];
4690: } elsif ($on eq 'number') {
4691: $answer=$args->{'response'}+1;
4692: if ($answer == 10) { $answer = '0'; }
4693: } else {
4694: substr($answer,$args->{'response'},1)=$on;
4695: }
4696: &scan_data($scan_data,
4697: "$whichline.no_bubble.".$args->{'question'},undef,'1');
4698: }
4699: my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
4700: substr($line,$where-1,$length)=$answer;
4701: }
4702: return $line;
4703: }
4704:
4705: sub scan_data {
4706: my ($scan_data,$key,$value,$delete)=@_;
4707: my $filename=$env{'form.scantron_selectfile'};
4708: if (defined($value)) {
4709: $scan_data->{$filename.'_'.$key} = $value;
4710: }
4711: if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
4712: return $scan_data->{$filename.'_'.$key};
4713: }
4714:
4715: sub scantron_parse_scanline {
4716: my ($line,$whichline,$scantron_config,$scan_data,$justHeader)=@_;
4717: my %record;
4718: my $questions=substr($line,$$scantron_config{'Qstart'}-1);
4719: my $data=substr($line,0,$$scantron_config{'Qstart'}-1);
4720: if (!($$scantron_config{'CODElocation'} eq 0 ||
4721: $$scantron_config{'CODElocation'} eq 'none')) {
4722: if ($$scantron_config{'CODElocation'} < 0 ||
4723: $$scantron_config{'CODElocation'} eq 'letter' ||
4724: $$scantron_config{'CODElocation'} eq 'number') {
4725: $record{'scantron.CODE'}=substr($data,
4726: $$scantron_config{'CODEstart'}-1,
4727: $$scantron_config{'CODElength'});
4728: if (&scan_data($scan_data,"$whichline.useCODE")) {
4729: $record{'scantron.useCODE'}=1;
4730: }
4731: if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
4732: $record{'scantron.CODE_ignore_dup'}=1;
4733: }
4734: } else {
4735: #FIXME interpret first N questions
4736: }
4737: }
4738: $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
4739: $$scantron_config{'IDlength'});
4740: $record{'scantron.PaperID'}=
4741: substr($data,$$scantron_config{'PaperID'}-1,
4742: $$scantron_config{'PaperIDlength'});
4743: $record{'scantron.FirstName'}=
4744: substr($data,$$scantron_config{'FirstName'}-1,
4745: $$scantron_config{'FirstNamelength'});
4746: $record{'scantron.LastName'}=
4747: substr($data,$$scantron_config{'LastName'}-1,
4748: $$scantron_config{'LastNamelength'});
4749: if ($justHeader) { return \%record; }
4750:
4751: my @alphabet=('A'..'Z');
4752: my $questnum=0;
4753: while ($questions) {
4754: $questnum++;
4755: my $currentquest=substr($questions,0,$$scantron_config{'Qlength'});
4756: substr($questions,0,$$scantron_config{'Qlength'})='';
4757: if (length($currentquest) < $$scantron_config{'Qlength'}) { next; }
4758: if ($$scantron_config{'Qon'} eq 'letter') {
4759: if ($currentquest eq '?'
4760: || $currentquest eq '*') {
4761: push(@{$record{'scantron.doubleerror'}},$questnum);
4762: $record{"scantron.$questnum.answer"}='';
4763: } elsif (!defined($currentquest)
4764: || $currentquest eq $$scantron_config{'Qoff'}
4765: || $currentquest !~ /^[A-Z]$/) {
4766: $record{"scantron.$questnum.answer"}='';
4767: if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
4768: push(@{$record{"scantron.missingerror"}},$questnum);
4769: }
4770: } else {
4771: $record{"scantron.$questnum.answer"}=$currentquest;
4772: }
4773: } elsif ($$scantron_config{'Qon'} eq 'number') {
4774: if ($currentquest eq '?'
4775: || $currentquest eq '*') {
4776: push(@{$record{'scantron.doubleerror'}},$questnum);
4777: $record{"scantron.$questnum.answer"}='';
4778: } elsif (!defined($currentquest)
4779: || $currentquest eq $$scantron_config{'Qoff'}
4780: || $currentquest !~ /^\d$/) {
4781: $record{"scantron.$questnum.answer"}='';
4782: if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
4783: push(@{$record{"scantron.missingerror"}},$questnum);
4784: }
4785: } else {
4786: # wrap zero back to J
4787: if ($currentquest eq '0') {
4788: $record{"scantron.$questnum.answer"}=
4789: $alphabet[9];
4790: } else {
4791: $record{"scantron.$questnum.answer"}=
4792: $alphabet[$currentquest-1];
4793: }
4794: }
4795: } else {
4796: my @array=split($$scantron_config{'Qon'},$currentquest,-1);
4797: if (length($array[0]) eq $$scantron_config{'Qlength'}) {
4798: $record{"scantron.$questnum.answer"}='';
4799: if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
4800: push(@{$record{"scantron.missingerror"}},$questnum);
4801: }
4802: } else {
4803: $record{"scantron.$questnum.answer"}=
4804: $alphabet[length($array[0])];
4805: }
4806: if (scalar(@array) gt 2) {
4807: push(@{$record{'scantron.doubleerror'}},$questnum);
4808: my @ans=@array;
4809: my $i=length($ans[0]);shift(@ans);
4810: while ($#ans) {
4811: $i+=length($ans[0])+1;
4812: $record{"scantron.$questnum.answer"}.=$alphabet[$i];
4813: shift(@ans);
4814: }
4815: }
4816: }
4817: }
4818: $record{'scantron.maxquest'}=$questnum;
4819: return \%record;
4820: }
4821:
4822: sub scantron_add_delay {
4823: my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
4824: push(@$delayqueue,
4825: {'line' => $scanline, 'emsg' => $errormessage,
4826: 'ecode' => $errorcode }
4827: );
4828: }
4829:
4830: sub scantron_find_student {
4831: my ($scantron_record,$scan_data,$idmap,$line)=@_;
4832: my $scanID=$$scantron_record{'scantron.ID'};
4833: if ($scanID =~ /^\s*$/) {
4834: return &scan_data($scan_data,"$line.user");
4835: }
4836: foreach my $id (keys(%$idmap)) {
4837: if (lc($id) eq lc($scanID)) {
4838: return $$idmap{$id};
4839: }
4840: }
4841: return undef;
4842: }
4843:
4844: sub scantron_filter {
4845: my ($curres)=@_;
4846:
4847: if (ref($curres) && $curres->is_problem()) {
4848: # if the user has asked to not have either hidden
4849: # or 'randomout' controlled resources to be graded
4850: # don't include them
4851: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
4852: && $curres->randomout) {
4853: return 0;
4854: }
4855: return 1;
4856: }
4857: return 0;
4858: }
4859:
4860: sub scantron_process_corrections {
4861: my ($r) = @_;
4862: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
4863: my ($scanlines,$scan_data)=&scantron_getfile();
4864: my $classlist=&Apache::loncoursedata::get_classlist();
4865: my $which=$env{'form.scantron_line'};
4866: my $line=&scantron_get_line($scanlines,$scan_data,$which);
4867: my ($skip,$err,$errmsg);
4868: if ($env{'form.scantron_skip_record'}) {
4869: $skip=1;
4870: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
4871: my $newstudent=$env{'form.scantron_username'}.':'.
4872: $env{'form.scantron_domain'};
4873: my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
4874: ($line,$err,$errmsg)=
4875: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
4876: 'ID',{'newid'=>$newid,
4877: 'username'=>$env{'form.scantron_username'},
4878: 'domain'=>$env{'form.scantron_domain'}});
4879: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
4880: my $resolution=$env{'form.scantron_CODE_resolution'};
4881: my $newCODE;
4882: my %args;
4883: if ($resolution eq 'use_unfound') {
4884: $newCODE='use_unfound';
4885: } elsif ($resolution eq 'use_found') {
4886: $newCODE=$env{'form.scantron_CODE_selectedvalue'};
4887: } elsif ($resolution eq 'use_typed') {
4888: $newCODE=$env{'form.scantron_CODE_newvalue'};
4889: } elsif ($resolution =~ /^use_closest_(\d+)/) {
4890: $newCODE=$env{"form.scantron_CODE_closest_$1"};
4891: }
4892: if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
4893: $args{'CODE_ignore_dup'}=1;
4894: }
4895: $args{'CODE'}=$newCODE;
4896: ($line,$err,$errmsg)=
4897: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
4898: 'CODE',\%args);
4899: } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
4900: foreach my $question (split(',',$env{'form.scantron_questions'})) {
4901: ($line,$err,$errmsg)=
4902: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
4903: $which,'answer',
4904: { 'question'=>$question,
4905: 'response'=>$env{"form.scantron_correct_Q_$question"}});
4906: if ($err) { last; }
4907: }
4908: }
4909: if ($err) {
4910: $r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
4911: } else {
4912: &scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
4913: &scantron_putfile($scanlines,$scan_data);
4914: }
4915: }
4916:
4917: sub reset_skipping_status {
4918: my ($scanlines,$scan_data)=&scantron_getfile();
4919: &scan_data($scan_data,'remember_skipping',undef,1);
4920: &scantron_putfile(undef,$scan_data);
4921: }
4922:
4923: sub start_skipping {
4924: my ($scan_data,$i)=@_;
4925: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
4926: if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
4927: $remembered{$i}=2;
4928: } else {
4929: $remembered{$i}=1;
4930: }
4931: &scan_data($scan_data,'remember_skipping',join(':',%remembered));
4932: }
4933:
4934: sub should_be_skipped {
4935: my ($scanlines,$scan_data,$i)=@_;
4936: if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
4937: # not redoing old skips
4938: if ($scanlines->{'skipped'}[$i]) { return 1; }
4939: return 0;
4940: }
4941: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
4942:
4943: if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
4944: return 0;
4945: }
4946: return 1;
4947: }
4948:
4949: sub remember_current_skipped {
4950: my ($scanlines,$scan_data)=&scantron_getfile();
4951: my %to_remember;
4952: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
4953: if ($scanlines->{'skipped'}[$i]) {
4954: $to_remember{$i}=1;
4955: }
4956: }
4957:
4958: &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
4959: &scantron_putfile(undef,$scan_data);
4960: }
4961:
4962: sub check_for_error {
4963: my ($r,$result)=@_;
4964: if ($result ne 'ok' && $result ne 'not_found' ) {
4965: $r->print("An error occurred ($result) when trying to Remove the existing corrections.");
4966: }
4967: }
4968:
4969: sub scantron_warning_screen {
4970: my ($button_text)=@_;
4971: my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
4972: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
4973: my $CODElist;
4974: if ($scantron_config{'CODElocation'} &&
4975: $scantron_config{'CODEstart'} &&
4976: $scantron_config{'CODElength'}) {
4977: $CODElist=$env{'form.scantron_CODElist'};
4978: if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
4979: $CODElist=
4980: '<tr><td><b>List of CODES to validate against:</b></td><td><tt>'.
4981: $env{'form.scantron_CODElist'}.'</tt></td></tr>';
4982: }
4983: return (<<STUFF);
4984: <p>
4985: <span class="LC_warning">Please double check the information
4986: below before clicking on '$button_text'</span>
4987: </p>
4988: <table>
4989: <tr><td><b>Sequence to be Graded:</b></td><td>$title</td></tr>
4990: <tr><td><b>Data File that will be used:</b></td><td><tt>$env{'form.scantron_selectfile'}</tt></td></tr>
4991: $CODElist
4992: </table>
4993: <br />
4994: <p> If this information is correct, please click on '$button_text'.</p>
4995: <p> If something is incorrect, please click the 'Grading Menu' button to start over.</p>
4996:
4997: <br />
4998: STUFF
4999: }
5000:
5001: sub scantron_do_warning {
5002: my ($r)=@_;
5003: my ($symb)=&get_symb($r);
5004: if (!$symb) {return '';}
5005: my $default_form_data=&defaultFormData($symb);
5006: $r->print(&scantron_form_start().$default_form_data);
5007: if ( $env{'form.selectpage'} eq '' ||
5008: $env{'form.scantron_selectfile'} eq '' ||
5009: $env{'form.scantron_format'} eq '' ) {
5010: $r->print("<p>You have forgetten to specify some information. Please go Back and try again.</p>");
5011: if ( $env{'form.selectpage'} eq '') {
5012: $r->print('<p><span class="LC_error">You have not selected a Sequence to grade</span></p>');
5013: }
5014: if ( $env{'form.scantron_selectfile'} eq '') {
5015: $r->print('<p><span class="LC_error">You have not selected a file that contains the student\'s response data.</span></p>');
5016: }
5017: if ( $env{'form.scantron_format'} eq '') {
5018: $r->print('<p><span class="LC_error">You have not selected a the format of the student\'s response data.</span></p>');
5019: }
5020: } else {
5021: my $warning=&scantron_warning_screen('Grading: Validate Records');
5022: $r->print(<<STUFF);
5023: $warning
5024: <input type="submit" name="submit" value="Grading: Validate Records" />
5025: <input type="hidden" name="command" value="scantron_validate" />
5026: STUFF
5027: }
5028: $r->print("</form><br />".&show_grading_menu_form($symb));
5029: return '';
5030: }
5031:
5032: sub scantron_form_start {
5033: my ($max_bubble)=@_;
5034: my $result= <<SCANTRONFORM;
5035: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
5036: <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
5037: <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
5038: <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
5039: <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
5040: <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
5041: <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
5042: <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
5043: <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
5044: <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
5045: SCANTRONFORM
5046: return $result;
5047: }
5048:
5049: sub scantron_validate_file {
5050: my ($r) = @_;
5051: my ($symb)=&get_symb($r);
5052: if (!$symb) {return '';}
5053: my $default_form_data=&defaultFormData($symb);
5054:
5055: # do the detection of only doing skipped records first befroe we delete
5056: # them when doing the corrections reset
5057: if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
5058: &reset_skipping_status();
5059: }
5060: if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
5061: &remember_current_skipped();
5062: $env{'form.scantron_options_redo'}='redo_skipped_ready';
5063: }
5064:
5065: if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
5066: &check_for_error($r,&scantron_remove_file('corrected'));
5067: &check_for_error($r,&scantron_remove_file('skipped'));
5068: &check_for_error($r,&scantron_remove_scan_data());
5069: $env{'form.scantron_options_ignore'}='done';
5070: }
5071:
5072: if ($env{'form.scantron_corrections'}) {
5073: &scantron_process_corrections($r);
5074: }
5075: $r->print("<p>Gathering neccessary info.</p>");$r->rflush();
5076: #get the student pick code ready
5077: $r->print(&Apache::loncommon::studentbrowser_javascript());
5078: my $max_bubble=&scantron_get_maxbubble();
5079: my $result=&scantron_form_start($max_bubble).$default_form_data;
5080: $r->print($result);
5081:
5082: my @validate_phases=( 'sequence',
5083: 'ID',
5084: 'CODE',
5085: 'doublebubble',
5086: 'missingbubbles');
5087: if (!$env{'form.validatepass'}) {
5088: $env{'form.validatepass'} = 0;
5089: }
5090: my $currentphase=$env{'form.validatepass'};
5091:
5092: my $stop=0;
5093: while (!$stop && $currentphase < scalar(@validate_phases)) {
5094: $r->print("<p> Validating ".$validate_phases[$currentphase]."</p>");
5095: $r->rflush();
5096: my $which="scantron_validate_".$validate_phases[$currentphase];
5097: {
5098: no strict 'refs';
5099: ($stop,$currentphase)=&$which($r,$currentphase);
5100: }
5101: }
5102: if (!$stop) {
5103: my $warning=&scantron_warning_screen('Start Grading');
5104: $r->print(<<STUFF);
5105: Validation process complete.<br />
5106: $warning
5107: <input type="submit" name="submit" value="Start Grading" />
5108: <input type="hidden" name="command" value="scantron_process" />
5109: STUFF
5110:
5111: } else {
5112: $r->print('<input type="hidden" name="command" value="scantron_validate" />');
5113: $r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
5114: }
5115: if ($stop) {
5116: if ($validate_phases[$currentphase] eq 'sequence') {
5117: $r->print('<input type="submit" name="submit" value="Ignore -> " />');
5118: $r->print(' this error <br />');
5119:
5120: $r->print(" <p>Or click the 'Grading Menu' button to start over.</p>");
5121: } else {
5122: $r->print('<input type="submit" name="submit" value="Continue ->" />');
5123: $r->print(' using corrected info <br />');
5124: $r->print("<input type='submit' value='Skip' name='scantron_skip_record' />");
5125: $r->print(" this scanline saving it for later.");
5126: }
5127: }
5128: $r->print(" </form><br />".&show_grading_menu_form($symb));
5129: return '';
5130: }
5131:
5132: sub scantron_remove_file {
5133: my ($which)=@_;
5134: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5135: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5136: my $file='scantron_';
5137: if ($which eq 'corrected' || $which eq 'skipped') {
5138: $file.=$which.'_';
5139: } else {
5140: return 'refused';
5141: }
5142: $file.=$env{'form.scantron_selectfile'};
5143: return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
5144: }
5145:
5146: sub scantron_remove_scan_data {
5147: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5148: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5149: my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
5150: my @todelete;
5151: my $filename=$env{'form.scantron_selectfile'};
5152: foreach my $key (@keys) {
5153: if ($key=~/^\Q$filename\E_/) {
5154: if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
5155: $key=~/remember_skipping/) {
5156: next;
5157: }
5158: push(@todelete,$key);
5159: }
5160: }
5161: my $result;
5162: if (@todelete) {
5163: $result=&Apache::lonnet::del('nohist_scantrondata',\@todelete,$cdom,$cname);
5164: }
5165: return $result;
5166: }
5167:
5168: sub scantron_getfile {
5169: #FIXME really would prefer a scantron directory
5170: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5171: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5172: my $lines;
5173: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
5174: 'scantron_orig_'.$env{'form.scantron_selectfile'});
5175: my %scanlines;
5176: $scanlines{'orig'}=[(split("\n",$lines,-1))];
5177: my $temp=$scanlines{'orig'};
5178: $scanlines{'count'}=$#$temp;
5179:
5180: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
5181: 'scantron_corrected_'.$env{'form.scantron_selectfile'});
5182: if ($lines eq '-1') {
5183: $scanlines{'corrected'}=[];
5184: } else {
5185: $scanlines{'corrected'}=[(split("\n",$lines,-1))];
5186: }
5187: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
5188: 'scantron_skipped_'.$env{'form.scantron_selectfile'});
5189: if ($lines eq '-1') {
5190: $scanlines{'skipped'}=[];
5191: } else {
5192: $scanlines{'skipped'}=[(split("\n",$lines,-1))];
5193: }
5194: my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
5195: if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
5196: my %scan_data = @tmp;
5197: return (\%scanlines,\%scan_data);
5198: }
5199:
5200: sub lonnet_putfile {
5201: my ($contents,$filename)=@_;
5202: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
5203: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5204: $env{'form.sillywaytopassafilearound'}=$contents;
5205: &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
5206:
5207: }
5208:
5209: sub scantron_putfile {
5210: my ($scanlines,$scan_data) = @_;
5211: #FIXME really would prefer a scantron directory
5212: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5213: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5214: if ($scanlines) {
5215: my $prefix='scantron_';
5216: # no need to update orig, shouldn't change
5217: # &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
5218: # $env{'form.scantron_selectfile'});
5219: &lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
5220: $prefix.'corrected_'.
5221: $env{'form.scantron_selectfile'});
5222: &lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
5223: $prefix.'skipped_'.
5224: $env{'form.scantron_selectfile'});
5225: }
5226: &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
5227: }
5228:
5229: sub scantron_get_line {
5230: my ($scanlines,$scan_data,$i)=@_;
5231: if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
5232: #if ($scanlines->{'skipped'}[$i]) { return undef; }
5233: if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
5234: return $scanlines->{'orig'}[$i];
5235: }
5236:
5237: sub get_todo_count {
5238: my ($scanlines,$scan_data)=@_;
5239: my $count=0;
5240: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
5241: my $line=&scantron_get_line($scanlines,$scan_data,$i);
5242: if ($line=~/^[\s\cz]*$/) { next; }
5243: $count++;
5244: }
5245: return $count;
5246: }
5247:
5248: sub scantron_put_line {
5249: my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
5250: if ($skip) {
5251: $scanlines->{'skipped'}[$i]=$newline;
5252: &start_skipping($scan_data,$i);
5253: return;
5254: }
5255: $scanlines->{'corrected'}[$i]=$newline;
5256: }
5257:
5258: sub scantron_clear_skip {
5259: my ($scanlines,$scan_data,$i)=@_;
5260: if (exists($scanlines->{'skipped'}[$i])) {
5261: undef($scanlines->{'skipped'}[$i]);
5262: return 1;
5263: }
5264: return 0;
5265: }
5266:
5267: sub scantron_filter_not_exam {
5268: my ($curres)=@_;
5269:
5270: if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
5271: # if the user has asked to not have either hidden
5272: # or 'randomout' controlled resources to be graded
5273: # don't include them
5274: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
5275: && $curres->randomout) {
5276: return 0;
5277: }
5278: return 1;
5279: }
5280: return 0;
5281: }
5282:
5283: sub scantron_validate_sequence {
5284: my ($r,$currentphase) = @_;
5285:
5286: my $navmap=Apache::lonnavmaps::navmap->new();
5287: my (undef,undef,$sequence)=
5288: &Apache::lonnet::decode_symb($env{'form.selectpage'});
5289:
5290: my $map=$navmap->getResourceByUrl($sequence);
5291:
5292: $r->print('<input type="hidden" name="validate_sequence_exam"
5293: value="ignore" />');
5294: if ($env{'form.validate_sequence_exam'} ne 'ignore') {
5295: my @resources=
5296: $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
5297: if (@resources) {
5298: $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>");
5299: return (1,$currentphase);
5300: }
5301: }
5302:
5303: return (0,$currentphase+1);
5304: }
5305:
5306: sub scantron_validate_ID {
5307: my ($r,$currentphase) = @_;
5308:
5309: #get student info
5310: my $classlist=&Apache::loncoursedata::get_classlist();
5311: my %idmap=&username_to_idmap($classlist);
5312:
5313: #get scantron line setup
5314: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
5315: my ($scanlines,$scan_data)=&scantron_getfile();
5316:
5317: my %found=('ids'=>{},'usernames'=>{});
5318: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
5319: my $line=&scantron_get_line($scanlines,$scan_data,$i);
5320: if ($line=~/^[\s\cz]*$/) { next; }
5321: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
5322: $scan_data);
5323: my $id=$$scan_record{'scantron.ID'};
5324: my $found;
5325: foreach my $checkid (keys(%idmap)) {
5326: if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
5327: }
5328: if ($found) {
5329: my $username=$idmap{$found};
5330: if ($found{'ids'}{$found}) {
5331: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
5332: $line,'duplicateID',$found);
5333: return(1,$currentphase);
5334: } elsif ($found{'usernames'}{$username}) {
5335: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
5336: $line,'duplicateID',$username);
5337: return(1,$currentphase);
5338: }
5339: #FIXME store away line we previously saw the ID on to use above
5340: $found{'ids'}{$found}++;
5341: $found{'usernames'}{$username}++;
5342: } else {
5343: if ($id =~ /^\s*$/) {
5344: my $username=&scan_data($scan_data,"$i.user");
5345: if (defined($username) && $found{'usernames'}{$username}) {
5346: &scantron_get_correction($r,$i,$scan_record,
5347: \%scantron_config,
5348: $line,'duplicateID',$username);
5349: return(1,$currentphase);
5350: } elsif (!defined($username)) {
5351: &scantron_get_correction($r,$i,$scan_record,
5352: \%scantron_config,
5353: $line,'incorrectID');
5354: return(1,$currentphase);
5355: }
5356: $found{'usernames'}{$username}++;
5357: } else {
5358: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
5359: $line,'incorrectID');
5360: return(1,$currentphase);
5361: }
5362: }
5363: }
5364:
5365: return (0,$currentphase+1);
5366: }
5367:
5368: sub scantron_get_correction {
5369: my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
5370:
5371: #FIXME in the case of a duplicated ID the previous line, probaly need
5372: #to show both the current line and the previous one and allow skipping
5373: #the previous one or the current one
5374:
5375: $r->print("<p><b>An error was detected ($error)</b>");
5376: if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
5377: $r->print(" for PaperID <tt>".
5378: $$scan_record{'scantron.PaperID'}."</tt> \n");
5379: } else {
5380: $r->print(" in scanline $i <pre>".
5381: $line."</pre> \n");
5382: }
5383: my $message="<p>The ID on the form is <tt>".
5384: $$scan_record{'scantron.ID'}."</tt><br />\n".
5385: "The name on the paper is ".
5386: $$scan_record{'scantron.LastName'}.",".
5387: $$scan_record{'scantron.FirstName'}."</p>";
5388:
5389: $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
5390: $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
5391: if ($error =~ /ID$/) {
5392: if ($error eq 'incorrectID') {
5393: $r->print("The encoded ID is not in the classlist</p>\n");
5394: } elsif ($error eq 'duplicateID') {
5395: $r->print("The encoded ID has also been used by a previous paper $arg</p>\n");
5396: }
5397: $r->print($message);
5398: $r->print("<p>How should I handle this? <br /> \n");
5399: $r->print("\n<ul><li> ");
5400: #FIXME it would be nice if this sent back the user ID and
5401: #could do partial userID matches
5402: $r->print(&Apache::loncommon::selectstudent_link('scantronupload',
5403: 'scantron_username','scantron_domain'));
5404: $r->print(": <input type='text' name='scantron_username' value='' />");
5405: $r->print("\n@".
5406: &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
5407:
5408: $r->print('</li>');
5409: } elsif ($error =~ /CODE$/) {
5410: if ($error eq 'incorrectCODE') {
5411: $r->print("</p><p>The encoded CODE is not in the list of possible CODEs</p>\n");
5412: } elsif ($error eq 'duplicateCODE') {
5413: $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");
5414: }
5415: $r->print("<p>The CODE on the form is <tt>'".
5416: $$scan_record{'scantron.CODE'}."'</tt><br />\n");
5417: $r->print($message);
5418: $r->print("<p>How should I handle this? <br /> \n");
5419: $r->print("\n<br /> ");
5420: my $i=0;
5421: if ($error eq 'incorrectCODE'
5422: && $$scan_record{'scantron.CODE'}=~/\S/ ) {
5423: my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
5424: if ($closest > 0) {
5425: foreach my $testcode (@{$closest}) {
5426: my $checked='';
5427: if (!$i) { $checked=' checked="checked" '; }
5428: $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' />");
5429: $r->print("\n<br />");
5430: $i++;
5431: }
5432: }
5433: }
5434: if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
5435: my $checked; if (!$i) { $checked=' checked="checked" '; }
5436: $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>");
5437: $r->print("\n<br />");
5438: }
5439:
5440: $r->print(<<ENDSCRIPT);
5441: <script type="text/javascript">
5442: function change_radio(field) {
5443: var slct=document.scantronupload.scantron_CODE_resolution;
5444: var i;
5445: for (i=0;i<slct.length;i++) {
5446: if (slct[i].value==field) { slct[i].checked=true; }
5447: }
5448: }
5449: </script>
5450: ENDSCRIPT
5451: my $href="/adm/pickcode?".
5452: "form=".&escape("scantronupload").
5453: "&scantron_format=".&escape($env{'form.scantron_format'}).
5454: "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
5455: "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
5456: "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
5457: if ($env{'form.scantron_CODElist'} =~ /\S/) {
5458: $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')\" />");
5459: $r->print("\n<br />");
5460: }
5461: $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.");
5462: $r->print("\n<br /><br />");
5463: } elsif ($error eq 'doublebubble') {
5464: $r->print("<p>There have been multiple bubbles scanned for a some question(s)</p>\n");
5465: $r->print('<input type="hidden" name="scantron_questions" value="'.
5466: join(',',@{$arg}).'" />');
5467: $r->print($message);
5468: $r->print("<p>Please indicate which bubble should be used for grading</p>");
5469: foreach my $question (@{$arg}) {
5470: my $selected=$$scan_record{"scantron.$question.answer"};
5471: &scantron_bubble_selector($r,$scan_config,$question,split('',$selected));
5472: }
5473: } elsif ($error eq 'missingbubble') {
5474: $r->print("<p>There have been <b>no</b> bubbles scanned for some question(s)</p>\n");
5475: $r->print($message);
5476: $r->print("<p>Please indicate which bubble should be used for grading</p>");
5477: $r->print("Some questions have no scanned bubbles\n");
5478: $r->print('<input type="hidden" name="scantron_questions" value="'.
5479: join(',',@{$arg}).'" />');
5480: foreach my $question (@{$arg}) {
5481: my $selected=$$scan_record{"scantron.$question.answer"};
5482: &scantron_bubble_selector($r,$scan_config,$question);
5483: }
5484: } else {
5485: $r->print("\n<ul>");
5486: }
5487: $r->print("\n</li></ul>");
5488:
5489: }
5490:
5491: sub scantron_bubble_selector {
5492: my ($r,$scan_config,$quest,@selected)=@_;
5493: my $max=$$scan_config{'Qlength'};
5494:
5495: my $scmode=$$scan_config{'Qon'};
5496: if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }
5497:
5498: my @alphabet=('A'..'Z');
5499: $r->print("<table border='1'><tr><td rowspan='2'>$quest</td>");
5500: for (my $i=0;$i<$max+1;$i++) {
5501: $r->print("\n".'<td align="center">');
5502: if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
5503: else { $r->print(' '); }
5504: $r->print('</td>');
5505: }
5506: $r->print('</tr><tr>');
5507: for (my $i=0;$i<$max;$i++) {
5508: $r->print("\n".
5509: '<td><label><input type="radio" name="scantron_correct_Q_'.
5510: $quest.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
5511: }
5512: $r->print('<td><label><input type="radio" name="scantron_correct_Q_'.
5513: $quest.'" value="none" /> No bubble </label></td>');
5514: $r->print('</tr></table>');
5515: }
5516:
5517: sub num_matches {
5518: my ($orig,$code) = @_;
5519: my @code=split(//,$code);
5520: my @orig=split(//,$orig);
5521: my $same=0;
5522: for (my $i=0;$i<scalar(@code);$i++) {
5523: if ($code[$i] eq $orig[$i]) { $same++; }
5524: }
5525: return $same;
5526: }
5527:
5528: sub scantron_get_closely_matching_CODEs {
5529: my ($allcodes,$CODE)=@_;
5530: my @CODEs;
5531: foreach my $testcode (sort(keys(%{$allcodes}))) {
5532: push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
5533: }
5534:
5535: return ($#CODEs,$CODEs[-1]);
5536: }
5537:
5538: sub get_codes {
5539: my ($old_name, $cdom, $cnum) = @_;
5540: if (!$old_name) {
5541: $old_name=$env{'form.scantron_CODElist'};
5542: }
5543: if (!$cdom) {
5544: $cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
5545: }
5546: if (!$cnum) {
5547: $cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
5548: }
5549: my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
5550: $cdom,$cnum);
5551: my %allcodes;
5552: if ($result{"type\0$old_name"} eq 'number') {
5553: %allcodes=map {($_,1)} split(',',$result{$old_name});
5554: } else {
5555: %allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
5556: }
5557: return %allcodes;
5558: }
5559:
5560: sub scantron_validate_CODE {
5561: my ($r,$currentphase) = @_;
5562: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
5563: if ($scantron_config{'CODElocation'} &&
5564: $scantron_config{'CODEstart'} &&
5565: $scantron_config{'CODElength'}) {
5566: if (!defined($env{'form.scantron_CODElist'})) {
5567: &FIXME_blow_up()
5568: }
5569: } else {
5570: return (0,$currentphase+1);
5571: }
5572:
5573: my %usedCODEs;
5574:
5575: my %allcodes=&get_codes();
5576:
5577: my ($scanlines,$scan_data)=&scantron_getfile();
5578: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
5579: my $line=&scantron_get_line($scanlines,$scan_data,$i);
5580: if ($line=~/^[\s\cz]*$/) { next; }
5581: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
5582: $scan_data);
5583: my $CODE=$$scan_record{'scantron.CODE'};
5584: my $error=0;
5585: if (!&Apache::lonnet::validCODE($CODE)) {
5586: &scantron_get_correction($r,$i,$scan_record,
5587: \%scantron_config,
5588: $line,'incorrectCODE',\%allcodes);
5589: return(1,$currentphase);
5590: }
5591: if (%allcodes && !exists($allcodes{$CODE})
5592: && !$$scan_record{'scantron.useCODE'}) {
5593: &scantron_get_correction($r,$i,$scan_record,
5594: \%scantron_config,
5595: $line,'incorrectCODE',\%allcodes);
5596: return(1,$currentphase);
5597: }
5598: if (exists($usedCODEs{$CODE})
5599: && $env{'form.scantron_CODEunique'} eq 'yes'
5600: && !$$scan_record{'scantron.CODE_ignore_dup'}) {
5601: &scantron_get_correction($r,$i,$scan_record,
5602: \%scantron_config,
5603: $line,'duplicateCODE',$usedCODEs{$CODE});
5604: return(1,$currentphase);
5605: }
5606: push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
5607: }
5608: return (0,$currentphase+1);
5609: }
5610:
5611: sub scantron_validate_doublebubble {
5612: my ($r,$currentphase) = @_;
5613: #get student info
5614: my $classlist=&Apache::loncoursedata::get_classlist();
5615: my %idmap=&username_to_idmap($classlist);
5616:
5617: #get scantron line setup
5618: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
5619: my ($scanlines,$scan_data)=&scantron_getfile();
5620: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
5621: my $line=&scantron_get_line($scanlines,$scan_data,$i);
5622: if ($line=~/^[\s\cz]*$/) { next; }
5623: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
5624: $scan_data);
5625: if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
5626: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
5627: 'doublebubble',
5628: $$scan_record{'scantron.doubleerror'});
5629: return (1,$currentphase);
5630: }
5631: return (0,$currentphase+1);
5632: }
5633:
5634: sub scantron_get_maxbubble {
5635: if (defined($env{'form.scantron_maxbubble'}) &&
5636: $env{'form.scantron_maxbubble'}) {
5637: return $env{'form.scantron_maxbubble'};
5638: }
5639:
5640: my $navmap=Apache::lonnavmaps::navmap->new();
5641: my (undef,undef,$sequence)=
5642: &Apache::lonnet::decode_symb($env{'form.selectpage'});
5643:
5644: my $map=$navmap->getResourceByUrl($sequence);
5645: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
5646:
5647: &Apache::lonxml::clear_problem_counter();
5648:
5649: foreach my $resource (@resources) {
5650: my $result=&Apache::lonnet::ssi($resource->src(),
5651: ('symb' => $resource->symb()));
5652: }
5653: &Apache::lonnet::delenv('scantron\.');
5654: $env{'form.scantron_maxbubble'} =
5655: &Apache::lonxml::get_problem_counter()-1;
5656:
5657: return $env{'form.scantron_maxbubble'};
5658: }
5659:
5660: sub scantron_validate_missingbubbles {
5661: my ($r,$currentphase) = @_;
5662: #get student info
5663: my $classlist=&Apache::loncoursedata::get_classlist();
5664: my %idmap=&username_to_idmap($classlist);
5665:
5666: #get scantron line setup
5667: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
5668: my ($scanlines,$scan_data)=&scantron_getfile();
5669: my $max_bubble=&scantron_get_maxbubble();
5670: if (!$max_bubble) { $max_bubble=2**31; }
5671: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
5672: my $line=&scantron_get_line($scanlines,$scan_data,$i);
5673: if ($line=~/^[\s\cz]*$/) { next; }
5674: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
5675: $scan_data);
5676: if (!defined($$scan_record{'scantron.missingerror'})) { next; }
5677: my @to_correct;
5678: foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
5679: if ($missing > $max_bubble) { next; }
5680: push(@to_correct,$missing);
5681: }
5682: if (@to_correct) {
5683: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
5684: $line,'missingbubble',\@to_correct);
5685: return (1,$currentphase);
5686: }
5687:
5688: }
5689: return (0,$currentphase+1);
5690: }
5691:
5692: sub scantron_process_students {
5693: my ($r) = @_;
5694: my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
5695: my ($symb)=&get_symb($r);
5696: if (!$symb) {return '';}
5697: my $default_form_data=&defaultFormData($symb);
5698:
5699: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
5700: my ($scanlines,$scan_data)=&scantron_getfile();
5701: my $classlist=&Apache::loncoursedata::get_classlist();
5702: my %idmap=&username_to_idmap($classlist);
5703: my $navmap=Apache::lonnavmaps::navmap->new();
5704: my $map=$navmap->getResourceByUrl($sequence);
5705: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
5706: # $r->print("geto ".scalar(@resources)."<br />");
5707: my $result= <<SCANTRONFORM;
5708: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
5709: <input type="hidden" name="command" value="scantron_configphase" />
5710: $default_form_data
5711: SCANTRONFORM
5712: $r->print($result);
5713:
5714: my @delayqueue;
5715: my %completedstudents;
5716:
5717: my $count=&get_todo_count($scanlines,$scan_data);
5718: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
5719: 'Scantron Progress',$count,
5720: 'inline',undef,'scantronupload');
5721: &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
5722: 'Processing first student');
5723: my $start=&Time::HiRes::time();
5724: my $i=-1;
5725: my ($uname,$udom,$started);
5726: while ($i<$scanlines->{'count'}) {
5727: ($uname,$udom)=('','');
5728: $i++;
5729: my $line=&scantron_get_line($scanlines,$scan_data,$i);
5730: if ($line=~/^[\s\cz]*$/) { next; }
5731: if ($started) {
5732: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
5733: 'last student');
5734: }
5735: $started=1;
5736: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
5737: $scan_data);
5738: unless ($uname=&scantron_find_student($scan_record,$scan_data,
5739: \%idmap,$i)) {
5740: &scantron_add_delay(\@delayqueue,$line,
5741: 'Unable to find a student that matches',1);
5742: next;
5743: }
5744: if (exists $completedstudents{$uname}) {
5745: &scantron_add_delay(\@delayqueue,$line,
5746: 'Student '.$uname.' has multiple sheets',2);
5747: next;
5748: }
5749: ($uname,$udom)=split(/:/,$uname);
5750:
5751: &Apache::lonxml::clear_problem_counter();
5752: &Apache::lonnet::appenv(%$scan_record);
5753:
5754: if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
5755: &scantron_putfile($scanlines,$scan_data);
5756: }
5757:
5758: my $i=0;
5759: foreach my $resource (@resources) {
5760: $i++;
5761: my %form=('submitted' =>'scantron',
5762: 'grade_target' =>'grade',
5763: 'grade_username'=>$uname,
5764: 'grade_domain' =>$udom,
5765: 'grade_courseid'=>$env{'request.course.id'},
5766: 'grade_symb' =>$resource->symb());
5767: if (exists($scan_record->{'scantron.CODE'})
5768: &&
5769: &Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
5770: $form{'CODE'}=$scan_record->{'scantron.CODE'};
5771: } else {
5772: $form{'CODE'}='';
5773: }
5774: my $result=&Apache::lonnet::ssi($resource->src(),%form);
5775: if ($result ne '') {
5776: &Apache::lonnet::logthis("scantron grading error -> $result");
5777: &Apache::lonnet::logthis("scantron grading error info name $uname domain $udom course $env{'request.course.id'} url ".$resource->src());
5778: }
5779: if (&Apache::loncommon::connection_aborted($r)) { last; }
5780: }
5781: $completedstudents{$uname}={'line'=>$line};
5782: if (&Apache::loncommon::connection_aborted($r)) { last; }
5783: } continue {
5784: &Apache::lonxml::clear_problem_counter();
5785: &Apache::lonnet::delenv('scantron\.');
5786: }
5787: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
5788: # my $lasttime = &Time::HiRes::time()-$start;
5789: # $r->print("<p>took $lasttime</p>");
5790:
5791: $r->print("</form>");
5792: $r->print(&show_grading_menu_form($symb));
5793: return '';
5794: }
5795:
5796: sub scantron_upload_scantron_data {
5797: my ($r)=@_;
5798: $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
5799: my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
5800: 'domainid',
5801: 'coursename');
5802: my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
5803: 'domainid');
5804: my $default_form_data=&defaultFormData(&get_symb($r,1));
5805: $r->print(<<UPLOAD);
5806: <script type="text/javascript" language="javascript">
5807: function checkUpload(formname) {
5808: if (formname.upfile.value == "") {
5809: alert("Please use the browse button to select a file from your local directory.");
5810: return false;
5811: }
5812: formname.submit();
5813: }
5814: </script>
5815:
5816: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
5817: $default_form_data
5818: <table>
5819: <tr><td>$select_link </td></tr>
5820: <tr><td>Course ID: </td><td><input name='courseid' type='text' /> </td></tr>
5821: <tr><td>Course Name: </td><td><input name='coursename' type='text' /></td></tr>
5822: <tr><td>Domain: </td><td>$domsel </td></tr>
5823: <tr><td>File to upload:</td><td><input type="file" name="upfile" size="50" /></td></tr>
5824: </table>
5825: <input name='command' value='scantronupload_save' type='hidden' />
5826: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
5827: </form>
5828: UPLOAD
5829: return '';
5830: }
5831:
5832: sub scantron_upload_scantron_data_save {
5833: my($r)=@_;
5834: my ($symb)=&get_symb($r,1);
5835: my $doanotherupload=
5836: '<br /><form action="/adm/grades" method="post">'."\n".
5837: '<input type="hidden" name="command" value="scantronupload" />'."\n".
5838: '<input type="submit" name="submit" value="Do Another Upload" />'."\n".
5839: '</form>'."\n";
5840: if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
5841: !&Apache::lonnet::allowed('usc',
5842: $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
5843: $r->print("You are not allowed to upload Scantron data to the requested course.<br />");
5844: if ($symb) {
5845: $r->print(&show_grading_menu_form($symb));
5846: } else {
5847: $r->print($doanotherupload);
5848: }
5849: return '';
5850: }
5851: my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
5852: $r->print("Doing upload to ".$coursedata{'description'}." <br />");
5853: my $fname=$env{'form.upfile.filename'};
5854: #FIXME
5855: #copied from lonnet::userfileupload()
5856: #make that function able to target a specified course
5857: # Replace Windows backslashes by forward slashes
5858: $fname=~s/\\/\//g;
5859: # Get rid of everything but the actual filename
5860: $fname=~s/^.*\/([^\/]+)$/$1/;
5861: # Replace spaces by underscores
5862: $fname=~s/\s+/\_/g;
5863: # Replace all other weird characters by nothing
5864: $fname=~s/[^\w\.\-]//g;
5865: # See if there is anything left
5866: unless ($fname) { return 'error: no uploaded file'; }
5867: my $uploadedfile=$fname;
5868: $fname='scantron_orig_'.$fname;
5869: if (length($env{'form.upfile'}) < 2) {
5870: $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.");
5871: } else {
5872: my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
5873: if ($result =~ m|^/uploaded/|) {
5874: $r->print("<span class=\"LC_success\">Success:</span> Successfully uploaded ".(length($env{'form.upfile'})-1)." bytes of data into location <tt>".$result."</tt>");
5875: } else {
5876: $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>");
5877: }
5878: }
5879: if ($symb) {
5880: $r->print(&scantron_selectphase($r,$uploadedfile));
5881: } else {
5882: $r->print($doanotherupload);
5883: }
5884: return '';
5885: }
5886:
5887: sub valid_file {
5888: my ($requested_file)=@_;
5889: foreach my $filename (sort(&scantron_filenames())) {
5890: if ($requested_file eq $filename) { return 1; }
5891: }
5892: return 0;
5893: }
5894:
5895: sub scantron_download_scantron_data {
5896: my ($r)=@_;
5897: my $default_form_data=&defaultFormData(&get_symb($r,1));
5898: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5899: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5900: my $file=$env{'form.scantron_selectfile'};
5901: if (! &valid_file($file)) {
5902: $r->print(<<ERROR);
5903: <p>
5904: The requested file name was invalid.
5905: </p>
5906: ERROR
5907: $r->print(&show_grading_menu_form(&get_symb($r,1)));
5908: return;
5909: }
5910: my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
5911: my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
5912: my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
5913: &Apache::lonnet::allowuploaded('/adm/grades',$orig);
5914: &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
5915: &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
5916: $r->print(<<DOWNLOAD);
5917: <p>
5918: <a href="$orig">Original</a> file as uploaded by the scantron office.
5919: </p>
5920: <p>
5921: <a href="$corrected">Corrections</a>, a file of corrected records that were used in grading.
5922: </p>
5923: <p>
5924: <a href="$skipped">Skipped</a>, a file of records that were skipped.
5925: </p>
5926: DOWNLOAD
5927: $r->print(&show_grading_menu_form(&get_symb($r,1)));
5928: return '';
5929: }
5930:
5931: #-------- end of section for handling grading scantron forms -------
5932: #
5933: #-------------------------------------------------------------------
5934:
5935: #-------------------------- Menu interface -------------------------
5936: #
5937: #--- Show a Grading Menu button - Calls the next routine ---
5938: sub show_grading_menu_form {
5939: my ($symb)=@_;
5940: my $result.='<br /><form action="/adm/grades" method="post">'."\n".
5941: '<input type="hidden" name="symb" value="'.$symb.'" />'."\n".
5942: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
5943: '<input type="hidden" name="command" value="gradingmenu" />'."\n".
5944: '<input type="submit" name="submit" value="Grading Menu" />'."\n".
5945: '</form>'."\n";
5946: return $result;
5947: }
5948:
5949: # -- Retrieve choices for grading form
5950: sub savedState {
5951: my %savedState = ();
5952: if ($env{'form.saveState'}) {
5953: foreach (split(/:/,$env{'form.saveState'})) {
5954: my ($key,$value) = split(/=/,$_,2);
5955: $savedState{$key} = $value;
5956: }
5957: }
5958: return \%savedState;
5959: }
5960:
5961: #--- Displays the main menu page -------
5962: sub gradingmenu {
5963: my ($request) = @_;
5964: my ($symb)=&get_symb($request);
5965: if (!$symb) {return '';}
5966: my $probTitle = &Apache::lonnet::gettitle($symb);
5967:
5968: $request->print(<<GRADINGMENUJS);
5969: <script type="text/javascript" language="javascript">
5970: function checkChoice(formname,val,cmdx) {
5971: if (val <= 2) {
5972: var cmd = radioSelection(formname.radioChoice);
5973: var cmdsave = cmd;
5974: } else {
5975: cmd = cmdx;
5976: cmdsave = 'submission';
5977: }
5978: formname.command.value = cmd;
5979: formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
5980: ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
5981: if (val < 5) formname.submit();
5982: if (val == 5) {
5983: if (!checkReceiptNo(formname,'notOK')) { return false;}
5984: formname.submit();
5985: }
5986: if (val < 7) formname.submit();
5987: }
5988:
5989: function checkReceiptNo(formname,nospace) {
5990: var receiptNo = formname.receipt.value;
5991: var checkOpt = false;
5992: if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
5993: if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
5994: if (checkOpt) {
5995: alert("Please enter a receipt number given by a student in the receipt box.");
5996: formname.receipt.value = "";
5997: formname.receipt.focus();
5998: return false;
5999: }
6000: return true;
6001: }
6002: </script>
6003: GRADINGMENUJS
6004: &commonJSfunctions($request);
6005: my $result='<h3> <span class="LC_info">Manual Grading/View Submission</span></h3>';
6006: my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
6007: $result.=$table;
6008: my (undef,$sections) = &getclasslist('all','0');
6009: my $savedState = &savedState();
6010: my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
6011: my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
6012: my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
6013: my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
6014:
6015: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
6016: '<input type="hidden" name="symb" value="'.$symb.'" />'."\n".
6017: '<input type="hidden" name="handgrade" value="'.$hdgrade.'" />'."\n".
6018: '<input type="hidden" name="probTitle" value="'.$probTitle.'" />'."\n".
6019: '<input type="hidden" name="command" value="" />'."\n".
6020: '<input type="hidden" name="saveState" value="" />'."\n".
6021: '<input type="hidden" name="gradingMenu" value="1" />'."\n".
6022: '<input type="hidden" name="showgrading" value="yes" />'."\n";
6023:
6024: $result.='<table width="100%" border="0"><tr><td bgcolor=#777777>'."\n".
6025: '<table width="100%" border="0"><tr bgcolor="#e6ffff"><td colspan="2">'."\n".
6026: ' <b>Select a Grading/Viewing Option</b></td></tr>'."\n".
6027: '<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
6028:
6029: $result.='<table width="100%" border="0">';
6030: $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
6031: ' '.&mt('Select Section').': <select name="section">'."\n";
6032: if (ref($sections)) {
6033: foreach (sort (@$sections)) {
6034: $result.='<option value="'.$_.'" '.
6035: ($saveSec eq $_ ? 'selected="selected"':'').'>'.$_.'</option>'."\n";
6036: }
6037: }
6038: $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> ';
6039:
6040: $result.=&mt('Student Status').':'.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,undef);
6041:
6042: $result.='</td></tr>';
6043:
6044: $result.='<tr bgcolor="#ffffe6"valign="top"><td><label>'.
6045: '<input type="radio" name="radioChoice" value="submission" '.
6046: ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.'<b>'.&mt('Current Resource').':</b> '.&mt('For one or more students').
6047: '</label> <select name="submitonly">'.
6048: '<option value="yes" '.
6049: ($saveSub eq 'yes' ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>'.
6050: '<option value="queued" '.
6051: ($saveSub eq 'queued' ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>'.
6052: '<option value="graded" '.
6053: ($saveSub eq 'graded' ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>'.
6054: '<option value="incorrect" '.
6055: ($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>'.
6056: '<option value="all" '.
6057: ($saveSub eq 'all' ? 'selected="selected"' : '').'>'.&mt('with any status').'</option></select></td></tr>'."\n";
6058:
6059: $result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
6060: '<label><input type="radio" name="radioChoice" value="viewgrades" '.
6061: ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
6062: '<b>Current Resource:</b> For all students in selected section or course</label></td></tr>'."\n";
6063:
6064: $result.='<tr bgcolor="#ffffe6" valign="top"><td>'.
6065: '<label><input type="radio" name="radioChoice" value="pickStudentPage" '.
6066: ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
6067: 'The <b>complete</b> set/page/sequence: For one student</label></td></tr>'."\n";
6068:
6069: $result.='<tr bgcolor="#ffffe6"><td><br />'.
6070: '<input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="Next->" />'.
6071: '</td></tr></table>'."\n";
6072:
6073: $result.='</td><td valign="top">';
6074:
6075: $result.='<table width="100%" border="0">';
6076: $result.='<tr bgcolor="#ffffe6"><td>'.
6077: '<input type="button" onClick="javascript:checkChoice(this.form,\'3\',\'csvform\');" value="'.&mt('Upload').'" />'.
6078: ' '.&mt('scores from file').' </td></tr>'."\n";
6079:
6080: $result.='<tr bgcolor="#ffffe6"><td>'.
6081: '<input type="button" onClick="javascript:checkChoice(this.form,\'6\',\'processclicker\');" value="'.&mt('Process').'" />'.
6082: ' '.&mt('clicker file').' </td></tr>'."\n";
6083:
6084: $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
6085: '<input type="button" onClick="javascript:checkChoice(this.form,\'4\',\'scantron_selectphase\');'.
6086: '" value="'.&mt('Grade').'" /> scantron forms</td></tr>'."\n";
6087:
6088: if ((&Apache::lonnet::allowed('mgr',$env{'request.course.id'})) && ($symb)) {
6089: $result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
6090: '<input type="button" onClick="javascript:checkChoice(this.form,\'5\',\'verify\');" value="'.&mt('Verify').'" />'.
6091: ' '.&mt('receipt').': '.
6092: &Apache::lonnet::recprefix($env{'request.course.id'}).
6093: '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />'.
6094: '</td></tr>'."\n";
6095: }
6096: $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
6097: '<input type="button" onClick="javascript:this.form.action=\'/adm/helper/resettimes.helper\';this.form.submit();'.
6098: '" value="'.&mt('Manage').'" /> access times.</td></tr>'."\n";
6099: $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
6100: '<input type="button" onClick="javascript:this.form.command.value=\'codelist\';this.form.action=\'/adm/pickcode\';this.form.submit();'.
6101: '" value="'.&mt('View').'" /> saved CODEs.</td></tr>'."\n";
6102:
6103: $result.='</table>'."\n".
6104: '</td></tr></table>'."\n".
6105: '</td></tr></table></form>'."\n";
6106: return $result;
6107: }
6108:
6109: sub reset_perm {
6110: undef(%perm);
6111: }
6112:
6113: sub init_perm {
6114: &reset_perm();
6115: foreach my $test_perm ('vgr','mgr','opa') {
6116:
6117: my $scope = $env{'request.course.id'};
6118: if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
6119:
6120: $scope .= '/'.$env{'request.course.sec'};
6121: if ( $perm{$test_perm}=
6122: &Apache::lonnet::allowed($test_perm,$scope)) {
6123: $perm{$test_perm.'_section'}=$env{'request.course.sec'};
6124: } else {
6125: delete($perm{$test_perm});
6126: }
6127: }
6128: }
6129: }
6130:
6131: sub gather_clicker_ids {
6132: my %clicker_ids;
6133:
6134: my $classlist = &Apache::loncoursedata::get_classlist();
6135:
6136: # Set up a couple variables.
6137: my $username_idx = &Apache::loncoursedata::CL_SNAME();
6138: my $domain_idx = &Apache::loncoursedata::CL_SDOM();
6139:
6140: foreach my $student (keys(%$classlist)) {
6141:
6142: my $username = $classlist->{$student}->[$username_idx];
6143: my $domain = $classlist->{$student}->[$domain_idx];
6144: my $clickers =
6145: (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
6146: foreach my $id (split(/\,/,$clickers)) {
6147: $id=~s/^0+//;
6148: if (exists($clicker_ids{$id})) {
6149: $clicker_ids{$id}.=','.$username.':'.$domain;
6150: } else {
6151: $clicker_ids{$id}=$username.':'.$domain;
6152: }
6153: }
6154: }
6155: return %clicker_ids;
6156: }
6157:
6158: sub gather_adv_clicker_ids {
6159: my %clicker_ids;
6160: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
6161: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6162: my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
6163: foreach my $element (sort keys %coursepersonnel) {
6164: foreach my $person (split(/\,/,$coursepersonnel{$element})) {
6165: my ($puname,$pudom)=split(/\:/,$person);
6166: my $clickers =
6167: (&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
6168: foreach my $id (split(/\,/,$clickers)) {
6169: $id=~s/^0+//;
6170: if (exists($clicker_ids{$id})) {
6171: $clicker_ids{$id}.=','.$puname.':'.$pudom;
6172: } else {
6173: $clicker_ids{$id}=$puname.':'.$pudom;
6174: }
6175: }
6176: }
6177: }
6178: return %clicker_ids;
6179: }
6180:
6181: sub process_clicker {
6182: my ($r)=@_;
6183: my ($symb)=&get_symb($r);
6184: if (!$symb) {return '';}
6185: my $result=&checkforfile_js();
6186: $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
6187: my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
6188: $result.=$table;
6189: $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
6190: $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
6191: $result.=' <b>'.&mt('Specify a file containing the clicker information for this resource').
6192: '.</b></td></tr>'."\n";
6193: $result.='<tr bgcolor=#ffffe6><td>'."\n";
6194: my $upload=&mt("Upload File");
6195: my $type=&mt("Type");
6196: my $attendance=&mt("Award points just for participation");
6197: my $personnel=&mt("Correctness determined from response by course personnel");
6198: my $specific=&mt("Correctness determined from response with clicker ID");
6199: my $pcorrect=&mt("Percentage points for correct solution");
6200: my $pincorrect=&mt("Percentage points for incorrect solution");
6201: my $selectform=&Apache::loncommon::select_form('iclicker','upfiletype',
6202: ('iclicker' => 'i>clicker'));
6203:
6204: $result.=<<ENDUPFORM;
6205: <script type="text/javascript">
6206: function sanitycheck() {
6207: // Accept only integer percentages
6208: document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
6209: document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
6210: // Find out grading choice
6211: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
6212: if (document.forms.gradesupload.gradingmechanism[i].checked) {
6213: gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
6214: }
6215: }
6216: // By default, new choice equals user selection
6217: newgradingchoice=gradingchoice;
6218: // Not good to give more points for false answers than correct ones
6219: if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
6220: document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
6221: }
6222: // If new choice is attendance only, and old choice was correctness-based, restore defaults
6223: if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
6224: document.forms.gradesupload.pcorrect.value=100;
6225: document.forms.gradesupload.pincorrect.value=100;
6226: }
6227: // If the values are different, cannot be attendance only
6228: if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
6229: (gradingchoice=='attendance')) {
6230: newgradingchoice='personnel';
6231: }
6232: // Change grading choice to new one
6233: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
6234: if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
6235: document.forms.gradesupload.gradingmechanism[i].checked=true;
6236: } else {
6237: document.forms.gradesupload.gradingmechanism[i].checked=false;
6238: }
6239: }
6240: // Remember the old state
6241: document.forms.gradesupload.waschecked.value=newgradingchoice;
6242: }
6243: </script>
6244: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
6245: <input type="hidden" name="symb" value="$symb" />
6246: <input type="hidden" name="command" value="processclickerfile" />
6247: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
6248: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
6249: <input type="file" name="upfile" size="50" />
6250: <br /><label>$type: $selectform</label>
6251: <br /><label>$attendance: <input type="radio" name="gradingmechanism" value="attendance" checked="checked" onClick="sanitycheck()" /></label>
6252: <br /><label>$personnel: <input type="radio" name="gradingmechanism" value="personnel" onClick="sanitycheck()" /></label>
6253: <br /><label>$specific: <input type="radio" name="gradingmechanism" value="specific" onClick="sanitycheck()" /></label>
6254: <input type="text" name="specificid" size="15" />
6255: <input type="hidden" name="waschecked" value="attendance" />
6256: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="100" onChange="sanitycheck()" /></label>
6257: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="100" onChange="sanitycheck()" /></label>
6258: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
6259: </form>
6260: ENDUPFORM
6261: $result.='</td></tr></table>'."\n".
6262: '</td></tr></table><br /><br />'."\n";
6263: $result.=&show_grading_menu_form($symb);
6264: return $result;
6265: }
6266:
6267: sub process_clicker_file {
6268: my ($r)=@_;
6269: my ($symb)=&get_symb($r);
6270: if (!$symb) {return '';}
6271: my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
6272: if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
6273: $result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
6274: return $result.&show_grading_menu_form($symb);
6275: }
6276: my %clicker_ids=&gather_clicker_ids();
6277: my %correct_ids;
6278: if ($env{'form.gradingmechanism'} eq 'personnel') {
6279: %correct_ids=&gather_adv_clicker_ids();
6280: }
6281: if ($env{'form.gradingmechanism'} eq 'specific') {
6282: my $correct_id=$env{'form.specificid'};
6283: $correct_id=~tr/a-z/A-Z/;
6284: $correct_id=~s/\s//gs;
6285: $correct_id=~s/^0+//;
6286: $correct_ids{$correct_id}='specified';
6287: }
6288: if ($env{'form.gradingmechanism'} eq 'attendance') {
6289: $result.=&mt('Score based on attendance only');
6290: } else {
6291: my $number=0;
6292: $result.='<h3>'.&mt('Correctness determined by the following IDs').'</h3>';
6293: foreach my $id (sort(keys(%correct_ids))) {
6294: $result.='<tt>'.$id.'</tt> - ';
6295: if ($correct_ids{$id} eq 'specified') {
6296: $result.=&mt('specified');
6297: } else {
6298: my ($uname,$udom)=split(/\:/,$correct_ids{$id});
6299: $result.=&Apache::loncommon::plainname($uname,$udom);
6300: }
6301: $result.='<br />';
6302: $number++;
6303: }
6304: if ($number==0) {
6305: $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
6306: return $result.&show_grading_menu_form($symb);
6307: }
6308: }
6309: if (length($env{'form.upfile'}) < 2) {
6310: $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
6311: '<span class="LC_error">',
6312: '</span>',
6313: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
6314: return $result.&show_grading_menu_form($symb);
6315: }
6316: my %responses;
6317: my @questiontitles;
6318: my $errormsg='';
6319: my $number=0;
6320: if ($env{'form.upfiletype'} eq 'iclicker') {
6321: ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
6322: }
6323: $result.='<br />'.&mt('Found [_1] questions',$number).'<br />';
6324: foreach my $id (keys %responses) {
6325: $result.='<br />'.$id.' - '.$responses{$id};
6326: }
6327: return $result.&show_grading_menu_form($symb);
6328: }
6329:
6330: sub iclicker_eval {
6331: my ($questiontitles,$responses)=@_;
6332: my $number=0;
6333: my $errormsg='';
6334: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
6335: chomp($line);
6336: foreach my $quoted ($line=~/\,\s*\"([^\"]*)\"\s*\,/g) {
6337: my $replace=$quoted;
6338: $replace=~s/\,//g;
6339: &Apache::lonnet::logthis($quoted.' - '.$replace.'<br />');
6340: $line=~s/\,\s*\"\Q$quoted\E\"\s*\,/,$replace,/gs;
6341: }
6342: my @entries=split(/\,/,$line);
6343: if ($entries[0] eq 'Question') {
6344: for (my $i=3;$i<$#entries;$i+=6) {
6345: $$questiontitles[$number]=$entries[$i];
6346: $number++;
6347: }
6348: }
6349: if ($entries[0]=~/^\#/) {
6350: my $id=$entries[0];
6351: my @idresponses;
6352: $id=~s/^[\#0]+//;
6353: for (my $i=0;$i<$number;$i++) {
6354: my $idx=3+$i*6;
6355: push(@idresponses,$entries[$idx]);
6356: }
6357: $$responses{$id}=join(',',@idresponses);
6358: }
6359: }
6360: return ($errormsg,$number);
6361: }
6362:
6363: sub handler {
6364: my $request=$_[0];
6365:
6366: &reset_perm();
6367: if ($env{'browser.mathml'}) {
6368: &Apache::loncommon::content_type($request,'text/xml');
6369: } else {
6370: &Apache::loncommon::content_type($request,'text/html');
6371: }
6372: $request->send_http_header;
6373: return '' if $request->header_only;
6374: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
6375: my $symb=&get_symb($request,1);
6376: my @commands=&Apache::loncommon::get_env_multiple('form.command');
6377: my $command=$commands[0];
6378: if ($#commands > 0) {
6379: &Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
6380: }
6381: $request->print(&Apache::loncommon::start_page('Grading'));
6382: if ($symb eq '' && $command eq '') {
6383: if ($env{'user.adv'}) {
6384: if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
6385: ($env{'form.codethree'})) {
6386: my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
6387: $env{'form.codethree'};
6388: my ($tsymb,$tuname,$tudom,$tcrsid)=
6389: &Apache::lonnet::checkin($token);
6390: if ($tsymb) {
6391: my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
6392: if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
6393: $request->print(&Apache::lonnet::ssi_body('/res/'.$url,
6394: ('grade_username' => $tuname,
6395: 'grade_domain' => $tudom,
6396: 'grade_courseid' => $tcrsid,
6397: 'grade_symb' => $tsymb)));
6398: } else {
6399: $request->print('<h3>Not authorized: '.$token.'</h3>');
6400: }
6401: } else {
6402: $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
6403: }
6404: } else {
6405: $request->print(&Apache::lonxml::tokeninputfield());
6406: }
6407: }
6408: } else {
6409: &init_perm();
6410: if ($command eq 'submission' && $perm{'vgr'}) {
6411: ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
6412: } elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
6413: &pickStudentPage($request);
6414: } elsif ($command eq 'displayPage' && $perm{'vgr'}) {
6415: &displayPage($request);
6416: } elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
6417: &updateGradeByPage($request);
6418: } elsif ($command eq 'processGroup' && $perm{'vgr'}) {
6419: &processGroup($request);
6420: } elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
6421: $request->print(&gradingmenu($request));
6422: } elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
6423: $request->print(&viewgrades($request));
6424: } elsif ($command eq 'handgrade' && $perm{'mgr'}) {
6425: $request->print(&processHandGrade($request));
6426: } elsif ($command eq 'editgrades' && $perm{'mgr'}) {
6427: $request->print(&editgrades($request));
6428: } elsif ($command eq 'verify' && $perm{'vgr'}) {
6429: $request->print(&verifyreceipt($request));
6430: } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
6431: $request->print(&process_clicker($request));
6432: } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
6433: $request->print(&process_clicker_file($request));
6434: } elsif ($command eq 'csvform' && $perm{'mgr'}) {
6435: $request->print(&upcsvScores_form($request));
6436: } elsif ($command eq 'csvupload' && $perm{'mgr'}) {
6437: $request->print(&csvupload($request));
6438: } elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
6439: $request->print(&csvuploadmap($request));
6440: } elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
6441: if ($env{'form.associate'} ne 'Reverse Association') {
6442: $request->print(&csvuploadoptions($request));
6443: } else {
6444: if ( $env{'form.upfile_associate'} ne 'reverse' ) {
6445: $env{'form.upfile_associate'} = 'reverse';
6446: } else {
6447: $env{'form.upfile_associate'} = 'forward';
6448: }
6449: $request->print(&csvuploadmap($request));
6450: }
6451: } elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
6452: $request->print(&csvuploadassign($request));
6453: } elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
6454: $request->print(&scantron_selectphase($request));
6455: } elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
6456: $request->print(&scantron_do_warning($request));
6457: } elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
6458: $request->print(&scantron_validate_file($request));
6459: } elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
6460: $request->print(&scantron_process_students($request));
6461: } elsif ($command eq 'scantronupload' &&
6462: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
6463: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
6464: $request->print(&scantron_upload_scantron_data($request));
6465: } elsif ($command eq 'scantronupload_save' &&
6466: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
6467: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
6468: $request->print(&scantron_upload_scantron_data_save($request));
6469: } elsif ($command eq 'scantron_download' &&
6470: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
6471: $request->print(&scantron_download_scantron_data($request));
6472: } elsif ($command) {
6473: $request->print("Access Denied ($command)");
6474: }
6475: }
6476: $request->print(&Apache::loncommon::end_page());
6477: return '';
6478: }
6479:
6480: 1;
6481:
6482: __END__;
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>