1: # The LearningOnline Network with CAPA
2: # The LON-CAPA Grading handler
3: #
4: # $Id: grades.pm,v 1.629 2010/04/21 20:22:19 www 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:
30:
31: package Apache::grades;
32: use strict;
33: use Apache::style;
34: use Apache::lonxml;
35: use Apache::lonnet;
36: use Apache::loncommon;
37: use Apache::lonhtmlcommon;
38: use Apache::lonnavmaps;
39: use Apache::lonhomework;
40: use Apache::lonpickcode;
41: use Apache::loncoursedata;
42: use Apache::lonmsg();
43: use Apache::Constants qw(:common);
44: use Apache::lonlocal;
45: use Apache::lonenc;
46: use Apache::lonstathelpers;
47: use String::Similarity;
48: use LONCAPA;
49:
50: use POSIX qw(floor);
51:
52:
53:
54: my %perm=();
55:
56: # These variables are used to recover from ssi errors
57:
58: my $ssi_retries = 5;
59: my $ssi_error;
60: my $ssi_error_resource;
61: my $ssi_error_message;
62:
63:
64: sub ssi_with_retries {
65: my ($resource, $retries, %form) = @_;
66: my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
67: if ($response->is_error) {
68: $ssi_error = 1;
69: $ssi_error_resource = $resource;
70: $ssi_error_message = $response->code . " " . $response->message;
71: }
72:
73: return $content;
74:
75: }
76: #
77: # Prodcuces an ssi retry failure error message to the user:
78: #
79:
80: sub ssi_print_error {
81: my ($r) = @_;
82: my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
83: $r->print('
84: <br />
85: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
86: <p>
87: '.&mt('Unable to retrieve a resource from a server:').'<br />
88: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
89: '.&mt('Error:').' '.$ssi_error_message.'
90: </p>
91: <p>'.
92: &mt('It is recommended that you try again later, as this error may mean the server was just temporarily unavailable, or is down for maintenance.').'<br />'.
93: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
94: '</p>');
95: return;
96: }
97:
98: #
99: # --- Retrieve the parts from the metadata file.---
100: # Returns an array of everything that the resources stores away
101: #
102:
103: sub getpartlist {
104: my ($symb,$errorref) = @_;
105:
106: my $navmap = Apache::lonnavmaps::navmap->new();
107: unless (ref($navmap)) {
108: if (ref($errorref)) {
109: $$errorref = 'navmap';
110: return;
111: }
112: }
113: my $res = $navmap->getBySymb($symb);
114: my $partlist = $res->parts();
115: my $url = $res->src();
116: my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
117:
118: my @stores;
119: foreach my $part (@{ $partlist }) {
120: foreach my $key (@metakeys) {
121: if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
122: }
123: }
124: return @stores;
125: }
126:
127: #--- Format fullname, username:domain if different for display
128: #--- Use anywhere where the student names are listed
129: sub nameUserString {
130: my ($type,$fullname,$uname,$udom) = @_;
131: if ($type eq 'header') {
132: return '<b> '.&mt('Fullname').' </b><span class="LC_internal_info">('.&mt('Username').')</span>';
133: } else {
134: return ' '.$fullname.'<span class="LC_internal_info"> ('.$uname.
135: ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
136: }
137: }
138:
139: #--- Get the partlist and the response type for a given problem. ---
140: #--- Indicate if a response type is coded handgraded or not. ---
141: #--- Sets response_error pointer to "1" if navmaps object broken ---
142: sub response_type {
143: my ($symb,$response_error) = @_;
144:
145: my $navmap = Apache::lonnavmaps::navmap->new();
146: unless (ref($navmap)) {
147: if (ref($response_error)) {
148: $$response_error = 1;
149: }
150: return;
151: }
152: my $res = $navmap->getBySymb($symb);
153: unless (ref($res)) {
154: $$response_error = 1;
155: return;
156: }
157: my $partlist = $res->parts();
158: my %vPart =
159: map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
160: my (%response_types,%handgrade);
161: foreach my $part (@{ $partlist }) {
162: next if (%vPart && !exists($vPart{$part}));
163:
164: my @types = $res->responseType($part);
165: my @ids = $res->responseIds($part);
166: for (my $i=0; $i < scalar(@ids); $i++) {
167: $response_types{$part}{$ids[$i]} = $types[$i];
168: $handgrade{$part.'_'.$ids[$i]} =
169: &Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
170: '.handgrade',$symb);
171: }
172: }
173: return ($partlist,\%handgrade,\%response_types);
174: }
175:
176: sub flatten_responseType {
177: my ($responseType) = @_;
178: my @part_response_id =
179: map {
180: my $part = $_;
181: map {
182: [$part,$_]
183: } sort(keys(%{ $responseType->{$part} }));
184: } sort(keys(%$responseType));
185: return @part_response_id;
186: }
187:
188: sub get_display_part {
189: my ($partID,$symb)=@_;
190: my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
191: if (defined($display) and $display ne '') {
192: $display.= ' (<span class="LC_internal_info">'
193: .&mt('Part ID: [_1]',$partID).'</span>)';
194: } else {
195: $display=$partID;
196: }
197: return $display;
198: }
199:
200: sub reset_caches {
201: &reset_analyze_cache();
202: &reset_perm();
203: }
204:
205: {
206: my %analyze_cache;
207: my %analyze_cache_formkeys;
208:
209: sub reset_analyze_cache {
210: undef(%analyze_cache);
211: undef(%analyze_cache_formkeys);
212: }
213:
214: sub get_analyze {
215: my ($symb,$uname,$udom,$no_increment,$add_to_hash)=@_;
216: my $key = "$symb\0$uname\0$udom";
217: if (exists($analyze_cache{$key})) {
218: my $getupdate = 0;
219: if (ref($add_to_hash) eq 'HASH') {
220: foreach my $item (keys(%{$add_to_hash})) {
221: if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
222: if (!exists($analyze_cache_formkeys{$key}{$item})) {
223: $getupdate = 1;
224: last;
225: }
226: } else {
227: $getupdate = 1;
228: }
229: }
230: }
231: if (!$getupdate) {
232: return $analyze_cache{$key};
233: }
234: }
235:
236: my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
237: $url=&Apache::lonnet::clutter($url);
238: my %form = ('grade_target' => 'analyze',
239: 'grade_domain' => $udom,
240: 'grade_symb' => $symb,
241: 'grade_courseid' => $env{'request.course.id'},
242: 'grade_username' => $uname,
243: 'grade_noincrement' => $no_increment);
244: if (ref($add_to_hash)) {
245: %form = (%form,%{$add_to_hash});
246: }
247: my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
248: (undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
249: my %analyze=&Apache::lonnet::str2hash($subresult);
250: if (ref($add_to_hash) eq 'HASH') {
251: $analyze_cache_formkeys{$key} = $add_to_hash;
252: } else {
253: $analyze_cache_formkeys{$key} = {};
254: }
255: return $analyze_cache{$key} = \%analyze;
256: }
257:
258: sub get_order {
259: my ($partid,$respid,$symb,$uname,$udom,$no_increment)=@_;
260: my $analyze = &get_analyze($symb,$uname,$udom,$no_increment);
261: return $analyze->{"$partid.$respid.shown"};
262: }
263:
264: sub get_radiobutton_correct_foil {
265: my ($partid,$respid,$symb,$uname,$udom)=@_;
266: my $analyze = &get_analyze($symb,$uname,$udom);
267: my $foils = &get_order($partid,$respid,$symb,$uname,$udom);
268: if (ref($foils) eq 'ARRAY') {
269: foreach my $foil (@{$foils}) {
270: if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
271: return $foil;
272: }
273: }
274: }
275: }
276:
277: sub scantron_partids_tograde {
278: my ($resource,$cid,$uname,$udom,$check_for_randomlist) = @_;
279: my (%analysis,@parts);
280: if (ref($resource)) {
281: my $symb = $resource->symb();
282: my $add_to_form;
283: if ($check_for_randomlist) {
284: $add_to_form = { 'check_parts_withrandomlist' => 1,};
285: }
286: my $analyze = &get_analyze($symb,$uname,$udom,undef,$add_to_form);
287: if (ref($analyze) eq 'HASH') {
288: %analysis = %{$analyze};
289: }
290: if (ref($analysis{'parts'}) eq 'ARRAY') {
291: foreach my $part (@{$analysis{'parts'}}) {
292: my ($id,$respid) = split(/\./,$part);
293: if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
294: push(@parts,$part);
295: }
296: }
297: }
298: }
299: return (\%analysis,\@parts);
300: }
301:
302: }
303:
304: #--- Clean response type for display
305: #--- Currently filters option/rank/radiobutton/match/essay/Task
306: # response types only.
307: sub cleanRecord {
308: my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
309: $uname,$udom) = @_;
310: my $grayFont = '<span class="LC_internal_info">';
311: if ($response =~ /^(option|rank)$/) {
312: my %answer=&Apache::lonnet::str2hash($answer);
313: my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
314: my ($toprow,$bottomrow);
315: foreach my $foil (@$order) {
316: if ($grading{$foil} == 1) {
317: $toprow.='<td><b>'.$answer{$foil}.' </b></td>';
318: } else {
319: $toprow.='<td><i>'.$answer{$foil}.' </i></td>';
320: }
321: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
322: }
323: return '<blockquote><table border="1">'.
324: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
325: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
326: $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
327: } elsif ($response eq 'match') {
328: my %answer=&Apache::lonnet::str2hash($answer);
329: my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
330: my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
331: my ($toprow,$middlerow,$bottomrow);
332: foreach my $foil (@$order) {
333: my $item=shift(@items);
334: if ($grading{$foil} == 1) {
335: $toprow.='<td><b>'.$item.' </b></td>';
336: $middlerow.='<td><b>'.$grayFont.$answer{$foil}.' </span></b></td>';
337: } else {
338: $toprow.='<td><i>'.$item.' </i></td>';
339: $middlerow.='<td><i>'.$grayFont.$answer{$foil}.' </span></i></td>';
340: }
341: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
342: }
343: return '<blockquote><table border="1">'.
344: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
345: '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
346: $middlerow.'</tr>'.
347: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
348: $bottomrow.'</tr>'.'</table></blockquote>';
349: } elsif ($response eq 'radiobutton') {
350: my %answer=&Apache::lonnet::str2hash($answer);
351: my ($toprow,$bottomrow);
352: my $correct =
353: &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
354: foreach my $foil (@$order) {
355: if (exists($answer{$foil})) {
356: if ($foil eq $correct) {
357: $toprow.='<td><b>'.&mt('true').'</b></td>';
358: } else {
359: $toprow.='<td><i>'.&mt('true').'</i></td>';
360: }
361: } else {
362: $toprow.='<td>'.&mt('false').'</td>';
363: }
364: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
365: }
366: return '<blockquote><table border="1">'.
367: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
368: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
369: $bottomrow.'</tr>'.'</table></blockquote>';
370: } elsif ($response eq 'essay') {
371: if (! exists ($env{'form.'.$symb})) {
372: my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
373: $env{'course.'.$env{'request.course.id'}.'.domain'},
374: $env{'course.'.$env{'request.course.id'}.'.num'});
375:
376: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
377: $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
378: $env{'form.kwclr'} = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
379: $env{'form.kwsize'} = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
380: $env{'form.kwstyle'} = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
381: $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
382: }
383: $answer =~ s-\n-<br />-g;
384: return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
385: } elsif ( $response eq 'organic') {
386: my $result='Smile representation: "<tt>'.$answer.'</tt>"';
387: my $jme=$record->{$version."resource.$partid.$respid.molecule"};
388: $result.=&Apache::chemresponse::jme_img($jme,$answer,400);
389: return $result;
390: } elsif ( $response eq 'Task') {
391: if ( $answer eq 'SUBMITTED') {
392: my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
393: my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
394: return $result;
395: } elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
396: my @matches = grep(/^\Q$version\E.*?\.instance$/,
397: keys(%{$record}));
398: return join('<br />',($version,@matches));
399:
400:
401: } else {
402: my $result =
403: '<p>'
404: .&mt('Overall result: [_1]',
405: $record->{$version."resource.$respid.$partid.status"})
406: .'</p>';
407:
408: $result .= '<ul>';
409: my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
410: keys(%{$record}));
411: foreach my $grade (sort(@grade)) {
412: my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
413: $result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
414: $dim, $record->{$grade}).
415: '</li>';
416: }
417: $result.='</ul>';
418: return $result;
419: }
420: } elsif ( $response =~ m/(?:numerical|formula)/) {
421: $answer =
422: &Apache::loncommon::format_previous_attempt_value('submission',
423: $answer);
424: }
425: return $answer;
426: }
427:
428: #-- A couple of common js functions
429: sub commonJSfunctions {
430: my $request = shift;
431: $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
432: function radioSelection(radioButton) {
433: var selection=null;
434: if (radioButton.length > 1) {
435: for (var i=0; i<radioButton.length; i++) {
436: if (radioButton[i].checked) {
437: return radioButton[i].value;
438: }
439: }
440: } else {
441: if (radioButton.checked) return radioButton.value;
442: }
443: return selection;
444: }
445:
446: function pullDownSelection(selectOne) {
447: var selection="";
448: if (selectOne.length > 1) {
449: for (var i=0; i<selectOne.length; i++) {
450: if (selectOne[i].selected) {
451: return selectOne[i].value;
452: }
453: }
454: } else {
455: // only one value it must be the selected one
456: return selectOne.value;
457: }
458: }
459: COMMONJSFUNCTIONS
460: }
461:
462: #--- Dumps the class list with usernames,list of sections,
463: #--- section, ids and fullnames for each user.
464: sub getclasslist {
465: my ($getsec,$filterlist,$getgroup) = @_;
466: my @getsec;
467: my @getgroup;
468: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
469: if (!ref($getsec)) {
470: if ($getsec ne '' && $getsec ne 'all') {
471: @getsec=($getsec);
472: }
473: } else {
474: @getsec=@{$getsec};
475: }
476: if (grep(/^all$/,@getsec)) { undef(@getsec); }
477: if (!ref($getgroup)) {
478: if ($getgroup ne '' && $getgroup ne 'all') {
479: @getgroup=($getgroup);
480: }
481: } else {
482: @getgroup=@{$getgroup};
483: }
484: if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
485:
486: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
487: # Bail out if we were unable to get the classlist
488: return if (! defined($classlist));
489: &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
490: #
491: my %sections;
492: my %fullnames;
493: foreach my $student (keys(%$classlist)) {
494: my $end =
495: $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
496: my $start =
497: $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
498: my $id =
499: $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
500: my $section =
501: $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
502: my $fullname =
503: $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
504: my $status =
505: $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
506: my $group =
507: $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
508: # filter students according to status selected
509: if ($filterlist && (!($stu_status =~ /Any/))) {
510: if (!($stu_status =~ $status)) {
511: delete($classlist->{$student});
512: next;
513: }
514: }
515: # filter students according to groups selected
516: my @stu_groups = split(/,/,$group);
517: if (@getgroup) {
518: my $exclude = 1;
519: foreach my $grp (@getgroup) {
520: foreach my $stu_group (@stu_groups) {
521: if ($stu_group eq $grp) {
522: $exclude = 0;
523: }
524: }
525: if (($grp eq 'none') && !$group) {
526: $exclude = 0;
527: }
528: }
529: if ($exclude) {
530: delete($classlist->{$student});
531: }
532: }
533: $section = ($section ne '' ? $section : 'none');
534: if (&canview($section)) {
535: if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
536: $sections{$section}++;
537: if ($classlist->{$student}) {
538: $fullnames{$student}=$fullname;
539: }
540: } else {
541: delete($classlist->{$student});
542: }
543: } else {
544: delete($classlist->{$student});
545: }
546: }
547: my %seen = ();
548: my @sections = sort(keys(%sections));
549: return ($classlist,\@sections,\%fullnames);
550: }
551:
552: sub canmodify {
553: my ($sec)=@_;
554: if ($perm{'mgr'}) {
555: if (!defined($perm{'mgr_section'})) {
556: # can modify whole class
557: return 1;
558: } else {
559: if ($sec eq $perm{'mgr_section'}) {
560: #can modify the requested section
561: return 1;
562: } else {
563: # can't modify the request section
564: return 0;
565: }
566: }
567: }
568: #can't modify
569: return 0;
570: }
571:
572: sub canview {
573: my ($sec)=@_;
574: if ($perm{'vgr'}) {
575: if (!defined($perm{'vgr_section'})) {
576: # can modify whole class
577: return 1;
578: } else {
579: if ($sec eq $perm{'vgr_section'}) {
580: #can modify the requested section
581: return 1;
582: } else {
583: # can't modify the request section
584: return 0;
585: }
586: }
587: }
588: #can't modify
589: return 0;
590: }
591:
592: #--- Retrieve the grade status of a student for all the parts
593: sub student_gradeStatus {
594: my ($symb,$udom,$uname,$partlist) = @_;
595: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
596: my %partstatus = ();
597: foreach (@$partlist) {
598: my ($status,undef) = split(/_/,$record{"resource.$_.solved"},2);
599: $status = 'nothing' if ($status eq '');
600: $partstatus{$_} = $status;
601: my $subkey = "resource.$_.submitted_by";
602: $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
603: }
604: return %partstatus;
605: }
606:
607: # hidden form and javascript that calls the form
608: # Use by verifyscript and viewgrades
609: # Shows a student's view of problem and submission
610: sub jscriptNform {
611: my ($symb) = @_;
612: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
613: my $jscript= &Apache::lonhtmlcommon::scripttag(
614: ' function viewOneStudent(user,domain) {'."\n".
615: ' document.onestudent.student.value = user;'."\n".
616: ' document.onestudent.userdom.value = domain;'."\n".
617: ' document.onestudent.submit();'."\n".
618: ' }'."\n".
619: "\n");
620: $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
621: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
622: '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
623: '<input type="hidden" name="command" value="submission" />'."\n".
624: '<input type="hidden" name="student" value="" />'."\n".
625: '<input type="hidden" name="userdom" value="" />'."\n".
626: '</form>'."\n";
627: return $jscript;
628: }
629:
630:
631:
632: # Given the score (as a number [0-1] and the weight) what is the final
633: # point value? This function will round to the nearest tenth, third,
634: # or quarter if one of those is within the tolerance of .00001.
635: sub compute_points {
636: my ($score, $weight) = @_;
637:
638: my $tolerance = .00001;
639: my $points = $score * $weight;
640:
641: # Check for nearness to 1/x.
642: my $check_for_nearness = sub {
643: my ($factor) = @_;
644: my $num = ($points * $factor) + $tolerance;
645: my $floored_num = floor($num);
646: if ($num - $floored_num < 2 * $tolerance * $factor) {
647: return $floored_num / $factor;
648: }
649: return $points;
650: };
651:
652: $points = $check_for_nearness->(10);
653: $points = $check_for_nearness->(3);
654: $points = $check_for_nearness->(4);
655:
656: return $points;
657: }
658:
659: #------------------ End of general use routines --------------------
660:
661: #
662: # Find most similar essay
663: #
664:
665: sub most_similar {
666: my ($uname,$udom,$uessay,$old_essays)=@_;
667:
668: # ignore spaces and punctuation
669:
670: $uessay=~s/\W+/ /gs;
671:
672: # ignore empty submissions (occuring when only files are sent)
673:
674: unless ($uessay=~/\w+/s) { return ''; }
675:
676: # these will be returned. Do not care if not at least 50 percent similar
677: my $limit=0.6;
678: my $sname='';
679: my $sdom='';
680: my $scrsid='';
681: my $sessay='';
682: # go through all essays ...
683: foreach my $tkey (keys(%$old_essays)) {
684: my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
685: # ... except the same student
686: next if (($tname eq $uname) && ($tdom eq $udom));
687: my $tessay=$old_essays->{$tkey};
688: $tessay=~s/\W+/ /gs;
689: # String similarity gives up if not even limit
690: my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
691: # Found one
692: if ($tsimilar>$limit) {
693: $limit=$tsimilar;
694: $sname=$tname;
695: $sdom=$tdom;
696: $scrsid=$tcrsid;
697: $sessay=$old_essays->{$tkey};
698: }
699: }
700: if ($limit>0.6) {
701: return ($sname,$sdom,$scrsid,$sessay,$limit);
702: } else {
703: return ('','','','',0);
704: }
705: }
706:
707: #-------------------------------------------------------------------
708:
709: #------------------------------------ Receipt Verification Routines
710: #
711:
712: sub initialverifyreceipt {
713: my ($request,$symb) = @_;
714: &commonJSfunctions($request);
715: return '<form name="gradingMenu"><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
716: &Apache::lonnet::recprefix($env{'request.course.id'}).
717: '-<input type="text" name="receipt" size="4" />'.
718: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
719: '<input type="hidden" name="command" value="verify" />'.
720: "</form>\n";
721: }
722:
723: #--- Check whether a receipt number is valid.---
724: sub verifyreceipt {
725: my ($request,$symb) = @_;
726:
727: my $courseid = $env{'request.course.id'};
728: my $receipt = &Apache::lonnet::recprefix($courseid).'-'.
729: $env{'form.receipt'};
730: $receipt =~ s/[^\-\d]//g;
731:
732: my $title.=
733: '<h3><span class="LC_info">'.
734: &mt('Verifying Receipt Number [_1]',$receipt).
735: '</span></h3>'."\n";
736:
737: my ($string,$contents,$matches) = ('','',0);
738: my (undef,undef,$fullname) = &getclasslist('all','0');
739:
740: my $receiptparts=0;
741: if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
742: $env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
743: my $parts=['0'];
744: if ($receiptparts) {
745: my $res_error;
746: ($parts)=&response_type($symb,\$res_error);
747: if ($res_error) {
748: return &navmap_errormsg();
749: }
750: }
751:
752: my $header =
753: &Apache::loncommon::start_data_table().
754: &Apache::loncommon::start_data_table_header_row().
755: '<th> '.&mt('Fullname').' </th>'."\n".
756: '<th> '.&mt('Username').' </th>'."\n".
757: '<th> '.&mt('Domain').' </th>';
758: if ($receiptparts) {
759: $header.='<th> '.&mt('Problem Part').' </th>';
760: }
761: $header.=
762: &Apache::loncommon::end_data_table_header_row();
763:
764: foreach (sort
765: {
766: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
767: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
768: }
769: return $a cmp $b;
770: } (keys(%$fullname))) {
771: my ($uname,$udom)=split(/\:/);
772: foreach my $part (@$parts) {
773: if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
774: $contents.=
775: &Apache::loncommon::start_data_table_row().
776: '<td> '."\n".
777: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
778: '\');" target="_self">'.$$fullname{$_}.'</a> </td>'."\n".
779: '<td> '.$uname.' </td>'.
780: '<td> '.$udom.' </td>';
781: if ($receiptparts) {
782: $contents.='<td> '.$part.' </td>';
783: }
784: $contents.=
785: &Apache::loncommon::end_data_table_row()."\n";
786:
787: $matches++;
788: }
789: }
790: }
791: if ($matches == 0) {
792: $string = $title
793: .'<p class="LC_warning">'
794: .&mt('No match found for the above receipt number.')
795: .'</p>';
796: } else {
797: $string = &jscriptNform($symb).$title.
798: '<p>'.
799: &mt('The above receipt number matches the following [quant,_1,student].',$matches).
800: '</p>'.
801: $header.
802: $contents.
803: &Apache::loncommon::end_data_table()."\n";
804: }
805: return $string;
806: }
807:
808: #--- This is called by a number of programs.
809: #--- Called from the Grading Menu - View/Grade an individual student
810: #--- Also called directly when one clicks on the subm button
811: # on the problem page.
812: sub listStudents {
813: my ($request,$symb,$submitonly) = @_;
814:
815: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
816: my $cnum = $env{"course.$env{'request.course.id'}.num"};
817: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
818: my $getgroup = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
819: unless ($submitonly) {
820: $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
821: }
822:
823: my $result='<h3><span class="LC_info"> '
824: .&mt("View/Grade/Regrade Submissions for a Student or a Group of Students")
825: .'</span></h3>';
826: my $res_error;
827: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
828:
829: my %lt = &Apache::lonlocal::texthash (
830: 'multiple' => 'Please select a student or group of students before clicking on the Next button.',
831: 'single' => 'Please select the student before clicking on the Next button.',
832: );
833: $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
834: function checkSelect(checkBox) {
835: var ctr=0;
836: var sense="";
837: if (checkBox.length > 1) {
838: for (var i=0; i<checkBox.length; i++) {
839: if (checkBox[i].checked) {
840: ctr++;
841: }
842: }
843: sense = '$lt{'multiple'}';
844: } else {
845: if (checkBox.checked) {
846: ctr = 1;
847: }
848: sense = '$lt{'single'}';
849: }
850: if (ctr == 0) {
851: alert(sense);
852: return false;
853: }
854: document.gradesub.submit();
855: }
856:
857: function reLoadList(formname) {
858: if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
859: formname.command.value = 'submission';
860: formname.submit();
861: }
862: LISTJAVASCRIPT
863:
864: &commonJSfunctions($request);
865: $request->print($result);
866:
867: my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
868: "\n";
869:
870: $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
871: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
872: .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
873: .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
874: .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
875: .&Apache::lonhtmlcommon::row_closure();
876: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
877: .'<label><input type="radio" name="vAns" value="no" /> '.&mt('no').' </label>'."\n"
878: .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
879: .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
880: .&Apache::lonhtmlcommon::row_closure();
881:
882: my $submission_options;
883: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
884: my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
885: $env{'form.Status'} = $saveStatus;
886: $submission_options.=
887: '<span class="LC_nobreak">'.
888: '<label><input type="radio" name="lastSub" value="lastonly" /> '.
889: &mt('last submission only').' </label></span>'."\n".
890: '<span class="LC_nobreak">'.
891: '<label><input type="radio" name="lastSub" value="last" /> '.
892: &mt('last submission & parts info').' </label></span>'."\n".
893: '<span class="LC_nobreak">'.
894: '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
895: &mt('by dates and submissions').'</label></span>'."\n".
896: '<span class="LC_nobreak">'.
897: '<label><input type="radio" name="lastSub" value="all" /> '.
898: &mt('all details').'</label></span>';
899: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
900: .$submission_options
901: .&Apache::lonhtmlcommon::row_closure();
902:
903: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
904: .'<select name="increment">'
905: .'<option value="1">'.&mt('Whole Points').'</option>'
906: .'<option value=".5">'.&mt('Half Points').'</option>'
907: .'<option value=".25">'.&mt('Quarter Points').'</option>'
908: .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
909: .'</select>'
910: .&Apache::lonhtmlcommon::row_closure();
911:
912: $gradeTable .=
913: &build_section_inputs().
914: '<input type="hidden" name="submitonly" value="'.$submitonly.'" />'."\n".
915: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
916: '<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
917:
918: if (exists($env{'form.Status'})) {
919: $gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
920: } else {
921: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
922: .&Apache::lonhtmlcommon::StatusOptions(
923: $saveStatus,undef,1,'javascript:reLoadList(this.form);')
924: .&Apache::lonhtmlcommon::row_closure();
925: }
926:
927: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
928: .'<input type="checkbox" name="checkPlag" checked="checked" />'
929: .&Apache::lonhtmlcommon::row_closure(1)
930: .&Apache::lonhtmlcommon::end_pick_box();
931:
932: $gradeTable .= '<p>'
933: .&mt("To view/grade/regrade a submission or a group of submissions, click on the check box(es) next to the student's name(s). Then click on the Next button.")."\n"
934: .'<input type="hidden" name="command" value="processGroup" />'
935: .'</p>';
936:
937: # checkall buttons
938: $gradeTable.=&check_script('gradesub', 'stuinfo');
939: $gradeTable.='<input type="button" '."\n".
940: 'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
941: 'value="'.&mt('Next').' →" /> <br />'."\n";
942: $gradeTable.=&check_buttons();
943: my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
944: $gradeTable.= &Apache::loncommon::start_data_table().
945: &Apache::loncommon::start_data_table_header_row();
946: my $loop = 0;
947: while ($loop < 2) {
948: $gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
949: '<th>'.&nameUserString('header').' '.&mt('Section/Group').'</th>';
950: if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
951: foreach my $part (sort(@$partlist)) {
952: my $display_part=
953: &get_display_part((split(/_/,$part))[0],$symb);
954: $gradeTable.=
955: '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
956: }
957: } elsif ($submitonly eq 'queued') {
958: $gradeTable.='<th>'.&mt('Queue Status').' </th>';
959: }
960: $loop++;
961: # $gradeTable.='<td></td>' if ($loop%2 ==1);
962: }
963: $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
964:
965: my $ctr = 0;
966: foreach my $student (sort
967: {
968: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
969: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
970: }
971: return $a cmp $b;
972: }
973: (keys(%$fullname))) {
974: my ($uname,$udom) = split(/:/,$student);
975:
976: my %status = ();
977:
978: if ($submitonly eq 'queued') {
979: my %queue_status =
980: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
981: $udom,$uname);
982: next if (!defined($queue_status{'gradingqueue'}));
983: $status{'gradingqueue'} = $queue_status{'gradingqueue'};
984: }
985:
986: if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
987: (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
988: my $submitted = 0;
989: my $graded = 0;
990: my $incorrect = 0;
991: foreach (keys(%status)) {
992: $submitted = 1 if ($status{$_} ne 'nothing');
993: $graded = 1 if ($status{$_} =~ /^ungraded/);
994: $incorrect = 1 if ($status{$_} =~ /^incorrect/);
995:
996: my ($foo,$partid,$foo1) = split(/\./,$_);
997: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
998: $submitted = 0;
999: my ($part)=split(/\./,$partid);
1000: $gradeTable.='<input type="hidden" name="'.
1001: $student.':'.$part.':submitted_by" value="'.
1002: $status{'resource.'.$partid.'.submitted_by'}.'" />';
1003: }
1004: }
1005:
1006: next if (!$submitted && ($submitonly eq 'yes' ||
1007: $submitonly eq 'incorrect' ||
1008: $submitonly eq 'graded'));
1009: next if (!$graded && ($submitonly eq 'graded'));
1010: next if (!$incorrect && $submitonly eq 'incorrect');
1011: }
1012:
1013: $ctr++;
1014: my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1015: my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1016: if ( $perm{'vgr'} eq 'F' ) {
1017: if ($ctr%2 ==1) {
1018: $gradeTable.= &Apache::loncommon::start_data_table_row();
1019: }
1020: $gradeTable.='<td align="right">'.$ctr.' </td>'.
1021: '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1022: $student.':'.$$fullname{$student}.':::SECTION'.$section.
1023: ') " /> </label></td>'."\n".'<td>'.
1024: &nameUserString(undef,$$fullname{$student},$uname,$udom).
1025: ' '.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1026:
1027: if ($submitonly ne 'all') {
1028: foreach (sort(keys(%status))) {
1029: next if ($_ =~ /^resource.*?submitted_by$/);
1030: $gradeTable.='<td align="center"> '.&mt($status{$_}).' </td>'."\n";
1031: }
1032: }
1033: # $gradeTable.='<td></td>' if ($ctr%2 ==1);
1034: if ($ctr%2 ==0) {
1035: $gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
1036: }
1037: }
1038: }
1039: if ($ctr%2 ==1) {
1040: $gradeTable.='<td> </td><td> </td><td> </td>';
1041: if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1042: foreach (@$partlist) {
1043: $gradeTable.='<td> </td>';
1044: }
1045: } elsif ($submitonly eq 'queued') {
1046: $gradeTable.='<td> </td>';
1047: }
1048: $gradeTable.=&Apache::loncommon::end_data_table_row();
1049: }
1050:
1051: $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1052: '<input type="button" '.
1053: 'onclick="javascript:checkSelect(this.form.stuinfo);" '.
1054: 'value="'.&mt('Next').' →" /></form>'."\n";
1055: if ($ctr == 0) {
1056: my $num_students=(scalar(keys(%$fullname)));
1057: if ($num_students eq 0) {
1058: $gradeTable='<br /> <span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1059: } else {
1060: my $submissions='submissions';
1061: if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
1062: if ($submitonly eq 'graded' ) { $submissions = 'ungraded submissions'; }
1063: if ($submitonly eq 'queued' ) { $submissions = 'queued submissions'; }
1064: $gradeTable='<br /> <span class="LC_warning">'.
1065: &mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
1066: $num_students).
1067: '</span><br />';
1068: }
1069: } elsif ($ctr == 1) {
1070: $gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1071: }
1072: $request->print($gradeTable);
1073: return '';
1074: }
1075:
1076: #---- Called from the listStudents routine
1077:
1078: sub check_script {
1079: my ($form, $type)=@_;
1080: my $chkallscript= &Apache::lonhtmlcommon::scripttag('
1081: function checkall() {
1082: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1083: ele = document.forms.'.$form.'.elements[i];
1084: if (ele.name == "'.$type.'") {
1085: document.forms.'.$form.'.elements[i].checked=true;
1086: }
1087: }
1088: }
1089:
1090: function checksec() {
1091: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1092: ele = document.forms.'.$form.'.elements[i];
1093: string = document.forms.'.$form.'.chksec.value;
1094: if
1095: (ele.value.indexOf(":::SECTION"+string)>0) {
1096: document.forms.'.$form.'.elements[i].checked=true;
1097: }
1098: }
1099: }
1100:
1101:
1102: function uncheckall() {
1103: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1104: ele = document.forms.'.$form.'.elements[i];
1105: if (ele.name == "'.$type.'") {
1106: document.forms.'.$form.'.elements[i].checked=false;
1107: }
1108: }
1109: }
1110:
1111: '."\n");
1112: return $chkallscript;
1113: }
1114:
1115: sub check_buttons {
1116: my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
1117: $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" /> ';
1118: $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1119: $buttons.='<input type="text" size="5" name="chksec" /> ';
1120: return $buttons;
1121: }
1122:
1123: # Displays the submissions for one student or a group of students
1124: sub processGroup {
1125: my ($request,$symb) = @_;
1126: my $ctr = 0;
1127: my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1128: my $total = scalar(@stuchecked)-1;
1129:
1130: foreach my $student (@stuchecked) {
1131: my ($uname,$udom,$fullname) = split(/:/,$student);
1132: $env{'form.student'} = $uname;
1133: $env{'form.userdom'} = $udom;
1134: $env{'form.fullname'} = $fullname;
1135: &submission($request,$ctr,$total,$symb);
1136: $ctr++;
1137: }
1138: return '';
1139: }
1140:
1141: #------------------------------------------------------------------------------------
1142: #
1143: #-------------------------- Next few routines handles grading by student, essentially
1144: # handles essay response type problem/part
1145: #
1146: #--- Javascript to handle the submission page functionality ---
1147: sub sub_page_js {
1148: my $request = shift;
1149: my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1150: $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1151: function updateRadio(formname,id,weight) {
1152: var gradeBox = formname["GD_BOX"+id];
1153: var radioButton = formname["RADVAL"+id];
1154: var oldpts = formname["oldpts"+id].value;
1155: var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1156: gradeBox.value = pts;
1157: var resetbox = false;
1158: if (isNaN(pts) || pts < 0) {
1159: alert("$alertmsg"+pts);
1160: for (var i=0; i<radioButton.length; i++) {
1161: if (radioButton[i].checked) {
1162: gradeBox.value = i;
1163: resetbox = true;
1164: }
1165: }
1166: if (!resetbox) {
1167: formtextbox.value = "";
1168: }
1169: return;
1170: }
1171:
1172: if (pts > weight) {
1173: var resp = confirm("You entered a value ("+pts+
1174: ") greater than the weight for the part. Accept?");
1175: if (resp == false) {
1176: gradeBox.value = oldpts;
1177: return;
1178: }
1179: }
1180:
1181: for (var i=0; i<radioButton.length; i++) {
1182: radioButton[i].checked=false;
1183: if (pts == i && pts != "") {
1184: radioButton[i].checked=true;
1185: }
1186: }
1187: updateSelect(formname,id);
1188: formname["stores"+id].value = "0";
1189: }
1190:
1191: function writeBox(formname,id,pts) {
1192: var gradeBox = formname["GD_BOX"+id];
1193: if (checkSolved(formname,id) == 'update') {
1194: gradeBox.value = pts;
1195: } else {
1196: var oldpts = formname["oldpts"+id].value;
1197: gradeBox.value = oldpts;
1198: var radioButton = formname["RADVAL"+id];
1199: for (var i=0; i<radioButton.length; i++) {
1200: radioButton[i].checked=false;
1201: if (i == oldpts) {
1202: radioButton[i].checked=true;
1203: }
1204: }
1205: }
1206: formname["stores"+id].value = "0";
1207: updateSelect(formname,id);
1208: return;
1209: }
1210:
1211: function clearRadBox(formname,id) {
1212: if (checkSolved(formname,id) == 'noupdate') {
1213: updateSelect(formname,id);
1214: return;
1215: }
1216: gradeSelect = formname["GD_SEL"+id];
1217: for (var i=0; i<gradeSelect.length; i++) {
1218: if (gradeSelect[i].selected) {
1219: var selectx=i;
1220: }
1221: }
1222: var stores = formname["stores"+id];
1223: if (selectx == stores.value) { return };
1224: var gradeBox = formname["GD_BOX"+id];
1225: gradeBox.value = "";
1226: var radioButton = formname["RADVAL"+id];
1227: for (var i=0; i<radioButton.length; i++) {
1228: radioButton[i].checked=false;
1229: }
1230: stores.value = selectx;
1231: }
1232:
1233: function checkSolved(formname,id) {
1234: if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1235: var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
1236: if (!reply) {return "noupdate";}
1237: formname.overRideScore.value = 'yes';
1238: }
1239: return "update";
1240: }
1241:
1242: function updateSelect(formname,id) {
1243: formname["GD_SEL"+id][0].selected = true;
1244: return;
1245: }
1246:
1247: //=========== Check that a point is assigned for all the parts ============
1248: function checksubmit(formname,val,total,parttot) {
1249: formname.gradeOpt.value = val;
1250: if (val == "Save & Next") {
1251: for (i=0;i<=total;i++) {
1252: for (j=0;j<parttot;j++) {
1253: var partid = formname["partid"+i+"_"+j].value;
1254: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1255: var points = formname["GD_BOX"+i+"_"+partid].value;
1256: if (points == "") {
1257: var name = formname["name"+i].value;
1258: var studentID = (name != '' ? name : formname["unamedom"+i].value);
1259: var resp = confirm("You did not assign a score for "+studentID+
1260: ", part "+partid+". Continue?");
1261: if (resp == false) {
1262: formname["GD_BOX"+i+"_"+partid].focus();
1263: return false;
1264: }
1265: }
1266: }
1267:
1268: }
1269: }
1270:
1271: }
1272: if (val == "Grade Student") {
1273: if (formname.Status.value == "") {
1274: formname.Status.value = "Active";
1275: }
1276: formname.studentNo.value = total;
1277: }
1278: formname.submit();
1279: }
1280:
1281: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
1282: function checkSubmitPage(formname,total) {
1283: noscore = new Array(100);
1284: var ptr = 0;
1285: for (i=1;i<total;i++) {
1286: var partid = formname["q_"+i].value;
1287: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1288: var points = formname["GD_BOX"+i+"_"+partid].value;
1289: var status = formname["solved"+i+"_"+partid].value;
1290: if (points == "" && status != "correct_by_student") {
1291: noscore[ptr] = i;
1292: ptr++;
1293: }
1294: }
1295: }
1296: if (ptr != 0) {
1297: var sense = ptr == 1 ? ": " : "s: ";
1298: var prolist = "";
1299: if (ptr == 1) {
1300: prolist = noscore[0];
1301: } else {
1302: var i = 0;
1303: while (i < ptr-1) {
1304: prolist += noscore[i]+", ";
1305: i++;
1306: }
1307: prolist += "and "+noscore[i];
1308: }
1309: var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
1310: if (resp == false) {
1311: return false;
1312: }
1313: }
1314:
1315: formname.submit();
1316: }
1317: SUBJAVASCRIPT
1318: }
1319:
1320: #--- javascript for essay type problem --
1321: sub sub_page_kw_js {
1322: my $request = shift;
1323: my $iconpath = $request->dir_config('lonIconsURL');
1324: &commonJSfunctions($request);
1325:
1326: my $inner_js_msg_central= (<<INNERJS);
1327: <script type="text/javascript">
1328: function checkInput() {
1329: opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
1330: var nmsg = opener.document.SCORE.savemsgN.value;
1331: var usrctr = document.msgcenter.usrctr.value;
1332: var newval = opener.document.SCORE["newmsg"+usrctr];
1333: newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
1334:
1335: var msgchk = "";
1336: if (document.msgcenter.subchk.checked) {
1337: msgchk = "msgsub,";
1338: }
1339: var includemsg = 0;
1340: for (var i=1; i<=nmsg; i++) {
1341: var opnmsg = opener.document.SCORE["savemsg"+i];
1342: var frmmsg = document.msgcenter["msg"+i];
1343: opnmsg.value = opener.checkEntities(frmmsg.value);
1344: var showflg = opener.document.SCORE["shownOnce"+i];
1345: showflg.value = "1";
1346: var chkbox = document.msgcenter["msgn"+i];
1347: if (chkbox.checked) {
1348: msgchk += "savemsg"+i+",";
1349: includemsg = 1;
1350: }
1351: }
1352: if (document.msgcenter.newmsgchk.checked) {
1353: msgchk += "newmsg"+usrctr;
1354: includemsg = 1;
1355: }
1356: imgformname = opener.document.SCORE["mailicon"+usrctr];
1357: imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
1358: var includemsg = opener.document.SCORE["includemsg"+usrctr];
1359: includemsg.value = msgchk;
1360:
1361: self.close()
1362:
1363: }
1364: </script>
1365: INNERJS
1366:
1367: my $inner_js_highlight_central= (<<INNERJS);
1368: <script type="text/javascript">
1369: function updateChoice(flag) {
1370: opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
1371: opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
1372: opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
1373: opener.document.SCORE.refresh.value = "on";
1374: if (opener.document.SCORE.keywords.value!=""){
1375: opener.document.SCORE.submit();
1376: }
1377: self.close()
1378: }
1379: </script>
1380: INNERJS
1381:
1382: my $start_page_msg_central =
1383: &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
1384: {'js_ready' => 1,
1385: 'only_body' => 1,
1386: 'bgcolor' =>'#FFFFFF',});
1387: my $end_page_msg_central =
1388: &Apache::loncommon::end_page({'js_ready' => 1});
1389:
1390:
1391: my $start_page_highlight_central =
1392: &Apache::loncommon::start_page('Highlight Central',
1393: $inner_js_highlight_central,
1394: {'js_ready' => 1,
1395: 'only_body' => 1,
1396: 'bgcolor' =>'#FFFFFF',});
1397: my $end_page_highlight_central =
1398: &Apache::loncommon::end_page({'js_ready' => 1});
1399:
1400: my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1401: $docopen=~s/^document\.//;
1402: my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
1403: $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1404:
1405: //===================== Show list of keywords ====================
1406: function keywords(formname) {
1407: var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1408: if (nret==null) return;
1409: formname.keywords.value = nret;
1410:
1411: if (formname.keywords.value != "") {
1412: formname.refresh.value = "on";
1413: formname.submit();
1414: }
1415: return;
1416: }
1417:
1418: //===================== Script to view submitted by ==================
1419: function viewSubmitter(submitter) {
1420: document.SCORE.refresh.value = "on";
1421: document.SCORE.NCT.value = "1";
1422: document.SCORE.unamedom0.value = submitter;
1423: document.SCORE.submit();
1424: return;
1425: }
1426:
1427: //===================== Script to add keyword(s) ==================
1428: function getSel() {
1429: if (document.getSelection) txt = document.getSelection();
1430: else if (document.selection) txt = document.selection.createRange().text;
1431: else return;
1432: var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
1433: if (cleantxt=="") {
1434: alert("$alertmsg");
1435: return;
1436: }
1437: var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
1438: if (nret==null) return;
1439: document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1440: if (document.SCORE.keywords.value != "") {
1441: document.SCORE.refresh.value = "on";
1442: document.SCORE.submit();
1443: }
1444: return;
1445: }
1446:
1447: //====================== Script for composing message ==============
1448: // preload images
1449: img1 = new Image();
1450: img1.src = "$iconpath/mailbkgrd.gif";
1451: img2 = new Image();
1452: img2.src = "$iconpath/mailto.gif";
1453:
1454: function msgCenter(msgform,usrctr,fullname) {
1455: var Nmsg = msgform.savemsgN.value;
1456: savedMsgHeader(Nmsg,usrctr,fullname);
1457: var subject = msgform.msgsub.value;
1458: var msgchk = document.SCORE["includemsg"+usrctr].value;
1459: re = /msgsub/;
1460: var shwsel = "";
1461: if (re.test(msgchk)) { shwsel = "checked" }
1462: subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
1463: displaySubject(checkEntities(subject),shwsel);
1464: for (var i=1; i<=Nmsg; i++) {
1465: var testmsg = "savemsg"+i+",";
1466: re = new RegExp(testmsg,"g");
1467: shwsel = "";
1468: if (re.test(msgchk)) { shwsel = "checked" }
1469: var message = document.SCORE["savemsg"+i].value;
1470: message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1471: displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
1472: //any < is already converted to <, etc. However, only once!!
1473: }
1474: newmsg = document.SCORE["newmsg"+usrctr].value;
1475: shwsel = "";
1476: re = /newmsg/;
1477: if (re.test(msgchk)) { shwsel = "checked" }
1478: newMsg(newmsg,shwsel);
1479: msgTail();
1480: return;
1481: }
1482:
1483: function checkEntities(strx) {
1484: if (strx.length == 0) return strx;
1485: var orgStr = ["&", "<", ">", '"'];
1486: var newStr = ["&", "<", ">", """];
1487: var counter = 0;
1488: while (counter < 4) {
1489: strx = strReplace(strx,orgStr[counter],newStr[counter]);
1490: counter++;
1491: }
1492: return strx;
1493: }
1494:
1495: function strReplace(strx, orgStr, newStr) {
1496: return strx.split(orgStr).join(newStr);
1497: }
1498:
1499: function savedMsgHeader(Nmsg,usrctr,fullname) {
1500: var height = 70*Nmsg+250;
1501: var scrollbar = "no";
1502: if (height > 600) {
1503: height = 600;
1504: scrollbar = "yes";
1505: }
1506: var xpos = (screen.width-600)/2;
1507: xpos = (xpos < 0) ? '0' : xpos;
1508: var ypos = (screen.height-height)/2-30;
1509: ypos = (ypos < 0) ? '0' : ypos;
1510:
1511: pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1512: pWin.focus();
1513: pDoc = pWin.document;
1514: pDoc.$docopen;
1515: pDoc.write('$start_page_msg_central');
1516:
1517: pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
1518: pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1519: pDoc.write("<h3><span class=\\"LC_info\\"> Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
1520:
1521: pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
1522: pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1523: pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
1524: }
1525: function displaySubject(msg,shwsel) {
1526: pDoc = pWin.document;
1527: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1528: pDoc.write("<td>Subject<\\/td>");
1529: pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1530: pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1531: }
1532:
1533: function displaySavedMsg(ctr,msg,shwsel) {
1534: pDoc = pWin.document;
1535: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1536: pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
1537: pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1538: pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1539: }
1540:
1541: function newMsg(newmsg,shwsel) {
1542: pDoc = pWin.document;
1543: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1544: pDoc.write("<td align=\\"center\\">New<\\/td>");
1545: pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1546: pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1547: }
1548:
1549: function msgTail() {
1550: pDoc = pWin.document;
1551: pDoc.write("<\\/table>");
1552: pDoc.write("<\\/td><\\/tr><\\/table> ");
1553: pDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:checkInput()\\"> ");
1554: pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
1555: pDoc.write("<\\/form>");
1556: pDoc.write('$end_page_msg_central');
1557: pDoc.close();
1558: }
1559:
1560: //====================== Script for keyword highlight options ==============
1561: function kwhighlight() {
1562: var kwclr = document.SCORE.kwclr.value;
1563: var kwsize = document.SCORE.kwsize.value;
1564: var kwstyle = document.SCORE.kwstyle.value;
1565: var redsel = "";
1566: var grnsel = "";
1567: var blusel = "";
1568: if (kwclr=="red") {var redsel="checked"};
1569: if (kwclr=="green") {var grnsel="checked"};
1570: if (kwclr=="blue") {var blusel="checked"};
1571: var sznsel = "";
1572: var sz1sel = "";
1573: var sz2sel = "";
1574: if (kwsize=="0") {var sznsel="checked"};
1575: if (kwsize=="+1") {var sz1sel="checked"};
1576: if (kwsize=="+2") {var sz2sel="checked"};
1577: var synsel = "";
1578: var syisel = "";
1579: var sybsel = "";
1580: if (kwstyle=="") {var synsel="checked"};
1581: if (kwstyle=="<i>") {var syisel="checked"};
1582: if (kwstyle=="<b>") {var sybsel="checked"};
1583: highlightCentral();
1584: highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
1585: highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
1586: highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
1587: highlightend();
1588: return;
1589: }
1590:
1591: function highlightCentral() {
1592: // if (window.hwdWin) window.hwdWin.close();
1593: var xpos = (screen.width-400)/2;
1594: xpos = (xpos < 0) ? '0' : xpos;
1595: var ypos = (screen.height-330)/2-30;
1596: ypos = (ypos < 0) ? '0' : ypos;
1597:
1598: hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1599: hwdWin.focus();
1600: var hDoc = hwdWin.document;
1601: hDoc.$docopen;
1602: hDoc.write('$start_page_highlight_central');
1603: hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1604: hDoc.write("<h3><span class=\\"LC_info\\"> Keyword Highlight Options<\\/span><\\/h3><br /><br />");
1605:
1606: hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
1607: hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1608: hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
1609: }
1610:
1611: function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) {
1612: var hDoc = hwdWin.document;
1613: hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1614: hDoc.write("<td align=\\"left\\">");
1615: hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+"> "+clrtxt+"<\\/td>");
1616: hDoc.write("<td align=\\"left\\">");
1617: hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+"> "+sztxt+"<\\/td>");
1618: hDoc.write("<td align=\\"left\\">");
1619: hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+"> "+sytxt+"<\\/td>");
1620: hDoc.write("<\\/tr>");
1621: }
1622:
1623: function highlightend() {
1624: var hDoc = hwdWin.document;
1625: hDoc.write("<\\/table>");
1626: hDoc.write("<\\/td><\\/tr><\\/table> ");
1627: hDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:updateChoice(1)\\"> ");
1628: hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
1629: hDoc.write("<\\/form>");
1630: hDoc.write('$end_page_highlight_central');
1631: hDoc.close();
1632: }
1633:
1634: SUBJAVASCRIPT
1635: }
1636:
1637: sub get_increment {
1638: my $increment = $env{'form.increment'};
1639: if ($increment != 1 && $increment != .5 && $increment != .25 &&
1640: $increment != .1) {
1641: $increment = 1;
1642: }
1643: return $increment;
1644: }
1645:
1646: sub gradeBox_start {
1647: return (
1648: &Apache::loncommon::start_data_table()
1649: .&Apache::loncommon::start_data_table_header_row()
1650: .'<th>'.&mt('Part').'</th>'
1651: .'<th>'.&mt('Points').'</th>'
1652: .'<th> </th>'
1653: .'<th>'.&mt('Assign Grade').'</th>'
1654: .'<th>'.&mt('Weight').'</th>'
1655: .'<th>'.&mt('Grade Status').'</th>'
1656: .&Apache::loncommon::end_data_table_header_row()
1657: );
1658: }
1659:
1660: sub gradeBox_end {
1661: return (
1662: &Apache::loncommon::end_data_table()
1663: );
1664: }
1665: #--- displays the grading box, used in essay type problem and grading by page/sequence
1666: sub gradeBox {
1667: my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1668: my $checkIcon = '<img alt="'.&mt('Check Mark').
1669: '" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1670: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1671: my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)')
1672: : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1673: $wgt = ($wgt > 0 ? $wgt : '1');
1674: my $score = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1675: '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1676: my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1677: my $display_part= &get_display_part($partid,$symb);
1678: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
1679: [$partid]);
1680: my $aggtries = $$record{'resource.'.$partid.'.tries'};
1681: if ($last_resets{$partid}) {
1682: $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
1683: }
1684: $result.=&Apache::loncommon::start_data_table_row();
1685: my $ctr = 0;
1686: my $thisweight = 0;
1687: my $increment = &get_increment();
1688:
1689: my $radio.='<table border="0"><tr>'."\n"; # display radio buttons in a nice table 10 across
1690: while ($thisweight<=$wgt) {
1691: $radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1692: 'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1693: $thisweight.')" value="'.$thisweight.'" '.
1694: ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1695: $radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1696: $thisweight += $increment;
1697: $ctr++;
1698: }
1699: $radio.='</tr></table>';
1700:
1701: my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1702: ($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1703: 'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1704: $wgt.')" /></td>'."\n";
1705: $line.='<td>/'.$wgt.' '.$wgtmsg.
1706: ($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? ' '.$checkIcon : '').
1707: ' </td>'."\n";
1708: $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1709: 'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1710: if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1711: $line.='<option></option>'.
1712: '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1713: } else {
1714: $line.='<option selected="selected"></option>'.
1715: '<option value="excused" >'.&mt('excused').'</option>';
1716: }
1717: $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
1718:
1719:
1720: $result .=
1721: '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
1722: $result.=&Apache::loncommon::end_data_table_row();
1723: $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
1724: '<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
1725: '<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1726: $$record{'resource.'.$partid.'.solved'}.'" />'."\n".
1727: '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
1728: $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
1729: '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
1730: $aggtries.'" />'."\n";
1731: my $res_error;
1732: $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1733: if ($res_error) {
1734: return &navmap_errormsg();
1735: }
1736: return $result;
1737: }
1738:
1739: sub handback_box {
1740: my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
1741: my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
1742: my (@respids);
1743: my @part_response_id = &flatten_responseType($responseType);
1744: foreach my $part_response_id (@part_response_id) {
1745: my ($part,$resp) = @{ $part_response_id };
1746: if ($part eq $partid) {
1747: push(@respids,$resp);
1748: }
1749: }
1750: my $result;
1751: foreach my $respid (@respids) {
1752: my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
1753: my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
1754: next if (!@$files);
1755: my $file_counter = 1;
1756: foreach my $file (@$files) {
1757: if ($file =~ /\/portfolio\//) {
1758: my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1759: my ($name,$version,$ext) = &file_name_version_ext($file_disp);
1760: $file_disp = "$name.$ext";
1761: $file = $file_path.$file_disp;
1762: $result.=&mt('Return commented version of [_1] to student.',
1763: '<span class="LC_filename">'.$file_disp.'</span>');
1764: $result.='<input type="file" name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1765: $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1766: $result.='('.&mt('File will be uploaded when you click on Save & Next below.').')<br />';
1767: $file_counter++;
1768: }
1769: }
1770: }
1771: return $result;
1772: }
1773:
1774: sub show_problem {
1775: my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1776: my $rendered;
1777: my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1778: &Apache::lonxml::remember_problem_counter();
1779: if ($mode eq 'both' or $mode eq 'text') {
1780: $rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1781: $env{'request.course.id'},
1782: undef,\%form);
1783: }
1784: if ($removeform) {
1785: $rendered=~s|<form(.*?)>||g;
1786: $rendered=~s|</form>||g;
1787: $rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1788: }
1789: my $companswer;
1790: if ($mode eq 'both' or $mode eq 'answer') {
1791: &Apache::lonxml::restore_problem_counter();
1792: $companswer=
1793: &Apache::loncommon::get_student_answers($symb,$uname,$udom,
1794: $env{'request.course.id'},
1795: %form);
1796: }
1797: if ($removeform) {
1798: $companswer=~s|<form(.*?)>||g;
1799: $companswer=~s|</form>||g;
1800: $companswer=~s|name="submit"|name="would_have_been_submit"|g;
1801: }
1802: $rendered=
1803: '<div class="LC_Box">'
1804: .'<h3 class="LC_hcell">'.&mt('View of the problem').'</h3>'
1805: .$rendered
1806: .'</div>';
1807: $companswer=
1808: '<div class="LC_Box">'
1809: .'<h3 class="LC_hcell">'.&mt('Correct answer').'</h3>'
1810: .$companswer
1811: .'</div>';
1812: my $result;
1813: if ($mode eq 'both') {
1814: $result=$rendered.$companswer;
1815: } elsif ($mode eq 'text') {
1816: $result=$rendered;
1817: } elsif ($mode eq 'answer') {
1818: $result=$companswer;
1819: }
1820: return $result;
1821: }
1822:
1823: sub files_exist {
1824: my ($r, $symb) = @_;
1825: my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1826:
1827: foreach my $student (@students) {
1828: my ($uname,$udom,$fullname) = split(/:/,$student);
1829: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
1830: $udom,$uname);
1831: my ($string,$timestamp)= &get_last_submission(\%record);
1832: foreach my $submission (@$string) {
1833: my ($partid,$respid) =
1834: ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1835: my $files=&get_submitted_files($udom,$uname,$partid,$respid,
1836: \%record);
1837: return 1 if (@$files);
1838: }
1839: }
1840: return 0;
1841: }
1842:
1843: sub download_all_link {
1844: my ($r,$symb) = @_;
1845: unless (&files_exist($r, $symb)) {
1846: $r->print(&mt('There are currently no submitted documents.'));
1847: return;
1848: }
1849:
1850: my $all_students =
1851: join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
1852:
1853: my $parts =
1854: join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
1855:
1856: my $identifier = &Apache::loncommon::get_cgi_id();
1857: &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
1858: 'cgi.'.$identifier.'.symb' => $symb,
1859: 'cgi.'.$identifier.'.parts' => $parts,});
1860: $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
1861: &mt('Download All Submitted Documents').'</a>');
1862: return;
1863: }
1864:
1865: sub submit_download_link {
1866: my ($request,$symb) = @_;
1867: if (!$symb) { return ''; }
1868: #FIXME: Figure out which type of problem this is and provide appropriate download
1869: &download_all_link($request,$symb);
1870: }
1871:
1872: sub build_section_inputs {
1873: my $section_inputs;
1874: if ($env{'form.section'} eq '') {
1875: $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
1876: } else {
1877: my @sections = &Apache::loncommon::get_env_multiple('form.section');
1878: foreach my $section (@sections) {
1879: $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
1880: }
1881: }
1882: return $section_inputs;
1883: }
1884:
1885: # --------------------------- show submissions of a student, option to grade
1886: sub submission {
1887: my ($request,$counter,$total,$symb) = @_;
1888: my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
1889: $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
1890: my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
1891: $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1892:
1893: my $probtitle=&Apache::lonnet::gettitle($symb);
1894: if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1895:
1896: if (!&canview($usec)) {
1897: $request->print('<span class="LC_warning">Unable to view requested student.('.
1898: $uname.':'.$udom.' in section '.$usec.' in course id '.
1899: $env{'request.course.id'}.')</span>');
1900: return;
1901: }
1902:
1903: if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
1904: if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
1905: if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
1906: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1907: my $checkIcon = '<img alt="'.&mt('Check Mark').
1908: '" src="'.$request->dir_config('lonIconsURL').
1909: '/check.gif" height="16" border="0" />';
1910:
1911: my %old_essays;
1912: # header info
1913: if ($counter == 0) {
1914: &sub_page_js($request);
1915: &sub_page_kw_js($request);
1916: $request->print('<h3> <span class="LC_info">'.&mt('Submission Record').'</span></h3>');
1917:
1918: # option to display problem, only once else it cause problems
1919: # with the form later since the problem has a form.
1920: if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1921: my $mode;
1922: if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1923: $mode='both';
1924: } elsif ($env{'form.vProb'} eq 'yes') {
1925: $mode='text';
1926: } elsif ($env{'form.vAns'} eq 'yes') {
1927: $mode='answer';
1928: }
1929: &Apache::lonxml::clear_problem_counter();
1930: $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1931: }
1932:
1933: # kwclr is the only variable that is guaranteed to be non blank
1934: # if this subroutine has been called once.
1935: my %keyhash = ();
1936: # if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1937: if (1) {
1938: %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1939: $env{'course.'.$env{'request.course.id'}.'.domain'},
1940: $env{'course.'.$env{'request.course.id'}.'.num'});
1941:
1942: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1943: $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
1944: $env{'form.kwclr'} = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
1945: $env{'form.kwsize'} = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
1946: $env{'form.kwstyle'} = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
1947: $env{'form.msgsub'} = $keyhash{$symb.'_subject'} ne '' ?
1948: $keyhash{$symb.'_subject'} : $probtitle;
1949: $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1950: }
1951: my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1952: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1953: $request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1954: '<input type="hidden" name="command" value="handgrade" />'."\n".
1955: '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
1956: '<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1957: '<input type="hidden" name="refresh" value="off" />'."\n".
1958: '<input type="hidden" name="studentNo" value="" />'."\n".
1959: '<input type="hidden" name="gradeOpt" value="" />'."\n".
1960: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1961: '<input type="hidden" name="vProb" value="'.$env{'form.vProb'}.'" />'."\n".
1962: '<input type="hidden" name="vAns" value="'.$env{'form.vAns'}.'" />'."\n".
1963: '<input type="hidden" name="lastSub" value="'.$env{'form.lastSub'}.'" />'."\n".
1964: &build_section_inputs().
1965: '<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1966: '<input type="hidden" name="NCT"'.
1967: ' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1968: # if ($env{'form.handgrade'} eq 'yes') {
1969: if (1) {
1970: $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
1971: '<input type="hidden" name="kwclr" value="'.$env{'form.kwclr'}.'" />'."\n".
1972: '<input type="hidden" name="kwsize" value="'.$env{'form.kwsize'}.'" />'."\n".
1973: '<input type="hidden" name="kwstyle" value="'.$env{'form.kwstyle'}.'" />'."\n".
1974: '<input type="hidden" name="msgsub" value="'.$env{'form.msgsub'}.'" />'."\n".
1975: '<input type="hidden" name="shownSub" value="0" />'."\n".
1976: '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1977: foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
1978: $request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
1979: }
1980: }
1981:
1982: my ($cts,$prnmsg) = (1,'');
1983: while ($cts <= $env{'form.savemsgN'}) {
1984: $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1985: (!exists($keyhash{$symb.'_savemsg'.$cts}) ?
1986: &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1987: &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1988: '" />'."\n".
1989: '<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1990: $cts++;
1991: }
1992: $request->print($prnmsg);
1993:
1994: # if ($env{'form.handgrade'} eq 'yes') {
1995: if (1) {
1996: #
1997: # Print out the keyword options line
1998: #
1999: $request->print(<<KEYWORDS);
2000: <b>Keyword Options:</b>
2001: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>
2002: <a href="#" onmousedown="javascript:getSel(); return false"
2003: CLASS="page">Paste Selection to List</a>
2004: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
2005: KEYWORDS
2006: #
2007: # Load the other essays for similarity check
2008: #
2009: my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
2010: my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
2011: $apath=&escape($apath);
2012: $apath=~s/\W/\_/gs;
2013: %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
2014: }
2015: }
2016:
2017: # This is where output for one specific student would start
2018: my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
2019: $request->print(
2020: "\n\n"
2021: .'<div class="LC_grade_show_user'.$add_class.'">'
2022: .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
2023: ."\n"
2024: );
2025:
2026: # Show additional functions if allowed
2027: if ($perm{'vgr'}) {
2028: $request->print(
2029: &Apache::loncommon::track_student_link(
2030: &mt('View recent activity'),
2031: $uname,$udom,'check')
2032: .' '
2033: );
2034: }
2035: if ($perm{'opa'}) {
2036: $request->print(
2037: &Apache::loncommon::pprmlink(
2038: &mt('Set/Change parameters'),
2039: $uname,$udom,$symb,'check'));
2040: }
2041:
2042: # Show Problem
2043: if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
2044: my $mode;
2045: if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
2046: $mode='both';
2047: } elsif ($env{'form.vProb'} eq 'all' ) {
2048: $mode='text';
2049: } elsif ($env{'form.vAns'} eq 'all') {
2050: $mode='answer';
2051: }
2052: &Apache::lonxml::clear_problem_counter();
2053: $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
2054: }
2055:
2056: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
2057: my $res_error;
2058: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
2059: if ($res_error) {
2060: $request->print(&navmap_errormsg());
2061: return;
2062: }
2063:
2064: # Display student info
2065: $request->print(($counter == 0 ? '' : '<br />'));
2066:
2067: my $result='<div class="LC_Box">'
2068: .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
2069: $result.='<input type="hidden" name="name'.$counter.
2070: '" value="'.$env{'form.fullname'}.'" />'."\n";
2071: # if ($env{'form.handgrade'} eq 'no') {
2072: if (1) {
2073: $result.='<p class="LC_info">'
2074: .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
2075: ."</p>\n";
2076: }
2077:
2078: # If any part of the problem is an essay-response (handgraded), then check for collaborators
2079: my $fullname;
2080: my $col_fullnames = [];
2081: # if ($env{'form.handgrade'} eq 'yes') {
2082: if (1) {
2083: (my $sub_result,$fullname,$col_fullnames)=
2084: &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
2085: $counter);
2086: $result.=$sub_result;
2087: }
2088: $request->print($result."\n");
2089:
2090: # print student answer/submission
2091: # Options are (1) Handgraded submission only
2092: # (2) Last submission, includes submission that is not handgraded
2093: # (for multi-response type part)
2094: # (3) Last submission plus the parts info
2095: # (4) The whole record for this student
2096: if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
2097: my ($string,$timestamp)= &get_last_submission(\%record);
2098:
2099: my $lastsubonly;
2100:
2101: if ($$timestamp eq '') {
2102: $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>';
2103: } else {
2104: $lastsubonly =
2105: '<div class="LC_grade_submissions_body">'
2106: .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
2107:
2108: my %seenparts;
2109: my @part_response_id = &flatten_responseType($responseType);
2110: foreach my $part (@part_response_id) {
2111: next if ($env{'form.lastSub'} eq 'hdgrade'
2112: && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
2113:
2114: my ($partid,$respid) = @{ $part };
2115: my $display_part=&get_display_part($partid,$symb);
2116: if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
2117: if (exists($seenparts{$partid})) { next; }
2118: $seenparts{$partid}=1;
2119: my $submitby='<b>Part:</b> '.$display_part.
2120: ' <b>Collaborative submission by:</b> '.
2121: '<a href="javascript:viewSubmitter(\''.
2122: $env{"form.$uname:$udom:$partid:submitted_by"}.
2123: '\');" target="_self">'.
2124: $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
2125: $request->print($submitby);
2126: next;
2127: }
2128: my $responsetype = $responseType->{$partid}->{$respid};
2129: if (!exists($record{"resource.$partid.$respid.submission"})) {
2130: $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
2131: '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
2132: ' <span class="LC_internal_info">'.
2133: '('.&mt('Response ID: [_1]',$respid).')'.
2134: '</span> '.
2135: '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
2136: next;
2137: }
2138: foreach my $submission (@$string) {
2139: my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
2140: if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
2141: my ($ressub,$hide,$subval) = split(/:/,$submission,3);
2142: # Similarity check
2143: my $similar='';
2144: if($env{'form.checkPlag'}){
2145: my ($oname,$odom,$ocrsid,$oessay,$osim)=
2146: &most_similar($uname,$udom,$subval,\%old_essays);
2147: if ($osim) {
2148: $osim=int($osim*100.0);
2149: my %old_course_desc =
2150: &Apache::lonnet::coursedescription($ocrsid,
2151: {'one_time' => 1});
2152:
2153: if ($hide) {
2154: $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
2155: &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
2156: } else {
2157: $similar="<hr /><h3><span class=\"LC_warning\">".
2158: &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
2159: $osim,
2160: &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
2161: $old_course_desc{'description'},
2162: $old_course_desc{'num'},
2163: $old_course_desc{'domain'}).
2164: '</span></h3><blockquote><i>'.
2165: &keywords_highlight($oessay).
2166: '</i></blockquote><hr />';
2167: }
2168: }
2169: }
2170: my $order=&get_order($partid,$respid,$symb,$uname,$udom);
2171: if ($env{'form.lastSub'} eq 'lastonly' ||
2172: ($env{'form.lastSub'} eq 'hdgrade' &&
2173: $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
2174: my $display_part=&get_display_part($partid,$symb);
2175: $lastsubonly.='<div class="LC_grade_submission_part">'.
2176: '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
2177: ' <span class="LC_internal_info">'.
2178: '('.&mt('Response ID: [_1]',$respid).')'.
2179: '</span> ';
2180: my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
2181: if (@$files) {
2182: if ($hide) {
2183: $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
2184: } else {
2185: $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
2186: foreach my $file (@$files) {
2187: &Apache::lonnet::allowuploaded('/adm/grades',$file);
2188: $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
2189: }
2190: }
2191: $lastsubonly.='<br />';
2192: }
2193: if ($hide) {
2194: $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>';
2195: } else {
2196: $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
2197: &cleanRecord($subval,$responsetype,$symb,$partid,
2198: $respid,\%record,$order,undef,$uname,$udom);
2199: }
2200: if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
2201: $lastsubonly.='</div>';
2202: }
2203: }
2204: }
2205: $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
2206: }
2207: $request->print($lastsubonly);
2208: } elsif ($env{'form.lastSub'} eq 'datesub') {
2209: my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
2210: $request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
2211: } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
2212: $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
2213: $env{'request.course.id'},
2214: $last,'.submission',
2215: 'Apache::grades::keywords_highlight'));
2216: }
2217: $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
2218: .$udom.'" />'."\n");
2219: # return if view submission with no grading option
2220: # FIXME: the logic seems off here. Why show the grade button if you cannot grade?
2221: if (!&canmodify($usec)) {
2222: my $toGrade.='<input type="button" value="Grade Student" '.
2223: 'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
2224: .$counter.'\');" target="_self" /> '."\n" if (&canmodify($usec));
2225: $toGrade.='</div>'."\n";
2226: $request->print($toGrade);
2227: return;
2228: } else {
2229: $request->print('</div>'."\n");
2230: }
2231:
2232: # essay grading message center
2233: # if ($env{'form.handgrade'} eq 'yes') {
2234: if (1) {
2235: my $result='<div class="LC_grade_message_center">';
2236:
2237: $result.='<div class="LC_grade_message_center_header">'.
2238: &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
2239: my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
2240: my $msgfor = $givenn.' '.$lastname;
2241: if (scalar(@$col_fullnames) > 0) {
2242: my $lastone = pop(@$col_fullnames);
2243: $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
2244: }
2245: $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
2246: $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
2247: '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
2248: $result.=' <a href="javascript:msgCenter(document.SCORE,'.$counter.
2249: ',\''.$msgfor.'\');" target="_self">'.
2250: &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
2251: &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
2252: '<img src="'.$request->dir_config('lonIconsURL').
2253: '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
2254: '<br /> ('.
2255: &mt('Message will be sent when you click on Save & Next below.').")\n";
2256: $result.='</div></div>';
2257: $request->print($result);
2258: }
2259:
2260: my %seen = ();
2261: my @partlist;
2262: my @gradePartRespid;
2263: my @part_response_id = &flatten_responseType($responseType);
2264: $request->print(
2265: '<div class="LC_Box">'
2266: .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
2267: );
2268: $request->print(&gradeBox_start());
2269: foreach my $part_response_id (@part_response_id) {
2270: my ($partid,$respid) = @{ $part_response_id };
2271: my $part_resp = join('_',@{ $part_response_id });
2272: next if ($seen{$partid} > 0);
2273: $seen{$partid}++;
2274: next if ($$handgrade{$part_resp} ne 'yes'
2275: && $env{'form.lastSub'} eq 'hdgrade');
2276: push(@partlist,$partid);
2277: push(@gradePartRespid,$partid.'.'.$respid);
2278: $request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
2279: }
2280: $request->print(&gradeBox_end()); # </div>
2281: $request->print('</div>');
2282:
2283: $request->print('<div class="LC_grade_info_links">');
2284: $request->print('</div>');
2285:
2286: $result='<input type="hidden" name="partlist'.$counter.
2287: '" value="'.(join ":",@partlist).'" />'."\n";
2288: $result.='<input type="hidden" name="gradePartRespid'.
2289: '" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
2290: my $ctr = 0;
2291: while ($ctr < scalar(@partlist)) {
2292: $result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
2293: $partlist[$ctr].'" />'."\n";
2294: $ctr++;
2295: }
2296: $request->print($result.''."\n");
2297:
2298: # Done with printing info for one student
2299:
2300: $request->print('</div>');#LC_grade_show_user
2301:
2302:
2303: # print end of form
2304: if ($counter == $total) {
2305: my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
2306: $endform.='<input type="button" value="'.&mt('Save & Next').'" '.
2307: 'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
2308: $total.','.scalar(@partlist).');" target="_self" /> '."\n";
2309: my $ntstu ='<select name="NTSTU">'.
2310: '<option>1</option><option>2</option>'.
2311: '<option>3</option><option>5</option>'.
2312: '<option>7</option><option>10</option></select>'."\n";
2313: my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
2314: $ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
2315: $endform.=&mt('[_1]student(s)',$ntstu);
2316: $endform.=' <input type="button" value="'.&mt('Previous').'" '.
2317: 'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> '."\n".
2318: '<input type="button" value="'.&mt('Next').'" '.
2319: 'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> ';
2320: $endform.='<span class="LC_warning">'.
2321: &mt('(Next and Previous (student) do not save the scores.)').
2322: '</span>'."\n" ;
2323: $endform.="<input type='hidden' value='".&get_increment().
2324: "' name='increment' />";
2325: $endform.='</td></tr></table></form>';
2326: $request->print($endform);
2327: }
2328: return '';
2329: }
2330:
2331: sub check_collaborators {
2332: my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
2333: my ($result,@col_fullnames);
2334: my ($classlist,undef,$fullname) = &getclasslist('all','0');
2335: foreach my $part (keys(%$handgrade)) {
2336: my $ncol = &Apache::lonnet::EXT('resource.'.$part.
2337: '.maxcollaborators',
2338: $symb,$udom,$uname);
2339: next if ($ncol <= 0);
2340: $part =~ s/\_/\./g;
2341: next if ($record->{'resource.'.$part.'.collaborators'} eq '');
2342: my (@good_collaborators, @bad_collaborators);
2343: foreach my $possible_collaborator
2344: (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) {
2345: $possible_collaborator =~ s/[\$\^\(\)]//g;
2346: next if ($possible_collaborator eq '');
2347: my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
2348: $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
2349: next if ($co_name eq $uname && $co_dom eq $udom);
2350: # Doing this grep allows 'fuzzy' specification
2351: my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i,
2352: keys(%$classlist));
2353: if (! scalar(@matches)) {
2354: push(@bad_collaborators, $possible_collaborator);
2355: } else {
2356: push(@good_collaborators, @matches);
2357: }
2358: }
2359: if (scalar(@good_collaborators) != 0) {
2360: $result.='<br />'.&mt('Collaborators: ');
2361: foreach my $name (@good_collaborators) {
2362: my ($lastname,$givenn) = split(/,/,$$fullname{$name});
2363: push(@col_fullnames, $givenn.' '.$lastname);
2364: $result.=$fullname->{$name}.' ';
2365: }
2366: $result.='<br />'."\n";
2367: my ($part)=split(/\./,$part);
2368: $result.='<input type="hidden" name="collaborator'.$counter.
2369: '" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
2370: "\n";
2371: }
2372: if (scalar(@bad_collaborators) > 0) {
2373: $result.='<div class="LC_warning">';
2374: $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
2375: $result .= '</div>';
2376: }
2377: if (scalar(@bad_collaborators > $ncol)) {
2378: $result .= '<div class="LC_warning">';
2379: $result .= &mt('This student has submitted too many '.
2380: 'collaborators. Maximum is [_1].',$ncol);
2381: $result .= '</div>';
2382: }
2383: }
2384: return ($result,$fullname,\@col_fullnames);
2385: }
2386:
2387: #--- Retrieve the last submission for all the parts
2388: sub get_last_submission {
2389: my ($returnhash)=@_;
2390: my (@string,$timestamp,%lasthidden);
2391: if ($$returnhash{'version'}) {
2392: my %lasthash=();
2393: my ($version);
2394: for ($version=1;$version<=$$returnhash{'version'};$version++) {
2395: foreach my $key (sort(split(/\:/,
2396: $$returnhash{$version.':keys'}))) {
2397: $lasthash{$key}=$$returnhash{$version.':'.$key};
2398: $timestamp =
2399: &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
2400: }
2401: }
2402: my %typeparts;
2403: my $showsurv =
2404: &Apache::lonnet::allowed('vas',$env{'request.course.id'});
2405: foreach my $key (sort(keys(%lasthash))) {
2406: if ($key =~ /\.type$/) {
2407: if (($lasthash{$key} eq 'anonsurvey') ||
2408: ($lasthash{$key} eq 'anonsurveycred')) {
2409: my ($ign,@parts) = split(/\./,$key);
2410: pop(@parts);
2411: unless ($showsurv) {
2412: my $id = join(',',@parts);
2413: $typeparts{$ign.'.'.$id} = $lasthash{$key};
2414: }
2415: delete($lasthash{$key});
2416: }
2417: }
2418: }
2419: my @hidden = keys(%typeparts);
2420: foreach my $key (keys(%lasthash)) {
2421: next if ($key !~ /\.submission$/);
2422: my $hide;
2423: if (@hidden) {
2424: foreach my $id (@hidden) {
2425: if ($key =~ /^\Q$id\E/) {
2426: $hide = 1;
2427: last;
2428: }
2429: }
2430: }
2431: my ($partid,$foo) = split(/submission$/,$key);
2432: my $draft = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
2433: '<span class="LC_warning">Draft Copy</span> ' : '';
2434: push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
2435: }
2436: }
2437: if (!@string) {
2438: $string[0] =
2439: '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
2440: }
2441: return (\@string,\$timestamp);
2442: }
2443:
2444: #--- High light keywords, with style choosen by user.
2445: sub keywords_highlight {
2446: my $string = shift;
2447: my $size = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
2448: my $styleon = $env{'form.kwstyle'} eq '' ? '' : $env{'form.kwstyle'};
2449: (my $styleoff = $styleon) =~ s/\</\<\//;
2450: my @keylist = split(/[,\s+]/,$env{'form.keywords'});
2451: foreach my $keyword (@keylist) {
2452: $string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
2453: }
2454: return $string;
2455: }
2456:
2457: #--- Called from submission routine
2458: sub processHandGrade {
2459: my ($request,$symb) = @_;
2460: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
2461: my $button = $env{'form.gradeOpt'};
2462: my $ngrade = $env{'form.NCT'};
2463: my $ntstu = $env{'form.NTSTU'};
2464: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2465: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2466:
2467: if ($button eq 'Save & Next') {
2468: my $ctr = 0;
2469: while ($ctr < $ngrade) {
2470: my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
2471: my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
2472: if ($errorflag eq 'no_score') {
2473: $ctr++;
2474: next;
2475: }
2476: if ($errorflag eq 'not_allowed') {
2477: $request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
2478: $ctr++;
2479: next;
2480: }
2481: my $includemsg = $env{'form.includemsg'.$ctr};
2482: my ($subject,$message,$msgstatus) = ('','','');
2483: my $restitle = &Apache::lonnet::gettitle($symb);
2484: my ($feedurl,$showsymb) =
2485: &get_feedurl_and_symb($symb,$uname,$udom);
2486: my $messagetail;
2487: if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
2488: $subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
2489: unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
2490: $subject.=' ['.$restitle.']';
2491: my (@msgnum) = split(/,/,$includemsg);
2492: foreach (@msgnum) {
2493: $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
2494: }
2495: $message =&Apache::lonfeedback::clear_out_html($message);
2496: if ($env{'form.withgrades'.$ctr}) {
2497: $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
2498: $messagetail = " for <a href=\"".
2499: $feedurl."?symb=$showsymb\">$restitle</a>";
2500: }
2501: $msgstatus =
2502: &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
2503: $message.$messagetail,
2504: undef,$feedurl,undef,
2505: undef,undef,$showsymb,
2506: $restitle);
2507: $request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
2508: $msgstatus);
2509: }
2510: if ($env{'form.collaborator'.$ctr}) {
2511: my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
2512: foreach my $collabstr (@collabstrs) {
2513: my ($part,@collaborators) = split(/:/,$collabstr);
2514: foreach my $collaborator (@collaborators) {
2515: my ($errorflag,$pts,$wgt) =
2516: &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
2517: $env{'form.unamedom'.$ctr},$part);
2518: if ($errorflag eq 'not_allowed') {
2519: $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
2520: next;
2521: } elsif ($message ne '') {
2522: my ($baseurl,$showsymb) =
2523: &get_feedurl_and_symb($symb,$collaborator,
2524: $udom);
2525: if ($env{'form.withgrades'.$ctr}) {
2526: $messagetail = " for <a href=\"".
2527: $baseurl."?symb=$showsymb\">$restitle</a>";
2528: }
2529: $msgstatus =
2530: &Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
2531: }
2532: }
2533: }
2534: }
2535: $ctr++;
2536: }
2537: }
2538:
2539: # if ($env{'form.handgrade'} eq 'yes') {
2540: if (1) {
2541: # Keywords sorted in alphabatical order
2542: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
2543: my %keyhash = ();
2544: $env{'form.keywords'} =~ s/,\s{0,}|\s+/ /g;
2545: $env{'form.keywords'} =~ s/^\s+|\s+$//;
2546: my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
2547: $env{'form.keywords'} = join(' ',@keywords);
2548: $keyhash{$symb.'_keywords'} = $env{'form.keywords'};
2549: $keyhash{$symb.'_subject'} = $env{'form.msgsub'};
2550: $keyhash{$loginuser.'_kwclr'} = $env{'form.kwclr'};
2551: $keyhash{$loginuser.'_kwsize'} = $env{'form.kwsize'};
2552: $keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
2553:
2554: # message center - Order of message gets changed. Blank line is eliminated.
2555: # New messages are saved in env for the next student.
2556: # All messages are saved in nohist_handgrade.db
2557: my ($ctr,$idx) = (1,1);
2558: while ($ctr <= $env{'form.savemsgN'}) {
2559: if ($env{'form.savemsg'.$ctr} ne '') {
2560: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
2561: $idx++;
2562: }
2563: $ctr++;
2564: }
2565: $ctr = 0;
2566: while ($ctr < $ngrade) {
2567: if ($env{'form.newmsg'.$ctr} ne '') {
2568: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2569: $env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2570: $idx++;
2571: }
2572: $ctr++;
2573: }
2574: $env{'form.savemsgN'} = --$idx;
2575: $keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
2576: my $putresult = &Apache::lonnet::put
2577: ('nohist_handgrade',\%keyhash,$cdom,$cnum);
2578: }
2579: # Called by Save & Refresh from Highlight Attribute Window
2580: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
2581: if ($env{'form.refresh'} eq 'on') {
2582: my ($ctr,$total) = (0,0);
2583: while ($ctr < $ngrade) {
2584: $total++ if $env{'form.unamedom'.$ctr} ne '';
2585: $ctr++;
2586: }
2587: $env{'form.NTSTU'}=$ngrade;
2588: $ctr = 0;
2589: while ($ctr < $total) {
2590: my $processUser = $env{'form.unamedom'.$ctr};
2591: ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
2592: $env{'form.fullname'} = $$fullname{$processUser};
2593: &submission($request,$ctr,$total-1,$symb);
2594: $ctr++;
2595: }
2596: return '';
2597: }
2598:
2599: # Go directly to grade student - from submission or link from chart page
2600: # FIXME: looks like reading off the button label!
2601: if ($button eq 'Grade Student') {
2602: my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
2603: ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
2604: $env{'form.fullname'} = $$fullname{$processUser};
2605: &submission($request,0,0,$symb);
2606: return '';
2607: }
2608:
2609: # Get the next/previous one or group of students
2610: my $firststu = $env{'form.unamedom0'};
2611: my $laststu = $env{'form.unamedom'.($ngrade-1)};
2612: my $ctr = 2;
2613: while ($laststu eq '') {
2614: $laststu = $env{'form.unamedom'.($ngrade-$ctr)};
2615: $ctr++;
2616: $laststu = $firststu if ($ctr > $ngrade);
2617: }
2618:
2619: my (@parsedlist,@nextlist);
2620: my ($nextflg) = 0;
2621: foreach my $item (sort
2622: {
2623: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
2624: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
2625: }
2626: return $a cmp $b;
2627: } (keys(%$fullname))) {
2628: # FIXME: this is fishy, looks like the button label
2629: if ($nextflg == 1 && $button =~ /Next$/) {
2630: push(@parsedlist,$item);
2631: }
2632: $nextflg = 1 if ($item eq $laststu);
2633: if ($button eq 'Previous') {
2634: last if ($item eq $firststu);
2635: push(@parsedlist,$item);
2636: }
2637: }
2638: $ctr = 0;
2639: # FIXME: this is fishy, looks like the button label
2640: @parsedlist = reverse @parsedlist if ($button eq 'Previous');
2641: my $res_error;
2642: my ($partlist) = &response_type($symb,\$res_error);
2643: if ($res_error) {
2644: $request->print(&navmap_errormsg());
2645: return;
2646: }
2647: foreach my $student (@parsedlist) {
2648: my $submitonly=$env{'form.submitonly'};
2649: my ($uname,$udom) = split(/:/,$student);
2650:
2651: if ($submitonly eq 'queued') {
2652: my %queue_status =
2653: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
2654: $udom,$uname);
2655: next if (!defined($queue_status{'gradingqueue'}));
2656: }
2657:
2658: if ($submitonly =~ /^(yes|graded|incorrect)$/) {
2659: # my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
2660: my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
2661: my $submitted = 0;
2662: my $ungraded = 0;
2663: my $incorrect = 0;
2664: foreach my $item (keys(%status)) {
2665: $submitted = 1 if ($status{$item} ne 'nothing');
2666: $ungraded = 1 if ($status{$item} =~ /^ungraded/);
2667: $incorrect = 1 if ($status{$item} =~ /^incorrect/);
2668: my ($foo,$partid,$foo1) = split(/\./,$item);
2669: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
2670: $submitted = 0;
2671: }
2672: }
2673: next if (!$submitted && ($submitonly eq 'yes' ||
2674: $submitonly eq 'incorrect' ||
2675: $submitonly eq 'graded'));
2676: next if (!$ungraded && ($submitonly eq 'graded'));
2677: next if (!$incorrect && $submitonly eq 'incorrect');
2678: }
2679: push(@nextlist,$student) if ($ctr < $ntstu);
2680: last if ($ctr == $ntstu);
2681: $ctr++;
2682: }
2683:
2684: $ctr = 0;
2685: my $total = scalar(@nextlist)-1;
2686:
2687: foreach (sort(@nextlist)) {
2688: my ($uname,$udom,$submitter) = split(/:/);
2689: $env{'form.student'} = $uname;
2690: $env{'form.userdom'} = $udom;
2691: $env{'form.fullname'} = $$fullname{$_};
2692: &submission($request,$ctr,$total,$symb);
2693: $ctr++;
2694: }
2695: if ($total < 0) {
2696: my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
2697: $the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
2698: $the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
2699: $request->print($the_end);
2700: }
2701: return '';
2702: }
2703:
2704: #---- Save the score and award for each student, if changed
2705: sub saveHandGrade {
2706: my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
2707: my @version_parts;
2708: my $usec = &Apache::lonnet::getsection($domain,$stuname,
2709: $env{'request.course.id'});
2710: if (!&canmodify($usec)) { return('not_allowed'); }
2711: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
2712: my @parts_graded;
2713: my %newrecord = ();
2714: my ($pts,$wgt) = ('','');
2715: my %aggregate = ();
2716: my $aggregateflag = 0;
2717: my @parts = split(/:/,$env{'form.partlist'.$newflg});
2718: foreach my $new_part (@parts) {
2719: #collaborator ($submi may vary for different parts
2720: if ($submitter && $new_part ne $part) { next; }
2721: my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
2722: if ($dropMenu eq 'excused') {
2723: if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
2724: $newrecord{'resource.'.$new_part.'.solved'} = 'excused';
2725: if (exists($record{'resource.'.$new_part.'.awarded'})) {
2726: $newrecord{'resource.'.$new_part.'.awarded'} = '';
2727: }
2728: $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
2729: }
2730: } elsif ($dropMenu eq 'reset status'
2731: && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
2732: foreach my $key (keys(%record)) {
2733: if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
2734: }
2735: $newrecord{'resource.'.$new_part.'.regrader'}=
2736: "$env{'user.name'}:$env{'user.domain'}";
2737: my $totaltries = $record{'resource.'.$part.'.tries'};
2738:
2739: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
2740: [$new_part]);
2741: my $aggtries =$totaltries;
2742: if ($last_resets{$new_part}) {
2743: $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
2744: $new_part);
2745: }
2746:
2747: my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
2748: if ($aggtries > 0) {
2749: &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
2750: $aggregateflag = 1;
2751: }
2752: } elsif ($dropMenu eq '') {
2753: $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ?
2754: $env{'form.GD_BOX'.$newflg.'_'.$new_part} :
2755: $env{'form.RADVAL'.$newflg.'_'.$new_part});
2756: if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
2757: next;
2758: }
2759: $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 :
2760: $env{'form.WGT'.$newflg.'_'.$new_part};
2761: my $partial= $pts/$wgt;
2762: if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
2763: #do not update score for part if not changed.
2764: &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
2765: next;
2766: } else {
2767: push(@parts_graded,$new_part);
2768: }
2769: if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
2770: $newrecord{'resource.'.$new_part.'.awarded'} = $partial;
2771: }
2772: my $reckey = 'resource.'.$new_part.'.solved';
2773: if ($partial == 0) {
2774: if ($record{$reckey} ne 'incorrect_by_override') {
2775: $newrecord{$reckey} = 'incorrect_by_override';
2776: }
2777: } else {
2778: if ($record{$reckey} ne 'correct_by_override') {
2779: $newrecord{$reckey} = 'correct_by_override';
2780: }
2781: }
2782: if ($submitter &&
2783: ($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
2784: $newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
2785: }
2786: $newrecord{'resource.'.$new_part.'.regrader'}=
2787: "$env{'user.name'}:$env{'user.domain'}";
2788: }
2789: # unless problem has been graded, set flag to version the submitted files
2790: unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/ ||
2791: $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
2792: $dropMenu eq 'reset status')
2793: {
2794: push(@version_parts,$new_part);
2795: }
2796: }
2797: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2798: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2799:
2800: if (%newrecord) {
2801: if (@version_parts) {
2802: my @changed_keys = &version_portfiles(\%record, \@parts_graded,
2803: $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
2804: @newrecord{@changed_keys} = @record{@changed_keys};
2805: foreach my $new_part (@version_parts) {
2806: &handback_files($request,$symb,$stuname,$domain,$newflg,
2807: $new_part,\%newrecord);
2808: }
2809: }
2810: &Apache::lonnet::cstore(\%newrecord,$symb,
2811: $env{'request.course.id'},$domain,$stuname);
2812: &check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
2813: $cdom,$cnum,$domain,$stuname);
2814: }
2815: if ($aggregateflag) {
2816: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
2817: $cdom,$cnum);
2818: }
2819: return ('',$pts,$wgt);
2820: }
2821:
2822: sub check_and_remove_from_queue {
2823: my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
2824: my @ungraded_parts;
2825: foreach my $part (@{$parts}) {
2826: if ( $record->{ 'resource.'.$part.'.awarded'} eq ''
2827: && $record->{ 'resource.'.$part.'.solved' } ne 'excused'
2828: && $newrecord->{'resource.'.$part.'.awarded'} eq ''
2829: && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
2830: ) {
2831: push(@ungraded_parts, $part);
2832: }
2833: }
2834: if ( !@ungraded_parts ) {
2835: &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
2836: $cnum,$domain,$stuname);
2837: }
2838: }
2839:
2840: sub handback_files {
2841: my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
2842: my $portfolio_root = '/userfiles/portfolio';
2843: my $res_error;
2844: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
2845: if ($res_error) {
2846: $request->print('<br />'.&navmap_errormsg().'<br />');
2847: return;
2848: }
2849: my @part_response_id = &flatten_responseType($responseType);
2850: foreach my $part_response_id (@part_response_id) {
2851: my ($part_id,$resp_id) = @{ $part_response_id };
2852: my $part_resp = join('_',@{ $part_response_id });
2853: if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
2854: # if multiple files are uploaded names will be 'returndoc2','returndoc3'
2855: my $file_counter = 1;
2856: my $file_msg;
2857: while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
2858: my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
2859: my ($directory,$answer_file) =
2860: ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
2861: my ($answer_name,$answer_ver,$answer_ext) =
2862: &file_name_version_ext($answer_file);
2863: my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
2864: my $getpropath = 1;
2865: my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
2866: my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
2867: # fix file name
2868: my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
2869: my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
2870: $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
2871: $save_file_name);
2872: if ($result !~ m|^/uploaded/|) {
2873: $request->print('<br /><span class="LC_error">'.
2874: &mt('An error occurred ([_1]) while trying to upload [_2].',
2875: $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
2876: '</span>');
2877: } else {
2878: # mark the file as read only
2879: my @files = ($save_file_name);
2880: my @what = ($symb,$env{'request.course.id'},'handback');
2881: &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
2882: if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
2883: $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
2884: }
2885: $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
2886: $file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
2887:
2888: }
2889: $request->print("<br />".$fname." will be the uploaded file name");
2890: $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
2891: $file_counter++;
2892: }
2893: my $subject = "File Handed Back by Instructor ";
2894: my $message = "A file has been returned that was originally submitted in reponse to: <br />";
2895: $message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
2896: $message .= ' The returned file(s) are named: '. $file_msg;
2897: $message .= " and can be found in your portfolio space.";
2898: my ($feedurl,$showsymb) =
2899: &get_feedurl_and_symb($symb,$domain,$stuname);
2900: my $restitle = &Apache::lonnet::gettitle($symb);
2901: my $msgstatus =
2902: &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
2903: ' (File Returned) ['.$restitle.']',$message,undef,
2904: $feedurl,undef,undef,undef,$showsymb,$restitle);
2905: }
2906: }
2907: return;
2908: }
2909:
2910: sub get_feedurl_and_symb {
2911: my ($symb,$uname,$udom) = @_;
2912: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
2913: $url = &Apache::lonnet::clutter($url);
2914: my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
2915: $symb,$udom,$uname);
2916: if ($encrypturl =~ /^yes$/i) {
2917: &Apache::lonenc::encrypted(\$url,1);
2918: &Apache::lonenc::encrypted(\$symb,1);
2919: }
2920: return ($url,$symb);
2921: }
2922:
2923: sub get_submitted_files {
2924: my ($udom,$uname,$partid,$respid,$record) = @_;
2925: my @files;
2926: if ($$record{"resource.$partid.$respid.portfiles"}) {
2927: my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
2928: foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
2929: push(@files,$file_url.$file);
2930: }
2931: }
2932: if ($$record{"resource.$partid.$respid.uploadedurl"}) {
2933: push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
2934: }
2935: return (\@files);
2936: }
2937:
2938: # ----------- Provides number of tries since last reset.
2939: sub get_num_tries {
2940: my ($record,$last_reset,$part) = @_;
2941: my $timestamp = '';
2942: my $num_tries = 0;
2943: if ($$record{'version'}) {
2944: for (my $version=$$record{'version'};$version>=1;$version--) {
2945: if (exists($$record{$version.':resource.'.$part.'.solved'})) {
2946: $timestamp = $$record{$version.':timestamp'};
2947: if ($timestamp > $last_reset) {
2948: $num_tries ++;
2949: } else {
2950: last;
2951: }
2952: }
2953: }
2954: }
2955: return $num_tries;
2956: }
2957:
2958: # ----------- Determine decrements required in aggregate totals
2959: sub decrement_aggs {
2960: my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
2961: my %decrement = (
2962: attempts => 0,
2963: users => 0,
2964: correct => 0
2965: );
2966: $decrement{'attempts'} = $aggtries;
2967: if ($solvedstatus =~ /^correct/) {
2968: $decrement{'correct'} = 1;
2969: }
2970: if ($aggtries == $totaltries) {
2971: $decrement{'users'} = 1;
2972: }
2973: foreach my $type (keys(%decrement)) {
2974: $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
2975: }
2976: return;
2977: }
2978:
2979: # ----------- Determine timestamps for last reset of aggregate totals for parts
2980: sub get_last_resets {
2981: my ($symb,$courseid,$partids) =@_;
2982: my %last_resets;
2983: my $cdom = $env{'course.'.$courseid.'.domain'};
2984: my $cname = $env{'course.'.$courseid.'.num'};
2985: my @keys;
2986: foreach my $part (@{$partids}) {
2987: push(@keys,"$symb\0$part\0resettime");
2988: }
2989: my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
2990: $cdom,$cname);
2991: foreach my $part (@{$partids}) {
2992: $last_resets{$part}=$results{"$symb\0$part\0resettime"};
2993: }
2994: return %last_resets;
2995: }
2996:
2997: # ----------- Handles creating versions for portfolio files as answers
2998: sub version_portfiles {
2999: my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
3000: my $version_parts = join('|',@$v_flag);
3001: my @returned_keys;
3002: my $parts = join('|', @$parts_graded);
3003: my $portfolio_root = '/userfiles/portfolio';
3004: foreach my $key (keys(%$record)) {
3005: my $new_portfiles;
3006: if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
3007: my @versioned_portfiles;
3008: my @portfiles = split(/\s*,\s*/,$$record{$key});
3009: foreach my $file (@portfiles) {
3010: &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
3011: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
3012: my ($answer_name,$answer_ver,$answer_ext) =
3013: &file_name_version_ext($answer_file);
3014: my $getpropath = 1;
3015: my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
3016: my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
3017: my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
3018: if ($new_answer ne 'problem getting file') {
3019: push(@versioned_portfiles, $directory.$new_answer);
3020: &Apache::lonnet::mark_as_readonly($domain,$stu_name,
3021: [$directory.$new_answer],
3022: [$symb,$env{'request.course.id'},'graded']);
3023: }
3024: }
3025: $$record{$key} = join(',',@versioned_portfiles);
3026: push(@returned_keys,$key);
3027: }
3028: }
3029: return (@returned_keys);
3030: }
3031:
3032: sub get_next_version {
3033: my ($answer_name, $answer_ext, $dir_list) = @_;
3034: my $version;
3035: foreach my $row (@$dir_list) {
3036: my ($file) = split(/\&/,$row,2);
3037: my ($file_name,$file_version,$file_ext) =
3038: &file_name_version_ext($file);
3039: if (($file_name eq $answer_name) &&
3040: ($file_ext eq $answer_ext)) {
3041: # gets here if filename and extension match, regardless of version
3042: if ($file_version ne '') {
3043: # a versioned file is found so save it for later
3044: if ($file_version > $version) {
3045: $version = $file_version;
3046: }
3047: }
3048: }
3049: }
3050: $version ++;
3051: return($version);
3052: }
3053:
3054: sub version_selected_portfile {
3055: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
3056: my ($answer_name,$answer_ver,$answer_ext) =
3057: &file_name_version_ext($file_name);
3058: my $new_answer;
3059: $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
3060: if($env{'form.copy'} eq '-1') {
3061: $new_answer = 'problem getting file';
3062: } else {
3063: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
3064: my $copy_result = &Apache::lonnet::finishuserfileupload(
3065: $stu_name,$domain,'copy',
3066: '/portfolio'.$directory.$new_answer);
3067: }
3068: return ($new_answer);
3069: }
3070:
3071: sub file_name_version_ext {
3072: my ($file)=@_;
3073: my @file_parts = split(/\./, $file);
3074: my ($name,$version,$ext);
3075: if (@file_parts > 1) {
3076: $ext=pop(@file_parts);
3077: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
3078: $version=pop(@file_parts);
3079: }
3080: $name=join('.',@file_parts);
3081: } else {
3082: $name=join('.',@file_parts);
3083: }
3084: return($name,$version,$ext);
3085: }
3086:
3087: #--------------------------------------------------------------------------------------
3088: #
3089: #-------------------------- Next few routines handles grading by section or whole class
3090: #
3091: #--- Javascript to handle grading by section or whole class
3092: sub viewgrades_js {
3093: my ($request) = shift;
3094:
3095: my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
3096: $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
3097: function writePoint(partid,weight,point) {
3098: var radioButton = document.classgrade["RADVAL_"+partid];
3099: var textbox = document.classgrade["TEXTVAL_"+partid];
3100: if (point == "textval") {
3101: point = document.classgrade["TEXTVAL_"+partid].value;
3102: if (isNaN(point) || parseFloat(point) < 0) {
3103: alert("$alertmsg"+parseFloat(point));
3104: var resetbox = false;
3105: for (var i=0; i<radioButton.length; i++) {
3106: if (radioButton[i].checked) {
3107: textbox.value = i;
3108: resetbox = true;
3109: }
3110: }
3111: if (!resetbox) {
3112: textbox.value = "";
3113: }
3114: return;
3115: }
3116: if (parseFloat(point) > parseFloat(weight)) {
3117: var resp = confirm("You entered a value ("+parseFloat(point)+
3118: ") greater than the weight for the part. Accept?");
3119: if (resp == false) {
3120: textbox.value = "";
3121: return;
3122: }
3123: }
3124: for (var i=0; i<radioButton.length; i++) {
3125: radioButton[i].checked=false;
3126: if (parseFloat(point) == i) {
3127: radioButton[i].checked=true;
3128: }
3129: }
3130:
3131: } else {
3132: textbox.value = parseFloat(point);
3133: }
3134: for (i=0;i<document.classgrade.total.value;i++) {
3135: var user = document.classgrade["ctr"+i].value;
3136: user = user.replace(new RegExp(':', 'g'),"_");
3137: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3138: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3139: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3140: if (saveval != "correct") {
3141: scorename.value = point;
3142: if (selname[0].selected != true) {
3143: selname[0].selected = true;
3144: }
3145: }
3146: }
3147: document.classgrade["SELVAL_"+partid][0].selected = true;
3148: }
3149:
3150: function writeRadText(partid,weight) {
3151: var selval = document.classgrade["SELVAL_"+partid];
3152: var radioButton = document.classgrade["RADVAL_"+partid];
3153: var override = document.classgrade["FORCE_"+partid].checked;
3154: var textbox = document.classgrade["TEXTVAL_"+partid];
3155: if (selval[1].selected || selval[2].selected) {
3156: for (var i=0; i<radioButton.length; i++) {
3157: radioButton[i].checked=false;
3158:
3159: }
3160: textbox.value = "";
3161:
3162: for (i=0;i<document.classgrade.total.value;i++) {
3163: var user = document.classgrade["ctr"+i].value;
3164: user = user.replace(new RegExp(':', 'g'),"_");
3165: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3166: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3167: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3168: if ((saveval != "correct") || override) {
3169: scorename.value = "";
3170: if (selval[1].selected) {
3171: selname[1].selected = true;
3172: } else {
3173: selname[2].selected = true;
3174: if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value))
3175: {document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
3176: }
3177: }
3178: }
3179: } else {
3180: for (i=0;i<document.classgrade.total.value;i++) {
3181: var user = document.classgrade["ctr"+i].value;
3182: user = user.replace(new RegExp(':', 'g'),"_");
3183: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3184: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3185: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3186: if ((saveval != "correct") || override) {
3187: scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
3188: selname[0].selected = true;
3189: }
3190: }
3191: }
3192: }
3193:
3194: function changeSelect(partid,user) {
3195: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
3196: var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
3197: var point = textbox.value;
3198: var weight = document.classgrade["weight_"+partid].value;
3199:
3200: if (isNaN(point) || parseFloat(point) < 0) {
3201: alert("$alertmsg"+parseFloat(point));
3202: textbox.value = "";
3203: return;
3204: }
3205: if (parseFloat(point) > parseFloat(weight)) {
3206: var resp = confirm("You entered a value ("+parseFloat(point)+
3207: ") greater than the weight of the part. Accept?");
3208: if (resp == false) {
3209: textbox.value = "";
3210: return;
3211: }
3212: }
3213: selval[0].selected = true;
3214: }
3215:
3216: function changeOneScore(partid,user) {
3217: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
3218: if (selval[1].selected || selval[2].selected) {
3219: document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
3220: if (selval[2].selected) {
3221: document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
3222: }
3223: }
3224: }
3225:
3226: function resetEntry(numpart) {
3227: for (ctpart=0;ctpart<numpart;ctpart++) {
3228: var partid = document.classgrade["partid_"+ctpart].value;
3229: var radioButton = document.classgrade["RADVAL_"+partid];
3230: var textbox = document.classgrade["TEXTVAL_"+partid];
3231: var selval = document.classgrade["SELVAL_"+partid];
3232: for (var i=0; i<radioButton.length; i++) {
3233: radioButton[i].checked=false;
3234:
3235: }
3236: textbox.value = "";
3237: selval[0].selected = true;
3238:
3239: for (i=0;i<document.classgrade.total.value;i++) {
3240: var user = document.classgrade["ctr"+i].value;
3241: user = user.replace(new RegExp(':', 'g'),"_");
3242: var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3243: resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
3244: var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
3245: resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
3246: var saveselval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3247: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3248: if (saveselval == "excused") {
3249: if (selname[1].selected == false) { selname[1].selected = true;}
3250: } else {
3251: if (selname[0].selected == false) {selname[0].selected = true};
3252: }
3253: }
3254: }
3255: }
3256:
3257: VIEWJAVASCRIPT
3258: }
3259:
3260: #--- show scores for a section or whole class w/ option to change/update a score
3261: sub viewgrades {
3262: my ($request,$symb) = @_;
3263: &viewgrades_js($request);
3264:
3265: #need to make sure we have the correct data for later EXT calls,
3266: #thus invalidate the cache
3267: &Apache::lonnet::devalidatecourseresdata(
3268: $env{'course.'.$env{'request.course.id'}.'.num'},
3269: $env{'course.'.$env{'request.course.id'}.'.domain'});
3270: &Apache::lonnet::clear_EXT_cache_status();
3271:
3272: my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
3273:
3274: #view individual student submission form - called using Javascript viewOneStudent
3275: $result.=&jscriptNform($symb);
3276:
3277: #beginning of class grading form
3278: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
3279: $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
3280: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
3281: '<input type="hidden" name="command" value="editgrades" />'."\n".
3282: &build_section_inputs().
3283: '<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
3284:
3285: my ($common_header,$specific_header);
3286: if ($env{'form.section'} eq 'all') {
3287: $common_header = &mt('Assign Common Grade to Class');
3288: $specific_header = &mt('Assign Grade to Specific Students in Class');
3289: } elsif ($env{'form.section'} eq 'none') {
3290: $common_header = &mt('Assign Common Grade to Students in no Section');
3291: $specific_header = &mt('Assign Grade to Specific Students in no Section');
3292: } else {
3293: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3294: $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
3295: $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
3296: }
3297: $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
3298: #radio buttons/text box for assigning points for a section or class.
3299: #handles different parts of a problem
3300: my $res_error;
3301: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
3302: if ($res_error) {
3303: return &navmap_errormsg();
3304: }
3305: my %weight = ();
3306: my $ctsparts = 0;
3307: my %seen = ();
3308: my @part_response_id = &flatten_responseType($responseType);
3309: foreach my $part_response_id (@part_response_id) {
3310: my ($partid,$respid) = @{ $part_response_id };
3311: my $part_resp = join('_',@{ $part_response_id });
3312: next if $seen{$partid};
3313: $seen{$partid}++;
3314: my $handgrade=$$handgrade{$part_resp};
3315: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
3316: $weight{$partid} = $wgt eq '' ? '1' : $wgt;
3317:
3318: my $display_part=&get_display_part($partid,$symb);
3319: my $radio.='<table border="0"><tr>';
3320: my $ctr = 0;
3321: while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
3322: $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
3323: 'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
3324: ','.$ctr.')" />'.$ctr."</label></td>\n";
3325: $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
3326: $ctr++;
3327: }
3328: $radio.='</tr></table>';
3329: my $line = '<input type="text" name="TEXTVAL_'.
3330: $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
3331: $partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
3332: $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
3333: $line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
3334: 'onchange="javascript:writeRadText(\''.$partid.'\','.
3335: $weight{$partid}.')"> '.
3336: '<option selected="selected"> </option>'.
3337: '<option value="excused">'.&mt('excused').'</option>'.
3338: '<option value="reset status">'.&mt('reset status').'</option>'.
3339: '</select></td>'.
3340: '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
3341: $line.='<input type="hidden" name="partid_'.
3342: $ctsparts.'" value="'.$partid.'" />'."\n";
3343: $line.='<input type="hidden" name="weight_'.
3344: $partid.'" value="'.$weight{$partid}.'" />'."\n";
3345:
3346: $result.=
3347: &Apache::loncommon::start_data_table_row()."\n".
3348: '<td><b>'.&mt('Part:').'</b></td><td>'.$display_part.'</td><td><b>'.&mt('Points:').'</b></td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>'.
3349: &Apache::loncommon::end_data_table_row()."\n";
3350: $ctsparts++;
3351: }
3352: $result.=&Apache::loncommon::end_data_table()."\n".
3353: '<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
3354: $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
3355: 'onclick="javascript:resetEntry('.$ctsparts.');" />';
3356:
3357: #table listing all the students in a section/class
3358: #header of table
3359: $result.= '<h3>'.$specific_header.'</h3>'.
3360: &Apache::loncommon::start_data_table().
3361: &Apache::loncommon::start_data_table_header_row().
3362: '<th>'.&mt('No.').'</th>'.
3363: '<th>'.&nameUserString('header')."</th>\n";
3364: my $partserror;
3365: my (@parts) = sort(&getpartlist($symb,\$partserror));
3366: if ($partserror) {
3367: return &navmap_errormsg();
3368: }
3369: my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
3370: my @partids = ();
3371: foreach my $part (@parts) {
3372: my $display=&Apache::lonnet::metadata($url,$part.'.display');
3373: my $narrowtext = &mt('Tries');
3374: $display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
3375: if (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
3376: my ($partid) = &split_part_type($part);
3377: push(@partids,$partid);
3378: #
3379: # FIXME: Looks like $display looks at English text
3380: #
3381: my $display_part=&get_display_part($partid,$symb);
3382: if ($display =~ /^Partial Credit Factor/) {
3383: $result.='<th>'.
3384: &mt('Score Part: [_1]<br /> (weight = [_2])',
3385: $display_part,$weight{$partid}).'</th>'."\n";
3386: next;
3387:
3388: } else {
3389: if ($display =~ /Problem Status/) {
3390: my $grade_status_mt = &mt('Grade Status');
3391: $display =~ s{Problem Status}{$grade_status_mt<br />};
3392: }
3393: my $part_mt = &mt('Part:');
3394: $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
3395: }
3396:
3397: $result.='<th>'.$display.'</th>'."\n";
3398: }
3399: $result.=&Apache::loncommon::end_data_table_header_row();
3400:
3401: my %last_resets =
3402: &get_last_resets($symb,$env{'request.course.id'},\@partids);
3403:
3404: #get info for each student
3405: #list all the students - with points and grade status
3406: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
3407: my $ctr = 0;
3408: foreach (sort
3409: {
3410: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
3411: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
3412: }
3413: return $a cmp $b;
3414: } (keys(%$fullname))) {
3415: $ctr++;
3416: $result.=&viewstudentgrade($symb,$env{'request.course.id'},
3417: $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
3418: }
3419: $result.=&Apache::loncommon::end_data_table();
3420: $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
3421: $result.='<input type="button" value="'.&mt('Save').'" '.
3422: 'onclick="javascript:submit();" target="_self" /></form>'."\n";
3423: if (scalar(%$fullname) eq 0) {
3424: my $colspan=3+scalar(@parts);
3425: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3426: my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
3427: $result='<span class="LC_warning">'.
3428: &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
3429: $section_display, $stu_status).
3430: '</span>';
3431: }
3432: return $result;
3433: }
3434:
3435: #--- call by previous routine to display each student
3436: sub viewstudentgrade {
3437: my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
3438: my ($uname,$udom) = split(/:/,$student);
3439: my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
3440: my %aggregates = ();
3441: my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
3442: '<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
3443: "\n".$ctr.' </td><td> '.
3444: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
3445: '\');" target="_self">'.$fullname.'</a> '.
3446: '<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
3447: $student=~s/:/_/; # colon doen't work in javascript for names
3448: foreach my $apart (@$parts) {
3449: my ($part,$type) = &split_part_type($apart);
3450: my $score=$record{"resource.$part.$type"};
3451: $result.='<td align="center">';
3452: my ($aggtries,$totaltries);
3453: unless (exists($aggregates{$part})) {
3454: $totaltries = $record{'resource.'.$part.'.tries'};
3455:
3456: $aggtries = $totaltries;
3457: if ($$last_resets{$part}) {
3458: $aggtries = &get_num_tries(\%record,$$last_resets{$part},
3459: $part);
3460: }
3461: $result.='<input type="hidden" name="'.
3462: 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
3463: $result.='<input type="hidden" name="'.
3464: 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
3465: $aggregates{$part} = 1;
3466: }
3467: if ($type eq 'awarded') {
3468: my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
3469: $result.='<input type="hidden" name="'.
3470: 'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
3471: $result.='<input type="text" name="'.
3472: 'GD_'.$student.'_'.$part.'_awarded" '.
3473: 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
3474: '\')" value="'.$pts.'" size="4" /></td>'."\n";
3475: } elsif ($type eq 'solved') {
3476: my ($status,$foo)=split(/_/,$score,2);
3477: $status = 'nothing' if ($status eq '');
3478: $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
3479: $part.'_solved_s" value="'.$status.'" />'."\n";
3480: $result.=' <select name="'.
3481: 'GD_'.$student.'_'.$part.'_solved" '.
3482: 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
3483: $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>'
3484: : '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
3485: $result.='<option value="reset status">'.&mt('reset status').'</option>';
3486: $result.="</select> </td>\n";
3487: } else {
3488: $result.='<input type="hidden" name="'.
3489: 'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
3490: "\n";
3491: $result.='<input type="text" name="'.
3492: 'GD_'.$student.'_'.$part.'_'.$type.'" '.
3493: 'value="'.$score.'" size="4" /></td>'."\n";
3494: }
3495: }
3496: $result.=&Apache::loncommon::end_data_table_row();
3497: return $result;
3498: }
3499:
3500: #--- change scores for all the students in a section/class
3501: # record does not get update if unchanged
3502: sub editgrades {
3503: my ($request,$symb) = @_;
3504:
3505: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3506: my $title='<h2>'.&mt('Current Grade Status').'</h2>';
3507: $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
3508:
3509: my $result= &Apache::loncommon::start_data_table().
3510: &Apache::loncommon::start_data_table_header_row().
3511: '<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
3512: '<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
3513: my %scoreptr = (
3514: 'correct' =>'correct_by_override',
3515: 'incorrect'=>'incorrect_by_override',
3516: 'excused' =>'excused',
3517: 'ungraded' =>'ungraded_attempted',
3518: 'credited' =>'credit_attempted',
3519: 'nothing' => '',
3520: );
3521: my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
3522:
3523: my (@partid);
3524: my %weight = ();
3525: my %columns = ();
3526: my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
3527:
3528: my $partserror;
3529: my (@parts) = sort(&getpartlist($symb,\$partserror));
3530: if ($partserror) {
3531: return &navmap_errormsg();
3532: }
3533: my $header;
3534: while ($ctr < $env{'form.totalparts'}) {
3535: my $partid = $env{'form.partid_'.$ctr};
3536: push(@partid,$partid);
3537: $weight{$partid} = $env{'form.weight_'.$partid};
3538: $ctr++;
3539: }
3540: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3541: foreach my $partid (@partid) {
3542: $header .= '<th align="center">'.&mt('Old Score').'</th>'.
3543: '<th align="center">'.&mt('New Score').'</th>';
3544: $columns{$partid}=2;
3545: foreach my $stores (@parts) {
3546: my ($part,$type) = &split_part_type($stores);
3547: if ($part !~ m/^\Q$partid\E/) { next;}
3548: if ($type eq 'awarded' || $type eq 'solved') { next; }
3549: my $display=&Apache::lonnet::metadata($url,$stores.'.display');
3550: $display =~ s/\[Part: \Q$part\E\]//;
3551: my $narrowtext = &mt('Tries');
3552: $display =~ s/Number of Attempts/$narrowtext/;
3553: $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
3554: '<th align="center">'.&mt('New').' '.$display.'</th>';
3555: $columns{$partid}+=2;
3556: }
3557: }
3558: foreach my $partid (@partid) {
3559: my $display_part=&get_display_part($partid,$symb);
3560: $result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
3561: &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
3562: '</th>';
3563:
3564: }
3565: $result .= &Apache::loncommon::end_data_table_header_row().
3566: &Apache::loncommon::start_data_table_header_row().
3567: $header.
3568: &Apache::loncommon::end_data_table_header_row();
3569: my @noupdate;
3570: my ($updateCtr,$noupdateCtr) = (1,1);
3571: for ($i=0; $i<$env{'form.total'}; $i++) {
3572: my $line;
3573: my $user = $env{'form.ctr'.$i};
3574: my ($uname,$udom)=split(/:/,$user);
3575: my %newrecord;
3576: my $updateflag = 0;
3577: $line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
3578: my $usec=$classlist->{"$uname:$udom"}[5];
3579: if (!&canmodify($usec)) {
3580: my $numcols=scalar(@partid)*4+2;
3581: push(@noupdate,
3582: $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
3583: &mt('Not allowed to modify student')."</span></td></tr>");
3584: next;
3585: }
3586: my %aggregate = ();
3587: my $aggregateflag = 0;
3588: $user=~s/:/_/; # colon doen't work in javascript for names
3589: foreach (@partid) {
3590: my $old_aw = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
3591: my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
3592: my $old_part = $old_aw eq '' ? '' : $old_part_pcr;
3593: my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
3594: my $awarded = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
3595: my $pcr = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
3596: my $partial = $awarded eq '' ? '' : $pcr;
3597: my $score;
3598: if ($partial eq '') {
3599: $score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
3600: } elsif ($partial > 0) {
3601: $score = 'correct_by_override';
3602: } elsif ($partial == 0) {
3603: $score = 'incorrect_by_override';
3604: }
3605: my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
3606: $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
3607:
3608: $newrecord{'resource.'.$_.'.regrader'}=
3609: "$env{'user.name'}:$env{'user.domain'}";
3610: if ($dropMenu eq 'reset status' &&
3611: $old_score ne '') { # ignore if no previous attempts => nothing to reset
3612: $newrecord{'resource.'.$_.'.tries'} = '';
3613: $newrecord{'resource.'.$_.'.solved'} = '';
3614: $newrecord{'resource.'.$_.'.award'} = '';
3615: $newrecord{'resource.'.$_.'.awarded'} = '';
3616: $updateflag = 1;
3617: if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
3618: my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
3619: my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
3620: my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
3621: &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
3622: $aggregateflag = 1;
3623: }
3624: } elsif (!($old_part eq $partial && $old_score eq $score)) {
3625: $updateflag = 1;
3626: $newrecord{'resource.'.$_.'.awarded'} = $partial if $partial ne '';
3627: $newrecord{'resource.'.$_.'.solved'} = $score;
3628: $rec_update++;
3629: }
3630:
3631: $line .= '<td align="center">'.$old_aw.' </td>'.
3632: '<td align="center">'.$awarded.
3633: ($score eq 'excused' ? $score : '').' </td>';
3634:
3635:
3636: my $partid=$_;
3637: foreach my $stores (@parts) {
3638: my ($part,$type) = &split_part_type($stores);
3639: if ($part !~ m/^\Q$partid\E/) { next;}
3640: if ($type eq 'awarded' || $type eq 'solved') { next; }
3641: my $old_aw = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
3642: my $awarded = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
3643: if ($awarded ne '' && $awarded ne $old_aw) {
3644: $newrecord{'resource.'.$part.'.'.$type}= $awarded;
3645: $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
3646: $updateflag=1;
3647: }
3648: $line .= '<td align="center">'.$old_aw.' </td>'.
3649: '<td align="center">'.$awarded.' </td>';
3650: }
3651: }
3652: $line.="\n";
3653:
3654: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3655: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3656:
3657: if ($updateflag) {
3658: $count++;
3659: &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
3660: $udom,$uname);
3661:
3662: if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
3663: $cnum,$udom,$uname)) {
3664: # need to figure out if should be in queue.
3665: my %record =
3666: &Apache::lonnet::restore($symb,$env{'request.course.id'},
3667: $udom,$uname);
3668: my $all_graded = 1;
3669: my $none_graded = 1;
3670: foreach my $part (@parts) {
3671: if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
3672: $all_graded = 0;
3673: } else {
3674: $none_graded = 0;
3675: }
3676: }
3677:
3678: if ($all_graded || $none_graded) {
3679: &Apache::bridgetask::remove_from_queue('gradingqueue',
3680: $symb,$cdom,$cnum,
3681: $udom,$uname);
3682: }
3683: }
3684:
3685: $result.=&Apache::loncommon::start_data_table_row().
3686: '<td align="right"> '.$updateCtr.' </td>'.$line.
3687: &Apache::loncommon::end_data_table_row();
3688: $updateCtr++;
3689: } else {
3690: push(@noupdate,
3691: '<td align="right"> '.$noupdateCtr.' </td>'.$line);
3692: $noupdateCtr++;
3693: }
3694: if ($aggregateflag) {
3695: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
3696: $cdom,$cnum);
3697: }
3698: }
3699: if (@noupdate) {
3700: # my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
3701: my $numcols=scalar(@partid)*4+2;
3702: $result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
3703: '<td align="center" colspan="'.$numcols.'">'.
3704: &mt('No Changes Occurred For the Students Below').
3705: '</td>'.
3706: &Apache::loncommon::end_data_table_row();
3707: foreach my $line (@noupdate) {
3708: $result.=
3709: &Apache::loncommon::start_data_table_row().
3710: $line.
3711: &Apache::loncommon::end_data_table_row();
3712: }
3713: }
3714: $result .= &Apache::loncommon::end_data_table();
3715: my $msg = '<p><b>'.
3716: &mt('Number of records updated = [_1] for [quant,_2,student].',
3717: $rec_update,$count).'</b><br />'.
3718: '<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
3719: '</b></p>';
3720: return $title.$msg.$result;
3721: }
3722:
3723: sub split_part_type {
3724: my ($partstr) = @_;
3725: my ($temp,@allparts)=split(/_/,$partstr);
3726: my $type=pop(@allparts);
3727: my $part=join('_',@allparts);
3728: return ($part,$type);
3729: }
3730:
3731: #------------- end of section for handling grading by section/class ---------
3732: #
3733: #----------------------------------------------------------------------------
3734:
3735:
3736: #----------------------------------------------------------------------------
3737: #
3738: #-------------------------- Next few routines handles grading by csv upload
3739: #
3740: #--- Javascript to handle csv upload
3741: sub csvupload_javascript_reverse_associate {
3742: my $error1=&mt('You need to specify the username or the student/employee ID');
3743: my $error2=&mt('You need to specify at least one grading field');
3744: return(<<ENDPICK);
3745: function verify(vf) {
3746: var foundsomething=0;
3747: var founduname=0;
3748: var foundID=0;
3749: for (i=0;i<=vf.nfields.value;i++) {
3750: tw=eval('vf.f'+i+'.selectedIndex');
3751: if (i==0 && tw!=0) { foundID=1; }
3752: if (i==1 && tw!=0) { founduname=1; }
3753: if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
3754: }
3755: if (founduname==0 && foundID==0) {
3756: alert('$error1');
3757: return;
3758: }
3759: if (foundsomething==0) {
3760: alert('$error2');
3761: return;
3762: }
3763: vf.submit();
3764: }
3765: function flip(vf,tf) {
3766: var nw=eval('vf.f'+tf+'.selectedIndex');
3767: var i;
3768: for (i=0;i<=vf.nfields.value;i++) {
3769: //can not pick the same destination field for both name and domain
3770: if (((i ==0)||(i ==1)) &&
3771: ((tf==0)||(tf==1)) &&
3772: (i!=tf) &&
3773: (eval('vf.f'+i+'.selectedIndex')==nw)) {
3774: eval('vf.f'+i+'.selectedIndex=0;')
3775: }
3776: }
3777: }
3778: ENDPICK
3779: }
3780:
3781: sub csvupload_javascript_forward_associate {
3782: my $error1=&mt('You need to specify the username or the student/employee ID');
3783: my $error2=&mt('You need to specify at least one grading field');
3784: return(<<ENDPICK);
3785: function verify(vf) {
3786: var foundsomething=0;
3787: var founduname=0;
3788: var foundID=0;
3789: for (i=0;i<=vf.nfields.value;i++) {
3790: tw=eval('vf.f'+i+'.selectedIndex');
3791: if (tw==1) { foundID=1; }
3792: if (tw==2) { founduname=1; }
3793: if (tw>3) { foundsomething=1; }
3794: }
3795: if (founduname==0 && foundID==0) {
3796: alert('$error1');
3797: return;
3798: }
3799: if (foundsomething==0) {
3800: alert('$error2');
3801: return;
3802: }
3803: vf.submit();
3804: }
3805: function flip(vf,tf) {
3806: var nw=eval('vf.f'+tf+'.selectedIndex');
3807: var i;
3808: //can not pick the same destination field twice
3809: for (i=0;i<=vf.nfields.value;i++) {
3810: if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
3811: eval('vf.f'+i+'.selectedIndex=0;')
3812: }
3813: }
3814: }
3815: ENDPICK
3816: }
3817:
3818: sub csvuploadmap_header {
3819: my ($request,$symb,$datatoken,$distotal)= @_;
3820: my $javascript;
3821: if ($env{'form.upfile_associate'} eq 'reverse') {
3822: $javascript=&csvupload_javascript_reverse_associate();
3823: } else {
3824: $javascript=&csvupload_javascript_forward_associate();
3825: }
3826:
3827: my $result='';
3828: $symb = &Apache::lonenc::check_encrypt($symb);
3829: $request->print(<<ENDPICK);
3830: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3831: <h3><span class="LC_info">Uploading Class Grades</span></h3>
3832: $result
3833: <hr />
3834: <h3>Identify fields</h3>
3835: Total number of records found in file: $distotal <hr />
3836: Enter as many fields as you can. The system will inform you and bring you back
3837: to this page if the data selected is insufficient to run your class.<hr />
3838: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
3839: <input type="hidden" name="associate" value="" />
3840: <input type="hidden" name="phase" value="three" />
3841: <input type="hidden" name="datatoken" value="$datatoken" />
3842: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
3843: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
3844: <input type="hidden" name="upfile_associate"
3845: value="$env{'form.upfile_associate'}" />
3846: <input type="hidden" name="symb" value="$symb" />
3847: <input type="hidden" name="command" value="csvuploadoptions" />
3848: <hr />
3849: ENDPICK
3850: $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
3851: return '';
3852:
3853: }
3854:
3855: sub csvupload_fields {
3856: my ($symb,$errorref) = @_;
3857: my (@parts) = &getpartlist($symb,$errorref);
3858: if (ref($errorref)) {
3859: if ($$errorref) {
3860: return;
3861: }
3862: }
3863:
3864: my @fields=(['ID','Student/Employee ID'],
3865: ['username','Student Username'],
3866: ['domain','Student Domain']);
3867: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3868: foreach my $part (sort(@parts)) {
3869: my @datum;
3870: my $display=&Apache::lonnet::metadata($url,$part.'.display');
3871: my $name=$part;
3872: if (!$display) { $display = $name; }
3873: @datum=($name,$display);
3874: if ($name=~/^stores_(.*)_awarded/) {
3875: push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
3876: }
3877: push(@fields,\@datum);
3878: }
3879: return (@fields);
3880: }
3881:
3882: sub csvuploadmap_footer {
3883: my ($request,$i,$keyfields) =@_;
3884: $request->print(<<ENDPICK);
3885: </table>
3886: <input type="hidden" name="nfields" value="$i" />
3887: <input type="hidden" name="keyfields" value="$keyfields" />
3888: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
3889: </form>
3890: ENDPICK
3891: }
3892:
3893: sub checkforfile_js {
3894: my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
3895: my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
3896: function checkUpload(formname) {
3897: if (formname.upfile.value == "") {
3898: alert("$alertmsg");
3899: return false;
3900: }
3901: formname.submit();
3902: }
3903: CSVFORMJS
3904: return $result;
3905: }
3906:
3907: sub upcsvScores_form {
3908: my ($request,$symb) = @_;
3909: if (!$symb) {return '';}
3910: my $result=&checkforfile_js();
3911: $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
3912: $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
3913: $result.=' <b>'.&mt('Specify a file containing the class scores for current resource.').
3914: '</b></td></tr>'."\n";
3915: $result.='<tr bgcolor=#ffffe6><td>'."\n";
3916: my $upload=&mt("Upload Scores");
3917: my $upfile_select=&Apache::loncommon::upfile_select_html();
3918: my $ignore=&mt('Ignore First Line');
3919: $symb = &Apache::lonenc::check_encrypt($symb);
3920: $result.=<<ENDUPFORM;
3921: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3922: <input type="hidden" name="symb" value="$symb" />
3923: <input type="hidden" name="command" value="csvuploadmap" />
3924: $upfile_select
3925: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
3926: </form>
3927: ENDUPFORM
3928: $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
3929: &mt("How do I create a CSV file from a spreadsheet"))
3930: .'</td></tr></table>'."\n";
3931: $result.='</td></tr></table><br /><br />'."\n";
3932: return $result;
3933: }
3934:
3935:
3936: sub csvuploadmap {
3937: my ($request,$symb)= @_;
3938: if (!$symb) {return '';}
3939:
3940: my $datatoken;
3941: if (!$env{'form.datatoken'}) {
3942: $datatoken=&Apache::loncommon::upfile_store($request);
3943: } else {
3944: $datatoken=$env{'form.datatoken'};
3945: &Apache::loncommon::load_tmp_file($request);
3946: }
3947: my @records=&Apache::loncommon::upfile_record_sep();
3948: &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
3949: my ($i,$keyfields);
3950: if (@records) {
3951: my $fieldserror;
3952: my @fields=&csvupload_fields($symb,\$fieldserror);
3953: if ($fieldserror) {
3954: $request->print(&navmap_errormsg());
3955: return;
3956: }
3957: if ($env{'form.upfile_associate'} eq 'reverse') {
3958: &Apache::loncommon::csv_print_samples($request,\@records);
3959: $i=&Apache::loncommon::csv_print_select_table($request,\@records,
3960: \@fields);
3961: foreach (@fields) { $keyfields.=$_->[0].','; }
3962: chop($keyfields);
3963: } else {
3964: unshift(@fields,['none','']);
3965: $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
3966: \@fields);
3967: foreach my $rec (@records) {
3968: my %temp = &Apache::loncommon::record_sep($rec);
3969: if (%temp) {
3970: $keyfields=join(',',sort(keys(%temp)));
3971: last;
3972: }
3973: }
3974: }
3975: }
3976: &csvuploadmap_footer($request,$i,$keyfields);
3977:
3978: return '';
3979: }
3980:
3981: sub csvuploadoptions {
3982: my ($request,$symb)= @_;
3983: $request->print(<<ENDPICK);
3984: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3985: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
3986: <input type="hidden" name="command" value="csvuploadassign" />
3987: <!--
3988: <p>
3989: <label>
3990: <input type="checkbox" name="show_full_results" />
3991: Show a table of all changes
3992: </label>
3993: </p>
3994: -->
3995: <p>
3996: <label>
3997: <input type="checkbox" name="overwite_scores" checked="checked" />
3998: Overwrite any existing score
3999: </label>
4000: </p>
4001: ENDPICK
4002: my %fields=&get_fields();
4003: if (!defined($fields{'domain'})) {
4004: my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
4005: $request->print("\n<p> Users are in domain: ".$domform."</p>\n");
4006: }
4007: foreach my $key (sort(keys(%env))) {
4008: if ($key !~ /^form\.(.*)$/) { next; }
4009: my $cleankey=$1;
4010: if ($cleankey eq 'command') { next; }
4011: $request->print('<input type="hidden" name="'.$cleankey.
4012: '" value="'.$env{$key}.'" />'."\n");
4013: }
4014: # FIXME do a check for any duplicated user ids...
4015: # FIXME do a check for any invalid user ids?...
4016: $request->print('<input type="submit" value="Assign Grades" /><br />
4017: <hr /></form>'."\n");
4018: return '';
4019: }
4020:
4021: sub get_fields {
4022: my %fields;
4023: my @keyfields = split(/\,/,$env{'form.keyfields'});
4024: for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
4025: if ($env{'form.upfile_associate'} eq 'reverse') {
4026: if ($env{'form.f'.$i} ne 'none') {
4027: $fields{$keyfields[$i]}=$env{'form.f'.$i};
4028: }
4029: } else {
4030: if ($env{'form.f'.$i} ne 'none') {
4031: $fields{$env{'form.f'.$i}}=$keyfields[$i];
4032: }
4033: }
4034: }
4035: return %fields;
4036: }
4037:
4038: sub csvuploadassign {
4039: my ($request,$symb)= @_;
4040: if (!$symb) {return '';}
4041: my $error_msg = '';
4042: &Apache::loncommon::load_tmp_file($request);
4043: my @gradedata = &Apache::loncommon::upfile_record_sep();
4044: my %fields=&get_fields();
4045: $request->print('<h3>Assigning Grades</h3>');
4046: my $courseid=$env{'request.course.id'};
4047: my ($classlist) = &getclasslist('all',0);
4048: my @notallowed;
4049: my @skipped;
4050: my $countdone=0;
4051: foreach my $grade (@gradedata) {
4052: my %entries=&Apache::loncommon::record_sep($grade);
4053: my $domain;
4054: if ($entries{$fields{'domain'}}) {
4055: $domain=$entries{$fields{'domain'}};
4056: } else {
4057: $domain=$env{'form.default_domain'};
4058: }
4059: $domain=~s/\s//g;
4060: my $username=$entries{$fields{'username'}};
4061: $username=~s/\s//g;
4062: if (!$username) {
4063: my $id=$entries{$fields{'ID'}};
4064: $id=~s/\s//g;
4065: my %ids=&Apache::lonnet::idget($domain,$id);
4066: $username=$ids{$id};
4067: }
4068: if (!exists($$classlist{"$username:$domain"})) {
4069: my $id=$entries{$fields{'ID'}};
4070: $id=~s/\s//g;
4071: if ($id) {
4072: push(@skipped,"$id:$domain");
4073: } else {
4074: push(@skipped,"$username:$domain");
4075: }
4076: next;
4077: }
4078: my $usec=$classlist->{"$username:$domain"}[5];
4079: if (!&canmodify($usec)) {
4080: push(@notallowed,"$username:$domain");
4081: next;
4082: }
4083: my %points;
4084: my %grades;
4085: foreach my $dest (keys(%fields)) {
4086: if ($dest eq 'ID' || $dest eq 'username' ||
4087: $dest eq 'domain') { next; }
4088: if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
4089: if ($dest=~/stores_(.*)_points/) {
4090: my $part=$1;
4091: my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
4092: $symb,$domain,$username);
4093: if ($wgt) {
4094: $entries{$fields{$dest}}=~s/\s//g;
4095: my $pcr=$entries{$fields{$dest}} / $wgt;
4096: my $award=($pcr == 0) ? 'incorrect_by_override'
4097: : 'correct_by_override';
4098: $grades{"resource.$part.awarded"}=$pcr;
4099: $grades{"resource.$part.solved"}=$award;
4100: $points{$part}=1;
4101: } else {
4102: $error_msg = "<br />" .
4103: &mt("Some point values were assigned"
4104: ." for problems with a weight "
4105: ."of zero. These values were "
4106: ."ignored.");
4107: }
4108: } else {
4109: if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
4110: if ($dest=~/stores_(.*)_solved/) { if ($points{$1}) {next;} }
4111: my $store_key=$dest;
4112: $store_key=~s/^stores/resource/;
4113: $store_key=~s/_/\./g;
4114: $grades{$store_key}=$entries{$fields{$dest}};
4115: }
4116: }
4117: if (! %grades) {
4118: push(@skipped,&mt("[_1]: no data to save","$username:$domain"));
4119: } else {
4120: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
4121: my $result=&Apache::lonnet::cstore(\%grades,$symb,
4122: $env{'request.course.id'},
4123: $domain,$username);
4124: if ($result eq 'ok') {
4125: # Successfully stored
4126: $request->print('.');
4127: # Remove from grading queue
4128: &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
4129: $env{'course.'.$env{'request.course.id'}.'.domain'},
4130: $env{'course.'.$env{'request.course.id'}.'.num'},
4131: $domain,$username);
4132: $countdone++;
4133: } else {
4134: $request->print("<p><span class=\"LC_error\">".
4135: &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
4136: "$username:$domain",$result)."</span></p>");
4137: }
4138: $request->rflush();
4139: }
4140: }
4141: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
4142: if (@skipped) {
4143: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
4144: $request->print(join(', ',@skipped));
4145: }
4146: if (@notallowed) {
4147: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
4148: $request->print(join(', ',@notallowed));
4149: }
4150: $request->print("<br />\n");
4151: return $error_msg;
4152: }
4153: #------------- end of section for handling csv file upload ---------
4154: #
4155: #-------------------------------------------------------------------
4156: #
4157: #-------------- Next few routines handle grading by page/sequence
4158: #
4159: #--- Select a page/sequence and a student to grade
4160: sub pickStudentPage {
4161: my ($request,$symb) = @_;
4162:
4163: my $alertmsg = &mt('Please select the student you wish to grade.');
4164: $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
4165:
4166: function checkPickOne(formname) {
4167: if (radioSelection(formname.student) == null) {
4168: alert("$alertmsg");
4169: return;
4170: }
4171: ptr = pullDownSelection(formname.selectpage);
4172: formname.page.value = formname["page"+ptr].value;
4173: formname.title.value = formname["title"+ptr].value;
4174: formname.submit();
4175: }
4176:
4177: LISTJAVASCRIPT
4178: &commonJSfunctions($request);
4179:
4180: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4181: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4182: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4183:
4184: my $result='<h3><span class="LC_info"> '.
4185: &mt('Manual Grading by Page or Sequence').'</span></h3>';
4186:
4187: $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
4188: my $map_error;
4189: my ($titles,$symbx) = &getSymbMap($map_error);
4190: if ($map_error) {
4191: $request->print(&navmap_errormsg());
4192: return;
4193: }
4194: my ($curpage) =&Apache::lonnet::decode_symb($symb);
4195: # my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb);
4196: # my $type=($curpage =~ /\.(page|sequence)/);
4197: my $select = '<select name="selectpage">'."\n";
4198: my $ctr=0;
4199: foreach (@$titles) {
4200: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4201: $select.='<option value="'.$ctr.'" '.
4202: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
4203: '>'.$showtitle.'</option>'."\n";
4204: $ctr++;
4205: }
4206: $select.= '</select>';
4207: $result.=' <b>'.&mt('Problems from').':</b> '.$select."<br />\n";
4208:
4209: $ctr=0;
4210: foreach (@$titles) {
4211: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4212: $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
4213: $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
4214: $ctr++;
4215: }
4216: $result.='<input type="hidden" name="page" />'."\n".
4217: '<input type="hidden" name="title" />'."\n";
4218:
4219: my $options =
4220: '<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
4221: '<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
4222: $result.=' <b>'.&mt('View Problem Text').': </b>'.$options;
4223:
4224: $options =
4225: '<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
4226: '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
4227: '<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
4228: $result.=' <b>'.&mt('Submissions').': </b>'.$options;
4229:
4230: $result.=&build_section_inputs();
4231: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
4232: $result.='<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
4233: '<input type="hidden" name="command" value="displayPage" />'."\n".
4234: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."<br />\n";
4235:
4236: $result.=' <b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
4237:
4238: $result.=' <input type="button" '.
4239: 'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' →" /><br />'."\n";
4240:
4241: $request->print($result);
4242:
4243: my $studentTable.=' <b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
4244: &Apache::loncommon::start_data_table().
4245: &Apache::loncommon::start_data_table_header_row().
4246: '<th align="right"> '.&mt('No.').'</th>'.
4247: '<th>'.&nameUserString('header').'</th>'.
4248: '<th align="right"> '.&mt('No.').'</th>'.
4249: '<th>'.&nameUserString('header').'</th>'.
4250: &Apache::loncommon::end_data_table_header_row();
4251:
4252: my (undef,undef,$fullname) = &getclasslist($getsec,'1');
4253: my $ptr = 1;
4254: foreach my $student (sort
4255: {
4256: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
4257: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
4258: }
4259: return $a cmp $b;
4260: } (keys(%$fullname))) {
4261: my ($uname,$udom) = split(/:/,$student);
4262: $studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
4263: : '</td>');
4264: $studentTable.='<td align="right">'.$ptr.' </td>';
4265: $studentTable.='<td> <label><input type="radio" name="student" value="'.$student.'" /> '
4266: .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
4267: $studentTable.=
4268: ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row()
4269: : '');
4270: $ptr++;
4271: }
4272: if ($ptr%2 == 0) {
4273: $studentTable.='</td><td> </td><td> </td>'.
4274: &Apache::loncommon::end_data_table_row();
4275: }
4276: $studentTable.=&Apache::loncommon::end_data_table()."\n";
4277: $studentTable.='<input type="button" '.
4278: 'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' →" /></form>'."\n";
4279:
4280: $request->print($studentTable);
4281:
4282: return '';
4283: }
4284:
4285: sub getSymbMap {
4286: my ($map_error) = @_;
4287: my $navmap = Apache::lonnavmaps::navmap->new();
4288: unless (ref($navmap)) {
4289: if (ref($map_error)) {
4290: $$map_error = 'navmap';
4291: }
4292: return;
4293: }
4294: my %symbx = ();
4295: my @titles = ();
4296: my $minder = 0;
4297:
4298: # Gather every sequence that has problems.
4299: my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
4300: 1,0,1);
4301: for my $sequence ($navmap->getById('0.0'), @sequences) {
4302: if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
4303: my $title = $minder.'.'.
4304: &HTML::Entities::encode($sequence->compTitle(),'"\'&');
4305: push(@titles, $title); # minder in case two titles are identical
4306: $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
4307: $minder++;
4308: }
4309: }
4310: return \@titles,\%symbx;
4311: }
4312:
4313: #
4314: #--- Displays a page/sequence w/wo problems, w/wo submissions
4315: sub displayPage {
4316: my ($request,$symb) = @_;
4317: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4318: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4319: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4320: my $pageTitle = $env{'form.page'};
4321: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
4322: my ($uname,$udom) = split(/:/,$env{'form.student'});
4323: my $usec=$classlist->{$env{'form.student'}}[5];
4324:
4325: #need to make sure we have the correct data for later EXT calls,
4326: #thus invalidate the cache
4327: &Apache::lonnet::devalidatecourseresdata(
4328: $env{'course.'.$env{'request.course.id'}.'.num'},
4329: $env{'course.'.$env{'request.course.id'}.'.domain'});
4330: &Apache::lonnet::clear_EXT_cache_status();
4331:
4332: if (!&canview($usec)) {
4333: $request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
4334: return;
4335: }
4336: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
4337: $result.='<h3> '.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
4338: '</h3>'."\n";
4339: $env{'form.CODE'} = uc($env{'form.CODE'});
4340: if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
4341: $result.='<h3> '.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
4342: } else {
4343: delete($env{'form.CODE'});
4344: }
4345: &sub_page_js($request);
4346: $request->print($result);
4347:
4348: my $navmap = Apache::lonnavmaps::navmap->new();
4349: unless (ref($navmap)) {
4350: $request->print(&navmap_errormsg());
4351: return;
4352: }
4353: my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
4354: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
4355: if (!$map) {
4356: $request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
4357: return;
4358: }
4359: my $iterator = $navmap->getIterator($map->map_start(),
4360: $map->map_finish());
4361:
4362: my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
4363: '<input type="hidden" name="command" value="gradeByPage" />'."\n".
4364: '<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
4365: '<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
4366: '<input type="hidden" name="page" value="'.$pageTitle.'" />'."\n".
4367: '<input type="hidden" name="title" value="'.$env{'form.title'}.'" />'."\n".
4368: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
4369: '<input type="hidden" name="overRideScore" value="no" />'."\n";
4370:
4371: if (defined($env{'form.CODE'})) {
4372: $studentTable.=
4373: '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
4374: }
4375: my $checkIcon = '<img alt="'.&mt('Check Mark').
4376: '" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
4377:
4378: $studentTable.=' <span class="LC_info">'.
4379: &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
4380: '</span>'."\n".
4381: &Apache::loncommon::start_data_table().
4382: &Apache::loncommon::start_data_table_header_row().
4383: '<th align="center"> Prob. </th>'.
4384: '<th> '.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
4385: &Apache::loncommon::end_data_table_header_row();
4386:
4387: &Apache::lonxml::clear_problem_counter();
4388: my ($depth,$question,$prob) = (1,1,1);
4389: $iterator->next(); # skip the first BEGIN_MAP
4390: my $curRes = $iterator->next(); # for "current resource"
4391: while ($depth > 0) {
4392: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
4393: if($curRes == $iterator->END_MAP) { $depth--; }
4394:
4395: if (ref($curRes) && $curRes->is_problem()) {
4396: my $parts = $curRes->parts();
4397: my $title = $curRes->compTitle();
4398: my $symbx = $curRes->symb();
4399: $studentTable.=
4400: &Apache::loncommon::start_data_table_row().
4401: '<td align="center" valign="top" >'.$prob.
4402: (scalar(@{$parts}) == 1 ? ''
4403: : '<br />('.&mt('[_1] parts)',
4404: scalar(@{$parts}))
4405: ).
4406: '</td>';
4407: $studentTable.='<td valign="top">';
4408: my %form = ('CODE' => $env{'form.CODE'},);
4409: if ($env{'form.vProb'} eq 'yes' ) {
4410: $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
4411: undef,'both',\%form);
4412: } else {
4413: my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
4414: $companswer =~ s|<form(.*?)>||g;
4415: $companswer =~ s|</form>||g;
4416: # while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
4417: # $companswer =~ s/$1/ /ms;
4418: # $request->print('match='.$1."<br />\n");
4419: # }
4420: # $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
4421: $studentTable.=' <b>'.$title.'</b> <br /> <b>'.&mt('Correct answer').':</b><br />'.$companswer;
4422: }
4423:
4424: my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
4425:
4426: if ($env{'form.lastSub'} eq 'datesub') {
4427: if ($record{'version'} eq '') {
4428: $studentTable.='<br /> <span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
4429: } else {
4430: my %responseType = ();
4431: foreach my $partid (@{$parts}) {
4432: my @responseIds =$curRes->responseIds($partid);
4433: my @responseType =$curRes->responseType($partid);
4434: my %responseIds;
4435: for (my $i=0;$i<=$#responseIds;$i++) {
4436: $responseIds{$responseIds[$i]}=$responseType[$i];
4437: }
4438: $responseType{$partid} = \%responseIds;
4439: }
4440: $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
4441:
4442: }
4443: } elsif ($env{'form.lastSub'} eq 'all') {
4444: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
4445: $studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
4446: $env{'request.course.id'},
4447: '','.submission');
4448:
4449: }
4450: if (&canmodify($usec)) {
4451: $studentTable.=&gradeBox_start();
4452: foreach my $partid (@{$parts}) {
4453: $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
4454: $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
4455: $question++;
4456: }
4457: $studentTable.=&gradeBox_end();
4458: $prob++;
4459: }
4460: $studentTable.='</td></tr>';
4461:
4462: }
4463: $curRes = $iterator->next();
4464: }
4465:
4466: $studentTable.=
4467: '</table>'."\n".
4468: '<input type="button" value="'.&mt('Save').'" '.
4469: 'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
4470: '</form>'."\n";
4471: $request->print($studentTable);
4472:
4473: return '';
4474: }
4475:
4476: sub displaySubByDates {
4477: my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
4478: my $isCODE=0;
4479: my $isTask = ($symb =~/\.task$/);
4480: if (exists($record->{'resource.CODE'})) { $isCODE=1; }
4481: my $studentTable=&Apache::loncommon::start_data_table().
4482: &Apache::loncommon::start_data_table_header_row().
4483: '<th>'.&mt('Date/Time').'</th>'.
4484: ($isCODE?'<th>'.&mt('CODE').'</th>':'').
4485: '<th>'.&mt('Submission').'</th>'.
4486: '<th>'.&mt('Status').'</th>'.
4487: &Apache::loncommon::end_data_table_header_row();
4488: my ($version);
4489: my %mark;
4490: my %orders;
4491: $mark{'correct_by_student'} = $checkIcon;
4492: if (!exists($$record{'1:timestamp'})) {
4493: return '<br /> <span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
4494: }
4495:
4496: my $interaction;
4497: my $no_increment = 1;
4498: for ($version=1;$version<=$$record{'version'};$version++) {
4499: my $timestamp =
4500: &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
4501: if (exists($$record{$version.':resource.0.version'})) {
4502: $interaction = $$record{$version.':resource.0.version'};
4503: }
4504:
4505: my $where = ($isTask ? "$version:resource.$interaction"
4506: : "$version:resource");
4507: $studentTable.=&Apache::loncommon::start_data_table_row().
4508: '<td>'.$timestamp.'</td>';
4509: if ($isCODE) {
4510: $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
4511: }
4512: my @versionKeys = split(/\:/,$$record{$version.':keys'});
4513: my @displaySub = ();
4514: foreach my $partid (@{$parts}) {
4515: my $hidden;
4516: if (($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurvey') ||
4517: ($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurveycred')) {
4518: $hidden = 1;
4519: }
4520: my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
4521: : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
4522:
4523: # next if ($$record{"$version:resource.$partid.solved"} eq '');
4524: my $display_part=&get_display_part($partid,$symb);
4525: foreach my $matchKey (@matchKey) {
4526: if (exists($$record{$version.':'.$matchKey}) &&
4527: $$record{$version.':'.$matchKey} ne '') {
4528:
4529: my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
4530: : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
4531: $displaySub[0].='<span class="LC_nobreak"';
4532: $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
4533: .' <span class="LC_internal_info">'
4534: .'('.&mt('Response ID: [_1]',$responseId).')'
4535: .'</span>'
4536: .' <b>';
4537: if ($hidden) {
4538: $displaySub[0].= &mt('Anonymous Survey').'</b>';
4539: } else {
4540: if ($$record{"$where.$partid.tries"} eq '') {
4541: $displaySub[0].=&mt('Trial not counted');
4542: } else {
4543: $displaySub[0].=&mt('Trial: [_1]',
4544: $$record{"$where.$partid.tries"});
4545: }
4546: my $responseType=($isTask ? 'Task'
4547: : $responseType->{$partid}->{$responseId});
4548: if (!exists($orders{$partid})) { $orders{$partid}={}; }
4549: if (!exists($orders{$partid}->{$responseId})) {
4550: $orders{$partid}->{$responseId}=
4551: &get_order($partid,$responseId,$symb,$uname,$udom,
4552: $no_increment);
4553: }
4554: $displaySub[0].='</b></span>'; # /nobreak
4555: $displaySub[0].=' '.
4556: &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
4557: }
4558: }
4559: }
4560: if (exists($$record{"$where.$partid.checkedin"})) {
4561: $displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
4562: $$record{"$where.$partid.checkedin"},
4563: $$record{"$where.$partid.checkedin.slot"}).
4564: '<br />';
4565: }
4566: if (exists $$record{"$where.$partid.award"}) {
4567: $displaySub[1].='<b>'.&mt('Part:').'</b> '.$display_part.' '.
4568: lc($$record{"$where.$partid.award"}).' '.
4569: $mark{$$record{"$where.$partid.solved"}}.
4570: '<br />';
4571: }
4572: if (exists $$record{"$where.$partid.regrader"}) {
4573: $displaySub[2].=$$record{"$where.$partid.regrader"}.
4574: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
4575: } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
4576: $displaySub[2].=
4577: $$record{"$version:resource.$partid.regrader"}.
4578: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
4579: }
4580: }
4581: # needed because old essay regrader has not parts info
4582: if (exists $$record{"$version:resource.regrader"}) {
4583: $displaySub[2].=$$record{"$version:resource.regrader"};
4584: }
4585: $studentTable.='<td>'.$displaySub[0].' </td><td>'.$displaySub[1];
4586: if ($displaySub[2]) {
4587: $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
4588: }
4589: $studentTable.=' </td>'.
4590: &Apache::loncommon::end_data_table_row();
4591: }
4592: $studentTable.=&Apache::loncommon::end_data_table();
4593: return $studentTable;
4594: }
4595:
4596: sub updateGradeByPage {
4597: my ($request,$symb) = @_;
4598:
4599: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4600: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4601: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4602: my $pageTitle = $env{'form.page'};
4603: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
4604: my ($uname,$udom) = split(/:/,$env{'form.student'});
4605: my $usec=$classlist->{$env{'form.student'}}[5];
4606: if (!&canmodify($usec)) {
4607: $request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
4608: return;
4609: }
4610: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
4611: $result.='<h3> '.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
4612: '</h3>'."\n";
4613:
4614: $request->print($result);
4615:
4616:
4617: my $navmap = Apache::lonnavmaps::navmap->new();
4618: unless (ref($navmap)) {
4619: $request->print(&navmap_errormsg());
4620: return;
4621: }
4622: my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
4623: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
4624: if (!$map) {
4625: $request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
4626: return;
4627: }
4628: my $iterator = $navmap->getIterator($map->map_start(),
4629: $map->map_finish());
4630:
4631: my $studentTable=
4632: &Apache::loncommon::start_data_table().
4633: &Apache::loncommon::start_data_table_header_row().
4634: '<th align="center"> '.&mt('Prob.').' </th>'.
4635: '<th> '.&mt('Title').' </th>'.
4636: '<th> '.&mt('Previous Score').' </th>'.
4637: '<th> '.&mt('New Score').' </th>'.
4638: &Apache::loncommon::end_data_table_header_row();
4639:
4640: $iterator->next(); # skip the first BEGIN_MAP
4641: my $curRes = $iterator->next(); # for "current resource"
4642: my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
4643: while ($depth > 0) {
4644: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
4645: if($curRes == $iterator->END_MAP) { $depth--; }
4646:
4647: if (ref($curRes) && $curRes->is_problem()) {
4648: my $parts = $curRes->parts();
4649: my $title = $curRes->compTitle();
4650: my $symbx = $curRes->symb();
4651: $studentTable.=
4652: &Apache::loncommon::start_data_table_row().
4653: '<td align="center" valign="top" >'.$prob.
4654: (scalar(@{$parts}) == 1 ? ''
4655: : '<br />('.&mt('[quant,_1, part]',scalar(@{$parts}))
4656: .')').'</td>';
4657: $studentTable.='<td valign="top"> <b>'.$title.'</b> </td>';
4658:
4659: my %newrecord=();
4660: my @displayPts=();
4661: my %aggregate = ();
4662: my $aggregateflag = 0;
4663: foreach my $partid (@{$parts}) {
4664: my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
4665: my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
4666:
4667: my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ?
4668: $env{'form.WGT'.$question.'_'.$partid} : 1;
4669: my $partial = $newpts/$wgt;
4670: my $score;
4671: if ($partial > 0) {
4672: $score = 'correct_by_override';
4673: } elsif ($newpts ne '') { #empty is taken as 0
4674: $score = 'incorrect_by_override';
4675: }
4676: my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
4677: if ($dropMenu eq 'excused') {
4678: $partial = '';
4679: $score = 'excused';
4680: } elsif ($dropMenu eq 'reset status'
4681: && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
4682: $newrecord{'resource.'.$partid.'.tries'} = 0;
4683: $newrecord{'resource.'.$partid.'.solved'} = '';
4684: $newrecord{'resource.'.$partid.'.award'} = '';
4685: $newrecord{'resource.'.$partid.'.awarded'} = 0;
4686: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
4687: $changeflag++;
4688: $newpts = '';
4689:
4690: my $aggtries = $env{'form.aggtries'.$question.'_'.$partid};
4691: my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
4692: my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
4693: if ($aggtries > 0) {
4694: &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
4695: $aggregateflag = 1;
4696: }
4697: }
4698: my $display_part=&get_display_part($partid,$curRes->symb());
4699: my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
4700: $displayPts[0].=' <b>'.&mt('Part').':</b> '.$display_part.' = '.
4701: (($oldstatus eq 'excused') ? 'excused' : $oldpts).
4702: ' <br />';
4703: $displayPts[1].=' <b>'.&mt('Part').':</b> '.$display_part.' = '.
4704: (($score eq 'excused') ? 'excused' : $newpts).
4705: ' <br />';
4706: $question++;
4707: next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
4708:
4709: $newrecord{'resource.'.$partid.'.awarded'} = $partial if $partial ne '';
4710: $newrecord{'resource.'.$partid.'.solved'} = $score if $score ne '';
4711: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
4712: if (scalar(keys(%newrecord)) > 0);
4713:
4714: $changeflag++;
4715: }
4716: if (scalar(keys(%newrecord)) > 0) {
4717: my %record =
4718: &Apache::lonnet::restore($symbx,$env{'request.course.id'},
4719: $udom,$uname);
4720:
4721: if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
4722: $newrecord{'resource.CODE'} = $env{'form.CODE'};
4723: } elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
4724: $newrecord{'resource.CODE'} = '';
4725: }
4726: &Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
4727: $udom,$uname);
4728: %record = &Apache::lonnet::restore($symbx,
4729: $env{'request.course.id'},
4730: $udom,$uname);
4731: &check_and_remove_from_queue($parts,\%record,undef,$symbx,
4732: $cdom,$cnum,$udom,$uname);
4733: }
4734:
4735: if ($aggregateflag) {
4736: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
4737: $env{'course.'.$env{'request.course.id'}.'.domain'},
4738: $env{'course.'.$env{'request.course.id'}.'.num'});
4739: }
4740:
4741: $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
4742: '<td valign="top">'.$displayPts[1].'</td>'.
4743: &Apache::loncommon::end_data_table_row();
4744:
4745: $prob++;
4746: }
4747: $curRes = $iterator->next();
4748: }
4749:
4750: $studentTable.=&Apache::loncommon::end_data_table();
4751: my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
4752: &mt('The scores were changed for [quant,_1,problem].',
4753: $changeflag));
4754: $request->print($grademsg.$studentTable);
4755:
4756: return '';
4757: }
4758:
4759: #-------- end of section for handling grading by page/sequence ---------
4760: #
4761: #-------------------------------------------------------------------
4762:
4763: #-------------------- Bubblesheet (Scantron) Grading -------------------
4764: #
4765: #------ start of section for handling grading by page/sequence ---------
4766:
4767: =pod
4768:
4769: =head1 Bubble sheet grading routines
4770:
4771: For this documentation:
4772:
4773: 'scanline' refers to the full line of characters
4774: from the file that we are parsing that represents one entire sheet
4775:
4776: 'bubble line' refers to the data
4777: representing the line of bubbles that are on the physical bubble sheet
4778:
4779:
4780: The overall process is that a scanned in bubble sheet data is uploaded
4781: into a course. When a user wants to grade, they select a
4782: sequence/folder of resources, a file of bubble sheet info, and pick
4783: one of the predefined configurations for what each scanline looks
4784: like.
4785:
4786: Next each scanline is checked for any errors of either 'missing
4787: bubbles' (it's an error because it may have been mis-scanned
4788: because too light bubbling), 'double bubble' (each bubble line should
4789: have no more that one letter picked), invalid or duplicated CODE,
4790: invalid student/employee ID
4791:
4792: If the CODE option is used that determines the randomization of the
4793: homework problems, either way the student/employee ID is looked up into a
4794: username:domain.
4795:
4796: During the validation phase the instructor can choose to skip scanlines.
4797:
4798: After the validation phase, there are now 3 bubble sheet files
4799:
4800: scantron_original_filename (unmodified original file)
4801: scantron_corrected_filename (file where the corrected information has replaced the original information)
4802: scantron_skipped_filename (contains the exact text of scanlines that where skipped)
4803:
4804: Also there is a separate hash nohist_scantrondata that contains extra
4805: correction information that isn't representable in the bubble sheet
4806: file (see &scantron_getfile() for more information)
4807:
4808: After all scanlines are either valid, marked as valid or skipped, then
4809: foreach line foreach problem in the picked sequence, an ssi request is
4810: made that simulates a user submitting their selected letter(s) against
4811: the homework problem.
4812:
4813: =over 4
4814:
4815:
4816:
4817: =item defaultFormData
4818:
4819: Returns html hidden inputs used to hold context/default values.
4820:
4821: Arguments:
4822: $symb - $symb of the current resource
4823:
4824: =cut
4825:
4826: sub defaultFormData {
4827: my ($symb)=@_;
4828: return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
4829: }
4830:
4831:
4832: =pod
4833:
4834: =item getSequenceDropDown
4835:
4836: Return html dropdown of possible sequences to grade
4837:
4838: Arguments:
4839: $symb - $symb of the current resource
4840: $map_error - ref to scalar which will container error if
4841: $navmap object is unavailable in &getSymbMap().
4842:
4843: =cut
4844:
4845: sub getSequenceDropDown {
4846: my ($symb,$map_error)=@_;
4847: my $result='<select name="selectpage">'."\n";
4848: my ($titles,$symbx) = &getSymbMap($map_error);
4849: if (ref($map_error)) {
4850: return if ($$map_error);
4851: }
4852: my ($curpage)=&Apache::lonnet::decode_symb($symb);
4853: my $ctr=0;
4854: foreach (@$titles) {
4855: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4856: $result.='<option value="'.$$symbx{$_}.'" '.
4857: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
4858: '>'.$showtitle.'</option>'."\n";
4859: $ctr++;
4860: }
4861: $result.= '</select>';
4862: return $result;
4863: }
4864:
4865: my %bubble_lines_per_response; # no. bubble lines for each response.
4866: # key is zero-based index - 0, 1, 2 ...
4867:
4868: my %first_bubble_line; # First bubble line no. for each bubble.
4869:
4870: my %subdivided_bubble_lines; # no. bubble lines for optionresponse,
4871: # matchresponse or rankresponse, where
4872: # an individual response can have multiple
4873: # lines
4874:
4875: my %responsetype_per_response; # responsetype for each response
4876:
4877: # Save and restore the bubble lines array to the form env.
4878:
4879:
4880: sub save_bubble_lines {
4881: foreach my $line (keys(%bubble_lines_per_response)) {
4882: $env{"form.scantron.bubblelines.$line"} = $bubble_lines_per_response{$line};
4883: $env{"form.scantron.first_bubble_line.$line"} =
4884: $first_bubble_line{$line};
4885: $env{"form.scantron.sub_bubblelines.$line"} =
4886: $subdivided_bubble_lines{$line};
4887: $env{"form.scantron.responsetype.$line"} =
4888: $responsetype_per_response{$line};
4889: }
4890: }
4891:
4892:
4893: sub restore_bubble_lines {
4894: my $line = 0;
4895: %bubble_lines_per_response = ();
4896: while ($env{"form.scantron.bubblelines.$line"}) {
4897: my $value = $env{"form.scantron.bubblelines.$line"};
4898: $bubble_lines_per_response{$line} = $value;
4899: $first_bubble_line{$line} =
4900: $env{"form.scantron.first_bubble_line.$line"};
4901: $subdivided_bubble_lines{$line} =
4902: $env{"form.scantron.sub_bubblelines.$line"};
4903: $responsetype_per_response{$line} =
4904: $env{"form.scantron.responsetype.$line"};
4905: $line++;
4906: }
4907: }
4908:
4909: # Given the parsed scanline, get the response for
4910: # 'answer' number n:
4911:
4912: sub get_response_bubbles {
4913: my ($parsed_line, $response) = @_;
4914:
4915: my $bubble_line = $first_bubble_line{$response-1} +1;
4916: my $bubble_lines= $bubble_lines_per_response{$response-1};
4917:
4918: my $selected = "";
4919:
4920: for (my $bline = 0; $bline < $bubble_lines; $bline++) {
4921: $selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
4922: $bubble_line++;
4923: }
4924: return $selected;
4925: }
4926:
4927: =pod
4928:
4929: =item scantron_filenames
4930:
4931: Returns a list of the scantron files in the current course
4932:
4933: =cut
4934:
4935: sub scantron_filenames {
4936: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4937: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
4938: my $getpropath = 1;
4939: my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
4940: $getpropath);
4941: my @possiblenames;
4942: foreach my $filename (sort(@files)) {
4943: ($filename)=split(/&/,$filename);
4944: if ($filename!~/^scantron_orig_/) { next ; }
4945: $filename=~s/^scantron_orig_//;
4946: push(@possiblenames,$filename);
4947: }
4948: return @possiblenames;
4949: }
4950:
4951: =pod
4952:
4953: =item scantron_uploads
4954:
4955: Returns html drop-down list of scantron files in current course.
4956:
4957: Arguments:
4958: $file2grade - filename to set as selected in the dropdown
4959:
4960: =cut
4961:
4962: sub scantron_uploads {
4963: my ($file2grade) = @_;
4964: my $result= '<select name="scantron_selectfile">';
4965: $result.="<option></option>";
4966: foreach my $filename (sort(&scantron_filenames())) {
4967: $result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
4968: }
4969: $result.="</select>";
4970: return $result;
4971: }
4972:
4973: =pod
4974:
4975: =item scantron_scantab
4976:
4977: Returns html drop down of the scantron formats in the scantronformat.tab
4978: file.
4979:
4980: =cut
4981:
4982: sub scantron_scantab {
4983: my $result='<select name="scantron_format">'."\n";
4984: $result.='<option></option>'."\n";
4985: my @lines = &get_scantronformat_file();
4986: if (@lines > 0) {
4987: foreach my $line (@lines) {
4988: next if (($line =~ /^\#/) || ($line eq ''));
4989: my ($name,$descrip)=split(/:/,$line);
4990: $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
4991: }
4992: }
4993: $result.='</select>'."\n";
4994: return $result;
4995: }
4996:
4997: =pod
4998:
4999: =item get_scantronformat_file
5000:
5001: Returns an array containing lines from the scantron format file for
5002: the domain of the course.
5003:
5004: If a url for a custom.tab file is listed in domain's configuration.db,
5005: lines are from this file.
5006:
5007: Otherwise, if a default.tab has been published in RES space by the
5008: domainconfig user, lines are from this file.
5009:
5010: Otherwise, fall back to getting lines from the legacy file on the
5011: local server: /home/httpd/lonTabs/default_scantronformat.tab
5012:
5013: =cut
5014:
5015: sub get_scantronformat_file {
5016: my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
5017: my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
5018: my $gottab = 0;
5019: my @lines;
5020: if (ref($domconfig{'scantron'}) eq 'HASH') {
5021: if ($domconfig{'scantron'}{'scantronformat'} ne '') {
5022: my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
5023: if ($formatfile ne '-1') {
5024: @lines = split("\n",$formatfile,-1);
5025: $gottab = 1;
5026: }
5027: }
5028: }
5029: if (!$gottab) {
5030: my $confname = $cdom.'-domainconfig';
5031: my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
5032: my $formatfile = &Apache::lonnet::getfile($default);
5033: if ($formatfile ne '-1') {
5034: @lines = split("\n",$formatfile,-1);
5035: $gottab = 1;
5036: }
5037: }
5038: if (!$gottab) {
5039: my @domains = &Apache::lonnet::current_machine_domains();
5040: if (grep(/^\Q$cdom\E$/,@domains)) {
5041: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
5042: @lines = <$fh>;
5043: close($fh);
5044: } else {
5045: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
5046: @lines = <$fh>;
5047: close($fh);
5048: }
5049: }
5050: return @lines;
5051: }
5052:
5053: =pod
5054:
5055: =item scantron_CODElist
5056:
5057: Returns html drop down of the saved CODE lists from current course,
5058: generated from earlier printings.
5059:
5060: =cut
5061:
5062: sub scantron_CODElist {
5063: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5064: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5065: my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
5066: my $namechoice='<option></option>';
5067: foreach my $name (sort {uc($a) cmp uc($b)} @names) {
5068: if ($name =~ /^error: 2 /) { next; }
5069: if ($name =~ /^type\0/) { next; }
5070: $namechoice.='<option value="'.$name.'">'.$name.'</option>';
5071: }
5072: $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
5073: return $namechoice;
5074: }
5075:
5076: =pod
5077:
5078: =item scantron_CODEunique
5079:
5080: Returns the html for "Each CODE to be used once" radio.
5081:
5082: =cut
5083:
5084: sub scantron_CODEunique {
5085: my $result='<span class="LC_nobreak">
5086: <label><input type="radio" name="scantron_CODEunique"
5087: value="yes" checked="checked" />'.&mt('Yes').' </label>
5088: </span>
5089: <span class="LC_nobreak">
5090: <label><input type="radio" name="scantron_CODEunique"
5091: value="no" />'.&mt('No').' </label>
5092: </span>';
5093: return $result;
5094: }
5095:
5096: =pod
5097:
5098: =item scantron_selectphase
5099:
5100: Generates the initial screen to start the bubble sheet process.
5101: Allows for - starting a grading run.
5102: - downloading existing scan data (original, corrected
5103: or skipped info)
5104:
5105: - uploading new scan data
5106:
5107: Arguments:
5108: $r - The Apache request object
5109: $file2grade - name of the file that contain the scanned data to score
5110:
5111: =cut
5112:
5113: sub scantron_selectphase {
5114: my ($r,$file2grade,$symb) = @_;
5115: if (!$symb) {return '';}
5116: my $map_error;
5117: my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
5118: if ($map_error) {
5119: $r->print('<br />'.&navmap_errormsg().'<br />');
5120: return;
5121: }
5122: my $default_form_data=&defaultFormData($symb);
5123: my $file_selector=&scantron_uploads($file2grade);
5124: my $format_selector=&scantron_scantab();
5125: my $CODE_selector=&scantron_CODElist();
5126: my $CODE_unique=&scantron_CODEunique();
5127: my $result;
5128:
5129: $ssi_error = 0;
5130:
5131: if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
5132: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
5133:
5134: # Chunk of form to prompt for a scantron file upload.
5135:
5136: $r->print('
5137: <br />
5138: '.&Apache::loncommon::start_data_table('LC_scantron_action').'
5139: '.&Apache::loncommon::start_data_table_header_row().'
5140: <th>
5141: '.&mt('Specify a bubblesheet data file to upload.').'
5142: </th>
5143: '.&Apache::loncommon::end_data_table_header_row().'
5144: '.&Apache::loncommon::start_data_table_row().'
5145: <td>
5146: ');
5147: my $default_form_data=&defaultFormData($symb);
5148: my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
5149: my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
5150: $r->print(&Apache::lonhtmlcommon::scripttag('
5151: function checkUpload(formname) {
5152: if (formname.upfile.value == "") {
5153: alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
5154: return false;
5155: }
5156: formname.submit();
5157: }'));
5158: $r->print('
5159: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
5160: '.$default_form_data.'
5161: <input name="courseid" type="hidden" value="'.$cnum.'" />
5162: <input name="domainid" type="hidden" value="'.$cdom.'" />
5163: <input name="command" value="scantronupload_save" type="hidden" />
5164: '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
5165: <br />
5166: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
5167: </form>
5168: ');
5169:
5170: $r->print('
5171: </td>
5172: '.&Apache::loncommon::end_data_table_row().'
5173: '.&Apache::loncommon::end_data_table().'
5174: ');
5175: }
5176:
5177: # Chunk of form to prompt for a file to grade and how:
5178:
5179: $result.= '
5180: <br />
5181: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
5182: <input type="hidden" name="command" value="scantron_warning" />
5183: '.$default_form_data.'
5184: '.&Apache::loncommon::start_data_table('LC_scantron_action').'
5185: '.&Apache::loncommon::start_data_table_header_row().'
5186: <th colspan="2">
5187: '.&mt('Specify file and which Folder/Sequence to grade').'
5188: </th>
5189: '.&Apache::loncommon::end_data_table_header_row().'
5190: '.&Apache::loncommon::start_data_table_row().'
5191: <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
5192: '.&Apache::loncommon::end_data_table_row().'
5193: '.&Apache::loncommon::start_data_table_row().'
5194: <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
5195: '.&Apache::loncommon::end_data_table_row().'
5196: '.&Apache::loncommon::start_data_table_row().'
5197: <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
5198: '.&Apache::loncommon::end_data_table_row().'
5199: '.&Apache::loncommon::start_data_table_row().'
5200: <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
5201: '.&Apache::loncommon::end_data_table_row().'
5202: '.&Apache::loncommon::start_data_table_row().'
5203: <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
5204: '.&Apache::loncommon::end_data_table_row().'
5205: '.&Apache::loncommon::start_data_table_row().'
5206: <td> '.&mt('Options:').' </td>
5207: <td>
5208: <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
5209: <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
5210: <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
5211: </td>
5212: '.&Apache::loncommon::end_data_table_row().'
5213: '.&Apache::loncommon::start_data_table_row().'
5214: <td colspan="2">
5215: <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
5216: </td>
5217: '.&Apache::loncommon::end_data_table_row().'
5218: '.&Apache::loncommon::end_data_table().'
5219: </form>
5220: ';
5221:
5222: $r->print($result);
5223:
5224:
5225:
5226: # Chunk of the form that prompts to view a scoring office file,
5227: # corrected file, skipped records in a file.
5228:
5229: $r->print('
5230: <br />
5231: <form action="/adm/grades" name="scantron_download">
5232: '.$default_form_data.'
5233: <input type="hidden" name="command" value="scantron_download" />
5234: '.&Apache::loncommon::start_data_table('LC_scantron_action').'
5235: '.&Apache::loncommon::start_data_table_header_row().'
5236: <th>
5237: '.&mt('Download a scoring office file').'
5238: </th>
5239: '.&Apache::loncommon::end_data_table_header_row().'
5240: '.&Apache::loncommon::start_data_table_row().'
5241: <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).'
5242: <br />
5243: <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
5244: '.&Apache::loncommon::end_data_table_row().'
5245: '.&Apache::loncommon::end_data_table().'
5246: </form>
5247: <br />
5248: ');
5249:
5250: &Apache::lonpickcode::code_list($r,2);
5251:
5252: $r->print('<br /><form method="post" name="checkscantron">'.
5253: $default_form_data."\n".
5254: &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
5255: &Apache::loncommon::start_data_table_header_row()."\n".
5256: '<th colspan="2">
5257: '.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
5258: '</th>'."\n".
5259: &Apache::loncommon::end_data_table_header_row()."\n".
5260: &Apache::loncommon::start_data_table_row()."\n".
5261: '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
5262: '<td> '.$sequence_selector.' </td>'.
5263: &Apache::loncommon::end_data_table_row()."\n".
5264: &Apache::loncommon::start_data_table_row()."\n".
5265: '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
5266: '<td> '.$file_selector.' </td>'."\n".
5267: &Apache::loncommon::end_data_table_row()."\n".
5268: &Apache::loncommon::start_data_table_row()."\n".
5269: '<td> '.&mt('Format of data file:').' </td>'."\n".
5270: '<td> '.$format_selector.' </td>'."\n".
5271: &Apache::loncommon::end_data_table_row()."\n".
5272: &Apache::loncommon::start_data_table_row()."\n".
5273: '<td> '.&mt('Options').' </td>'."\n".
5274: '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
5275: &Apache::loncommon::end_data_table_row()."\n".
5276: &Apache::loncommon::start_data_table_row()."\n".
5277: '<td colspan="2">'."\n".
5278: '<input type="hidden" name="command" value="checksubmissions" />'."\n".
5279: '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
5280: '</td>'."\n".
5281: &Apache::loncommon::end_data_table_row()."\n".
5282: &Apache::loncommon::end_data_table()."\n".
5283: '</form><br />');
5284: return;
5285: }
5286:
5287: =pod
5288:
5289: =item get_scantron_config
5290:
5291: Parse and return the scantron configuration line selected as a
5292: hash of configuration file fields.
5293:
5294: Arguments:
5295: which - the name of the configuration to parse from the file.
5296:
5297:
5298: Returns:
5299: If the named configuration is not in the file, an empty
5300: hash is returned.
5301: a hash with the fields
5302: name - internal name for the this configuration setup
5303: description - text to display to operator that describes this config
5304: CODElocation - if 0 or the string 'none'
5305: - no CODE exists for this config
5306: if -1 || the string 'letter'
5307: - a CODE exists for this config and is
5308: a string of letters
5309: Unsupported value (but planned for future support)
5310: if a positive integer
5311: - The CODE exists as the first n items from
5312: the question section of the form
5313: if the string 'number'
5314: - The CODE exists for this config and is
5315: a string of numbers
5316: CODEstart - (only matter if a CODE exists) column in the line where
5317: the CODE starts
5318: CODElength - length of the CODE
5319: IDstart - column where the student/employee ID starts
5320: IDlength - length of the student/employee ID info
5321: Qstart - column where the information from the bubbled
5322: 'questions' start
5323: Qlength - number of columns comprising a single bubble line from
5324: the sheet. (usually either 1 or 10)
5325: Qon - either a single character representing the character used
5326: to signal a bubble was chosen in the positional setup, or
5327: the string 'letter' if the letter of the chosen bubble is
5328: in the final, or 'number' if a number representing the
5329: chosen bubble is in the file (1->A 0->J)
5330: Qoff - the character used to represent that a bubble was
5331: left blank
5332: PaperID - if the scanning process generates a unique number for each
5333: sheet scanned the column that this ID number starts in
5334: PaperIDlength - number of columns that comprise the unique ID number
5335: for the sheet of paper
5336: FirstName - column that the first name starts in
5337: FirstNameLength - number of columns that the first name spans
5338:
5339: LastName - column that the last name starts in
5340: LastNameLength - number of columns that the last name spans
5341:
5342: =cut
5343:
5344: sub get_scantron_config {
5345: my ($which) = @_;
5346: my @lines = &get_scantronformat_file();
5347: my %config;
5348: #FIXME probably should move to XML it has already gotten a bit much now
5349: foreach my $line (@lines) {
5350: my ($name,$descrip)=split(/:/,$line);
5351: if ($name ne $which ) { next; }
5352: chomp($line);
5353: my @config=split(/:/,$line);
5354: $config{'name'}=$config[0];
5355: $config{'description'}=$config[1];
5356: $config{'CODElocation'}=$config[2];
5357: $config{'CODEstart'}=$config[3];
5358: $config{'CODElength'}=$config[4];
5359: $config{'IDstart'}=$config[5];
5360: $config{'IDlength'}=$config[6];
5361: $config{'Qstart'}=$config[7];
5362: $config{'Qlength'}=$config[8];
5363: $config{'Qoff'}=$config[9];
5364: $config{'Qon'}=$config[10];
5365: $config{'PaperID'}=$config[11];
5366: $config{'PaperIDlength'}=$config[12];
5367: $config{'FirstName'}=$config[13];
5368: $config{'FirstNamelength'}=$config[14];
5369: $config{'LastName'}=$config[15];
5370: $config{'LastNamelength'}=$config[16];
5371: last;
5372: }
5373: return %config;
5374: }
5375:
5376: =pod
5377:
5378: =item username_to_idmap
5379:
5380: creates a hash keyed by student/employee ID with values of the corresponding
5381: student username:domain.
5382:
5383: Arguments:
5384:
5385: $classlist - reference to the class list hash. This is a hash
5386: keyed by student name:domain whose elements are references
5387: to arrays containing various chunks of information
5388: about the student. (See loncoursedata for more info).
5389:
5390: Returns
5391: %idmap - the constructed hash
5392:
5393: =cut
5394:
5395: sub username_to_idmap {
5396: my ($classlist)= @_;
5397: my %idmap;
5398: foreach my $student (keys(%$classlist)) {
5399: $idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
5400: $student;
5401: }
5402: return %idmap;
5403: }
5404:
5405: =pod
5406:
5407: =item scantron_fixup_scanline
5408:
5409: Process a requested correction to a scanline.
5410:
5411: Arguments:
5412: $scantron_config - hash from &get_scantron_config()
5413: $scan_data - hash of correction information
5414: (see &scantron_getfile())
5415: $line - existing scanline
5416: $whichline - line number of the passed in scanline
5417: $field - type of change to process
5418: (either
5419: 'ID' -> correct the student/employee ID
5420: 'CODE' -> correct the CODE
5421: 'answer' -> fixup the submitted answers)
5422:
5423: $args - hash of additional info,
5424: - 'ID'
5425: 'newid' -> studentID to use in replacement
5426: of existing one
5427: - 'CODE'
5428: 'CODE_ignore_dup' - set to true if duplicates
5429: should be ignored.
5430: 'CODE' - is new code or 'use_unfound'
5431: if the existing unfound code should
5432: be used as is
5433: - 'answer'
5434: 'response' - new answer or 'none' if blank
5435: 'question' - the bubble line to change
5436: 'questionnum' - the question identifier,
5437: may include subquestion.
5438:
5439: Returns:
5440: $line - the modified scanline
5441:
5442: Side effects:
5443: $scan_data - may be updated
5444:
5445: =cut
5446:
5447:
5448: sub scantron_fixup_scanline {
5449: my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
5450: if ($field eq 'ID') {
5451: if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
5452: return ($line,1,'New value too large');
5453: }
5454: if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
5455: $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
5456: $args->{'newid'});
5457: }
5458: substr($line,$$scantron_config{'IDstart'}-1,
5459: $$scantron_config{'IDlength'})=$args->{'newid'};
5460: if ($args->{'newid'}=~/^\s*$/) {
5461: &scan_data($scan_data,"$whichline.user",
5462: $args->{'username'}.':'.$args->{'domain'});
5463: }
5464: } elsif ($field eq 'CODE') {
5465: if ($args->{'CODE_ignore_dup'}) {
5466: &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
5467: }
5468: &scan_data($scan_data,"$whichline.useCODE",'1');
5469: if ($args->{'CODE'} ne 'use_unfound') {
5470: if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
5471: return ($line,1,'New CODE value too large');
5472: }
5473: if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
5474: $args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
5475: }
5476: substr($line,$$scantron_config{'CODEstart'}-1,
5477: $$scantron_config{'CODElength'})=$args->{'CODE'};
5478: }
5479: } elsif ($field eq 'answer') {
5480: my $length=$scantron_config->{'Qlength'};
5481: my $off=$scantron_config->{'Qoff'};
5482: my $on=$scantron_config->{'Qon'};
5483: my $answer=${off}x$length;
5484: if ($args->{'response'} eq 'none') {
5485: &scan_data($scan_data,
5486: "$whichline.no_bubble.".$args->{'questionnum'},'1');
5487: } else {
5488: if ($on eq 'letter') {
5489: my @alphabet=('A'..'Z');
5490: $answer=$alphabet[$args->{'response'}];
5491: } elsif ($on eq 'number') {
5492: $answer=$args->{'response'}+1;
5493: if ($answer == 10) { $answer = '0'; }
5494: } else {
5495: substr($answer,$args->{'response'},1)=$on;
5496: }
5497: &scan_data($scan_data,
5498: "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
5499: }
5500: my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
5501: substr($line,$where-1,$length)=$answer;
5502: }
5503: return $line;
5504: }
5505:
5506: =pod
5507:
5508: =item scan_data
5509:
5510: Edit or look up an item in the scan_data hash.
5511:
5512: Arguments:
5513: $scan_data - The hash (see scantron_getfile)
5514: $key - shorthand of the key to edit (actual key is
5515: scantronfilename_key).
5516: $data - New value of the hash entry.
5517: $delete - If true, the entry is removed from the hash.
5518:
5519: Returns:
5520: The new value of the hash table field (undefined if deleted).
5521:
5522: =cut
5523:
5524:
5525: sub scan_data {
5526: my ($scan_data,$key,$value,$delete)=@_;
5527: my $filename=$env{'form.scantron_selectfile'};
5528: if (defined($value)) {
5529: $scan_data->{$filename.'_'.$key} = $value;
5530: }
5531: if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
5532: return $scan_data->{$filename.'_'.$key};
5533: }
5534:
5535: # ----- These first few routines are general use routines.----
5536:
5537: # Return the number of occurences of a pattern in a string.
5538:
5539: sub occurence_count {
5540: my ($string, $pattern) = @_;
5541:
5542: my @matches = ($string =~ /$pattern/g);
5543:
5544: return scalar(@matches);
5545: }
5546:
5547:
5548: # Take a string known to have digits and convert all the
5549: # digits into letters in the range J,A..I.
5550:
5551: sub digits_to_letters {
5552: my ($input) = @_;
5553:
5554: my @alphabet = ('J', 'A'..'I');
5555:
5556: my @input = split(//, $input);
5557: my $output ='';
5558: for (my $i = 0; $i < scalar(@input); $i++) {
5559: if ($input[$i] =~ /\d/) {
5560: $output .= $alphabet[$input[$i]];
5561: } else {
5562: $output .= $input[$i];
5563: }
5564: }
5565: return $output;
5566: }
5567:
5568: =pod
5569:
5570: =item scantron_parse_scanline
5571:
5572: Decodes a scanline from the selected scantron file
5573:
5574: Arguments:
5575: line - The text of the scantron file line to process
5576: whichline - Line number
5577: scantron_config - Hash describing the format of the scantron lines.
5578: scan_data - Hash of extra information about the scanline
5579: (see scantron_getfile for more information)
5580: just_header - True if should not process question answers but only
5581: the stuff to the left of the answers.
5582: Returns:
5583: Hash containing the result of parsing the scanline
5584:
5585: Keys are all proceeded by the string 'scantron.'
5586:
5587: CODE - the CODE in use for this scanline
5588: useCODE - 1 if the CODE is invalid but it usage has been forced
5589: by the operator
5590: CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
5591: CODEs were selected, but the usage has been
5592: forced by the operator
5593: ID - student/employee ID
5594: PaperID - if used, the ID number printed on the sheet when the
5595: paper was scanned
5596: FirstName - first name from the sheet
5597: LastName - last name from the sheet
5598:
5599: if just_header was not true these key may also exist
5600:
5601: missingerror - a list of bubble ranges that are considered to be answers
5602: to a single question that don't have any bubbles filled in.
5603: Of the form questionnumber:firstbubblenumber:count.
5604: doubleerror - a list of bubble ranges that are considered to be answers
5605: to a single question that have more than one bubble filled in.
5606: Of the form questionnumber::firstbubblenumber:count
5607:
5608: In the above, count is the number of bubble responses in the
5609: input line needed to represent the possible answers to the question.
5610: e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
5611: per line would have count = 2.
5612:
5613: maxquest - the number of the last bubble line that was parsed
5614:
5615: (<number> starts at 1)
5616: <number>.answer - zero or more letters representing the selected
5617: letters from the scanline for the bubble line
5618: <number>.
5619: if blank there was either no bubble or there where
5620: multiple bubbles, (consult the keys missingerror and
5621: doubleerror if this is an error condition)
5622:
5623: =cut
5624:
5625: sub scantron_parse_scanline {
5626: my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
5627:
5628: my %record;
5629: my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
5630: my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos); # Answers
5631: my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # earlier stuff
5632: if (!($$scantron_config{'CODElocation'} eq 0 ||
5633: $$scantron_config{'CODElocation'} eq 'none')) {
5634: if ($$scantron_config{'CODElocation'} < 0 ||
5635: $$scantron_config{'CODElocation'} eq 'letter' ||
5636: $$scantron_config{'CODElocation'} eq 'number') {
5637: $record{'scantron.CODE'}=substr($data,
5638: $$scantron_config{'CODEstart'}-1,
5639: $$scantron_config{'CODElength'});
5640: if (&scan_data($scan_data,"$whichline.useCODE")) {
5641: $record{'scantron.useCODE'}=1;
5642: }
5643: if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
5644: $record{'scantron.CODE_ignore_dup'}=1;
5645: }
5646: } else {
5647: #FIXME interpret first N questions
5648: }
5649: }
5650: $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
5651: $$scantron_config{'IDlength'});
5652: $record{'scantron.PaperID'}=
5653: substr($data,$$scantron_config{'PaperID'}-1,
5654: $$scantron_config{'PaperIDlength'});
5655: $record{'scantron.FirstName'}=
5656: substr($data,$$scantron_config{'FirstName'}-1,
5657: $$scantron_config{'FirstNamelength'});
5658: $record{'scantron.LastName'}=
5659: substr($data,$$scantron_config{'LastName'}-1,
5660: $$scantron_config{'LastNamelength'});
5661: if ($just_header) { return \%record; }
5662:
5663: my @alphabet=('A'..'Z');
5664: my $questnum=0;
5665: my $ansnum =1; # Multiple 'answer lines'/question.
5666:
5667: chomp($questions); # Get rid of any trailing \n.
5668: $questions =~ s/\r$//; # Get rid of trailing \r too (MAC or Win uploads).
5669: while (length($questions)) {
5670: my $answers_needed = $bubble_lines_per_response{$questnum};
5671: my $answer_length = ($$scantron_config{'Qlength'} * $answers_needed)
5672: || 1;
5673: $questnum++;
5674: my $quest_id = $questnum;
5675: my $currentquest = substr($questions,0,$answer_length);
5676: $questions = substr($questions,$answer_length);
5677: if (length($currentquest) < $answer_length) { next; }
5678:
5679: if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
5680: my $subquestnum = 1;
5681: my $subquestions = $currentquest;
5682: my @subanswers_needed =
5683: split(/,/,$subdivided_bubble_lines{$questnum-1});
5684: foreach my $subans (@subanswers_needed) {
5685: my $subans_length =
5686: ($$scantron_config{'Qlength'} * $subans) || 1;
5687: my $currsubquest = substr($subquestions,0,$subans_length);
5688: $subquestions = substr($subquestions,$subans_length);
5689: $quest_id = "$questnum.$subquestnum";
5690: if (($$scantron_config{'Qon'} eq 'letter') ||
5691: ($$scantron_config{'Qon'} eq 'number')) {
5692: $ansnum = &scantron_validator_lettnum($ansnum,
5693: $questnum,$quest_id,$subans,$currsubquest,$whichline,
5694: \@alphabet,\%record,$scantron_config,$scan_data);
5695: } else {
5696: $ansnum = &scantron_validator_positional($ansnum,
5697: $questnum,$quest_id,$subans,$currsubquest,$whichline, \@alphabet,\%record,$scantron_config,$scan_data);
5698: }
5699: $subquestnum ++;
5700: }
5701: } else {
5702: if (($$scantron_config{'Qon'} eq 'letter') ||
5703: ($$scantron_config{'Qon'} eq 'number')) {
5704: $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
5705: $quest_id,$answers_needed,$currentquest,$whichline,
5706: \@alphabet,\%record,$scantron_config,$scan_data);
5707: } else {
5708: $ansnum = &scantron_validator_positional($ansnum,$questnum,
5709: $quest_id,$answers_needed,$currentquest,$whichline,
5710: \@alphabet,\%record,$scantron_config,$scan_data);
5711: }
5712: }
5713: }
5714: $record{'scantron.maxquest'}=$questnum;
5715: return \%record;
5716: }
5717:
5718: sub scantron_validator_lettnum {
5719: my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
5720: $alphabet,$record,$scantron_config,$scan_data) = @_;
5721:
5722: # Qon 'letter' implies for each slot in currquest we have:
5723: # ? or * for doubles, a letter in A-Z for a bubble, and
5724: # about anything else (esp. a value of Qoff) for missing
5725: # bubbles.
5726: #
5727: # Qon 'number' implies each slot gives a digit that indexes the
5728: # bubbles filled, or Qoff, or a non-number for unbubbled lines,
5729: # and * or ? for double bubbles on a single line.
5730: #
5731:
5732: my $matchon;
5733: if ($$scantron_config{'Qon'} eq 'letter') {
5734: $matchon = '[A-Z]';
5735: } elsif ($$scantron_config{'Qon'} eq 'number') {
5736: $matchon = '\d';
5737: }
5738: my $occurrences = 0;
5739: if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
5740: ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
5741: ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
5742: ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
5743: ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
5744: ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
5745: my @singlelines = split('',$currquest);
5746: foreach my $entry (@singlelines) {
5747: $occurrences = &occurence_count($entry,$matchon);
5748: if ($occurrences > 1) {
5749: last;
5750: }
5751: }
5752: } else {
5753: $occurrences = &occurence_count($currquest,$matchon);
5754: }
5755: if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
5756: push(@{$record->{'scantron.doubleerror'}},$quest_id);
5757: for (my $ans=0; $ans<$answers_needed; $ans++) {
5758: my $bubble = substr($currquest,$ans,1);
5759: if ($bubble =~ /$matchon/ ) {
5760: if ($$scantron_config{'Qon'} eq 'number') {
5761: if ($bubble == 0) {
5762: $bubble = 10;
5763: }
5764: $record->{"scantron.$ansnum.answer"} =
5765: $alphabet->[$bubble-1];
5766: } else {
5767: $record->{"scantron.$ansnum.answer"} = $bubble;
5768: }
5769: } else {
5770: $record->{"scantron.$ansnum.answer"}='';
5771: }
5772: $ansnum++;
5773: }
5774: } elsif (!defined($currquest)
5775: || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
5776: || (&occurence_count($currquest,$matchon) == 0)) {
5777: for (my $ans=0; $ans<$answers_needed; $ans++ ) {
5778: $record->{"scantron.$ansnum.answer"}='';
5779: $ansnum++;
5780: }
5781: if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
5782: push(@{$record->{'scantron.missingerror'}},$quest_id);
5783: }
5784: } else {
5785: if ($$scantron_config{'Qon'} eq 'number') {
5786: $currquest = &digits_to_letters($currquest);
5787: }
5788: for (my $ans=0; $ans<$answers_needed; $ans++) {
5789: my $bubble = substr($currquest,$ans,1);
5790: $record->{"scantron.$ansnum.answer"} = $bubble;
5791: $ansnum++;
5792: }
5793: }
5794: return $ansnum;
5795: }
5796:
5797: sub scantron_validator_positional {
5798: my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
5799: $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
5800:
5801: # Otherwise there's a positional notation;
5802: # each bubble line requires Qlength items, and there are filled in
5803: # bubbles for each case where there 'Qon' characters.
5804: #
5805:
5806: my @array=split($$scantron_config{'Qon'},$currquest,-1);
5807:
5808: # If the split only gives us one element.. the full length of the
5809: # answer string, no bubbles are filled in:
5810:
5811: if ($answers_needed eq '') {
5812: return;
5813: }
5814:
5815: if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
5816: for (my $ans=0; $ans<$answers_needed; $ans++ ) {
5817: $record->{"scantron.$ansnum.answer"}='';
5818: $ansnum++;
5819: }
5820: if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
5821: push(@{$record->{"scantron.missingerror"}},$quest_id);
5822: }
5823: } elsif (scalar(@array) == 2) {
5824: my $location = length($array[0]);
5825: my $line_num = int($location / $$scantron_config{'Qlength'});
5826: my $bubble = $alphabet->[$location % $$scantron_config{'Qlength'}];
5827: for (my $ans=0; $ans<$answers_needed; $ans++) {
5828: if ($ans eq $line_num) {
5829: $record->{"scantron.$ansnum.answer"} = $bubble;
5830: } else {
5831: $record->{"scantron.$ansnum.answer"} = ' ';
5832: }
5833: $ansnum++;
5834: }
5835: } else {
5836: # If there's more than one instance of a bubble character
5837: # That's a double bubble; with positional notation we can
5838: # record all the bubbles filled in as well as the
5839: # fact this response consists of multiple bubbles.
5840: #
5841: if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
5842: ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
5843: ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
5844: ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
5845: ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
5846: ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
5847: my $doubleerror = 0;
5848: while (($currquest >= $$scantron_config{'Qlength'}) &&
5849: (!$doubleerror)) {
5850: my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
5851: $currquest = substr($currquest,$$scantron_config{'Qlength'});
5852: my @currarray = split($$scantron_config{'Qon'},$currline,-1);
5853: if (length(@currarray) > 2) {
5854: $doubleerror = 1;
5855: }
5856: }
5857: if ($doubleerror) {
5858: push(@{$record->{'scantron.doubleerror'}},$quest_id);
5859: }
5860: } else {
5861: push(@{$record->{'scantron.doubleerror'}},$quest_id);
5862: }
5863: my $item = $ansnum;
5864: for (my $ans=0; $ans<$answers_needed; $ans++) {
5865: $record->{"scantron.$item.answer"} = '';
5866: $item ++;
5867: }
5868:
5869: my @ans=@array;
5870: my $i=0;
5871: my $increment = 0;
5872: while ($#ans) {
5873: $i+=length($ans[0]) + $increment;
5874: my $line = int($i/$$scantron_config{'Qlength'} + $ansnum);
5875: my $bubble = $i%$$scantron_config{'Qlength'};
5876: $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
5877: shift(@ans);
5878: $increment = 1;
5879: }
5880: $ansnum += $answers_needed;
5881: }
5882: return $ansnum;
5883: }
5884:
5885: =pod
5886:
5887: =item scantron_add_delay
5888:
5889: Adds an error message that occurred during the grading phase to a
5890: queue of messages to be shown after grading pass is complete
5891:
5892: Arguments:
5893: $delayqueue - arrary ref of hash ref of error messages
5894: $scanline - the scanline that caused the error
5895: $errormesage - the error message
5896: $errorcode - a numeric code for the error
5897:
5898: Side Effects:
5899: updates the $delayqueue to have a new hash ref of the error
5900:
5901: =cut
5902:
5903: sub scantron_add_delay {
5904: my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
5905: push(@$delayqueue,
5906: {'line' => $scanline, 'emsg' => $errormessage,
5907: 'ecode' => $errorcode }
5908: );
5909: }
5910:
5911: =pod
5912:
5913: =item scantron_find_student
5914:
5915: Finds the username for the current scanline
5916:
5917: Arguments:
5918: $scantron_record - hash result from scantron_parse_scanline
5919: $scan_data - hash of correction information
5920: (see &scantron_getfile() form more information)
5921: $idmap - hash from &username_to_idmap()
5922: $line - number of current scanline
5923:
5924: Returns:
5925: Either 'username:domain' or undef if unknown
5926:
5927: =cut
5928:
5929: sub scantron_find_student {
5930: my ($scantron_record,$scan_data,$idmap,$line)=@_;
5931: my $scanID=$$scantron_record{'scantron.ID'};
5932: if ($scanID =~ /^\s*$/) {
5933: return &scan_data($scan_data,"$line.user");
5934: }
5935: foreach my $id (keys(%$idmap)) {
5936: if (lc($id) eq lc($scanID)) {
5937: return $$idmap{$id};
5938: }
5939: }
5940: return undef;
5941: }
5942:
5943: =pod
5944:
5945: =item scantron_filter
5946:
5947: Filter sub for lonnavmaps, filters out hidden resources if ignore
5948: hidden resources was selected
5949:
5950: =cut
5951:
5952: sub scantron_filter {
5953: my ($curres)=@_;
5954:
5955: if (ref($curres) && $curres->is_problem()) {
5956: # if the user has asked to not have either hidden
5957: # or 'randomout' controlled resources to be graded
5958: # don't include them
5959: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
5960: && $curres->randomout) {
5961: return 0;
5962: }
5963: return 1;
5964: }
5965: return 0;
5966: }
5967:
5968: =pod
5969:
5970: =item scantron_process_corrections
5971:
5972: Gets correction information out of submitted form data and corrects
5973: the scanline
5974:
5975: =cut
5976:
5977: sub scantron_process_corrections {
5978: my ($r) = @_;
5979: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
5980: my ($scanlines,$scan_data)=&scantron_getfile();
5981: my $classlist=&Apache::loncoursedata::get_classlist();
5982: my $which=$env{'form.scantron_line'};
5983: my $line=&scantron_get_line($scanlines,$scan_data,$which);
5984: my ($skip,$err,$errmsg);
5985: if ($env{'form.scantron_skip_record'}) {
5986: $skip=1;
5987: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
5988: my $newstudent=$env{'form.scantron_username'}.':'.
5989: $env{'form.scantron_domain'};
5990: my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
5991: ($line,$err,$errmsg)=
5992: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
5993: 'ID',{'newid'=>$newid,
5994: 'username'=>$env{'form.scantron_username'},
5995: 'domain'=>$env{'form.scantron_domain'}});
5996: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
5997: my $resolution=$env{'form.scantron_CODE_resolution'};
5998: my $newCODE;
5999: my %args;
6000: if ($resolution eq 'use_unfound') {
6001: $newCODE='use_unfound';
6002: } elsif ($resolution eq 'use_found') {
6003: $newCODE=$env{'form.scantron_CODE_selectedvalue'};
6004: } elsif ($resolution eq 'use_typed') {
6005: $newCODE=$env{'form.scantron_CODE_newvalue'};
6006: } elsif ($resolution =~ /^use_closest_(\d+)/) {
6007: $newCODE=$env{"form.scantron_CODE_closest_$1"};
6008: }
6009: if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
6010: $args{'CODE_ignore_dup'}=1;
6011: }
6012: $args{'CODE'}=$newCODE;
6013: ($line,$err,$errmsg)=
6014: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
6015: 'CODE',\%args);
6016: } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
6017: foreach my $question (split(',',$env{'form.scantron_questions'})) {
6018: ($line,$err,$errmsg)=
6019: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
6020: $which,'answer',
6021: { 'question'=>$question,
6022: 'response'=>$env{"form.scantron_correct_Q_$question"},
6023: 'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
6024: if ($err) { last; }
6025: }
6026: }
6027: if ($err) {
6028: $r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
6029: } else {
6030: &scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
6031: &scantron_putfile($scanlines,$scan_data);
6032: }
6033: }
6034:
6035: =pod
6036:
6037: =item reset_skipping_status
6038:
6039: Forgets the current set of remember skipped scanlines (and thus
6040: reverts back to considering all lines in the
6041: scantron_skipped_<filename> file)
6042:
6043: =cut
6044:
6045: sub reset_skipping_status {
6046: my ($scanlines,$scan_data)=&scantron_getfile();
6047: &scan_data($scan_data,'remember_skipping',undef,1);
6048: &scantron_putfile(undef,$scan_data);
6049: }
6050:
6051: =pod
6052:
6053: =item start_skipping
6054:
6055: Marks a scanline to be skipped.
6056:
6057: =cut
6058:
6059: sub start_skipping {
6060: my ($scan_data,$i)=@_;
6061: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
6062: if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
6063: $remembered{$i}=2;
6064: } else {
6065: $remembered{$i}=1;
6066: }
6067: &scan_data($scan_data,'remember_skipping',join(':',%remembered));
6068: }
6069:
6070: =pod
6071:
6072: =item should_be_skipped
6073:
6074: Checks whether a scanline should be skipped.
6075:
6076: =cut
6077:
6078: sub should_be_skipped {
6079: my ($scanlines,$scan_data,$i)=@_;
6080: if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
6081: # not redoing old skips
6082: if ($scanlines->{'skipped'}[$i]) { return 1; }
6083: return 0;
6084: }
6085: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
6086:
6087: if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
6088: return 0;
6089: }
6090: return 1;
6091: }
6092:
6093: =pod
6094:
6095: =item remember_current_skipped
6096:
6097: Discovers what scanlines are in the scantron_skipped_<filename>
6098: file and remembers them into scan_data for later use.
6099:
6100: =cut
6101:
6102: sub remember_current_skipped {
6103: my ($scanlines,$scan_data)=&scantron_getfile();
6104: my %to_remember;
6105: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6106: if ($scanlines->{'skipped'}[$i]) {
6107: $to_remember{$i}=1;
6108: }
6109: }
6110:
6111: &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
6112: &scantron_putfile(undef,$scan_data);
6113: }
6114:
6115: =pod
6116:
6117: =item check_for_error
6118:
6119: Checks if there was an error when attempting to remove a specific
6120: scantron_.. bubble sheet data file. Prints out an error if
6121: something went wrong.
6122:
6123: =cut
6124:
6125: sub check_for_error {
6126: my ($r,$result)=@_;
6127: if ($result ne 'ok' && $result ne 'not_found' ) {
6128: $r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
6129: }
6130: }
6131:
6132: =pod
6133:
6134: =item scantron_warning_screen
6135:
6136: Interstitial screen to make sure the operator has selected the
6137: correct options before we start the validation phase.
6138:
6139: =cut
6140:
6141: sub scantron_warning_screen {
6142: my ($button_text)=@_;
6143: my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
6144: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6145: my $CODElist;
6146: if ($scantron_config{'CODElocation'} &&
6147: $scantron_config{'CODEstart'} &&
6148: $scantron_config{'CODElength'}) {
6149: $CODElist=$env{'form.scantron_CODElist'};
6150: if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
6151: $CODElist=
6152: '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
6153: $env{'form.scantron_CODElist'}.'</tt></td></tr>';
6154: }
6155: return ('
6156: <p>
6157: <span class="LC_warning">
6158: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
6159: </p>
6160: <table>
6161: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
6162: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
6163: '.$CODElist.'
6164: </table>
6165: <br />
6166: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
6167: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
6168:
6169: <br />
6170: ');
6171: }
6172:
6173: =pod
6174:
6175: =item scantron_do_warning
6176:
6177: Check if the operator has picked something for all required
6178: fields. Error out if something is missing.
6179:
6180: =cut
6181:
6182: sub scantron_do_warning {
6183: my ($r,$symb)=@_;
6184: if (!$symb) {return '';}
6185: my $default_form_data=&defaultFormData($symb);
6186: $r->print(&scantron_form_start().$default_form_data);
6187: if ( $env{'form.selectpage'} eq '' ||
6188: $env{'form.scantron_selectfile'} eq '' ||
6189: $env{'form.scantron_format'} eq '' ) {
6190: $r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
6191: if ( $env{'form.selectpage'} eq '') {
6192: $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
6193: }
6194: if ( $env{'form.scantron_selectfile'} eq '') {
6195: $r->print('<p><span class="LC_error">'.&mt('You have not selected a file that contains the student\'s response data.').'</span></p>');
6196: }
6197: if ( $env{'form.scantron_format'} eq '') {
6198: $r->print('<p><span class="LC_error">'.&mt('You have not selected a the format of the student\'s response data.').'</span></p>');
6199: }
6200: } else {
6201: my $warning=&scantron_warning_screen('Grading: Validate Records');
6202: $r->print('
6203: '.$warning.'
6204: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
6205: <input type="hidden" name="command" value="scantron_validate" />
6206: ');
6207: }
6208: $r->print("</form><br />");
6209: return '';
6210: }
6211:
6212: =pod
6213:
6214: =item scantron_form_start
6215:
6216: html hidden input for remembering all selected grading options
6217:
6218: =cut
6219:
6220: sub scantron_form_start {
6221: my ($max_bubble)=@_;
6222: my $result= <<SCANTRONFORM;
6223: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
6224: <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
6225: <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
6226: <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
6227: <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
6228: <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
6229: <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
6230: <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
6231: <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
6232: <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
6233: SCANTRONFORM
6234:
6235: my $line = 0;
6236: while (defined($env{"form.scantron.bubblelines.$line"})) {
6237: my $chunk =
6238: '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
6239: $chunk .=
6240: '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
6241: $chunk .=
6242: '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
6243: $chunk .=
6244: '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
6245: $result .= $chunk;
6246: $line++;
6247: }
6248: return $result;
6249: }
6250:
6251: =pod
6252:
6253: =item scantron_validate_file
6254:
6255: Dispatch routine for doing validation of a bubble sheet data file.
6256:
6257: Also processes any necessary information resets that need to
6258: occur before validation begins (ignore previous corrections,
6259: restarting the skipped records processing)
6260:
6261: =cut
6262:
6263: sub scantron_validate_file {
6264: my ($r,$symb) = @_;
6265: if (!$symb) {return '';}
6266: my $default_form_data=&defaultFormData($symb);
6267:
6268: # do the detection of only doing skipped records first befroe we delete
6269: # them when doing the corrections reset
6270: if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
6271: &reset_skipping_status();
6272: }
6273: if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
6274: &remember_current_skipped();
6275: $env{'form.scantron_options_redo'}='redo_skipped_ready';
6276: }
6277:
6278: if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
6279: &check_for_error($r,&scantron_remove_file('corrected'));
6280: &check_for_error($r,&scantron_remove_file('skipped'));
6281: &check_for_error($r,&scantron_remove_scan_data());
6282: $env{'form.scantron_options_ignore'}='done';
6283: }
6284:
6285: if ($env{'form.scantron_corrections'}) {
6286: &scantron_process_corrections($r);
6287: }
6288: $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
6289: #get the student pick code ready
6290: $r->print(&Apache::loncommon::studentbrowser_javascript());
6291: my $nav_error;
6292: my $max_bubble=&scantron_get_maxbubble(\$nav_error);
6293: if ($nav_error) {
6294: $r->print(&navmap_errormsg());
6295: return '';
6296: }
6297: my $result=&scantron_form_start($max_bubble).$default_form_data;
6298: $r->print($result);
6299:
6300: my @validate_phases=( 'sequence',
6301: 'ID',
6302: 'CODE',
6303: 'doublebubble',
6304: 'missingbubbles');
6305: if (!$env{'form.validatepass'}) {
6306: $env{'form.validatepass'} = 0;
6307: }
6308: my $currentphase=$env{'form.validatepass'};
6309:
6310:
6311: my $stop=0;
6312: while (!$stop && $currentphase < scalar(@validate_phases)) {
6313: $r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
6314: $r->rflush();
6315: my $which="scantron_validate_".$validate_phases[$currentphase];
6316: {
6317: no strict 'refs';
6318: ($stop,$currentphase)=&$which($r,$currentphase);
6319: }
6320: }
6321: if (!$stop) {
6322: my $warning=&scantron_warning_screen('Start Grading');
6323: $r->print(&mt('Validation process complete.').'<br />'.
6324: $warning.
6325: &mt('Perform verification for each student after storage of submissions?').
6326: ' <span class="LC_nobreak"><label>'.
6327: '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
6328: (' 'x3).'<label>'.
6329: '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
6330: '</label></span><br />'.
6331: &mt('Grading will take longer if you use verification.').'<br />'.
6332: &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
6333: '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
6334: '<input type="hidden" name="command" value="scantron_process" />'."\n");
6335: } else {
6336: $r->print('<input type="hidden" name="command" value="scantron_validate" />');
6337: $r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
6338: }
6339: if ($stop) {
6340: if ($validate_phases[$currentphase] eq 'sequence') {
6341: $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' → " />');
6342: $r->print(' '.&mt('this error').' <br />');
6343:
6344: $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
6345: } else {
6346: if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
6347: $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' →" onclick="javascript:verify_bubble_radio(this.form)" />');
6348: } else {
6349: $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' →" />');
6350: }
6351: $r->print(' '.&mt('using corrected info').' <br />');
6352: $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
6353: $r->print(" ".&mt("this scanline saving it for later."));
6354: }
6355: }
6356: $r->print(" </form><br />");
6357: return '';
6358: }
6359:
6360:
6361: =pod
6362:
6363: =item scantron_remove_file
6364:
6365: Removes the requested bubble sheet data file, makes sure that
6366: scantron_original_<filename> is never removed
6367:
6368:
6369: =cut
6370:
6371: sub scantron_remove_file {
6372: my ($which)=@_;
6373: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6374: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6375: my $file='scantron_';
6376: if ($which eq 'corrected' || $which eq 'skipped') {
6377: $file.=$which.'_';
6378: } else {
6379: return 'refused';
6380: }
6381: $file.=$env{'form.scantron_selectfile'};
6382: return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
6383: }
6384:
6385:
6386: =pod
6387:
6388: =item scantron_remove_scan_data
6389:
6390: Removes all scan_data correction for the requested bubble sheet
6391: data file. (In the case that both the are doing skipped records we need
6392: to remember the old skipped lines for the time being so that element
6393: persists for a while.)
6394:
6395: =cut
6396:
6397: sub scantron_remove_scan_data {
6398: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6399: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6400: my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
6401: my @todelete;
6402: my $filename=$env{'form.scantron_selectfile'};
6403: foreach my $key (@keys) {
6404: if ($key=~/^\Q$filename\E_/) {
6405: if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
6406: $key=~/remember_skipping/) {
6407: next;
6408: }
6409: push(@todelete,$key);
6410: }
6411: }
6412: my $result;
6413: if (@todelete) {
6414: $result = &Apache::lonnet::del('nohist_scantrondata',
6415: \@todelete,$cdom,$cname);
6416: } else {
6417: $result = 'ok';
6418: }
6419: return $result;
6420: }
6421:
6422:
6423: =pod
6424:
6425: =item scantron_getfile
6426:
6427: Fetches the requested bubble sheet data file (all 3 versions), and
6428: the scan_data hash
6429:
6430: Arguments:
6431: None
6432:
6433: Returns:
6434: 2 hash references
6435:
6436: - first one has
6437: orig -
6438: corrected -
6439: skipped - each of which points to an array ref of the specified
6440: file broken up into individual lines
6441: count - number of scanlines
6442:
6443: - second is the scan_data hash possible keys are
6444: ($number refers to scanline numbered $number and thus the key affects
6445: only that scanline
6446: $bubline refers to the specific bubble line element and the aspects
6447: refers to that specific bubble line element)
6448:
6449: $number.user - username:domain to use
6450: $number.CODE_ignore_dup
6451: - ignore the duplicate CODE error
6452: $number.useCODE
6453: - use the CODE in the scanline as is
6454: $number.no_bubble.$bubline
6455: - it is valid that there is no bubbled in bubble
6456: at $number $bubline
6457: remember_skipping
6458: - a frozen hash containing keys of $number and values
6459: of either
6460: 1 - we are on a 'do skipped records pass' and plan
6461: on processing this line
6462: 2 - we are on a 'do skipped records pass' and this
6463: scanline has been marked to skip yet again
6464:
6465: =cut
6466:
6467: sub scantron_getfile {
6468: #FIXME really would prefer a scantron directory
6469: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6470: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6471: my $lines;
6472: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
6473: 'scantron_orig_'.$env{'form.scantron_selectfile'});
6474: my %scanlines;
6475: $scanlines{'orig'}=[(split("\n",$lines,-1))];
6476: my $temp=$scanlines{'orig'};
6477: $scanlines{'count'}=$#$temp;
6478:
6479: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
6480: 'scantron_corrected_'.$env{'form.scantron_selectfile'});
6481: if ($lines eq '-1') {
6482: $scanlines{'corrected'}=[];
6483: } else {
6484: $scanlines{'corrected'}=[(split("\n",$lines,-1))];
6485: }
6486: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
6487: 'scantron_skipped_'.$env{'form.scantron_selectfile'});
6488: if ($lines eq '-1') {
6489: $scanlines{'skipped'}=[];
6490: } else {
6491: $scanlines{'skipped'}=[(split("\n",$lines,-1))];
6492: }
6493: my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
6494: if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
6495: my %scan_data = @tmp;
6496: return (\%scanlines,\%scan_data);
6497: }
6498:
6499: =pod
6500:
6501: =item lonnet_putfile
6502:
6503: Wrapper routine to call &Apache::lonnet::finishuserfileupload
6504:
6505: Arguments:
6506: $contents - data to store
6507: $filename - filename to store $contents into
6508:
6509: Returns:
6510: result value from &Apache::lonnet::finishuserfileupload
6511:
6512: =cut
6513:
6514: sub lonnet_putfile {
6515: my ($contents,$filename)=@_;
6516: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
6517: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6518: $env{'form.sillywaytopassafilearound'}=$contents;
6519: &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
6520:
6521: }
6522:
6523: =pod
6524:
6525: =item scantron_putfile
6526:
6527: Stores the current version of the bubble sheet data files, and the
6528: scan_data hash. (Does not modify the original version only the
6529: corrected and skipped versions.
6530:
6531: Arguments:
6532: $scanlines - hash ref that looks like the first return value from
6533: &scantron_getfile()
6534: $scan_data - hash ref that looks like the second return value from
6535: &scantron_getfile()
6536:
6537: =cut
6538:
6539: sub scantron_putfile {
6540: my ($scanlines,$scan_data) = @_;
6541: #FIXME really would prefer a scantron directory
6542: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6543: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6544: if ($scanlines) {
6545: my $prefix='scantron_';
6546: # no need to update orig, shouldn't change
6547: # &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
6548: # $env{'form.scantron_selectfile'});
6549: &lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
6550: $prefix.'corrected_'.
6551: $env{'form.scantron_selectfile'});
6552: &lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
6553: $prefix.'skipped_'.
6554: $env{'form.scantron_selectfile'});
6555: }
6556: &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
6557: }
6558:
6559: =pod
6560:
6561: =item scantron_get_line
6562:
6563: Returns the correct version of the scanline
6564:
6565: Arguments:
6566: $scanlines - hash ref that looks like the first return value from
6567: &scantron_getfile()
6568: $scan_data - hash ref that looks like the second return value from
6569: &scantron_getfile()
6570: $i - number of the requested line (starts at 0)
6571:
6572: Returns:
6573: A scanline, (either the original or the corrected one if it
6574: exists), or undef if the requested scanline should be
6575: skipped. (Either because it's an skipped scanline, or it's an
6576: unskipped scanline and we are not doing a 'do skipped scanlines'
6577: pass.
6578:
6579: =cut
6580:
6581: sub scantron_get_line {
6582: my ($scanlines,$scan_data,$i)=@_;
6583: if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
6584: #if ($scanlines->{'skipped'}[$i]) { return undef; }
6585: if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
6586: return $scanlines->{'orig'}[$i];
6587: }
6588:
6589: =pod
6590:
6591: =item scantron_todo_count
6592:
6593: Counts the number of scanlines that need processing.
6594:
6595: Arguments:
6596: $scanlines - hash ref that looks like the first return value from
6597: &scantron_getfile()
6598: $scan_data - hash ref that looks like the second return value from
6599: &scantron_getfile()
6600:
6601: Returns:
6602: $count - number of scanlines to process
6603:
6604: =cut
6605:
6606: sub get_todo_count {
6607: my ($scanlines,$scan_data)=@_;
6608: my $count=0;
6609: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6610: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6611: if ($line=~/^[\s\cz]*$/) { next; }
6612: $count++;
6613: }
6614: return $count;
6615: }
6616:
6617: =pod
6618:
6619: =item scantron_put_line
6620:
6621: Updates the 'corrected' or 'skipped' versions of the bubble sheet
6622: data file.
6623:
6624: Arguments:
6625: $scanlines - hash ref that looks like the first return value from
6626: &scantron_getfile()
6627: $scan_data - hash ref that looks like the second return value from
6628: &scantron_getfile()
6629: $i - line number to update
6630: $newline - contents of the updated scanline
6631: $skip - if true make the line for skipping and update the
6632: 'skipped' file
6633:
6634: =cut
6635:
6636: sub scantron_put_line {
6637: my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
6638: if ($skip) {
6639: $scanlines->{'skipped'}[$i]=$newline;
6640: &start_skipping($scan_data,$i);
6641: return;
6642: }
6643: $scanlines->{'corrected'}[$i]=$newline;
6644: }
6645:
6646: =pod
6647:
6648: =item scantron_clear_skip
6649:
6650: Remove a line from the 'skipped' file
6651:
6652: Arguments:
6653: $scanlines - hash ref that looks like the first return value from
6654: &scantron_getfile()
6655: $scan_data - hash ref that looks like the second return value from
6656: &scantron_getfile()
6657: $i - line number to update
6658:
6659: =cut
6660:
6661: sub scantron_clear_skip {
6662: my ($scanlines,$scan_data,$i)=@_;
6663: if (exists($scanlines->{'skipped'}[$i])) {
6664: undef($scanlines->{'skipped'}[$i]);
6665: return 1;
6666: }
6667: return 0;
6668: }
6669:
6670: =pod
6671:
6672: =item scantron_filter_not_exam
6673:
6674: Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
6675: filter out resources that are not marked as 'exam' mode
6676:
6677: =cut
6678:
6679: sub scantron_filter_not_exam {
6680: my ($curres)=@_;
6681:
6682: if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
6683: # if the user has asked to not have either hidden
6684: # or 'randomout' controlled resources to be graded
6685: # don't include them
6686: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
6687: && $curres->randomout) {
6688: return 0;
6689: }
6690: return 1;
6691: }
6692: return 0;
6693: }
6694:
6695: =pod
6696:
6697: =item scantron_validate_sequence
6698:
6699: Validates the selected sequence, checking for resource that are
6700: not set to exam mode.
6701:
6702: =cut
6703:
6704: sub scantron_validate_sequence {
6705: my ($r,$currentphase) = @_;
6706:
6707: my $navmap=Apache::lonnavmaps::navmap->new();
6708: unless (ref($navmap)) {
6709: $r->print(&navmap_errormsg());
6710: return (1,$currentphase);
6711: }
6712: my (undef,undef,$sequence)=
6713: &Apache::lonnet::decode_symb($env{'form.selectpage'});
6714:
6715: my $map=$navmap->getResourceByUrl($sequence);
6716:
6717: $r->print('<input type="hidden" name="validate_sequence_exam"
6718: value="ignore" />');
6719: if ($env{'form.validate_sequence_exam'} ne 'ignore') {
6720: my @resources=
6721: $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
6722: if (@resources) {
6723: $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>");
6724: return (1,$currentphase);
6725: }
6726: }
6727:
6728: return (0,$currentphase+1);
6729: }
6730:
6731:
6732:
6733: sub scantron_validate_ID {
6734: my ($r,$currentphase) = @_;
6735:
6736: #get student info
6737: my $classlist=&Apache::loncoursedata::get_classlist();
6738: my %idmap=&username_to_idmap($classlist);
6739:
6740: #get scantron line setup
6741: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6742: my ($scanlines,$scan_data)=&scantron_getfile();
6743:
6744: my $nav_error;
6745: &scantron_get_maxbubble(\$nav_error); # parse needs the bubble_lines.. array.
6746: if ($nav_error) {
6747: $r->print(&navmap_errormsg());
6748: return(1,$currentphase);
6749: }
6750:
6751: my %found=('ids'=>{},'usernames'=>{});
6752: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6753: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6754: if ($line=~/^[\s\cz]*$/) { next; }
6755: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6756: $scan_data);
6757: my $id=$$scan_record{'scantron.ID'};
6758: my $found;
6759: foreach my $checkid (keys(%idmap)) {
6760: if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
6761: }
6762: if ($found) {
6763: my $username=$idmap{$found};
6764: if ($found{'ids'}{$found}) {
6765: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6766: $line,'duplicateID',$found);
6767: return(1,$currentphase);
6768: } elsif ($found{'usernames'}{$username}) {
6769: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6770: $line,'duplicateID',$username);
6771: return(1,$currentphase);
6772: }
6773: #FIXME store away line we previously saw the ID on to use above
6774: $found{'ids'}{$found}++;
6775: $found{'usernames'}{$username}++;
6776: } else {
6777: if ($id =~ /^\s*$/) {
6778: my $username=&scan_data($scan_data,"$i.user");
6779: if (defined($username) && $found{'usernames'}{$username}) {
6780: &scantron_get_correction($r,$i,$scan_record,
6781: \%scantron_config,
6782: $line,'duplicateID',$username);
6783: return(1,$currentphase);
6784: } elsif (!defined($username)) {
6785: &scantron_get_correction($r,$i,$scan_record,
6786: \%scantron_config,
6787: $line,'incorrectID');
6788: return(1,$currentphase);
6789: }
6790: $found{'usernames'}{$username}++;
6791: } else {
6792: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6793: $line,'incorrectID');
6794: return(1,$currentphase);
6795: }
6796: }
6797: }
6798:
6799: return (0,$currentphase+1);
6800: }
6801:
6802:
6803: sub scantron_get_correction {
6804: my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
6805: #FIXME in the case of a duplicated ID the previous line, probably need
6806: #to show both the current line and the previous one and allow skipping
6807: #the previous one or the current one
6808:
6809: if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
6810: $r->print("<p>".&mt("<b>An error was detected ($error)</b>".
6811: " for PaperID <tt>[_1]</tt>",
6812: $$scan_record{'scantron.PaperID'})."</p> \n");
6813: } else {
6814: $r->print("<p>".&mt("<b>An error was detected ($error)</b>".
6815: " in scanline [_1] <pre>[_2]</pre>",
6816: $i,$line)."</p> \n");
6817: }
6818: my $message="<p>".&mt("The ID on the form is <tt>[_1]</tt><br />".
6819: "The name on the paper is [_2],[_3]",
6820: $$scan_record{'scantron.ID'},
6821: $$scan_record{'scantron.LastName'},
6822: $$scan_record{'scantron.FirstName'})."</p>";
6823:
6824: $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
6825: $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
6826: # Array populated for doublebubble or
6827: my @lines_to_correct; # missingbubble errors to build javascript
6828: # to validate radio button checking
6829:
6830: if ($error =~ /ID$/) {
6831: if ($error eq 'incorrectID') {
6832: $r->print("<p>".&mt("The encoded ID is not in the classlist").
6833: "</p>\n");
6834: } elsif ($error eq 'duplicateID') {
6835: $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
6836: }
6837: $r->print($message);
6838: $r->print("<p>".&mt("How should I handle this?")." <br /> \n");
6839: $r->print("\n<ul><li> ");
6840: #FIXME it would be nice if this sent back the user ID and
6841: #could do partial userID matches
6842: $r->print(&Apache::loncommon::selectstudent_link('scantronupload',
6843: 'scantron_username','scantron_domain'));
6844: $r->print(": <input type='text' name='scantron_username' value='' />");
6845: $r->print("\n@".
6846: &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
6847:
6848: $r->print('</li>');
6849: } elsif ($error =~ /CODE$/) {
6850: if ($error eq 'incorrectCODE') {
6851: $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
6852: } elsif ($error eq 'duplicateCODE') {
6853: $r->print("<p>".&mt("The encoded CODE has also been used by a previous paper [_1], and CODEs are supposed to be unique.",join(', ',@{$arg}))."</p>\n");
6854: }
6855: $r->print("<p>".&mt("The CODE on the form is <tt>'[_1]'</tt>",
6856: $$scan_record{'scantron.CODE'})."<br />\n");
6857: $r->print($message);
6858: $r->print("<p>".&mt("How should I handle this?")." <br /> \n");
6859: $r->print("\n<br /> ");
6860: my $i=0;
6861: if ($error eq 'incorrectCODE'
6862: && $$scan_record{'scantron.CODE'}=~/\S/ ) {
6863: my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
6864: if ($closest > 0) {
6865: foreach my $testcode (@{$closest}) {
6866: my $checked='';
6867: if (!$i) { $checked=' checked="checked"'; }
6868: $r->print("
6869: <label>
6870: <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
6871: ".&mt("Use the similar CODE [_1] instead.",
6872: "<b><tt>".$testcode."</tt></b>")."
6873: </label>
6874: <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
6875: $r->print("\n<br />");
6876: $i++;
6877: }
6878: }
6879: }
6880: if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
6881: my $checked; if (!$i) { $checked=' checked="checked"'; }
6882: $r->print("
6883: <label>
6884: <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
6885: ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
6886: "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
6887: </label>");
6888: $r->print("\n<br />");
6889: }
6890:
6891: $r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
6892: function change_radio(field) {
6893: var slct=document.scantronupload.scantron_CODE_resolution;
6894: var i;
6895: for (i=0;i<slct.length;i++) {
6896: if (slct[i].value==field) { slct[i].checked=true; }
6897: }
6898: }
6899: ENDSCRIPT
6900: my $href="/adm/pickcode?".
6901: "form=".&escape("scantronupload").
6902: "&scantron_format=".&escape($env{'form.scantron_format'}).
6903: "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
6904: "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
6905: "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
6906: if ($env{'form.scantron_CODElist'} =~ /\S/) {
6907: $r->print("
6908: <label>
6909: <input type='radio' name='scantron_CODE_resolution' value='use_found' />
6910: ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
6911: "<a target='_blank' href='$href'>","</a>")."
6912: </label>
6913: ".&mt("Selected CODE is [_1]",'<input readonly="readonly" type="text" size="8" name="scantron_CODE_selectedvalue" onfocus="javascript:change_radio(\'use_found\')" onchange="javascript:change_radio(\'use_found\')" />'));
6914: $r->print("\n<br />");
6915: }
6916: $r->print("
6917: <label>
6918: <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
6919: ".&mt("Use [_1] as the CODE.",
6920: "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
6921: $r->print("\n<br /><br />");
6922: } elsif ($error eq 'doublebubble') {
6923: $r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
6924:
6925: # The form field scantron_questions is acutally a list of line numbers.
6926: # represented by this form so:
6927:
6928: my $line_list = &questions_to_line_list($arg);
6929:
6930: $r->print('<input type="hidden" name="scantron_questions" value="'.
6931: $line_list.'" />');
6932: $r->print($message);
6933: $r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
6934: foreach my $question (@{$arg}) {
6935: my @linenums = &prompt_for_corrections($r,$question,$scan_config,
6936: $scan_record, $error);
6937: push(@lines_to_correct,@linenums);
6938: }
6939: $r->print(&verify_bubbles_checked(@lines_to_correct));
6940: } elsif ($error eq 'missingbubble') {
6941: $r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
6942: $r->print($message);
6943: $r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
6944: $r->print(&mt("Some questions have no scanned bubbles.")."\n");
6945:
6946: # The form field scantron_questions is actually a list of line numbers not
6947: # a list of question numbers. Therefore:
6948: #
6949:
6950: my $line_list = &questions_to_line_list($arg);
6951:
6952: $r->print('<input type="hidden" name="scantron_questions" value="'.
6953: $line_list.'" />');
6954: foreach my $question (@{$arg}) {
6955: my @linenums = &prompt_for_corrections($r,$question,$scan_config,
6956: $scan_record, $error);
6957: push(@lines_to_correct,@linenums);
6958: }
6959: $r->print(&verify_bubbles_checked(@lines_to_correct));
6960: } else {
6961: $r->print("\n<ul>");
6962: }
6963: $r->print("\n</li></ul>");
6964: }
6965:
6966: sub verify_bubbles_checked {
6967: my (@ansnums) = @_;
6968: my $ansnumstr = join('","',@ansnums);
6969: my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
6970: my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
6971: function verify_bubble_radio(form) {
6972: var ansnumArray = new Array ("$ansnumstr");
6973: var need_bubble_count = 0;
6974: for (var i=0; i<ansnumArray.length; i++) {
6975: if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
6976: var bubble_picked = 0;
6977: for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
6978: if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
6979: bubble_picked = 1;
6980: }
6981: }
6982: if (bubble_picked == 0) {
6983: need_bubble_count ++;
6984: }
6985: }
6986: }
6987: if (need_bubble_count) {
6988: alert("$warning");
6989: return;
6990: }
6991: form.submit();
6992: }
6993: ENDSCRIPT
6994: return $output;
6995: }
6996:
6997: =pod
6998:
6999: =item questions_to_line_list
7000:
7001: Converts a list of questions into a string of comma separated
7002: line numbers in the answer sheet used by the questions. This is
7003: used to fill in the scantron_questions form field.
7004:
7005: Arguments:
7006: questions - Reference to an array of questions.
7007:
7008: =cut
7009:
7010:
7011: sub questions_to_line_list {
7012: my ($questions) = @_;
7013: my @lines;
7014:
7015: foreach my $item (@{$questions}) {
7016: my $question = $item;
7017: my ($first,$count,$last);
7018: if ($item =~ /^(\d+)\.(\d+)$/) {
7019: $question = $1;
7020: my $subquestion = $2;
7021: $first = $first_bubble_line{$question-1} + 1;
7022: my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
7023: my $subcount = 1;
7024: while ($subcount<$subquestion) {
7025: $first += $subans[$subcount-1];
7026: $subcount ++;
7027: }
7028: $count = $subans[$subquestion-1];
7029: } else {
7030: $first = $first_bubble_line{$question-1} + 1;
7031: $count = $bubble_lines_per_response{$question-1};
7032: }
7033: $last = $first+$count-1;
7034: push(@lines, ($first..$last));
7035: }
7036: return join(',', @lines);
7037: }
7038:
7039: =pod
7040:
7041: =item prompt_for_corrections
7042:
7043: Prompts for a potentially multiline correction to the
7044: user's bubbling (factors out common code from scantron_get_correction
7045: for multi and missing bubble cases).
7046:
7047: Arguments:
7048: $r - Apache request object.
7049: $question - The question number to prompt for.
7050: $scan_config - The scantron file configuration hash.
7051: $scan_record - Reference to the hash that has the the parsed scanlines.
7052: $error - Type of error
7053:
7054: Implicit inputs:
7055: %bubble_lines_per_response - Starting line numbers for each question.
7056: Numbered from 0 (but question numbers are from
7057: 1.
7058: %first_bubble_line - Starting bubble line for each question.
7059: %subdivided_bubble_lines - optionresponse, matchresponse and rankresponse
7060: type problems render as separate sub-questions,
7061: in exam mode. This hash contains a
7062: comma-separated list of the lines per
7063: sub-question.
7064: %responsetype_per_response - essayresponse, formularesponse,
7065: stringresponse, imageresponse, reactionresponse,
7066: and organicresponse type problem parts can have
7067: multiple lines per response if the weight
7068: assigned exceeds 10. In this case, only
7069: one bubble per line is permitted, but more
7070: than one line might contain bubbles, e.g.
7071: bubbling of: line 1 - J, line 2 - J,
7072: line 3 - B would assign 22 points.
7073:
7074: =cut
7075:
7076: sub prompt_for_corrections {
7077: my ($r, $question, $scan_config, $scan_record, $error) = @_;
7078: my ($current_line,$lines);
7079: my @linenums;
7080: my $questionnum = $question;
7081: if ($question =~ /^(\d+)\.(\d+)$/) {
7082: $question = $1;
7083: $current_line = $first_bubble_line{$question-1} + 1 ;
7084: my $subquestion = $2;
7085: my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
7086: my $subcount = 1;
7087: while ($subcount<$subquestion) {
7088: $current_line += $subans[$subcount-1];
7089: $subcount ++;
7090: }
7091: $lines = $subans[$subquestion-1];
7092: } else {
7093: $current_line = $first_bubble_line{$question-1} + 1 ;
7094: $lines = $bubble_lines_per_response{$question-1};
7095: }
7096: if ($lines > 1) {
7097: $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
7098: if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
7099: ($responsetype_per_response{$question-1} eq 'formularesponse') ||
7100: ($responsetype_per_response{$question-1} eq 'stringresponse') ||
7101: ($responsetype_per_response{$question-1} eq 'imageresponse') ||
7102: ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
7103: ($responsetype_per_response{$question-1} eq 'organicresponse')) {
7104: $r->print(&mt("Although this particular question type requires handgrading, the instructions for this question in the exam directed students to leave [quant,_1,line] blank on their bubblesheets.",$lines).'<br /><br />'.&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.').'<br />'.&mt('The score for this question will be a sum of the numeric values for the selected bubbles from each line, where A=1 point, B=2 points etc.').'<br />'.&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.").'<br /><br />');
7105: } else {
7106: $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
7107: }
7108: }
7109: for (my $i =0; $i < $lines; $i++) {
7110: my $selected = $$scan_record{"scantron.$current_line.answer"};
7111: &scantron_bubble_selector($r,$scan_config,$current_line,
7112: $questionnum,$error,split('', $selected));
7113: push(@linenums,$current_line);
7114: $current_line++;
7115: }
7116: if ($lines > 1) {
7117: $r->print("<hr /><br />");
7118: }
7119: return @linenums;
7120: }
7121:
7122: =pod
7123:
7124: =item scantron_bubble_selector
7125:
7126: Generates the html radiobuttons to correct a single bubble line
7127: possibly showing the existing the selected bubbles if known
7128:
7129: Arguments:
7130: $r - Apache request object
7131: $scan_config - hash from &get_scantron_config()
7132: $line - Number of the line being displayed.
7133: $questionnum - Question number (may include subquestion)
7134: $error - Type of error.
7135: @selected - Array of bubbles picked on this line.
7136:
7137: =cut
7138:
7139: sub scantron_bubble_selector {
7140: my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
7141: my $max=$$scan_config{'Qlength'};
7142:
7143: my $scmode=$$scan_config{'Qon'};
7144: if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }
7145:
7146: my @alphabet=('A'..'Z');
7147: $r->print(&Apache::loncommon::start_data_table().
7148: &Apache::loncommon::start_data_table_row());
7149: $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
7150: for (my $i=0;$i<$max+1;$i++) {
7151: $r->print("\n".'<td align="center">');
7152: if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
7153: else { $r->print(' '); }
7154: $r->print('</td>');
7155: }
7156: $r->print(&Apache::loncommon::end_data_table_row().
7157: &Apache::loncommon::start_data_table_row());
7158: for (my $i=0;$i<$max;$i++) {
7159: $r->print("\n".
7160: '<td><label><input type="radio" name="scantron_correct_Q_'.
7161: $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
7162: }
7163: my $nobub_checked = ' ';
7164: if ($error eq 'missingbubble') {
7165: $nobub_checked = ' checked = "checked" ';
7166: }
7167: $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
7168: $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
7169: '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
7170: $line.'" value="'.$questionnum.'" /></td>');
7171: $r->print(&Apache::loncommon::end_data_table_row().
7172: &Apache::loncommon::end_data_table());
7173: }
7174:
7175: =pod
7176:
7177: =item num_matches
7178:
7179: Counts the number of characters that are the same between the two arguments.
7180:
7181: Arguments:
7182: $orig - CODE from the scanline
7183: $code - CODE to match against
7184:
7185: Returns:
7186: $count - integer count of the number of same characters between the
7187: two arguments
7188:
7189: =cut
7190:
7191: sub num_matches {
7192: my ($orig,$code) = @_;
7193: my @code=split(//,$code);
7194: my @orig=split(//,$orig);
7195: my $same=0;
7196: for (my $i=0;$i<scalar(@code);$i++) {
7197: if ($code[$i] eq $orig[$i]) { $same++; }
7198: }
7199: return $same;
7200: }
7201:
7202: =pod
7203:
7204: =item scantron_get_closely_matching_CODEs
7205:
7206: Cycles through all CODEs and finds the set that has the greatest
7207: number of same characters as the provided CODE
7208:
7209: Arguments:
7210: $allcodes - hash ref returned by &get_codes()
7211: $CODE - CODE from the current scanline
7212:
7213: Returns:
7214: 2 element list
7215: - first elements is number of how closely matching the best fit is
7216: (5 means best set has 5 matching characters)
7217: - second element is an arrary ref containing the set of valid CODEs
7218: that best fit the passed in CODE
7219:
7220: =cut
7221:
7222: sub scantron_get_closely_matching_CODEs {
7223: my ($allcodes,$CODE)=@_;
7224: my @CODEs;
7225: foreach my $testcode (sort(keys(%{$allcodes}))) {
7226: push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
7227: }
7228:
7229: return ($#CODEs,$CODEs[-1]);
7230: }
7231:
7232: =pod
7233:
7234: =item get_codes
7235:
7236: Builds a hash which has keys of all of the valid CODEs from the selected
7237: set of remembered CODEs.
7238:
7239: Arguments:
7240: $old_name - name of the set of remembered CODEs
7241: $cdom - domain of the course
7242: $cnum - internal course name
7243:
7244: Returns:
7245: %allcodes - keys are the valid CODEs, values are all 1
7246:
7247: =cut
7248:
7249: sub get_codes {
7250: my ($old_name, $cdom, $cnum) = @_;
7251: if (!$old_name) {
7252: $old_name=$env{'form.scantron_CODElist'};
7253: }
7254: if (!$cdom) {
7255: $cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
7256: }
7257: if (!$cnum) {
7258: $cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
7259: }
7260: my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
7261: $cdom,$cnum);
7262: my %allcodes;
7263: if ($result{"type\0$old_name"} eq 'number') {
7264: %allcodes=map {($_,1)} split(',',$result{$old_name});
7265: } else {
7266: %allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
7267: }
7268: return %allcodes;
7269: }
7270:
7271: =pod
7272:
7273: =item scantron_validate_CODE
7274:
7275: Validates all scanlines in the selected file to not have any
7276: invalid or underspecified CODEs and that none of the codes are
7277: duplicated if this was requested.
7278:
7279: =cut
7280:
7281: sub scantron_validate_CODE {
7282: my ($r,$currentphase) = @_;
7283: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7284: if ($scantron_config{'CODElocation'} &&
7285: $scantron_config{'CODEstart'} &&
7286: $scantron_config{'CODElength'}) {
7287: if (!defined($env{'form.scantron_CODElist'})) {
7288: &FIXME_blow_up()
7289: }
7290: } else {
7291: return (0,$currentphase+1);
7292: }
7293:
7294: my %usedCODEs;
7295:
7296: my %allcodes=&get_codes();
7297:
7298: my $nav_error;
7299: &scantron_get_maxbubble(\$nav_error); # parse needs the lines per response array.
7300: if ($nav_error) {
7301: $r->print(&navmap_errormsg());
7302: return(1,$currentphase);
7303: }
7304:
7305: my ($scanlines,$scan_data)=&scantron_getfile();
7306: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7307: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7308: if ($line=~/^[\s\cz]*$/) { next; }
7309: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7310: $scan_data);
7311: my $CODE=$$scan_record{'scantron.CODE'};
7312: my $error=0;
7313: if (!&Apache::lonnet::validCODE($CODE)) {
7314: &scantron_get_correction($r,$i,$scan_record,
7315: \%scantron_config,
7316: $line,'incorrectCODE',\%allcodes);
7317: return(1,$currentphase);
7318: }
7319: if (%allcodes && !exists($allcodes{$CODE})
7320: && !$$scan_record{'scantron.useCODE'}) {
7321: &scantron_get_correction($r,$i,$scan_record,
7322: \%scantron_config,
7323: $line,'incorrectCODE',\%allcodes);
7324: return(1,$currentphase);
7325: }
7326: if (exists($usedCODEs{$CODE})
7327: && $env{'form.scantron_CODEunique'} eq 'yes'
7328: && !$$scan_record{'scantron.CODE_ignore_dup'}) {
7329: &scantron_get_correction($r,$i,$scan_record,
7330: \%scantron_config,
7331: $line,'duplicateCODE',$usedCODEs{$CODE});
7332: return(1,$currentphase);
7333: }
7334: push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
7335: }
7336: return (0,$currentphase+1);
7337: }
7338:
7339: =pod
7340:
7341: =item scantron_validate_doublebubble
7342:
7343: Validates all scanlines in the selected file to not have any
7344: bubble lines with multiple bubbles marked.
7345:
7346: =cut
7347:
7348: sub scantron_validate_doublebubble {
7349: my ($r,$currentphase) = @_;
7350: #get student info
7351: my $classlist=&Apache::loncoursedata::get_classlist();
7352: my %idmap=&username_to_idmap($classlist);
7353:
7354: #get scantron line setup
7355: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7356: my ($scanlines,$scan_data)=&scantron_getfile();
7357: my $nav_error;
7358: &scantron_get_maxbubble(\$nav_error); # parse needs the bubble line array.
7359: if ($nav_error) {
7360: $r->print(&navmap_errormsg());
7361: return(1,$currentphase);
7362: }
7363:
7364: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7365: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7366: if ($line=~/^[\s\cz]*$/) { next; }
7367: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7368: $scan_data);
7369: if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
7370: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
7371: 'doublebubble',
7372: $$scan_record{'scantron.doubleerror'});
7373: return (1,$currentphase);
7374: }
7375: return (0,$currentphase+1);
7376: }
7377:
7378:
7379: sub scantron_get_maxbubble {
7380: my ($nav_error) = @_;
7381: if (defined($env{'form.scantron_maxbubble'}) &&
7382: $env{'form.scantron_maxbubble'}) {
7383: &restore_bubble_lines();
7384: return $env{'form.scantron_maxbubble'};
7385: }
7386:
7387: my (undef, undef, $sequence) =
7388: &Apache::lonnet::decode_symb($env{'form.selectpage'});
7389:
7390: my $navmap=Apache::lonnavmaps::navmap->new();
7391: unless (ref($navmap)) {
7392: if (ref($nav_error)) {
7393: $$nav_error = 1;
7394: }
7395: return;
7396: }
7397: my $map=$navmap->getResourceByUrl($sequence);
7398: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
7399:
7400: &Apache::lonxml::clear_problem_counter();
7401:
7402: my $uname = $env{'user.name'};
7403: my $udom = $env{'user.domain'};
7404: my $cid = $env{'request.course.id'};
7405: my $total_lines = 0;
7406: %bubble_lines_per_response = ();
7407: %first_bubble_line = ();
7408: %subdivided_bubble_lines = ();
7409: %responsetype_per_response = ();
7410:
7411: my $response_number = 0;
7412: my $bubble_line = 0;
7413: foreach my $resource (@resources) {
7414: my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
7415: if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
7416: foreach my $part_id (@{$parts}) {
7417: my $lines;
7418:
7419: # TODO - make this a persistent hash not an array.
7420:
7421: # optionresponse, matchresponse and rankresponse type items
7422: # render as separate sub-questions in exam mode.
7423: if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
7424: ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
7425: ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
7426: my ($numbub,$numshown);
7427: if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
7428: if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
7429: $numbub = scalar(@{$analysis->{$part_id.'.options'}});
7430: }
7431: } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
7432: if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
7433: $numbub = scalar(@{$analysis->{$part_id.'.items'}});
7434: }
7435: } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
7436: if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
7437: $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
7438: }
7439: }
7440: if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
7441: $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
7442: }
7443: my $bubbles_per_line = 10;
7444: my $inner_bubble_lines = int($numbub/$bubbles_per_line);
7445: if (($numbub % $bubbles_per_line) != 0) {
7446: $inner_bubble_lines++;
7447: }
7448: for (my $i=0; $i<$numshown; $i++) {
7449: $subdivided_bubble_lines{$response_number} .=
7450: $inner_bubble_lines.',';
7451: }
7452: $subdivided_bubble_lines{$response_number} =~ s/,$//;
7453: $lines = $numshown * $inner_bubble_lines;
7454: } else {
7455: $lines = $analysis->{"$part_id.bubble_lines"};
7456: }
7457:
7458: $first_bubble_line{$response_number} = $bubble_line;
7459: $bubble_lines_per_response{$response_number} = $lines;
7460: $responsetype_per_response{$response_number} =
7461: $analysis->{$part_id.'.type'};
7462: $response_number++;
7463:
7464: $bubble_line += $lines;
7465: $total_lines += $lines;
7466: }
7467: }
7468: }
7469: &Apache::lonnet::delenv('scantron.');
7470:
7471: &save_bubble_lines();
7472: $env{'form.scantron_maxbubble'} =
7473: $total_lines;
7474: return $env{'form.scantron_maxbubble'};
7475: }
7476:
7477: sub scantron_validate_missingbubbles {
7478: my ($r,$currentphase) = @_;
7479: #get student info
7480: my $classlist=&Apache::loncoursedata::get_classlist();
7481: my %idmap=&username_to_idmap($classlist);
7482:
7483: #get scantron line setup
7484: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7485: my ($scanlines,$scan_data)=&scantron_getfile();
7486: my $nav_error;
7487: my $max_bubble=&scantron_get_maxbubble(\$nav_error);
7488: if ($nav_error) {
7489: return(1,$currentphase);
7490: }
7491: if (!$max_bubble) { $max_bubble=2**31; }
7492: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7493: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7494: if ($line=~/^[\s\cz]*$/) { next; }
7495: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7496: $scan_data);
7497: if (!defined($$scan_record{'scantron.missingerror'})) { next; }
7498: my @to_correct;
7499:
7500: # Probably here's where the error is...
7501:
7502: foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
7503: my $lastbubble;
7504: if ($missing =~ /^(\d+)\.(\d+)$/) {
7505: my $question = $1;
7506: my $subquestion = $2;
7507: if (!defined($first_bubble_line{$question -1})) { next; }
7508: my $first = $first_bubble_line{$question-1};
7509: my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
7510: my $subcount = 1;
7511: while ($subcount<$subquestion) {
7512: $first += $subans[$subcount-1];
7513: $subcount ++;
7514: }
7515: my $count = $subans[$subquestion-1];
7516: $lastbubble = $first + $count;
7517: } else {
7518: if (!defined($first_bubble_line{$missing - 1})) { next; }
7519: $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
7520: }
7521: if ($lastbubble > $max_bubble) { next; }
7522: push(@to_correct,$missing);
7523: }
7524: if (@to_correct) {
7525: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
7526: $line,'missingbubble',\@to_correct);
7527: return (1,$currentphase);
7528: }
7529:
7530: }
7531: return (0,$currentphase+1);
7532: }
7533:
7534:
7535: sub scantron_process_students {
7536: my ($r,$symb) = @_;
7537:
7538: my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
7539: if (!$symb) {
7540: return '';
7541: }
7542: my $default_form_data=&defaultFormData($symb);
7543:
7544: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7545: my ($scanlines,$scan_data)=&scantron_getfile();
7546: my $classlist=&Apache::loncoursedata::get_classlist();
7547: my %idmap=&username_to_idmap($classlist);
7548: my $navmap=Apache::lonnavmaps::navmap->new();
7549: unless (ref($navmap)) {
7550: $r->print(&navmap_errormsg());
7551: return '';
7552: }
7553: my $map=$navmap->getResourceByUrl($sequence);
7554: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
7555: my (%grader_partids_by_symb,%grader_randomlists_by_symb);
7556: &graders_resources_pass(\@resources,\%grader_partids_by_symb,
7557: \%grader_randomlists_by_symb);
7558: my $resource_error;
7559: foreach my $resource (@resources) {
7560: my $ressymb;
7561: if (ref($resource)) {
7562: $ressymb = $resource->symb();
7563: } else {
7564: $resource_error = 1;
7565: last;
7566: }
7567: my ($analysis,$parts) =
7568: &scantron_partids_tograde($resource,$env{'request.course.id'},
7569: $env{'user.name'},$env{'user.domain'},1);
7570: $grader_partids_by_symb{$ressymb} = $parts;
7571: if (ref($analysis) eq 'HASH') {
7572: if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
7573: $grader_randomlists_by_symb{$ressymb} =
7574: $analysis->{'parts_withrandomlist'};
7575: }
7576: }
7577: }
7578: if ($resource_error) {
7579: $r->print(&navmap_errormsg());
7580: return '';
7581: }
7582:
7583: my ($uname,$udom);
7584: my $result= <<SCANTRONFORM;
7585: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
7586: <input type="hidden" name="command" value="scantron_configphase" />
7587: $default_form_data
7588: SCANTRONFORM
7589: $r->print($result);
7590:
7591: my @delayqueue;
7592: my (%completedstudents,%scandata);
7593:
7594: my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
7595: my $count=&get_todo_count($scanlines,$scan_data);
7596: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
7597: 'Bubblesheet Progress',$count,
7598: 'inline',undef,'scantronupload');
7599: &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
7600: 'Processing first student');
7601: $r->print('<br />');
7602: my $start=&Time::HiRes::time();
7603: my $i=-1;
7604: my $started;
7605:
7606: my $nav_error;
7607: &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
7608: if ($nav_error) {
7609: $r->print(&navmap_errormsg());
7610: return '';
7611: }
7612:
7613: # If an ssi failed in scantron_get_maxbubble, put an error message out to
7614: # the user and return.
7615:
7616: if ($ssi_error) {
7617: $r->print("</form>");
7618: &ssi_print_error($r);
7619: &Apache::lonnet::remove_lock($lock);
7620: return ''; # Dunno why the other returns return '' rather than just returning.
7621: }
7622:
7623: my %lettdig = &letter_to_digits();
7624: my $numletts = scalar(keys(%lettdig));
7625:
7626: while ($i<$scanlines->{'count'}) {
7627: ($uname,$udom)=('','');
7628: $i++;
7629: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7630: if ($line=~/^[\s\cz]*$/) { next; }
7631: if ($started) {
7632: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
7633: 'last student');
7634: }
7635: $started=1;
7636: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7637: $scan_data);
7638: unless ($uname=&scantron_find_student($scan_record,$scan_data,
7639: \%idmap,$i)) {
7640: &scantron_add_delay(\@delayqueue,$line,
7641: 'Unable to find a student that matches',1);
7642: next;
7643: }
7644: if (exists $completedstudents{$uname}) {
7645: &scantron_add_delay(\@delayqueue,$line,
7646: 'Student '.$uname.' has multiple sheets',2);
7647: next;
7648: }
7649: ($uname,$udom)=split(/:/,$uname);
7650:
7651: my (%partids_by_symb,$res_error);
7652: foreach my $resource (@resources) {
7653: my $ressymb;
7654: if (ref($resource)) {
7655: $ressymb = $resource->symb();
7656: } else {
7657: $res_error = 1;
7658: last;
7659: }
7660: if ((exists($grader_randomlists_by_symb{$ressymb})) ||
7661: (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
7662: my ($analysis,$parts) =
7663: &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
7664: $partids_by_symb{$ressymb} = $parts;
7665: } else {
7666: $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
7667: }
7668: }
7669:
7670: if ($res_error) {
7671: &scantron_add_delay(\@delayqueue,$line,
7672: 'An error occurred while grading student '.$uname,2);
7673: next;
7674: }
7675:
7676: &Apache::lonxml::clear_problem_counter();
7677: &Apache::lonnet::appenv($scan_record);
7678:
7679: if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
7680: &scantron_putfile($scanlines,$scan_data);
7681: }
7682:
7683: my $scancode;
7684: if ((exists($scan_record->{'scantron.CODE'})) &&
7685: (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
7686: $scancode = $scan_record->{'scantron.CODE'};
7687: } else {
7688: $scancode = '';
7689: }
7690:
7691: if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
7692: \@resources,\%partids_by_symb) eq 'ssi_error') {
7693: $ssi_error = 0; # So end of handler error message does not trigger.
7694: $r->print("</form>");
7695: &ssi_print_error($r);
7696: &Apache::lonnet::remove_lock($lock);
7697: return ''; # Why return ''? Beats me.
7698: }
7699:
7700: $completedstudents{$uname}={'line'=>$line};
7701: if ($env{'form.verifyrecord'}) {
7702: my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
7703: my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
7704: chomp($studentdata);
7705: $studentdata =~ s/\r$//;
7706: my $studentrecord = '';
7707: my $counter = -1;
7708: foreach my $resource (@resources) {
7709: my $ressymb = $resource->symb();
7710: ($counter,my $recording) =
7711: &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
7712: $counter,$studentdata,$partids_by_symb{$ressymb},
7713: \%scantron_config,\%lettdig,$numletts);
7714: $studentrecord .= $recording;
7715: }
7716: if ($studentrecord ne $studentdata) {
7717: &Apache::lonxml::clear_problem_counter();
7718: if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
7719: \@resources,\%partids_by_symb) eq 'ssi_error') {
7720: $ssi_error = 0; # So end of handler error message does not trigger.
7721: $r->print("</form>");
7722: &ssi_print_error($r);
7723: &Apache::lonnet::remove_lock($lock);
7724: delete($completedstudents{$uname});
7725: return '';
7726: }
7727: $counter = -1;
7728: $studentrecord = '';
7729: foreach my $resource (@resources) {
7730: my $ressymb = $resource->symb();
7731: ($counter,my $recording) =
7732: &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
7733: $counter,$studentdata,$partids_by_symb{$ressymb},
7734: \%scantron_config,\%lettdig,$numletts);
7735: $studentrecord .= $recording;
7736: }
7737: if ($studentrecord ne $studentdata) {
7738: $r->print('<p><span class="LC_error">');
7739: if ($scancode eq '') {
7740: $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
7741: $uname.':'.$udom,$scan_record->{'scantron.ID'}));
7742: } else {
7743: $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
7744: $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
7745: }
7746: $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
7747: &Apache::loncommon::start_data_table_header_row()."\n".
7748: '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
7749: &Apache::loncommon::end_data_table_header_row()."\n".
7750: &Apache::loncommon::start_data_table_row().
7751: '<td>'.&mt('Bubble Sheet').'</td>'.
7752: '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
7753: &Apache::loncommon::end_data_table_row().
7754: &Apache::loncommon::start_data_table_row().
7755: '<td>Stored submissions</td>'.
7756: '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
7757: &Apache::loncommon::end_data_table_row().
7758: &Apache::loncommon::end_data_table().'</p>');
7759: } else {
7760: $r->print('<br /><span class="LC_warning">'.
7761: &mt('A second grading pass was needed for user: [_1] with ID: [_2], because a mismatch was seen on the first pass.',$uname.':'.$udom,$scan_record->{'scantron.ID'}).'<br />'.
7762: &mt("As a consequence, this user's submission history records two tries.").
7763: '</span><br />');
7764: }
7765: }
7766: }
7767: if (&Apache::loncommon::connection_aborted($r)) { last; }
7768: } continue {
7769: &Apache::lonxml::clear_problem_counter();
7770: &Apache::lonnet::delenv('scantron.');
7771: }
7772: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
7773: &Apache::lonnet::remove_lock($lock);
7774: # my $lasttime = &Time::HiRes::time()-$start;
7775: # $r->print("<p>took $lasttime</p>");
7776:
7777: $r->print("</form>");
7778: return '';
7779: }
7780:
7781: sub graders_resources_pass {
7782: my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
7783: if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) &&
7784: (ref($grader_randomlists_by_symb) eq 'HASH')) {
7785: foreach my $resource (@{$resources}) {
7786: my $ressymb = $resource->symb();
7787: my ($analysis,$parts) =
7788: &scantron_partids_tograde($resource,$env{'request.course.id'},
7789: $env{'user.name'},$env{'user.domain'},1);
7790: $grader_partids_by_symb->{$ressymb} = $parts;
7791: if (ref($analysis) eq 'HASH') {
7792: if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
7793: $grader_randomlists_by_symb->{$ressymb} =
7794: $analysis->{'parts_withrandomlist'};
7795: }
7796: }
7797: }
7798: }
7799: return;
7800: }
7801:
7802: sub grade_student_bubbles {
7803: my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
7804: if (ref($resources) eq 'ARRAY') {
7805: my $count = 0;
7806: foreach my $resource (@{$resources}) {
7807: my $ressymb = $resource->symb();
7808: my %form = ('submitted' => 'scantron',
7809: 'grade_target' => 'grade',
7810: 'grade_username' => $uname,
7811: 'grade_domain' => $udom,
7812: 'grade_courseid' => $env{'request.course.id'},
7813: 'grade_symb' => $ressymb,
7814: 'CODE' => $scancode
7815: );
7816: if (ref($parts) eq 'HASH') {
7817: if (ref($parts->{$ressymb}) eq 'ARRAY') {
7818: foreach my $part (@{$parts->{$ressymb}}) {
7819: $form{'scantron_questnum_start.'.$part} =
7820: 1+$env{'form.scantron.first_bubble_line.'.$count};
7821: $count++;
7822: }
7823: }
7824: }
7825: my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
7826: return 'ssi_error' if ($ssi_error);
7827: last if (&Apache::loncommon::connection_aborted($r));
7828: }
7829: }
7830: return;
7831: }
7832:
7833: sub scantron_upload_scantron_data {
7834: my ($r,$symb)=@_;
7835: my $dom = $env{'request.role.domain'};
7836: my $domdesc = &Apache::lonnet::domain($dom,'description');
7837: $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
7838: my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
7839: 'domainid',
7840: 'coursename',$dom);
7841: my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
7842: (' 'x2).&mt('(shows course personnel)');
7843: my $default_form_data=&defaultFormData($symb);
7844: my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
7845: my $nocourseid_alert = &mt("Please use the 'Select Course' link to open a separate window where you can search for a course to which a file can be uploaded.");
7846: $r->print(&Apache::lonhtmlcommon::scripttag('
7847: function checkUpload(formname) {
7848: if (formname.upfile.value == "") {
7849: alert("'.$nofile_alert.'");
7850: return false;
7851: }
7852: if (formname.courseid.value == "") {
7853: alert("'.$nocourseid_alert.'");
7854: return false;
7855: }
7856: formname.submit();
7857: }
7858:
7859: function ToSyllabus() {
7860: var cdom = '."'$dom'".';
7861: var cnum = document.rules.courseid.value;
7862: if (cdom == "" || cdom == null) {
7863: return;
7864: }
7865: if (cnum == "" || cnum == null) {
7866: return;
7867: }
7868: syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
7869: "height=350,width=350,scrollbars=yes,menubar=no");
7870: return;
7871: }
7872:
7873: '));
7874: $r->print('
7875: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
7876:
7877: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
7878: '.$default_form_data.
7879: &Apache::lonhtmlcommon::start_pick_box().
7880: &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
7881: '<input name="courseid" type="text" size="30" />'.$select_link.
7882: &Apache::lonhtmlcommon::row_closure().
7883: &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
7884: '<input name="coursename" type="text" size="30" />'.$syllabuslink.
7885: &Apache::lonhtmlcommon::row_closure().
7886: &Apache::lonhtmlcommon::row_title(&mt('Domain')).
7887: '<input name="domainid" type="hidden" />'.$domdesc.
7888: &Apache::lonhtmlcommon::row_closure().
7889: &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
7890: '<input type="file" name="upfile" size="50" />'.
7891: &Apache::lonhtmlcommon::row_closure(1).
7892: &Apache::lonhtmlcommon::end_pick_box().'<br />
7893:
7894: <input name="command" value="scantronupload_save" type="hidden" />
7895: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
7896: </form>
7897: ');
7898: return '';
7899: }
7900:
7901:
7902: sub scantron_upload_scantron_data_save {
7903: my($r,$symb)=@_;
7904: my $doanotherupload=
7905: '<br /><form action="/adm/grades" method="post">'."\n".
7906: '<input type="hidden" name="command" value="scantronupload" />'."\n".
7907: '<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
7908: '</form>'."\n";
7909: if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
7910: !&Apache::lonnet::allowed('usc',
7911: $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
7912: $r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
7913: unless ($symb) {
7914: $r->print($doanotherupload);
7915: }
7916: return '';
7917: }
7918: my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
7919: my $uploadedfile;
7920: $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
7921: if (length($env{'form.upfile'}) < 2) {
7922: $r->print(&mt('[_1]Error:[_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.','<span class="LC_error">','</span>','<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
7923: } else {
7924: my $result =
7925: &Apache::lonnet::userfileupload('upfile','','scantron','','','',
7926: $env{'form.courseid'},$env{'form.domainid'});
7927: if ($result =~ m{^/uploaded/}) {
7928: $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
7929: '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
7930: '<span class="LC_filename">'.$result.'</span>'));
7931: ($uploadedfile) = ($result =~ m{/([^/]+)$});
7932: $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
7933: $env{'form.courseid'},$uploadedfile));
7934: } else {
7935: $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
7936: '<span class="LC_error">','</span>',$result,
7937: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
7938: }
7939: }
7940: if ($symb) {
7941: $r->print(&scantron_selectphase($r,$uploadedfile,$symb));
7942: } else {
7943: $r->print($doanotherupload);
7944: }
7945: return '';
7946: }
7947:
7948: sub validate_uploaded_scantron_file {
7949: my ($cdom,$cname,$fname) = @_;
7950: my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
7951: my @lines;
7952: if ($scanlines ne '-1') {
7953: @lines=split("\n",$scanlines,-1);
7954: }
7955: my $output;
7956: if (@lines) {
7957: my (%counts,$max_match_format);
7958: my ($max_match_count,$max_match_pct) = (0,0);
7959: my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
7960: my %idmap = &username_to_idmap($classlist);
7961: foreach my $key (keys(%idmap)) {
7962: my $lckey = lc($key);
7963: $idmap{$lckey} = $idmap{$key};
7964: }
7965: my %unique_formats;
7966: my @formatlines = &get_scantronformat_file();
7967: foreach my $line (@formatlines) {
7968: chomp($line);
7969: my @config = split(/:/,$line);
7970: my $idstart = $config[5];
7971: my $idlength = $config[6];
7972: if (($idstart ne '') && ($idlength > 0)) {
7973: if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
7974: push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]);
7975: } else {
7976: $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
7977: }
7978: }
7979: }
7980: foreach my $key (keys(%unique_formats)) {
7981: my ($idstart,$idlength) = split(':',$key);
7982: %{$counts{$key}} = (
7983: 'found' => 0,
7984: 'total' => 0,
7985: );
7986: foreach my $line (@lines) {
7987: next if ($line =~ /^#/);
7988: next if ($line =~ /^[\s\cz]*$/);
7989: my $id = substr($line,$idstart-1,$idlength);
7990: $id = lc($id);
7991: if (exists($idmap{$id})) {
7992: $counts{$key}{'found'} ++;
7993: }
7994: $counts{$key}{'total'} ++;
7995: }
7996: if ($counts{$key}{'total'}) {
7997: my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
7998: if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
7999: $max_match_pct = $percent_match;
8000: $max_match_format = $key;
8001: $max_match_count = $counts{$key}{'total'};
8002: }
8003: }
8004: }
8005: if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
8006: my $format_descs;
8007: my $numwithformat = @{$unique_formats{$max_match_format}};
8008: for (my $i=0; $i<$numwithformat; $i++) {
8009: my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
8010: if ($i<$numwithformat-2) {
8011: $format_descs .= '"<i>'.$desc.'</i>", ';
8012: } elsif ($i==$numwithformat-2) {
8013: $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
8014: } elsif ($i==$numwithformat-1) {
8015: $format_descs .= '"<i>'.$desc.'</i>"';
8016: }
8017: }
8018: my $showpct = sprintf("%.0f",$max_match_pct).'%';
8019: $output .= '<br />'.&mt('Comparison of student IDs in the uploaded file with the course roster found matches for [_1] of the [_2] entries in the file (for the format defined for [_3]).','<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
8020: '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
8021: '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
8022: '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
8023: '<i>'.$cdom.'</i>').'</li>'.
8024: '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
8025: '<li>'.&mt('The course roster is not up to date').'</li>'.
8026: '</ul>';
8027: }
8028: } else {
8029: $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
8030: }
8031: return $output;
8032: }
8033:
8034: sub valid_file {
8035: my ($requested_file)=@_;
8036: foreach my $filename (sort(&scantron_filenames())) {
8037: if ($requested_file eq $filename) { return 1; }
8038: }
8039: return 0;
8040: }
8041:
8042: sub scantron_download_scantron_data {
8043: my ($r,$symb)=@_;
8044: my $default_form_data=&defaultFormData($symb);
8045: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
8046: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
8047: my $file=$env{'form.scantron_selectfile'};
8048: if (! &valid_file($file)) {
8049: $r->print('
8050: <p>
8051: '.&mt('The requested file name was invalid.').'
8052: </p>
8053: ');
8054: return;
8055: }
8056: my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
8057: my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
8058: my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
8059: &Apache::lonnet::allowuploaded('/adm/grades',$orig);
8060: &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
8061: &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
8062: $r->print('
8063: <p>
8064: '.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
8065: '<a href="'.$orig.'">','</a>').'
8066: </p>
8067: <p>
8068: '.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
8069: '<a href="'.$corrected.'">','</a>').'
8070: </p>
8071: <p>
8072: '.&mt('[_1]Skipped[_2], a file of records that were skipped.',
8073: '<a href="'.$skipped.'">','</a>').'
8074: </p>
8075: ');
8076: return '';
8077: }
8078:
8079: sub checkscantron_results {
8080: my ($r,$symb) = @_;
8081: if (!$symb) {return '';}
8082: my $cid = $env{'request.course.id'};
8083: my %lettdig = &letter_to_digits();
8084: my $numletts = scalar(keys(%lettdig));
8085: my $cnum = $env{'course.'.$cid.'.num'};
8086: my $cdom = $env{'course.'.$cid.'.domain'};
8087: my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
8088: my %record;
8089: my %scantron_config =
8090: &Apache::grades::get_scantron_config($env{'form.scantron_format'});
8091: my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
8092: my $classlist=&Apache::loncoursedata::get_classlist();
8093: my %idmap=&Apache::grades::username_to_idmap($classlist);
8094: my $navmap=Apache::lonnavmaps::navmap->new();
8095: unless (ref($navmap)) {
8096: $r->print(&navmap_errormsg());
8097: return '';
8098: }
8099: my $map=$navmap->getResourceByUrl($sequence);
8100: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
8101: my (%grader_partids_by_symb,%grader_randomlists_by_symb);
8102: &graders_resources_pass(\@resources,\%grader_partids_by_symb, \%grader_randomlists_by_symb);
8103:
8104: my ($uname,$udom);
8105: my (%scandata,%lastname,%bylast);
8106: $r->print('
8107: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
8108:
8109: my @delayqueue;
8110: my %completedstudents;
8111:
8112: my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
8113: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
8114: 'Progress of Bubblesheet Data/Submission Records Comparison',$count,
8115: 'inline',undef,'checkscantron');
8116: my ($username,$domain,$started);
8117: my $nav_error;
8118: &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
8119: if ($nav_error) {
8120: $r->print(&navmap_errormsg());
8121: return '';
8122: }
8123:
8124: &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
8125: 'Processing first student');
8126: my $start=&Time::HiRes::time();
8127: my $i=-1;
8128:
8129: while ($i<$scanlines->{'count'}) {
8130: ($username,$domain,$uname)=('','','');
8131: $i++;
8132: my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
8133: if ($line=~/^[\s\cz]*$/) { next; }
8134: if ($started) {
8135: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
8136: 'last student');
8137: }
8138: $started=1;
8139: my $scan_record=
8140: &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
8141: $scan_data);
8142: unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
8143: \%idmap,$i)) {
8144: &Apache::grades::scantron_add_delay(\@delayqueue,$line,
8145: 'Unable to find a student that matches',1);
8146: next;
8147: }
8148: if (exists $completedstudents{$uname}) {
8149: &Apache::grades::scantron_add_delay(\@delayqueue,$line,
8150: 'Student '.$uname.' has multiple sheets',2);
8151: next;
8152: }
8153: my $pid = $scan_record->{'scantron.ID'};
8154: $lastname{$pid} = $scan_record->{'scantron.LastName'};
8155: push(@{$bylast{$lastname{$pid}}},$pid);
8156: my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
8157: $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
8158: chomp($scandata{$pid});
8159: $scandata{$pid} =~ s/\r$//;
8160: ($username,$domain)=split(/:/,$uname);
8161: my $counter = -1;
8162: foreach my $resource (@resources) {
8163: my $parts;
8164: my $ressymb = $resource->symb();
8165: if ((exists($grader_randomlists_by_symb{$ressymb})) ||
8166: (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
8167: (my $analysis,$parts) =
8168: &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
8169: } else {
8170: $parts = $grader_partids_by_symb{$ressymb};
8171: }
8172: ($counter,my $recording) =
8173: &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
8174: $scandata{$pid},$parts,
8175: \%scantron_config,\%lettdig,$numletts);
8176: $record{$pid} .= $recording;
8177: }
8178: }
8179: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
8180: $r->print('<br />');
8181: my ($okstudents,$badstudents,$numstudents,$passed,$failed);
8182: $passed = 0;
8183: $failed = 0;
8184: $numstudents = 0;
8185: foreach my $last (sort(keys(%bylast))) {
8186: if (ref($bylast{$last}) eq 'ARRAY') {
8187: foreach my $pid (sort(@{$bylast{$last}})) {
8188: my $showscandata = $scandata{$pid};
8189: my $showrecord = $record{$pid};
8190: $showscandata =~ s/\s/ /g;
8191: $showrecord =~ s/\s/ /g;
8192: if ($scandata{$pid} eq $record{$pid}) {
8193: my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
8194: $okstudents .= '<tr class="'.$css_class.'">'.
8195: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
8196: '</tr>'."\n".
8197: '<tr class="'.$css_class.'">'."\n".
8198: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
8199: $passed ++;
8200: } else {
8201: my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
8202: $badstudents .= '<tr class="'.$css_class.'"><td>'.&mt('Bubblesheet').'</td><td><span class="LC_nobreak">'.$scandata{$pid}.'</span></td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
8203: '</tr>'."\n".
8204: '<tr class="'.$css_class.'">'."\n".
8205: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
8206: '</tr>'."\n";
8207: $failed ++;
8208: }
8209: $numstudents ++;
8210: }
8211: }
8212: }
8213: $r->print('<p>'.&mt('Comparison of bubblesheet data (including corrections) with corresponding submission records (most recent submission) for <b>[quant,_1,student]</b> ([_2] scantron lines/student).',$numstudents,$env{'form.scantron_maxbubble'}).'</p>');
8214: $r->print('<p>'.&mt('Exact matches for <b>[quant,_1,student]</b>.',$passed).'<br />'.&mt('Discrepancies detected for <b>[quant,_1,student]</b>.',$failed).'</p>');
8215: if ($passed) {
8216: $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
8217: $r->print(&Apache::loncommon::start_data_table()."\n".
8218: &Apache::loncommon::start_data_table_header_row()."\n".
8219: '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
8220: &Apache::loncommon::end_data_table_header_row()."\n".
8221: $okstudents."\n".
8222: &Apache::loncommon::end_data_table().'<br />');
8223: }
8224: if ($failed) {
8225: $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
8226: $r->print(&Apache::loncommon::start_data_table()."\n".
8227: &Apache::loncommon::start_data_table_header_row()."\n".
8228: '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
8229: &Apache::loncommon::end_data_table_header_row()."\n".
8230: $badstudents."\n".
8231: &Apache::loncommon::end_data_table()).'<br />'.
8232: &mt('Differences can occur if submissions were modified using manual grading after a bubblesheet grading pass.').'<br />'.&mt('If unexpected discrepancies were detected, it is recommended that you inspect the original bubblesheets.');
8233: }
8234: $r->print('</form><br />');
8235: return;
8236: }
8237:
8238: sub verify_scantron_grading {
8239: my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
8240: $scantron_config,$lettdig,$numletts) = @_;
8241: my ($record,%expected,%startpos);
8242: return ($counter,$record) if (!ref($resource));
8243: return ($counter,$record) if (!$resource->is_problem());
8244: my $symb = $resource->symb();
8245: return ($counter,$record) if (ref($partids) ne 'ARRAY');
8246: foreach my $part_id (@{$partids}) {
8247: $counter ++;
8248: $expected{$part_id} = 0;
8249: if ($env{"form.scantron.sub_bubblelines.$counter"}) {
8250: my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
8251: foreach my $item (@sub_lines) {
8252: $expected{$part_id} += $item;
8253: }
8254: } else {
8255: $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
8256: }
8257: $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
8258: }
8259: if ($symb) {
8260: my %recorded;
8261: my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
8262: if ($returnhash{'version'}) {
8263: my %lasthash=();
8264: my $version;
8265: for ($version=1;$version<=$returnhash{'version'};$version++) {
8266: foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
8267: $lasthash{$key}=$returnhash{$version.':'.$key};
8268: }
8269: }
8270: foreach my $key (keys(%lasthash)) {
8271: if ($key =~ /\.scantron$/) {
8272: my $value = &unescape($lasthash{$key});
8273: my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
8274: if ($value eq '') {
8275: for (my $i=0; $i<$expected{$part_id}; $i++) {
8276: for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
8277: $recorded{$part_id} .= $scantron_config->{'Qoff'};
8278: }
8279: }
8280: } else {
8281: my @tocheck;
8282: my @items = split(//,$value);
8283: if (($scantron_config->{'Qon'} eq 'letter') ||
8284: ($scantron_config->{'Qon'} eq 'number')) {
8285: if (@items < $expected{$part_id}) {
8286: my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
8287: my @singles = split(//,$fragment);
8288: foreach my $pos (@singles) {
8289: if ($pos eq ' ') {
8290: push(@tocheck,$pos);
8291: } else {
8292: my $next = shift(@items);
8293: push(@tocheck,$next);
8294: }
8295: }
8296: } else {
8297: @tocheck = @items;
8298: }
8299: foreach my $letter (@tocheck) {
8300: if ($scantron_config->{'Qon'} eq 'letter') {
8301: if ($letter !~ /^[A-J]$/) {
8302: $letter = $scantron_config->{'Qoff'};
8303: }
8304: $recorded{$part_id} .= $letter;
8305: } elsif ($scantron_config->{'Qon'} eq 'number') {
8306: my $digit;
8307: if ($letter !~ /^[A-J]$/) {
8308: $digit = $scantron_config->{'Qoff'};
8309: } else {
8310: $digit = $lettdig->{$letter};
8311: }
8312: $recorded{$part_id} .= $digit;
8313: }
8314: }
8315: } else {
8316: @tocheck = @items;
8317: for (my $i=0; $i<$expected{$part_id}; $i++) {
8318: my $curr_sub = shift(@tocheck);
8319: my $digit;
8320: if ($curr_sub =~ /^[A-J]$/) {
8321: $digit = $lettdig->{$curr_sub}-1;
8322: }
8323: if ($curr_sub eq 'J') {
8324: $digit += scalar($numletts);
8325: }
8326: for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
8327: if ($j == $digit) {
8328: $recorded{$part_id} .= $scantron_config->{'Qon'};
8329: } else {
8330: $recorded{$part_id} .= $scantron_config->{'Qoff'};
8331: }
8332: }
8333: }
8334: }
8335: }
8336: }
8337: }
8338: }
8339: foreach my $part_id (@{$partids}) {
8340: if ($recorded{$part_id} eq '') {
8341: for (my $i=0; $i<$expected{$part_id}; $i++) {
8342: for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
8343: $recorded{$part_id} .= $scantron_config->{'Qoff'};
8344: }
8345: }
8346: }
8347: $record .= $recorded{$part_id};
8348: }
8349: }
8350: return ($counter,$record);
8351: }
8352:
8353: sub letter_to_digits {
8354: my %lettdig = (
8355: A => 1,
8356: B => 2,
8357: C => 3,
8358: D => 4,
8359: E => 5,
8360: F => 6,
8361: G => 7,
8362: H => 8,
8363: I => 9,
8364: J => 0,
8365: );
8366: return %lettdig;
8367: }
8368:
8369:
8370: #-------- end of section for handling grading scantron forms -------
8371: #
8372: #-------------------------------------------------------------------
8373:
8374: #-------------------------- Menu interface -------------------------
8375: #
8376: #--- Href with symb and command ---
8377:
8378: sub href_symb_cmd {
8379: my ($symb,$cmd)=@_;
8380: return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&command='.$cmd;
8381: }
8382:
8383: sub grading_menu {
8384: my ($request,$symb) = @_;
8385: if (!$symb) {return '';}
8386:
8387: my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
8388: 'command'=>'individual');
8389:
8390: my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
8391:
8392: $fields{'command'}='ungraded';
8393: my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
8394:
8395: $fields{'command'}='table';
8396: my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
8397:
8398: $fields{'command'}='all_for_one';
8399: my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
8400:
8401: $fields{'command'}='downloadfilesselect';
8402: my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
8403:
8404: $fields{'command'} = 'csvform';
8405: my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
8406:
8407: $fields{'command'} = 'processclicker';
8408: my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
8409:
8410: $fields{'command'} = 'scantron_selectphase';
8411: my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
8412:
8413: $fields{'command'} = 'initialverifyreceipt';
8414: my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
8415:
8416: my @menu = ({ categorytitle=>'Hand Grading',
8417: items =>[
8418: { linktext => 'Select individual students to grade',
8419: url => $url1a,
8420: permission => 'F',
8421: icon => 'edit-find-replace.png',
8422: linktitle => 'Grade current resource for a selection of students.'
8423: },
8424: { linktext => 'Grade ungraded submissions.',
8425: url => $url1b,
8426: permission => 'F',
8427: icon => 'edit-find-replace.png',
8428: linktitle => 'Grade all submissions that have not been graded yet.'
8429: },
8430:
8431: { linktext => 'Grading table',
8432: url => $url1c,
8433: permission => 'F',
8434: icon => 'edit-find-replace.png',
8435: linktitle => 'Grade current resource for all students.'
8436: },
8437: { linktext => 'Grade page/folder for one student',
8438: url => $url1d,
8439: permission => 'F',
8440: icon => 'edit-find-replace.png',
8441: linktitle => 'Grade all resources in current page/sequence/folder for one student.'
8442: },
8443: { linktext => 'Download submissions',
8444: url => $url1e,
8445: permission => 'F',
8446: icon => 'edit-find-replace.png',
8447: linktitle => 'Download all students submissions.'
8448: }]},
8449: { categorytitle=>'Automated Grading',
8450: items =>[
8451:
8452: { linktext => 'Upload Scores',
8453: url => $url2,
8454: permission => 'F',
8455: icon => 'uploadscores.png',
8456: linktitle => 'Specify a file containing the class scores for current resource.'
8457: },
8458: { linktext => 'Process Clicker',
8459: url => $url3,
8460: permission => 'F',
8461: icon => 'addClickerInfoFile.png',
8462: linktitle => 'Specify a file containing the clicker information for this resource.'
8463: },
8464: { linktext => 'Grade/Manage/Review Bubblesheets',
8465: url => $url4,
8466: permission => 'F',
8467: icon => 'stat.png',
8468: linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
8469: },
8470: { linktext => 'Verify Receipt Number',
8471: url => $url5,
8472: permission => 'F',
8473: icon => 'edit-find-replace.png',
8474: linktitle => 'Verify a system-generated receipt number for correct problem solution.'
8475: }
8476:
8477: ]
8478: });
8479:
8480: # Create the menu
8481: my $Str;
8482: $Str .= '<form method="post" action="" name="gradingMenu">';
8483: $Str .= '<input type="hidden" name="command" value="" />'.
8484: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
8485:
8486: $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
8487: return $Str;
8488: }
8489:
8490:
8491: sub ungraded {
8492: my ($request)=@_;
8493: &submit_options($request);
8494: }
8495:
8496: sub submit_options_sequence {
8497: my ($request,$symb) = @_;
8498: if (!$symb) {return '';}
8499: &commonJSfunctions($request);
8500: my $result;
8501:
8502: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
8503: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
8504: $result.='
8505: <h2>
8506: '.&mt('Grade page/folder for one student').'
8507: </h2>'.
8508: &selectfield(0).
8509: '<input type="hidden" name="command" value="pickStudentPage" />
8510: <div>
8511: <input type="submit" value="'.&mt('Next').' →" />
8512: </div>
8513: </div>
8514: </form>';
8515: return $result;
8516: }
8517:
8518: sub submit_options_table {
8519: my ($request,$symb) = @_;
8520: if (!$symb) {return '';}
8521: &commonJSfunctions($request);
8522: my $result;
8523:
8524: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
8525: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
8526:
8527: $result.='
8528: <h2>
8529: '.&mt('Grading table').'
8530: </h2>'.
8531: &selectfield(0).
8532: '<input type="hidden" name="command" value="viewgrades" />
8533: <div>
8534: <input type="submit" value="'.&mt('Next').' →" />
8535: </div>
8536: </div>
8537: </form>';
8538: return $result;
8539: }
8540:
8541: sub submit_options_download {
8542: my ($request,$symb) = @_;
8543: if (!$symb) {return '';}
8544:
8545: &commonJSfunctions($request);
8546:
8547: my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
8548: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
8549: $result.='
8550: <h2>
8551: '.&mt('Select Students for Which to Download Submissions').'
8552: </h2>'.&selectfield(1).'
8553: <input type="hidden" name="command" value="downloadfileslink" />
8554: <input type="submit" value="'.&mt('Next').' →" />
8555: </div>
8556: </div>
8557:
8558:
8559: </form>';
8560: return $result;
8561: }
8562:
8563: #--- Displays the submissions first page -------
8564: sub submit_options {
8565: my ($request,$symb) = @_;
8566: if (!$symb) {return '';}
8567:
8568: &commonJSfunctions($request);
8569: my $result;
8570:
8571: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
8572: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
8573: $result.='
8574: <h2>
8575: '.&mt('Select individual students to grade').'
8576: </h2>'.&selectfield(1).'
8577: <input type="hidden" name="command" value="submission" />
8578: <input type="submit" value="'.&mt('Next').' →" />
8579: </div>
8580: </div>
8581:
8582:
8583: </form>';
8584: return $result;
8585: }
8586:
8587: sub selectfield {
8588: my ($full)=@_;
8589: my $result='<div class="LC_columnSection">
8590:
8591: <fieldset>
8592: <legend>
8593: '.&mt('Sections').'
8594: </legend>
8595: '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
8596: </fieldset>
8597:
8598: <fieldset>
8599: <legend>
8600: '.&mt('Groups').'
8601: </legend>
8602: '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
8603: </fieldset>
8604:
8605: <fieldset>
8606: <legend>
8607: '.&mt('Access Status').'
8608: </legend>
8609: '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
8610: </fieldset>';
8611: if ($full) {
8612: $result.='
8613: <fieldset>
8614: <legend>
8615: '.&mt('Submission Status').'
8616: </legend>'.
8617: &Apache::loncommon::select_form('all','submitonly',
8618: (&Apache::lonlocal::texthash(
8619: 'yes' => 'with submissions',
8620: 'queued' => 'in grading queue',
8621: 'graded' => 'with ungraded submissions',
8622: 'incorrect' => 'with incorrect submissions',
8623: 'all' => 'with any status'),
8624: 'select_form_order' => ['yes','queued','graded','incorrect','all'])).
8625: '</fieldset>';
8626: }
8627: $result.='</div><br />';
8628: return $result;
8629: }
8630:
8631: sub reset_perm {
8632: undef(%perm);
8633: }
8634:
8635: sub init_perm {
8636: &reset_perm();
8637: foreach my $test_perm ('vgr','mgr','opa') {
8638:
8639: my $scope = $env{'request.course.id'};
8640: if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
8641:
8642: $scope .= '/'.$env{'request.course.sec'};
8643: if ( $perm{$test_perm}=
8644: &Apache::lonnet::allowed($test_perm,$scope)) {
8645: $perm{$test_perm.'_section'}=$env{'request.course.sec'};
8646: } else {
8647: delete($perm{$test_perm});
8648: }
8649: }
8650: }
8651: }
8652:
8653: sub gather_clicker_ids {
8654: my %clicker_ids;
8655:
8656: my $classlist = &Apache::loncoursedata::get_classlist();
8657:
8658: # Set up a couple variables.
8659: my $username_idx = &Apache::loncoursedata::CL_SNAME();
8660: my $domain_idx = &Apache::loncoursedata::CL_SDOM();
8661: my $status_idx = &Apache::loncoursedata::CL_STATUS();
8662:
8663: foreach my $student (keys(%$classlist)) {
8664: if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
8665: my $username = $classlist->{$student}->[$username_idx];
8666: my $domain = $classlist->{$student}->[$domain_idx];
8667: my $clickers =
8668: (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
8669: foreach my $id (split(/\,/,$clickers)) {
8670: $id=~s/^[\#0]+//;
8671: $id=~s/[\-\:]//g;
8672: if (exists($clicker_ids{$id})) {
8673: $clicker_ids{$id}.=','.$username.':'.$domain;
8674: } else {
8675: $clicker_ids{$id}=$username.':'.$domain;
8676: }
8677: }
8678: }
8679: return %clicker_ids;
8680: }
8681:
8682: sub gather_adv_clicker_ids {
8683: my %clicker_ids;
8684: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
8685: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
8686: my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
8687: foreach my $element (sort(keys(%coursepersonnel))) {
8688: foreach my $person (split(/\,/,$coursepersonnel{$element})) {
8689: my ($puname,$pudom)=split(/\:/,$person);
8690: my $clickers =
8691: (&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
8692: foreach my $id (split(/\,/,$clickers)) {
8693: $id=~s/^[\#0]+//;
8694: $id=~s/[\-\:]//g;
8695: if (exists($clicker_ids{$id})) {
8696: $clicker_ids{$id}.=','.$puname.':'.$pudom;
8697: } else {
8698: $clicker_ids{$id}=$puname.':'.$pudom;
8699: }
8700: }
8701: }
8702: }
8703: return %clicker_ids;
8704: }
8705:
8706: sub clicker_grading_parameters {
8707: return ('gradingmechanism' => 'scalar',
8708: 'upfiletype' => 'scalar',
8709: 'specificid' => 'scalar',
8710: 'pcorrect' => 'scalar',
8711: 'pincorrect' => 'scalar');
8712: }
8713:
8714: sub process_clicker {
8715: my ($r,$symb)=@_;
8716: if (!$symb) {return '';}
8717: my $result=&checkforfile_js();
8718: $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
8719: $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
8720: $result.=' <b>'.&mt('Specify a file containing the clicker information for this resource.').
8721: '</b></td></tr>'."\n";
8722: $result.='<tr bgcolor="#ffffe6"><td>'."\n";
8723: # Attempt to restore parameters from last session, set defaults if not present
8724: my %Saveable_Parameters=&clicker_grading_parameters();
8725: &Apache::loncommon::restore_course_settings('grades_clicker',
8726: \%Saveable_Parameters);
8727: if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
8728: if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
8729: if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
8730: if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
8731:
8732: my %checked;
8733: foreach my $gradingmechanism ('attendance','personnel','specific','given') {
8734: if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
8735: $checked{$gradingmechanism}=' checked="checked"';
8736: }
8737: }
8738:
8739: my $upload=&mt("Upload File");
8740: my $type=&mt("Type");
8741: my $attendance=&mt("Award points just for participation");
8742: my $personnel=&mt("Correctness determined from response by course personnel");
8743: my $specific=&mt("Correctness determined from response with clicker ID(s)");
8744: my $given=&mt("Correctness determined from given list of answers").' '.
8745: '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
8746: my $pcorrect=&mt("Percentage points for correct solution");
8747: my $pincorrect=&mt("Percentage points for incorrect solution");
8748: my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
8749: ('iclicker' => 'i>clicker',
8750: 'interwrite' => 'interwrite PRS'));
8751: $symb = &Apache::lonenc::check_encrypt($symb);
8752: $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
8753: function sanitycheck() {
8754: // Accept only integer percentages
8755: document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
8756: document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
8757: // Find out grading choice
8758: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
8759: if (document.forms.gradesupload.gradingmechanism[i].checked) {
8760: gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
8761: }
8762: }
8763: // By default, new choice equals user selection
8764: newgradingchoice=gradingchoice;
8765: // Not good to give more points for false answers than correct ones
8766: if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
8767: document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
8768: }
8769: // If new choice is attendance only, and old choice was correctness-based, restore defaults
8770: if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
8771: document.forms.gradesupload.pcorrect.value=100;
8772: document.forms.gradesupload.pincorrect.value=100;
8773: }
8774: // If the values are different, cannot be attendance only
8775: if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
8776: (gradingchoice=='attendance')) {
8777: newgradingchoice='personnel';
8778: }
8779: // Change grading choice to new one
8780: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
8781: if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
8782: document.forms.gradesupload.gradingmechanism[i].checked=true;
8783: } else {
8784: document.forms.gradesupload.gradingmechanism[i].checked=false;
8785: }
8786: }
8787: // Remember the old state
8788: document.forms.gradesupload.waschecked.value=newgradingchoice;
8789: }
8790: ENDUPFORM
8791: $result.= <<ENDUPFORM;
8792: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
8793: <input type="hidden" name="symb" value="$symb" />
8794: <input type="hidden" name="command" value="processclickerfile" />
8795: <input type="file" name="upfile" size="50" />
8796: <br /><label>$type: $selectform</label>
8797: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
8798: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
8799: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
8800: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
8801: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
8802: <br />
8803: <input type="text" name="givenanswer" size="50" />
8804: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
8805: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
8806: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
8807: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
8808: </form>'
8809: ENDUPFORM
8810: $result.='</td></tr></table>'."\n".
8811: '</td></tr></table><br /><br />'."\n";
8812: return $result;
8813: }
8814:
8815: sub process_clicker_file {
8816: my ($r,$symb)=@_;
8817: if (!$symb) {return '';}
8818:
8819: my %Saveable_Parameters=&clicker_grading_parameters();
8820: &Apache::loncommon::store_course_settings('grades_clicker',
8821: \%Saveable_Parameters);
8822: my $result='';
8823: if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
8824: $result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
8825: return $result;
8826: }
8827: if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
8828: $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
8829: return $result;
8830: }
8831: my $foundgiven=0;
8832: if ($env{'form.gradingmechanism'} eq 'given') {
8833: $env{'form.givenanswer'}=~s/^\s*//gs;
8834: $env{'form.givenanswer'}=~s/\s*$//gs;
8835: $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
8836: $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
8837: my @answers=split(/\,/,$env{'form.givenanswer'});
8838: $foundgiven=$#answers+1;
8839: }
8840: my %clicker_ids=&gather_clicker_ids();
8841: my %correct_ids;
8842: if ($env{'form.gradingmechanism'} eq 'personnel') {
8843: %correct_ids=&gather_adv_clicker_ids();
8844: }
8845: if ($env{'form.gradingmechanism'} eq 'specific') {
8846: foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
8847: $correct_id=~tr/a-z/A-Z/;
8848: $correct_id=~s/\s//gs;
8849: $correct_id=~s/^[\#0]+//;
8850: $correct_id=~s/[\-\:]//g;
8851: if ($correct_id) {
8852: $correct_ids{$correct_id}='specified';
8853: }
8854: }
8855: }
8856: if ($env{'form.gradingmechanism'} eq 'attendance') {
8857: $result.=&mt('Score based on attendance only');
8858: } elsif ($env{'form.gradingmechanism'} eq 'given') {
8859: $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
8860: } else {
8861: my $number=0;
8862: $result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
8863: foreach my $id (sort(keys(%correct_ids))) {
8864: $result.='<br /><tt>'.$id.'</tt> - ';
8865: if ($correct_ids{$id} eq 'specified') {
8866: $result.=&mt('specified');
8867: } else {
8868: my ($uname,$udom)=split(/\:/,$correct_ids{$id});
8869: $result.=&Apache::loncommon::plainname($uname,$udom);
8870: }
8871: $number++;
8872: }
8873: $result.="</p>\n";
8874: if ($number==0) {
8875: $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
8876: return $result;
8877: }
8878: }
8879: if (length($env{'form.upfile'}) < 2) {
8880: $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
8881: '<span class="LC_error">',
8882: '</span>',
8883: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
8884: return $result;
8885: }
8886:
8887: # Were able to get all the info needed, now analyze the file
8888:
8889: $result.=&Apache::loncommon::studentbrowser_javascript();
8890: $symb = &Apache::lonenc::check_encrypt($symb);
8891: my $heading=&mt('Scanning clicker file');
8892: $result.=(<<ENDHEADER);
8893: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
8894: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
8895: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
8896: <form method="post" action="/adm/grades" name="clickeranalysis">
8897: <input type="hidden" name="symb" value="$symb" />
8898: <input type="hidden" name="command" value="assignclickergrades" />
8899: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
8900: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
8901: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
8902: ENDHEADER
8903: if ($env{'form.gradingmechanism'} eq 'given') {
8904: $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
8905: }
8906: my %responses;
8907: my @questiontitles;
8908: my $errormsg='';
8909: my $number=0;
8910: if ($env{'form.upfiletype'} eq 'iclicker') {
8911: ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
8912: }
8913: if ($env{'form.upfiletype'} eq 'interwrite') {
8914: ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
8915: }
8916: $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
8917: '<input type="hidden" name="number" value="'.$number.'" />'.
8918: &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
8919: $env{'form.pcorrect'},$env{'form.pincorrect'}).
8920: '<br />';
8921: if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
8922: $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
8923: return $result;
8924: }
8925: # Remember Question Titles
8926: # FIXME: Possibly need delimiter other than ":"
8927: for (my $i=0;$i<$number;$i++) {
8928: $result.='<input type="hidden" name="question:'.$i.'" value="'.
8929: &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
8930: }
8931: my $correct_count=0;
8932: my $student_count=0;
8933: my $unknown_count=0;
8934: # Match answers with usernames
8935: # FIXME: Possibly need delimiter other than ":"
8936: foreach my $id (keys(%responses)) {
8937: if ($correct_ids{$id}) {
8938: $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
8939: $correct_count++;
8940: } elsif ($clicker_ids{$id}) {
8941: if ($clicker_ids{$id}=~/\,/) {
8942: # More than one user with the same clicker!
8943: $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
8944: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
8945: "<select name='multi".$id."'>";
8946: foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
8947: $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
8948: }
8949: $result.='</select>';
8950: $unknown_count++;
8951: } else {
8952: # Good: found one and only one user with the right clicker
8953: $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
8954: $student_count++;
8955: }
8956: } else {
8957: $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
8958: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
8959: "\n".&mt("Username").": <input type='text' name='uname".$id."' /> ".
8960: "\n".&mt("Domain").": ".
8961: &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).' '.
8962: &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
8963: $unknown_count++;
8964: }
8965: }
8966: $result.='<hr />'.
8967: &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
8968: if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
8969: if ($correct_count==0) {
8970: $errormsg.="Found no correct answers answers for grading!";
8971: } elsif ($correct_count>1) {
8972: $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
8973: }
8974: }
8975: if ($number<1) {
8976: $errormsg.="Found no questions.";
8977: }
8978: if ($errormsg) {
8979: $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
8980: } else {
8981: $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
8982: }
8983: $result.='</form></td></tr></table>'."\n".
8984: '</td></tr></table><br /><br />'."\n";
8985: return $result;
8986: }
8987:
8988: sub iclicker_eval {
8989: my ($questiontitles,$responses)=@_;
8990: my $number=0;
8991: my $errormsg='';
8992: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
8993: my %components=&Apache::loncommon::record_sep($line);
8994: my @entries=map {$components{$_}} (sort(keys(%components)));
8995: if ($entries[0] eq 'Question') {
8996: for (my $i=3;$i<$#entries;$i+=6) {
8997: $$questiontitles[$number]=$entries[$i];
8998: $number++;
8999: }
9000: }
9001: if ($entries[0]=~/^\#/) {
9002: my $id=$entries[0];
9003: my @idresponses;
9004: $id=~s/^[\#0]+//;
9005: for (my $i=0;$i<$number;$i++) {
9006: my $idx=3+$i*6;
9007: push(@idresponses,$entries[$idx]);
9008: }
9009: $$responses{$id}=join(',',@idresponses);
9010: }
9011: }
9012: return ($errormsg,$number);
9013: }
9014:
9015: sub interwrite_eval {
9016: my ($questiontitles,$responses)=@_;
9017: my $number=0;
9018: my $errormsg='';
9019: my $skipline=1;
9020: my $questionnumber=0;
9021: my %idresponses=();
9022: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
9023: my %components=&Apache::loncommon::record_sep($line);
9024: my @entries=map {$components{$_}} (sort(keys(%components)));
9025: if ($entries[1] eq 'Time') { $skipline=0; next; }
9026: if ($entries[1] eq 'Response') { $skipline=1; }
9027: next if $skipline;
9028: if ($entries[0]!=$questionnumber) {
9029: $questionnumber=$entries[0];
9030: $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
9031: $number++;
9032: }
9033: my $id=$entries[4];
9034: $id=~s/^[\#0]+//;
9035: $id=~s/^v\d*\://i;
9036: $id=~s/[\-\:]//g;
9037: $idresponses{$id}[$number]=$entries[6];
9038: }
9039: foreach my $id (keys(%idresponses)) {
9040: $$responses{$id}=join(',',@{$idresponses{$id}});
9041: $$responses{$id}=~s/^\s*\,//;
9042: }
9043: return ($errormsg,$number);
9044: }
9045:
9046: sub assign_clicker_grades {
9047: my ($r,$symb)=@_;
9048: if (!$symb) {return '';}
9049: # See which part we are saving to
9050: my $res_error;
9051: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
9052: if ($res_error) {
9053: return &navmap_errormsg();
9054: }
9055: # FIXME: This should probably look for the first handgradeable part
9056: my $part=$$partlist[0];
9057: # Start screen output
9058: my $result='';
9059:
9060: my $heading=&mt('Assigning grades based on clicker file');
9061: $result.=(<<ENDHEADER);
9062: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
9063: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
9064: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
9065: ENDHEADER
9066: # Get correct result
9067: # FIXME: Possibly need delimiter other than ":"
9068: my @correct=();
9069: my $gradingmechanism=$env{'form.gradingmechanism'};
9070: my $number=$env{'form.number'};
9071: if ($gradingmechanism ne 'attendance') {
9072: foreach my $key (keys(%env)) {
9073: if ($key=~/^form\.correct\:/) {
9074: my @input=split(/\,/,$env{$key});
9075: for (my $i=0;$i<=$#input;$i++) {
9076: if (($correct[$i]) && ($input[$i]) &&
9077: ($correct[$i] ne $input[$i])) {
9078: $result.='<br /><span class="LC_warning">'.
9079: &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
9080: $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
9081: } elsif ($input[$i]) {
9082: $correct[$i]=$input[$i];
9083: }
9084: }
9085: }
9086: }
9087: for (my $i=0;$i<$number;$i++) {
9088: if (!$correct[$i]) {
9089: $result.='<br /><span class="LC_error">'.
9090: &mt('No correct result given for question "[_1]"!',
9091: $env{'form.question:'.$i}).'</span>';
9092: }
9093: }
9094: $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
9095: }
9096: # Start grading
9097: my $pcorrect=$env{'form.pcorrect'};
9098: my $pincorrect=$env{'form.pincorrect'};
9099: my $storecount=0;
9100: foreach my $key (keys(%env)) {
9101: my $user='';
9102: if ($key=~/^form\.student\:(.*)$/) {
9103: $user=$1;
9104: }
9105: if ($key=~/^form\.unknown\:(.*)$/) {
9106: my $id=$1;
9107: if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
9108: $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
9109: } elsif ($env{'form.multi'.$id}) {
9110: $user=$env{'form.multi'.$id};
9111: }
9112: }
9113: if ($user) {
9114: my @answer=split(/\,/,$env{$key});
9115: my $sum=0;
9116: my $realnumber=$number;
9117: for (my $i=0;$i<$number;$i++) {
9118: if ($correct[$i] eq '-') {
9119: $realnumber--;
9120: } elsif ($answer[$i]) {
9121: if ($gradingmechanism eq 'attendance') {
9122: $sum+=$pcorrect;
9123: } elsif ($correct[$i] eq '*') {
9124: $sum+=$pcorrect;
9125: } else {
9126: if ($answer[$i] eq $correct[$i]) {
9127: $sum+=$pcorrect;
9128: } else {
9129: $sum+=$pincorrect;
9130: }
9131: }
9132: }
9133: }
9134: my $ave=$sum/(100*$realnumber);
9135: # Store
9136: my ($username,$domain)=split(/\:/,$user);
9137: my %grades=();
9138: $grades{"resource.$part.solved"}='correct_by_override';
9139: $grades{"resource.$part.awarded"}=$ave;
9140: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
9141: my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
9142: $env{'request.course.id'},
9143: $domain,$username);
9144: if ($returncode ne 'ok') {
9145: $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
9146: } else {
9147: $storecount++;
9148: }
9149: }
9150: }
9151: # We are done
9152: $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
9153: '</td></tr></table>'."\n".
9154: '</td></tr></table><br /><br />'."\n";
9155: return $result;
9156: }
9157:
9158: sub navmap_errormsg {
9159: return '<div class="LC_error">'.
9160: &mt('An error occurred retrieving information about resources in the course.').'<br />'.
9161: &mt('It is recommended that you [_1]re-initialize the course[_2] and then return to this grading page.','<a href="/adm/roles?selectrole=1&newrole='.$env{'request.role'}.'">','</a>').
9162: '</div>';
9163: }
9164:
9165: sub startpage {
9166: my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag) = @_;
9167: unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
9168: $r->print(&Apache::loncommon::start_page('Grading',undef,
9169: {'bread_crumbs' => $crumbs}));
9170: unless ($nodisplayflag) {
9171: $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag));
9172: }
9173: }
9174:
9175: sub select_problem {
9176: my ($r)=@_;
9177: $r->print('<h2>'.&mt('Select the problem or one of the problems you want to grade').'</h2><form action="/adm/grades">');
9178: $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
9179: $r->print('<input type="hidden" name="command" value="gradingmenu" />');
9180: $r->print('<input type="submit" value="'.&mt('Next').' →" /></form>');
9181: }
9182:
9183: sub handler {
9184: my $request=$_[0];
9185: &reset_caches();
9186: if ($env{'browser.mathml'}) {
9187: &Apache::loncommon::content_type($request,'text/xml');
9188: } else {
9189: &Apache::loncommon::content_type($request,'text/html');
9190: }
9191: $request->send_http_header;
9192: return '' if $request->header_only;
9193: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
9194:
9195: # see what command we need to execute
9196:
9197: my @commands=&Apache::loncommon::get_env_multiple('form.command');
9198: my $command=$commands[0];
9199:
9200: if ($#commands > 0) {
9201: &Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
9202: }
9203:
9204: # see what the symb is
9205:
9206: my $symb=$env{'form.symb'};
9207: unless ($symb) {
9208: (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
9209: $symb=&Apache::lonnet::symbread($url);
9210: }
9211: &Apache::lonenc::check_decrypt(\$symb);
9212:
9213: $ssi_error = 0;
9214: if ($symb eq '' || $command eq '') {
9215: #
9216: # Not called from a resource
9217: #
9218: &startpage($request,undef,[],1,1);
9219: &select_problem($request);
9220: } else {
9221: &init_perm();
9222: if ($command eq 'submission' && $perm{'vgr'}) {
9223: &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}]);
9224: ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
9225: } elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
9226: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
9227: {href=>'',text=>'Select student'}],1,1);
9228: &pickStudentPage($request,$symb);
9229: } elsif ($command eq 'displayPage' && $perm{'vgr'}) {
9230: &startpage($request,$symb,
9231: [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
9232: {href=>'',text=>'Select student'},
9233: {href=>'',text=>'Grade student'}],1,1);
9234: &displayPage($request,$symb);
9235: } elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
9236: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
9237: {href=>'',text=>'Select student'},
9238: {href=>'',text=>'Grade student'},
9239: {href=>'',text=>'Store grades'}],1,1);
9240: &updateGradeByPage($request,$symb);
9241: } elsif ($command eq 'processGroup' && $perm{'vgr'}) {
9242: &startpage($request,$symb,[{href=>'',text=>'...'},
9243: {href=>'',text=>'Modify grades'}]);
9244: &processGroup($request,$symb);
9245: } elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
9246: &startpage($request,$symb);
9247: $request->print(&grading_menu($request,$symb));
9248: } elsif ($command eq 'individual' && $perm{'vgr'}) {
9249: &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
9250: $request->print(&submit_options($request,$symb));
9251: } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
9252: &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
9253: $request->print(&listStudents($request,$symb,'graded'));
9254: } elsif ($command eq 'table' && $perm{'vgr'}) {
9255: &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
9256: $request->print(&submit_options_table($request,$symb));
9257: } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
9258: &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
9259: $request->print(&submit_options_sequence($request,$symb));
9260: } elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
9261: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
9262: $request->print(&viewgrades($request,$symb));
9263: } elsif ($command eq 'handgrade' && $perm{'mgr'}) {
9264: &startpage($request,$symb,[{href=>'',text=>'...'},
9265: {href=>'',text=>'Store grades'}]);
9266: $request->print(&processHandGrade($request,$symb));
9267: } elsif ($command eq 'editgrades' && $perm{'mgr'}) {
9268: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
9269: {href=>&href_symb_cmd($symb,'viewgrades').'&group=all§ion=all&Status=Active',
9270: text=>"Modify grades"},
9271: {href=>'', text=>"Store grades"}]);
9272: $request->print(&editgrades($request,$symb));
9273: } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
9274: &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
9275: $request->print(&initialverifyreceipt($request,$symb));
9276: } elsif ($command eq 'verify' && $perm{'vgr'}) {
9277: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
9278: {href=>'',text=>'Verification Result'}]);
9279: $request->print(&verifyreceipt($request,$symb));
9280: } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
9281: &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
9282: $request->print(&process_clicker($request,$symb));
9283: } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
9284: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
9285: {href=>'', text=>'Process clicker file'}]);
9286: $request->print(&process_clicker_file($request,$symb));
9287: } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
9288: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
9289: {href=>'', text=>'Process clicker file'},
9290: {href=>'', text=>'Store grades'}]);
9291: $request->print(&assign_clicker_grades($request,$symb));
9292: } elsif ($command eq 'csvform' && $perm{'mgr'}) {
9293: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
9294: $request->print(&upcsvScores_form($request,$symb));
9295: } elsif ($command eq 'csvupload' && $perm{'mgr'}) {
9296: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
9297: $request->print(&csvupload($request,$symb));
9298: } elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
9299: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
9300: $request->print(&csvuploadmap($request,$symb));
9301: } elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
9302: if ($env{'form.associate'} ne 'Reverse Association') {
9303: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
9304: $request->print(&csvuploadoptions($request,$symb));
9305: } else {
9306: if ( $env{'form.upfile_associate'} ne 'reverse' ) {
9307: $env{'form.upfile_associate'} = 'reverse';
9308: } else {
9309: $env{'form.upfile_associate'} = 'forward';
9310: }
9311: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
9312: $request->print(&csvuploadmap($request,$symb));
9313: }
9314: } elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
9315: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
9316: $request->print(&csvuploadassign($request,$symb));
9317: } elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
9318: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9319: $request->print(&scantron_selectphase($request,undef,$symb));
9320: } elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
9321: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9322: $request->print(&scantron_do_warning($request,$symb));
9323: } elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
9324: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9325: $request->print(&scantron_validate_file($request,$symb));
9326: } elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
9327: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9328: $request->print(&scantron_process_students($request,$symb));
9329: } elsif ($command eq 'scantronupload' &&
9330: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
9331: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
9332: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9333: $request->print(&scantron_upload_scantron_data($request,$symb));
9334: } elsif ($command eq 'scantronupload_save' &&
9335: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
9336: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
9337: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9338: $request->print(&scantron_upload_scantron_data_save($request,$symb));
9339: } elsif ($command eq 'scantron_download' &&
9340: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
9341: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9342: $request->print(&scantron_download_scantron_data($request,$symb));
9343: } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
9344: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9345: $request->print(&checkscantron_results($request,$symb));
9346: } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
9347: &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
9348: $request->print(&submit_options_download($request,$symb));
9349: } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
9350: &startpage($request,$symb,
9351: [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
9352: {href=>'', text=>'Download submissions'}]);
9353: &submit_download_link($request,$symb);
9354: } elsif ($command) {
9355: &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
9356: $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
9357: }
9358: }
9359: if ($ssi_error) {
9360: &ssi_print_error($request);
9361: }
9362: $request->print(&Apache::loncommon::end_page());
9363: &reset_caches();
9364: return '';
9365: }
9366:
9367: 1;
9368:
9369: __END__;
9370:
9371:
9372: =head1 NAME
9373:
9374: Apache::grades
9375:
9376: =head1 SYNOPSIS
9377:
9378: Handles the viewing of grades.
9379:
9380: This is part of the LearningOnline Network with CAPA project
9381: described at http://www.lon-capa.org.
9382:
9383: =head1 OVERVIEW
9384:
9385: Do an ssi with retries:
9386: While I'd love to factor out this with the vesrion in lonprintout,
9387: that would either require a data coupling between modules, which I refuse to perpetuate (there's quite enough of that already), or would require the invention of another infrastructure
9388: I'm not quite ready to invent (e.g. an ssi_with_retry object).
9389:
9390: At least the logic that drives this has been pulled out into loncommon.
9391:
9392:
9393:
9394: ssi_with_retries - Does the server side include of a resource.
9395: if the ssi call returns an error we'll retry it up to
9396: the number of times requested by the caller.
9397: If we still have a proble, no text is appended to the
9398: output and we set some global variables.
9399: to indicate to the caller an SSI error occurred.
9400: All of this is supposed to deal with the issues described
9401: in LonCAPA BZ 5631 see:
9402: http://bugs.lon-capa.org/show_bug.cgi?id=5631
9403: by informing the user that this happened.
9404:
9405: Parameters:
9406: resource - The resource to include. This is passed directly, without
9407: interpretation to lonnet::ssi.
9408: form - The form hash parameters that guide the interpretation of the resource
9409:
9410: retries - Number of retries allowed before giving up completely.
9411: Returns:
9412: On success, returns the rendered resource identified by the resource parameter.
9413: Side Effects:
9414: The following global variables can be set:
9415: ssi_error - If an unrecoverable error occurred this becomes true.
9416: It is up to the caller to initialize this to false
9417: if desired.
9418: ssi_error_resource - If an unrecoverable error occurred, this is the value
9419: of the resource that could not be rendered by the ssi
9420: call.
9421: ssi_error_message - The error string fetched from the ssi response
9422: in the event of an error.
9423:
9424:
9425: =head1 HANDLER SUBROUTINE
9426:
9427: ssi_with_retries()
9428:
9429: =head1 SUBROUTINES
9430:
9431: =over
9432:
9433: =item scantron_get_correction() :
9434:
9435: Builds the interface screen to interact with the operator to fix a
9436: specific error condition in a specific scanline
9437:
9438: Arguments:
9439: $r - Apache request object
9440: $i - number of the current scanline
9441: $scan_record - hash ref as returned from &scantron_parse_scanline()
9442: $scan_config - hash ref as returned from &get_scantron_config()
9443: $line - full contents of the current scanline
9444: $error - error condition, valid values are
9445: 'incorrectCODE', 'duplicateCODE',
9446: 'doublebubble', 'missingbubble',
9447: 'duplicateID', 'incorrectID'
9448: $arg - extra information needed
9449: For errors:
9450: - duplicateID - paper number that this studentID was seen before on
9451: - duplicateCODE - array ref of the paper numbers this CODE was
9452: seen on before
9453: - incorrectCODE - current incorrect CODE
9454: - doublebubble - array ref of the bubble lines that have double
9455: bubble errors
9456: - missingbubble - array ref of the bubble lines that have missing
9457: bubble errors
9458:
9459: =item scantron_get_maxbubble() :
9460:
9461: Arguments:
9462: $nav_error - Reference to scalar which is a flag to indicate a
9463: failure to retrieve a navmap object.
9464: if $nav_error is set to 1 by scantron_get_maxbubble(), the
9465: calling routine should trap the error condition and display the warning
9466: found in &navmap_errormsg().
9467:
9468: Returns the maximum number of bubble lines that are expected to
9469: occur. Does this by walking the selected sequence rendering the
9470: resource and then checking &Apache::lonxml::get_problem_counter()
9471: for what the current value of the problem counter is.
9472:
9473: Caches the results to $env{'form.scantron_maxbubble'},
9474: $env{'form.scantron.bubble_lines.n'},
9475: $env{'form.scantron.first_bubble_line.n'} and
9476: $env{"form.scantron.sub_bubblelines.n"}
9477: which are the total number of bubble, lines, the number of bubble
9478: lines for response n and number of the first bubble line for response n,
9479: and a comma separated list of numbers of bubble lines for sub-questions
9480: (for optionresponse, matchresponse, and rankresponse items), for response n.
9481:
9482:
9483: =item scantron_validate_missingbubbles() :
9484:
9485: Validates all scanlines in the selected file to not have any
9486: answers that don't have bubbles that have not been verified
9487: to be bubble free.
9488:
9489: =item scantron_process_students() :
9490:
9491: Routine that does the actual grading of the bubble sheet information.
9492:
9493: The parsed scanline hash is added to %env
9494:
9495: Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
9496: foreach resource , with the form data of
9497:
9498: 'submitted' =>'scantron'
9499: 'grade_target' =>'grade',
9500: 'grade_username'=> username of student
9501: 'grade_domain' => domain of student
9502: 'grade_courseid'=> of course
9503: 'grade_symb' => symb of resource to grade
9504:
9505: This triggers a grading pass. The problem grading code takes care
9506: of converting the bubbled letter information (now in %env) into a
9507: valid submission.
9508:
9509: =item scantron_upload_scantron_data() :
9510:
9511: Creates the screen for adding a new bubble sheet data file to a course.
9512:
9513: =item scantron_upload_scantron_data_save() :
9514:
9515: Adds a provided bubble information data file to the course if user
9516: has the correct privileges to do so.
9517:
9518: =item valid_file() :
9519:
9520: Validates that the requested bubble data file exists in the course.
9521:
9522: =item scantron_download_scantron_data() :
9523:
9524: Shows a list of the three internal files (original, corrected,
9525: skipped) for a specific bubble sheet data file that exists in the
9526: course.
9527:
9528: =item scantron_validate_ID() :
9529:
9530: Validates all scanlines in the selected file to not have any
9531: invalid or underspecified student/employee IDs
9532:
9533: =item navmap_errormsg() :
9534:
9535: Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
9536: Should be called whenever the request to instantiate a navmap object fails.
9537:
9538: =back
9539:
9540: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>