1: # The LearningOnline Network with CAPA
2: # The LON-CAPA Grading handler
3: #
4: # $Id: grades.pm,v 1.748 2017/12/31 13:29:53 raeburn 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 :http);
44: use Apache::lonlocal;
45: use Apache::lonenc;
46: use Apache::lonstathelpers;
47: use Apache::lonquickgrades;
48: use Apache::bridgetask();
49: use String::Similarity;
50: use LONCAPA;
51:
52: use POSIX qw(floor);
53:
54:
55:
56: my %perm=();
57: my %old_essays=();
58:
59: # These variables are used to recover from ssi errors
60:
61: my $ssi_retries = 5;
62: my $ssi_error;
63: my $ssi_error_resource;
64: my $ssi_error_message;
65:
66:
67: sub ssi_with_retries {
68: my ($resource, $retries, %form) = @_;
69: my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
70: if ($response->is_error) {
71: $ssi_error = 1;
72: $ssi_error_resource = $resource;
73: $ssi_error_message = $response->code . " " . $response->message;
74: }
75:
76: return $content;
77:
78: }
79: #
80: # Prodcuces an ssi retry failure error message to the user:
81: #
82:
83: sub ssi_print_error {
84: my ($r) = @_;
85: my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
86: $r->print('
87: <br />
88: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
89: <p>
90: '.&mt('Unable to retrieve a resource from a server:').'<br />
91: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
92: '.&mt('Error:').' '.$ssi_error_message.'
93: </p>
94: <p>'.
95: &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 />'.
96: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
97: '</p>');
98: return;
99: }
100:
101: #
102: # --- Retrieve the parts from the metadata file.---
103: # Returns an array of everything that the resources stores away
104: #
105:
106: sub getpartlist {
107: my ($symb,$errorref) = @_;
108:
109: my $navmap = Apache::lonnavmaps::navmap->new();
110: unless (ref($navmap)) {
111: if (ref($errorref)) {
112: $$errorref = 'navmap';
113: return;
114: }
115: }
116: my $res = $navmap->getBySymb($symb);
117: my $partlist = $res->parts();
118: my $url = $res->src();
119: my $toolsymb;
120: if ($url =~ /ext\.tool$/) {
121: $toolsymb = $symb;
122: }
123: my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys',$toolsymb));
124:
125: my @stores;
126: foreach my $part (@{ $partlist }) {
127: foreach my $key (@metakeys) {
128: if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
129: }
130: }
131: return @stores;
132: }
133:
134: #--- Format fullname, username:domain if different for display
135: #--- Use anywhere where the student names are listed
136: sub nameUserString {
137: my ($type,$fullname,$uname,$udom) = @_;
138: if ($type eq 'header') {
139: return '<b> '.&mt('Fullname').' </b><span class="LC_internal_info">('.&mt('Username').')</span>';
140: } else {
141: return ' '.$fullname.'<span class="LC_internal_info"> ('.$uname.
142: ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
143: }
144: }
145:
146: #--- Get the partlist and the response type for a given problem. ---
147: #--- Indicate if a response type is coded handgraded or not. ---
148: #--- Sets response_error pointer to "1" if navmaps object broken ---
149: sub response_type {
150: my ($symb,$response_error) = @_;
151:
152: my $navmap = Apache::lonnavmaps::navmap->new();
153: unless (ref($navmap)) {
154: if (ref($response_error)) {
155: $$response_error = 1;
156: }
157: return;
158: }
159: my $res = $navmap->getBySymb($symb);
160: unless (ref($res)) {
161: $$response_error = 1;
162: return;
163: }
164: my $partlist = $res->parts();
165: my %vPart =
166: map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
167: my (%response_types,%handgrade);
168: foreach my $part (@{ $partlist }) {
169: next if (%vPart && !exists($vPart{$part}));
170:
171: my @types = $res->responseType($part);
172: my @ids = $res->responseIds($part);
173: for (my $i=0; $i < scalar(@ids); $i++) {
174: $response_types{$part}{$ids[$i]} = $types[$i];
175: $handgrade{$part.'_'.$ids[$i]} =
176: &Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
177: '.handgrade',$symb);
178: }
179: }
180: return ($partlist,\%handgrade,\%response_types);
181: }
182:
183: sub flatten_responseType {
184: my ($responseType) = @_;
185: my @part_response_id =
186: map {
187: my $part = $_;
188: map {
189: [$part,$_]
190: } sort(keys(%{ $responseType->{$part} }));
191: } sort(keys(%$responseType));
192: return @part_response_id;
193: }
194:
195: sub get_display_part {
196: my ($partID,$symb)=@_;
197: my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
198: if (defined($display) and $display ne '') {
199: $display.= ' (<span class="LC_internal_info">'
200: .&mt('Part ID: [_1]',$partID).'</span>)';
201: } else {
202: $display=$partID;
203: }
204: return $display;
205: }
206:
207: sub reset_caches {
208: &reset_analyze_cache();
209: &reset_perm();
210: &reset_old_essays();
211: }
212:
213: {
214: my %analyze_cache;
215: my %analyze_cache_formkeys;
216:
217: sub reset_analyze_cache {
218: undef(%analyze_cache);
219: undef(%analyze_cache_formkeys);
220: }
221:
222: sub get_analyze {
223: my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
224: my $key = "$symb\0$uname\0$udom";
225: if ($type eq 'randomizetry') {
226: if ($trial ne '') {
227: $key .= "\0".$trial;
228: }
229: }
230: if (exists($analyze_cache{$key})) {
231: my $getupdate = 0;
232: if (ref($add_to_hash) eq 'HASH') {
233: foreach my $item (keys(%{$add_to_hash})) {
234: if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
235: if (!exists($analyze_cache_formkeys{$key}{$item})) {
236: $getupdate = 1;
237: last;
238: }
239: } else {
240: $getupdate = 1;
241: }
242: }
243: }
244: if (!$getupdate) {
245: return $analyze_cache{$key};
246: }
247: }
248:
249: my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
250: $url=&Apache::lonnet::clutter($url);
251: my %form = ('grade_target' => 'analyze',
252: 'grade_domain' => $udom,
253: 'grade_symb' => $symb,
254: 'grade_courseid' => $env{'request.course.id'},
255: 'grade_username' => $uname,
256: 'grade_noincrement' => $no_increment);
257: if ($bubbles_per_row ne '') {
258: $form{'bubbles_per_row'} = $bubbles_per_row;
259: }
260: if ($type eq 'randomizetry') {
261: $form{'grade_questiontype'} = $type;
262: if ($rndseed ne '') {
263: $form{'grade_rndseed'} = $rndseed;
264: }
265: }
266: if (ref($add_to_hash)) {
267: %form = (%form,%{$add_to_hash});
268: }
269: my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
270: (undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
271: my %analyze=&Apache::lonnet::str2hash($subresult);
272: if (ref($add_to_hash) eq 'HASH') {
273: $analyze_cache_formkeys{$key} = $add_to_hash;
274: } else {
275: $analyze_cache_formkeys{$key} = {};
276: }
277: return $analyze_cache{$key} = \%analyze;
278: }
279:
280: sub get_order {
281: my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
282: my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
283: return $analyze->{"$partid.$respid.shown"};
284: }
285:
286: sub get_radiobutton_correct_foil {
287: my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
288: my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
289: my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
290: if (ref($foils) eq 'ARRAY') {
291: foreach my $foil (@{$foils}) {
292: if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
293: return $foil;
294: }
295: }
296: }
297: }
298:
299: sub scantron_partids_tograde {
300: my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row,$scancode) = @_;
301: my (%analysis,@parts);
302: if (ref($resource)) {
303: my $symb = $resource->symb();
304: my $add_to_form;
305: if ($check_for_randomlist) {
306: $add_to_form = { 'check_parts_withrandomlist' => 1,};
307: }
308: if ($scancode) {
309: if (ref($add_to_form) eq 'HASH') {
310: $add_to_form->{'code_for_randomlist'} = $scancode;
311: } else {
312: $add_to_form = { 'code_for_randomlist' => $scancode,};
313: }
314: }
315: my $analyze =
316: &get_analyze($symb,$uname,$udom,undef,$add_to_form,
317: undef,undef,undef,$bubbles_per_row);
318: if (ref($analyze) eq 'HASH') {
319: %analysis = %{$analyze};
320: }
321: if (ref($analysis{'parts'}) eq 'ARRAY') {
322: foreach my $part (@{$analysis{'parts'}}) {
323: my ($id,$respid) = split(/\./,$part);
324: if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
325: push(@parts,$part);
326: }
327: }
328: }
329: }
330: return (\%analysis,\@parts);
331: }
332:
333: }
334:
335: #--- Clean response type for display
336: #--- Currently filters option/rank/radiobutton/match/essay/Task
337: # response types only.
338: sub cleanRecord {
339: my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
340: $uname,$udom,$type,$trial,$rndseed) = @_;
341: my $grayFont = '<span class="LC_internal_info">';
342: if ($response =~ /^(option|rank)$/) {
343: my %answer=&Apache::lonnet::str2hash($answer);
344: my @answer = %answer;
345: %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
346: my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
347: my ($toprow,$bottomrow);
348: foreach my $foil (@$order) {
349: if ($grading{$foil} == 1) {
350: $toprow.='<td><b>'.$answer{$foil}.' </b></td>';
351: } else {
352: $toprow.='<td><i>'.$answer{$foil}.' </i></td>';
353: }
354: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
355: }
356: return '<blockquote><table border="1">'.
357: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
358: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
359: $bottomrow.'</tr></table></blockquote>';
360: } elsif ($response eq 'match') {
361: my %answer=&Apache::lonnet::str2hash($answer);
362: my @answer = %answer;
363: %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
364: my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
365: my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
366: my ($toprow,$middlerow,$bottomrow);
367: foreach my $foil (@$order) {
368: my $item=shift(@items);
369: if ($grading{$foil} == 1) {
370: $toprow.='<td><b>'.$item.' </b></td>';
371: $middlerow.='<td><b>'.$grayFont.$answer{$foil}.' </span></b></td>';
372: } else {
373: $toprow.='<td><i>'.$item.' </i></td>';
374: $middlerow.='<td><i>'.$grayFont.$answer{$foil}.' </span></i></td>';
375: }
376: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
377: }
378: return '<blockquote><table border="1">'.
379: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
380: '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
381: $middlerow.'</tr>'.
382: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
383: $bottomrow.'</tr></table></blockquote>';
384: } elsif ($response eq 'radiobutton') {
385: my %answer=&Apache::lonnet::str2hash($answer);
386: my @answer = %answer;
387: %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
388: my ($toprow,$bottomrow);
389: my $correct =
390: &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
391: foreach my $foil (@$order) {
392: if (exists($answer{$foil})) {
393: if ($foil eq $correct) {
394: $toprow.='<td><b>'.&mt('true').'</b></td>';
395: } else {
396: $toprow.='<td><i>'.&mt('true').'</i></td>';
397: }
398: } else {
399: $toprow.='<td>'.&mt('false').'</td>';
400: }
401: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
402: }
403: return '<blockquote><table border="1">'.
404: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
405: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
406: $bottomrow.'</tr></table></blockquote>';
407: } elsif ($response eq 'essay') {
408: if (! exists ($env{'form.'.$symb})) {
409: my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
410: $env{'course.'.$env{'request.course.id'}.'.domain'},
411: $env{'course.'.$env{'request.course.id'}.'.num'});
412:
413: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
414: $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
415: $env{'form.kwclr'} = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
416: $env{'form.kwsize'} = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
417: $env{'form.kwstyle'} = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
418: $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
419: }
420: return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
421:
422: } elsif ( $response eq 'organic') {
423: my $result=&mt('Smile representation: [_1]',
424: '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
425: my $jme=$record->{$version."resource.$partid.$respid.molecule"};
426: $result.=&Apache::chemresponse::jme_img($jme,$answer,400);
427: return $result;
428: } elsif ( $response eq 'Task') {
429: if ( $answer eq 'SUBMITTED') {
430: my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
431: my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
432: return $result;
433: } elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
434: my @matches = grep(/^\Q$version\E.*?\.instance$/,
435: keys(%{$record}));
436: return join('<br />',($version,@matches));
437:
438:
439: } else {
440: my $result =
441: '<p>'
442: .&mt('Overall result: [_1]',
443: $record->{$version."resource.$respid.$partid.status"})
444: .'</p>';
445:
446: $result .= '<ul>';
447: my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
448: keys(%{$record}));
449: foreach my $grade (sort(@grade)) {
450: my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
451: $result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
452: $dim, $record->{$grade}).
453: '</li>';
454: }
455: $result.='</ul>';
456: return $result;
457: }
458: } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
459: # Respect multiple input fields, see Bug #5409
460: $answer =
461: &Apache::loncommon::format_previous_attempt_value('submission',
462: $answer);
463: return $answer;
464: }
465: return &HTML::Entities::encode($answer, '"<>&');
466: }
467:
468: #-- A couple of common js functions
469: sub commonJSfunctions {
470: my $request = shift;
471: $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
472: function radioSelection(radioButton) {
473: var selection=null;
474: if (radioButton.length > 1) {
475: for (var i=0; i<radioButton.length; i++) {
476: if (radioButton[i].checked) {
477: return radioButton[i].value;
478: }
479: }
480: } else {
481: if (radioButton.checked) return radioButton.value;
482: }
483: return selection;
484: }
485:
486: function pullDownSelection(selectOne) {
487: var selection="";
488: if (selectOne.length > 1) {
489: for (var i=0; i<selectOne.length; i++) {
490: if (selectOne[i].selected) {
491: return selectOne[i].value;
492: }
493: }
494: } else {
495: // only one value it must be the selected one
496: return selectOne.value;
497: }
498: }
499: COMMONJSFUNCTIONS
500: }
501:
502: #--- Dumps the class list with usernames,list of sections,
503: #--- section, ids and fullnames for each user.
504: sub getclasslist {
505: my ($getsec,$filterlist,$getgroup) = @_;
506: my @getsec;
507: my @getgroup;
508: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
509: if (!ref($getsec)) {
510: if ($getsec ne '' && $getsec ne 'all') {
511: @getsec=($getsec);
512: }
513: } else {
514: @getsec=@{$getsec};
515: }
516: if (grep(/^all$/,@getsec)) { undef(@getsec); }
517: if (!ref($getgroup)) {
518: if ($getgroup ne '' && $getgroup ne 'all') {
519: @getgroup=($getgroup);
520: }
521: } else {
522: @getgroup=@{$getgroup};
523: }
524: if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
525:
526: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
527: # Bail out if we were unable to get the classlist
528: return if (! defined($classlist));
529: &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
530: #
531: my %sections;
532: my %fullnames;
533: foreach my $student (keys(%$classlist)) {
534: my $end =
535: $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
536: my $start =
537: $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
538: my $id =
539: $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
540: my $section =
541: $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
542: my $fullname =
543: $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
544: my $status =
545: $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
546: my $group =
547: $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
548: # filter students according to status selected
549: if ($filterlist && (!($stu_status =~ /Any/))) {
550: if (!($stu_status =~ $status)) {
551: delete($classlist->{$student});
552: next;
553: }
554: }
555: # filter students according to groups selected
556: my @stu_groups = split(/,/,$group);
557: if (@getgroup) {
558: my $exclude = 1;
559: foreach my $grp (@getgroup) {
560: foreach my $stu_group (@stu_groups) {
561: if ($stu_group eq $grp) {
562: $exclude = 0;
563: }
564: }
565: if (($grp eq 'none') && !$group) {
566: $exclude = 0;
567: }
568: }
569: if ($exclude) {
570: delete($classlist->{$student});
571: }
572: }
573: $section = ($section ne '' ? $section : 'none');
574: if (&canview($section)) {
575: if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
576: $sections{$section}++;
577: if ($classlist->{$student}) {
578: $fullnames{$student}=$fullname;
579: }
580: } else {
581: delete($classlist->{$student});
582: }
583: } else {
584: delete($classlist->{$student});
585: }
586: }
587: my %seen = ();
588: my @sections = sort(keys(%sections));
589: return ($classlist,\@sections,\%fullnames);
590: }
591:
592: sub canmodify {
593: my ($sec)=@_;
594: if ($perm{'mgr'}) {
595: if (!defined($perm{'mgr_section'})) {
596: # can modify whole class
597: return 1;
598: } else {
599: if ($sec eq $perm{'mgr_section'}) {
600: #can modify the requested section
601: return 1;
602: } else {
603: # can't modify the request section
604: return 0;
605: }
606: }
607: }
608: #can't modify
609: return 0;
610: }
611:
612: sub canview {
613: my ($sec)=@_;
614: if ($perm{'vgr'}) {
615: if (!defined($perm{'vgr_section'})) {
616: # can modify whole class
617: return 1;
618: } else {
619: if ($sec eq $perm{'vgr_section'}) {
620: #can modify the requested section
621: return 1;
622: } else {
623: # can't modify the request section
624: return 0;
625: }
626: }
627: }
628: #can't modify
629: return 0;
630: }
631:
632: #--- Retrieve the grade status of a student for all the parts
633: sub student_gradeStatus {
634: my ($symb,$udom,$uname,$partlist) = @_;
635: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
636: my %partstatus = ();
637: foreach (@$partlist) {
638: my ($status,undef) = split(/_/,$record{"resource.$_.solved"},2);
639: $status = 'nothing' if ($status eq '');
640: $partstatus{$_} = $status;
641: my $subkey = "resource.$_.submitted_by";
642: $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
643: }
644: return %partstatus;
645: }
646:
647: # hidden form and javascript that calls the form
648: # Use by verifyscript and viewgrades
649: # Shows a student's view of problem and submission
650: sub jscriptNform {
651: my ($symb) = @_;
652: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
653: my $jscript= &Apache::lonhtmlcommon::scripttag(
654: ' function viewOneStudent(user,domain) {'."\n".
655: ' document.onestudent.student.value = user;'."\n".
656: ' document.onestudent.userdom.value = domain;'."\n".
657: ' document.onestudent.submit();'."\n".
658: ' }'."\n".
659: "\n");
660: $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
661: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
662: '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
663: '<input type="hidden" name="command" value="submission" />'."\n".
664: '<input type="hidden" name="student" value="" />'."\n".
665: '<input type="hidden" name="userdom" value="" />'."\n".
666: '</form>'."\n";
667: return $jscript;
668: }
669:
670:
671:
672: # Given the score (as a number [0-1] and the weight) what is the final
673: # point value? This function will round to the nearest tenth, third,
674: # or quarter if one of those is within the tolerance of .00001.
675: sub compute_points {
676: my ($score, $weight) = @_;
677:
678: my $tolerance = .00001;
679: my $points = $score * $weight;
680:
681: # Check for nearness to 1/x.
682: my $check_for_nearness = sub {
683: my ($factor) = @_;
684: my $num = ($points * $factor) + $tolerance;
685: my $floored_num = floor($num);
686: if ($num - $floored_num < 2 * $tolerance * $factor) {
687: return $floored_num / $factor;
688: }
689: return $points;
690: };
691:
692: $points = $check_for_nearness->(10);
693: $points = $check_for_nearness->(3);
694: $points = $check_for_nearness->(4);
695:
696: return $points;
697: }
698:
699: #------------------ End of general use routines --------------------
700:
701: #
702: # Find most similar essay
703: #
704:
705: sub most_similar {
706: my ($uname,$udom,$symb,$uessay)=@_;
707:
708: unless ($symb) { return ''; }
709:
710: unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
711:
712: # ignore spaces and punctuation
713:
714: $uessay=~s/\W+/ /gs;
715:
716: # ignore empty submissions (occuring when only files are sent)
717:
718: unless ($uessay=~/\w+/s) { return ''; }
719:
720: # these will be returned. Do not care if not at least 50 percent similar
721: my $limit=0.6;
722: my $sname='';
723: my $sdom='';
724: my $scrsid='';
725: my $sessay='';
726: # go through all essays ...
727: foreach my $tkey (keys(%{$old_essays{$symb}})) {
728: my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
729: # ... except the same student
730: next if (($tname eq $uname) && ($tdom eq $udom));
731: my $tessay=$old_essays{$symb}{$tkey};
732: $tessay=~s/\W+/ /gs;
733: # String similarity gives up if not even limit
734: my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
735: # Found one
736: if ($tsimilar>$limit) {
737: $limit=$tsimilar;
738: $sname=$tname;
739: $sdom=$tdom;
740: $scrsid=$tcrsid;
741: $sessay=$old_essays{$symb}{$tkey};
742: }
743: }
744: if ($limit>0.6) {
745: return ($sname,$sdom,$scrsid,$sessay,$limit);
746: } else {
747: return ('','','','',0);
748: }
749: }
750:
751: #-------------------------------------------------------------------
752:
753: #------------------------------------ Receipt Verification Routines
754: #
755:
756: sub initialverifyreceipt {
757: my ($request,$symb) = @_;
758: &commonJSfunctions($request);
759: return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
760: &Apache::lonnet::recprefix($env{'request.course.id'}).
761: '-<input type="text" name="receipt" size="4" />'.
762: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
763: '<input type="hidden" name="command" value="verify" />'.
764: "</form>\n";
765: }
766:
767: #--- Check whether a receipt number is valid.---
768: sub verifyreceipt {
769: my ($request,$symb) = @_;
770:
771: my $courseid = $env{'request.course.id'};
772: my $receipt = &Apache::lonnet::recprefix($courseid).'-'.
773: $env{'form.receipt'};
774: $receipt =~ s/[^\-\d]//g;
775:
776: my $title.=
777: '<h3><span class="LC_info">'.
778: &mt('Verifying Receipt Number [_1]',$receipt).
779: '</span></h3>'."\n";
780:
781: my ($string,$contents,$matches) = ('','',0);
782: my (undef,undef,$fullname) = &getclasslist('all','0');
783:
784: my $receiptparts=0;
785: if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
786: $env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
787: my $parts=['0'];
788: if ($receiptparts) {
789: my $res_error;
790: ($parts)=&response_type($symb,\$res_error);
791: if ($res_error) {
792: return &navmap_errormsg();
793: }
794: }
795:
796: my $header =
797: &Apache::loncommon::start_data_table().
798: &Apache::loncommon::start_data_table_header_row().
799: '<th> '.&mt('Fullname').' </th>'."\n".
800: '<th> '.&mt('Username').' </th>'."\n".
801: '<th> '.&mt('Domain').' </th>';
802: if ($receiptparts) {
803: $header.='<th> '.&mt('Problem Part').' </th>';
804: }
805: $header.=
806: &Apache::loncommon::end_data_table_header_row();
807:
808: foreach (sort
809: {
810: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
811: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
812: }
813: return $a cmp $b;
814: } (keys(%$fullname))) {
815: my ($uname,$udom)=split(/\:/);
816: foreach my $part (@$parts) {
817: if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
818: $contents.=
819: &Apache::loncommon::start_data_table_row().
820: '<td> '."\n".
821: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
822: '\');" target="_self">'.$$fullname{$_}.'</a> </td>'."\n".
823: '<td> '.$uname.' </td>'.
824: '<td> '.$udom.' </td>';
825: if ($receiptparts) {
826: $contents.='<td> '.$part.' </td>';
827: }
828: $contents.=
829: &Apache::loncommon::end_data_table_row()."\n";
830:
831: $matches++;
832: }
833: }
834: }
835: if ($matches == 0) {
836: $string = $title
837: .'<p class="LC_warning">'
838: .&mt('No match found for the above receipt number.')
839: .'</p>';
840: } else {
841: $string = &jscriptNform($symb).$title.
842: '<p>'.
843: &mt('The above receipt number matches the following [quant,_1,student].',$matches).
844: '</p>'.
845: $header.
846: $contents.
847: &Apache::loncommon::end_data_table()."\n";
848: }
849: return $string;
850: }
851:
852: #--- This is called by a number of programs.
853: #--- Called from the Grading Menu - View/Grade an individual student
854: #--- Also called directly when one clicks on the subm button
855: # on the problem page.
856: sub listStudents {
857: my ($request,$symb,$submitonly) = @_;
858:
859: my $is_tool = ($symb =~ /ext\.tool$/);
860: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
861: my $cnum = $env{"course.$env{'request.course.id'}.num"};
862: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
863: my $getgroup = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
864: unless ($submitonly) {
865: $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
866: }
867:
868: my $result='';
869: my $res_error;
870: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
871:
872: my %js_lt = &Apache::lonlocal::texthash (
873: 'multiple' => 'Please select a student or group of students before clicking on the Next button.',
874: 'single' => 'Please select the student before clicking on the Next button.',
875: );
876: &js_escape(\%js_lt);
877: $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
878: function checkSelect(checkBox) {
879: var ctr=0;
880: var sense="";
881: if (checkBox.length > 1) {
882: for (var i=0; i<checkBox.length; i++) {
883: if (checkBox[i].checked) {
884: ctr++;
885: }
886: }
887: sense = '$js_lt{'multiple'}';
888: } else {
889: if (checkBox.checked) {
890: ctr = 1;
891: }
892: sense = '$js_lt{'single'}';
893: }
894: if (ctr == 0) {
895: alert(sense);
896: return false;
897: }
898: document.gradesub.submit();
899: }
900:
901: function reLoadList(formname) {
902: if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
903: formname.command.value = 'submission';
904: formname.submit();
905: }
906: LISTJAVASCRIPT
907:
908: &commonJSfunctions($request);
909: $request->print($result);
910:
911: my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
912: "\n";
913:
914: $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
915: unless ($is_tool) {
916: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
917: .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
918: .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
919: .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
920: .&Apache::lonhtmlcommon::row_closure();
921: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
922: .'<label><input type="radio" name="vAns" value="no" /> '.&mt('no').' </label>'."\n"
923: .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
924: .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
925: .&Apache::lonhtmlcommon::row_closure();
926: }
927:
928: my $submission_options;
929: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
930: my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
931: $env{'form.Status'} = $saveStatus;
932: my %optiontext;
933: if ($is_tool) {
934: %optiontext = &Apache::lonlocal::texthash (
935: lastonly => 'last transaction',
936: last => 'last transaction with details',
937: datesub => 'all transactions',
938: all => 'all transactions with details',
939: );
940: } else {
941: %optiontext = &Apache::lonlocal::texthash (
942: lastonly => 'last submission',
943: last => 'last submission with details',
944: datesub => 'all submissions',
945: all => 'all submissions with details',
946: );
947: }
948: $submission_options.=
949: '<span class="LC_nobreak">'.
950: '<label><input type="radio" name="lastSub" value="lastonly" /> '.
951: $optiontext{'lastonly'}.' </label></span>'."\n".
952: '<span class="LC_nobreak">'.
953: '<label><input type="radio" name="lastSub" value="last" /> '.
954: $optiontext{'last'}.' </label></span>'."\n".
955: '<span class="LC_nobreak">'.
956: '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
957: $optiontext{'datesub'}.'</label></span>'."\n".
958: '<span class="LC_nobreak">'.
959: '<label><input type="radio" name="lastSub" value="all" /> '.
960: $optiontext{'all'}.'</label></span>';
961: my $viewtitle;
962: if ($is_tool) {
963: $viewtitle = &mt('View Transactions');
964: } else {
965: $viewtitle = &mt('View Submissions');
966: }
967: $gradeTable .= &Apache::lonhtmlcommon::row_title($viewtitle)
968: .$submission_options
969: .&Apache::lonhtmlcommon::row_closure();
970:
971: my $closure;
972: if (($is_tool) && (exists($env{'form.Status'}))) {
973: $closure = 1;
974: }
975: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
976: .'<select name="increment">'
977: .'<option value="1">'.&mt('Whole Points').'</option>'
978: .'<option value=".5">'.&mt('Half Points').'</option>'
979: .'<option value=".25">'.&mt('Quarter Points').'</option>'
980: .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
981: .'</select>'
982: .&Apache::lonhtmlcommon::row_closure($closure);
983:
984: $gradeTable .=
985: &build_section_inputs().
986: '<input type="hidden" name="submitonly" value="'.$submitonly.'" />'."\n".
987: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
988: '<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
989:
990: if (exists($env{'form.Status'})) {
991: $gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
992: } else {
993: if ($is_tool) {
994: $closure = 1;
995: }
996: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
997: .&Apache::lonhtmlcommon::StatusOptions(
998: $saveStatus,undef,1,'javascript:reLoadList(this.form);')
999: .&Apache::lonhtmlcommon::row_closure($closure);
1000: }
1001:
1002: unless ($is_tool) {
1003: $closure = 1;
1004: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
1005: .'<input type="checkbox" name="checkPlag" checked="checked" />'
1006: .&Apache::lonhtmlcommon::row_closure($closure);
1007: }
1008: $gradeTable .= &Apache::lonhtmlcommon::end_pick_box();
1009: my $regrademsg;
1010: if ($is_tool) {
1011: $regrademsg =&mt("To view/grade/regrade, click on the check box(es) next to the student's name(s). Then click on the Next button.");
1012: } else {
1013: $regrademsg = &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.");
1014: }
1015: $gradeTable .= '<p>'
1016: .$regrademsg."\n"
1017: .'<input type="hidden" name="command" value="processGroup" />'
1018: .'</p>';
1019:
1020: # checkall buttons
1021: $gradeTable.=&check_script('gradesub', 'stuinfo');
1022: $gradeTable.='<input type="button" '."\n".
1023: 'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
1024: 'value="'.&mt('Next').' →" /> <br />'."\n";
1025: $gradeTable.=&check_buttons();
1026: my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1027: $gradeTable.= &Apache::loncommon::start_data_table().
1028: &Apache::loncommon::start_data_table_header_row();
1029: my $loop = 0;
1030: while ($loop < 2) {
1031: $gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
1032: '<th>'.&nameUserString('header').' '.&mt('Section/Group').'</th>';
1033: if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1034: foreach my $part (sort(@$partlist)) {
1035: my $display_part=
1036: &get_display_part((split(/_/,$part))[0],$symb);
1037: $gradeTable.=
1038: '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1039: }
1040: } elsif ($submitonly eq 'queued') {
1041: $gradeTable.='<th>'.&mt('Queue Status').' </th>';
1042: }
1043: $loop++;
1044: # $gradeTable.='<td></td>' if ($loop%2 ==1);
1045: }
1046: $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1047:
1048: my $ctr = 0;
1049: foreach my $student (sort
1050: {
1051: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
1052: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
1053: }
1054: return $a cmp $b;
1055: }
1056: (keys(%$fullname))) {
1057: my ($uname,$udom) = split(/:/,$student);
1058:
1059: my %status = ();
1060:
1061: if ($submitonly eq 'queued') {
1062: my %queue_status =
1063: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
1064: $udom,$uname);
1065: next if (!defined($queue_status{'gradingqueue'}));
1066: $status{'gradingqueue'} = $queue_status{'gradingqueue'};
1067: }
1068:
1069: if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1070: (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1071: my $submitted = 0;
1072: my $graded = 0;
1073: my $incorrect = 0;
1074: foreach (keys(%status)) {
1075: $submitted = 1 if ($status{$_} ne 'nothing');
1076: $graded = 1 if ($status{$_} =~ /^ungraded/);
1077: $incorrect = 1 if ($status{$_} =~ /^incorrect/);
1078:
1079: my ($foo,$partid,$foo1) = split(/\./,$_);
1080: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1081: $submitted = 0;
1082: my ($part)=split(/\./,$partid);
1083: $gradeTable.='<input type="hidden" name="'.
1084: $student.':'.$part.':submitted_by" value="'.
1085: $status{'resource.'.$partid.'.submitted_by'}.'" />';
1086: }
1087: }
1088:
1089: next if (!$submitted && ($submitonly eq 'yes' ||
1090: $submitonly eq 'incorrect' ||
1091: $submitonly eq 'graded'));
1092: next if (!$graded && ($submitonly eq 'graded'));
1093: next if (!$incorrect && $submitonly eq 'incorrect');
1094: }
1095:
1096: $ctr++;
1097: my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1098: my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1099: if ( $perm{'vgr'} eq 'F' ) {
1100: if ($ctr%2 ==1) {
1101: $gradeTable.= &Apache::loncommon::start_data_table_row();
1102: }
1103: $gradeTable.='<td align="right">'.$ctr.' </td>'.
1104: '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1105: $student.':'.$$fullname{$student}.':::SECTION'.$section.
1106: ') " /> </label></td>'."\n".'<td>'.
1107: &nameUserString(undef,$$fullname{$student},$uname,$udom).
1108: ' '.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1109:
1110: if ($submitonly ne 'all') {
1111: foreach (sort(keys(%status))) {
1112: next if ($_ =~ /^resource.*?submitted_by$/);
1113: $gradeTable.='<td align="center"> '.&mt($status{$_}).' </td>'."\n";
1114: }
1115: }
1116: # $gradeTable.='<td></td>' if ($ctr%2 ==1);
1117: if ($ctr%2 ==0) {
1118: $gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
1119: }
1120: }
1121: }
1122: if ($ctr%2 ==1) {
1123: $gradeTable.='<td> </td><td> </td><td> </td>';
1124: if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1125: foreach (@$partlist) {
1126: $gradeTable.='<td> </td>';
1127: }
1128: } elsif ($submitonly eq 'queued') {
1129: $gradeTable.='<td> </td>';
1130: }
1131: $gradeTable.=&Apache::loncommon::end_data_table_row();
1132: }
1133:
1134: $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1135: '<input type="button" '.
1136: 'onclick="javascript:checkSelect(this.form.stuinfo);" '.
1137: 'value="'.&mt('Next').' →" /></form>'."\n";
1138: if ($ctr == 0) {
1139: my $num_students=(scalar(keys(%$fullname)));
1140: if ($num_students eq 0) {
1141: $gradeTable='<br /> <span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1142: } else {
1143: my $submissions='submissions';
1144: if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
1145: if ($submitonly eq 'graded' ) { $submissions = 'ungraded submissions'; }
1146: if ($submitonly eq 'queued' ) { $submissions = 'queued submissions'; }
1147: $gradeTable='<br /> <span class="LC_warning">'.
1148: &mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
1149: $num_students).
1150: '</span><br />';
1151: }
1152: } elsif ($ctr == 1) {
1153: $gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1154: }
1155: $request->print($gradeTable);
1156: return '';
1157: }
1158:
1159: #---- Called from the listStudents routine
1160:
1161: sub check_script {
1162: my ($form, $type)=@_;
1163: my $chkallscript= &Apache::lonhtmlcommon::scripttag('
1164: function checkall() {
1165: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1166: ele = document.forms.'.$form.'.elements[i];
1167: if (ele.name == "'.$type.'") {
1168: document.forms.'.$form.'.elements[i].checked=true;
1169: }
1170: }
1171: }
1172:
1173: function checksec() {
1174: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1175: ele = document.forms.'.$form.'.elements[i];
1176: string = document.forms.'.$form.'.chksec.value;
1177: if
1178: (ele.value.indexOf(":::SECTION"+string)>0) {
1179: document.forms.'.$form.'.elements[i].checked=true;
1180: }
1181: }
1182: }
1183:
1184:
1185: function uncheckall() {
1186: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1187: ele = document.forms.'.$form.'.elements[i];
1188: if (ele.name == "'.$type.'") {
1189: document.forms.'.$form.'.elements[i].checked=false;
1190: }
1191: }
1192: }
1193:
1194: '."\n");
1195: return $chkallscript;
1196: }
1197:
1198: sub check_buttons {
1199: my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
1200: $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" /> ';
1201: $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1202: $buttons.='<input type="text" size="5" name="chksec" /> ';
1203: return $buttons;
1204: }
1205:
1206: # Displays the submissions for one student or a group of students
1207: sub processGroup {
1208: my ($request,$symb) = @_;
1209: my $ctr = 0;
1210: my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1211: my $total = scalar(@stuchecked)-1;
1212:
1213: foreach my $student (@stuchecked) {
1214: my ($uname,$udom,$fullname) = split(/:/,$student);
1215: $env{'form.student'} = $uname;
1216: $env{'form.userdom'} = $udom;
1217: $env{'form.fullname'} = $fullname;
1218: &submission($request,$ctr,$total,$symb);
1219: $ctr++;
1220: }
1221: return '';
1222: }
1223:
1224: #------------------------------------------------------------------------------------
1225: #
1226: #-------------------------- Next few routines handles grading by student, essentially
1227: # handles essay response type problem/part
1228: #
1229: #--- Javascript to handle the submission page functionality ---
1230: sub sub_page_js {
1231: my $request = shift;
1232: my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1233: &js_escape(\$alertmsg);
1234: $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1235: function updateRadio(formname,id,weight) {
1236: var gradeBox = formname["GD_BOX"+id];
1237: var radioButton = formname["RADVAL"+id];
1238: var oldpts = formname["oldpts"+id].value;
1239: var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1240: gradeBox.value = pts;
1241: var resetbox = false;
1242: if (isNaN(pts) || pts < 0) {
1243: alert("$alertmsg"+pts);
1244: for (var i=0; i<radioButton.length; i++) {
1245: if (radioButton[i].checked) {
1246: gradeBox.value = i;
1247: resetbox = true;
1248: }
1249: }
1250: if (!resetbox) {
1251: formtextbox.value = "";
1252: }
1253: return;
1254: }
1255:
1256: if (pts > weight) {
1257: var resp = confirm("You entered a value ("+pts+
1258: ") greater than the weight for the part. Accept?");
1259: if (resp == false) {
1260: gradeBox.value = oldpts;
1261: return;
1262: }
1263: }
1264:
1265: for (var i=0; i<radioButton.length; i++) {
1266: radioButton[i].checked=false;
1267: if (pts == i && pts != "") {
1268: radioButton[i].checked=true;
1269: }
1270: }
1271: updateSelect(formname,id);
1272: formname["stores"+id].value = "0";
1273: }
1274:
1275: function writeBox(formname,id,pts) {
1276: var gradeBox = formname["GD_BOX"+id];
1277: if (checkSolved(formname,id) == 'update') {
1278: gradeBox.value = pts;
1279: } else {
1280: var oldpts = formname["oldpts"+id].value;
1281: gradeBox.value = oldpts;
1282: var radioButton = formname["RADVAL"+id];
1283: for (var i=0; i<radioButton.length; i++) {
1284: radioButton[i].checked=false;
1285: if (i == oldpts) {
1286: radioButton[i].checked=true;
1287: }
1288: }
1289: }
1290: formname["stores"+id].value = "0";
1291: updateSelect(formname,id);
1292: return;
1293: }
1294:
1295: function clearRadBox(formname,id) {
1296: if (checkSolved(formname,id) == 'noupdate') {
1297: updateSelect(formname,id);
1298: return;
1299: }
1300: gradeSelect = formname["GD_SEL"+id];
1301: for (var i=0; i<gradeSelect.length; i++) {
1302: if (gradeSelect[i].selected) {
1303: var selectx=i;
1304: }
1305: }
1306: var stores = formname["stores"+id];
1307: if (selectx == stores.value) { return };
1308: var gradeBox = formname["GD_BOX"+id];
1309: gradeBox.value = "";
1310: var radioButton = formname["RADVAL"+id];
1311: for (var i=0; i<radioButton.length; i++) {
1312: radioButton[i].checked=false;
1313: }
1314: stores.value = selectx;
1315: }
1316:
1317: function checkSolved(formname,id) {
1318: if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1319: var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
1320: if (!reply) {return "noupdate";}
1321: formname.overRideScore.value = 'yes';
1322: }
1323: return "update";
1324: }
1325:
1326: function updateSelect(formname,id) {
1327: formname["GD_SEL"+id][0].selected = true;
1328: return;
1329: }
1330:
1331: //=========== Check that a point is assigned for all the parts ============
1332: function checksubmit(formname,val,total,parttot) {
1333: formname.gradeOpt.value = val;
1334: if (val == "Save & Next") {
1335: for (i=0;i<=total;i++) {
1336: for (j=0;j<parttot;j++) {
1337: var partid = formname["partid"+i+"_"+j].value;
1338: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1339: var points = formname["GD_BOX"+i+"_"+partid].value;
1340: if (points == "") {
1341: var name = formname["name"+i].value;
1342: var studentID = (name != '' ? name : formname["unamedom"+i].value);
1343: var resp = confirm("You did not assign a score for "+studentID+
1344: ", part "+partid+". Continue?");
1345: if (resp == false) {
1346: formname["GD_BOX"+i+"_"+partid].focus();
1347: return false;
1348: }
1349: }
1350: }
1351: }
1352: }
1353: }
1354: formname.submit();
1355: }
1356:
1357: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
1358: function checkSubmitPage(formname,total) {
1359: noscore = new Array(100);
1360: var ptr = 0;
1361: for (i=1;i<total;i++) {
1362: var partid = formname["q_"+i].value;
1363: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1364: var points = formname["GD_BOX"+i+"_"+partid].value;
1365: var status = formname["solved"+i+"_"+partid].value;
1366: if (points == "" && status != "correct_by_student") {
1367: noscore[ptr] = i;
1368: ptr++;
1369: }
1370: }
1371: }
1372: if (ptr != 0) {
1373: var sense = ptr == 1 ? ": " : "s: ";
1374: var prolist = "";
1375: if (ptr == 1) {
1376: prolist = noscore[0];
1377: } else {
1378: var i = 0;
1379: while (i < ptr-1) {
1380: prolist += noscore[i]+", ";
1381: i++;
1382: }
1383: prolist += "and "+noscore[i];
1384: }
1385: var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
1386: if (resp == false) {
1387: return false;
1388: }
1389: }
1390:
1391: formname.submit();
1392: }
1393: SUBJAVASCRIPT
1394: }
1395:
1396: #--- javascript for essay type problem --
1397: sub sub_page_kw_js {
1398: my $request = shift;
1399: my $iconpath = $request->dir_config('lonIconsURL');
1400: &commonJSfunctions($request);
1401:
1402: my $inner_js_msg_central= (<<INNERJS);
1403: <script type="text/javascript">
1404: function checkInput() {
1405: opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
1406: var nmsg = opener.document.SCORE.savemsgN.value;
1407: var usrctr = document.msgcenter.usrctr.value;
1408: var newval = opener.document.SCORE["newmsg"+usrctr];
1409: newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
1410:
1411: var msgchk = "";
1412: if (document.msgcenter.subchk.checked) {
1413: msgchk = "msgsub,";
1414: }
1415: var includemsg = 0;
1416: for (var i=1; i<=nmsg; i++) {
1417: var opnmsg = opener.document.SCORE["savemsg"+i];
1418: var frmmsg = document.msgcenter["msg"+i];
1419: opnmsg.value = opener.checkEntities(frmmsg.value);
1420: var showflg = opener.document.SCORE["shownOnce"+i];
1421: showflg.value = "1";
1422: var chkbox = document.msgcenter["msgn"+i];
1423: if (chkbox.checked) {
1424: msgchk += "savemsg"+i+",";
1425: includemsg = 1;
1426: }
1427: }
1428: if (document.msgcenter.newmsgchk.checked) {
1429: msgchk += "newmsg"+usrctr;
1430: includemsg = 1;
1431: }
1432: imgformname = opener.document.SCORE["mailicon"+usrctr];
1433: imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
1434: var includemsg = opener.document.SCORE["includemsg"+usrctr];
1435: includemsg.value = msgchk;
1436:
1437: self.close()
1438:
1439: }
1440: </script>
1441: INNERJS
1442:
1443: my $inner_js_highlight_central= (<<INNERJS);
1444: <script type="text/javascript">
1445: function updateChoice(flag) {
1446: opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
1447: opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
1448: opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
1449: opener.document.SCORE.refresh.value = "on";
1450: if (opener.document.SCORE.keywords.value!=""){
1451: opener.document.SCORE.submit();
1452: }
1453: self.close()
1454: }
1455: </script>
1456: INNERJS
1457:
1458: my $start_page_msg_central =
1459: &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
1460: {'js_ready' => 1,
1461: 'only_body' => 1,
1462: 'bgcolor' =>'#FFFFFF',});
1463: my $end_page_msg_central =
1464: &Apache::loncommon::end_page({'js_ready' => 1});
1465:
1466:
1467: my $start_page_highlight_central =
1468: &Apache::loncommon::start_page('Highlight Central',
1469: $inner_js_highlight_central,
1470: {'js_ready' => 1,
1471: 'only_body' => 1,
1472: 'bgcolor' =>'#FFFFFF',});
1473: my $end_page_highlight_central =
1474: &Apache::loncommon::end_page({'js_ready' => 1});
1475:
1476: my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1477: $docopen=~s/^document\.//;
1478: my %js_lt = &Apache::lonlocal::texthash(
1479: keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
1480: plse => 'Please select a word or group of words from document and then click this link.',
1481: adds => 'Add selection to keyword list? Edit if desired.',
1482: col1 => 'red',
1483: col2 => 'green',
1484: col3 => 'blue',
1485: siz1 => 'normal',
1486: siz2 => '+1',
1487: siz3 => '+2',
1488: sty1 => 'normal',
1489: sty2 => 'italic',
1490: sty3 => 'bold',
1491: );
1492: my %html_js_lt = &Apache::lonlocal::texthash(
1493: comp => 'Compose Message for: ',
1494: incl => 'Include',
1495: type => 'Type',
1496: subj => 'Subject',
1497: mesa => 'Message',
1498: new => 'New',
1499: save => 'Save',
1500: canc => 'Cancel',
1501: kehi => 'Keyword Highlight Options',
1502: txtc => 'Text Color',
1503: font => 'Font Size',
1504: fnst => 'Font Style',
1505: );
1506: &js_escape(\%js_lt);
1507: &html_escape(\%html_js_lt);
1508: &js_escape(\%html_js_lt);
1509: $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1510:
1511: //===================== Show list of keywords ====================
1512: function keywords(formname) {
1513: var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
1514: if (nret==null) return;
1515: formname.keywords.value = nret;
1516:
1517: if (formname.keywords.value != "") {
1518: formname.refresh.value = "on";
1519: formname.submit();
1520: }
1521: return;
1522: }
1523:
1524: //===================== Script to view submitted by ==================
1525: function viewSubmitter(submitter) {
1526: document.SCORE.refresh.value = "on";
1527: document.SCORE.NCT.value = "1";
1528: document.SCORE.unamedom0.value = submitter;
1529: document.SCORE.submit();
1530: return;
1531: }
1532:
1533: //===================== Script to add keyword(s) ==================
1534: function getSel() {
1535: if (document.getSelection) txt = document.getSelection();
1536: else if (document.selection) txt = document.selection.createRange().text;
1537: else return;
1538: var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
1539: if (cleantxt=="") {
1540: alert("$js_lt{'plse'}");
1541: return;
1542: }
1543: var nret = prompt("$js_lt{'adds'}",cleantxt);
1544: if (nret==null) return;
1545: document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1546: if (document.SCORE.keywords.value != "") {
1547: document.SCORE.refresh.value = "on";
1548: document.SCORE.submit();
1549: }
1550: return;
1551: }
1552:
1553: //====================== Script for composing message ==============
1554: // preload images
1555: img1 = new Image();
1556: img1.src = "$iconpath/mailbkgrd.gif";
1557: img2 = new Image();
1558: img2.src = "$iconpath/mailto.gif";
1559:
1560: function msgCenter(msgform,usrctr,fullname) {
1561: var Nmsg = msgform.savemsgN.value;
1562: savedMsgHeader(Nmsg,usrctr,fullname);
1563: var subject = msgform.msgsub.value;
1564: var msgchk = document.SCORE["includemsg"+usrctr].value;
1565: re = /msgsub/;
1566: var shwsel = "";
1567: if (re.test(msgchk)) { shwsel = "checked" }
1568: subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
1569: displaySubject(checkEntities(subject),shwsel);
1570: for (var i=1; i<=Nmsg; i++) {
1571: var testmsg = "savemsg"+i+",";
1572: re = new RegExp(testmsg,"g");
1573: shwsel = "";
1574: if (re.test(msgchk)) { shwsel = "checked" }
1575: var message = document.SCORE["savemsg"+i].value;
1576: message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1577: displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
1578: //any < is already converted to <, etc. However, only once!!
1579: }
1580: newmsg = document.SCORE["newmsg"+usrctr].value;
1581: shwsel = "";
1582: re = /newmsg/;
1583: if (re.test(msgchk)) { shwsel = "checked" }
1584: newMsg(newmsg,shwsel);
1585: msgTail();
1586: return;
1587: }
1588:
1589: function checkEntities(strx) {
1590: if (strx.length == 0) return strx;
1591: var orgStr = ["&", "<", ">", '"'];
1592: var newStr = ["&", "<", ">", """];
1593: var counter = 0;
1594: while (counter < 4) {
1595: strx = strReplace(strx,orgStr[counter],newStr[counter]);
1596: counter++;
1597: }
1598: return strx;
1599: }
1600:
1601: function strReplace(strx, orgStr, newStr) {
1602: return strx.split(orgStr).join(newStr);
1603: }
1604:
1605: function savedMsgHeader(Nmsg,usrctr,fullname) {
1606: var height = 70*Nmsg+250;
1607: if (height > 600) {
1608: height = 600;
1609: }
1610: var xpos = (screen.width-600)/2;
1611: xpos = (xpos < 0) ? '0' : xpos;
1612: var ypos = (screen.height-height)/2-30;
1613: ypos = (ypos < 0) ? '0' : ypos;
1614:
1615: pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1616: pWin.focus();
1617: pDoc = pWin.document;
1618: pDoc.$docopen;
1619: pDoc.write('$start_page_msg_central');
1620:
1621: pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
1622: pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1623: pDoc.write("<h1> $html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
1624:
1625: pDoc.write('<table style="border:1px solid black;"><tr>');
1626: pDoc.write("<td><b>$html_js_lt{'incl'}<\\/b><\\/td><td><b>$html_js_lt{'type'}<\\/b><\\/td><td><b>$html_js_lt{'mesa'}<\\/td><\\/tr>");
1627: }
1628: function displaySubject(msg,shwsel) {
1629: pDoc = pWin.document;
1630: pDoc.write("<tr>");
1631: pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1632: pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
1633: pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1634: }
1635:
1636: function displaySavedMsg(ctr,msg,shwsel) {
1637: pDoc = pWin.document;
1638: pDoc.write("<tr>");
1639: pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1640: pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
1641: pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1642: }
1643:
1644: function newMsg(newmsg,shwsel) {
1645: pDoc = pWin.document;
1646: pDoc.write("<tr>");
1647: pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1648: pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
1649: pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1650: }
1651:
1652: function msgTail() {
1653: pDoc = pWin.document;
1654: //pDoc.write("<\\/table>");
1655: pDoc.write("<\\/td><\\/tr><\\/table> ");
1656: pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\"> ");
1657: pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1658: pDoc.write("<\\/form>");
1659: pDoc.write('$end_page_msg_central');
1660: pDoc.close();
1661: }
1662:
1663: //====================== Script for keyword highlight options ==============
1664: function kwhighlight() {
1665: var kwclr = document.SCORE.kwclr.value;
1666: var kwsize = document.SCORE.kwsize.value;
1667: var kwstyle = document.SCORE.kwstyle.value;
1668: var redsel = "";
1669: var grnsel = "";
1670: var blusel = "";
1671: var txtcol1 = "$js_lt{'col1'}";
1672: var txtcol2 = "$js_lt{'col2'}";
1673: var txtcol3 = "$js_lt{'col3'}";
1674: var txtsiz1 = "$js_lt{'siz1'}";
1675: var txtsiz2 = "$js_lt{'siz2'}";
1676: var txtsiz3 = "$js_lt{'siz3'}";
1677: var txtsty1 = "$js_lt{'sty1'}";
1678: var txtsty2 = "$js_lt{'sty2'}";
1679: var txtsty3 = "$js_lt{'sty3'}";
1680: if (kwclr=="red") {var redsel="checked='checked'"};
1681: if (kwclr=="green") {var grnsel="checked='checked'"};
1682: if (kwclr=="blue") {var blusel="checked='checked'"};
1683: var sznsel = "";
1684: var sz1sel = "";
1685: var sz2sel = "";
1686: if (kwsize=="0") {var sznsel="checked='checked'"};
1687: if (kwsize=="+1") {var sz1sel="checked='checked'"};
1688: if (kwsize=="+2") {var sz2sel="checked='checked'"};
1689: var synsel = "";
1690: var syisel = "";
1691: var sybsel = "";
1692: if (kwstyle=="") {var synsel="checked='checked'"};
1693: if (kwstyle=="<i>") {var syisel="checked='checked'"};
1694: if (kwstyle=="<b>") {var sybsel="checked='checked'"};
1695: highlightCentral();
1696: highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
1697: highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
1698: highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
1699: highlightend();
1700: return;
1701: }
1702:
1703: function highlightCentral() {
1704: // if (window.hwdWin) window.hwdWin.close();
1705: var xpos = (screen.width-400)/2;
1706: xpos = (xpos < 0) ? '0' : xpos;
1707: var ypos = (screen.height-330)/2-30;
1708: ypos = (ypos < 0) ? '0' : ypos;
1709:
1710: hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1711: hwdWin.focus();
1712: var hDoc = hwdWin.document;
1713: hDoc.$docopen;
1714: hDoc.write('$start_page_highlight_central');
1715: hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1716: hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
1717:
1718: hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
1719: hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
1720: }
1721:
1722: function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) {
1723: var hDoc = hwdWin.document;
1724: hDoc.write("<tr>");
1725: hDoc.write("<td align=\\"left\\">");
1726: hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/> "+clrtxt+"<\\/td>");
1727: hDoc.write("<td align=\\"left\\">");
1728: hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/> "+sztxt+"<\\/td>");
1729: hDoc.write("<td align=\\"left\\">");
1730: hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/> "+sytxt+"<\\/td>");
1731: hDoc.write("<\\/tr>");
1732: }
1733:
1734: function highlightend() {
1735: var hDoc = hwdWin.document;
1736: hDoc.write("<\\/table><br \\/>");
1737: hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/> ");
1738: hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
1739: hDoc.write("<\\/form>");
1740: hDoc.write('$end_page_highlight_central');
1741: hDoc.close();
1742: }
1743:
1744: SUBJAVASCRIPT
1745: }
1746:
1747: sub get_increment {
1748: my $increment = $env{'form.increment'};
1749: if ($increment != 1 && $increment != .5 && $increment != .25 &&
1750: $increment != .1) {
1751: $increment = 1;
1752: }
1753: return $increment;
1754: }
1755:
1756: sub gradeBox_start {
1757: return (
1758: &Apache::loncommon::start_data_table()
1759: .&Apache::loncommon::start_data_table_header_row()
1760: .'<th>'.&mt('Part').'</th>'
1761: .'<th>'.&mt('Points').'</th>'
1762: .'<th> </th>'
1763: .'<th>'.&mt('Assign Grade').'</th>'
1764: .'<th>'.&mt('Weight').'</th>'
1765: .'<th>'.&mt('Grade Status').'</th>'
1766: .&Apache::loncommon::end_data_table_header_row()
1767: );
1768: }
1769:
1770: sub gradeBox_end {
1771: return (
1772: &Apache::loncommon::end_data_table()
1773: );
1774: }
1775: #--- displays the grading box, used in essay type problem and grading by page/sequence
1776: sub gradeBox {
1777: my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1778: my $checkIcon = '<img alt="'.&mt('Check Mark').
1779: '" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1780: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1781: my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)')
1782: : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1783: $wgt = ($wgt > 0 ? $wgt : '1');
1784: my $score = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1785: '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1786: my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1787: my $display_part= &get_display_part($partid,$symb);
1788: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
1789: [$partid]);
1790: my $aggtries = $$record{'resource.'.$partid.'.tries'};
1791: if ($last_resets{$partid}) {
1792: $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
1793: }
1794: my $result=&Apache::loncommon::start_data_table_row();
1795: my $ctr = 0;
1796: my $thisweight = 0;
1797: my $increment = &get_increment();
1798:
1799: my $radio.='<table border="0"><tr>'."\n"; # display radio buttons in a nice table 10 across
1800: while ($thisweight<=$wgt) {
1801: $radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1802: 'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1803: $thisweight.')" value="'.$thisweight.'" '.
1804: ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1805: $radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1806: $thisweight += $increment;
1807: $ctr++;
1808: }
1809: $radio.='</tr></table>';
1810:
1811: my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1812: ($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1813: 'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1814: $wgt.')" /></td>'."\n";
1815: $line.='<td>/'.$wgt.' '.$wgtmsg.
1816: ($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? ' '.$checkIcon : '').
1817: ' </td>'."\n";
1818: $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1819: 'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1820: if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1821: $line.='<option></option>'.
1822: '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1823: } else {
1824: $line.='<option selected="selected"></option>'.
1825: '<option value="excused" >'.&mt('excused').'</option>';
1826: }
1827: $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
1828:
1829:
1830: $result .=
1831: '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
1832: $result.=&Apache::loncommon::end_data_table_row();
1833: $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
1834: $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
1835: '<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
1836: '<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1837: $$record{'resource.'.$partid.'.solved'}.'" />'."\n".
1838: '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
1839: $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
1840: '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
1841: $aggtries.'" />'."\n";
1842: my $res_error;
1843: $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1844: $result.='</td>'.&Apache::loncommon::end_data_table_row();
1845: if ($res_error) {
1846: return &navmap_errormsg();
1847: }
1848: return $result;
1849: }
1850:
1851: sub handback_box {
1852: my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
1853: my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
1854: my (@respids);
1855: my @part_response_id = &flatten_responseType($responseType);
1856: foreach my $part_response_id (@part_response_id) {
1857: my ($part,$resp) = @{ $part_response_id };
1858: if ($part eq $partid) {
1859: push(@respids,$resp);
1860: }
1861: }
1862: my $result;
1863: foreach my $respid (@respids) {
1864: my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
1865: my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
1866: next if (!@$files);
1867: my $file_counter = 0;
1868: foreach my $file (@$files) {
1869: if ($file =~ /\/portfolio\//) {
1870: $file_counter++;
1871: my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1872: my ($name,$version,$ext) = &Apache::lonnet::file_name_version_ext($file_disp);
1873: $file_disp = "$name.$ext";
1874: $file = $file_path.$file_disp;
1875: $result.=&mt('Return commented version of [_1] to student.',
1876: '<span class="LC_filename">'.$file_disp.'</span>');
1877: $result.='<input type="file" name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1878: $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1879: }
1880: }
1881: if ($file_counter) {
1882: $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
1883: '<span class="LC_info">'.
1884: '('.&mt('File(s) will be uploaded when you click on Save & Next below.',$file_counter).')</span><br /><br />';
1885: }
1886: }
1887: return $result;
1888: }
1889:
1890: sub show_problem {
1891: my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1892: my $rendered;
1893: my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1894: &Apache::lonxml::remember_problem_counter();
1895: if ($mode eq 'both' or $mode eq 'text') {
1896: $rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1897: $env{'request.course.id'},
1898: undef,\%form);
1899: }
1900: if ($removeform) {
1901: $rendered=~s|<form(.*?)>||g;
1902: $rendered=~s|</form>||g;
1903: $rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1904: }
1905: my $companswer;
1906: if ($mode eq 'both' or $mode eq 'answer') {
1907: &Apache::lonxml::restore_problem_counter();
1908: $companswer=
1909: &Apache::loncommon::get_student_answers($symb,$uname,$udom,
1910: $env{'request.course.id'},
1911: %form);
1912: }
1913: if ($removeform) {
1914: $companswer=~s|<form(.*?)>||g;
1915: $companswer=~s|</form>||g;
1916: $companswer=~s|name="submit"|name="would_have_been_submit"|g;
1917: }
1918: my $renderheading = &mt('View of the problem');
1919: my $answerheading = &mt('Correct answer');
1920: if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1921: my $stu_fullname = $env{'form.fullname'};
1922: if ($stu_fullname eq '') {
1923: $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
1924: }
1925: my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
1926: if ($forwhom ne '') {
1927: $renderheading = &mt('View of the problem for[_1]',$forwhom);
1928: $answerheading = &mt('Correct answer for[_1]',$forwhom);
1929: }
1930: }
1931: $rendered=
1932: '<div class="LC_Box">'
1933: .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1934: .$rendered
1935: .'</div>';
1936: $companswer=
1937: '<div class="LC_Box">'
1938: .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1939: .$companswer
1940: .'</div>';
1941: my $result;
1942: if ($mode eq 'both') {
1943: $result=$rendered.$companswer;
1944: } elsif ($mode eq 'text') {
1945: $result=$rendered;
1946: } elsif ($mode eq 'answer') {
1947: $result=$companswer;
1948: }
1949: return $result;
1950: }
1951:
1952: sub files_exist {
1953: my ($r, $symb) = @_;
1954: my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1955:
1956: foreach my $student (@students) {
1957: my ($uname,$udom,$fullname) = split(/:/,$student);
1958: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
1959: $udom,$uname);
1960: my ($string,$timestamp)= &get_last_submission(\%record);
1961: foreach my $submission (@$string) {
1962: my ($partid,$respid) =
1963: ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1964: my $files=&get_submitted_files($udom,$uname,$partid,$respid,
1965: \%record);
1966: return 1 if (@$files);
1967: }
1968: }
1969: return 0;
1970: }
1971:
1972: sub download_all_link {
1973: my ($r,$symb) = @_;
1974: unless (&files_exist($r, $symb)) {
1975: $r->print(&mt('There are currently no submitted documents.'));
1976: return;
1977: }
1978:
1979: my $all_students =
1980: join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
1981:
1982: my $parts =
1983: join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
1984:
1985: my $identifier = &Apache::loncommon::get_cgi_id();
1986: &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
1987: 'cgi.'.$identifier.'.symb' => $symb,
1988: 'cgi.'.$identifier.'.parts' => $parts,});
1989: $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
1990: &mt('Download All Submitted Documents').'</a>');
1991: return;
1992: }
1993:
1994: sub submit_download_link {
1995: my ($request,$symb) = @_;
1996: if (!$symb) { return ''; }
1997: #FIXME: Figure out which type of problem this is and provide appropriate download
1998: &download_all_link($request,$symb);
1999: }
2000:
2001: sub build_section_inputs {
2002: my $section_inputs;
2003: if ($env{'form.section'} eq '') {
2004: $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
2005: } else {
2006: my @sections = &Apache::loncommon::get_env_multiple('form.section');
2007: foreach my $section (@sections) {
2008: $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
2009: }
2010: }
2011: return $section_inputs;
2012: }
2013:
2014: # --------------------------- show submissions of a student, option to grade
2015: sub submission {
2016: my ($request,$counter,$total,$symb) = @_;
2017: my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
2018: $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
2019: my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
2020: $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
2021:
2022: my $probtitle=&Apache::lonnet::gettitle($symb);
2023: if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
2024: my $is_tool = ($symb =~ /ext\.tool$/);
2025:
2026: if (!&canview($usec)) {
2027: $request->print(
2028: '<span class="LC_warning">'.
2029: &mt('Unable to view requested student.').
2030: ' '.&mt('([_1] in section [_2] in course id [_3])',
2031: $uname.':'.$udom,$usec,$env{'request.course.id'}).
2032: '</span>');
2033: return;
2034: }
2035:
2036: if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
2037: unless ($is_tool) {
2038: if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
2039: if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
2040: }
2041: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
2042: my $checkIcon = '<img alt="'.&mt('Check Mark').
2043: '" src="'.$request->dir_config('lonIconsURL').
2044: '/check.gif" height="16" border="0" />';
2045:
2046: # header info
2047: if ($counter == 0) {
2048: &sub_page_js($request);
2049: &sub_page_kw_js($request);
2050:
2051: # option to display problem, only once else it cause problems
2052: # with the form later since the problem has a form.
2053: if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
2054: my $mode;
2055: if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
2056: $mode='both';
2057: } elsif ($env{'form.vProb'} eq 'yes') {
2058: $mode='text';
2059: } elsif ($env{'form.vAns'} eq 'yes') {
2060: $mode='answer';
2061: }
2062: &Apache::lonxml::clear_problem_counter();
2063: $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
2064: }
2065:
2066: # kwclr is the only variable that is guaranteed not to be blank
2067: # if this subroutine has been called once.
2068: my %keyhash = ();
2069: # if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
2070: if (1) {
2071: %keyhash = &Apache::lonnet::dump('nohist_handgrade',
2072: $env{'course.'.$env{'request.course.id'}.'.domain'},
2073: $env{'course.'.$env{'request.course.id'}.'.num'});
2074:
2075: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
2076: $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
2077: $env{'form.kwclr'} = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
2078: $env{'form.kwsize'} = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
2079: $env{'form.kwstyle'} = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
2080: $env{'form.msgsub'} = $keyhash{$symb.'_subject'} ne '' ?
2081: $keyhash{$symb.'_subject'} : $probtitle;
2082: $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
2083: }
2084: my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
2085: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
2086: $request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
2087: '<input type="hidden" name="command" value="handgrade" />'."\n".
2088: '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
2089: '<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
2090: '<input type="hidden" name="refresh" value="off" />'."\n".
2091: '<input type="hidden" name="studentNo" value="" />'."\n".
2092: '<input type="hidden" name="gradeOpt" value="" />'."\n".
2093: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
2094: '<input type="hidden" name="vProb" value="'.$env{'form.vProb'}.'" />'."\n".
2095: '<input type="hidden" name="vAns" value="'.$env{'form.vAns'}.'" />'."\n".
2096: '<input type="hidden" name="lastSub" value="'.$env{'form.lastSub'}.'" />'."\n".
2097: &build_section_inputs().
2098: '<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
2099: '<input type="hidden" name="NCT"'.
2100: ' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
2101: # if ($env{'form.handgrade'} eq 'yes') {
2102: if (1) {
2103: $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
2104: '<input type="hidden" name="kwclr" value="'.$env{'form.kwclr'}.'" />'."\n".
2105: '<input type="hidden" name="kwsize" value="'.$env{'form.kwsize'}.'" />'."\n".
2106: '<input type="hidden" name="kwstyle" value="'.$env{'form.kwstyle'}.'" />'."\n".
2107: '<input type="hidden" name="msgsub" value="'.$env{'form.msgsub'}.'" />'."\n".
2108: '<input type="hidden" name="shownSub" value="0" />'."\n".
2109: '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
2110: foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
2111: $request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
2112: }
2113: }
2114:
2115: my ($cts,$prnmsg) = (1,'');
2116: while ($cts <= $env{'form.savemsgN'}) {
2117: $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
2118: (!exists($keyhash{$symb.'_savemsg'.$cts}) ?
2119: &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
2120: &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
2121: '" />'."\n".
2122: '<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
2123: $cts++;
2124: }
2125: $request->print($prnmsg);
2126:
2127: # if ($env{'form.handgrade'} eq 'yes') {
2128: unless ($is_tool) {
2129:
2130: my %lt = &Apache::lonlocal::texthash(
2131: keyh => 'Keyword Highlighting for Essays',
2132: keyw => 'Keyword Options',
2133: list => 'List',
2134: past => 'Paste Selection to List',
2135: high => 'Highlight Attribute',
2136: );
2137: #
2138: # Print out the keyword options line
2139: #
2140: $request->print(
2141: '<div class="LC_columnSection">'
2142: .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
2143: .&Apache::lonhtmlcommon::funclist_from_array(
2144: ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
2145: '<a href="#" onmousedown="javascript:getSel(); return false"
2146: class="page">'.$lt{'past'}.'</a>',
2147: '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
2148: {legend => $lt{'keyw'}})
2149: .'</fieldset></div>'
2150: );
2151:
2152: #
2153: # Load the other essays for similarity check
2154: #
2155: my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
2156: my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
2157: $apath=&escape($apath);
2158: $apath=~s/\W/\_/gs;
2159: &init_old_essays($symb,$apath,$adom,$aname);
2160: }
2161: }
2162:
2163: # This is where output for one specific student would start
2164: my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
2165: $request->print(
2166: "\n\n"
2167: .'<div class="LC_grade_show_user'.$add_class.'">'
2168: .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
2169: ."\n"
2170: );
2171:
2172: # Show additional functions if allowed
2173: if ($perm{'vgr'}) {
2174: $request->print(
2175: &Apache::loncommon::track_student_link(
2176: 'View recent activity',
2177: $uname,$udom,'check')
2178: .' '
2179: );
2180: }
2181: if ($perm{'opa'}) {
2182: $request->print(
2183: &Apache::loncommon::pprmlink(
2184: &mt('Set/Change parameters'),
2185: $uname,$udom,$symb,'check'));
2186: }
2187:
2188: # Show Problem
2189: if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
2190: my $mode;
2191: if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
2192: $mode='both';
2193: } elsif ($env{'form.vProb'} eq 'all' ) {
2194: $mode='text';
2195: } elsif ($env{'form.vAns'} eq 'all') {
2196: $mode='answer';
2197: }
2198: &Apache::lonxml::clear_problem_counter();
2199: $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
2200: }
2201:
2202: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
2203: my $res_error;
2204: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
2205: if ($res_error) {
2206: $request->print(&navmap_errormsg());
2207: return;
2208: }
2209:
2210: # Display student info
2211: $request->print(($counter == 0 ? '' : '<br />'));
2212:
2213: my $boxtitle = &mt('Submissions');
2214: if ($is_tool) {
2215: $boxtitle = &mt('Transactions')
2216: }
2217: my $result='<div class="LC_Box">'
2218: .'<h3 class="LC_hcell">'.$boxtitle.'</h3>';
2219: $result.='<input type="hidden" name="name'.$counter.
2220: '" value="'.$env{'form.fullname'}.'" />'."\n";
2221: # if ($env{'form.handgrade'} eq 'no') {
2222: unless ($is_tool) {
2223: $result.='<p class="LC_info">'
2224: .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
2225: ."</p>\n";
2226: }
2227:
2228: # If any part of the problem is an essay-response (handgraded), then check for collaborators
2229: my $fullname;
2230: my $col_fullnames = [];
2231: # if ($env{'form.handgrade'} eq 'yes') {
2232: unless ($is_tool) {
2233: (my $sub_result,$fullname,$col_fullnames)=
2234: &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
2235: $counter);
2236: $result.=$sub_result;
2237: }
2238: $request->print($result."\n");
2239:
2240: # print student answer/submission
2241: # Options are (1) Handgraded submission only
2242: # (2) Last submission, includes submission that is not handgraded
2243: # (for multi-response type part)
2244: # (3) Last submission plus the parts info
2245: # (4) The whole record for this student
2246:
2247: my ($string,$timestamp)= &get_last_submission(\%record,$is_tool);
2248:
2249: my $lastsubonly;
2250:
2251: if ($$timestamp eq '') {
2252: $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>';
2253: } elsif ($is_tool) {
2254: $lastsubonly =
2255: '<div class="LC_grade_submissions_body">'
2256: .'<b>'.&mt('Date Grade Passed Back:').'</b> '.$$timestamp."</div>\n";
2257: } else {
2258: $lastsubonly =
2259: '<div class="LC_grade_submissions_body">'
2260: .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
2261:
2262: my %seenparts;
2263: my @part_response_id = &flatten_responseType($responseType);
2264: foreach my $part (@part_response_id) {
2265: next if ($env{'form.lastSub'} eq 'hdgrade'
2266: && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
2267:
2268: my ($partid,$respid) = @{ $part };
2269: my $display_part=&get_display_part($partid,$symb);
2270: if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
2271: if (exists($seenparts{$partid})) { next; }
2272: $seenparts{$partid}=1;
2273: $request->print(
2274: '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
2275: ' <b>'.&mt('Collaborative submission by: [_1]',
2276: '<a href="javascript:viewSubmitter(\''.
2277: $env{"form.$uname:$udom:$partid:submitted_by"}.
2278: '\');" target="_self">'.
2279: $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
2280: '<br />');
2281: next;
2282: }
2283: my $responsetype = $responseType->{$partid}->{$respid};
2284: if (!exists($record{"resource.$partid.$respid.submission"})) {
2285: $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
2286: '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
2287: ' <span class="LC_internal_info">'.
2288: '('.&mt('Response ID: [_1]',$respid).')'.
2289: '</span> '.
2290: '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
2291: next;
2292: }
2293: foreach my $submission (@$string) {
2294: my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
2295: if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
2296: my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
2297: # Similarity check
2298: my $similar='';
2299: my ($type,$trial,$rndseed);
2300: if ($hide eq 'rand') {
2301: $type = 'randomizetry';
2302: $trial = $record{"resource.$partid.tries"};
2303: $rndseed = $record{"resource.$partid.rndseed"};
2304: }
2305: if ($env{'form.checkPlag'}) {
2306: my ($oname,$odom,$ocrsid,$oessay,$osim)=
2307: &most_similar($uname,$udom,$symb,$subval);
2308: if ($osim) {
2309: $osim=int($osim*100.0);
2310: my %old_course_desc =
2311: &Apache::lonnet::coursedescription($ocrsid,
2312: {'one_time' => 1});
2313:
2314: if ($hide eq 'anon') {
2315: $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
2316: &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
2317: } else {
2318: $similar="<hr /><h3><span class=\"LC_warning\">".
2319: &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
2320: $osim,
2321: &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
2322: $old_course_desc{'description'},
2323: $old_course_desc{'num'},
2324: $old_course_desc{'domain'}).
2325: '</span></h3><blockquote><i>'.
2326: &keywords_highlight($oessay).
2327: '</i></blockquote><hr />';
2328: }
2329: }
2330: }
2331: my $order=&get_order($partid,$respid,$symb,$uname,$udom,
2332: undef,$type,$trial,$rndseed);
2333: if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' &&
2334: $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
2335: my $display_part=&get_display_part($partid,$symb);
2336: $lastsubonly.='<div class="LC_grade_submission_part">'.
2337: '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
2338: ' <span class="LC_internal_info">'.
2339: '('.&mt('Response ID: [_1]',$respid).')'.
2340: '</span> ';
2341: my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
2342:
2343: if (@$files) {
2344: if ($hide eq 'anon') {
2345: $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
2346: } else {
2347: $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
2348: .'<br /><span class="LC_warning">';
2349: if(@$files == 1) {
2350: $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
2351: } else {
2352: $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
2353: }
2354: $lastsubonly .= '</span>';
2355: foreach my $file (@$files) {
2356: &Apache::lonnet::allowuploaded('/adm/grades',$file);
2357: $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
2358: }
2359: }
2360: $lastsubonly.='<br />';
2361: }
2362: if ($hide eq 'anon') {
2363: $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>';
2364: } else {
2365: $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
2366: if ($draft) {
2367: $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
2368: }
2369: $subval =
2370: &cleanRecord($subval,$responsetype,$symb,$partid,
2371: $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
2372: if ($responsetype eq 'essay') {
2373: $subval =~ s{\n}{<br />}g;
2374: }
2375: $lastsubonly.=$subval."\n";
2376: }
2377: if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
2378: $lastsubonly.='</div>';
2379: }
2380: }
2381: }
2382: $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
2383: }
2384: $request->print($lastsubonly);
2385: if ($env{'form.lastSub'} eq 'datesub') {
2386: my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
2387: $request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
2388:
2389: }
2390: if ($env{'form.lastSub'} =~ /^(last|all)$/) {
2391: my $identifier = (&canmodify($usec)? $counter : '');
2392: $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
2393: $env{'request.course.id'},
2394: $last,'.submission',
2395: 'Apache::grades::keywords_highlight',
2396: $usec,$identifier));
2397: }
2398: $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
2399: .$udom.'" />'."\n");
2400: # return if view submission with no grading option
2401: if (!&canmodify($usec)) {
2402: $request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
2403: return;
2404: } else {
2405: $request->print('</div>'."\n");
2406: }
2407:
2408: # essay grading message center
2409: # if ($env{'form.handgrade'} eq 'yes') {
2410: if (1) {
2411: my $result='<div class="LC_grade_message_center">';
2412:
2413: $result.='<div class="LC_grade_message_center_header">'.
2414: &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
2415: my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
2416: my $msgfor = $givenn.' '.$lastname;
2417: if (scalar(@$col_fullnames) > 0) {
2418: my $lastone = pop(@$col_fullnames);
2419: $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
2420: }
2421: $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
2422: $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
2423: '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
2424: $result.=' <a href="javascript:msgCenter(document.SCORE,'.$counter.
2425: ',\''.$msgfor.'\');" target="_self">'.
2426: &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
2427: &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
2428: ' <img src="'.$request->dir_config('lonIconsURL').
2429: '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
2430: '<br /> ('.
2431: &mt('Message will be sent when you click on Save & Next below.').")\n";
2432: $result.='</div></div>';
2433: $request->print($result);
2434: }
2435:
2436: my %seen = ();
2437: my @partlist;
2438: my @gradePartRespid;
2439: my @part_response_id;
2440: if ($is_tool) {
2441: @part_response_id = ([0,'']);
2442: } else {
2443: @part_response_id = &flatten_responseType($responseType);
2444: }
2445: $request->print(
2446: '<div class="LC_Box">'
2447: .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
2448: );
2449: $request->print(&gradeBox_start());
2450: foreach my $part_response_id (@part_response_id) {
2451: my ($partid,$respid) = @{ $part_response_id };
2452: my $part_resp = join('_',@{ $part_response_id });
2453: next if ($seen{$partid} > 0);
2454: $seen{$partid}++;
2455: next if ($$handgrade{$part_resp} ne 'yes'
2456: && $env{'form.lastSub'} eq 'hdgrade');
2457: push(@partlist,$partid);
2458: push(@gradePartRespid,$partid.'.'.$respid);
2459: $request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
2460: }
2461: $request->print(&gradeBox_end()); # </div>
2462: $request->print('</div>');
2463:
2464: $request->print('<div class="LC_grade_info_links">');
2465: $request->print('</div>');
2466:
2467: $result='<input type="hidden" name="partlist'.$counter.
2468: '" value="'.(join ":",@partlist).'" />'."\n";
2469: $result.='<input type="hidden" name="gradePartRespid'.
2470: '" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
2471: my $ctr = 0;
2472: while ($ctr < scalar(@partlist)) {
2473: $result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
2474: $partlist[$ctr].'" />'."\n";
2475: $ctr++;
2476: }
2477: $request->print($result.''."\n");
2478:
2479: # Done with printing info for one student
2480:
2481: $request->print('</div>');#LC_grade_show_user
2482:
2483:
2484: # print end of form
2485: if ($counter == $total) {
2486: my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
2487: $endform.='<input type="button" value="'.&mt('Save & Next').'" '.
2488: 'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
2489: $total.','.scalar(@partlist).');" target="_self" /> '."\n";
2490: my $ntstu ='<select name="NTSTU">'.
2491: '<option>1</option><option>2</option>'.
2492: '<option>3</option><option>5</option>'.
2493: '<option>7</option><option>10</option></select>'."\n";
2494: my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
2495: $ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
2496: $endform.=&mt('[_1]student(s)',$ntstu);
2497: $endform.=' <input type="button" value="'.&mt('Previous').'" '.
2498: 'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> '."\n".
2499: '<input type="button" value="'.&mt('Next').'" '.
2500: 'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> ';
2501: $endform.='<span class="LC_warning">'.
2502: &mt('(Next and Previous (student) do not save the scores.)').
2503: '</span>'."\n" ;
2504: $endform.="<input type='hidden' value='".&get_increment().
2505: "' name='increment' />";
2506: $endform.='</td></tr></table></form>';
2507: $request->print($endform);
2508: }
2509: return '';
2510: }
2511:
2512: sub check_collaborators {
2513: my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
2514: my ($result,@col_fullnames);
2515: my ($classlist,undef,$fullname) = &getclasslist('all','0');
2516: foreach my $part (keys(%$handgrade)) {
2517: my $ncol = &Apache::lonnet::EXT('resource.'.$part.
2518: '.maxcollaborators',
2519: $symb,$udom,$uname);
2520: next if ($ncol <= 0);
2521: $part =~ s/\_/\./g;
2522: next if ($record->{'resource.'.$part.'.collaborators'} eq '');
2523: my (@good_collaborators, @bad_collaborators);
2524: foreach my $possible_collaborator
2525: (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) {
2526: $possible_collaborator =~ s/[\$\^\(\)]//g;
2527: next if ($possible_collaborator eq '');
2528: my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
2529: $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
2530: next if ($co_name eq $uname && $co_dom eq $udom);
2531: # Doing this grep allows 'fuzzy' specification
2532: my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i,
2533: keys(%$classlist));
2534: if (! scalar(@matches)) {
2535: push(@bad_collaborators, $possible_collaborator);
2536: } else {
2537: push(@good_collaborators, @matches);
2538: }
2539: }
2540: if (scalar(@good_collaborators) != 0) {
2541: $result.='<br />'.&mt('Collaborators:').'<ol>';
2542: foreach my $name (@good_collaborators) {
2543: my ($lastname,$givenn) = split(/,/,$$fullname{$name});
2544: push(@col_fullnames, $givenn.' '.$lastname);
2545: $result.='<li>'.$fullname->{$name}.'</li>';
2546: }
2547: $result.='</ol><br />'."\n";
2548: my ($part)=split(/\./,$part);
2549: $result.='<input type="hidden" name="collaborator'.$counter.
2550: '" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
2551: "\n";
2552: }
2553: if (scalar(@bad_collaborators) > 0) {
2554: $result.='<div class="LC_warning">';
2555: $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
2556: $result .= '</div>';
2557: }
2558: if (scalar(@bad_collaborators > $ncol)) {
2559: $result .= '<div class="LC_warning">';
2560: $result .= &mt('This student has submitted too many '.
2561: 'collaborators. Maximum is [_1].',$ncol);
2562: $result .= '</div>';
2563: }
2564: }
2565: return ($result,$fullname,\@col_fullnames);
2566: }
2567:
2568: #--- Retrieve the last submission for all the parts
2569: sub get_last_submission {
2570: my ($returnhash,$is_tool)=@_;
2571: my (@string,$timestamp,%lasthidden);
2572: if ($$returnhash{'version'}) {
2573: my %lasthash=();
2574: my ($version);
2575: for ($version=1;$version<=$$returnhash{'version'};$version++) {
2576: foreach my $key (sort(split(/\:/,
2577: $$returnhash{$version.':keys'}))) {
2578: $lasthash{$key}=$$returnhash{$version.':'.$key};
2579: $timestamp =
2580: &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
2581: }
2582: }
2583: my (%typeparts,%randombytry);
2584: my $showsurv =
2585: &Apache::lonnet::allowed('vas',$env{'request.course.id'});
2586: foreach my $key (sort(keys(%lasthash))) {
2587: if ($key =~ /\.type$/) {
2588: if (($lasthash{$key} eq 'anonsurvey') ||
2589: ($lasthash{$key} eq 'anonsurveycred') ||
2590: ($lasthash{$key} eq 'randomizetry')) {
2591: my ($ign,@parts) = split(/\./,$key);
2592: pop(@parts);
2593: my $id = join('.',@parts);
2594: if ($lasthash{$key} eq 'randomizetry') {
2595: $randombytry{$ign.'.'.$id} = $lasthash{$key};
2596: } else {
2597: unless ($showsurv) {
2598: $typeparts{$ign.'.'.$id} = $lasthash{$key};
2599: }
2600: }
2601: delete($lasthash{$key});
2602: }
2603: }
2604: }
2605: my @hidden = keys(%typeparts);
2606: my @randomize = keys(%randombytry);
2607: foreach my $key (keys(%lasthash)) {
2608: next if ($key !~ /\.submission$/);
2609: my $hide;
2610: if (@hidden) {
2611: foreach my $id (@hidden) {
2612: if ($key =~ /^\Q$id\E/) {
2613: $hide = 'anon';
2614: last;
2615: }
2616: }
2617: }
2618: unless ($hide) {
2619: if (@randomize) {
2620: foreach my $id (@randomize) {
2621: if ($key =~ /^\Q$id\E/) {
2622: $hide = 'rand';
2623: last;
2624: }
2625: }
2626: }
2627: }
2628: my ($partid,$foo) = split(/submission$/,$key);
2629: my $draft = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
2630: push(@string, join(':', $key, $hide, $draft, (
2631: ref($lasthash{$key}) eq 'ARRAY' ?
2632: join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
2633: }
2634: }
2635: if (!@string) {
2636: my $msg;
2637: if ($is_tool) {
2638: $msg = &mt('No grade passed back.');
2639: } else {
2640: $msg = &mt('Nothing submitted - no attempts.');
2641: }
2642: $string[0] =
2643: '<span class="LC_warning">'.$msg.'</span>';
2644: }
2645: return (\@string,\$timestamp);
2646: }
2647:
2648: #--- High light keywords, with style choosen by user.
2649: sub keywords_highlight {
2650: my $string = shift;
2651: my $size = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
2652: my $styleon = $env{'form.kwstyle'} eq '' ? '' : $env{'form.kwstyle'};
2653: (my $styleoff = $styleon) =~ s/\</\<\//;
2654: my @keylist = split(/[,\s+]/,$env{'form.keywords'});
2655: foreach my $keyword (@keylist) {
2656: $string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
2657: }
2658: return $string;
2659: }
2660:
2661: # For Tasks provide a mechanism to display previous version for one specific student
2662:
2663: sub show_previous_task_version {
2664: my ($request,$symb) = @_;
2665: if ($symb eq '') {
2666: $request->print(
2667: '<span class="LC_error">'.
2668: &mt('Unable to handle ambiguous references.').
2669: '</span>');
2670: return '';
2671: }
2672: my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
2673: my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
2674: if (!&canview($usec)) {
2675: $request->print(
2676: '<span class="LC_warning">'.
2677: &mt('Unable to view previous version for requested student.').
2678: ' '.&mt('([_1] in section [_2] in course id [_3])',
2679: $uname.':'.$udom,$usec,$env{'request.course.id'}).
2680: '</span>');
2681: return;
2682: }
2683: my $mode = 'both';
2684: my $isTask = ($symb =~/\.task$/);
2685: if ($isTask) {
2686: if ($env{'form.previousversion'} =~ /^\d+$/) {
2687: if ($env{'form.fullname'} eq '') {
2688: $env{'form.fullname'} =
2689: &Apache::loncommon::plainname($uname,$udom,'lastname');
2690: }
2691: my $probtitle=&Apache::lonnet::gettitle($symb);
2692: $request->print("\n\n".
2693: '<div class="LC_grade_show_user">'.
2694: '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
2695: '</h2>'."\n");
2696: &Apache::lonxml::clear_problem_counter();
2697: $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
2698: {'previousversion' => $env{'form.previousversion'} }));
2699: $request->print("\n</div>");
2700: }
2701: }
2702: return;
2703: }
2704:
2705: sub choose_task_version_form {
2706: my ($symb,$uname,$udom,$nomenu) = @_;
2707: my $isTask = ($symb =~/\.task$/);
2708: my ($current,$version,$result,$js,$displayed,$rowtitle);
2709: if ($isTask) {
2710: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
2711: $udom,$uname);
2712: if (($record{'resource.0.version'} eq '') ||
2713: ($record{'resource.0.version'} < 2)) {
2714: return ($record{'resource.0.version'},
2715: $record{'resource.0.version'},$result,$js);
2716: } else {
2717: $current = $record{'resource.0.version'};
2718: }
2719: if ($env{'form.previousversion'}) {
2720: $displayed = $env{'form.previousversion'};
2721: $rowtitle = &mt('Choose another version:')
2722: } else {
2723: $displayed = $current;
2724: $rowtitle = &mt('Show earlier version:');
2725: }
2726: $result = '<div class="LC_left_float">';
2727: my $list;
2728: my $numversions = 0;
2729: for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
2730: if ($i == $current) {
2731: if (!$env{'form.previousversion'} || $nomenu) {
2732: next;
2733: } else {
2734: $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
2735: $numversions ++;
2736: }
2737: } elsif (defined($record{'resource.'.$i.'.0.status'})) {
2738: unless ($i == $env{'form.previousversion'}) {
2739: $numversions ++;
2740: }
2741: $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
2742: }
2743: }
2744: if ($numversions) {
2745: $symb = &HTML::Entities::encode($symb,'<>"&');
2746: $result .=
2747: '<form name="getprev" method="post" action=""'.
2748: ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
2749: &Apache::loncommon::start_data_table().
2750: &Apache::loncommon::start_data_table_row().
2751: '<th align="left">'.$rowtitle.'</th>'.
2752: '<td><select name="version">'.
2753: '<option>'.&mt('Select').'</option>'.
2754: $list.
2755: '</select></td>'.
2756: &Apache::loncommon::end_data_table_row();
2757: unless ($nomenu) {
2758: $result .= &Apache::loncommon::start_data_table_row().
2759: '<th align="left">'.&mt('Open in new window').'</th>'.
2760: '<td><span class="LC_nobreak">'.
2761: '<label><input type="radio" name="prevwin" value="1" />'.
2762: &mt('Yes').'</label>'.
2763: '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
2764: '</span></td>'.
2765: &Apache::loncommon::end_data_table_row();
2766: }
2767: $result .=
2768: &Apache::loncommon::start_data_table_row().
2769: '<th align="left"> </th>'.
2770: '<td>'.
2771: '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
2772: '</td>'.
2773: &Apache::loncommon::end_data_table_row().
2774: &Apache::loncommon::end_data_table().
2775: '</form>';
2776: $js = &previous_display_javascript($nomenu,$current);
2777: } elsif ($displayed && $nomenu) {
2778: $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
2779: } else {
2780: $result .= &mt('No previous versions to show for this student');
2781: }
2782: $result .= '</div>';
2783: }
2784: return ($current,$displayed,$result,$js);
2785: }
2786:
2787: sub previous_display_javascript {
2788: my ($nomenu,$current) = @_;
2789: my $js = <<"JSONE";
2790: <script type="text/javascript">
2791: // <![CDATA[
2792: function previousVersion(uname,udom,symb) {
2793: var current = '$current';
2794: var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
2795: var prevstr = new RegExp("^\\\\d+\$");
2796: if (!prevstr.test(version)) {
2797: return false;
2798: }
2799: var url = '';
2800: if (version == current) {
2801: url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
2802: } else {
2803: url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
2804: }
2805: JSONE
2806: if ($nomenu) {
2807: $js .= <<"JSTWO";
2808: document.location.href = url;
2809: JSTWO
2810: } else {
2811: $js .= <<"JSTHREE";
2812: var newwin = 0;
2813: for (var i=0; i<document.getprev.prevwin.length; i++) {
2814: if (document.getprev.prevwin[i].checked == true) {
2815: newwin = document.getprev.prevwin[i].value;
2816: }
2817: }
2818: if (newwin == 1) {
2819: var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
2820: url = url+'&inhibitmenu=yes';
2821: if (typeof(previousWin) == 'undefined' || previousWin.closed) {
2822: previousWin = window.open(url,'',options,1);
2823: } else {
2824: previousWin.location.href = url;
2825: }
2826: previousWin.focus();
2827: return false;
2828: } else {
2829: document.location.href = url;
2830: return false;
2831: }
2832: JSTHREE
2833: }
2834: $js .= <<"ENDJS";
2835: return false;
2836: }
2837: // ]]>
2838: </script>
2839: ENDJS
2840:
2841: }
2842:
2843: #--- Called from submission routine
2844: sub processHandGrade {
2845: my ($request,$symb) = @_;
2846: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
2847: my $button = $env{'form.gradeOpt'};
2848: my $ngrade = $env{'form.NCT'};
2849: my $ntstu = $env{'form.NTSTU'};
2850: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2851: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2852:
2853: if ($button eq 'Save & Next') {
2854: my $ctr = 0;
2855: while ($ctr < $ngrade) {
2856: my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
2857: my ($errorflag,$pts,$wgt,$numhidden) =
2858: &saveHandGrade($request,$symb,$uname,$udom,$ctr);
2859: if ($errorflag eq 'no_score') {
2860: $ctr++;
2861: next;
2862: }
2863: if ($errorflag eq 'not_allowed') {
2864: $request->print(
2865: '<span class="LC_error">'
2866: .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
2867: .'</span>');
2868: $ctr++;
2869: next;
2870: }
2871: if ($numhidden) {
2872: $request->print(
2873: '<span class="LC_info">'
2874: .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
2875: .'</span><br />');
2876: }
2877: my $includemsg = $env{'form.includemsg'.$ctr};
2878: my ($subject,$message,$msgstatus) = ('','','');
2879: my $restitle = &Apache::lonnet::gettitle($symb);
2880: my ($feedurl,$showsymb) =
2881: &get_feedurl_and_symb($symb,$uname,$udom);
2882: my $messagetail;
2883: if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
2884: $subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
2885: unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
2886: $subject.=' ['.$restitle.']';
2887: my (@msgnum) = split(/,/,$includemsg);
2888: foreach (@msgnum) {
2889: $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
2890: }
2891: $message =&Apache::lonfeedback::clear_out_html($message);
2892: if ($env{'form.withgrades'.$ctr}) {
2893: $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
2894: $messagetail = " for <a href=\"".
2895: $feedurl."?symb=$showsymb\">$restitle</a>";
2896: }
2897: $msgstatus =
2898: &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
2899: $message.$messagetail,
2900: undef,$feedurl,undef,
2901: undef,undef,$showsymb,
2902: $restitle);
2903: $request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
2904: $msgstatus.'<br />');
2905: }
2906: if ($env{'form.collaborator'.$ctr}) {
2907: my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
2908: foreach my $collabstr (@collabstrs) {
2909: my ($part,@collaborators) = split(/:/,$collabstr);
2910: foreach my $collaborator (@collaborators) {
2911: my ($errorflag,$pts,$wgt) =
2912: &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
2913: $env{'form.unamedom'.$ctr},$part);
2914: if ($errorflag eq 'not_allowed') {
2915: $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
2916: next;
2917: } elsif ($message ne '') {
2918: my ($baseurl,$showsymb) =
2919: &get_feedurl_and_symb($symb,$collaborator,
2920: $udom);
2921: if ($env{'form.withgrades'.$ctr}) {
2922: $messagetail = " for <a href=\"".
2923: $baseurl."?symb=$showsymb\">$restitle</a>";
2924: }
2925: $msgstatus =
2926: &Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
2927: }
2928: }
2929: }
2930: }
2931: $ctr++;
2932: }
2933: }
2934:
2935: # if ($env{'form.handgrade'} eq 'yes') {
2936: if (1) {
2937: # Keywords sorted in alphabatical order
2938: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
2939: my %keyhash = ();
2940: $env{'form.keywords'} =~ s/,\s{0,}|\s+/ /g;
2941: $env{'form.keywords'} =~ s/^\s+|\s+$//;
2942: my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
2943: $env{'form.keywords'} = join(' ',@keywords);
2944: $keyhash{$symb.'_keywords'} = $env{'form.keywords'};
2945: $keyhash{$symb.'_subject'} = $env{'form.msgsub'};
2946: $keyhash{$loginuser.'_kwclr'} = $env{'form.kwclr'};
2947: $keyhash{$loginuser.'_kwsize'} = $env{'form.kwsize'};
2948: $keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
2949:
2950: # message center - Order of message gets changed. Blank line is eliminated.
2951: # New messages are saved in env for the next student.
2952: # All messages are saved in nohist_handgrade.db
2953: my ($ctr,$idx) = (1,1);
2954: while ($ctr <= $env{'form.savemsgN'}) {
2955: if ($env{'form.savemsg'.$ctr} ne '') {
2956: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
2957: $idx++;
2958: }
2959: $ctr++;
2960: }
2961: $ctr = 0;
2962: while ($ctr < $ngrade) {
2963: if ($env{'form.newmsg'.$ctr} ne '') {
2964: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2965: $env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2966: $idx++;
2967: }
2968: $ctr++;
2969: }
2970: $env{'form.savemsgN'} = --$idx;
2971: $keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
2972: my $putresult = &Apache::lonnet::put
2973: ('nohist_handgrade',\%keyhash,$cdom,$cnum);
2974: }
2975: # Called by Save & Refresh from Highlight Attribute Window
2976: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
2977: if ($env{'form.refresh'} eq 'on') {
2978: my ($ctr,$total) = (0,0);
2979: while ($ctr < $ngrade) {
2980: $total++ if $env{'form.unamedom'.$ctr} ne '';
2981: $ctr++;
2982: }
2983: $env{'form.NTSTU'}=$ngrade;
2984: $ctr = 0;
2985: while ($ctr < $total) {
2986: my $processUser = $env{'form.unamedom'.$ctr};
2987: ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
2988: $env{'form.fullname'} = $$fullname{$processUser};
2989: &submission($request,$ctr,$total-1,$symb);
2990: $ctr++;
2991: }
2992: return '';
2993: }
2994:
2995: # Get the next/previous one or group of students
2996: my $firststu = $env{'form.unamedom0'};
2997: my $laststu = $env{'form.unamedom'.($ngrade-1)};
2998: my $ctr = 2;
2999: while ($laststu eq '') {
3000: $laststu = $env{'form.unamedom'.($ngrade-$ctr)};
3001: $ctr++;
3002: $laststu = $firststu if ($ctr > $ngrade);
3003: }
3004:
3005: my (@parsedlist,@nextlist);
3006: my ($nextflg) = 0;
3007: foreach my $item (sort
3008: {
3009: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
3010: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
3011: }
3012: return $a cmp $b;
3013: } (keys(%$fullname))) {
3014: # FIXME: this is fishy, looks like the button label
3015: if ($nextflg == 1 && $button =~ /Next$/) {
3016: push(@parsedlist,$item);
3017: }
3018: $nextflg = 1 if ($item eq $laststu);
3019: if ($button eq 'Previous') {
3020: last if ($item eq $firststu);
3021: push(@parsedlist,$item);
3022: }
3023: }
3024: $ctr = 0;
3025: # FIXME: this is fishy, looks like the button label
3026: @parsedlist = reverse @parsedlist if ($button eq 'Previous');
3027: my $res_error;
3028: my ($partlist) = &response_type($symb,\$res_error);
3029: if ($res_error) {
3030: $request->print(&navmap_errormsg());
3031: return;
3032: }
3033: foreach my $student (@parsedlist) {
3034: my $submitonly=$env{'form.submitonly'};
3035: my ($uname,$udom) = split(/:/,$student);
3036:
3037: if ($submitonly eq 'queued') {
3038: my %queue_status =
3039: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
3040: $udom,$uname);
3041: next if (!defined($queue_status{'gradingqueue'}));
3042: }
3043:
3044: if ($submitonly =~ /^(yes|graded|incorrect)$/) {
3045: # my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
3046: my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
3047: my $submitted = 0;
3048: my $ungraded = 0;
3049: my $incorrect = 0;
3050: foreach my $item (keys(%status)) {
3051: $submitted = 1 if ($status{$item} ne 'nothing');
3052: $ungraded = 1 if ($status{$item} =~ /^ungraded/);
3053: $incorrect = 1 if ($status{$item} =~ /^incorrect/);
3054: my ($foo,$partid,$foo1) = split(/\./,$item);
3055: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
3056: $submitted = 0;
3057: }
3058: }
3059: next if (!$submitted && ($submitonly eq 'yes' ||
3060: $submitonly eq 'incorrect' ||
3061: $submitonly eq 'graded'));
3062: next if (!$ungraded && ($submitonly eq 'graded'));
3063: next if (!$incorrect && $submitonly eq 'incorrect');
3064: }
3065: push(@nextlist,$student) if ($ctr < $ntstu);
3066: last if ($ctr == $ntstu);
3067: $ctr++;
3068: }
3069:
3070: $ctr = 0;
3071: my $total = scalar(@nextlist)-1;
3072:
3073: foreach (sort(@nextlist)) {
3074: my ($uname,$udom,$submitter) = split(/:/);
3075: $env{'form.student'} = $uname;
3076: $env{'form.userdom'} = $udom;
3077: $env{'form.fullname'} = $$fullname{$_};
3078: &submission($request,$ctr,$total,$symb);
3079: $ctr++;
3080: }
3081: if ($total < 0) {
3082: my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
3083: $request->print($the_end);
3084: }
3085: return '';
3086: }
3087:
3088: #---- Save the score and award for each student, if changed
3089: sub saveHandGrade {
3090: my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
3091: my @version_parts;
3092: my $usec = &Apache::lonnet::getsection($domain,$stuname,
3093: $env{'request.course.id'});
3094: if (!&canmodify($usec)) { return('not_allowed'); }
3095: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
3096: my @parts_graded;
3097: my %newrecord = ();
3098: my ($pts,$wgt,$totchg) = ('','',0);
3099: my %aggregate = ();
3100: my $aggregateflag = 0;
3101: if ($env{'form.HIDE'.$newflg}) {
3102: my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
3103: my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
3104: $totchg += $numchgs;
3105: }
3106: my @parts = split(/:/,$env{'form.partlist'.$newflg});
3107: foreach my $new_part (@parts) {
3108: #collaborator ($submi may vary for different parts
3109: if ($submitter && $new_part ne $part) { next; }
3110: my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
3111: if ($dropMenu eq 'excused') {
3112: if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
3113: $newrecord{'resource.'.$new_part.'.solved'} = 'excused';
3114: if (exists($record{'resource.'.$new_part.'.awarded'})) {
3115: $newrecord{'resource.'.$new_part.'.awarded'} = '';
3116: }
3117: $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
3118: }
3119: } elsif ($dropMenu eq 'reset status'
3120: && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
3121: foreach my $key (keys(%record)) {
3122: if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
3123: }
3124: $newrecord{'resource.'.$new_part.'.regrader'}=
3125: "$env{'user.name'}:$env{'user.domain'}";
3126: my $totaltries = $record{'resource.'.$part.'.tries'};
3127:
3128: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
3129: [$new_part]);
3130: my $aggtries =$totaltries;
3131: if ($last_resets{$new_part}) {
3132: $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
3133: $new_part);
3134: }
3135:
3136: my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
3137: if ($aggtries > 0) {
3138: &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
3139: $aggregateflag = 1;
3140: }
3141: } elsif ($dropMenu eq '') {
3142: $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ?
3143: $env{'form.GD_BOX'.$newflg.'_'.$new_part} :
3144: $env{'form.RADVAL'.$newflg.'_'.$new_part});
3145: if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
3146: next;
3147: }
3148: $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 :
3149: $env{'form.WGT'.$newflg.'_'.$new_part};
3150: my $partial= $pts/$wgt;
3151: if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
3152: #do not update score for part if not changed.
3153: &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
3154: next;
3155: } else {
3156: push(@parts_graded,$new_part);
3157: }
3158: if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
3159: $newrecord{'resource.'.$new_part.'.awarded'} = $partial;
3160: }
3161: my $reckey = 'resource.'.$new_part.'.solved';
3162: if ($partial == 0) {
3163: if ($record{$reckey} ne 'incorrect_by_override') {
3164: $newrecord{$reckey} = 'incorrect_by_override';
3165: }
3166: } else {
3167: if ($record{$reckey} ne 'correct_by_override') {
3168: $newrecord{$reckey} = 'correct_by_override';
3169: }
3170: }
3171: if ($submitter &&
3172: ($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
3173: $newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
3174: }
3175: $newrecord{'resource.'.$new_part.'.regrader'}=
3176: "$env{'user.name'}:$env{'user.domain'}";
3177: }
3178: # unless problem has been graded, set flag to version the submitted files
3179: unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/ ||
3180: $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
3181: $dropMenu eq 'reset status')
3182: {
3183: push(@version_parts,$new_part);
3184: }
3185: }
3186: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3187: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3188:
3189: if (%newrecord) {
3190: if (@version_parts) {
3191: my @changed_keys = &version_portfiles(\%record, \@parts_graded,
3192: $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
3193: @newrecord{@changed_keys} = @record{@changed_keys};
3194: foreach my $new_part (@version_parts) {
3195: &handback_files($request,$symb,$stuname,$domain,$newflg,
3196: $new_part,\%newrecord);
3197: }
3198: }
3199: &Apache::lonnet::cstore(\%newrecord,$symb,
3200: $env{'request.course.id'},$domain,$stuname);
3201: &check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
3202: $cdom,$cnum,$domain,$stuname);
3203: }
3204: if ($aggregateflag) {
3205: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
3206: $cdom,$cnum);
3207: }
3208: return ('',$pts,$wgt,$totchg);
3209: }
3210:
3211: sub makehidden {
3212: my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
3213: return unless (ref($record) eq 'HASH');
3214: my %modified;
3215: my $numchanged = 0;
3216: if (exists($record->{$version.':keys'})) {
3217: my $partsregexp = $parts;
3218: $partsregexp =~ s/,/|/g;
3219: foreach my $key (split(/\:/,$record->{$version.':keys'})) {
3220: if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
3221: my $item = $1;
3222: unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
3223: $modified{$key} = $record->{$version.':'.$key};
3224: }
3225: } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
3226: $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
3227: } elsif ($key =~ /^(ip|timestamp|host)$/) {
3228: $modified{$key} = $record->{$version.':'.$key};
3229: }
3230: }
3231: if (keys(%modified)) {
3232: if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
3233: $domain,$stuname,$tolog) eq 'ok') {
3234: $numchanged ++;
3235: }
3236: }
3237: }
3238: return $numchanged;
3239: }
3240:
3241: sub check_and_remove_from_queue {
3242: my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
3243: my @ungraded_parts;
3244: foreach my $part (@{$parts}) {
3245: if ( $record->{ 'resource.'.$part.'.awarded'} eq ''
3246: && $record->{ 'resource.'.$part.'.solved' } ne 'excused'
3247: && $newrecord->{'resource.'.$part.'.awarded'} eq ''
3248: && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
3249: ) {
3250: push(@ungraded_parts, $part);
3251: }
3252: }
3253: if ( !@ungraded_parts ) {
3254: &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
3255: $cnum,$domain,$stuname);
3256: }
3257: }
3258:
3259: sub handback_files {
3260: my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
3261: my $portfolio_root = '/userfiles/portfolio';
3262: my $res_error;
3263: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
3264: if ($res_error) {
3265: $request->print('<br />'.&navmap_errormsg().'<br />');
3266: return;
3267: }
3268: my @handedback;
3269: my $file_msg;
3270: my @part_response_id = &flatten_responseType($responseType);
3271: foreach my $part_response_id (@part_response_id) {
3272: my ($part_id,$resp_id) = @{ $part_response_id };
3273: my $part_resp = join('_',@{ $part_response_id });
3274: if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
3275: for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
3276: # if multiple files are uploaded names will be 'returndoc2','returndoc3'
3277: if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
3278: my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
3279: my ($directory,$answer_file) =
3280: ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
3281: my ($answer_name,$answer_ver,$answer_ext) =
3282: &Apache::lonnet::file_name_version_ext($answer_file);
3283: my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
3284: my $getpropath = 1;
3285: my ($dir_list,$listerror) =
3286: &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
3287: $domain,$stuname,$getpropath);
3288: my $version = &Apache::lonnet::get_next_version($answer_name,$answer_ext,$dir_list);
3289: # fix filename
3290: my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
3291: my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
3292: $newflg.'_'.$part_resp.'_returndoc'.$counter,
3293: $save_file_name);
3294: if ($result !~ m|^/uploaded/|) {
3295: $request->print('<br /><span class="LC_error">'.
3296: &mt('An error occurred ([_1]) while trying to upload [_2].',
3297: $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
3298: '</span>');
3299: } else {
3300: # mark the file as read only
3301: push(@handedback,$save_file_name);
3302: if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
3303: $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
3304: }
3305: $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
3306: $file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
3307: }
3308: $request->print('<br />'.&mt('[_1] will be the uploaded filename [_2]','<span class="LC_info">'.$fname.'</span>','<span class="LC_filename">'.$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter}.'</span>'));
3309: }
3310: }
3311: }
3312: }
3313: if (@handedback > 0) {
3314: $request->print('<br />');
3315: my @what = ($symb,$env{'request.course.id'},'handback');
3316: &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
3317: my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});
3318: my ($subject,$message);
3319: if (scalar(@handedback) == 1) {
3320: $subject = &mt_user($user_lh,'File Handed Back by Instructor');
3321: $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
3322: } else {
3323: $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
3324: $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
3325: }
3326: $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
3327: $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
3328: &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
3329: my ($feedurl,$showsymb) =
3330: &get_feedurl_and_symb($symb,$domain,$stuname);
3331: my $restitle = &Apache::lonnet::gettitle($symb);
3332: $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
3333: my $msgstatus =
3334: &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
3335: $message,undef,$feedurl,undef,undef,undef,$showsymb,
3336: $restitle);
3337: if ($msgstatus) {
3338: $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
3339: }
3340: }
3341: return;
3342: }
3343:
3344: sub get_feedurl_and_symb {
3345: my ($symb,$uname,$udom) = @_;
3346: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3347: $url = &Apache::lonnet::clutter($url);
3348: my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
3349: $symb,$udom,$uname);
3350: if ($encrypturl =~ /^yes$/i) {
3351: &Apache::lonenc::encrypted(\$url,1);
3352: &Apache::lonenc::encrypted(\$symb,1);
3353: }
3354: return ($url,$symb);
3355: }
3356:
3357: sub get_submitted_files {
3358: my ($udom,$uname,$partid,$respid,$record) = @_;
3359: my @files;
3360: if ($$record{"resource.$partid.$respid.portfiles"}) {
3361: my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
3362: foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
3363: push(@files,$file_url.$file);
3364: }
3365: }
3366: if ($$record{"resource.$partid.$respid.uploadedurl"}) {
3367: push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
3368: }
3369: return (\@files);
3370: }
3371:
3372: # ----------- Provides number of tries since last reset.
3373: sub get_num_tries {
3374: my ($record,$last_reset,$part) = @_;
3375: my $timestamp = '';
3376: my $num_tries = 0;
3377: if ($$record{'version'}) {
3378: for (my $version=$$record{'version'};$version>=1;$version--) {
3379: if (exists($$record{$version.':resource.'.$part.'.solved'})) {
3380: $timestamp = $$record{$version.':timestamp'};
3381: if ($timestamp > $last_reset) {
3382: $num_tries ++;
3383: } else {
3384: last;
3385: }
3386: }
3387: }
3388: }
3389: return $num_tries;
3390: }
3391:
3392: # ----------- Determine decrements required in aggregate totals
3393: sub decrement_aggs {
3394: my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
3395: my %decrement = (
3396: attempts => 0,
3397: users => 0,
3398: correct => 0
3399: );
3400: $decrement{'attempts'} = $aggtries;
3401: if ($solvedstatus =~ /^correct/) {
3402: $decrement{'correct'} = 1;
3403: }
3404: if ($aggtries == $totaltries) {
3405: $decrement{'users'} = 1;
3406: }
3407: foreach my $type (keys(%decrement)) {
3408: $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
3409: }
3410: return;
3411: }
3412:
3413: # ----------- Determine timestamps for last reset of aggregate totals for parts
3414: sub get_last_resets {
3415: my ($symb,$courseid,$partids) =@_;
3416: my %last_resets;
3417: my $cdom = $env{'course.'.$courseid.'.domain'};
3418: my $cname = $env{'course.'.$courseid.'.num'};
3419: my @keys;
3420: foreach my $part (@{$partids}) {
3421: push(@keys,"$symb\0$part\0resettime");
3422: }
3423: my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
3424: $cdom,$cname);
3425: foreach my $part (@{$partids}) {
3426: $last_resets{$part}=$results{"$symb\0$part\0resettime"};
3427: }
3428: return %last_resets;
3429: }
3430:
3431: # ----------- Handles creating versions for portfolio files as answers
3432: sub version_portfiles {
3433: my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
3434: my $version_parts = join('|',@$v_flag);
3435: my @returned_keys;
3436: my $parts = join('|', @$parts_graded);
3437: foreach my $key (keys(%$record)) {
3438: my $new_portfiles;
3439: if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
3440: my @versioned_portfiles;
3441: my @portfiles = split(/\s*,\s*/,$$record{$key});
3442: if (@portfiles) {
3443: &Apache::lonnet::portfiles_versioning($symb,$domain,$stu_name,\@portfiles,
3444: \@versioned_portfiles);
3445: }
3446: $$record{$key} = join(',',@versioned_portfiles);
3447: push(@returned_keys,$key);
3448: }
3449: }
3450: return (@returned_keys);
3451: }
3452:
3453: #--------------------------------------------------------------------------------------
3454: #
3455: #-------------------------- Next few routines handles grading by section or whole class
3456: #
3457: #--- Javascript to handle grading by section or whole class
3458: sub viewgrades_js {
3459: my ($request) = shift;
3460:
3461: my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
3462: &js_escape(\$alertmsg);
3463: $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
3464: function writePoint(partid,weight,point) {
3465: var radioButton = document.classgrade["RADVAL_"+partid];
3466: var textbox = document.classgrade["TEXTVAL_"+partid];
3467: if (point == "textval") {
3468: point = document.classgrade["TEXTVAL_"+partid].value;
3469: if (isNaN(point) || parseFloat(point) < 0) {
3470: alert("$alertmsg"+parseFloat(point));
3471: var resetbox = false;
3472: for (var i=0; i<radioButton.length; i++) {
3473: if (radioButton[i].checked) {
3474: textbox.value = i;
3475: resetbox = true;
3476: }
3477: }
3478: if (!resetbox) {
3479: textbox.value = "";
3480: }
3481: return;
3482: }
3483: if (parseFloat(point) > parseFloat(weight)) {
3484: var resp = confirm("You entered a value ("+parseFloat(point)+
3485: ") greater than the weight for the part. Accept?");
3486: if (resp == false) {
3487: textbox.value = "";
3488: return;
3489: }
3490: }
3491: for (var i=0; i<radioButton.length; i++) {
3492: radioButton[i].checked=false;
3493: if (parseFloat(point) == i) {
3494: radioButton[i].checked=true;
3495: }
3496: }
3497:
3498: } else {
3499: textbox.value = parseFloat(point);
3500: }
3501: for (i=0;i<document.classgrade.total.value;i++) {
3502: var user = document.classgrade["ctr"+i].value;
3503: user = user.replace(new RegExp(':', 'g'),"_");
3504: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3505: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3506: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3507: if (saveval != "correct") {
3508: scorename.value = point;
3509: if (selname[0].selected != true) {
3510: selname[0].selected = true;
3511: }
3512: }
3513: }
3514: document.classgrade["SELVAL_"+partid][0].selected = true;
3515: }
3516:
3517: function writeRadText(partid,weight) {
3518: var selval = document.classgrade["SELVAL_"+partid];
3519: var radioButton = document.classgrade["RADVAL_"+partid];
3520: var override = document.classgrade["FORCE_"+partid].checked;
3521: var textbox = document.classgrade["TEXTVAL_"+partid];
3522: if (selval[1].selected || selval[2].selected) {
3523: for (var i=0; i<radioButton.length; i++) {
3524: radioButton[i].checked=false;
3525:
3526: }
3527: textbox.value = "";
3528:
3529: for (i=0;i<document.classgrade.total.value;i++) {
3530: var user = document.classgrade["ctr"+i].value;
3531: user = user.replace(new RegExp(':', 'g'),"_");
3532: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3533: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3534: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3535: if ((saveval != "correct") || override) {
3536: scorename.value = "";
3537: if (selval[1].selected) {
3538: selname[1].selected = true;
3539: } else {
3540: selname[2].selected = true;
3541: if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value))
3542: {document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
3543: }
3544: }
3545: }
3546: } else {
3547: for (i=0;i<document.classgrade.total.value;i++) {
3548: var user = document.classgrade["ctr"+i].value;
3549: user = user.replace(new RegExp(':', 'g'),"_");
3550: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3551: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3552: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3553: if ((saveval != "correct") || override) {
3554: scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
3555: selname[0].selected = true;
3556: }
3557: }
3558: }
3559: }
3560:
3561: function changeSelect(partid,user) {
3562: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
3563: var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
3564: var point = textbox.value;
3565: var weight = document.classgrade["weight_"+partid].value;
3566:
3567: if (isNaN(point) || parseFloat(point) < 0) {
3568: alert("$alertmsg"+parseFloat(point));
3569: textbox.value = "";
3570: return;
3571: }
3572: if (parseFloat(point) > parseFloat(weight)) {
3573: var resp = confirm("You entered a value ("+parseFloat(point)+
3574: ") greater than the weight of the part. Accept?");
3575: if (resp == false) {
3576: textbox.value = "";
3577: return;
3578: }
3579: }
3580: selval[0].selected = true;
3581: }
3582:
3583: function changeOneScore(partid,user) {
3584: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
3585: if (selval[1].selected || selval[2].selected) {
3586: document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
3587: if (selval[2].selected) {
3588: document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
3589: }
3590: }
3591: }
3592:
3593: function resetEntry(numpart) {
3594: for (ctpart=0;ctpart<numpart;ctpart++) {
3595: var partid = document.classgrade["partid_"+ctpart].value;
3596: var radioButton = document.classgrade["RADVAL_"+partid];
3597: var textbox = document.classgrade["TEXTVAL_"+partid];
3598: var selval = document.classgrade["SELVAL_"+partid];
3599: for (var i=0; i<radioButton.length; i++) {
3600: radioButton[i].checked=false;
3601:
3602: }
3603: textbox.value = "";
3604: selval[0].selected = true;
3605:
3606: for (i=0;i<document.classgrade.total.value;i++) {
3607: var user = document.classgrade["ctr"+i].value;
3608: user = user.replace(new RegExp(':', 'g'),"_");
3609: var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3610: resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
3611: var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
3612: resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
3613: var saveselval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3614: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3615: if (saveselval == "excused") {
3616: if (selname[1].selected == false) { selname[1].selected = true;}
3617: } else {
3618: if (selname[0].selected == false) {selname[0].selected = true};
3619: }
3620: }
3621: }
3622: }
3623:
3624: VIEWJAVASCRIPT
3625: }
3626:
3627: #--- show scores for a section or whole class w/ option to change/update a score
3628: sub viewgrades {
3629: my ($request,$symb) = @_;
3630: my ($is_tool,$toolsymb);
3631: if ($symb =~ /ext\.tool$/) {
3632: $is_tool = 1;
3633: $toolsymb = $symb;
3634: }
3635: &viewgrades_js($request);
3636:
3637: #need to make sure we have the correct data for later EXT calls,
3638: #thus invalidate the cache
3639: &Apache::lonnet::devalidatecourseresdata(
3640: $env{'course.'.$env{'request.course.id'}.'.num'},
3641: $env{'course.'.$env{'request.course.id'}.'.domain'});
3642: &Apache::lonnet::clear_EXT_cache_status();
3643:
3644: my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
3645:
3646: #view individual student submission form - called using Javascript viewOneStudent
3647: $result.=&jscriptNform($symb);
3648:
3649: #beginning of class grading form
3650: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
3651: $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
3652: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
3653: '<input type="hidden" name="command" value="editgrades" />'."\n".
3654: &build_section_inputs().
3655: '<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
3656:
3657: #retrieve selected groups
3658: my (@groups,$group_display);
3659: @groups = &Apache::loncommon::get_env_multiple('form.group');
3660: if (grep(/^all$/,@groups)) {
3661: @groups = ('all');
3662: } elsif (grep(/^none$/,@groups)) {
3663: @groups = ('none');
3664: } elsif (@groups > 0) {
3665: $group_display = join(', ',@groups);
3666: }
3667:
3668: my ($common_header,$specific_header,@sections,$section_display);
3669: @sections = &Apache::loncommon::get_env_multiple('form.section');
3670: if (grep(/^all$/,@sections)) {
3671: @sections = ('all');
3672: if ($group_display) {
3673: $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
3674: $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
3675: } elsif (grep(/^none$/,@groups)) {
3676: $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
3677: $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
3678: } else {
3679: $common_header = &mt('Assign Common Grade to Class');
3680: $specific_header = &mt('Assign Grade to Specific Students in Class');
3681: }
3682: } elsif (grep(/^none$/,@sections)) {
3683: @sections = ('none');
3684: if ($group_display) {
3685: $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
3686: $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
3687: } elsif (grep(/^none$/,@groups)) {
3688: $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
3689: $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
3690: } else {
3691: $common_header = &mt('Assign Common Grade to Students in no Section');
3692: $specific_header = &mt('Assign Grade to Specific Students in no Section');
3693: }
3694: } else {
3695: $section_display = join (", ",@sections);
3696: if ($group_display) {
3697: $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
3698: $section_display,$group_display);
3699: $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
3700: $section_display,$group_display);
3701: } elsif (grep(/^none$/,@groups)) {
3702: $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
3703: $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
3704: } else {
3705: $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
3706: $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
3707: }
3708: }
3709: my %submit_types = &substatus_options();
3710: my $submission_status = $submit_types{$env{'form.submitonly'}};
3711:
3712: if ($env{'form.submitonly'} eq 'all') {
3713: $result.= '<h3>'.$common_header.'</h3>';
3714: } else {
3715: my $text;
3716: if ($is_tool) {
3717: $text = &mt('(transaction status: "[_1]")',$submission_status);
3718: } else {
3719: $text = &mt('(submission status: "[_1]")',$submission_status);
3720: }
3721: $result.= '<h3>'.$common_header.' '.$text.'</h3>';
3722: }
3723: $result .= &Apache::loncommon::start_data_table();
3724: #radio buttons/text box for assigning points for a section or class.
3725: #handles different parts of a problem
3726: my $res_error;
3727: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
3728: if ($res_error) {
3729: return &navmap_errormsg();
3730: }
3731: my %weight = ();
3732: my $ctsparts = 0;
3733: my %seen = ();
3734: my @part_response_id;
3735: if ($is_tool) {
3736: @part_response_id = ([0,'']);
3737: } else {
3738: @part_response_id = &flatten_responseType($responseType);
3739: }
3740: foreach my $part_response_id (@part_response_id) {
3741: my ($partid,$respid) = @{ $part_response_id };
3742: my $part_resp = join('_',@{ $part_response_id });
3743: next if $seen{$partid};
3744: $seen{$partid}++;
3745: # my $handgrade=$$handgrade{$part_resp};
3746: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
3747: $weight{$partid} = $wgt eq '' ? '1' : $wgt;
3748:
3749: my $display_part=&get_display_part($partid,$symb);
3750: my $radio.='<table border="0"><tr>';
3751: my $ctr = 0;
3752: while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
3753: $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
3754: 'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
3755: ','.$ctr.')" />'.$ctr."</label></td>\n";
3756: $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
3757: $ctr++;
3758: }
3759: $radio.='</tr></table>';
3760: my $line = '<input type="text" name="TEXTVAL_'.
3761: $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
3762: $partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
3763: $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
3764: $line.= '<td><b>'.&mt('Grade Status').':</b>'.
3765: '<select name="SELVAL_'.$partid.'" '.
3766: 'onchange="javascript:writeRadText(\''.$partid.'\','.
3767: $weight{$partid}.')"> '.
3768: '<option selected="selected"> </option>'.
3769: '<option value="excused">'.&mt('excused').'</option>'.
3770: '<option value="reset status">'.&mt('reset status').'</option>'.
3771: '</select></td>'.
3772: '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
3773: $line.='<input type="hidden" name="partid_'.
3774: $ctsparts.'" value="'.$partid.'" />'."\n";
3775: $line.='<input type="hidden" name="weight_'.
3776: $partid.'" value="'.$weight{$partid}.'" />'."\n";
3777:
3778: $result.=
3779: &Apache::loncommon::start_data_table_row()."\n".
3780: '<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>'.
3781: &Apache::loncommon::end_data_table_row()."\n";
3782: $ctsparts++;
3783: }
3784: $result.=&Apache::loncommon::end_data_table()."\n".
3785: '<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
3786: $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
3787: 'onclick="javascript:resetEntry('.$ctsparts.');" />';
3788:
3789: #table listing all the students in a section/class
3790: #header of table
3791: if ($env{'form.submitonly'} eq 'all') {
3792: $result.= '<h3>'.$specific_header.'</h3>';
3793: } else {
3794: my $text;
3795: if ($is_tool) {
3796: $text = &mt('(transaction status: "[_1]")',$submission_status);
3797: } else {
3798: $text = &mt('(submission status: "[_1]")',$submission_status);
3799: }
3800: $result.= '<h3>'.$specific_header.' '.$text.'</h3>';
3801: }
3802: $result.= &Apache::loncommon::start_data_table().
3803: &Apache::loncommon::start_data_table_header_row().
3804: '<th>'.&mt('No.').'</th>'.
3805: '<th>'.&nameUserString('header')."</th>\n";
3806: my $partserror;
3807: my (@parts) = sort(&getpartlist($symb,\$partserror));
3808: if ($partserror) {
3809: return &navmap_errormsg();
3810: }
3811: my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
3812: my @partids = ();
3813: foreach my $part (@parts) {
3814: my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
3815: my $narrowtext = &mt('Tries');
3816: $display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
3817: if (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name',$toolsymb); }
3818: my ($partid) = &split_part_type($part);
3819: push(@partids,$partid);
3820: #
3821: # FIXME: Looks like $display looks at English text
3822: #
3823: my $display_part=&get_display_part($partid,$symb);
3824: if ($display =~ /^Partial Credit Factor/) {
3825: $result.='<th>'.
3826: &mt('Score Part: [_1][_2](weight = [_3])',
3827: $display_part,'<br />',$weight{$partid}).'</th>'."\n";
3828: next;
3829:
3830: } else {
3831: if ($display =~ /Problem Status/) {
3832: my $grade_status_mt = &mt('Grade Status');
3833: $display =~ s{Problem Status}{$grade_status_mt<br />};
3834: }
3835: my $part_mt = &mt('Part:');
3836: $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
3837: }
3838:
3839: $result.='<th>'.$display.'</th>'."\n";
3840: }
3841: $result.=&Apache::loncommon::end_data_table_header_row();
3842:
3843: my %last_resets =
3844: &get_last_resets($symb,$env{'request.course.id'},\@partids);
3845:
3846: #get info for each student
3847: #list all the students - with points and grade status
3848: my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
3849: my $ctr = 0;
3850: foreach (sort
3851: {
3852: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
3853: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
3854: }
3855: return $a cmp $b;
3856: } (keys(%$fullname))) {
3857: $result.=&viewstudentgrade($symb,$env{'request.course.id'},
3858: $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets,$is_tool);
3859: }
3860: $result.=&Apache::loncommon::end_data_table();
3861: $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
3862: $result.='<input type="button" value="'.&mt('Save').'" '.
3863: 'onclick="javascript:submit();" target="_self" /></form>'."\n";
3864: if ($ctr == 0) {
3865: my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
3866: $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
3867: '<span class="LC_warning">';
3868: if ($env{'form.submitonly'} eq 'all') {
3869: if (grep(/^all$/,@sections)) {
3870: if (grep(/^all$/,@groups)) {
3871: $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
3872: $stu_status);
3873: } elsif (grep(/^none$/,@groups)) {
3874: $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
3875: $stu_status);
3876: } else {
3877: $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
3878: $group_display,$stu_status);
3879: }
3880: } elsif (grep(/^none$/,@sections)) {
3881: if (grep(/^all$/,@groups)) {
3882: $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
3883: $stu_status);
3884: } elsif (grep(/^none$/,@groups)) {
3885: $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
3886: $stu_status);
3887: } else {
3888: $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
3889: $group_display,$stu_status);
3890: }
3891: } else {
3892: if (grep(/^all$/,@groups)) {
3893: $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
3894: $section_display,$stu_status);
3895: } elsif (grep(/^none$/,@groups)) {
3896: $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
3897: $section_display,$stu_status);
3898: } else {
3899: $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
3900: $section_display,$group_display,$stu_status);
3901: }
3902: }
3903: } else {
3904: if (grep(/^all$/,@sections)) {
3905: if (grep(/^all$/,@groups)) {
3906: $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
3907: $stu_status,$submission_status);
3908: } elsif (grep(/^none$/,@groups)) {
3909: $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
3910: $stu_status,$submission_status);
3911: } else {
3912: $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
3913: $group_display,$stu_status,$submission_status);
3914: }
3915: } elsif (grep(/^none$/,@sections)) {
3916: if (grep(/^all$/,@groups)) {
3917: $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
3918: $stu_status,$submission_status);
3919: } elsif (grep(/^none$/,@groups)) {
3920: $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
3921: $stu_status,$submission_status);
3922: } else {
3923: $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
3924: $group_display,$stu_status,$submission_status);
3925: }
3926: } else {
3927: if (grep(/^all$/,@groups)) {
3928: $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
3929: $section_display,$stu_status,$submission_status);
3930: } elsif (grep(/^none$/,@groups)) {
3931: $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] and submission status "[_3]" to modify or grade.',
3932: $section_display,$stu_status,$submission_status);
3933: } else {
3934: $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] and submission status "[_4]" to modify or grade.',
3935: $section_display,$group_display,$stu_status,$submission_status);
3936: }
3937: }
3938: }
3939: $result .= '</span><br />';
3940: }
3941: return $result;
3942: }
3943:
3944: #--- call by previous routine to display each student who satisfies submission filter.
3945: sub viewstudentgrade {
3946: my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets,$is_tool) = @_;
3947: my ($uname,$udom) = split(/:/,$student);
3948: my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
3949: my $submitonly = $env{'form.submitonly'};
3950: unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
3951: my %partstatus = ();
3952: if (ref($parts) eq 'ARRAY') {
3953: foreach my $apart (@{$parts}) {
3954: my ($part,$type) = &split_part_type($apart);
3955: my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
3956: $status = 'nothing' if ($status eq '');
3957: $partstatus{$part} = $status;
3958: my $subkey = "resource.$part.submitted_by";
3959: $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
3960: }
3961: my $submitted = 0;
3962: my $graded = 0;
3963: my $incorrect = 0;
3964: foreach my $key (keys(%partstatus)) {
3965: $submitted = 1 if ($partstatus{$key} ne 'nothing');
3966: $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
3967: $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
3968:
3969: my $partid = (split(/\./,$key))[1];
3970: if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
3971: $submitted = 0;
3972: }
3973: }
3974: return if (!$submitted && ($submitonly eq 'yes' ||
3975: $submitonly eq 'incorrect' ||
3976: $submitonly eq 'graded'));
3977: return if (!$graded && ($submitonly eq 'graded'));
3978: return if (!$incorrect && $submitonly eq 'incorrect');
3979: }
3980: }
3981: if ($submitonly eq 'queued') {
3982: my ($cdom,$cnum) = split(/_/,$courseid);
3983: my %queue_status =
3984: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
3985: $udom,$uname);
3986: return if (!defined($queue_status{'gradingqueue'}));
3987: }
3988: $$ctr++;
3989: my %aggregates = ();
3990: my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
3991: '<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
3992: "\n".$$ctr.' </td><td> '.
3993: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
3994: '\');" target="_self">'.$fullname.'</a> '.
3995: '<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
3996: $student=~s/:/_/; # colon doen't work in javascript for names
3997: foreach my $apart (@$parts) {
3998: my ($part,$type) = &split_part_type($apart);
3999: my $score=$record{"resource.$part.$type"};
4000: $result.='<td align="center">';
4001: my ($aggtries,$totaltries);
4002: unless (exists($aggregates{$part})) {
4003: $totaltries = $record{'resource.'.$part.'.tries'};
4004: $aggtries = $totaltries;
4005: if ($$last_resets{$part}) {
4006: $aggtries = &get_num_tries(\%record,$$last_resets{$part},
4007: $part);
4008: }
4009: $result.='<input type="hidden" name="'.
4010: 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
4011: $result.='<input type="hidden" name="'.
4012: 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
4013: $aggregates{$part} = 1;
4014: }
4015: if ($type eq 'awarded') {
4016: my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
4017: $result.='<input type="hidden" name="'.
4018: 'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
4019: $result.='<input type="text" name="'.
4020: 'GD_'.$student.'_'.$part.'_awarded" '.
4021: 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
4022: '\')" value="'.$pts.'" size="4" /></td>'."\n";
4023: } elsif ($type eq 'solved') {
4024: my ($status,$foo)=split(/_/,$score,2);
4025: $status = 'nothing' if ($status eq '');
4026: $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
4027: $part.'_solved_s" value="'.$status.'" />'."\n";
4028: $result.=' <select name="'.
4029: 'GD_'.$student.'_'.$part.'_solved" '.
4030: 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
4031: $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>'
4032: : '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
4033: $result.='<option value="reset status">'.&mt('reset status').'</option>';
4034: $result.="</select> </td>\n";
4035: } else {
4036: $result.='<input type="hidden" name="'.
4037: 'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
4038: "\n";
4039: $result.='<input type="text" name="'.
4040: 'GD_'.$student.'_'.$part.'_'.$type.'" '.
4041: 'value="'.$score.'" size="4" /></td>'."\n";
4042: }
4043: }
4044: $result.=&Apache::loncommon::end_data_table_row();
4045: return $result;
4046: }
4047:
4048: #--- change scores for all the students in a section/class
4049: # record does not get update if unchanged
4050: sub editgrades {
4051: my ($request,$symb) = @_;
4052: my $toolsymb;
4053: if ($symb =~ /ext\.tool$/) {
4054: $toolsymb = $symb;
4055: }
4056:
4057: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
4058: my $title='<h2>'.&mt('Current Grade Status').'</h2>';
4059: $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
4060:
4061: my $result= &Apache::loncommon::start_data_table().
4062: &Apache::loncommon::start_data_table_header_row().
4063: '<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
4064: '<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
4065: my %scoreptr = (
4066: 'correct' =>'correct_by_override',
4067: 'incorrect'=>'incorrect_by_override',
4068: 'excused' =>'excused',
4069: 'ungraded' =>'ungraded_attempted',
4070: 'credited' =>'credit_attempted',
4071: 'nothing' => '',
4072: );
4073: my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
4074:
4075: my (@partid);
4076: my %weight = ();
4077: my %columns = ();
4078: my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
4079:
4080: my $partserror;
4081: my (@parts) = sort(&getpartlist($symb,\$partserror));
4082: if ($partserror) {
4083: return &navmap_errormsg();
4084: }
4085: my $header;
4086: while ($ctr < $env{'form.totalparts'}) {
4087: my $partid = $env{'form.partid_'.$ctr};
4088: push(@partid,$partid);
4089: $weight{$partid} = $env{'form.weight_'.$partid};
4090: $ctr++;
4091: }
4092: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
4093: my $totcolspan = 0;
4094: foreach my $partid (@partid) {
4095: $header .= '<th align="center">'.&mt('Old Score').'</th>'.
4096: '<th align="center">'.&mt('New Score').'</th>';
4097: $columns{$partid}=2;
4098: foreach my $stores (@parts) {
4099: my ($part,$type) = &split_part_type($stores);
4100: if ($part !~ m/^\Q$partid\E/) { next;}
4101: if ($type eq 'awarded' || $type eq 'solved') { next; }
4102: my $display=&Apache::lonnet::metadata($url,$stores.'.display',$toolsymb);
4103: $display =~ s/\[Part: \Q$part\E\]//;
4104: my $narrowtext = &mt('Tries');
4105: $display =~ s/Number of Attempts/$narrowtext/;
4106: $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
4107: '<th align="center">'.&mt('New').' '.$display.'</th>';
4108: $columns{$partid}+=2;
4109: }
4110: $totcolspan += $columns{$partid};
4111: }
4112: foreach my $partid (@partid) {
4113: my $display_part=&get_display_part($partid,$symb);
4114: $result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
4115: &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
4116: '</th>';
4117:
4118: }
4119: $result .= &Apache::loncommon::end_data_table_header_row().
4120: &Apache::loncommon::start_data_table_header_row().
4121: $header.
4122: &Apache::loncommon::end_data_table_header_row();
4123: my @noupdate;
4124: my ($updateCtr,$noupdateCtr) = (1,1);
4125: for ($i=0; $i<$env{'form.total'}; $i++) {
4126: my $user = $env{'form.ctr'.$i};
4127: my ($uname,$udom)=split(/:/,$user);
4128: my %newrecord;
4129: my $updateflag = 0;
4130: my $usec=$classlist->{"$uname:$udom"}[5];
4131: my $canmodify = &canmodify($usec);
4132: my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
4133: &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
4134: if (!$canmodify) {
4135: push(@noupdate,
4136: $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
4137: &mt('Not allowed to modify student')."</span></td>");
4138: next;
4139: }
4140: my %aggregate = ();
4141: my $aggregateflag = 0;
4142: $user=~s/:/_/; # colon doen't work in javascript for names
4143: foreach (@partid) {
4144: my $old_aw = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
4145: my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
4146: my $old_part = $old_aw eq '' ? '' : $old_part_pcr;
4147: my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
4148: my $awarded = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
4149: my $pcr = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
4150: my $partial = $awarded eq '' ? '' : $pcr;
4151: my $score;
4152: if ($partial eq '') {
4153: $score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
4154: } elsif ($partial > 0) {
4155: $score = 'correct_by_override';
4156: } elsif ($partial == 0) {
4157: $score = 'incorrect_by_override';
4158: }
4159: my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
4160: $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
4161:
4162: $newrecord{'resource.'.$_.'.regrader'}=
4163: "$env{'user.name'}:$env{'user.domain'}";
4164: if ($dropMenu eq 'reset status' &&
4165: $old_score ne '') { # ignore if no previous attempts => nothing to reset
4166: $newrecord{'resource.'.$_.'.tries'} = '';
4167: $newrecord{'resource.'.$_.'.solved'} = '';
4168: $newrecord{'resource.'.$_.'.award'} = '';
4169: $newrecord{'resource.'.$_.'.awarded'} = '';
4170: $updateflag = 1;
4171: if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
4172: my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
4173: my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
4174: my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
4175: &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
4176: $aggregateflag = 1;
4177: }
4178: } elsif (!($old_part eq $partial && $old_score eq $score)) {
4179: $updateflag = 1;
4180: $newrecord{'resource.'.$_.'.awarded'} = $partial if $partial ne '';
4181: $newrecord{'resource.'.$_.'.solved'} = $score;
4182: $rec_update++;
4183: }
4184:
4185: $line .= '<td align="center">'.$old_aw.' </td>'.
4186: '<td align="center">'.$awarded.
4187: ($score eq 'excused' ? $score : '').' </td>';
4188:
4189:
4190: my $partid=$_;
4191: foreach my $stores (@parts) {
4192: my ($part,$type) = &split_part_type($stores);
4193: if ($part !~ m/^\Q$partid\E/) { next;}
4194: if ($type eq 'awarded' || $type eq 'solved') { next; }
4195: my $old_aw = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
4196: my $awarded = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
4197: if ($awarded ne '' && $awarded ne $old_aw) {
4198: $newrecord{'resource.'.$part.'.'.$type}= $awarded;
4199: $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
4200: $updateflag=1;
4201: }
4202: $line .= '<td align="center">'.$old_aw.' </td>'.
4203: '<td align="center">'.$awarded.' </td>';
4204: }
4205: }
4206: $line.="\n";
4207:
4208: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4209: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4210:
4211: if ($updateflag) {
4212: $count++;
4213: &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
4214: $udom,$uname);
4215:
4216: if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
4217: $cnum,$udom,$uname)) {
4218: # need to figure out if should be in queue.
4219: my %record =
4220: &Apache::lonnet::restore($symb,$env{'request.course.id'},
4221: $udom,$uname);
4222: my $all_graded = 1;
4223: my $none_graded = 1;
4224: foreach my $part (@parts) {
4225: if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
4226: $all_graded = 0;
4227: } else {
4228: $none_graded = 0;
4229: }
4230: }
4231:
4232: if ($all_graded || $none_graded) {
4233: &Apache::bridgetask::remove_from_queue('gradingqueue',
4234: $symb,$cdom,$cnum,
4235: $udom,$uname);
4236: }
4237: }
4238:
4239: $result.=&Apache::loncommon::start_data_table_row().
4240: '<td align="right"> '.$updateCtr.' </td>'.$line.
4241: &Apache::loncommon::end_data_table_row();
4242: $updateCtr++;
4243: } else {
4244: push(@noupdate,
4245: '<td align="right"> '.$noupdateCtr.' </td>'.$line);
4246: $noupdateCtr++;
4247: }
4248: if ($aggregateflag) {
4249: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
4250: $cdom,$cnum);
4251: }
4252: }
4253: if (@noupdate) {
4254: my $numcols=$totcolspan+2;
4255: $result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
4256: '<td align="center" colspan="'.$numcols.'">'.
4257: &mt('No Changes Occurred For the Students Below').
4258: '</td>'.
4259: &Apache::loncommon::end_data_table_row();
4260: foreach my $line (@noupdate) {
4261: $result.=
4262: &Apache::loncommon::start_data_table_row().
4263: $line.
4264: &Apache::loncommon::end_data_table_row();
4265: }
4266: }
4267: $result .= &Apache::loncommon::end_data_table();
4268: my $msg = '<p><b>'.
4269: &mt('Number of records updated = [_1] for [quant,_2,student].',
4270: $rec_update,$count).'</b><br />'.
4271: '<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
4272: '</b></p>';
4273: return $title.$msg.$result;
4274: }
4275:
4276: sub split_part_type {
4277: my ($partstr) = @_;
4278: my ($temp,@allparts)=split(/_/,$partstr);
4279: my $type=pop(@allparts);
4280: my $part=join('_',@allparts);
4281: return ($part,$type);
4282: }
4283:
4284: #------------- end of section for handling grading by section/class ---------
4285: #
4286: #----------------------------------------------------------------------------
4287:
4288:
4289: #----------------------------------------------------------------------------
4290: #
4291: #-------------------------- Next few routines handles grading by csv upload
4292: #
4293: #--- Javascript to handle csv upload
4294: sub csvupload_javascript_reverse_associate {
4295: my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
4296: my $error2=&mt('You need to specify at least one grading field');
4297: &js_escape(\$error1);
4298: &js_escape(\$error2);
4299: return(<<ENDPICK);
4300: function verify(vf) {
4301: var foundsomething=0;
4302: var founduname=0;
4303: var foundID=0;
4304: var foundclicker=0;
4305: for (i=0;i<=vf.nfields.value;i++) {
4306: tw=eval('vf.f'+i+'.selectedIndex');
4307: if (i==0 && tw!=0) { foundID=1; }
4308: if (i==1 && tw!=0) { founduname=1; }
4309: if (i==2 && tw!=0) { foundclicker=1; }
4310: if (i!=0 && i!=1 && i!=2 && i!=3 && tw!=0) { foundsomething=1; }
4311: }
4312: if (founduname==0 && foundID==0 && foundclicker==0) {
4313: alert('$error1');
4314: return;
4315: }
4316: if (foundsomething==0) {
4317: alert('$error2');
4318: return;
4319: }
4320: vf.submit();
4321: }
4322: function flip(vf,tf) {
4323: var nw=eval('vf.f'+tf+'.selectedIndex');
4324: var i;
4325: for (i=0;i<=vf.nfields.value;i++) {
4326: //can not pick the same destination field for both name and domain
4327: if (((i ==0)||(i ==1)) &&
4328: ((tf==0)||(tf==1)) &&
4329: (i!=tf) &&
4330: (eval('vf.f'+i+'.selectedIndex')==nw)) {
4331: eval('vf.f'+i+'.selectedIndex=0;')
4332: }
4333: }
4334: }
4335: ENDPICK
4336: }
4337:
4338: sub csvupload_javascript_forward_associate {
4339: my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
4340: my $error2=&mt('You need to specify at least one grading field');
4341: &js_escape(\$error1);
4342: &js_escape(\$error2);
4343: return(<<ENDPICK);
4344: function verify(vf) {
4345: var foundsomething=0;
4346: var founduname=0;
4347: var foundID=0;
4348: var foundclicker=0;
4349: for (i=0;i<=vf.nfields.value;i++) {
4350: tw=eval('vf.f'+i+'.selectedIndex');
4351: if (tw==1) { foundID=1; }
4352: if (tw==2) { founduname=1; }
4353: if (tw==3) { foundclicker=1; }
4354: if (tw>4) { foundsomething=1; }
4355: }
4356: if (founduname==0 && foundID==0 && Æ’oundclicker==0) {
4357: alert('$error1');
4358: return;
4359: }
4360: if (foundsomething==0) {
4361: alert('$error2');
4362: return;
4363: }
4364: vf.submit();
4365: }
4366: function flip(vf,tf) {
4367: var nw=eval('vf.f'+tf+'.selectedIndex');
4368: var i;
4369: //can not pick the same destination field twice
4370: for (i=0;i<=vf.nfields.value;i++) {
4371: if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
4372: eval('vf.f'+i+'.selectedIndex=0;')
4373: }
4374: }
4375: }
4376: ENDPICK
4377: }
4378:
4379: sub csvuploadmap_header {
4380: my ($request,$symb,$datatoken,$distotal)= @_;
4381: my $javascript;
4382: if ($env{'form.upfile_associate'} eq 'reverse') {
4383: $javascript=&csvupload_javascript_reverse_associate();
4384: } else {
4385: $javascript=&csvupload_javascript_forward_associate();
4386: }
4387:
4388: $symb = &Apache::lonenc::check_encrypt($symb);
4389: $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
4390: &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
4391: &mt('Associate entries from the uploaded file with as many fields as you can.'));
4392: my $reverse=&mt("Reverse Association");
4393: $request->print(<<ENDPICK);
4394: <br />
4395: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
4396: <input type="hidden" name="associate" value="" />
4397: <input type="hidden" name="phase" value="three" />
4398: <input type="hidden" name="datatoken" value="$datatoken" />
4399: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
4400: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
4401: <input type="hidden" name="upfile_associate"
4402: value="$env{'form.upfile_associate'}" />
4403: <input type="hidden" name="symb" value="$symb" />
4404: <input type="hidden" name="command" value="csvuploadoptions" />
4405: <hr />
4406: ENDPICK
4407: $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
4408: return '';
4409:
4410: }
4411:
4412: sub csvupload_fields {
4413: my ($symb,$errorref) = @_;
4414: my $toolsymb;
4415: if ($symb =~ /ext\.tool$/) {
4416: $toolsymb = $symb;
4417: }
4418: my (@parts) = &getpartlist($symb,$errorref);
4419: if (ref($errorref)) {
4420: if ($$errorref) {
4421: return;
4422: }
4423: }
4424:
4425: my @fields=(['ID','Student/Employee ID'],
4426: ['username','Student Username'],
4427: ['clicker','Clicker ID'],
4428: ['domain','Student Domain']);
4429: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
4430: foreach my $part (sort(@parts)) {
4431: my @datum;
4432: my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
4433: my $name=$part;
4434: if (!$display) { $display = $name; }
4435: @datum=($name,$display);
4436: if ($name=~/^stores_(.*)_awarded/) {
4437: push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
4438: }
4439: push(@fields,\@datum);
4440: }
4441: return (@fields);
4442: }
4443:
4444: sub csvuploadmap_footer {
4445: my ($request,$i,$keyfields) =@_;
4446: my $buttontext = &mt('Assign Grades');
4447: $request->print(<<ENDPICK);
4448: </table>
4449: <input type="hidden" name="nfields" value="$i" />
4450: <input type="hidden" name="keyfields" value="$keyfields" />
4451: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
4452: </form>
4453: ENDPICK
4454: }
4455:
4456: sub checkforfile_js {
4457: my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
4458: &js_escape(\$alertmsg);
4459: my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
4460: function checkUpload(formname) {
4461: if (formname.upfile.value == "") {
4462: alert("$alertmsg");
4463: return false;
4464: }
4465: formname.submit();
4466: }
4467: CSVFORMJS
4468: return $result;
4469: }
4470:
4471: sub upcsvScores_form {
4472: my ($request,$symb) = @_;
4473: if (!$symb) {return '';}
4474: my $result=&checkforfile_js();
4475: $result.=&Apache::loncommon::start_data_table().
4476: &Apache::loncommon::start_data_table_header_row().
4477: '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
4478: &Apache::loncommon::end_data_table_header_row().
4479: &Apache::loncommon::start_data_table_row().'<td>';
4480: my $upload=&mt("Upload Scores");
4481: my $upfile_select=&Apache::loncommon::upfile_select_html();
4482: my $ignore=&mt('Ignore First Line');
4483: $symb = &Apache::lonenc::check_encrypt($symb);
4484: $result.=<<ENDUPFORM;
4485: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
4486: <input type="hidden" name="symb" value="$symb" />
4487: <input type="hidden" name="command" value="csvuploadmap" />
4488: $upfile_select
4489: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
4490: </form>
4491: ENDUPFORM
4492: $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
4493: &mt("How do I create a CSV file from a spreadsheet")).
4494: '</td>'.
4495: &Apache::loncommon::end_data_table_row().
4496: &Apache::loncommon::end_data_table();
4497: return $result;
4498: }
4499:
4500:
4501: sub csvuploadmap {
4502: my ($request,$symb)= @_;
4503: if (!$symb) {return '';}
4504:
4505: my $datatoken;
4506: if (!$env{'form.datatoken'}) {
4507: $datatoken=&Apache::loncommon::upfile_store($request);
4508: } else {
4509: $datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
4510: if ($datatoken ne '') {
4511: &Apache::loncommon::load_tmp_file($request,$datatoken);
4512: }
4513: }
4514: my @records=&Apache::loncommon::upfile_record_sep();
4515: &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
4516: my ($i,$keyfields);
4517: if (@records) {
4518: my $fieldserror;
4519: my @fields=&csvupload_fields($symb,\$fieldserror);
4520: if ($fieldserror) {
4521: $request->print(&navmap_errormsg());
4522: return;
4523: }
4524: if ($env{'form.upfile_associate'} eq 'reverse') {
4525: &Apache::loncommon::csv_print_samples($request,\@records);
4526: $i=&Apache::loncommon::csv_print_select_table($request,\@records,
4527: \@fields);
4528: foreach (@fields) { $keyfields.=$_->[0].','; }
4529: chop($keyfields);
4530: } else {
4531: unshift(@fields,['none','']);
4532: $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
4533: \@fields);
4534: foreach my $rec (@records) {
4535: my %temp = &Apache::loncommon::record_sep($rec);
4536: if (%temp) {
4537: $keyfields=join(',',sort(keys(%temp)));
4538: last;
4539: }
4540: }
4541: }
4542: }
4543: &csvuploadmap_footer($request,$i,$keyfields);
4544:
4545: return '';
4546: }
4547:
4548: sub csvuploadoptions {
4549: my ($request,$symb)= @_;
4550: my $overwrite=&mt('Overwrite any existing score');
4551: $request->print(<<ENDPICK);
4552: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
4553: <input type="hidden" name="command" value="csvuploadassign" />
4554: <p>
4555: <label>
4556: <input type="checkbox" name="overwite_scores" checked="checked" />
4557: $overwrite
4558: </label>
4559: </p>
4560: ENDPICK
4561: my %fields=&get_fields();
4562: if (!defined($fields{'domain'})) {
4563: my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
4564: $request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
4565: }
4566: foreach my $key (sort(keys(%env))) {
4567: if ($key !~ /^form\.(.*)$/) { next; }
4568: my $cleankey=$1;
4569: if ($cleankey eq 'command') { next; }
4570: $request->print('<input type="hidden" name="'.$cleankey.
4571: '" value="'.$env{$key}.'" />'."\n");
4572: }
4573: # FIXME do a check for any duplicated user ids...
4574: # FIXME do a check for any invalid user ids?...
4575: $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
4576: <hr /></form>'."\n");
4577: return '';
4578: }
4579:
4580: sub get_fields {
4581: my %fields;
4582: my @keyfields = split(/\,/,$env{'form.keyfields'});
4583: for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
4584: if ($env{'form.upfile_associate'} eq 'reverse') {
4585: if ($env{'form.f'.$i} ne 'none') {
4586: $fields{$keyfields[$i]}=$env{'form.f'.$i};
4587: }
4588: } else {
4589: if ($env{'form.f'.$i} ne 'none') {
4590: $fields{$env{'form.f'.$i}}=$keyfields[$i];
4591: }
4592: }
4593: }
4594: return %fields;
4595: }
4596:
4597: sub csvuploadassign {
4598: my ($request,$symb)= @_;
4599: if (!$symb) {return '';}
4600: my $error_msg = '';
4601: my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
4602: if ($datatoken ne '') {
4603: &Apache::loncommon::load_tmp_file($request,$datatoken);
4604: }
4605: my @gradedata = &Apache::loncommon::upfile_record_sep();
4606: my %fields=&get_fields();
4607: my $courseid=$env{'request.course.id'};
4608: my ($classlist) = &getclasslist('all',0);
4609: my @notallowed;
4610: my @skipped;
4611: my @warnings;
4612: my $countdone=0;
4613: foreach my $grade (@gradedata) {
4614: my %entries=&Apache::loncommon::record_sep($grade);
4615: my $domain;
4616: if ($entries{$fields{'domain'}}) {
4617: $domain=$entries{$fields{'domain'}};
4618: } else {
4619: $domain=$env{'form.default_domain'};
4620: }
4621: $domain=~s/\s//g;
4622: my $username=$entries{$fields{'username'}};
4623: $username=~s/\s//g;
4624: if (!$username) {
4625: my $id=$entries{$fields{'ID'}};
4626: $id=~s/\s//g;
4627: if ($id ne '') {
4628: my %ids=&Apache::lonnet::idget($domain,[$id]);
4629: $username=$ids{$id};
4630: } else {
4631: if ($entries{$fields{'clicker'}}) {
4632: my $clicker = $entries{$fields{'clicker'}};
4633: $clicker=~s/\s//g;
4634: if ($clicker ne '') {
4635: my %clickers = &Apache::lonnet::idget($domain,[$clicker],'clickers');
4636: if ($clickers{$clicker} ne '') {
4637: my $match = 0;
4638: my @inclass;
4639: foreach my $poss (split(/,/,$clickers{$clicker})) {
4640: if (exists($$classlist{"$poss:$domain"})) {
4641: $username = $poss;
4642: push(@inclass,$poss);
4643: $match ++;
4644:
4645: }
4646: }
4647: if ($match > 1) {
4648: undef($username);
4649: $request->print('<p class="LC_warning">'.
4650: &mt('Score not saved for clicker: [_1] (matched multiple usernames: [_2])',
4651: $clicker,join(', ',@inclass)).'</p>');
4652: }
4653: }
4654: }
4655: }
4656: }
4657: }
4658: if (!exists($$classlist{"$username:$domain"})) {
4659: my $id=$entries{$fields{'ID'}};
4660: $id=~s/\s//g;
4661: my $clicker = $entries{$fields{'clicker'}};
4662: $clicker=~s/\s//g;
4663: if ($clicker) {
4664: push(@skipped,"$clicker:$domain");
4665: } elsif ($id) {
4666: push(@skipped,"$id:$domain");
4667: } else {
4668: push(@skipped,"$username:$domain");
4669: }
4670: next;
4671: }
4672: my $usec=$classlist->{"$username:$domain"}[5];
4673: if (!&canmodify($usec)) {
4674: push(@notallowed,"$username:$domain");
4675: next;
4676: }
4677: my %points;
4678: my %grades;
4679: foreach my $dest (keys(%fields)) {
4680: if ($dest eq 'ID' || $dest eq 'username' ||
4681: $dest eq 'domain') { next; }
4682: if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
4683: if ($dest=~/stores_(.*)_points/) {
4684: my $part=$1;
4685: my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
4686: $symb,$domain,$username);
4687: if ($wgt) {
4688: $entries{$fields{$dest}}=~s/\s//g;
4689: my $pcr=$entries{$fields{$dest}} / $wgt;
4690: my $award=($pcr == 0) ? 'incorrect_by_override'
4691: : 'correct_by_override';
4692: if ($pcr>1) {
4693: push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
4694: }
4695: $grades{"resource.$part.awarded"}=$pcr;
4696: $grades{"resource.$part.solved"}=$award;
4697: $points{$part}=1;
4698: } else {
4699: $error_msg = "<br />" .
4700: &mt("Some point values were assigned"
4701: ." for problems with a weight "
4702: ."of zero. These values were "
4703: ."ignored.");
4704: }
4705: } else {
4706: if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
4707: if ($dest=~/stores_(.*)_solved/) { if ($points{$1}) {next;} }
4708: my $store_key=$dest;
4709: $store_key=~s/^stores/resource/;
4710: $store_key=~s/_/\./g;
4711: $grades{$store_key}=$entries{$fields{$dest}};
4712: }
4713: }
4714: if (! %grades) {
4715: push(@skipped,&mt("[_1]: no data to save","$username:$domain"));
4716: } else {
4717: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
4718: my $result=&Apache::lonnet::cstore(\%grades,$symb,
4719: $env{'request.course.id'},
4720: $domain,$username);
4721: if ($result eq 'ok') {
4722: # Successfully stored
4723: $request->print('.');
4724: # Remove from grading queue
4725: &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
4726: $env{'course.'.$env{'request.course.id'}.'.domain'},
4727: $env{'course.'.$env{'request.course.id'}.'.num'},
4728: $domain,$username);
4729: $countdone++;
4730: } else {
4731: $request->print("<p><span class=\"LC_error\">".
4732: &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
4733: "$username:$domain",$result)."</span></p>");
4734: }
4735: $request->rflush();
4736: }
4737: }
4738: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
4739: if (@warnings) {
4740: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
4741: $request->print(join(', ',@warnings));
4742: }
4743: if (@skipped) {
4744: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
4745: $request->print(join(', ',@skipped));
4746: }
4747: if (@notallowed) {
4748: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
4749: $request->print(join(', ',@notallowed));
4750: }
4751: $request->print("<br />\n");
4752: return $error_msg;
4753: }
4754: #------------- end of section for handling csv file upload ---------
4755: #
4756: #-------------------------------------------------------------------
4757: #
4758: #-------------- Next few routines handle grading by page/sequence
4759: #
4760: #--- Select a page/sequence and a student to grade
4761: sub pickStudentPage {
4762: my ($request,$symb) = @_;
4763:
4764: my $alertmsg = &mt('Please select the student you wish to grade.');
4765: &js_escape(\$alertmsg);
4766: $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
4767:
4768: function checkPickOne(formname) {
4769: if (radioSelection(formname.student) == null) {
4770: alert("$alertmsg");
4771: return;
4772: }
4773: ptr = pullDownSelection(formname.selectpage);
4774: formname.page.value = formname["page"+ptr].value;
4775: formname.title.value = formname["title"+ptr].value;
4776: formname.submit();
4777: }
4778:
4779: LISTJAVASCRIPT
4780: &commonJSfunctions($request);
4781:
4782: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4783: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4784: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4785:
4786: my $result='<h3><span class="LC_info"> '.
4787: &mt('Manual Grading by Page or Sequence').'</span></h3>';
4788:
4789: $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
4790: my $map_error;
4791: my ($titles,$symbx) = &getSymbMap($map_error);
4792: if ($map_error) {
4793: $request->print(&navmap_errormsg());
4794: return;
4795: }
4796: my ($curpage) =&Apache::lonnet::decode_symb($symb);
4797: # my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb);
4798: # my $type=($curpage =~ /\.(page|sequence)/);
4799:
4800: # Collection of hidden fields
4801: my $ctr=0;
4802: foreach (@$titles) {
4803: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4804: $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
4805: $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
4806: $ctr++;
4807: }
4808: $result.='<input type="hidden" name="page" />'."\n".
4809: '<input type="hidden" name="title" />'."\n";
4810:
4811: $result.=&build_section_inputs();
4812: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
4813: $result.='<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
4814: '<input type="hidden" name="command" value="displayPage" />'."\n".
4815: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
4816:
4817: # Show grading options
4818: $result.=&Apache::lonhtmlcommon::start_pick_box();
4819: my $select = '<select name="selectpage">'."\n";
4820: $ctr=0;
4821: foreach (@$titles) {
4822: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4823: $select.='<option value="'.$ctr.'"'.
4824: ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
4825: '>'.$showtitle.'</option>'."\n";
4826: $ctr++;
4827: }
4828: $select.= '</select>';
4829:
4830: $result.=
4831: &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
4832: .$select
4833: .&Apache::lonhtmlcommon::row_closure();
4834:
4835: $result.=
4836: &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
4837: .'<label><input type="radio" name="vProb" value="no"'
4838: .' checked="checked" /> '.&mt('no').' </label>'."\n"
4839: .'<label><input type="radio" name="vProb" value="yes" />'
4840: .&mt('yes').'</label>'."\n"
4841: .&Apache::lonhtmlcommon::row_closure();
4842:
4843: $result.=
4844: &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
4845: .'<label><input type="radio" name="lastSub" value="none" /> '
4846: .&mt('none').' </label>'."\n"
4847: .'<label><input type="radio" name="lastSub" value="datesub"'
4848: .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
4849: .'<label><input type="radio" name="lastSub" value="all" /> '
4850: .&mt('all submissions with details').' </label>'
4851: .&Apache::lonhtmlcommon::row_closure();
4852:
4853: $result.=
4854: &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
4855: .'<input type="text" name="CODE" value="" />'
4856: .&Apache::lonhtmlcommon::row_closure(1)
4857: .&Apache::lonhtmlcommon::end_pick_box();
4858:
4859: # Show list of students to select for grading
4860: $result.='<br /><input type="button" '.
4861: 'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' →" /><br />'."\n";
4862:
4863: $request->print($result);
4864:
4865: my $studentTable.=' <b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
4866: &Apache::loncommon::start_data_table().
4867: &Apache::loncommon::start_data_table_header_row().
4868: '<th align="right"> '.&mt('No.').'</th>'.
4869: '<th>'.&nameUserString('header').'</th>'.
4870: '<th align="right"> '.&mt('No.').'</th>'.
4871: '<th>'.&nameUserString('header').'</th>'.
4872: &Apache::loncommon::end_data_table_header_row();
4873:
4874: my (undef,undef,$fullname) = &getclasslist($getsec,'1');
4875: my $ptr = 1;
4876: foreach my $student (sort
4877: {
4878: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
4879: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
4880: }
4881: return $a cmp $b;
4882: } (keys(%$fullname))) {
4883: my ($uname,$udom) = split(/:/,$student);
4884: $studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
4885: : '</td>');
4886: $studentTable.='<td align="right">'.$ptr.' </td>';
4887: $studentTable.='<td> <label><input type="radio" name="student" value="'.$student.'" /> '
4888: .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
4889: $studentTable.=
4890: ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row()
4891: : '');
4892: $ptr++;
4893: }
4894: if ($ptr%2 == 0) {
4895: $studentTable.='</td><td> </td><td> </td>'.
4896: &Apache::loncommon::end_data_table_row();
4897: }
4898: $studentTable.=&Apache::loncommon::end_data_table()."\n";
4899: $studentTable.='<input type="button" '.
4900: 'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' →" /></form>'."\n";
4901:
4902: $request->print($studentTable);
4903:
4904: return '';
4905: }
4906:
4907: sub getSymbMap {
4908: my ($map_error) = @_;
4909: my $navmap = Apache::lonnavmaps::navmap->new();
4910: unless (ref($navmap)) {
4911: if (ref($map_error)) {
4912: $$map_error = 'navmap';
4913: }
4914: return;
4915: }
4916: my %symbx = ();
4917: my @titles = ();
4918: my $minder = 0;
4919:
4920: # Gather every sequence that has problems.
4921: my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
4922: 1,0,1);
4923: for my $sequence ($navmap->getById('0.0'), @sequences) {
4924: if ($navmap->hasResource($sequence, sub { shift->is_gradable(); }, 0) ) {
4925: my $title = $minder.'.'.
4926: &HTML::Entities::encode($sequence->compTitle(),'"\'&');
4927: push(@titles, $title); # minder in case two titles are identical
4928: $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
4929: $minder++;
4930: }
4931: }
4932: return \@titles,\%symbx;
4933: }
4934:
4935: #
4936: #--- Displays a page/sequence w/wo problems, w/wo submissions
4937: sub displayPage {
4938: my ($request,$symb) = @_;
4939: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4940: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4941: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4942: my $pageTitle = $env{'form.page'};
4943: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
4944: my ($uname,$udom) = split(/:/,$env{'form.student'});
4945: my $usec=$classlist->{$env{'form.student'}}[5];
4946:
4947: #need to make sure we have the correct data for later EXT calls,
4948: #thus invalidate the cache
4949: &Apache::lonnet::devalidatecourseresdata(
4950: $env{'course.'.$env{'request.course.id'}.'.num'},
4951: $env{'course.'.$env{'request.course.id'}.'.domain'});
4952: &Apache::lonnet::clear_EXT_cache_status();
4953:
4954: if (!&canview($usec)) {
4955: $request->print(
4956: '<span class="LC_warning">'.
4957: &mt('Unable to view requested student. ([_1])',
4958: $env{'form.student'}).
4959: '</span>');
4960: return;
4961: }
4962: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
4963: $result.='<h3> '.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
4964: '</h3>'."\n";
4965: $env{'form.CODE'} = uc($env{'form.CODE'});
4966: if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
4967: $result.='<h3> '.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
4968: } else {
4969: delete($env{'form.CODE'});
4970: }
4971: &sub_page_js($request);
4972: $request->print($result);
4973:
4974: my $navmap = Apache::lonnavmaps::navmap->new();
4975: unless (ref($navmap)) {
4976: $request->print(&navmap_errormsg());
4977: return;
4978: }
4979: my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
4980: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
4981: if (!$map) {
4982: $request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
4983: return;
4984: }
4985: my $iterator = $navmap->getIterator($map->map_start(),
4986: $map->map_finish());
4987:
4988: my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
4989: '<input type="hidden" name="command" value="gradeByPage" />'."\n".
4990: '<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
4991: '<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
4992: '<input type="hidden" name="page" value="'.$pageTitle.'" />'."\n".
4993: '<input type="hidden" name="title" value="'.$env{'form.title'}.'" />'."\n".
4994: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
4995: '<input type="hidden" name="overRideScore" value="no" />'."\n";
4996:
4997: if (defined($env{'form.CODE'})) {
4998: $studentTable.=
4999: '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
5000: }
5001: my $checkIcon = '<img alt="'.&mt('Check Mark').
5002: '" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
5003:
5004: $studentTable.=' <span class="LC_info">'.
5005: &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
5006: '</span>'."\n".
5007: &Apache::loncommon::start_data_table().
5008: &Apache::loncommon::start_data_table_header_row().
5009: '<th>'.&mt('Prob.').'</th>'.
5010: '<th> '.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
5011: &Apache::loncommon::end_data_table_header_row();
5012:
5013: &Apache::lonxml::clear_problem_counter();
5014: my ($depth,$question,$prob) = (1,1,1);
5015: $iterator->next(); # skip the first BEGIN_MAP
5016: my $curRes = $iterator->next(); # for "current resource"
5017: while ($depth > 0) {
5018: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
5019: if($curRes == $iterator->END_MAP) { $depth--; }
5020:
5021: if (ref($curRes) && $curRes->is_gradable()) {
5022: my $parts = $curRes->parts();
5023: my $title = $curRes->compTitle();
5024: my $symbx = $curRes->symb();
5025: my $is_tool = ($symbx =~ /ext\.tool$/);
5026: $studentTable.=
5027: &Apache::loncommon::start_data_table_row().
5028: '<td align="center" valign="top" >'.$prob.
5029: (scalar(@{$parts}) == 1 ? ''
5030: : '<br />('.&mt('[_1]parts',
5031: scalar(@{$parts}).' ').')'
5032: ).
5033: '</td>';
5034: $studentTable.='<td valign="top">';
5035: my %form = ('CODE' => $env{'form.CODE'},);
5036: unless ($is_tool) {
5037: if ($env{'form.vProb'} eq 'yes' ) {
5038: $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
5039: undef,'both',\%form);
5040: } else {
5041: my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
5042: $companswer =~ s|<form(.*?)>||g;
5043: $companswer =~ s|</form>||g;
5044: # while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
5045: # $companswer =~ s/$1/ /ms;
5046: # $request->print('match='.$1."<br />\n");
5047: # }
5048: # $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
5049: $studentTable.=' <b>'.$title.'</b> <br /> <b>'.&mt('Correct answer').':</b><br />'.$companswer;
5050: }
5051: }
5052:
5053: my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
5054:
5055: if ($env{'form.lastSub'} eq 'datesub') {
5056: if ($record{'version'} eq '') {
5057: my $msg = &mt('No recorded submission for this problem.');
5058: if ($is_tool) {
5059: $msg = &mt('No recorded transactions for this external tool');
5060: }
5061: $studentTable.='<br /> <span class="LC_warning">'.$msg.'</span><br />';
5062: } else {
5063: my %responseType = ();
5064: foreach my $partid (@{$parts}) {
5065: my @responseIds =$curRes->responseIds($partid);
5066: my @responseType =$curRes->responseType($partid);
5067: my %responseIds;
5068: for (my $i=0;$i<=$#responseIds;$i++) {
5069: $responseIds{$responseIds[$i]}=$responseType[$i];
5070: }
5071: $responseType{$partid} = \%responseIds;
5072: }
5073: $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
5074: }
5075: } elsif ($env{'form.lastSub'} eq 'all') {
5076: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
5077: my $identifier = (&canmodify($usec)? $prob : '');
5078: $studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
5079: $env{'request.course.id'},
5080: '','.submission',undef,
5081: $usec,$identifier);
5082:
5083: }
5084: if (&canmodify($usec)) {
5085: $studentTable.=&gradeBox_start();
5086: foreach my $partid (@{$parts}) {
5087: $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
5088: $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
5089: $question++;
5090: }
5091: $studentTable.=&gradeBox_end();
5092: $prob++;
5093: }
5094: $studentTable.='</td></tr>';
5095:
5096: }
5097: $curRes = $iterator->next();
5098: }
5099:
5100: $studentTable.=
5101: '</table>'."\n".
5102: '<input type="button" value="'.&mt('Save').'" '.
5103: 'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
5104: '</form>'."\n";
5105: $request->print($studentTable);
5106:
5107: return '';
5108: }
5109:
5110: sub displaySubByDates {
5111: my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
5112: my $isCODE=0;
5113: my $isTask = ($symb =~/\.task$/);
5114: my $is_tool = ($symb =~/\.tool$/);
5115: if (exists($record->{'resource.CODE'})) { $isCODE=1; }
5116: my $studentTable=&Apache::loncommon::start_data_table().
5117: &Apache::loncommon::start_data_table_header_row().
5118: '<th>'.&mt('Date/Time').'</th>'.
5119: ($isCODE?'<th>'.&mt('CODE').'</th>':'').
5120: ($isTask?'<th>'.&mt('Version').'</th>':'').
5121: '<th>'.&mt('Submission').'</th>'.
5122: '<th>'.&mt('Status').'</th>'.
5123: &Apache::loncommon::end_data_table_header_row();
5124: my ($version);
5125: my %mark;
5126: my %orders;
5127: $mark{'correct_by_student'} = $checkIcon;
5128: if (!exists($$record{'1:timestamp'})) {
5129: if ($is_tool) {
5130: return '<br /> <span class="LC_warning">'.&mt('No grade passed back.').'</span><br />';
5131: } else {
5132: return '<br /> <span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
5133: }
5134: }
5135:
5136: my $interaction;
5137: my $no_increment = 1;
5138: my (%lastrndseed,%lasttype);
5139: for ($version=1;$version<=$$record{'version'};$version++) {
5140: my $timestamp =
5141: &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
5142: if (exists($$record{$version.':resource.0.version'})) {
5143: $interaction = $$record{$version.':resource.0.version'};
5144: }
5145: if ($isTask && $env{'form.previousversion'}) {
5146: next unless ($interaction == $env{'form.previousversion'});
5147: }
5148: my $where = ($isTask ? "$version:resource.$interaction"
5149: : "$version:resource");
5150: $studentTable.=&Apache::loncommon::start_data_table_row().
5151: '<td>'.$timestamp.'</td>';
5152: if ($isCODE) {
5153: $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
5154: }
5155: if ($isTask) {
5156: $studentTable.='<td>'.$interaction.'</td>';
5157: }
5158: my @versionKeys = split(/\:/,$$record{$version.':keys'});
5159: my @displaySub = ();
5160: foreach my $partid (@{$parts}) {
5161: my ($hidden,$type);
5162: $type = $$record{$version.':resource.'.$partid.'.type'};
5163: if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
5164: $hidden = 1;
5165: }
5166: my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
5167: : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
5168:
5169: # next if ($$record{"$version:resource.$partid.solved"} eq '');
5170: my $display_part=&get_display_part($partid,$symb);
5171: foreach my $matchKey (@matchKey) {
5172: if (exists($$record{$version.':'.$matchKey}) &&
5173: $$record{$version.':'.$matchKey} ne '') {
5174:
5175: my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
5176: : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
5177: $displaySub[0].='<span class="LC_nobreak">';
5178: $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
5179: .' <span class="LC_internal_info">'
5180: .'('.&mt('Response ID: [_1]',$responseId).')'
5181: .'</span>'
5182: .' <b>';
5183: if ($hidden) {
5184: $displaySub[0].= &mt('Anonymous Survey').'</b>';
5185: } else {
5186: my ($trial,$rndseed,$newvariation);
5187: if ($type eq 'randomizetry') {
5188: $trial = $$record{"$where.$partid.tries"};
5189: $rndseed = $$record{"$where.$partid.rndseed"};
5190: }
5191: if ($$record{"$where.$partid.tries"} eq '') {
5192: $displaySub[0].=&mt('Trial not counted');
5193: } else {
5194: $displaySub[0].=&mt('Trial: [_1]',
5195: $$record{"$where.$partid.tries"});
5196: if (($rndseed ne '') && ($lastrndseed{$partid} ne '')) {
5197: if (($rndseed ne $lastrndseed{$partid}) &&
5198: (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
5199: $newvariation = ' ('.&mt('New variation this try').')';
5200: }
5201: }
5202: $lastrndseed{$partid} = $rndseed;
5203: $lasttype{$partid} = $type;
5204: }
5205: my $responseType=($isTask ? 'Task'
5206: : $responseType->{$partid}->{$responseId});
5207: if (!exists($orders{$partid})) { $orders{$partid}={}; }
5208: if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
5209: $orders{$partid}->{$responseId}=
5210: &get_order($partid,$responseId,$symb,$uname,$udom,
5211: $no_increment,$type,$trial,$rndseed);
5212: }
5213: $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
5214: $displaySub[0].=' '.
5215: &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
5216: }
5217: }
5218: }
5219: if (exists($$record{"$where.$partid.checkedin"})) {
5220: $displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
5221: $$record{"$where.$partid.checkedin"},
5222: $$record{"$where.$partid.checkedin.slot"}).
5223: '<br />';
5224: }
5225: if (exists $$record{"$where.$partid.award"}) {
5226: $displaySub[1].='<b>'.&mt('Part:').'</b> '.$display_part.' '.
5227: lc($$record{"$where.$partid.award"}).' '.
5228: $mark{$$record{"$where.$partid.solved"}}.
5229: '<br />';
5230: }
5231: if (exists $$record{"$where.$partid.regrader"}) {
5232: $displaySub[2].=$$record{"$where.$partid.regrader"}.
5233: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
5234: } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
5235: $displaySub[2].=
5236: $$record{"$version:resource.$partid.regrader"}.
5237: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
5238: }
5239: }
5240: # needed because old essay regrader has not parts info
5241: if (exists $$record{"$version:resource.regrader"}) {
5242: $displaySub[2].=$$record{"$version:resource.regrader"};
5243: }
5244: $studentTable.='<td>'.$displaySub[0].' </td><td>'.$displaySub[1];
5245: if ($displaySub[2]) {
5246: $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
5247: }
5248: $studentTable.=' </td>'.
5249: &Apache::loncommon::end_data_table_row();
5250: }
5251: $studentTable.=&Apache::loncommon::end_data_table();
5252: return $studentTable;
5253: }
5254:
5255: sub updateGradeByPage {
5256: my ($request,$symb) = @_;
5257:
5258: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
5259: my $cnum = $env{"course.$env{'request.course.id'}.num"};
5260: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
5261: my $pageTitle = $env{'form.page'};
5262: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
5263: my ($uname,$udom) = split(/:/,$env{'form.student'});
5264: my $usec=$classlist->{$env{'form.student'}}[5];
5265: if (!&canmodify($usec)) {
5266: $request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
5267: return;
5268: }
5269: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
5270: $result.='<h3> '.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
5271: '</h3>'."\n";
5272:
5273: $request->print($result);
5274:
5275:
5276: my $navmap = Apache::lonnavmaps::navmap->new();
5277: unless (ref($navmap)) {
5278: $request->print(&navmap_errormsg());
5279: return;
5280: }
5281: my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
5282: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
5283: if (!$map) {
5284: $request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
5285: return;
5286: }
5287: my $iterator = $navmap->getIterator($map->map_start(),
5288: $map->map_finish());
5289:
5290: my $studentTable=
5291: &Apache::loncommon::start_data_table().
5292: &Apache::loncommon::start_data_table_header_row().
5293: '<th align="center"> '.&mt('Prob.').' </th>'.
5294: '<th> '.&mt('Title').' </th>'.
5295: '<th> '.&mt('Previous Score').' </th>'.
5296: '<th> '.&mt('New Score').' </th>'.
5297: &Apache::loncommon::end_data_table_header_row();
5298:
5299: $iterator->next(); # skip the first BEGIN_MAP
5300: my $curRes = $iterator->next(); # for "current resource"
5301: my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
5302: while ($depth > 0) {
5303: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
5304: if($curRes == $iterator->END_MAP) { $depth--; }
5305:
5306: if (ref($curRes) && $curRes->is_problem()) {
5307: my $parts = $curRes->parts();
5308: my $title = $curRes->compTitle();
5309: my $symbx = $curRes->symb();
5310: $studentTable.=
5311: &Apache::loncommon::start_data_table_row().
5312: '<td align="center" valign="top" >'.$prob.
5313: (scalar(@{$parts}) == 1 ? ''
5314: : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
5315: .')').'</td>';
5316: $studentTable.='<td valign="top"> <b>'.$title.'</b> </td>';
5317:
5318: my %newrecord=();
5319: my @displayPts=();
5320: my %aggregate = ();
5321: my $aggregateflag = 0;
5322: if ($env{'form.HIDE'.$prob}) {
5323: my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
5324: my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
5325: my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
5326: $hideflag += $numchgs;
5327: }
5328: foreach my $partid (@{$parts}) {
5329: my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
5330: my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
5331:
5332: my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ?
5333: $env{'form.WGT'.$question.'_'.$partid} : 1;
5334: my $partial = $newpts/$wgt;
5335: my $score;
5336: if ($partial > 0) {
5337: $score = 'correct_by_override';
5338: } elsif ($newpts ne '') { #empty is taken as 0
5339: $score = 'incorrect_by_override';
5340: }
5341: my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
5342: if ($dropMenu eq 'excused') {
5343: $partial = '';
5344: $score = 'excused';
5345: } elsif ($dropMenu eq 'reset status'
5346: && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
5347: $newrecord{'resource.'.$partid.'.tries'} = 0;
5348: $newrecord{'resource.'.$partid.'.solved'} = '';
5349: $newrecord{'resource.'.$partid.'.award'} = '';
5350: $newrecord{'resource.'.$partid.'.awarded'} = 0;
5351: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
5352: $changeflag++;
5353: $newpts = '';
5354:
5355: my $aggtries = $env{'form.aggtries'.$question.'_'.$partid};
5356: my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
5357: my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
5358: if ($aggtries > 0) {
5359: &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
5360: $aggregateflag = 1;
5361: }
5362: }
5363: my $display_part=&get_display_part($partid,$curRes->symb());
5364: my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
5365: $displayPts[0].=' <b>'.&mt('Part').':</b> '.$display_part.' = '.
5366: (($oldstatus eq 'excused') ? 'excused' : $oldpts).
5367: ' <br />';
5368: $displayPts[1].=' <b>'.&mt('Part').':</b> '.$display_part.' = '.
5369: (($score eq 'excused') ? 'excused' : $newpts).
5370: ' <br />';
5371: $question++;
5372: next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
5373:
5374: $newrecord{'resource.'.$partid.'.awarded'} = $partial if $partial ne '';
5375: $newrecord{'resource.'.$partid.'.solved'} = $score if $score ne '';
5376: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
5377: if (scalar(keys(%newrecord)) > 0);
5378:
5379: $changeflag++;
5380: }
5381: if (scalar(keys(%newrecord)) > 0) {
5382: my %record =
5383: &Apache::lonnet::restore($symbx,$env{'request.course.id'},
5384: $udom,$uname);
5385:
5386: if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
5387: $newrecord{'resource.CODE'} = $env{'form.CODE'};
5388: } elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
5389: $newrecord{'resource.CODE'} = '';
5390: }
5391: &Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
5392: $udom,$uname);
5393: %record = &Apache::lonnet::restore($symbx,
5394: $env{'request.course.id'},
5395: $udom,$uname);
5396: &check_and_remove_from_queue($parts,\%record,undef,$symbx,
5397: $cdom,$cnum,$udom,$uname);
5398: }
5399:
5400: if ($aggregateflag) {
5401: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
5402: $env{'course.'.$env{'request.course.id'}.'.domain'},
5403: $env{'course.'.$env{'request.course.id'}.'.num'});
5404: }
5405:
5406: $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
5407: '<td valign="top">'.$displayPts[1].'</td>'.
5408: &Apache::loncommon::end_data_table_row();
5409:
5410: $prob++;
5411: }
5412: $curRes = $iterator->next();
5413: }
5414:
5415: $studentTable.=&Apache::loncommon::end_data_table();
5416: my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
5417: &mt('The scores were changed for [quant,_1,problem].',
5418: $changeflag).'<br />');
5419: my $hidemsg=($hideflag == 0 ? '' :
5420: &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
5421: $hideflag).'<br />');
5422: $request->print($hidemsg.$grademsg.$studentTable);
5423:
5424: return '';
5425: }
5426:
5427: #-------- end of section for handling grading by page/sequence ---------
5428: #
5429: #-------------------------------------------------------------------
5430:
5431: #-------------------- Bubblesheet (Scantron) Grading -------------------
5432: #
5433: #------ start of section for handling grading by page/sequence ---------
5434:
5435: =pod
5436:
5437: =head1 Bubble sheet grading routines
5438:
5439: For this documentation:
5440:
5441: 'scanline' refers to the full line of characters
5442: from the file that we are parsing that represents one entire sheet
5443:
5444: 'bubble line' refers to the data
5445: representing the line of bubbles that are on the physical bubblesheet
5446:
5447:
5448: The overall process is that a scanned in bubblesheet data is uploaded
5449: into a course. When a user wants to grade, they select a
5450: sequence/folder of resources, a file of bubblesheet info, and pick
5451: one of the predefined configurations for what each scanline looks
5452: like.
5453:
5454: Next each scanline is checked for any errors of either 'missing
5455: bubbles' (it's an error because it may have been mis-scanned
5456: because too light bubbling), 'double bubble' (each bubble line should
5457: have no more than one letter picked), invalid or duplicated CODE,
5458: invalid student/employee ID
5459:
5460: If the CODE option is used that determines the randomization of the
5461: homework problems, either way the student/employee ID is looked up into a
5462: username:domain.
5463:
5464: During the validation phase the instructor can choose to skip scanlines.
5465:
5466: After the validation phase, there are now 3 bubblesheet files
5467:
5468: scantron_original_filename (unmodified original file)
5469: scantron_corrected_filename (file where the corrected information has replaced the original information)
5470: scantron_skipped_filename (contains the exact text of scanlines that where skipped)
5471:
5472: Also there is a separate hash nohist_scantrondata that contains extra
5473: correction information that isn't representable in the bubblesheet
5474: file (see &scantron_getfile() for more information)
5475:
5476: After all scanlines are either valid, marked as valid or skipped, then
5477: foreach line foreach problem in the picked sequence, an ssi request is
5478: made that simulates a user submitting their selected letter(s) against
5479: the homework problem.
5480:
5481: =over 4
5482:
5483:
5484:
5485: =item defaultFormData
5486:
5487: Returns html hidden inputs used to hold context/default values.
5488:
5489: Arguments:
5490: $symb - $symb of the current resource
5491:
5492: =cut
5493:
5494: sub defaultFormData {
5495: my ($symb)=@_;
5496: return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
5497: }
5498:
5499:
5500: =pod
5501:
5502: =item getSequenceDropDown
5503:
5504: Return html dropdown of possible sequences to grade
5505:
5506: Arguments:
5507: $symb - $symb of the current resource
5508: $map_error - ref to scalar which will container error if
5509: $navmap object is unavailable in &getSymbMap().
5510:
5511: =cut
5512:
5513: sub getSequenceDropDown {
5514: my ($symb,$map_error)=@_;
5515: my $result='<select name="selectpage">'."\n";
5516: my ($titles,$symbx) = &getSymbMap($map_error);
5517: if (ref($map_error)) {
5518: return if ($$map_error);
5519: }
5520: my ($curpage)=&Apache::lonnet::decode_symb($symb);
5521: my $ctr=0;
5522: foreach (@$titles) {
5523: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
5524: $result.='<option value="'.$$symbx{$_}.'" '.
5525: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
5526: '>'.$showtitle.'</option>'."\n";
5527: $ctr++;
5528: }
5529: $result.= '</select>';
5530: return $result;
5531: }
5532:
5533: my %bubble_lines_per_response; # no. bubble lines for each response.
5534: # key is zero-based index - 0, 1, 2 ...
5535:
5536: my %first_bubble_line; # First bubble line no. for each bubble.
5537:
5538: my %subdivided_bubble_lines; # no. bubble lines for optionresponse,
5539: # matchresponse or rankresponse, where
5540: # an individual response can have multiple
5541: # lines
5542:
5543: my %responsetype_per_response; # responsetype for each response
5544:
5545: my %masterseq_id_responsenum; # src_id (e.g., 12.3_0.11 etc.) for each
5546: # numbered response. Needed when randomorder
5547: # or randompick are in use. Key is ID, value
5548: # is response number.
5549:
5550: # Save and restore the bubble lines array to the form env.
5551:
5552:
5553: sub save_bubble_lines {
5554: foreach my $line (keys(%bubble_lines_per_response)) {
5555: $env{"form.scantron.bubblelines.$line"} = $bubble_lines_per_response{$line};
5556: $env{"form.scantron.first_bubble_line.$line"} =
5557: $first_bubble_line{$line};
5558: $env{"form.scantron.sub_bubblelines.$line"} =
5559: $subdivided_bubble_lines{$line};
5560: $env{"form.scantron.responsetype.$line"} =
5561: $responsetype_per_response{$line};
5562: }
5563: foreach my $resid (keys(%masterseq_id_responsenum)) {
5564: my $line = $masterseq_id_responsenum{$resid};
5565: $env{"form.scantron.residpart.$line"} = $resid;
5566: }
5567: }
5568:
5569:
5570: sub restore_bubble_lines {
5571: my $line = 0;
5572: %bubble_lines_per_response = ();
5573: %masterseq_id_responsenum = ();
5574: while ($env{"form.scantron.bubblelines.$line"}) {
5575: my $value = $env{"form.scantron.bubblelines.$line"};
5576: $bubble_lines_per_response{$line} = $value;
5577: $first_bubble_line{$line} =
5578: $env{"form.scantron.first_bubble_line.$line"};
5579: $subdivided_bubble_lines{$line} =
5580: $env{"form.scantron.sub_bubblelines.$line"};
5581: $responsetype_per_response{$line} =
5582: $env{"form.scantron.responsetype.$line"};
5583: my $id = $env{"form.scantron.residpart.$line"};
5584: $masterseq_id_responsenum{$id} = $line;
5585: $line++;
5586: }
5587: }
5588:
5589: =pod
5590:
5591: =item scantron_filenames
5592:
5593: Returns a list of the scantron files in the current course
5594:
5595: =cut
5596:
5597: sub scantron_filenames {
5598: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5599: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5600: my $getpropath = 1;
5601: my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
5602: $cname,$getpropath);
5603: my @possiblenames;
5604: if (ref($dirlist) eq 'ARRAY') {
5605: foreach my $filename (sort(@{$dirlist})) {
5606: ($filename)=split(/&/,$filename);
5607: if ($filename!~/^scantron_orig_/) { next ; }
5608: $filename=~s/^scantron_orig_//;
5609: push(@possiblenames,$filename);
5610: }
5611: }
5612: return @possiblenames;
5613: }
5614:
5615: =pod
5616:
5617: =item scantron_uploads
5618:
5619: Returns html drop-down list of scantron files in current course.
5620:
5621: Arguments:
5622: $file2grade - filename to set as selected in the dropdown
5623:
5624: =cut
5625:
5626: sub scantron_uploads {
5627: my ($file2grade) = @_;
5628: my $result= '<select name="scantron_selectfile">';
5629: $result.="<option></option>";
5630: foreach my $filename (sort(&scantron_filenames())) {
5631: $result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
5632: }
5633: $result.="</select>";
5634: return $result;
5635: }
5636:
5637: =pod
5638:
5639: =item scantron_scantab
5640:
5641: Returns html drop down of the scantron formats in the scantronformat.tab
5642: file.
5643:
5644: =cut
5645:
5646: sub scantron_scantab {
5647: my $result='<select name="scantron_format">'."\n";
5648: $result.='<option></option>'."\n";
5649: my @lines = &get_scantronformat_file();
5650: if (@lines > 0) {
5651: foreach my $line (@lines) {
5652: next if (($line =~ /^\#/) || ($line eq ''));
5653: my ($name,$descrip)=split(/:/,$line);
5654: $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
5655: }
5656: }
5657: $result.='</select>'."\n";
5658: return $result;
5659: }
5660:
5661: =pod
5662:
5663: =item get_scantronformat_file
5664:
5665: Returns an array containing lines from the scantron format file for
5666: the domain of the course.
5667:
5668: If a url for a custom.tab file is listed in domain's configuration.db,
5669: lines are from this file.
5670:
5671: Otherwise, if a default.tab has been published in RES space by the
5672: domainconfig user, lines are from this file.
5673:
5674: Otherwise, fall back to getting lines from the legacy file on the
5675: local server: /home/httpd/lonTabs/default_scantronformat.tab
5676:
5677: =cut
5678:
5679: sub get_scantronformat_file {
5680: my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
5681: my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
5682: my $gottab = 0;
5683: my @lines;
5684: if (ref($domconfig{'scantron'}) eq 'HASH') {
5685: if ($domconfig{'scantron'}{'scantronformat'} ne '') {
5686: my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
5687: if ($formatfile ne '-1') {
5688: @lines = split("\n",$formatfile,-1);
5689: $gottab = 1;
5690: }
5691: }
5692: }
5693: if (!$gottab) {
5694: my $confname = $cdom.'-domainconfig';
5695: my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
5696: my $formatfile = &Apache::lonnet::getfile($default);
5697: if ($formatfile ne '-1') {
5698: @lines = split("\n",$formatfile,-1);
5699: $gottab = 1;
5700: }
5701: }
5702: if (!$gottab) {
5703: my @domains = &Apache::lonnet::current_machine_domains();
5704: if (grep(/^\Q$cdom\E$/,@domains)) {
5705: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
5706: @lines = <$fh>;
5707: close($fh);
5708: } else {
5709: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
5710: @lines = <$fh>;
5711: close($fh);
5712: }
5713: }
5714: return @lines;
5715: }
5716:
5717: =pod
5718:
5719: =item scantron_CODElist
5720:
5721: Returns html drop down of the saved CODE lists from current course,
5722: generated from earlier printings.
5723:
5724: =cut
5725:
5726: sub scantron_CODElist {
5727: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5728: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5729: my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
5730: my $namechoice='<option></option>';
5731: foreach my $name (sort {uc($a) cmp uc($b)} @names) {
5732: if ($name =~ /^error: 2 /) { next; }
5733: if ($name =~ /^type\0/) { next; }
5734: $namechoice.='<option value="'.$name.'">'.$name.'</option>';
5735: }
5736: $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
5737: return $namechoice;
5738: }
5739:
5740: =pod
5741:
5742: =item scantron_CODEunique
5743:
5744: Returns the html for "Each CODE to be used once" radio.
5745:
5746: =cut
5747:
5748: sub scantron_CODEunique {
5749: my $result='<span class="LC_nobreak">
5750: <label><input type="radio" name="scantron_CODEunique"
5751: value="yes" checked="checked" />'.&mt('Yes').' </label>
5752: </span>
5753: <span class="LC_nobreak">
5754: <label><input type="radio" name="scantron_CODEunique"
5755: value="no" />'.&mt('No').' </label>
5756: </span>';
5757: return $result;
5758: }
5759:
5760: =pod
5761:
5762: =item scantron_selectphase
5763:
5764: Generates the initial screen to start the bubblesheet process.
5765: Allows for - starting a grading run.
5766: - downloading existing scan data (original, corrected
5767: or skipped info)
5768:
5769: - uploading new scan data
5770:
5771: Arguments:
5772: $r - The Apache request object
5773: $file2grade - name of the file that contain the scanned data to score
5774:
5775: =cut
5776:
5777: sub scantron_selectphase {
5778: my ($r,$file2grade,$symb) = @_;
5779: if (!$symb) {return '';}
5780: my $map_error;
5781: my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
5782: if ($map_error) {
5783: $r->print('<br />'.&navmap_errormsg().'<br />');
5784: return;
5785: }
5786: my $default_form_data=&defaultFormData($symb);
5787: my $file_selector=&scantron_uploads($file2grade);
5788: my $format_selector=&scantron_scantab();
5789: my $CODE_selector=&scantron_CODElist();
5790: my $CODE_unique=&scantron_CODEunique();
5791: my $result;
5792:
5793: $ssi_error = 0;
5794:
5795: if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
5796: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
5797:
5798: # Chunk of form to prompt for a scantron file upload.
5799:
5800: $r->print('
5801: <br />
5802: '.&Apache::loncommon::start_data_table('LC_scantron_action').'
5803: '.&Apache::loncommon::start_data_table_header_row().'
5804: <th>
5805: '.&mt('Specify a bubblesheet data file to upload.').'
5806: </th>
5807: '.&Apache::loncommon::end_data_table_header_row().'
5808: '.&Apache::loncommon::start_data_table_row().'
5809: <td>
5810: ');
5811: my $default_form_data=&defaultFormData($symb);
5812: my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
5813: my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
5814: my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
5815: &js_escape(\$alertmsg);
5816: $r->print(&Apache::lonhtmlcommon::scripttag('
5817: function checkUpload(formname) {
5818: if (formname.upfile.value == "") {
5819: alert("'.$alertmsg.'");
5820: return false;
5821: }
5822: formname.submit();
5823: }'));
5824: $r->print('
5825: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
5826: '.$default_form_data.'
5827: <input name="courseid" type="hidden" value="'.$cnum.'" />
5828: <input name="domainid" type="hidden" value="'.$cdom.'" />
5829: <input name="command" value="scantronupload_save" type="hidden" />
5830: '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
5831: <br />
5832: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
5833: </form>
5834: ');
5835:
5836: $r->print('
5837: </td>
5838: '.&Apache::loncommon::end_data_table_row().'
5839: '.&Apache::loncommon::end_data_table().'
5840: ');
5841: }
5842:
5843: # Chunk of form to prompt for a file to grade and how:
5844:
5845: $result.= '
5846: <br />
5847: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
5848: <input type="hidden" name="command" value="scantron_warning" />
5849: '.$default_form_data.'
5850: '.&Apache::loncommon::start_data_table('LC_scantron_action').'
5851: '.&Apache::loncommon::start_data_table_header_row().'
5852: <th colspan="2">
5853: '.&mt('Specify file and which Folder/Sequence to grade').'
5854: </th>
5855: '.&Apache::loncommon::end_data_table_header_row().'
5856: '.&Apache::loncommon::start_data_table_row().'
5857: <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
5858: '.&Apache::loncommon::end_data_table_row().'
5859: '.&Apache::loncommon::start_data_table_row().'
5860: <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
5861: '.&Apache::loncommon::end_data_table_row().'
5862: '.&Apache::loncommon::start_data_table_row().'
5863: <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
5864: '.&Apache::loncommon::end_data_table_row().'
5865: '.&Apache::loncommon::start_data_table_row().'
5866: <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
5867: '.&Apache::loncommon::end_data_table_row().'
5868: '.&Apache::loncommon::start_data_table_row().'
5869: <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
5870: '.&Apache::loncommon::end_data_table_row().'
5871: '.&Apache::loncommon::start_data_table_row().'
5872: <td> '.&mt('Options:').' </td>
5873: <td>
5874: <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
5875: <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
5876: <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
5877: </td>
5878: '.&Apache::loncommon::end_data_table_row().'
5879: '.&Apache::loncommon::start_data_table_row().'
5880: <td colspan="2">
5881: <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
5882: </td>
5883: '.&Apache::loncommon::end_data_table_row().'
5884: '.&Apache::loncommon::end_data_table().'
5885: </form>
5886: ';
5887:
5888: $r->print($result);
5889:
5890:
5891:
5892: # Chunk of the form that prompts to view a scoring office file,
5893: # corrected file, skipped records in a file.
5894:
5895: $r->print('
5896: <br />
5897: <form action="/adm/grades" name="scantron_download">
5898: '.$default_form_data.'
5899: <input type="hidden" name="command" value="scantron_download" />
5900: '.&Apache::loncommon::start_data_table('LC_scantron_action').'
5901: '.&Apache::loncommon::start_data_table_header_row().'
5902: <th>
5903: '.&mt('Download a scoring office file').'
5904: </th>
5905: '.&Apache::loncommon::end_data_table_header_row().'
5906: '.&Apache::loncommon::start_data_table_row().'
5907: <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).'
5908: <br />
5909: <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
5910: '.&Apache::loncommon::end_data_table_row().'
5911: '.&Apache::loncommon::end_data_table().'
5912: </form>
5913: <br />
5914: ');
5915:
5916: &Apache::lonpickcode::code_list($r,2);
5917:
5918: $r->print('<br /><form method="post" name="checkscantron" action="">'.
5919: $default_form_data."\n".
5920: &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
5921: &Apache::loncommon::start_data_table_header_row()."\n".
5922: '<th colspan="2">
5923: '.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
5924: '</th>'."\n".
5925: &Apache::loncommon::end_data_table_header_row()."\n".
5926: &Apache::loncommon::start_data_table_row()."\n".
5927: '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
5928: '<td> '.$sequence_selector.' </td>'.
5929: &Apache::loncommon::end_data_table_row()."\n".
5930: &Apache::loncommon::start_data_table_row()."\n".
5931: '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
5932: '<td> '.$file_selector.' </td>'."\n".
5933: &Apache::loncommon::end_data_table_row()."\n".
5934: &Apache::loncommon::start_data_table_row()."\n".
5935: '<td> '.&mt('Format of data file:').' </td>'."\n".
5936: '<td> '.$format_selector.' </td>'."\n".
5937: &Apache::loncommon::end_data_table_row()."\n".
5938: &Apache::loncommon::start_data_table_row()."\n".
5939: '<td> '.&mt('Options').' </td>'."\n".
5940: '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
5941: &Apache::loncommon::end_data_table_row()."\n".
5942: &Apache::loncommon::start_data_table_row()."\n".
5943: '<td colspan="2">'."\n".
5944: '<input type="hidden" name="command" value="checksubmissions" />'."\n".
5945: '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
5946: '</td>'."\n".
5947: &Apache::loncommon::end_data_table_row()."\n".
5948: &Apache::loncommon::end_data_table()."\n".
5949: '</form><br />');
5950: return;
5951: }
5952:
5953: =pod
5954:
5955: =item get_scantron_config
5956:
5957: Parse and return the bubblesheet configuration line selected as a
5958: hash of configuration file fields.
5959:
5960: Arguments:
5961: which - the name of the configuration to parse from the file.
5962:
5963:
5964: Returns:
5965: If the named configuration is not in the file, an empty
5966: hash is returned.
5967: a hash with the fields
5968: name - internal name for the this configuration setup
5969: description - text to display to operator that describes this config
5970: CODElocation - if 0 or the string 'none'
5971: - no CODE exists for this config
5972: if -1 || the string 'letter'
5973: - a CODE exists for this config and is
5974: a string of letters
5975: Unsupported value (but planned for future support)
5976: if a positive integer
5977: - The CODE exists as the first n items from
5978: the question section of the form
5979: if the string 'number'
5980: - The CODE exists for this config and is
5981: a string of numbers
5982: CODEstart - (only matter if a CODE exists) column in the line where
5983: the CODE starts
5984: CODElength - length of the CODE
5985: IDstart - column where the student/employee ID starts
5986: IDlength - length of the student/employee ID info
5987: Qstart - column where the information from the bubbled
5988: 'questions' start
5989: Qlength - number of columns comprising a single bubble line from
5990: the sheet. (usually either 1 or 10)
5991: Qon - either a single character representing the character used
5992: to signal a bubble was chosen in the positional setup, or
5993: the string 'letter' if the letter of the chosen bubble is
5994: in the final, or 'number' if a number representing the
5995: chosen bubble is in the file (1->A 0->J)
5996: Qoff - the character used to represent that a bubble was
5997: left blank
5998: PaperID - if the scanning process generates a unique number for each
5999: sheet scanned the column that this ID number starts in
6000: PaperIDlength - number of columns that comprise the unique ID number
6001: for the sheet of paper
6002: FirstName - column that the first name starts in
6003: FirstNameLength - number of columns that the first name spans
6004:
6005: LastName - column that the last name starts in
6006: LastNameLength - number of columns that the last name spans
6007: BubblesPerRow - number of bubbles available in each row used to
6008: bubble an answer. (If not specified, 10 assumed).
6009:
6010: =cut
6011:
6012: sub get_scantron_config {
6013: my ($which) = @_;
6014: my @lines = &get_scantronformat_file();
6015: my %config;
6016: #FIXME probably should move to XML it has already gotten a bit much now
6017: foreach my $line (@lines) {
6018: my ($name,$descrip)=split(/:/,$line);
6019: if ($name ne $which ) { next; }
6020: chomp($line);
6021: my @config=split(/:/,$line);
6022: $config{'name'}=$config[0];
6023: $config{'description'}=$config[1];
6024: $config{'CODElocation'}=$config[2];
6025: $config{'CODEstart'}=$config[3];
6026: $config{'CODElength'}=$config[4];
6027: $config{'IDstart'}=$config[5];
6028: $config{'IDlength'}=$config[6];
6029: $config{'Qstart'}=$config[7];
6030: $config{'Qlength'}=$config[8];
6031: $config{'Qoff'}=$config[9];
6032: $config{'Qon'}=$config[10];
6033: $config{'PaperID'}=$config[11];
6034: $config{'PaperIDlength'}=$config[12];
6035: $config{'FirstName'}=$config[13];
6036: $config{'FirstNamelength'}=$config[14];
6037: $config{'LastName'}=$config[15];
6038: $config{'LastNamelength'}=$config[16];
6039: $config{'BubblesPerRow'}=$config[17];
6040: last;
6041: }
6042: return %config;
6043: }
6044:
6045: =pod
6046:
6047: =item username_to_idmap
6048:
6049: creates a hash keyed by student/employee ID with values of the corresponding
6050: student username:domain. If a single ID occurs for more than one student,
6051: the status of the student is checked, and if Active, the value in the hash
6052: will be set to the Active student.
6053:
6054: Arguments:
6055:
6056: $classlist - reference to the class list hash. This is a hash
6057: keyed by student name:domain whose elements are references
6058: to arrays containing various chunks of information
6059: about the student. (See loncoursedata for more info).
6060:
6061: Returns
6062: %idmap - the constructed hash
6063:
6064: =cut
6065:
6066: sub username_to_idmap {
6067: my ($classlist)= @_;
6068: my %idmap;
6069: foreach my $student (keys(%$classlist)) {
6070: my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
6071: unless ($id eq '') {
6072: if (!exists($idmap{$id})) {
6073: $idmap{$id} = $student;
6074: } else {
6075: my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
6076: if ($status eq 'Active') {
6077: $idmap{$id} = $student;
6078: }
6079: }
6080: }
6081: }
6082: return %idmap;
6083: }
6084:
6085: =pod
6086:
6087: =item scantron_fixup_scanline
6088:
6089: Process a requested correction to a scanline.
6090:
6091: Arguments:
6092: $scantron_config - hash from &get_scantron_config()
6093: $scan_data - hash of correction information
6094: (see &scantron_getfile())
6095: $line - existing scanline
6096: $whichline - line number of the passed in scanline
6097: $field - type of change to process
6098: (either
6099: 'ID' -> correct the student/employee ID
6100: 'CODE' -> correct the CODE
6101: 'answer' -> fixup the submitted answers)
6102:
6103: $args - hash of additional info,
6104: - 'ID'
6105: 'newid' -> studentID to use in replacement
6106: of existing one
6107: - 'CODE'
6108: 'CODE_ignore_dup' - set to true if duplicates
6109: should be ignored.
6110: 'CODE' - is new code or 'use_unfound'
6111: if the existing unfound code should
6112: be used as is
6113: - 'answer'
6114: 'response' - new answer or 'none' if blank
6115: 'question' - the bubble line to change
6116: 'questionnum' - the question identifier,
6117: may include subquestion.
6118:
6119: Returns:
6120: $line - the modified scanline
6121:
6122: Side effects:
6123: $scan_data - may be updated
6124:
6125: =cut
6126:
6127:
6128: sub scantron_fixup_scanline {
6129: my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
6130: if ($field eq 'ID') {
6131: if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
6132: return ($line,1,'New value too large');
6133: }
6134: if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
6135: $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
6136: $args->{'newid'});
6137: }
6138: substr($line,$$scantron_config{'IDstart'}-1,
6139: $$scantron_config{'IDlength'})=$args->{'newid'};
6140: if ($args->{'newid'}=~/^\s*$/) {
6141: &scan_data($scan_data,"$whichline.user",
6142: $args->{'username'}.':'.$args->{'domain'});
6143: }
6144: } elsif ($field eq 'CODE') {
6145: if ($args->{'CODE_ignore_dup'}) {
6146: &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
6147: }
6148: &scan_data($scan_data,"$whichline.useCODE",'1');
6149: if ($args->{'CODE'} ne 'use_unfound') {
6150: if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
6151: return ($line,1,'New CODE value too large');
6152: }
6153: if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
6154: $args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
6155: }
6156: substr($line,$$scantron_config{'CODEstart'}-1,
6157: $$scantron_config{'CODElength'})=$args->{'CODE'};
6158: }
6159: } elsif ($field eq 'answer') {
6160: my $length=$scantron_config->{'Qlength'};
6161: my $off=$scantron_config->{'Qoff'};
6162: my $on=$scantron_config->{'Qon'};
6163: my $answer=${off}x$length;
6164: if ($args->{'response'} eq 'none') {
6165: &scan_data($scan_data,
6166: "$whichline.no_bubble.".$args->{'questionnum'},'1');
6167: } else {
6168: if ($on eq 'letter') {
6169: my @alphabet=('A'..'Z');
6170: $answer=$alphabet[$args->{'response'}];
6171: } elsif ($on eq 'number') {
6172: $answer=$args->{'response'}+1;
6173: if ($answer == 10) { $answer = '0'; }
6174: } else {
6175: substr($answer,$args->{'response'},1)=$on;
6176: }
6177: &scan_data($scan_data,
6178: "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
6179: }
6180: my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
6181: substr($line,$where-1,$length)=$answer;
6182: }
6183: return $line;
6184: }
6185:
6186: =pod
6187:
6188: =item scan_data
6189:
6190: Edit or look up an item in the scan_data hash.
6191:
6192: Arguments:
6193: $scan_data - The hash (see scantron_getfile)
6194: $key - shorthand of the key to edit (actual key is
6195: scantronfilename_key).
6196: $data - New value of the hash entry.
6197: $delete - If true, the entry is removed from the hash.
6198:
6199: Returns:
6200: The new value of the hash table field (undefined if deleted).
6201:
6202: =cut
6203:
6204:
6205: sub scan_data {
6206: my ($scan_data,$key,$value,$delete)=@_;
6207: my $filename=$env{'form.scantron_selectfile'};
6208: if (defined($value)) {
6209: $scan_data->{$filename.'_'.$key} = $value;
6210: }
6211: if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
6212: return $scan_data->{$filename.'_'.$key};
6213: }
6214:
6215: # ----- These first few routines are general use routines.----
6216:
6217: # Return the number of occurences of a pattern in a string.
6218:
6219: sub occurence_count {
6220: my ($string, $pattern) = @_;
6221:
6222: my @matches = ($string =~ /$pattern/g);
6223:
6224: return scalar(@matches);
6225: }
6226:
6227:
6228: # Take a string known to have digits and convert all the
6229: # digits into letters in the range J,A..I.
6230:
6231: sub digits_to_letters {
6232: my ($input) = @_;
6233:
6234: my @alphabet = ('J', 'A'..'I');
6235:
6236: my @input = split(//, $input);
6237: my $output ='';
6238: for (my $i = 0; $i < scalar(@input); $i++) {
6239: if ($input[$i] =~ /\d/) {
6240: $output .= $alphabet[$input[$i]];
6241: } else {
6242: $output .= $input[$i];
6243: }
6244: }
6245: return $output;
6246: }
6247:
6248: =pod
6249:
6250: =item scantron_parse_scanline
6251:
6252: Decodes a scanline from the selected bubblesheet file
6253:
6254: Arguments:
6255: line - The text of the bubblesheet file line to process
6256: whichline - Line number
6257: scantron_config - Hash describing the format of the bubblesheet lines.
6258: scan_data - Hash of extra information about the scanline
6259: (see scantron_getfile for more information)
6260: just_header - True if should not process question answers but only
6261: the stuff to the left of the answers.
6262: randomorder - True if randomorder in use
6263: randompick - True if randompick in use
6264: sequence - Exam folder URL
6265: master_seq - Ref to array containing symbs in exam folder
6266: symb_to_resource - Ref to hash of symbs for resources in exam folder
6267: (corresponding values are resource objects)
6268: partids_by_symb - Ref to hash of symb -> array ref of partIDs
6269: orderedforcode - Ref to hash of arrays. keys are CODEs and values
6270: are refs to an array of resource objects, ordered
6271: according to order used for CODE, when randomorder
6272: and or randompick are in use.
6273: respnumlookup - Ref to hash mapping question numbers in bubble lines
6274: for current line to question number used for same question
6275: in "Master Sequence" (as seen by Course Coordinator).
6276: startline - Ref to hash where key is question number (0 is first)
6277: and value is number of first bubble line for current
6278: student or code-based randompick and/or randomorder.
6279: totalref - Ref of scalar used to score total number of bubble
6280: lines needed for responses in a scan line (used when
6281: randompick in use.
6282:
6283: Returns:
6284: Hash containing the result of parsing the scanline
6285:
6286: Keys are all proceeded by the string 'scantron.'
6287:
6288: CODE - the CODE in use for this scanline
6289: useCODE - 1 if the CODE is invalid but it usage has been forced
6290: by the operator
6291: CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
6292: CODEs were selected, but the usage has been
6293: forced by the operator
6294: ID - student/employee ID
6295: PaperID - if used, the ID number printed on the sheet when the
6296: paper was scanned
6297: FirstName - first name from the sheet
6298: LastName - last name from the sheet
6299:
6300: if just_header was not true these key may also exist
6301:
6302: missingerror - a list of bubble ranges that are considered to be answers
6303: to a single question that don't have any bubbles filled in.
6304: Of the form questionnumber:firstbubblenumber:count.
6305: doubleerror - a list of bubble ranges that are considered to be answers
6306: to a single question that have more than one bubble filled in.
6307: Of the form questionnumber::firstbubblenumber:count
6308:
6309: In the above, count is the number of bubble responses in the
6310: input line needed to represent the possible answers to the question.
6311: e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
6312: per line would have count = 2.
6313:
6314: maxquest - the number of the last bubble line that was parsed
6315:
6316: (<number> starts at 1)
6317: <number>.answer - zero or more letters representing the selected
6318: letters from the scanline for the bubble line
6319: <number>.
6320: if blank there was either no bubble or there where
6321: multiple bubbles, (consult the keys missingerror and
6322: doubleerror if this is an error condition)
6323:
6324: =cut
6325:
6326: sub scantron_parse_scanline {
6327: my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
6328: $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
6329: $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
6330:
6331: my %record;
6332: my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
6333: if (!($$scantron_config{'CODElocation'} eq 0 ||
6334: $$scantron_config{'CODElocation'} eq 'none')) {
6335: if ($$scantron_config{'CODElocation'} < 0 ||
6336: $$scantron_config{'CODElocation'} eq 'letter' ||
6337: $$scantron_config{'CODElocation'} eq 'number') {
6338: $record{'scantron.CODE'}=substr($data,
6339: $$scantron_config{'CODEstart'}-1,
6340: $$scantron_config{'CODElength'});
6341: if (&scan_data($scan_data,"$whichline.useCODE")) {
6342: $record{'scantron.useCODE'}=1;
6343: }
6344: if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
6345: $record{'scantron.CODE_ignore_dup'}=1;
6346: }
6347: } else {
6348: #FIXME interpret first N questions
6349: }
6350: }
6351: $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
6352: $$scantron_config{'IDlength'});
6353: $record{'scantron.PaperID'}=
6354: substr($data,$$scantron_config{'PaperID'}-1,
6355: $$scantron_config{'PaperIDlength'});
6356: $record{'scantron.FirstName'}=
6357: substr($data,$$scantron_config{'FirstName'}-1,
6358: $$scantron_config{'FirstNamelength'});
6359: $record{'scantron.LastName'}=
6360: substr($data,$$scantron_config{'LastName'}-1,
6361: $$scantron_config{'LastNamelength'});
6362: if ($just_header) { return \%record; }
6363:
6364: my @alphabet=('A'..'Z');
6365: my $questnum=0;
6366: my $ansnum =1; # Multiple 'answer lines'/question.
6367:
6368: my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
6369: if ($randompick || $randomorder) {
6370: my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
6371: $master_seq,$symb_to_resource,
6372: $partids_by_symb,$orderedforcode,
6373: $respnumlookup,$startline);
6374: if ($total) {
6375: $lastpos = $total*$$scantron_config{'Qlength'};
6376: }
6377: if (ref($totalref)) {
6378: $$totalref = $total;
6379: }
6380: }
6381: my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos); # Answers
6382: chomp($questions); # Get rid of any trailing \n.
6383: $questions =~ s/\r$//; # Get rid of trailing \r too (MAC or Win uploads).
6384: while (length($questions)) {
6385: my $answers_needed;
6386: if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
6387: $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
6388: } else {
6389: $answers_needed = $bubble_lines_per_response{$questnum};
6390: }
6391: my $answer_length = ($$scantron_config{'Qlength'} * $answers_needed)
6392: || 1;
6393: $questnum++;
6394: my $quest_id = $questnum;
6395: my $currentquest = substr($questions,0,$answer_length);
6396: $questions = substr($questions,$answer_length);
6397: if (length($currentquest) < $answer_length) { next; }
6398:
6399: my $subdivided;
6400: if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
6401: $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
6402: } else {
6403: $subdivided = $subdivided_bubble_lines{$questnum-1};
6404: }
6405: if ($subdivided =~ /,/) {
6406: my $subquestnum = 1;
6407: my $subquestions = $currentquest;
6408: my @subanswers_needed = split(/,/,$subdivided);
6409: foreach my $subans (@subanswers_needed) {
6410: my $subans_length =
6411: ($$scantron_config{'Qlength'} * $subans) || 1;
6412: my $currsubquest = substr($subquestions,0,$subans_length);
6413: $subquestions = substr($subquestions,$subans_length);
6414: $quest_id = "$questnum.$subquestnum";
6415: if (($$scantron_config{'Qon'} eq 'letter') ||
6416: ($$scantron_config{'Qon'} eq 'number')) {
6417: $ansnum = &scantron_validator_lettnum($ansnum,
6418: $questnum,$quest_id,$subans,$currsubquest,$whichline,
6419: \@alphabet,\%record,$scantron_config,$scan_data,
6420: $randomorder,$randompick,$respnumlookup);
6421: } else {
6422: $ansnum = &scantron_validator_positional($ansnum,
6423: $questnum,$quest_id,$subans,$currsubquest,$whichline,
6424: \@alphabet,\%record,$scantron_config,$scan_data,
6425: $randomorder,$randompick,$respnumlookup);
6426: }
6427: $subquestnum ++;
6428: }
6429: } else {
6430: if (($$scantron_config{'Qon'} eq 'letter') ||
6431: ($$scantron_config{'Qon'} eq 'number')) {
6432: $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
6433: $quest_id,$answers_needed,$currentquest,$whichline,
6434: \@alphabet,\%record,$scantron_config,$scan_data,
6435: $randomorder,$randompick,$respnumlookup);
6436: } else {
6437: $ansnum = &scantron_validator_positional($ansnum,$questnum,
6438: $quest_id,$answers_needed,$currentquest,$whichline,
6439: \@alphabet,\%record,$scantron_config,$scan_data,
6440: $randomorder,$randompick,$respnumlookup);
6441: }
6442: }
6443: }
6444: $record{'scantron.maxquest'}=$questnum;
6445: return \%record;
6446: }
6447:
6448: sub get_master_seq {
6449: my ($resources,$master_seq,$symb_to_resource) = @_;
6450: return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') &&
6451: (ref($symb_to_resource) eq 'HASH'));
6452: my $resource_error;
6453: foreach my $resource (@{$resources}) {
6454: my $ressymb;
6455: if (ref($resource)) {
6456: $ressymb = $resource->symb();
6457: push(@{$master_seq},$ressymb);
6458: $symb_to_resource->{$ressymb} = $resource;
6459: } else {
6460: $resource_error = 1;
6461: last;
6462: }
6463: }
6464: return $resource_error;
6465: }
6466:
6467: sub get_respnum_lookups {
6468: my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
6469: $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
6470: return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
6471: (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
6472: (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
6473: (ref($startline) eq 'HASH'));
6474: my ($user,$scancode);
6475: if ((exists($record->{'scantron.CODE'})) &&
6476: (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
6477: $scancode = $record->{'scantron.CODE'};
6478: } else {
6479: $user = &scantron_find_student($record,$scan_data,$idmap,$line);
6480: }
6481: my @mapresources =
6482: &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
6483: $orderedforcode);
6484: my $total = 0;
6485: my $count = 0;
6486: foreach my $resource (@mapresources) {
6487: my $id = $resource->id();
6488: my $symb = $resource->symb();
6489: if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
6490: foreach my $partid (@{$partids_by_symb->{$symb}}) {
6491: my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
6492: if ($respnum ne '') {
6493: $respnumlookup->{$count} = $respnum;
6494: $startline->{$count} = $total;
6495: $total += $bubble_lines_per_response{$respnum};
6496: $count ++;
6497: }
6498: }
6499: }
6500: }
6501: return $total;
6502: }
6503:
6504: sub scantron_validator_lettnum {
6505: my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
6506: $alphabet,$record,$scantron_config,$scan_data,$randomorder,
6507: $randompick,$respnumlookup) = @_;
6508:
6509: # Qon 'letter' implies for each slot in currquest we have:
6510: # ? or * for doubles, a letter in A-Z for a bubble, and
6511: # about anything else (esp. a value of Qoff) for missing
6512: # bubbles.
6513: #
6514: # Qon 'number' implies each slot gives a digit that indexes the
6515: # bubbles filled, or Qoff, or a non-number for unbubbled lines,
6516: # and * or ? for double bubbles on a single line.
6517: #
6518:
6519: my $matchon;
6520: if ($$scantron_config{'Qon'} eq 'letter') {
6521: $matchon = '[A-Z]';
6522: } elsif ($$scantron_config{'Qon'} eq 'number') {
6523: $matchon = '\d';
6524: }
6525: my $occurrences = 0;
6526: my $responsenum = $questnum-1;
6527: if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
6528: $responsenum = $respnumlookup->{$questnum-1}
6529: }
6530: if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
6531: ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
6532: ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
6533: ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
6534: ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
6535: ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
6536: my @singlelines = split('',$currquest);
6537: foreach my $entry (@singlelines) {
6538: $occurrences = &occurence_count($entry,$matchon);
6539: if ($occurrences > 1) {
6540: last;
6541: }
6542: }
6543: } else {
6544: $occurrences = &occurence_count($currquest,$matchon);
6545: }
6546: if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
6547: push(@{$record->{'scantron.doubleerror'}},$quest_id);
6548: for (my $ans=0; $ans<$answers_needed; $ans++) {
6549: my $bubble = substr($currquest,$ans,1);
6550: if ($bubble =~ /$matchon/ ) {
6551: if ($$scantron_config{'Qon'} eq 'number') {
6552: if ($bubble == 0) {
6553: $bubble = 10;
6554: }
6555: $record->{"scantron.$ansnum.answer"} =
6556: $alphabet->[$bubble-1];
6557: } else {
6558: $record->{"scantron.$ansnum.answer"} = $bubble;
6559: }
6560: } else {
6561: $record->{"scantron.$ansnum.answer"}='';
6562: }
6563: $ansnum++;
6564: }
6565: } elsif (!defined($currquest)
6566: || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
6567: || (&occurence_count($currquest,$matchon) == 0)) {
6568: for (my $ans=0; $ans<$answers_needed; $ans++ ) {
6569: $record->{"scantron.$ansnum.answer"}='';
6570: $ansnum++;
6571: }
6572: if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
6573: push(@{$record->{'scantron.missingerror'}},$quest_id);
6574: }
6575: } else {
6576: if ($$scantron_config{'Qon'} eq 'number') {
6577: $currquest = &digits_to_letters($currquest);
6578: }
6579: for (my $ans=0; $ans<$answers_needed; $ans++) {
6580: my $bubble = substr($currquest,$ans,1);
6581: $record->{"scantron.$ansnum.answer"} = $bubble;
6582: $ansnum++;
6583: }
6584: }
6585: return $ansnum;
6586: }
6587:
6588: sub scantron_validator_positional {
6589: my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
6590: $whichline,$alphabet,$record,$scantron_config,$scan_data,
6591: $randomorder,$randompick,$respnumlookup) = @_;
6592:
6593: # Otherwise there's a positional notation;
6594: # each bubble line requires Qlength items, and there are filled in
6595: # bubbles for each case where there 'Qon' characters.
6596: #
6597:
6598: my @array=split($$scantron_config{'Qon'},$currquest,-1);
6599:
6600: # If the split only gives us one element.. the full length of the
6601: # answer string, no bubbles are filled in:
6602:
6603: if ($answers_needed eq '') {
6604: return;
6605: }
6606:
6607: if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
6608: for (my $ans=0; $ans<$answers_needed; $ans++ ) {
6609: $record->{"scantron.$ansnum.answer"}='';
6610: $ansnum++;
6611: }
6612: if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
6613: push(@{$record->{"scantron.missingerror"}},$quest_id);
6614: }
6615: } elsif (scalar(@array) == 2) {
6616: my $location = length($array[0]);
6617: my $line_num = int($location / $$scantron_config{'Qlength'});
6618: my $bubble = $alphabet->[$location % $$scantron_config{'Qlength'}];
6619: for (my $ans=0; $ans<$answers_needed; $ans++) {
6620: if ($ans eq $line_num) {
6621: $record->{"scantron.$ansnum.answer"} = $bubble;
6622: } else {
6623: $record->{"scantron.$ansnum.answer"} = ' ';
6624: }
6625: $ansnum++;
6626: }
6627: } else {
6628: # If there's more than one instance of a bubble character
6629: # That's a double bubble; with positional notation we can
6630: # record all the bubbles filled in as well as the
6631: # fact this response consists of multiple bubbles.
6632: #
6633: my $responsenum = $questnum-1;
6634: if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
6635: $responsenum = $respnumlookup->{$questnum-1}
6636: }
6637: if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
6638: ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
6639: ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
6640: ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
6641: ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
6642: ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
6643: my $doubleerror = 0;
6644: while (($currquest >= $$scantron_config{'Qlength'}) &&
6645: (!$doubleerror)) {
6646: my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
6647: $currquest = substr($currquest,$$scantron_config{'Qlength'});
6648: my @currarray = split($$scantron_config{'Qon'},$currline,-1);
6649: if (length(@currarray) > 2) {
6650: $doubleerror = 1;
6651: }
6652: }
6653: if ($doubleerror) {
6654: push(@{$record->{'scantron.doubleerror'}},$quest_id);
6655: }
6656: } else {
6657: push(@{$record->{'scantron.doubleerror'}},$quest_id);
6658: }
6659: my $item = $ansnum;
6660: for (my $ans=0; $ans<$answers_needed; $ans++) {
6661: $record->{"scantron.$item.answer"} = '';
6662: $item ++;
6663: }
6664:
6665: my @ans=@array;
6666: my $i=0;
6667: my $increment = 0;
6668: while ($#ans) {
6669: $i+=length($ans[0]) + $increment;
6670: my $line = int($i/$$scantron_config{'Qlength'} + $ansnum);
6671: my $bubble = $i%$$scantron_config{'Qlength'};
6672: $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
6673: shift(@ans);
6674: $increment = 1;
6675: }
6676: $ansnum += $answers_needed;
6677: }
6678: return $ansnum;
6679: }
6680:
6681: =pod
6682:
6683: =item scantron_add_delay
6684:
6685: Adds an error message that occurred during the grading phase to a
6686: queue of messages to be shown after grading pass is complete
6687:
6688: Arguments:
6689: $delayqueue - arrary ref of hash ref of error messages
6690: $scanline - the scanline that caused the error
6691: $errormesage - the error message
6692: $errorcode - a numeric code for the error
6693:
6694: Side Effects:
6695: updates the $delayqueue to have a new hash ref of the error
6696:
6697: =cut
6698:
6699: sub scantron_add_delay {
6700: my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
6701: push(@$delayqueue,
6702: {'line' => $scanline, 'emsg' => $errormessage,
6703: 'ecode' => $errorcode }
6704: );
6705: }
6706:
6707: =pod
6708:
6709: =item scantron_find_student
6710:
6711: Finds the username for the current scanline
6712:
6713: Arguments:
6714: $scantron_record - hash result from scantron_parse_scanline
6715: $scan_data - hash of correction information
6716: (see &scantron_getfile() form more information)
6717: $idmap - hash from &username_to_idmap()
6718: $line - number of current scanline
6719:
6720: Returns:
6721: Either 'username:domain' or undef if unknown
6722:
6723: =cut
6724:
6725: sub scantron_find_student {
6726: my ($scantron_record,$scan_data,$idmap,$line)=@_;
6727: my $scanID=$$scantron_record{'scantron.ID'};
6728: if ($scanID =~ /^\s*$/) {
6729: return &scan_data($scan_data,"$line.user");
6730: }
6731: foreach my $id (keys(%$idmap)) {
6732: if (lc($id) eq lc($scanID)) {
6733: return $$idmap{$id};
6734: }
6735: }
6736: return undef;
6737: }
6738:
6739: =pod
6740:
6741: =item scantron_filter
6742:
6743: Filter sub for lonnavmaps, filters out hidden resources if ignore
6744: hidden resources was selected
6745:
6746: =cut
6747:
6748: sub scantron_filter {
6749: my ($curres)=@_;
6750:
6751: if (ref($curres) && $curres->is_problem()) {
6752: # if the user has asked to not have either hidden
6753: # or 'randomout' controlled resources to be graded
6754: # don't include them
6755: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
6756: && $curres->randomout) {
6757: return 0;
6758: }
6759: return 1;
6760: }
6761: return 0;
6762: }
6763:
6764: =pod
6765:
6766: =item scantron_process_corrections
6767:
6768: Gets correction information out of submitted form data and corrects
6769: the scanline
6770:
6771: =cut
6772:
6773: sub scantron_process_corrections {
6774: my ($r) = @_;
6775: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6776: my ($scanlines,$scan_data)=&scantron_getfile();
6777: my $classlist=&Apache::loncoursedata::get_classlist();
6778: my $which=$env{'form.scantron_line'};
6779: my $line=&scantron_get_line($scanlines,$scan_data,$which);
6780: my ($skip,$err,$errmsg);
6781: if ($env{'form.scantron_skip_record'}) {
6782: $skip=1;
6783: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
6784: my $newstudent=$env{'form.scantron_username'}.':'.
6785: $env{'form.scantron_domain'};
6786: my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
6787: ($line,$err,$errmsg)=
6788: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
6789: 'ID',{'newid'=>$newid,
6790: 'username'=>$env{'form.scantron_username'},
6791: 'domain'=>$env{'form.scantron_domain'}});
6792: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
6793: my $resolution=$env{'form.scantron_CODE_resolution'};
6794: my $newCODE;
6795: my %args;
6796: if ($resolution eq 'use_unfound') {
6797: $newCODE='use_unfound';
6798: } elsif ($resolution eq 'use_found') {
6799: $newCODE=$env{'form.scantron_CODE_selectedvalue'};
6800: } elsif ($resolution eq 'use_typed') {
6801: $newCODE=$env{'form.scantron_CODE_newvalue'};
6802: } elsif ($resolution =~ /^use_closest_(\d+)/) {
6803: $newCODE=$env{"form.scantron_CODE_closest_$1"};
6804: }
6805: if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
6806: $args{'CODE_ignore_dup'}=1;
6807: }
6808: $args{'CODE'}=$newCODE;
6809: ($line,$err,$errmsg)=
6810: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
6811: 'CODE',\%args);
6812: } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
6813: foreach my $question (split(',',$env{'form.scantron_questions'})) {
6814: ($line,$err,$errmsg)=
6815: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
6816: $which,'answer',
6817: { 'question'=>$question,
6818: 'response'=>$env{"form.scantron_correct_Q_$question"},
6819: 'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
6820: if ($err) { last; }
6821: }
6822: }
6823: if ($err) {
6824: $r->print(
6825: '<p class="LC_error">'
6826: .&mt('Unable to accept last correction, an error occurred: [_1]',
6827: $errmsg)
6828: .'</p>');
6829: } else {
6830: &scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
6831: &scantron_putfile($scanlines,$scan_data);
6832: }
6833: }
6834:
6835: =pod
6836:
6837: =item reset_skipping_status
6838:
6839: Forgets the current set of remember skipped scanlines (and thus
6840: reverts back to considering all lines in the
6841: scantron_skipped_<filename> file)
6842:
6843: =cut
6844:
6845: sub reset_skipping_status {
6846: my ($scanlines,$scan_data)=&scantron_getfile();
6847: &scan_data($scan_data,'remember_skipping',undef,1);
6848: &scantron_putfile(undef,$scan_data);
6849: }
6850:
6851: =pod
6852:
6853: =item start_skipping
6854:
6855: Marks a scanline to be skipped.
6856:
6857: =cut
6858:
6859: sub start_skipping {
6860: my ($scan_data,$i)=@_;
6861: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
6862: if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
6863: $remembered{$i}=2;
6864: } else {
6865: $remembered{$i}=1;
6866: }
6867: &scan_data($scan_data,'remember_skipping',join(':',%remembered));
6868: }
6869:
6870: =pod
6871:
6872: =item should_be_skipped
6873:
6874: Checks whether a scanline should be skipped.
6875:
6876: =cut
6877:
6878: sub should_be_skipped {
6879: my ($scanlines,$scan_data,$i)=@_;
6880: if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
6881: # not redoing old skips
6882: if ($scanlines->{'skipped'}[$i]) { return 1; }
6883: return 0;
6884: }
6885: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
6886:
6887: if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
6888: return 0;
6889: }
6890: return 1;
6891: }
6892:
6893: =pod
6894:
6895: =item remember_current_skipped
6896:
6897: Discovers what scanlines are in the scantron_skipped_<filename>
6898: file and remembers them into scan_data for later use.
6899:
6900: =cut
6901:
6902: sub remember_current_skipped {
6903: my ($scanlines,$scan_data)=&scantron_getfile();
6904: my %to_remember;
6905: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6906: if ($scanlines->{'skipped'}[$i]) {
6907: $to_remember{$i}=1;
6908: }
6909: }
6910:
6911: &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
6912: &scantron_putfile(undef,$scan_data);
6913: }
6914:
6915: =pod
6916:
6917: =item check_for_error
6918:
6919: Checks if there was an error when attempting to remove a specific
6920: scantron_.. bubblesheet data file. Prints out an error if
6921: something went wrong.
6922:
6923: =cut
6924:
6925: sub check_for_error {
6926: my ($r,$result)=@_;
6927: if ($result ne 'ok' && $result ne 'not_found' ) {
6928: $r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
6929: }
6930: }
6931:
6932: =pod
6933:
6934: =item scantron_warning_screen
6935:
6936: Interstitial screen to make sure the operator has selected the
6937: correct options before we start the validation phase.
6938:
6939: =cut
6940:
6941: sub scantron_warning_screen {
6942: my ($button_text,$symb)=@_;
6943: my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
6944: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6945: my $CODElist;
6946: if ($scantron_config{'CODElocation'} &&
6947: $scantron_config{'CODEstart'} &&
6948: $scantron_config{'CODElength'}) {
6949: $CODElist=$env{'form.scantron_CODElist'};
6950: if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
6951: $CODElist=
6952: '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
6953: $env{'form.scantron_CODElist'}.'</tt></td></tr>';
6954: }
6955: my $lastbubblepoints;
6956: if ($env{'form.scantron_lastbubblepoints'} ne '') {
6957: $lastbubblepoints =
6958: '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
6959: $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
6960: }
6961: return ('
6962: <p>
6963: <span class="LC_warning">
6964: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
6965: </p>
6966: <table>
6967: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
6968: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
6969: '.$CODElist.$lastbubblepoints.'
6970: </table>
6971: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
6972: '.&mt('If something is incorrect, please return to [_1]Grade/Manage/Review Bubblesheets[_2] to start over.','<a href="/adm/grades?symb='.$symb.'&command=scantron_selectphase" class="LC_info">','</a>').'</p>
6973:
6974: <br />
6975: ');
6976: }
6977:
6978: =pod
6979:
6980: =item scantron_do_warning
6981:
6982: Check if the operator has picked something for all required
6983: fields. Error out if something is missing.
6984:
6985: =cut
6986:
6987: sub scantron_do_warning {
6988: my ($r,$symb)=@_;
6989: if (!$symb) {return '';}
6990: my $default_form_data=&defaultFormData($symb);
6991: $r->print(&scantron_form_start().$default_form_data);
6992: if ( $env{'form.selectpage'} eq '' ||
6993: $env{'form.scantron_selectfile'} eq '' ||
6994: $env{'form.scantron_format'} eq '' ) {
6995: $r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
6996: if ( $env{'form.selectpage'} eq '') {
6997: $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
6998: }
6999: if ( $env{'form.scantron_selectfile'} eq '') {
7000: $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
7001: }
7002: if ( $env{'form.scantron_format'} eq '') {
7003: $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
7004: }
7005: } else {
7006: my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
7007: my $bubbledbyhand=&hand_bubble_option();
7008: $r->print('
7009: '.$warning.$bubbledbyhand.'
7010: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
7011: <input type="hidden" name="command" value="scantron_validate" />
7012: ');
7013: }
7014: $r->print("</form><br />");
7015: return '';
7016: }
7017:
7018: =pod
7019:
7020: =item scantron_form_start
7021:
7022: html hidden input for remembering all selected grading options
7023:
7024: =cut
7025:
7026: sub scantron_form_start {
7027: my ($max_bubble)=@_;
7028: my $result= <<SCANTRONFORM;
7029: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
7030: <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
7031: <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
7032: <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
7033: <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
7034: <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
7035: <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
7036: <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
7037: <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
7038: <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
7039: SCANTRONFORM
7040:
7041: my $line = 0;
7042: while (defined($env{"form.scantron.bubblelines.$line"})) {
7043: my $chunk =
7044: '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
7045: $chunk .=
7046: '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
7047: $chunk .=
7048: '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
7049: $chunk .=
7050: '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
7051: $chunk .=
7052: '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
7053: $result .= $chunk;
7054: $line++;
7055: }
7056: return $result;
7057: }
7058:
7059: =pod
7060:
7061: =item scantron_validate_file
7062:
7063: Dispatch routine for doing validation of a bubblesheet data file.
7064:
7065: Also processes any necessary information resets that need to
7066: occur before validation begins (ignore previous corrections,
7067: restarting the skipped records processing)
7068:
7069: =cut
7070:
7071: sub scantron_validate_file {
7072: my ($r,$symb) = @_;
7073: if (!$symb) {return '';}
7074: my $default_form_data=&defaultFormData($symb);
7075:
7076: # do the detection of only doing skipped records first before we delete
7077: # them when doing the corrections reset
7078: if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
7079: &reset_skipping_status();
7080: }
7081: if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
7082: &remember_current_skipped();
7083: $env{'form.scantron_options_redo'}='redo_skipped_ready';
7084: }
7085:
7086: if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
7087: &check_for_error($r,&scantron_remove_file('corrected'));
7088: &check_for_error($r,&scantron_remove_file('skipped'));
7089: &check_for_error($r,&scantron_remove_scan_data());
7090: $env{'form.scantron_options_ignore'}='done';
7091: }
7092:
7093: if ($env{'form.scantron_corrections'}) {
7094: &scantron_process_corrections($r);
7095: }
7096: $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
7097: #get the student pick code ready
7098: $r->print(&Apache::loncommon::studentbrowser_javascript());
7099: my $nav_error;
7100: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7101: my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
7102: if ($nav_error) {
7103: $r->print(&navmap_errormsg());
7104: return '';
7105: }
7106: my $result=&scantron_form_start($max_bubble).$default_form_data;
7107: if ($env{'form.scantron_lastbubblepoints'} ne '') {
7108: $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
7109: }
7110: $r->print($result);
7111:
7112: my @validate_phases=( 'sequence',
7113: 'ID',
7114: 'CODE',
7115: 'doublebubble',
7116: 'missingbubbles');
7117: if (!$env{'form.validatepass'}) {
7118: $env{'form.validatepass'} = 0;
7119: }
7120: my $currentphase=$env{'form.validatepass'};
7121:
7122:
7123: my $stop=0;
7124: while (!$stop && $currentphase < scalar(@validate_phases)) {
7125: $r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
7126: $r->rflush();
7127:
7128: my $which="scantron_validate_".$validate_phases[$currentphase];
7129: {
7130: no strict 'refs';
7131: ($stop,$currentphase)=&$which($r,$currentphase);
7132: }
7133: }
7134: if (!$stop) {
7135: my $warning=&scantron_warning_screen('Start Grading',$symb);
7136: $r->print(&mt('Validation process complete.').'<br />'.
7137: $warning.
7138: &mt('Perform verification for each student after storage of submissions?').
7139: ' <span class="LC_nobreak"><label>'.
7140: '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
7141: (' 'x3).'<label>'.
7142: '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
7143: '</label></span><br />'.
7144: &mt('Grading will take longer if you use verification.').'<br />'.
7145: &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','»').'<br /><br />'.
7146: '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
7147: '<input type="hidden" name="command" value="scantron_process" />'."\n");
7148: } else {
7149: $r->print('<input type="hidden" name="command" value="scantron_validate" />');
7150: $r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
7151: }
7152: if ($stop) {
7153: if ($validate_phases[$currentphase] eq 'sequence') {
7154: $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' → " />');
7155: $r->print(' '.&mt('this error').' <br />');
7156:
7157: $r->print('<p>'.&mt('Or return to [_1]Grade/Manage/Review Bubblesheets[_2] to start over.','<a href="/adm/grades?symb='.$symb.'&command=scantron_selectphase" class="LC_info">','</a>').'</p>');
7158: } else {
7159: if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
7160: $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' →" onclick="javascript:verify_bubble_radio(this.form)" />');
7161: } else {
7162: $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' →" />');
7163: }
7164: $r->print(' '.&mt('using corrected info').' <br />');
7165: $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
7166: $r->print(" ".&mt("this scanline saving it for later."));
7167: }
7168: }
7169: $r->print(" </form><br />");
7170: return '';
7171: }
7172:
7173:
7174: =pod
7175:
7176: =item scantron_remove_file
7177:
7178: Removes the requested bubblesheet data file, makes sure that
7179: scantron_original_<filename> is never removed
7180:
7181:
7182: =cut
7183:
7184: sub scantron_remove_file {
7185: my ($which)=@_;
7186: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7187: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7188: my $file='scantron_';
7189: if ($which eq 'corrected' || $which eq 'skipped') {
7190: $file.=$which.'_';
7191: } else {
7192: return 'refused';
7193: }
7194: $file.=$env{'form.scantron_selectfile'};
7195: return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
7196: }
7197:
7198:
7199: =pod
7200:
7201: =item scantron_remove_scan_data
7202:
7203: Removes all scan_data correction for the requested bubblesheet
7204: data file. (In the case that both the are doing skipped records we need
7205: to remember the old skipped lines for the time being so that element
7206: persists for a while.)
7207:
7208: =cut
7209:
7210: sub scantron_remove_scan_data {
7211: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7212: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7213: my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
7214: my @todelete;
7215: my $filename=$env{'form.scantron_selectfile'};
7216: foreach my $key (@keys) {
7217: if ($key=~/^\Q$filename\E_/) {
7218: if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
7219: $key=~/remember_skipping/) {
7220: next;
7221: }
7222: push(@todelete,$key);
7223: }
7224: }
7225: my $result;
7226: if (@todelete) {
7227: $result = &Apache::lonnet::del('nohist_scantrondata',
7228: \@todelete,$cdom,$cname);
7229: } else {
7230: $result = 'ok';
7231: }
7232: return $result;
7233: }
7234:
7235:
7236: =pod
7237:
7238: =item scantron_getfile
7239:
7240: Fetches the requested bubblesheet data file (all 3 versions), and
7241: the scan_data hash
7242:
7243: Arguments:
7244: None
7245:
7246: Returns:
7247: 2 hash references
7248:
7249: - first one has
7250: orig -
7251: corrected -
7252: skipped - each of which points to an array ref of the specified
7253: file broken up into individual lines
7254: count - number of scanlines
7255:
7256: - second is the scan_data hash possible keys are
7257: ($number refers to scanline numbered $number and thus the key affects
7258: only that scanline
7259: $bubline refers to the specific bubble line element and the aspects
7260: refers to that specific bubble line element)
7261:
7262: $number.user - username:domain to use
7263: $number.CODE_ignore_dup
7264: - ignore the duplicate CODE error
7265: $number.useCODE
7266: - use the CODE in the scanline as is
7267: $number.no_bubble.$bubline
7268: - it is valid that there is no bubbled in bubble
7269: at $number $bubline
7270: remember_skipping
7271: - a frozen hash containing keys of $number and values
7272: of either
7273: 1 - we are on a 'do skipped records pass' and plan
7274: on processing this line
7275: 2 - we are on a 'do skipped records pass' and this
7276: scanline has been marked to skip yet again
7277:
7278: =cut
7279:
7280: sub scantron_getfile {
7281: #FIXME really would prefer a scantron directory
7282: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7283: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7284: my $lines;
7285: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
7286: 'scantron_orig_'.$env{'form.scantron_selectfile'});
7287: my %scanlines;
7288: $scanlines{'orig'}=[(split("\n",$lines,-1))];
7289: my $temp=$scanlines{'orig'};
7290: $scanlines{'count'}=$#$temp;
7291:
7292: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
7293: 'scantron_corrected_'.$env{'form.scantron_selectfile'});
7294: if ($lines eq '-1') {
7295: $scanlines{'corrected'}=[];
7296: } else {
7297: $scanlines{'corrected'}=[(split("\n",$lines,-1))];
7298: }
7299: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
7300: 'scantron_skipped_'.$env{'form.scantron_selectfile'});
7301: if ($lines eq '-1') {
7302: $scanlines{'skipped'}=[];
7303: } else {
7304: $scanlines{'skipped'}=[(split("\n",$lines,-1))];
7305: }
7306: my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
7307: if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
7308: my %scan_data = @tmp;
7309: return (\%scanlines,\%scan_data);
7310: }
7311:
7312: =pod
7313:
7314: =item lonnet_putfile
7315:
7316: Wrapper routine to call &Apache::lonnet::finishuserfileupload
7317:
7318: Arguments:
7319: $contents - data to store
7320: $filename - filename to store $contents into
7321:
7322: Returns:
7323: result value from &Apache::lonnet::finishuserfileupload
7324:
7325: =cut
7326:
7327: sub lonnet_putfile {
7328: my ($contents,$filename)=@_;
7329: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
7330: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7331: $env{'form.sillywaytopassafilearound'}=$contents;
7332: &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
7333:
7334: }
7335:
7336: =pod
7337:
7338: =item scantron_putfile
7339:
7340: Stores the current version of the bubblesheet data files, and the
7341: scan_data hash. (Does not modify the original version only the
7342: corrected and skipped versions.
7343:
7344: Arguments:
7345: $scanlines - hash ref that looks like the first return value from
7346: &scantron_getfile()
7347: $scan_data - hash ref that looks like the second return value from
7348: &scantron_getfile()
7349:
7350: =cut
7351:
7352: sub scantron_putfile {
7353: my ($scanlines,$scan_data) = @_;
7354: #FIXME really would prefer a scantron directory
7355: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7356: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7357: if ($scanlines) {
7358: my $prefix='scantron_';
7359: # no need to update orig, shouldn't change
7360: # &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
7361: # $env{'form.scantron_selectfile'});
7362: &lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
7363: $prefix.'corrected_'.
7364: $env{'form.scantron_selectfile'});
7365: &lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
7366: $prefix.'skipped_'.
7367: $env{'form.scantron_selectfile'});
7368: }
7369: &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
7370: }
7371:
7372: =pod
7373:
7374: =item scantron_get_line
7375:
7376: Returns the correct version of the scanline
7377:
7378: Arguments:
7379: $scanlines - hash ref that looks like the first return value from
7380: &scantron_getfile()
7381: $scan_data - hash ref that looks like the second return value from
7382: &scantron_getfile()
7383: $i - number of the requested line (starts at 0)
7384:
7385: Returns:
7386: A scanline, (either the original or the corrected one if it
7387: exists), or undef if the requested scanline should be
7388: skipped. (Either because it's an skipped scanline, or it's an
7389: unskipped scanline and we are not doing a 'do skipped scanlines'
7390: pass.
7391:
7392: =cut
7393:
7394: sub scantron_get_line {
7395: my ($scanlines,$scan_data,$i)=@_;
7396: if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
7397: #if ($scanlines->{'skipped'}[$i]) { return undef; }
7398: if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
7399: return $scanlines->{'orig'}[$i];
7400: }
7401:
7402: =pod
7403:
7404: =item scantron_todo_count
7405:
7406: Counts the number of scanlines that need processing.
7407:
7408: Arguments:
7409: $scanlines - hash ref that looks like the first return value from
7410: &scantron_getfile()
7411: $scan_data - hash ref that looks like the second return value from
7412: &scantron_getfile()
7413:
7414: Returns:
7415: $count - number of scanlines to process
7416:
7417: =cut
7418:
7419: sub get_todo_count {
7420: my ($scanlines,$scan_data)=@_;
7421: my $count=0;
7422: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7423: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7424: if ($line=~/^[\s\cz]*$/) { next; }
7425: $count++;
7426: }
7427: return $count;
7428: }
7429:
7430: =pod
7431:
7432: =item scantron_put_line
7433:
7434: Updates the 'corrected' or 'skipped' versions of the bubblesheet
7435: data file.
7436:
7437: Arguments:
7438: $scanlines - hash ref that looks like the first return value from
7439: &scantron_getfile()
7440: $scan_data - hash ref that looks like the second return value from
7441: &scantron_getfile()
7442: $i - line number to update
7443: $newline - contents of the updated scanline
7444: $skip - if true make the line for skipping and update the
7445: 'skipped' file
7446:
7447: =cut
7448:
7449: sub scantron_put_line {
7450: my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
7451: if ($skip) {
7452: $scanlines->{'skipped'}[$i]=$newline;
7453: &start_skipping($scan_data,$i);
7454: return;
7455: }
7456: $scanlines->{'corrected'}[$i]=$newline;
7457: }
7458:
7459: =pod
7460:
7461: =item scantron_clear_skip
7462:
7463: Remove a line from the 'skipped' file
7464:
7465: Arguments:
7466: $scanlines - hash ref that looks like the first return value from
7467: &scantron_getfile()
7468: $scan_data - hash ref that looks like the second return value from
7469: &scantron_getfile()
7470: $i - line number to update
7471:
7472: =cut
7473:
7474: sub scantron_clear_skip {
7475: my ($scanlines,$scan_data,$i)=@_;
7476: if (exists($scanlines->{'skipped'}[$i])) {
7477: undef($scanlines->{'skipped'}[$i]);
7478: return 1;
7479: }
7480: return 0;
7481: }
7482:
7483: =pod
7484:
7485: =item scantron_filter_not_exam
7486:
7487: Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
7488: filter out resources that are not marked as 'exam' mode
7489:
7490: =cut
7491:
7492: sub scantron_filter_not_exam {
7493: my ($curres)=@_;
7494:
7495: if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
7496: # if the user has asked to not have either hidden
7497: # or 'randomout' controlled resources to be graded
7498: # don't include them
7499: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
7500: && $curres->randomout) {
7501: return 0;
7502: }
7503: return 1;
7504: }
7505: return 0;
7506: }
7507:
7508: =pod
7509:
7510: =item scantron_validate_sequence
7511:
7512: Validates the selected sequence, checking for resource that are
7513: not set to exam mode.
7514:
7515: =cut
7516:
7517: sub scantron_validate_sequence {
7518: my ($r,$currentphase) = @_;
7519:
7520: my $navmap=Apache::lonnavmaps::navmap->new();
7521: unless (ref($navmap)) {
7522: $r->print(&navmap_errormsg());
7523: return (1,$currentphase);
7524: }
7525: my (undef,undef,$sequence)=
7526: &Apache::lonnet::decode_symb($env{'form.selectpage'});
7527:
7528: my $map=$navmap->getResourceByUrl($sequence);
7529:
7530: $r->print('<input type="hidden" name="validate_sequence_exam"
7531: value="ignore" />');
7532: if ($env{'form.validate_sequence_exam'} ne 'ignore') {
7533: my @resources=
7534: $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
7535: if (@resources) {
7536: $r->print(
7537: '<p class="LC_warning">'
7538: .&mt('Some resources in the sequence currently are not set to'
7539: .' bubblesheet exam mode. Grading these resources currently may not'
7540: .' work correctly.')
7541: .'</p>'
7542: );
7543: return (1,$currentphase);
7544: }
7545: }
7546:
7547: return (0,$currentphase+1);
7548: }
7549:
7550:
7551:
7552: sub scantron_validate_ID {
7553: my ($r,$currentphase) = @_;
7554:
7555: #get student info
7556: my $classlist=&Apache::loncoursedata::get_classlist();
7557: my %idmap=&username_to_idmap($classlist);
7558:
7559: #get scantron line setup
7560: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7561: my ($scanlines,$scan_data)=&scantron_getfile();
7562:
7563: my $nav_error;
7564: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
7565: if ($nav_error) {
7566: $r->print(&navmap_errormsg());
7567: return(1,$currentphase);
7568: }
7569:
7570: my %found=('ids'=>{},'usernames'=>{});
7571: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7572: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7573: if ($line=~/^[\s\cz]*$/) { next; }
7574: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7575: $scan_data);
7576: my $id=$$scan_record{'scantron.ID'};
7577: my $found;
7578: foreach my $checkid (keys(%idmap)) {
7579: if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
7580: }
7581: if ($found) {
7582: my $username=$idmap{$found};
7583: if ($found{'ids'}{$found}) {
7584: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
7585: $line,'duplicateID',$found);
7586: return(1,$currentphase);
7587: } elsif ($found{'usernames'}{$username}) {
7588: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
7589: $line,'duplicateID',$username);
7590: return(1,$currentphase);
7591: }
7592: #FIXME store away line we previously saw the ID on to use above
7593: $found{'ids'}{$found}++;
7594: $found{'usernames'}{$username}++;
7595: } else {
7596: if ($id =~ /^\s*$/) {
7597: my $username=&scan_data($scan_data,"$i.user");
7598: if (defined($username) && $found{'usernames'}{$username}) {
7599: &scantron_get_correction($r,$i,$scan_record,
7600: \%scantron_config,
7601: $line,'duplicateID',$username);
7602: return(1,$currentphase);
7603: } elsif (!defined($username)) {
7604: &scantron_get_correction($r,$i,$scan_record,
7605: \%scantron_config,
7606: $line,'incorrectID');
7607: return(1,$currentphase);
7608: }
7609: $found{'usernames'}{$username}++;
7610: } else {
7611: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
7612: $line,'incorrectID');
7613: return(1,$currentphase);
7614: }
7615: }
7616: }
7617:
7618: return (0,$currentphase+1);
7619: }
7620:
7621:
7622: sub scantron_get_correction {
7623: my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
7624: $randomorder,$randompick,$respnumlookup,$startline)=@_;
7625: #FIXME in the case of a duplicated ID the previous line, probably need
7626: #to show both the current line and the previous one and allow skipping
7627: #the previous one or the current one
7628:
7629: if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
7630: $r->print(
7631: '<p class="LC_warning">'
7632: .&mt('An error was detected ([_1]) for PaperID [_2]',
7633: "<b>$error</b>",
7634: '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
7635: ."</p> \n");
7636: } else {
7637: $r->print(
7638: '<p class="LC_warning">'
7639: .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
7640: "<b>$error</b>", $i, "<pre>$line</pre>")
7641: ."</p> \n");
7642: }
7643: my $message =
7644: '<p>'
7645: .&mt('The ID on the form is [_1]',
7646: "<tt>$$scan_record{'scantron.ID'}</tt>")
7647: .'<br />'
7648: .&mt('The name on the paper is [_1], [_2]',
7649: $$scan_record{'scantron.LastName'},
7650: $$scan_record{'scantron.FirstName'})
7651: .'</p>';
7652:
7653: $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
7654: $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
7655: # Array populated for doublebubble or
7656: my @lines_to_correct; # missingbubble errors to build javascript
7657: # to validate radio button checking
7658:
7659: if ($error =~ /ID$/) {
7660: if ($error eq 'incorrectID') {
7661: $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
7662: "</p>\n");
7663: } elsif ($error eq 'duplicateID') {
7664: $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
7665: }
7666: $r->print($message);
7667: $r->print("<p>".&mt("How should I handle this?")." <br /> \n");
7668: $r->print("\n<ul><li> ");
7669: #FIXME it would be nice if this sent back the user ID and
7670: #could do partial userID matches
7671: $r->print(&Apache::loncommon::selectstudent_link('scantronupload',
7672: 'scantron_username','scantron_domain'));
7673: $r->print(": <input type='text' name='scantron_username' value='' />");
7674: $r->print("\n:\n".
7675: &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
7676:
7677: $r->print('</li>');
7678: } elsif ($error =~ /CODE$/) {
7679: if ($error eq 'incorrectCODE') {
7680: $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
7681: } elsif ($error eq 'duplicateCODE') {
7682: $r->print('<p class="LC_warning">'.&mt("The encoded CODE has also been used by a previous paper [_1], and CODEs are supposed to be unique.",join(', ',@{$arg}))."</p>\n");
7683: }
7684: $r->print("<p>".&mt('The CODE on the form is [_1]',
7685: "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
7686: ."</p>\n");
7687: $r->print($message);
7688: $r->print("<p>".&mt("How should I handle this?")."</p>\n");
7689: $r->print("\n<br /> ");
7690: my $i=0;
7691: if ($error eq 'incorrectCODE'
7692: && $$scan_record{'scantron.CODE'}=~/\S/ ) {
7693: my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
7694: if ($closest > 0) {
7695: foreach my $testcode (@{$closest}) {
7696: my $checked='';
7697: if (!$i) { $checked=' checked="checked"'; }
7698: $r->print("
7699: <label>
7700: <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
7701: ".&mt("Use the similar CODE [_1] instead.",
7702: "<b><tt>".$testcode."</tt></b>")."
7703: </label>
7704: <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
7705: $r->print("\n<br />");
7706: $i++;
7707: }
7708: }
7709: }
7710: if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
7711: my $checked; if (!$i) { $checked=' checked="checked"'; }
7712: $r->print("
7713: <label>
7714: <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
7715: ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
7716: "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
7717: </label>");
7718: $r->print("\n<br />");
7719: }
7720:
7721: $r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
7722: function change_radio(field) {
7723: var slct=document.scantronupload.scantron_CODE_resolution;
7724: var i;
7725: for (i=0;i<slct.length;i++) {
7726: if (slct[i].value==field) { slct[i].checked=true; }
7727: }
7728: }
7729: ENDSCRIPT
7730: my $href="/adm/pickcode?".
7731: "form=".&escape("scantronupload").
7732: "&scantron_format=".&escape($env{'form.scantron_format'}).
7733: "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
7734: "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
7735: "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
7736: if ($env{'form.scantron_CODElist'} =~ /\S/) {
7737: $r->print("
7738: <label>
7739: <input type='radio' name='scantron_CODE_resolution' value='use_found' />
7740: ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
7741: "<a target='_blank' href='$href'>","</a>")."
7742: </label>
7743: ".&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\')" />'));
7744: $r->print("\n<br />");
7745: }
7746: $r->print("
7747: <label>
7748: <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
7749: ".&mt("Use [_1] as the CODE.",
7750: "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
7751: $r->print("\n<br /><br />");
7752: } elsif ($error eq 'doublebubble') {
7753: $r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
7754:
7755: # The form field scantron_questions is acutally a list of line numbers.
7756: # represented by this form so:
7757:
7758: my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
7759: $respnumlookup,$startline);
7760:
7761: $r->print('<input type="hidden" name="scantron_questions" value="'.
7762: $line_list.'" />');
7763: $r->print($message);
7764: $r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
7765: foreach my $question (@{$arg}) {
7766: my @linenums = &prompt_for_corrections($r,$question,$scan_config,
7767: $scan_record, $error,
7768: $randomorder,$randompick,
7769: $respnumlookup,$startline);
7770: push(@lines_to_correct,@linenums);
7771: }
7772: $r->print(&verify_bubbles_checked(@lines_to_correct));
7773: } elsif ($error eq 'missingbubble') {
7774: $r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
7775: $r->print($message);
7776: $r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
7777: $r->print(&mt("Some questions have no scanned bubbles.")."\n");
7778:
7779: # The form field scantron_questions is actually a list of line numbers not
7780: # a list of question numbers. Therefore:
7781: #
7782:
7783: my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
7784: $respnumlookup,$startline);
7785:
7786: $r->print('<input type="hidden" name="scantron_questions" value="'.
7787: $line_list.'" />');
7788: foreach my $question (@{$arg}) {
7789: my @linenums = &prompt_for_corrections($r,$question,$scan_config,
7790: $scan_record, $error,
7791: $randomorder,$randompick,
7792: $respnumlookup,$startline);
7793: push(@lines_to_correct,@linenums);
7794: }
7795: $r->print(&verify_bubbles_checked(@lines_to_correct));
7796: } else {
7797: $r->print("\n<ul>");
7798: }
7799: $r->print("\n</li></ul>");
7800: }
7801:
7802: sub verify_bubbles_checked {
7803: my (@ansnums) = @_;
7804: my $ansnumstr = join('","',@ansnums);
7805: my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
7806: &js_escape(\$warning);
7807: my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
7808: function verify_bubble_radio(form) {
7809: var ansnumArray = new Array ("$ansnumstr");
7810: var need_bubble_count = 0;
7811: for (var i=0; i<ansnumArray.length; i++) {
7812: if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
7813: var bubble_picked = 0;
7814: for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
7815: if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
7816: bubble_picked = 1;
7817: }
7818: }
7819: if (bubble_picked == 0) {
7820: need_bubble_count ++;
7821: }
7822: }
7823: }
7824: if (need_bubble_count) {
7825: alert("$warning");
7826: return;
7827: }
7828: form.submit();
7829: }
7830: ENDSCRIPT
7831: return $output;
7832: }
7833:
7834: =pod
7835:
7836: =item questions_to_line_list
7837:
7838: Converts a list of questions into a string of comma separated
7839: line numbers in the answer sheet used by the questions. This is
7840: used to fill in the scantron_questions form field.
7841:
7842: Arguments:
7843: questions - Reference to an array of questions.
7844: randomorder - True if randomorder in use.
7845: randompick - True if randompick in use.
7846: respnumlookup - Reference to HASH mapping question numbers in bubble lines
7847: for current line to question number used for same question
7848: in "Master Seqence" (as seen by Course Coordinator).
7849: startline - Reference to hash where key is question number (0 is first)
7850: and key is number of first bubble line for current student
7851: or code-based randompick and/or randomorder.
7852:
7853: =cut
7854:
7855:
7856: sub questions_to_line_list {
7857: my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
7858: my @lines;
7859:
7860: foreach my $item (@{$questions}) {
7861: my $question = $item;
7862: my ($first,$count,$last);
7863: if ($item =~ /^(\d+)\.(\d+)$/) {
7864: $question = $1;
7865: my $subquestion = $2;
7866: my $responsenum = $question-1;
7867: if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
7868: $responsenum = $respnumlookup->{$question-1};
7869: if (ref($startline) eq 'HASH') {
7870: $first = $startline->{$question-1} + 1;
7871: }
7872: } else {
7873: $first = $first_bubble_line{$responsenum} + 1;
7874: }
7875: my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
7876: my $subcount = 1;
7877: while ($subcount<$subquestion) {
7878: $first += $subans[$subcount-1];
7879: $subcount ++;
7880: }
7881: $count = $subans[$subquestion-1];
7882: } else {
7883: my $responsenum = $question-1;
7884: if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
7885: $responsenum = $respnumlookup->{$question-1};
7886: if (ref($startline) eq 'HASH') {
7887: $first = $startline->{$question-1} + 1;
7888: }
7889: } else {
7890: $first = $first_bubble_line{$responsenum} + 1;
7891: }
7892: $count = $bubble_lines_per_response{$responsenum};
7893: }
7894: $last = $first+$count-1;
7895: push(@lines, ($first..$last));
7896: }
7897: return join(',', @lines);
7898: }
7899:
7900: =pod
7901:
7902: =item prompt_for_corrections
7903:
7904: Prompts for a potentially multiline correction to the
7905: user's bubbling (factors out common code from scantron_get_correction
7906: for multi and missing bubble cases).
7907:
7908: Arguments:
7909: $r - Apache request object.
7910: $question - The question number to prompt for.
7911: $scan_config - The scantron file configuration hash.
7912: $scan_record - Reference to the hash that has the the parsed scanlines.
7913: $error - Type of error
7914: $randomorder - True if randomorder in use.
7915: $randompick - True if randompick in use.
7916: $respnumlookup - Reference to HASH mapping question numbers in bubble lines
7917: for current line to question number used for same question
7918: in "Master Seqence" (as seen by Course Coordinator).
7919: $startline - Reference to hash where key is question number (0 is first)
7920: and value is number of first bubble line for current student
7921: or code-based randompick and/or randomorder.
7922:
7923:
7924: Implicit inputs:
7925: %bubble_lines_per_response - Starting line numbers for each question.
7926: Numbered from 0 (but question numbers are from
7927: 1.
7928: %first_bubble_line - Starting bubble line for each question.
7929: %subdivided_bubble_lines - optionresponse, matchresponse and rankresponse
7930: type problems render as separate sub-questions,
7931: in exam mode. This hash contains a
7932: comma-separated list of the lines per
7933: sub-question.
7934: %responsetype_per_response - essayresponse, formularesponse,
7935: stringresponse, imageresponse, reactionresponse,
7936: and organicresponse type problem parts can have
7937: multiple lines per response if the weight
7938: assigned exceeds 10. In this case, only
7939: one bubble per line is permitted, but more
7940: than one line might contain bubbles, e.g.
7941: bubbling of: line 1 - J, line 2 - J,
7942: line 3 - B would assign 22 points.
7943:
7944: =cut
7945:
7946: sub prompt_for_corrections {
7947: my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
7948: $randompick, $respnumlookup, $startline) = @_;
7949: my ($current_line,$lines);
7950: my @linenums;
7951: my $questionnum = $question;
7952: my ($first,$responsenum);
7953: if ($question =~ /^(\d+)\.(\d+)$/) {
7954: $question = $1;
7955: my $subquestion = $2;
7956: if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
7957: $responsenum = $respnumlookup->{$question-1};
7958: if (ref($startline) eq 'HASH') {
7959: $first = $startline->{$question-1};
7960: }
7961: } else {
7962: $responsenum = $question-1;
7963: $first = $first_bubble_line{$responsenum};
7964: }
7965: $current_line = $first + 1 ;
7966: my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
7967: my $subcount = 1;
7968: while ($subcount<$subquestion) {
7969: $current_line += $subans[$subcount-1];
7970: $subcount ++;
7971: }
7972: $lines = $subans[$subquestion-1];
7973: } else {
7974: if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
7975: $responsenum = $respnumlookup->{$question-1};
7976: if (ref($startline) eq 'HASH') {
7977: $first = $startline->{$question-1};
7978: }
7979: } else {
7980: $responsenum = $question-1;
7981: $first = $first_bubble_line{$responsenum};
7982: }
7983: $current_line = $first + 1;
7984: $lines = $bubble_lines_per_response{$responsenum};
7985: }
7986: if ($lines > 1) {
7987: $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
7988: if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
7989: ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
7990: ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
7991: ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
7992: ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
7993: ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
7994: $r->print(
7995: &mt("Although this particular question type requires handgrading, the instructions for this question in the bubblesheet exam directed students to leave [quant,_1,line] blank on their bubblesheets.",$lines)
7996: .'<br /><br />'
7997: .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
7998: .'<br />'
7999: .&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.')
8000: .'<br />'
8001: .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
8002: .'<br /><br />'
8003: );
8004: } else {
8005: $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
8006: }
8007: }
8008: for (my $i =0; $i < $lines; $i++) {
8009: my $selected = $$scan_record{"scantron.$current_line.answer"};
8010: &scantron_bubble_selector($r,$scan_config,$current_line,
8011: $questionnum,$error,split('', $selected));
8012: push(@linenums,$current_line);
8013: $current_line++;
8014: }
8015: if ($lines > 1) {
8016: $r->print("<hr /><br />");
8017: }
8018: return @linenums;
8019: }
8020:
8021: =pod
8022:
8023: =item scantron_bubble_selector
8024:
8025: Generates the html radiobuttons to correct a single bubble line
8026: possibly showing the existing the selected bubbles if known
8027:
8028: Arguments:
8029: $r - Apache request object
8030: $scan_config - hash from &get_scantron_config()
8031: $line - Number of the line being displayed.
8032: $questionnum - Question number (may include subquestion)
8033: $error - Type of error.
8034: @selected - Array of bubbles picked on this line.
8035:
8036: =cut
8037:
8038: sub scantron_bubble_selector {
8039: my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
8040: my $max=$$scan_config{'Qlength'};
8041:
8042: my $scmode=$$scan_config{'Qon'};
8043: if ($scmode eq 'number' || $scmode eq 'letter') {
8044: if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
8045: ($$scan_config{'BubblesPerRow'} > 0)) {
8046: $max=$$scan_config{'BubblesPerRow'};
8047: if (($scmode eq 'number') && ($max > 10)) {
8048: $max = 10;
8049: } elsif (($scmode eq 'letter') && $max > 26) {
8050: $max = 26;
8051: }
8052: } else {
8053: $max = 10;
8054: }
8055: }
8056:
8057: my @alphabet=('A'..'Z');
8058: $r->print(&Apache::loncommon::start_data_table().
8059: &Apache::loncommon::start_data_table_row());
8060: $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
8061: for (my $i=0;$i<$max+1;$i++) {
8062: $r->print("\n".'<td align="center">');
8063: if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
8064: else { $r->print(' '); }
8065: $r->print('</td>');
8066: }
8067: $r->print(&Apache::loncommon::end_data_table_row().
8068: &Apache::loncommon::start_data_table_row());
8069: for (my $i=0;$i<$max;$i++) {
8070: $r->print("\n".
8071: '<td><label><input type="radio" name="scantron_correct_Q_'.
8072: $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
8073: }
8074: my $nobub_checked = ' ';
8075: if ($error eq 'missingbubble') {
8076: $nobub_checked = ' checked = "checked" ';
8077: }
8078: $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
8079: $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
8080: '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
8081: $line.'" value="'.$questionnum.'" /></td>');
8082: $r->print(&Apache::loncommon::end_data_table_row().
8083: &Apache::loncommon::end_data_table());
8084: }
8085:
8086: =pod
8087:
8088: =item num_matches
8089:
8090: Counts the number of characters that are the same between the two arguments.
8091:
8092: Arguments:
8093: $orig - CODE from the scanline
8094: $code - CODE to match against
8095:
8096: Returns:
8097: $count - integer count of the number of same characters between the
8098: two arguments
8099:
8100: =cut
8101:
8102: sub num_matches {
8103: my ($orig,$code) = @_;
8104: my @code=split(//,$code);
8105: my @orig=split(//,$orig);
8106: my $same=0;
8107: for (my $i=0;$i<scalar(@code);$i++) {
8108: if ($code[$i] eq $orig[$i]) { $same++; }
8109: }
8110: return $same;
8111: }
8112:
8113: =pod
8114:
8115: =item scantron_get_closely_matching_CODEs
8116:
8117: Cycles through all CODEs and finds the set that has the greatest
8118: number of same characters as the provided CODE
8119:
8120: Arguments:
8121: $allcodes - hash ref returned by &get_codes()
8122: $CODE - CODE from the current scanline
8123:
8124: Returns:
8125: 2 element list
8126: - first elements is number of how closely matching the best fit is
8127: (5 means best set has 5 matching characters)
8128: - second element is an arrary ref containing the set of valid CODEs
8129: that best fit the passed in CODE
8130:
8131: =cut
8132:
8133: sub scantron_get_closely_matching_CODEs {
8134: my ($allcodes,$CODE)=@_;
8135: my @CODEs;
8136: foreach my $testcode (sort(keys(%{$allcodes}))) {
8137: push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
8138: }
8139:
8140: return ($#CODEs,$CODEs[-1]);
8141: }
8142:
8143: =pod
8144:
8145: =item get_codes
8146:
8147: Builds a hash which has keys of all of the valid CODEs from the selected
8148: set of remembered CODEs.
8149:
8150: Arguments:
8151: $old_name - name of the set of remembered CODEs
8152: $cdom - domain of the course
8153: $cnum - internal course name
8154:
8155: Returns:
8156: %allcodes - keys are the valid CODEs, values are all 1
8157:
8158: =cut
8159:
8160: sub get_codes {
8161: my ($old_name, $cdom, $cnum) = @_;
8162: if (!$old_name) {
8163: $old_name=$env{'form.scantron_CODElist'};
8164: }
8165: if (!$cdom) {
8166: $cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
8167: }
8168: if (!$cnum) {
8169: $cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
8170: }
8171: my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
8172: $cdom,$cnum);
8173: my %allcodes;
8174: if ($result{"type\0$old_name"} eq 'number') {
8175: %allcodes=map {($_,1)} split(',',$result{$old_name});
8176: } else {
8177: %allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
8178: }
8179: return %allcodes;
8180: }
8181:
8182: =pod
8183:
8184: =item scantron_validate_CODE
8185:
8186: Validates all scanlines in the selected file to not have any
8187: invalid or underspecified CODEs and that none of the codes are
8188: duplicated if this was requested.
8189:
8190: =cut
8191:
8192: sub scantron_validate_CODE {
8193: my ($r,$currentphase) = @_;
8194: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
8195: if ($scantron_config{'CODElocation'} &&
8196: $scantron_config{'CODEstart'} &&
8197: $scantron_config{'CODElength'}) {
8198: if (!defined($env{'form.scantron_CODElist'})) {
8199: &FIXME_blow_up()
8200: }
8201: } else {
8202: return (0,$currentphase+1);
8203: }
8204:
8205: my %usedCODEs;
8206:
8207: my %allcodes=&get_codes();
8208:
8209: my $nav_error;
8210: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
8211: if ($nav_error) {
8212: $r->print(&navmap_errormsg());
8213: return(1,$currentphase);
8214: }
8215:
8216: my ($scanlines,$scan_data)=&scantron_getfile();
8217: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
8218: my $line=&scantron_get_line($scanlines,$scan_data,$i);
8219: if ($line=~/^[\s\cz]*$/) { next; }
8220: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
8221: $scan_data);
8222: my $CODE=$$scan_record{'scantron.CODE'};
8223: my $error=0;
8224: if (!&Apache::lonnet::validCODE($CODE)) {
8225: &scantron_get_correction($r,$i,$scan_record,
8226: \%scantron_config,
8227: $line,'incorrectCODE',\%allcodes);
8228: return(1,$currentphase);
8229: }
8230: if (%allcodes && !exists($allcodes{$CODE})
8231: && !$$scan_record{'scantron.useCODE'}) {
8232: &scantron_get_correction($r,$i,$scan_record,
8233: \%scantron_config,
8234: $line,'incorrectCODE',\%allcodes);
8235: return(1,$currentphase);
8236: }
8237: if (exists($usedCODEs{$CODE})
8238: && $env{'form.scantron_CODEunique'} eq 'yes'
8239: && !$$scan_record{'scantron.CODE_ignore_dup'}) {
8240: &scantron_get_correction($r,$i,$scan_record,
8241: \%scantron_config,
8242: $line,'duplicateCODE',$usedCODEs{$CODE});
8243: return(1,$currentphase);
8244: }
8245: push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
8246: }
8247: return (0,$currentphase+1);
8248: }
8249:
8250: =pod
8251:
8252: =item scantron_validate_doublebubble
8253:
8254: Validates all scanlines in the selected file to not have any
8255: bubble lines with multiple bubbles marked.
8256:
8257: =cut
8258:
8259: sub scantron_validate_doublebubble {
8260: my ($r,$currentphase) = @_;
8261: #get student info
8262: my $classlist=&Apache::loncoursedata::get_classlist();
8263: my %idmap=&username_to_idmap($classlist);
8264: my (undef,undef,$sequence)=
8265: &Apache::lonnet::decode_symb($env{'form.selectpage'});
8266:
8267: #get scantron line setup
8268: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
8269: my ($scanlines,$scan_data)=&scantron_getfile();
8270:
8271: my $navmap = Apache::lonnavmaps::navmap->new();
8272: unless (ref($navmap)) {
8273: $r->print(&navmap_errormsg());
8274: return(1,$currentphase);
8275: }
8276: my $map=$navmap->getResourceByUrl($sequence);
8277: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
8278: my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
8279: %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
8280: my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
8281:
8282: my $nav_error;
8283: if (ref($map)) {
8284: $randomorder = $map->randomorder();
8285: $randompick = $map->randompick();
8286: if ($randomorder || $randompick) {
8287: $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
8288: if ($nav_error) {
8289: $r->print(&navmap_errormsg());
8290: return(1,$currentphase);
8291: }
8292: &graders_resources_pass(\@resources,\%grader_partids_by_symb,
8293: \%grader_randomlists_by_symb,$bubbles_per_row);
8294: }
8295: } else {
8296: $r->print(&navmap_errormsg());
8297: return(1,$currentphase);
8298: }
8299:
8300: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
8301: if ($nav_error) {
8302: $r->print(&navmap_errormsg());
8303: return(1,$currentphase);
8304: }
8305:
8306: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
8307: my $line=&scantron_get_line($scanlines,$scan_data,$i);
8308: if ($line=~/^[\s\cz]*$/) { next; }
8309: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
8310: $scan_data,undef,\%idmap,$randomorder,
8311: $randompick,$sequence,\@master_seq,
8312: \%symb_to_resource,\%grader_partids_by_symb,
8313: \%orderedforcode,\%respnumlookup,\%startline);
8314: if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
8315: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
8316: 'doublebubble',
8317: $$scan_record{'scantron.doubleerror'},
8318: $randomorder,$randompick,\%respnumlookup,\%startline);
8319: return (1,$currentphase);
8320: }
8321: return (0,$currentphase+1);
8322: }
8323:
8324:
8325: sub scantron_get_maxbubble {
8326: my ($nav_error,$scantron_config) = @_;
8327: if (defined($env{'form.scantron_maxbubble'}) &&
8328: $env{'form.scantron_maxbubble'}) {
8329: &restore_bubble_lines();
8330: return $env{'form.scantron_maxbubble'};
8331: }
8332:
8333: my (undef, undef, $sequence) =
8334: &Apache::lonnet::decode_symb($env{'form.selectpage'});
8335:
8336: my $navmap=Apache::lonnavmaps::navmap->new();
8337: unless (ref($navmap)) {
8338: if (ref($nav_error)) {
8339: $$nav_error = 1;
8340: }
8341: return;
8342: }
8343: my $map=$navmap->getResourceByUrl($sequence);
8344: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
8345: my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
8346:
8347: &Apache::lonxml::clear_problem_counter();
8348:
8349: my $uname = $env{'user.name'};
8350: my $udom = $env{'user.domain'};
8351: my $cid = $env{'request.course.id'};
8352: my $total_lines = 0;
8353: %bubble_lines_per_response = ();
8354: %first_bubble_line = ();
8355: %subdivided_bubble_lines = ();
8356: %responsetype_per_response = ();
8357: %masterseq_id_responsenum = ();
8358:
8359: my $response_number = 0;
8360: my $bubble_line = 0;
8361: foreach my $resource (@resources) {
8362: my $resid = $resource->id();
8363: my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
8364: $udom,undef,$bubbles_per_row);
8365: if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
8366: foreach my $part_id (@{$parts}) {
8367: my $lines;
8368:
8369: # TODO - make this a persistent hash not an array.
8370:
8371: # optionresponse, matchresponse and rankresponse type items
8372: # render as separate sub-questions in exam mode.
8373: if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
8374: ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
8375: ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
8376: my ($numbub,$numshown);
8377: if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
8378: if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
8379: $numbub = scalar(@{$analysis->{$part_id.'.options'}});
8380: }
8381: } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
8382: if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
8383: $numbub = scalar(@{$analysis->{$part_id.'.items'}});
8384: }
8385: } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
8386: if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
8387: $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
8388: }
8389: }
8390: if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
8391: $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
8392: }
8393: my $bubbles_per_row =
8394: &bubblesheet_bubbles_per_row($scantron_config);
8395: my $inner_bubble_lines = int($numbub/$bubbles_per_row);
8396: if (($numbub % $bubbles_per_row) != 0) {
8397: $inner_bubble_lines++;
8398: }
8399: for (my $i=0; $i<$numshown; $i++) {
8400: $subdivided_bubble_lines{$response_number} .=
8401: $inner_bubble_lines.',';
8402: }
8403: $subdivided_bubble_lines{$response_number} =~ s/,$//;
8404: $lines = $numshown * $inner_bubble_lines;
8405: } else {
8406: $lines = $analysis->{"$part_id.bubble_lines"};
8407: }
8408:
8409: $first_bubble_line{$response_number} = $bubble_line;
8410: $bubble_lines_per_response{$response_number} = $lines;
8411: $responsetype_per_response{$response_number} =
8412: $analysis->{$part_id.'.type'};
8413: $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;
8414: $response_number++;
8415:
8416: $bubble_line += $lines;
8417: $total_lines += $lines;
8418: }
8419: }
8420: }
8421: &Apache::lonnet::delenv('scantron.');
8422:
8423: &save_bubble_lines();
8424: $env{'form.scantron_maxbubble'} =
8425: $total_lines;
8426: return $env{'form.scantron_maxbubble'};
8427: }
8428:
8429: sub bubblesheet_bubbles_per_row {
8430: my ($scantron_config) = @_;
8431: my $bubbles_per_row;
8432: if (ref($scantron_config) eq 'HASH') {
8433: $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
8434: }
8435: if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
8436: $bubbles_per_row = 10;
8437: }
8438: return $bubbles_per_row;
8439: }
8440:
8441: sub scantron_validate_missingbubbles {
8442: my ($r,$currentphase) = @_;
8443: #get student info
8444: my $classlist=&Apache::loncoursedata::get_classlist();
8445: my %idmap=&username_to_idmap($classlist);
8446: my (undef,undef,$sequence)=
8447: &Apache::lonnet::decode_symb($env{'form.selectpage'});
8448:
8449: #get scantron line setup
8450: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
8451: my ($scanlines,$scan_data)=&scantron_getfile();
8452:
8453: my $navmap = Apache::lonnavmaps::navmap->new();
8454: unless (ref($navmap)) {
8455: $r->print(&navmap_errormsg());
8456: return(1,$currentphase);
8457: }
8458:
8459: my $map=$navmap->getResourceByUrl($sequence);
8460: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
8461: my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
8462: %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
8463: my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
8464:
8465: my $nav_error;
8466: if (ref($map)) {
8467: $randomorder = $map->randomorder();
8468: $randompick = $map->randompick();
8469: if ($randomorder || $randompick) {
8470: $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
8471: if ($nav_error) {
8472: $r->print(&navmap_errormsg());
8473: return(1,$currentphase);
8474: }
8475: &graders_resources_pass(\@resources,\%grader_partids_by_symb,
8476: \%grader_randomlists_by_symb,$bubbles_per_row);
8477: }
8478: } else {
8479: $r->print(&navmap_errormsg());
8480: return(1,$currentphase);
8481: }
8482:
8483:
8484: my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
8485: if ($nav_error) {
8486: $r->print(&navmap_errormsg());
8487: return(1,$currentphase);
8488: }
8489:
8490: if (!$max_bubble) { $max_bubble=2**31; }
8491: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
8492: my $line=&scantron_get_line($scanlines,$scan_data,$i);
8493: if ($line=~/^[\s\cz]*$/) { next; }
8494: my $scan_record =
8495: &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
8496: $randomorder,$randompick,$sequence,\@master_seq,
8497: \%symb_to_resource,\%grader_partids_by_symb,
8498: \%orderedforcode,\%respnumlookup,\%startline);
8499: if (!defined($$scan_record{'scantron.missingerror'})) { next; }
8500: my @to_correct;
8501:
8502: # Probably here's where the error is...
8503:
8504: foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
8505: my $lastbubble;
8506: if ($missing =~ /^(\d+)\.(\d+)$/) {
8507: my $question = $1;
8508: my $subquestion = $2;
8509: my ($first,$responsenum);
8510: if ($randomorder || $randompick) {
8511: $responsenum = $respnumlookup{$question-1};
8512: $first = $startline{$question-1};
8513: } else {
8514: $responsenum = $question-1;
8515: $first = $first_bubble_line{$responsenum};
8516: }
8517: if (!defined($first)) { next; }
8518: my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
8519: my $subcount = 1;
8520: while ($subcount<$subquestion) {
8521: $first += $subans[$subcount-1];
8522: $subcount ++;
8523: }
8524: my $count = $subans[$subquestion-1];
8525: $lastbubble = $first + $count;
8526: } else {
8527: my ($first,$responsenum);
8528: if ($randomorder || $randompick) {
8529: $responsenum = $respnumlookup{$missing-1};
8530: $first = $startline{$missing-1};
8531: } else {
8532: $responsenum = $missing-1;
8533: $first = $first_bubble_line{$responsenum};
8534: }
8535: if (!defined($first)) { next; }
8536: $lastbubble = $first + $bubble_lines_per_response{$responsenum};
8537: }
8538: if ($lastbubble > $max_bubble) { next; }
8539: push(@to_correct,$missing);
8540: }
8541: if (@to_correct) {
8542: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
8543: $line,'missingbubble',\@to_correct,
8544: $randomorder,$randompick,\%respnumlookup,
8545: \%startline);
8546: return (1,$currentphase);
8547: }
8548:
8549: }
8550: return (0,$currentphase+1);
8551: }
8552:
8553: sub hand_bubble_option {
8554: my (undef, undef, $sequence) =
8555: &Apache::lonnet::decode_symb($env{'form.selectpage'});
8556: return if ($sequence eq '');
8557: my $navmap = Apache::lonnavmaps::navmap->new();
8558: unless (ref($navmap)) {
8559: return;
8560: }
8561: my $needs_hand_bubbles;
8562: my $map=$navmap->getResourceByUrl($sequence);
8563: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
8564: foreach my $res (@resources) {
8565: if (ref($res)) {
8566: if ($res->is_problem()) {
8567: my $partlist = $res->parts();
8568: foreach my $part (@{ $partlist }) {
8569: my @types = $res->responseType($part);
8570: if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
8571: $needs_hand_bubbles = 1;
8572: last;
8573: }
8574: }
8575: }
8576: }
8577: }
8578: if ($needs_hand_bubbles) {
8579: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
8580: my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
8581: return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
8582: &mt('If you have already graded these by bubbling sheets to indicate points awarded, [_1]what point value is assigned to a filled last bubble in each row?','<br />').
8583: '<label><input type="radio" name="scantron_lastbubblepoints" value="'.$bubbles_per_row.'" checked="checked" />'.&mt('[quant,_1,point]',$bubbles_per_row).'</label> '.&mt('or').' '.
8584: '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
8585: }
8586: return;
8587: }
8588:
8589: sub scantron_process_students {
8590: my ($r,$symb) = @_;
8591:
8592: my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
8593: if (!$symb) {
8594: return '';
8595: }
8596: my $default_form_data=&defaultFormData($symb);
8597:
8598: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
8599: my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
8600: my ($scanlines,$scan_data)=&scantron_getfile();
8601: my $classlist=&Apache::loncoursedata::get_classlist();
8602: my %idmap=&username_to_idmap($classlist);
8603: my $navmap=Apache::lonnavmaps::navmap->new();
8604: unless (ref($navmap)) {
8605: $r->print(&navmap_errormsg());
8606: return '';
8607: }
8608: my $map=$navmap->getResourceByUrl($sequence);
8609: my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
8610: %grader_randomlists_by_symb);
8611: if (ref($map)) {
8612: $randomorder = $map->randomorder();
8613: $randompick = $map->randompick();
8614: } else {
8615: $r->print(&navmap_errormsg());
8616: return '';
8617: }
8618: my $nav_error;
8619: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
8620: if ($randomorder || $randompick) {
8621: $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
8622: if ($nav_error) {
8623: $r->print(&navmap_errormsg());
8624: return '';
8625: }
8626: }
8627: &graders_resources_pass(\@resources,\%grader_partids_by_symb,
8628: \%grader_randomlists_by_symb,$bubbles_per_row);
8629:
8630: my ($uname,$udom);
8631: my $result= <<SCANTRONFORM;
8632: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
8633: <input type="hidden" name="command" value="scantron_configphase" />
8634: $default_form_data
8635: SCANTRONFORM
8636: $r->print($result);
8637:
8638: my @delayqueue;
8639: my (%completedstudents,%scandata);
8640:
8641: my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
8642: my $count=&get_todo_count($scanlines,$scan_data);
8643: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
8644: &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
8645: $r->print('<br />');
8646: my $start=&Time::HiRes::time();
8647: my $i=-1;
8648: my $started;
8649:
8650: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
8651: if ($nav_error) {
8652: $r->print(&navmap_errormsg());
8653: return '';
8654: }
8655:
8656: # If an ssi failed in scantron_get_maxbubble, put an error message out to
8657: # the user and return.
8658:
8659: if ($ssi_error) {
8660: $r->print("</form>");
8661: &ssi_print_error($r);
8662: &Apache::lonnet::remove_lock($lock);
8663: return ''; # Dunno why the other returns return '' rather than just returning.
8664: }
8665:
8666: my %lettdig = &letter_to_digits();
8667: my $numletts = scalar(keys(%lettdig));
8668: my %orderedforcode;
8669:
8670: while ($i<$scanlines->{'count'}) {
8671: ($uname,$udom)=('','');
8672: $i++;
8673: my $line=&scantron_get_line($scanlines,$scan_data,$i);
8674: if ($line=~/^[\s\cz]*$/) { next; }
8675: if ($started) {
8676: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
8677: }
8678: $started=1;
8679: my %respnumlookup = ();
8680: my %startline = ();
8681: my $total;
8682: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
8683: $scan_data,undef,\%idmap,$randomorder,
8684: $randompick,$sequence,\@master_seq,
8685: \%symb_to_resource,\%grader_partids_by_symb,
8686: \%orderedforcode,\%respnumlookup,\%startline,
8687: \$total);
8688: unless ($uname=&scantron_find_student($scan_record,$scan_data,
8689: \%idmap,$i)) {
8690: &scantron_add_delay(\@delayqueue,$line,
8691: 'Unable to find a student that matches',1);
8692: next;
8693: }
8694: if (exists $completedstudents{$uname}) {
8695: &scantron_add_delay(\@delayqueue,$line,
8696: 'Student '.$uname.' has multiple sheets',2);
8697: next;
8698: }
8699: my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
8700: my $user = $uname.':'.$usec;
8701: ($uname,$udom)=split(/:/,$uname);
8702:
8703: my $scancode;
8704: if ((exists($scan_record->{'scantron.CODE'})) &&
8705: (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
8706: $scancode = $scan_record->{'scantron.CODE'};
8707: } else {
8708: $scancode = '';
8709: }
8710:
8711: my @mapresources = @resources;
8712: if ($randomorder || $randompick) {
8713: @mapresources =
8714: &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
8715: \%orderedforcode);
8716: }
8717: my (%partids_by_symb,$res_error);
8718: foreach my $resource (@mapresources) {
8719: my $ressymb;
8720: if (ref($resource)) {
8721: $ressymb = $resource->symb();
8722: } else {
8723: $res_error = 1;
8724: last;
8725: }
8726: if ((exists($grader_randomlists_by_symb{$ressymb})) ||
8727: (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
8728: my $currcode;
8729: if (exists($grader_randomlists_by_symb{$ressymb})) {
8730: $currcode = $scancode;
8731: }
8732: my ($analysis,$parts) =
8733: &scantron_partids_tograde($resource,$env{'request.course.id'},
8734: $uname,$udom,undef,$bubbles_per_row,
8735: $currcode);
8736: $partids_by_symb{$ressymb} = $parts;
8737: } else {
8738: $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
8739: }
8740: }
8741:
8742: if ($res_error) {
8743: &scantron_add_delay(\@delayqueue,$line,
8744: 'An error occurred while grading student '.$uname,2);
8745: next;
8746: }
8747:
8748: &Apache::lonxml::clear_problem_counter();
8749: &Apache::lonnet::appenv($scan_record);
8750:
8751: if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
8752: &scantron_putfile($scanlines,$scan_data);
8753: }
8754:
8755: if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
8756: \@mapresources,\%partids_by_symb,
8757: $bubbles_per_row,$randomorder,$randompick,
8758: \%respnumlookup,\%startline)
8759: eq 'ssi_error') {
8760: $ssi_error = 0; # So end of handler error message does not trigger.
8761: $r->print("</form>");
8762: &ssi_print_error($r);
8763: &Apache::lonnet::remove_lock($lock);
8764: return ''; # Why return ''? Beats me.
8765: }
8766:
8767: if (($scancode) && ($randomorder || $randompick)) {
8768: my $parmresult =
8769: &Apache::lonparmset::storeparm_by_symb($symb,
8770: '0_examcode',2,$scancode,
8771: 'string_examcode',$uname,
8772: $udom);
8773: }
8774: $completedstudents{$uname}={'line'=>$line};
8775: if ($env{'form.verifyrecord'}) {
8776: my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
8777: if ($randompick) {
8778: if ($total) {
8779: $lastpos = $total*$scantron_config{'Qlength'};
8780: }
8781: }
8782:
8783: my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
8784: chomp($studentdata);
8785: $studentdata =~ s/\r$//;
8786: my $studentrecord = '';
8787: my $counter = -1;
8788: foreach my $resource (@mapresources) {
8789: my $ressymb = $resource->symb();
8790: ($counter,my $recording) =
8791: &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
8792: $counter,$studentdata,$partids_by_symb{$ressymb},
8793: \%scantron_config,\%lettdig,$numletts,$randomorder,
8794: $randompick,\%respnumlookup,\%startline);
8795: $studentrecord .= $recording;
8796: }
8797: if ($studentrecord ne $studentdata) {
8798: &Apache::lonxml::clear_problem_counter();
8799: if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
8800: \@mapresources,\%partids_by_symb,
8801: $bubbles_per_row,$randomorder,$randompick,
8802: \%respnumlookup,\%startline)
8803: eq 'ssi_error') {
8804: $ssi_error = 0; # So end of handler error message does not trigger.
8805: $r->print("</form>");
8806: &ssi_print_error($r);
8807: &Apache::lonnet::remove_lock($lock);
8808: delete($completedstudents{$uname});
8809: return '';
8810: }
8811: $counter = -1;
8812: $studentrecord = '';
8813: foreach my $resource (@mapresources) {
8814: my $ressymb = $resource->symb();
8815: ($counter,my $recording) =
8816: &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
8817: $counter,$studentdata,$partids_by_symb{$ressymb},
8818: \%scantron_config,\%lettdig,$numletts,
8819: $randomorder,$randompick,\%respnumlookup,
8820: \%startline);
8821: $studentrecord .= $recording;
8822: }
8823: if ($studentrecord ne $studentdata) {
8824: $r->print('<p><span class="LC_warning">');
8825: if ($scancode eq '') {
8826: $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
8827: $uname.':'.$udom,$scan_record->{'scantron.ID'}));
8828: } else {
8829: $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
8830: $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
8831: }
8832: $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
8833: &Apache::loncommon::start_data_table_header_row()."\n".
8834: '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
8835: &Apache::loncommon::end_data_table_header_row()."\n".
8836: &Apache::loncommon::start_data_table_row().
8837: '<td>'.&mt('Bubblesheet').'</td>'.
8838: '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
8839: &Apache::loncommon::end_data_table_row().
8840: &Apache::loncommon::start_data_table_row().
8841: '<td>'.&mt('Stored submissions').'</td>'.
8842: '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
8843: &Apache::loncommon::end_data_table_row().
8844: &Apache::loncommon::end_data_table().'</p>');
8845: } else {
8846: $r->print('<br /><span class="LC_warning">'.
8847: &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 />'.
8848: &mt("As a consequence, this user's submission history records two tries.").
8849: '</span><br />');
8850: }
8851: }
8852: }
8853: if (&Apache::loncommon::connection_aborted($r)) { last; }
8854: } continue {
8855: &Apache::lonxml::clear_problem_counter();
8856: &Apache::lonnet::delenv('scantron.');
8857: }
8858: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
8859: &Apache::lonnet::remove_lock($lock);
8860: # my $lasttime = &Time::HiRes::time()-$start;
8861: # $r->print("<p>took $lasttime</p>");
8862:
8863: $r->print("</form>");
8864: return '';
8865: }
8866:
8867: sub graders_resources_pass {
8868: my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
8869: $bubbles_per_row) = @_;
8870: if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) &&
8871: (ref($grader_randomlists_by_symb) eq 'HASH')) {
8872: foreach my $resource (@{$resources}) {
8873: my $ressymb = $resource->symb();
8874: my ($analysis,$parts) =
8875: &scantron_partids_tograde($resource,$env{'request.course.id'},
8876: $env{'user.name'},$env{'user.domain'},
8877: 1,$bubbles_per_row);
8878: $grader_partids_by_symb->{$ressymb} = $parts;
8879: if (ref($analysis) eq 'HASH') {
8880: if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
8881: $grader_randomlists_by_symb->{$ressymb} =
8882: $analysis->{'parts_withrandomlist'};
8883: }
8884: }
8885: }
8886: }
8887: return;
8888: }
8889:
8890: =pod
8891:
8892: =item users_order
8893:
8894: Returns array of resources in current map, ordered based on either CODE,
8895: if this is a CODEd exam, or based on student's identity if this is a
8896: "NAMEd" exam.
8897:
8898: Should be used when randomorder and/or randompick applied when the
8899: corresponding exam was printed, prior to students completing bubblesheets
8900: for the version of the exam the student received.
8901:
8902: =cut
8903:
8904: sub users_order {
8905: my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
8906: my @mapresources;
8907: unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
8908: return @mapresources;
8909: }
8910: if ($scancode) {
8911: if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
8912: @mapresources = @{$orderedforcode->{$scancode}};
8913: } else {
8914: $env{'form.CODE'} = $scancode;
8915: my $actual_seq =
8916: &Apache::lonprintout::master_seq_to_person_seq($mapurl,
8917: $master_seq,
8918: $user,$scancode,1);
8919: if (ref($actual_seq) eq 'ARRAY') {
8920: @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
8921: if (ref($orderedforcode) eq 'HASH') {
8922: if (@mapresources > 0) {
8923: $orderedforcode->{$scancode} = \@mapresources;
8924: }
8925: }
8926: }
8927: delete($env{'form.CODE'});
8928: }
8929: } else {
8930: my $actual_seq =
8931: &Apache::lonprintout::master_seq_to_person_seq($mapurl,
8932: $master_seq,
8933: $user,undef,1);
8934: if (ref($actual_seq) eq 'ARRAY') {
8935: @mapresources =
8936: map { $symb_to_resource->{$_}; } @{$actual_seq};
8937: }
8938: }
8939: return @mapresources;
8940: }
8941:
8942: sub grade_student_bubbles {
8943: my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
8944: $randomorder,$randompick,$respnumlookup,$startline) = @_;
8945: my $uselookup = 0;
8946: if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
8947: (ref($startline) eq 'HASH')) {
8948: $uselookup = 1;
8949: }
8950:
8951: if (ref($resources) eq 'ARRAY') {
8952: my $count = 0;
8953: foreach my $resource (@{$resources}) {
8954: my $ressymb = $resource->symb();
8955: my %form = ('submitted' => 'scantron',
8956: 'grade_target' => 'grade',
8957: 'grade_username' => $uname,
8958: 'grade_domain' => $udom,
8959: 'grade_courseid' => $env{'request.course.id'},
8960: 'grade_symb' => $ressymb,
8961: 'CODE' => $scancode
8962: );
8963: if ($bubbles_per_row ne '') {
8964: $form{'bubbles_per_row'} = $bubbles_per_row;
8965: }
8966: if ($env{'form.scantron_lastbubblepoints'} ne '') {
8967: $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
8968: }
8969: if (ref($parts) eq 'HASH') {
8970: if (ref($parts->{$ressymb}) eq 'ARRAY') {
8971: foreach my $part (@{$parts->{$ressymb}}) {
8972: if ($uselookup) {
8973: $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
8974: } else {
8975: $form{'scantron_questnum_start.'.$part} =
8976: 1+$env{'form.scantron.first_bubble_line.'.$count};
8977: }
8978: $count++;
8979: }
8980: }
8981: }
8982: my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
8983: return 'ssi_error' if ($ssi_error);
8984: last if (&Apache::loncommon::connection_aborted($r));
8985: }
8986: }
8987: return;
8988: }
8989:
8990: sub scantron_upload_scantron_data {
8991: my ($r,$symb)=@_;
8992: my $dom = $env{'request.role.domain'};
8993: my $domdesc = &Apache::lonnet::domain($dom,'description');
8994: $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
8995: my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
8996: 'domainid',
8997: 'coursename',$dom);
8998: my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
8999: (' 'x2).&mt('(shows course personnel)');
9000: my $default_form_data=&defaultFormData($symb);
9001: my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
9002: &js_escape(\$nofile_alert);
9003: 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.");
9004: &js_escape(\$nocourseid_alert);
9005: $r->print(&Apache::lonhtmlcommon::scripttag('
9006: function checkUpload(formname) {
9007: if (formname.upfile.value == "") {
9008: alert("'.$nofile_alert.'");
9009: return false;
9010: }
9011: if (formname.courseid.value == "") {
9012: alert("'.$nocourseid_alert.'");
9013: return false;
9014: }
9015: formname.submit();
9016: }
9017:
9018: function ToSyllabus() {
9019: var cdom = '."'$dom'".';
9020: var cnum = document.rules.courseid.value;
9021: if (cdom == "" || cdom == null) {
9022: return;
9023: }
9024: if (cnum == "" || cnum == null) {
9025: return;
9026: }
9027: syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
9028: "height=350,width=350,scrollbars=yes,menubar=no");
9029: return;
9030: }
9031:
9032: '));
9033: $r->print('
9034: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
9035:
9036: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
9037: '.$default_form_data.
9038: &Apache::lonhtmlcommon::start_pick_box().
9039: &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
9040: '<input name="courseid" type="text" size="30" />'.$select_link.
9041: &Apache::lonhtmlcommon::row_closure().
9042: &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
9043: '<input name="coursename" type="text" size="30" />'.$syllabuslink.
9044: &Apache::lonhtmlcommon::row_closure().
9045: &Apache::lonhtmlcommon::row_title(&mt('Domain')).
9046: '<input name="domainid" type="hidden" />'.$domdesc.
9047: &Apache::lonhtmlcommon::row_closure().
9048: &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
9049: '<input type="file" name="upfile" size="50" />'.
9050: &Apache::lonhtmlcommon::row_closure(1).
9051: &Apache::lonhtmlcommon::end_pick_box().'<br />
9052:
9053: <input name="command" value="scantronupload_save" type="hidden" />
9054: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
9055: </form>
9056: ');
9057: return '';
9058: }
9059:
9060:
9061: sub scantron_upload_scantron_data_save {
9062: my($r,$symb)=@_;
9063: my $doanotherupload=
9064: '<br /><form action="/adm/grades" method="post">'."\n".
9065: '<input type="hidden" name="command" value="scantronupload" />'."\n".
9066: '<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
9067: '</form>'."\n";
9068: if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
9069: !&Apache::lonnet::allowed('usc',
9070: $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
9071: $r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
9072: unless ($symb) {
9073: $r->print($doanotherupload);
9074: }
9075: return '';
9076: }
9077: my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
9078: my $uploadedfile;
9079: $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
9080: if (length($env{'form.upfile'}) < 2) {
9081: $r->print(
9082: &Apache::lonhtmlcommon::confirm_success(
9083: &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
9084: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
9085: } else {
9086: my $result =
9087: &Apache::lonnet::userfileupload('upfile','','scantron','','','',
9088: $env{'form.courseid'},$env{'form.domainid'});
9089: if ($result =~ m{^/uploaded/}) {
9090: $r->print(
9091: &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
9092: &mt('Uploaded [_1] bytes of data into location: [_2]',
9093: (length($env{'form.upfile'})-1),
9094: '<span class="LC_filename">'.$result.'</span>'));
9095: ($uploadedfile) = ($result =~ m{/([^/]+)$});
9096: $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
9097: $env{'form.courseid'},$uploadedfile));
9098: } else {
9099: $r->print(
9100: &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
9101: &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
9102: $result,
9103: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
9104: }
9105: }
9106: if ($symb) {
9107: $r->print(&scantron_selectphase($r,$uploadedfile,$symb));
9108: } else {
9109: $r->print($doanotherupload);
9110: }
9111: return '';
9112: }
9113:
9114: sub validate_uploaded_scantron_file {
9115: my ($cdom,$cname,$fname) = @_;
9116: my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
9117: my @lines;
9118: if ($scanlines ne '-1') {
9119: @lines=split("\n",$scanlines,-1);
9120: }
9121: my $output;
9122: if (@lines) {
9123: my (%counts,$max_match_format);
9124: my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
9125: my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
9126: my %idmap = &username_to_idmap($classlist);
9127: foreach my $key (keys(%idmap)) {
9128: my $lckey = lc($key);
9129: $idmap{$lckey} = $idmap{$key};
9130: }
9131: my %unique_formats;
9132: my @formatlines = &get_scantronformat_file();
9133: foreach my $line (@formatlines) {
9134: chomp($line);
9135: my @config = split(/:/,$line);
9136: my $idstart = $config[5];
9137: my $idlength = $config[6];
9138: if (($idstart ne '') && ($idlength > 0)) {
9139: if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
9140: push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]);
9141: } else {
9142: $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
9143: }
9144: }
9145: }
9146: foreach my $key (keys(%unique_formats)) {
9147: my ($idstart,$idlength) = split(':',$key);
9148: %{$counts{$key}} = (
9149: 'found' => 0,
9150: 'total' => 0,
9151: );
9152: foreach my $line (@lines) {
9153: next if ($line =~ /^#/);
9154: next if ($line =~ /^[\s\cz]*$/);
9155: my $id = substr($line,$idstart-1,$idlength);
9156: $id = lc($id);
9157: if (exists($idmap{$id})) {
9158: $counts{$key}{'found'} ++;
9159: }
9160: $counts{$key}{'total'} ++;
9161: }
9162: if ($counts{$key}{'total'}) {
9163: my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
9164: if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
9165: $max_match_pct = $percent_match;
9166: $max_match_format = $key;
9167: $found_match_count = $counts{$key}{'found'};
9168: $max_match_count = $counts{$key}{'total'};
9169: }
9170: }
9171: }
9172: if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
9173: my $format_descs;
9174: my $numwithformat = @{$unique_formats{$max_match_format}};
9175: for (my $i=0; $i<$numwithformat; $i++) {
9176: my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
9177: if ($i<$numwithformat-2) {
9178: $format_descs .= '"<i>'.$desc.'</i>", ';
9179: } elsif ($i==$numwithformat-2) {
9180: $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
9181: } elsif ($i==$numwithformat-1) {
9182: $format_descs .= '"<i>'.$desc.'</i>"';
9183: }
9184: }
9185: my $showpct = sprintf("%.0f",$max_match_pct).'%';
9186: $output .= '<br />';
9187: if ($found_match_count == $max_match_count) {
9188: # 100% matching entries
9189: $output .= &Apache::lonhtmlcommon::confirm_success(
9190: &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
9191: '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
9192: &mt('Comparison of student IDs in the uploaded file with'.
9193: ' the course roster found matches for [_1] of the [_2] entries'.
9194: ' in the file (for the format defined for [_3]).',
9195: '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
9196: } else {
9197: # Not all entries matching? -> Show warning and additional info
9198: $output .=
9199: &Apache::lonhtmlcommon::confirm_success(
9200: &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
9201: '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
9202: &mt('Not all entries could be matched!'),1).'<br />'.
9203: &mt('Comparison of student IDs in the uploaded file with'.
9204: ' the course roster found matches for [_1] of the [_2] entries'.
9205: ' in the file (for the format defined for [_3]).',
9206: '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
9207: '<p class="LC_info">'.
9208: &mt('A low percentage of matches results from one of the following:').
9209: '</p><ul>'.
9210: '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
9211: '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
9212: '<i>'.$cdom.'</i>').'</li>'.
9213: '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
9214: '<li>'.&mt('The course roster is not up to date.').'</li>'.
9215: '</ul>';
9216: }
9217: }
9218: } else {
9219: $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
9220: }
9221: return $output;
9222: }
9223:
9224: sub valid_file {
9225: my ($requested_file)=@_;
9226: foreach my $filename (sort(&scantron_filenames())) {
9227: if ($requested_file eq $filename) { return 1; }
9228: }
9229: return 0;
9230: }
9231:
9232: sub scantron_download_scantron_data {
9233: my ($r,$symb)=@_;
9234: my $default_form_data=&defaultFormData($symb);
9235: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
9236: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
9237: my $file=$env{'form.scantron_selectfile'};
9238: if (! &valid_file($file)) {
9239: $r->print('
9240: <p>
9241: '.&mt('The requested filename was invalid.').'
9242: </p>
9243: ');
9244: return;
9245: }
9246: my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
9247: my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
9248: my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
9249: &Apache::lonnet::allowuploaded('/adm/grades',$orig);
9250: &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
9251: &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
9252: $r->print('
9253: <p>
9254: '.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
9255: '<a href="'.$orig.'">','</a>').'
9256: </p>
9257: <p>
9258: '.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
9259: '<a href="'.$corrected.'">','</a>').'
9260: </p>
9261: <p>
9262: '.&mt('[_1]Skipped[_2], a file of records that were skipped.',
9263: '<a href="'.$skipped.'">','</a>').'
9264: </p>
9265: ');
9266: return '';
9267: }
9268:
9269: sub checkscantron_results {
9270: my ($r,$symb) = @_;
9271: if (!$symb) {return '';}
9272: my $cid = $env{'request.course.id'};
9273: my %lettdig = &letter_to_digits();
9274: my $numletts = scalar(keys(%lettdig));
9275: my $cnum = $env{'course.'.$cid.'.num'};
9276: my $cdom = $env{'course.'.$cid.'.domain'};
9277: my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
9278: my %record;
9279: my %scantron_config =
9280: &Apache::grades::get_scantron_config($env{'form.scantron_format'});
9281: my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
9282: my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
9283: my $classlist=&Apache::loncoursedata::get_classlist();
9284: my %idmap=&Apache::grades::username_to_idmap($classlist);
9285: my $navmap=Apache::lonnavmaps::navmap->new();
9286: unless (ref($navmap)) {
9287: $r->print(&navmap_errormsg());
9288: return '';
9289: }
9290: my $map=$navmap->getResourceByUrl($sequence);
9291: my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
9292: %grader_randomlists_by_symb,%orderedforcode);
9293: if (ref($map)) {
9294: $randomorder=$map->randomorder();
9295: $randompick=$map->randompick();
9296: }
9297: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
9298: my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
9299: if ($nav_error) {
9300: $r->print(&navmap_errormsg());
9301: return '';
9302: }
9303: &graders_resources_pass(\@resources,\%grader_partids_by_symb,
9304: \%grader_randomlists_by_symb,$bubbles_per_row);
9305: my ($uname,$udom);
9306: my (%scandata,%lastname,%bylast);
9307: $r->print('
9308: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
9309:
9310: my @delayqueue;
9311: my %completedstudents;
9312:
9313: my $count=&get_todo_count($scanlines,$scan_data);
9314: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
9315: my ($username,$domain,$started);
9316: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
9317: if ($nav_error) {
9318: $r->print(&navmap_errormsg());
9319: return '';
9320: }
9321:
9322: &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
9323: my $start=&Time::HiRes::time();
9324: my $i=-1;
9325:
9326: while ($i<$scanlines->{'count'}) {
9327: ($username,$domain,$uname)=('','','');
9328: $i++;
9329: my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
9330: if ($line=~/^[\s\cz]*$/) { next; }
9331: if ($started) {
9332: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
9333: }
9334: $started=1;
9335: my $scan_record=
9336: &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
9337: $scan_data);
9338: unless ($uname=&scantron_find_student($scan_record,$scan_data,
9339: \%idmap,$i)) {
9340: &Apache::grades::scantron_add_delay(\@delayqueue,$line,
9341: 'Unable to find a student that matches',1);
9342: next;
9343: }
9344: if (exists $completedstudents{$uname}) {
9345: &Apache::grades::scantron_add_delay(\@delayqueue,$line,
9346: 'Student '.$uname.' has multiple sheets',2);
9347: next;
9348: }
9349: my $pid = $scan_record->{'scantron.ID'};
9350: $lastname{$pid} = $scan_record->{'scantron.LastName'};
9351: push(@{$bylast{$lastname{$pid}}},$pid);
9352: my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
9353: my $user = $uname.':'.$usec;
9354: ($username,$domain)=split(/:/,$uname);
9355:
9356: my $scancode;
9357: if ((exists($scan_record->{'scantron.CODE'})) &&
9358: (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
9359: $scancode = $scan_record->{'scantron.CODE'};
9360: } else {
9361: $scancode = '';
9362: }
9363:
9364: my @mapresources = @resources;
9365: my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
9366: my %respnumlookup=();
9367: my %startline=();
9368: if ($randomorder || $randompick) {
9369: @mapresources =
9370: &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
9371: \%orderedforcode);
9372: my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
9373: $scan_record,\@master_seq,\%symb_to_resource,
9374: \%grader_partids_by_symb,\%orderedforcode,
9375: \%respnumlookup,\%startline);
9376: if ($randompick && $total) {
9377: $lastpos = $total*$scantron_config{'Qlength'};
9378: }
9379: }
9380: $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
9381: chomp($scandata{$pid});
9382: $scandata{$pid} =~ s/\r$//;
9383:
9384: my $counter = -1;
9385: foreach my $resource (@mapresources) {
9386: my $parts;
9387: my $ressymb = $resource->symb();
9388: if ((exists($grader_randomlists_by_symb{$ressymb})) ||
9389: (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
9390: my $currcode;
9391: if (exists($grader_randomlists_by_symb{$ressymb})) {
9392: $currcode = $scancode;
9393: }
9394: (my $analysis,$parts) =
9395: &scantron_partids_tograde($resource,$env{'request.course.id'},
9396: $username,$domain,undef,
9397: $bubbles_per_row,$currcode);
9398: } else {
9399: $parts = $grader_partids_by_symb{$ressymb};
9400: }
9401: ($counter,my $recording) =
9402: &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
9403: $scandata{$pid},$parts,
9404: \%scantron_config,\%lettdig,$numletts,
9405: $randomorder,$randompick,
9406: \%respnumlookup,\%startline);
9407: $record{$pid} .= $recording;
9408: }
9409: }
9410: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
9411: $r->print('<br />');
9412: my ($okstudents,$badstudents,$numstudents,$passed,$failed);
9413: $passed = 0;
9414: $failed = 0;
9415: $numstudents = 0;
9416: foreach my $last (sort(keys(%bylast))) {
9417: if (ref($bylast{$last}) eq 'ARRAY') {
9418: foreach my $pid (sort(@{$bylast{$last}})) {
9419: my $showscandata = $scandata{$pid};
9420: my $showrecord = $record{$pid};
9421: $showscandata =~ s/\s/ /g;
9422: $showrecord =~ s/\s/ /g;
9423: if ($scandata{$pid} eq $record{$pid}) {
9424: my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
9425: $okstudents .= '<tr class="'.$css_class.'">'.
9426: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
9427: '</tr>'."\n".
9428: '<tr class="'.$css_class.'">'."\n".
9429: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
9430: $passed ++;
9431: } else {
9432: my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
9433: $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".
9434: '</tr>'."\n".
9435: '<tr class="'.$css_class.'">'."\n".
9436: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
9437: '</tr>'."\n";
9438: $failed ++;
9439: }
9440: $numstudents ++;
9441: }
9442: }
9443: }
9444: $r->print(
9445: '<p>'
9446: .&mt('Comparison of bubblesheet data (including corrections) with corresponding submission records (most recent submission) for [_1][quant,_2,student][_3] ([quant,_4,bubblesheet line] per student).',
9447: '<b>',
9448: $numstudents,
9449: '</b>',
9450: $env{'form.scantron_maxbubble'})
9451: .'</p>'
9452: );
9453: $r->print('<p>'
9454: .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
9455: .'<br />'
9456: .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
9457: .'</p>'
9458: );
9459: if ($passed) {
9460: $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
9461: $r->print(&Apache::loncommon::start_data_table()."\n".
9462: &Apache::loncommon::start_data_table_header_row()."\n".
9463: '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
9464: &Apache::loncommon::end_data_table_header_row()."\n".
9465: $okstudents."\n".
9466: &Apache::loncommon::end_data_table().'<br />');
9467: }
9468: if ($failed) {
9469: $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
9470: $r->print(&Apache::loncommon::start_data_table()."\n".
9471: &Apache::loncommon::start_data_table_header_row()."\n".
9472: '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
9473: &Apache::loncommon::end_data_table_header_row()."\n".
9474: $badstudents."\n".
9475: &Apache::loncommon::end_data_table()).'<br />'.
9476: &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.');
9477: }
9478: $r->print('</form><br />');
9479: return;
9480: }
9481:
9482: sub verify_scantron_grading {
9483: my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
9484: $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
9485: $respnumlookup,$startline) = @_;
9486: my ($record,%expected,%startpos);
9487: return ($counter,$record) if (!ref($resource));
9488: return ($counter,$record) if (!$resource->is_problem());
9489: my $symb = $resource->symb();
9490: return ($counter,$record) if (ref($partids) ne 'ARRAY');
9491: foreach my $part_id (@{$partids}) {
9492: $counter ++;
9493: $expected{$part_id} = 0;
9494: my $respnum = $counter;
9495: if ($randomorder || $randompick) {
9496: $respnum = $respnumlookup->{$counter};
9497: $startpos{$part_id} = $startline->{$counter} + 1;
9498: } else {
9499: $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
9500: }
9501: if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
9502: my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
9503: foreach my $item (@sub_lines) {
9504: $expected{$part_id} += $item;
9505: }
9506: } else {
9507: $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
9508: }
9509: }
9510: if ($symb) {
9511: my %recorded;
9512: my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
9513: if ($returnhash{'version'}) {
9514: my %lasthash=();
9515: my $version;
9516: for ($version=1;$version<=$returnhash{'version'};$version++) {
9517: foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
9518: $lasthash{$key}=$returnhash{$version.':'.$key};
9519: }
9520: }
9521: foreach my $key (keys(%lasthash)) {
9522: if ($key =~ /\.scantron$/) {
9523: my $value = &unescape($lasthash{$key});
9524: my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
9525: if ($value eq '') {
9526: for (my $i=0; $i<$expected{$part_id}; $i++) {
9527: for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
9528: $recorded{$part_id} .= $scantron_config->{'Qoff'};
9529: }
9530: }
9531: } else {
9532: my @tocheck;
9533: my @items = split(//,$value);
9534: if (($scantron_config->{'Qon'} eq 'letter') ||
9535: ($scantron_config->{'Qon'} eq 'number')) {
9536: if (@items < $expected{$part_id}) {
9537: my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
9538: my @singles = split(//,$fragment);
9539: foreach my $pos (@singles) {
9540: if ($pos eq ' ') {
9541: push(@tocheck,$pos);
9542: } else {
9543: my $next = shift(@items);
9544: push(@tocheck,$next);
9545: }
9546: }
9547: } else {
9548: @tocheck = @items;
9549: }
9550: foreach my $letter (@tocheck) {
9551: if ($scantron_config->{'Qon'} eq 'letter') {
9552: if ($letter !~ /^[A-J]$/) {
9553: $letter = $scantron_config->{'Qoff'};
9554: }
9555: $recorded{$part_id} .= $letter;
9556: } elsif ($scantron_config->{'Qon'} eq 'number') {
9557: my $digit;
9558: if ($letter !~ /^[A-J]$/) {
9559: $digit = $scantron_config->{'Qoff'};
9560: } else {
9561: $digit = $lettdig->{$letter};
9562: }
9563: $recorded{$part_id} .= $digit;
9564: }
9565: }
9566: } else {
9567: @tocheck = @items;
9568: for (my $i=0; $i<$expected{$part_id}; $i++) {
9569: my $curr_sub = shift(@tocheck);
9570: my $digit;
9571: if ($curr_sub =~ /^[A-J]$/) {
9572: $digit = $lettdig->{$curr_sub}-1;
9573: }
9574: if ($curr_sub eq 'J') {
9575: $digit += scalar($numletts);
9576: }
9577: for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
9578: if ($j == $digit) {
9579: $recorded{$part_id} .= $scantron_config->{'Qon'};
9580: } else {
9581: $recorded{$part_id} .= $scantron_config->{'Qoff'};
9582: }
9583: }
9584: }
9585: }
9586: }
9587: }
9588: }
9589: }
9590: foreach my $part_id (@{$partids}) {
9591: if ($recorded{$part_id} eq '') {
9592: for (my $i=0; $i<$expected{$part_id}; $i++) {
9593: for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
9594: $recorded{$part_id} .= $scantron_config->{'Qoff'};
9595: }
9596: }
9597: }
9598: $record .= $recorded{$part_id};
9599: }
9600: }
9601: return ($counter,$record);
9602: }
9603:
9604: sub letter_to_digits {
9605: my %lettdig = (
9606: A => 1,
9607: B => 2,
9608: C => 3,
9609: D => 4,
9610: E => 5,
9611: F => 6,
9612: G => 7,
9613: H => 8,
9614: I => 9,
9615: J => 0,
9616: );
9617: return %lettdig;
9618: }
9619:
9620:
9621: #-------- end of section for handling grading scantron forms -------
9622: #
9623: #-------------------------------------------------------------------
9624:
9625: #-------------------------- Menu interface -------------------------
9626: #
9627: #--- Href with symb and command ---
9628:
9629: sub href_symb_cmd {
9630: my ($symb,$cmd)=@_;
9631: return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&command='.$cmd;
9632: }
9633:
9634: sub grading_menu {
9635: my ($request,$symb) = @_;
9636: if (!$symb) {return '';}
9637:
9638: my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
9639: 'command'=>'individual');
9640:
9641: my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
9642:
9643: $fields{'command'}='ungraded';
9644: my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
9645:
9646: $fields{'command'}='table';
9647: my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
9648:
9649: $fields{'command'}='all_for_one';
9650: my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
9651:
9652: $fields{'command'}='downloadfilesselect';
9653: my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
9654:
9655: $fields{'command'} = 'csvform';
9656: my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
9657:
9658: $fields{'command'} = 'processclicker';
9659: my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
9660:
9661: $fields{'command'} = 'scantron_selectphase';
9662: my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
9663:
9664: $fields{'command'} = 'initialverifyreceipt';
9665: my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
9666:
9667: my @menu = ({ categorytitle=>'Hand Grading',
9668: items =>[
9669: { linktext => 'Select individual students to grade',
9670: url => $url1a,
9671: permission => 'F',
9672: icon => 'grade_students.png',
9673: linktitle => 'Grade current resource for a selection of students.'
9674: },
9675: { linktext => 'Grade ungraded submissions.',
9676: url => $url1b,
9677: permission => 'F',
9678: icon => 'ungrade_sub.png',
9679: linktitle => 'Grade all submissions that have not been graded yet.'
9680: },
9681:
9682: { linktext => 'Grading table',
9683: url => $url1c,
9684: permission => 'F',
9685: icon => 'grading_table.png',
9686: linktitle => 'Grade current resource for all students.'
9687: },
9688: { linktext => 'Grade page/folder for one student',
9689: url => $url1d,
9690: permission => 'F',
9691: icon => 'grade_PageFolder.png',
9692: linktitle => 'Grade all resources in current page/sequence/folder for one student.'
9693: },
9694: { linktext => 'Download submissions',
9695: url => $url1e,
9696: permission => 'F',
9697: icon => 'download_sub.png',
9698: linktitle => 'Download all students submissions.'
9699: }]},
9700: { categorytitle=>'Automated Grading',
9701: items =>[
9702:
9703: { linktext => 'Upload Scores',
9704: url => $url2,
9705: permission => 'F',
9706: icon => 'uploadscores.png',
9707: linktitle => 'Specify a file containing the class scores for current resource.'
9708: },
9709: { linktext => 'Process Clicker',
9710: url => $url3,
9711: permission => 'F',
9712: icon => 'addClickerInfoFile.png',
9713: linktitle => 'Specify a file containing the clicker information for this resource.'
9714: },
9715: { linktext => 'Grade/Manage/Review Bubblesheets',
9716: url => $url4,
9717: permission => 'F',
9718: icon => 'bubblesheet.png',
9719: linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
9720: },
9721: { linktext => 'Verify Receipt Number',
9722: url => $url5,
9723: permission => 'F',
9724: icon => 'receipt_number.png',
9725: linktitle => 'Verify a system-generated receipt number for correct problem solution.'
9726: }
9727:
9728: ]
9729: });
9730:
9731: # Create the menu
9732: my $Str;
9733: $Str .= '<form method="post" action="" name="gradingMenu">';
9734: $Str .= '<input type="hidden" name="command" value="" />'.
9735: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
9736:
9737: $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
9738: return $Str;
9739: }
9740:
9741:
9742: sub ungraded {
9743: my ($request)=@_;
9744: &submit_options($request);
9745: }
9746:
9747: sub submit_options_sequence {
9748: my ($request,$symb) = @_;
9749: if (!$symb) {return '';}
9750: &commonJSfunctions($request);
9751: my $result;
9752:
9753: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
9754: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
9755: $result.=&selectfield(0).
9756: '<input type="hidden" name="command" value="pickStudentPage" />
9757: <div>
9758: <input type="submit" value="'.&mt('Next').' →" />
9759: </div>
9760: </div>
9761: </form>';
9762: return $result;
9763: }
9764:
9765: sub submit_options_table {
9766: my ($request,$symb) = @_;
9767: if (!$symb) {return '';}
9768: &commonJSfunctions($request);
9769: my $is_tool = ($symb =~ /ext\.tool$/);
9770: my $result;
9771:
9772: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
9773: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
9774:
9775: $result.=&selectfield(1,$is_tool).
9776: '<input type="hidden" name="command" value="viewgrades" />
9777: <div>
9778: <input type="submit" value="'.&mt('Next').' →" />
9779: </div>
9780: </div>
9781: </form>';
9782: return $result;
9783: }
9784:
9785: sub submit_options_download {
9786: my ($request,$symb) = @_;
9787: if (!$symb) {return '';}
9788:
9789: my $is_tool = ($symb =~ /ext\.tool$/);
9790: &commonJSfunctions($request);
9791:
9792: my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
9793: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
9794: $result.='
9795: <h2>
9796: '.&mt('Select Students for Which to Download Submissions').'
9797: </h2>'.&selectfield(1,$is_tool).'
9798: <input type="hidden" name="command" value="downloadfileslink" />
9799: <input type="submit" value="'.&mt('Next').' →" />
9800: </div>
9801: </div>
9802:
9803:
9804: </form>';
9805: return $result;
9806: }
9807:
9808: #--- Displays the submissions first page -------
9809: sub submit_options {
9810: my ($request,$symb) = @_;
9811: if (!$symb) {return '';}
9812:
9813: my $is_tool = ($symb =~ /ext\.tool$/);
9814: &commonJSfunctions($request);
9815: my $result;
9816:
9817: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
9818: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
9819: $result.=&selectfield(1,$is_tool).'
9820: <input type="hidden" name="command" value="submission" />
9821: <input type="submit" value="'.&mt('Next').' →" />
9822: </div>
9823: </div>
9824:
9825:
9826: </form>';
9827: return $result;
9828: }
9829:
9830: sub selectfield {
9831: my ($full,$is_tool)=@_;
9832: my %options;
9833: if ($is_tool) {
9834: %options =
9835: (&transtatus_options,
9836: 'select_form_order' => ['yes','incorrect','all']);
9837: } else {
9838: %options =
9839: (&substatus_options,
9840: 'select_form_order' => ['yes','queued','graded','incorrect','all']);
9841: }
9842: my $result='<div class="LC_columnSection">
9843:
9844: <fieldset>
9845: <legend>
9846: '.&mt('Sections').'
9847: </legend>
9848: '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
9849: </fieldset>
9850:
9851: <fieldset>
9852: <legend>
9853: '.&mt('Groups').'
9854: </legend>
9855: '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
9856: </fieldset>
9857:
9858: <fieldset>
9859: <legend>
9860: '.&mt('Access Status').'
9861: </legend>
9862: '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
9863: </fieldset>';
9864: if ($full) {
9865: my $heading = &mt('Submission Status');
9866: if ($is_tool) {
9867: $heading = &mt('Transaction Status');
9868: }
9869: $result.='
9870: <fieldset>
9871: <legend>
9872: '.$heading.'
9873: </legend>'.
9874: &Apache::loncommon::select_form('all','submitonly',\%options).
9875: '</fieldset>';
9876: }
9877: $result.='</div><br />';
9878: return $result;
9879: }
9880:
9881: sub substatus_options {
9882: return &Apache::lonlocal::texthash(
9883: 'yes' => 'with submissions',
9884: 'queued' => 'in grading queue',
9885: 'graded' => 'with ungraded submissions',
9886: 'incorrect' => 'with incorrect submissions',
9887: 'all' => 'with any status',
9888: );
9889: }
9890:
9891: sub transtatus_options {
9892: return &Apache::lonlocal::texthash(
9893: 'yes' => 'with score transactions',
9894: 'incorrect' => 'with less than full credit',
9895: 'all' => 'with any status',
9896: );
9897: }
9898:
9899: sub reset_perm {
9900: undef(%perm);
9901: }
9902:
9903: sub init_perm {
9904: &reset_perm();
9905: foreach my $test_perm ('vgr','mgr','opa') {
9906:
9907: my $scope = $env{'request.course.id'};
9908: if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
9909:
9910: $scope .= '/'.$env{'request.course.sec'};
9911: if ( $perm{$test_perm}=
9912: &Apache::lonnet::allowed($test_perm,$scope)) {
9913: $perm{$test_perm.'_section'}=$env{'request.course.sec'};
9914: } else {
9915: delete($perm{$test_perm});
9916: }
9917: }
9918: }
9919: }
9920:
9921: sub init_old_essays {
9922: my ($symb,$apath,$adom,$aname) = @_;
9923: if ($symb ne '') {
9924: my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
9925: if (keys(%essays) > 0) {
9926: $old_essays{$symb} = \%essays;
9927: }
9928: }
9929: return;
9930: }
9931:
9932: sub reset_old_essays {
9933: undef(%old_essays);
9934: }
9935:
9936: sub gather_clicker_ids {
9937: my %clicker_ids;
9938:
9939: my $classlist = &Apache::loncoursedata::get_classlist();
9940:
9941: # Set up a couple variables.
9942: my $username_idx = &Apache::loncoursedata::CL_SNAME();
9943: my $domain_idx = &Apache::loncoursedata::CL_SDOM();
9944: my $status_idx = &Apache::loncoursedata::CL_STATUS();
9945:
9946: foreach my $student (keys(%$classlist)) {
9947: if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
9948: my $username = $classlist->{$student}->[$username_idx];
9949: my $domain = $classlist->{$student}->[$domain_idx];
9950: my $clickers =
9951: (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
9952: foreach my $id (split(/\,/,$clickers)) {
9953: $id=~s/^[\#0]+//;
9954: $id=~s/[\-\:]//g;
9955: if (exists($clicker_ids{$id})) {
9956: $clicker_ids{$id}.=','.$username.':'.$domain;
9957: } else {
9958: $clicker_ids{$id}=$username.':'.$domain;
9959: }
9960: }
9961: }
9962: return %clicker_ids;
9963: }
9964:
9965: sub gather_adv_clicker_ids {
9966: my %clicker_ids;
9967: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
9968: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
9969: my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
9970: foreach my $element (sort(keys(%coursepersonnel))) {
9971: foreach my $person (split(/\,/,$coursepersonnel{$element})) {
9972: my ($puname,$pudom)=split(/\:/,$person);
9973: my $clickers =
9974: (&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
9975: foreach my $id (split(/\,/,$clickers)) {
9976: $id=~s/^[\#0]+//;
9977: $id=~s/[\-\:]//g;
9978: if (exists($clicker_ids{$id})) {
9979: $clicker_ids{$id}.=','.$puname.':'.$pudom;
9980: } else {
9981: $clicker_ids{$id}=$puname.':'.$pudom;
9982: }
9983: }
9984: }
9985: }
9986: return %clicker_ids;
9987: }
9988:
9989: sub clicker_grading_parameters {
9990: return ('gradingmechanism' => 'scalar',
9991: 'upfiletype' => 'scalar',
9992: 'specificid' => 'scalar',
9993: 'pcorrect' => 'scalar',
9994: 'pincorrect' => 'scalar');
9995: }
9996:
9997: sub process_clicker {
9998: my ($r,$symb)=@_;
9999: if (!$symb) {return '';}
10000: my $result=&checkforfile_js();
10001: $result.=&Apache::loncommon::start_data_table().
10002: &Apache::loncommon::start_data_table_header_row().
10003: '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
10004: &Apache::loncommon::end_data_table_header_row().
10005: &Apache::loncommon::start_data_table_row()."<td>\n";
10006: # Attempt to restore parameters from last session, set defaults if not present
10007: my %Saveable_Parameters=&clicker_grading_parameters();
10008: &Apache::loncommon::restore_course_settings('grades_clicker',
10009: \%Saveable_Parameters);
10010: if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
10011: if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
10012: if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
10013: if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
10014:
10015: my %checked;
10016: foreach my $gradingmechanism ('attendance','personnel','specific','given') {
10017: if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
10018: $checked{$gradingmechanism}=' checked="checked"';
10019: }
10020: }
10021:
10022: my $upload=&mt("Evaluate File");
10023: my $type=&mt("Type");
10024: my $attendance=&mt("Award points just for participation");
10025: my $personnel=&mt("Correctness determined from response by course personnel");
10026: my $specific=&mt("Correctness determined from response with clicker ID(s)");
10027: my $given=&mt("Correctness determined from given list of answers").' '.
10028: '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
10029: my $pcorrect=&mt("Percentage points for correct solution");
10030: my $pincorrect=&mt("Percentage points for incorrect solution");
10031: my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
10032: {'iclicker' => 'i>clicker',
10033: 'interwrite' => 'interwrite PRS',
10034: 'turning' => 'Turning Technologies'});
10035: $symb = &Apache::lonenc::check_encrypt($symb);
10036: $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
10037: function sanitycheck() {
10038: // Accept only integer percentages
10039: document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
10040: document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
10041: // Find out grading choice
10042: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10043: if (document.forms.gradesupload.gradingmechanism[i].checked) {
10044: gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
10045: }
10046: }
10047: // By default, new choice equals user selection
10048: newgradingchoice=gradingchoice;
10049: // Not good to give more points for false answers than correct ones
10050: if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
10051: document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
10052: }
10053: // If new choice is attendance only, and old choice was correctness-based, restore defaults
10054: if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
10055: document.forms.gradesupload.pcorrect.value=100;
10056: document.forms.gradesupload.pincorrect.value=100;
10057: }
10058: // If the values are different, cannot be attendance only
10059: if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
10060: (gradingchoice=='attendance')) {
10061: newgradingchoice='personnel';
10062: }
10063: // Change grading choice to new one
10064: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10065: if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
10066: document.forms.gradesupload.gradingmechanism[i].checked=true;
10067: } else {
10068: document.forms.gradesupload.gradingmechanism[i].checked=false;
10069: }
10070: }
10071: // Remember the old state
10072: document.forms.gradesupload.waschecked.value=newgradingchoice;
10073: }
10074: ENDUPFORM
10075: $result.= <<ENDUPFORM;
10076: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
10077: <input type="hidden" name="symb" value="$symb" />
10078: <input type="hidden" name="command" value="processclickerfile" />
10079: <input type="file" name="upfile" size="50" />
10080: <br /><label>$type: $selectform</label>
10081: ENDUPFORM
10082: $result.='</td>'.&Apache::loncommon::end_data_table_row().
10083: &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
10084: <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
10085: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
10086: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
10087: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
10088: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
10089: <br />
10090: <input type="text" name="givenanswer" size="50" />
10091: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
10092: ENDGRADINGFORM
10093: $result.='</td>'.&Apache::loncommon::end_data_table_row().
10094: &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
10095: <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
10096: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
10097: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
10098: </form>'
10099: ENDPERCFORM
10100: $result.='</td>'.
10101: &Apache::loncommon::end_data_table_row().
10102: &Apache::loncommon::end_data_table();
10103: return $result;
10104: }
10105:
10106: sub process_clicker_file {
10107: my ($r,$symb)=@_;
10108: if (!$symb) {return '';}
10109:
10110: my %Saveable_Parameters=&clicker_grading_parameters();
10111: &Apache::loncommon::store_course_settings('grades_clicker',
10112: \%Saveable_Parameters);
10113: my $result='';
10114: if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
10115: $result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
10116: return $result;
10117: }
10118: if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
10119: $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
10120: return $result;
10121: }
10122: my $foundgiven=0;
10123: if ($env{'form.gradingmechanism'} eq 'given') {
10124: $env{'form.givenanswer'}=~s/^\s*//gs;
10125: $env{'form.givenanswer'}=~s/\s*$//gs;
10126: $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
10127: $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
10128: my @answers=split(/\,/,$env{'form.givenanswer'});
10129: $foundgiven=$#answers+1;
10130: }
10131: my %clicker_ids=&gather_clicker_ids();
10132: my %correct_ids;
10133: if ($env{'form.gradingmechanism'} eq 'personnel') {
10134: %correct_ids=&gather_adv_clicker_ids();
10135: }
10136: if ($env{'form.gradingmechanism'} eq 'specific') {
10137: foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
10138: $correct_id=~tr/a-z/A-Z/;
10139: $correct_id=~s/\s//gs;
10140: $correct_id=~s/^[\#0]+//;
10141: $correct_id=~s/[\-\:]//g;
10142: if ($correct_id) {
10143: $correct_ids{$correct_id}='specified';
10144: }
10145: }
10146: }
10147: if ($env{'form.gradingmechanism'} eq 'attendance') {
10148: $result.=&mt('Score based on attendance only');
10149: } elsif ($env{'form.gradingmechanism'} eq 'given') {
10150: $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
10151: } else {
10152: my $number=0;
10153: $result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
10154: foreach my $id (sort(keys(%correct_ids))) {
10155: $result.='<br /><tt>'.$id.'</tt> - ';
10156: if ($correct_ids{$id} eq 'specified') {
10157: $result.=&mt('specified');
10158: } else {
10159: my ($uname,$udom)=split(/\:/,$correct_ids{$id});
10160: $result.=&Apache::loncommon::plainname($uname,$udom);
10161: }
10162: $number++;
10163: }
10164: $result.="</p>\n";
10165: if ($number==0) {
10166: $result .=
10167: &Apache::lonhtmlcommon::confirm_success(
10168: &mt('No IDs found to determine correct answer'),1);
10169: return $result;
10170: }
10171: }
10172: if (length($env{'form.upfile'}) < 2) {
10173: $result .=
10174: &Apache::lonhtmlcommon::confirm_success(
10175: &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
10176: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
10177: return $result;
10178: }
10179:
10180: # Were able to get all the info needed, now analyze the file
10181:
10182: $result.=&Apache::loncommon::studentbrowser_javascript();
10183: $symb = &Apache::lonenc::check_encrypt($symb);
10184: $result.=&Apache::loncommon::start_data_table().
10185: &Apache::loncommon::start_data_table_header_row().
10186: '<th>'.&mt('Evaluate clicker file').'</th>'.
10187: &Apache::loncommon::end_data_table_header_row().
10188: &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
10189: <td>
10190: <form method="post" action="/adm/grades" name="clickeranalysis">
10191: <input type="hidden" name="symb" value="$symb" />
10192: <input type="hidden" name="command" value="assignclickergrades" />
10193: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
10194: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
10195: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
10196: ENDHEADER
10197: if ($env{'form.gradingmechanism'} eq 'given') {
10198: $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
10199: }
10200: my %responses;
10201: my @questiontitles;
10202: my $errormsg='';
10203: my $number=0;
10204: if ($env{'form.upfiletype'} eq 'iclicker') {
10205: ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
10206: }
10207: if ($env{'form.upfiletype'} eq 'interwrite') {
10208: ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
10209: }
10210: if ($env{'form.upfiletype'} eq 'turning') {
10211: ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
10212: }
10213: $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
10214: '<input type="hidden" name="number" value="'.$number.'" />'.
10215: &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
10216: $env{'form.pcorrect'},$env{'form.pincorrect'}).
10217: '<br />';
10218: if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
10219: $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
10220: return $result;
10221: }
10222: # Remember Question Titles
10223: # FIXME: Possibly need delimiter other than ":"
10224: for (my $i=0;$i<$number;$i++) {
10225: $result.='<input type="hidden" name="question:'.$i.'" value="'.
10226: &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
10227: }
10228: my $correct_count=0;
10229: my $student_count=0;
10230: my $unknown_count=0;
10231: # Match answers with usernames
10232: # FIXME: Possibly need delimiter other than ":"
10233: foreach my $id (keys(%responses)) {
10234: if ($correct_ids{$id}) {
10235: $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
10236: $correct_count++;
10237: } elsif ($clicker_ids{$id}) {
10238: if ($clicker_ids{$id}=~/\,/) {
10239: # More than one user with the same clicker!
10240: $result.="</td>".&Apache::loncommon::end_data_table_row().
10241: &Apache::loncommon::start_data_table_row()."<td>".
10242: &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
10243: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10244: "<select name='multi".$id."'>";
10245: foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
10246: $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
10247: }
10248: $result.='</select>';
10249: $unknown_count++;
10250: } else {
10251: # Good: found one and only one user with the right clicker
10252: $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
10253: $student_count++;
10254: }
10255: } else {
10256: $result.="</td>".&Apache::loncommon::end_data_table_row().
10257: &Apache::loncommon::start_data_table_row()."<td>".
10258: &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
10259: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10260: "\n".&mt("Username").": <input type='text' name='uname".$id."' /> ".
10261: "\n".&mt("Domain").": ".
10262: &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).' '.
10263: &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
10264: $unknown_count++;
10265: }
10266: }
10267: $result.='<hr />'.
10268: &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
10269: if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
10270: if ($correct_count==0) {
10271: $errormsg.="Found no correct answers for grading!";
10272: } elsif ($correct_count>1) {
10273: $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
10274: }
10275: }
10276: if ($number<1) {
10277: $errormsg.="Found no questions.";
10278: }
10279: if ($errormsg) {
10280: $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
10281: } else {
10282: $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
10283: }
10284: $result.='</form></td>'.
10285: &Apache::loncommon::end_data_table_row().
10286: &Apache::loncommon::end_data_table();
10287: return $result;
10288: }
10289:
10290: sub iclicker_eval {
10291: my ($questiontitles,$responses)=@_;
10292: my $number=0;
10293: my $errormsg='';
10294: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10295: my %components=&Apache::loncommon::record_sep($line);
10296: my @entries=map {$components{$_}} (sort(keys(%components)));
10297: if ($entries[0] eq 'Question') {
10298: for (my $i=3;$i<$#entries;$i+=6) {
10299: $$questiontitles[$number]=$entries[$i];
10300: $number++;
10301: }
10302: }
10303: if ($entries[0]=~/^\#/) {
10304: my $id=$entries[0];
10305: my @idresponses;
10306: $id=~s/^[\#0]+//;
10307: for (my $i=0;$i<$number;$i++) {
10308: my $idx=3+$i*6;
10309: $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
10310: push(@idresponses,$entries[$idx]);
10311: }
10312: $$responses{$id}=join(',',@idresponses);
10313: }
10314: }
10315: return ($errormsg,$number);
10316: }
10317:
10318: sub interwrite_eval {
10319: my ($questiontitles,$responses)=@_;
10320: my $number=0;
10321: my $errormsg='';
10322: my $skipline=1;
10323: my $questionnumber=0;
10324: my %idresponses=();
10325: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10326: my %components=&Apache::loncommon::record_sep($line);
10327: my @entries=map {$components{$_}} (sort(keys(%components)));
10328: if ($entries[1] eq 'Time') { $skipline=0; next; }
10329: if ($entries[1] eq 'Response') { $skipline=1; }
10330: next if $skipline;
10331: if ($entries[0]!=$questionnumber) {
10332: $questionnumber=$entries[0];
10333: $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
10334: $number++;
10335: }
10336: my $id=$entries[4];
10337: $id=~s/^[\#0]+//;
10338: $id=~s/^v\d*\://i;
10339: $id=~s/[\-\:]//g;
10340: $idresponses{$id}[$number]=$entries[6];
10341: }
10342: foreach my $id (keys(%idresponses)) {
10343: $$responses{$id}=join(',',@{$idresponses{$id}});
10344: $$responses{$id}=~s/^\s*\,//;
10345: }
10346: return ($errormsg,$number);
10347: }
10348:
10349: sub turning_eval {
10350: my ($questiontitles,$responses)=@_;
10351: my $number=0;
10352: my $errormsg='';
10353: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10354: my %components=&Apache::loncommon::record_sep($line);
10355: my @entries=map {$components{$_}} (sort(keys(%components)));
10356: if ($#entries>$number) { $number=$#entries; }
10357: my $id=$entries[0];
10358: my @idresponses;
10359: $id=~s/^[\#0]+//;
10360: unless ($id) { next; }
10361: for (my $idx=1;$idx<=$#entries;$idx++) {
10362: $entries[$idx]=~s/\,/\;/g;
10363: $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
10364: push(@idresponses,$entries[$idx]);
10365: }
10366: $$responses{$id}=join(',',@idresponses);
10367: }
10368: for (my $i=1; $i<=$number; $i++) {
10369: $$questiontitles[$i]=&mt('Question [_1]',$i);
10370: }
10371: return ($errormsg,$number);
10372: }
10373:
10374:
10375: sub assign_clicker_grades {
10376: my ($r,$symb)=@_;
10377: if (!$symb) {return '';}
10378: # See which part we are saving to
10379: my $res_error;
10380: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
10381: if ($res_error) {
10382: return &navmap_errormsg();
10383: }
10384: # FIXME: This should probably look for the first handgradeable part
10385: my $part=$$partlist[0];
10386: # Start screen output
10387: my $result=&Apache::loncommon::start_data_table().
10388: &Apache::loncommon::start_data_table_header_row().
10389: '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
10390: &Apache::loncommon::end_data_table_header_row().
10391: &Apache::loncommon::start_data_table_row().'<td>';
10392: # Get correct result
10393: # FIXME: Possibly need delimiter other than ":"
10394: my @correct=();
10395: my $gradingmechanism=$env{'form.gradingmechanism'};
10396: my $number=$env{'form.number'};
10397: if ($gradingmechanism ne 'attendance') {
10398: foreach my $key (keys(%env)) {
10399: if ($key=~/^form\.correct\:/) {
10400: my @input=split(/\,/,$env{$key});
10401: for (my $i=0;$i<=$#input;$i++) {
10402: if (($correct[$i]) && ($input[$i]) &&
10403: ($correct[$i] ne $input[$i])) {
10404: $result.='<br /><span class="LC_warning">'.
10405: &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
10406: $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
10407: } elsif (($input[$i]) || ($input[$i] eq '0')) {
10408: $correct[$i]=$input[$i];
10409: }
10410: }
10411: }
10412: }
10413: for (my $i=0;$i<$number;$i++) {
10414: if ((!$correct[$i]) && ($correct[$i] ne '0')) {
10415: $result.='<br /><span class="LC_error">'.
10416: &mt('No correct result given for question "[_1]"!',
10417: $env{'form.question:'.$i}).'</span>';
10418: }
10419: }
10420: $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
10421: }
10422: # Start grading
10423: my $pcorrect=$env{'form.pcorrect'};
10424: my $pincorrect=$env{'form.pincorrect'};
10425: my $storecount=0;
10426: my %users=();
10427: foreach my $key (keys(%env)) {
10428: my $user='';
10429: if ($key=~/^form\.student\:(.*)$/) {
10430: $user=$1;
10431: }
10432: if ($key=~/^form\.unknown\:(.*)$/) {
10433: my $id=$1;
10434: if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
10435: $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
10436: } elsif ($env{'form.multi'.$id}) {
10437: $user=$env{'form.multi'.$id};
10438: }
10439: }
10440: if ($user) {
10441: if ($users{$user}) {
10442: $result.='<br /><span class="LC_warning">'.
10443: &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
10444: '</span><br />';
10445: }
10446: $users{$user}=1;
10447: my @answer=split(/\,/,$env{$key});
10448: my $sum=0;
10449: my $realnumber=$number;
10450: for (my $i=0;$i<$number;$i++) {
10451: if ($correct[$i] eq '-') {
10452: $realnumber--;
10453: } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
10454: if ($gradingmechanism eq 'attendance') {
10455: $sum+=$pcorrect;
10456: } elsif ($correct[$i] eq '*') {
10457: $sum+=$pcorrect;
10458: } else {
10459: # We actually grade if correct or not
10460: my $increment=$pincorrect;
10461: # Special case: numerical answer "0"
10462: if ($correct[$i] eq '0') {
10463: if ($answer[$i]=~/^[0\.]+$/) {
10464: $increment=$pcorrect;
10465: }
10466: # General numerical answer, both evaluate to something non-zero
10467: } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
10468: if (1.0*$correct[$i]==1.0*$answer[$i]) {
10469: $increment=$pcorrect;
10470: }
10471: # Must be just alphanumeric
10472: } elsif ($answer[$i] eq $correct[$i]) {
10473: $increment=$pcorrect;
10474: }
10475: $sum+=$increment;
10476: }
10477: }
10478: }
10479: my $ave=$sum/(100*$realnumber);
10480: # Store
10481: my ($username,$domain)=split(/\:/,$user);
10482: my %grades=();
10483: $grades{"resource.$part.solved"}='correct_by_override';
10484: $grades{"resource.$part.awarded"}=$ave;
10485: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
10486: my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
10487: $env{'request.course.id'},
10488: $domain,$username);
10489: if ($returncode ne 'ok') {
10490: $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
10491: } else {
10492: $storecount++;
10493: }
10494: }
10495: }
10496: # We are done
10497: $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
10498: '</td>'.
10499: &Apache::loncommon::end_data_table_row().
10500: &Apache::loncommon::end_data_table();
10501: return $result;
10502: }
10503:
10504: sub navmap_errormsg {
10505: return '<div class="LC_error">'.
10506: &mt('An error occurred retrieving information about resources in the course.').'<br />'.
10507: &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>').
10508: '</div>';
10509: }
10510:
10511: sub startpage {
10512: my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
10513: if ($nomenu) {
10514: $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
10515: } else {
10516: unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
10517: $r->print(&Apache::loncommon::start_page('Grading',$js,
10518: {'bread_crumbs' => $crumbs}));
10519: &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
10520: }
10521: unless ($nodisplayflag) {
10522: $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
10523: }
10524: }
10525:
10526: sub select_problem {
10527: my ($r)=@_;
10528: $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
10529: $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,undef,undef,1));
10530: $r->print('<input type="hidden" name="command" value="gradingmenu" />');
10531: $r->print('<input type="submit" value="'.&mt('Next').' →" /></form>');
10532: }
10533:
10534: sub handler {
10535: my $request=$_[0];
10536: &reset_caches();
10537: if ($request->header_only) {
10538: &Apache::loncommon::content_type($request,'text/html');
10539: $request->send_http_header;
10540: return OK;
10541: }
10542: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
10543:
10544: # see what command we need to execute
10545:
10546: my @commands=&Apache::loncommon::get_env_multiple('form.command');
10547: my $command=$commands[0];
10548:
10549: &init_perm();
10550: if (!$env{'request.course.id'}) {
10551: unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
10552: ($command =~ /^scantronupload/)) {
10553: # Not in a course.
10554: $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
10555: return HTTP_NOT_ACCEPTABLE;
10556: }
10557: } elsif (!%perm) {
10558: $request->internal_redirect('/adm/quickgrades');
10559: return OK;
10560: }
10561: &Apache::loncommon::content_type($request,'text/html');
10562: $request->send_http_header;
10563:
10564: if ($#commands > 0) {
10565: &Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
10566: }
10567:
10568: # see what the symb is
10569:
10570: my $symb=$env{'form.symb'};
10571: unless ($symb) {
10572: (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
10573: $symb=&Apache::lonnet::symbread($url);
10574: }
10575: &Apache::lonenc::check_decrypt(\$symb);
10576:
10577: $ssi_error = 0;
10578: if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
10579: #
10580: # Not called from a resource, but inside a course
10581: #
10582: &startpage($request,undef,[],1,1);
10583: &select_problem($request);
10584: } else {
10585: if ($command eq 'submission' && $perm{'vgr'}) {
10586: my ($stuvcurrent,$stuvdisp,$versionform,$js);
10587: if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
10588: ($stuvcurrent,$stuvdisp,$versionform,$js) =
10589: &choose_task_version_form($symb,$env{'form.student'},
10590: $env{'form.userdom'});
10591: }
10592: &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
10593: if ($versionform) {
10594: $request->print($versionform);
10595: }
10596: $request->print('<br clear="all" />');
10597: ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
10598: } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
10599: my ($stuvcurrent,$stuvdisp,$versionform,$js) =
10600: &choose_task_version_form($symb,$env{'form.student'},
10601: $env{'form.userdom'},
10602: $env{'form.inhibitmenu'});
10603: &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
10604: if ($versionform) {
10605: $request->print($versionform);
10606: }
10607: $request->print('<br clear="all" />');
10608: $request->print(&show_previous_task_version($request,$symb));
10609: } elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
10610: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10611: {href=>'',text=>'Select student'}],1,1);
10612: &pickStudentPage($request,$symb);
10613: } elsif ($command eq 'displayPage' && $perm{'vgr'}) {
10614: &startpage($request,$symb,
10615: [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10616: {href=>'',text=>'Select student'},
10617: {href=>'',text=>'Grade student'}],1,1);
10618: &displayPage($request,$symb);
10619: } elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
10620: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10621: {href=>'',text=>'Select student'},
10622: {href=>'',text=>'Grade student'},
10623: {href=>'',text=>'Store grades'}],1,1);
10624: &updateGradeByPage($request,$symb);
10625: } elsif ($command eq 'processGroup' && $perm{'vgr'}) {
10626: &startpage($request,$symb,[{href=>'',text=>'...'},
10627: {href=>'',text=>'Modify grades'}]);
10628: &processGroup($request,$symb);
10629: } elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
10630: &startpage($request,$symb);
10631: $request->print(&grading_menu($request,$symb));
10632: } elsif ($command eq 'individual' && $perm{'vgr'}) {
10633: &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
10634: $request->print(&submit_options($request,$symb));
10635: } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
10636: &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
10637: $request->print(&listStudents($request,$symb,'graded'));
10638: } elsif ($command eq 'table' && $perm{'vgr'}) {
10639: &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
10640: $request->print(&submit_options_table($request,$symb));
10641: } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
10642: &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
10643: $request->print(&submit_options_sequence($request,$symb));
10644: } elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
10645: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
10646: $request->print(&viewgrades($request,$symb));
10647: } elsif ($command eq 'handgrade' && $perm{'mgr'}) {
10648: &startpage($request,$symb,[{href=>'',text=>'...'},
10649: {href=>'',text=>'Store grades'}]);
10650: $request->print(&processHandGrade($request,$symb));
10651: } elsif ($command eq 'editgrades' && $perm{'mgr'}) {
10652: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
10653: {href=>&href_symb_cmd($symb,'viewgrades').'&group=all§ion=all&Status=Active',
10654: text=>"Modify grades"},
10655: {href=>'', text=>"Store grades"}]);
10656: $request->print(&editgrades($request,$symb));
10657: } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
10658: &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
10659: $request->print(&initialverifyreceipt($request,$symb));
10660: } elsif ($command eq 'verify' && $perm{'vgr'}) {
10661: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
10662: {href=>'',text=>'Verification Result'}]);
10663: $request->print(&verifyreceipt($request,$symb));
10664: } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
10665: &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
10666: $request->print(&process_clicker($request,$symb));
10667: } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
10668: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
10669: {href=>'', text=>'Process clicker file'}]);
10670: $request->print(&process_clicker_file($request,$symb));
10671: } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
10672: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
10673: {href=>'', text=>'Process clicker file'},
10674: {href=>'', text=>'Store grades'}]);
10675: $request->print(&assign_clicker_grades($request,$symb));
10676: } elsif ($command eq 'csvform' && $perm{'mgr'}) {
10677: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10678: $request->print(&upcsvScores_form($request,$symb));
10679: } elsif ($command eq 'csvupload' && $perm{'mgr'}) {
10680: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10681: $request->print(&csvupload($request,$symb));
10682: } elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
10683: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10684: $request->print(&csvuploadmap($request,$symb));
10685: } elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
10686: if ($env{'form.associate'} ne 'Reverse Association') {
10687: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10688: $request->print(&csvuploadoptions($request,$symb));
10689: } else {
10690: if ( $env{'form.upfile_associate'} ne 'reverse' ) {
10691: $env{'form.upfile_associate'} = 'reverse';
10692: } else {
10693: $env{'form.upfile_associate'} = 'forward';
10694: }
10695: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10696: $request->print(&csvuploadmap($request,$symb));
10697: }
10698: } elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
10699: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10700: $request->print(&csvuploadassign($request,$symb));
10701: } elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
10702: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10703: $request->print(&scantron_selectphase($request,undef,$symb));
10704: } elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
10705: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10706: $request->print(&scantron_do_warning($request,$symb));
10707: } elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
10708: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10709: $request->print(&scantron_validate_file($request,$symb));
10710: } elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
10711: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10712: $request->print(&scantron_process_students($request,$symb));
10713: } elsif ($command eq 'scantronupload' &&
10714: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10715: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10716: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10717: $request->print(&scantron_upload_scantron_data($request,$symb));
10718: } elsif ($command eq 'scantronupload_save' &&
10719: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10720: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10721: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10722: $request->print(&scantron_upload_scantron_data_save($request,$symb));
10723: } elsif ($command eq 'scantron_download' &&
10724: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
10725: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10726: $request->print(&scantron_download_scantron_data($request,$symb));
10727: } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
10728: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10729: $request->print(&checkscantron_results($request,$symb));
10730: } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
10731: &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
10732: $request->print(&submit_options_download($request,$symb));
10733: } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
10734: &startpage($request,$symb,
10735: [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
10736: {href=>'', text=>'Download submissions'}]);
10737: &submit_download_link($request,$symb);
10738: } elsif ($command) {
10739: &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
10740: $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
10741: }
10742: }
10743: if ($ssi_error) {
10744: &ssi_print_error($request);
10745: }
10746: if ($env{'form.inhibitmenu'}) {
10747: $request->print(&Apache::loncommon::end_page());
10748: } else {
10749: &Apache::lonquickgrades::endGradeScreen($request);
10750: }
10751: &reset_caches();
10752: return OK;
10753: }
10754:
10755: 1;
10756:
10757: __END__;
10758:
10759:
10760: =head1 NAME
10761:
10762: Apache::grades
10763:
10764: =head1 SYNOPSIS
10765:
10766: Handles the viewing of grades.
10767:
10768: This is part of the LearningOnline Network with CAPA project
10769: described at http://www.lon-capa.org.
10770:
10771: =head1 OVERVIEW
10772:
10773: Do an ssi with retries:
10774: While I'd love to factor out this with the version in lonprintout,
10775: 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
10776: I'm not quite ready to invent (e.g. an ssi_with_retry object).
10777:
10778: At least the logic that drives this has been pulled out into loncommon.
10779:
10780:
10781:
10782: ssi_with_retries - Does the server side include of a resource.
10783: if the ssi call returns an error we'll retry it up to
10784: the number of times requested by the caller.
10785: If we still have a problem, no text is appended to the
10786: output and we set some global variables.
10787: to indicate to the caller an SSI error occurred.
10788: All of this is supposed to deal with the issues described
10789: in LON-CAPA BZ 5631 see:
10790: http://bugs.lon-capa.org/show_bug.cgi?id=5631
10791: by informing the user that this happened.
10792:
10793: Parameters:
10794: resource - The resource to include. This is passed directly, without
10795: interpretation to lonnet::ssi.
10796: form - The form hash parameters that guide the interpretation of the resource
10797:
10798: retries - Number of retries allowed before giving up completely.
10799: Returns:
10800: On success, returns the rendered resource identified by the resource parameter.
10801: Side Effects:
10802: The following global variables can be set:
10803: ssi_error - If an unrecoverable error occurred this becomes true.
10804: It is up to the caller to initialize this to false
10805: if desired.
10806: ssi_error_resource - If an unrecoverable error occurred, this is the value
10807: of the resource that could not be rendered by the ssi
10808: call.
10809: ssi_error_message - The error string fetched from the ssi response
10810: in the event of an error.
10811:
10812:
10813: =head1 HANDLER SUBROUTINE
10814:
10815: ssi_with_retries()
10816:
10817: =head1 SUBROUTINES
10818:
10819: =over
10820:
10821: =head1 Routines to display previous version of a Task for a specific student
10822:
10823: Tasks are graded pass/fail. Students who have yet to pass a particular Task
10824: can receive another opportunity. Access to tasks is slot-based. If a slot
10825: requires a proctor to check-in the student, a new version of the Task will
10826: be created when the student is checked in to the new opportunity.
10827:
10828: If a particular student has tried two or more versions of a particular task,
10829: the submission screen provides a user with vgr privileges (e.g., a Course
10830: Coordinator) the ability to display a previous version worked on by the
10831: student. By default, the current version is displayed. If a previous version
10832: has been selected for display, submission data are only shown that pertain
10833: to that particular version, and the interface to submit grades is not shown.
10834:
10835: =over 4
10836:
10837: =item show_previous_task_version()
10838:
10839: Displays a specified version of a student's Task, as the student sees it.
10840:
10841: Inputs: 2
10842: request - request object
10843: symb - unique symb for current instance of resource
10844:
10845: Output: None.
10846:
10847: Side Effects: calls &show_problem() to print version of Task, with
10848: version contained in form item: $env{'form.previousversion'}
10849:
10850: =item choose_task_version_form()
10851:
10852: Displays a web form used to select which version of a student's view of a
10853: Task should be displayed. Either launches a pop-up window, or replaces
10854: content in existing pop-up, or replaces page in main window.
10855:
10856: Inputs: 4
10857: symb - unique symb for current instance of resource
10858: uname - username of student
10859: udom - domain of student
10860: nomenu - 1 if display is in a pop-up window, and hence no menu
10861: breadcrumbs etc., are displayed
10862:
10863: Output: 4
10864: current - student's current version
10865: displayed - student's version being displayed
10866: result - scalar containing HTML for web form used to switch to
10867: a different version (or a link to close window, if pop-up).
10868: js - javascript for processing selection in versions web form
10869:
10870: Side Effects: None.
10871:
10872: =item previous_display_javascript()
10873:
10874: Inputs: 2
10875: nomenu - 1 if display is in a pop-up window, and hence no menu
10876: breadcrumbs etc., are displayed.
10877: current - student's current version number.
10878:
10879: Output: 1
10880: js - javascript for processing selection in versions web form.
10881:
10882: Side Effects: None.
10883:
10884: =back
10885:
10886: =head1 Routines to process bubblesheet data.
10887:
10888: =over 4
10889:
10890: =item scantron_get_correction() :
10891:
10892: Builds the interface screen to interact with the operator to fix a
10893: specific error condition in a specific scanline
10894:
10895: Arguments:
10896: $r - Apache request object
10897: $i - number of the current scanline
10898: $scan_record - hash ref as returned from &scantron_parse_scanline()
10899: $scan_config - hash ref as returned from &get_scantron_config()
10900: $line - full contents of the current scanline
10901: $error - error condition, valid values are
10902: 'incorrectCODE', 'duplicateCODE',
10903: 'doublebubble', 'missingbubble',
10904: 'duplicateID', 'incorrectID'
10905: $arg - extra information needed
10906: For errors:
10907: - duplicateID - paper number that this studentID was seen before on
10908: - duplicateCODE - array ref of the paper numbers this CODE was
10909: seen on before
10910: - incorrectCODE - current incorrect CODE
10911: - doublebubble - array ref of the bubble lines that have double
10912: bubble errors
10913: - missingbubble - array ref of the bubble lines that have missing
10914: bubble errors
10915:
10916: $randomorder - True if exam folder has randomorder set
10917: $randompick - True if exam folder has randompick set
10918: $respnumlookup - Reference to HASH mapping question numbers in bubble lines
10919: for current line to question number used for same question
10920: in "Master Seqence" (as seen by Course Coordinator).
10921: $startline - Reference to hash where key is question number (0 is first)
10922: and value is number of first bubble line for current student
10923: or code-based randompick and/or randomorder.
10924:
10925:
10926:
10927: =item scantron_get_maxbubble() :
10928:
10929: Arguments:
10930: $nav_error - Reference to scalar which is a flag to indicate a
10931: failure to retrieve a navmap object.
10932: if $nav_error is set to 1 by scantron_get_maxbubble(), the
10933: calling routine should trap the error condition and display the warning
10934: found in &navmap_errormsg().
10935:
10936: $scantron_config - Reference to bubblesheet format configuration hash.
10937:
10938: Returns the maximum number of bubble lines that are expected to
10939: occur. Does this by walking the selected sequence rendering the
10940: resource and then checking &Apache::lonxml::get_problem_counter()
10941: for what the current value of the problem counter is.
10942:
10943: Caches the results to $env{'form.scantron_maxbubble'},
10944: $env{'form.scantron.bubble_lines.n'},
10945: $env{'form.scantron.first_bubble_line.n'} and
10946: $env{"form.scantron.sub_bubblelines.n"}
10947: which are the total number of bubble lines, the number of bubble
10948: lines for response n and number of the first bubble line for response n,
10949: and a comma separated list of numbers of bubble lines for sub-questions
10950: (for optionresponse, matchresponse, and rankresponse items), for response n.
10951:
10952:
10953: =item scantron_validate_missingbubbles() :
10954:
10955: Validates all scanlines in the selected file to not have any
10956: answers that don't have bubbles that have not been verified
10957: to be bubble free.
10958:
10959: =item scantron_process_students() :
10960:
10961: Routine that does the actual grading of the bubblesheet information.
10962:
10963: The parsed scanline hash is added to %env
10964:
10965: Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
10966: foreach resource , with the form data of
10967:
10968: 'submitted' =>'scantron'
10969: 'grade_target' =>'grade',
10970: 'grade_username'=> username of student
10971: 'grade_domain' => domain of student
10972: 'grade_courseid'=> of course
10973: 'grade_symb' => symb of resource to grade
10974:
10975: This triggers a grading pass. The problem grading code takes care
10976: of converting the bubbled letter information (now in %env) into a
10977: valid submission.
10978:
10979: =item scantron_upload_scantron_data() :
10980:
10981: Creates the screen for adding a new bubblesheet data file to a course.
10982:
10983: =item scantron_upload_scantron_data_save() :
10984:
10985: Adds a provided bubble information data file to the course if user
10986: has the correct privileges to do so.
10987:
10988: =item valid_file() :
10989:
10990: Validates that the requested bubble data file exists in the course.
10991:
10992: =item scantron_download_scantron_data() :
10993:
10994: Shows a list of the three internal files (original, corrected,
10995: skipped) for a specific bubblesheet data file that exists in the
10996: course.
10997:
10998: =item scantron_validate_ID() :
10999:
11000: Validates all scanlines in the selected file to not have any
11001: invalid or underspecified student/employee IDs
11002:
11003: =item navmap_errormsg() :
11004:
11005: Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
11006: Should be called whenever the request to instantiate a navmap object fails.
11007:
11008: =back
11009:
11010: =back
11011:
11012: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>