File:
[LON-CAPA] /
loncom /
homework /
grades.pm
Revision
1.724:
download - view:
text,
annotated -
select for diffs
Mon Aug 25 20:23:01 2014 UTC (9 years, 8 months ago) by
raeburn
Branches:
MAIN
CVS tags:
HEAD
- Bug 6726.
- Delay adding "Draft Copy" text, if draft, and conversion of line feeds
to <br /> when showing Submitted Answer in grading interface, for
essayresponsa,e until after entity encoding (grades.pm rev. 1.720 change).
1: # The LearningOnline Network with CAPA
2: # The LON-CAPA Grading handler
3: #
4: # $Id: grades.pm,v 1.724 2014/08/25 20:23:01 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 @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
120:
121: my @stores;
122: foreach my $part (@{ $partlist }) {
123: foreach my $key (@metakeys) {
124: if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
125: }
126: }
127: return @stores;
128: }
129:
130: #--- Format fullname, username:domain if different for display
131: #--- Use anywhere where the student names are listed
132: sub nameUserString {
133: my ($type,$fullname,$uname,$udom) = @_;
134: if ($type eq 'header') {
135: return '<b> '.&mt('Fullname').' </b><span class="LC_internal_info">('.&mt('Username').')</span>';
136: } else {
137: return ' '.$fullname.'<span class="LC_internal_info"> ('.$uname.
138: ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
139: }
140: }
141:
142: #--- Get the partlist and the response type for a given problem. ---
143: #--- Indicate if a response type is coded handgraded or not. ---
144: #--- Sets response_error pointer to "1" if navmaps object broken ---
145: sub response_type {
146: my ($symb,$response_error) = @_;
147:
148: my $navmap = Apache::lonnavmaps::navmap->new();
149: unless (ref($navmap)) {
150: if (ref($response_error)) {
151: $$response_error = 1;
152: }
153: return;
154: }
155: my $res = $navmap->getBySymb($symb);
156: unless (ref($res)) {
157: $$response_error = 1;
158: return;
159: }
160: my $partlist = $res->parts();
161: my %vPart =
162: map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
163: my (%response_types,%handgrade);
164: foreach my $part (@{ $partlist }) {
165: next if (%vPart && !exists($vPart{$part}));
166:
167: my @types = $res->responseType($part);
168: my @ids = $res->responseIds($part);
169: for (my $i=0; $i < scalar(@ids); $i++) {
170: $response_types{$part}{$ids[$i]} = $types[$i];
171: $handgrade{$part.'_'.$ids[$i]} =
172: &Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
173: '.handgrade',$symb);
174: }
175: }
176: return ($partlist,\%handgrade,\%response_types);
177: }
178:
179: sub flatten_responseType {
180: my ($responseType) = @_;
181: my @part_response_id =
182: map {
183: my $part = $_;
184: map {
185: [$part,$_]
186: } sort(keys(%{ $responseType->{$part} }));
187: } sort(keys(%$responseType));
188: return @part_response_id;
189: }
190:
191: sub get_display_part {
192: my ($partID,$symb)=@_;
193: my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
194: if (defined($display) and $display ne '') {
195: $display.= ' (<span class="LC_internal_info">'
196: .&mt('Part ID: [_1]',$partID).'</span>)';
197: } else {
198: $display=$partID;
199: }
200: return $display;
201: }
202:
203: sub reset_caches {
204: &reset_analyze_cache();
205: &reset_perm();
206: &reset_old_essays();
207: }
208:
209: {
210: my %analyze_cache;
211: my %analyze_cache_formkeys;
212:
213: sub reset_analyze_cache {
214: undef(%analyze_cache);
215: undef(%analyze_cache_formkeys);
216: }
217:
218: sub get_analyze {
219: my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
220: my $key = "$symb\0$uname\0$udom";
221: if ($type eq 'randomizetry') {
222: if ($trial ne '') {
223: $key .= "\0".$trial;
224: }
225: }
226: if (exists($analyze_cache{$key})) {
227: my $getupdate = 0;
228: if (ref($add_to_hash) eq 'HASH') {
229: foreach my $item (keys(%{$add_to_hash})) {
230: if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
231: if (!exists($analyze_cache_formkeys{$key}{$item})) {
232: $getupdate = 1;
233: last;
234: }
235: } else {
236: $getupdate = 1;
237: }
238: }
239: }
240: if (!$getupdate) {
241: return $analyze_cache{$key};
242: }
243: }
244:
245: my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
246: $url=&Apache::lonnet::clutter($url);
247: my %form = ('grade_target' => 'analyze',
248: 'grade_domain' => $udom,
249: 'grade_symb' => $symb,
250: 'grade_courseid' => $env{'request.course.id'},
251: 'grade_username' => $uname,
252: 'grade_noincrement' => $no_increment);
253: if ($bubbles_per_row ne '') {
254: $form{'bubbles_per_row'} = $bubbles_per_row;
255: }
256: if ($type eq 'randomizetry') {
257: $form{'grade_questiontype'} = $type;
258: if ($rndseed ne '') {
259: $form{'grade_rndseed'} = $rndseed;
260: }
261: }
262: if (ref($add_to_hash)) {
263: %form = (%form,%{$add_to_hash});
264: }
265: my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
266: (undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
267: my %analyze=&Apache::lonnet::str2hash($subresult);
268: if (ref($add_to_hash) eq 'HASH') {
269: $analyze_cache_formkeys{$key} = $add_to_hash;
270: } else {
271: $analyze_cache_formkeys{$key} = {};
272: }
273: return $analyze_cache{$key} = \%analyze;
274: }
275:
276: sub get_order {
277: my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
278: my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
279: return $analyze->{"$partid.$respid.shown"};
280: }
281:
282: sub get_radiobutton_correct_foil {
283: my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
284: my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
285: my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
286: if (ref($foils) eq 'ARRAY') {
287: foreach my $foil (@{$foils}) {
288: if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
289: return $foil;
290: }
291: }
292: }
293: }
294:
295: sub scantron_partids_tograde {
296: my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row) = @_;
297: my (%analysis,@parts);
298: if (ref($resource)) {
299: my $symb = $resource->symb();
300: my $add_to_form;
301: if ($check_for_randomlist) {
302: $add_to_form = { 'check_parts_withrandomlist' => 1,};
303: }
304: my $analyze =
305: &get_analyze($symb,$uname,$udom,undef,$add_to_form,
306: undef,undef,undef,$bubbles_per_row);
307: if (ref($analyze) eq 'HASH') {
308: %analysis = %{$analyze};
309: }
310: if (ref($analysis{'parts'}) eq 'ARRAY') {
311: foreach my $part (@{$analysis{'parts'}}) {
312: my ($id,$respid) = split(/\./,$part);
313: if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
314: push(@parts,$part);
315: }
316: }
317: }
318: }
319: return (\%analysis,\@parts);
320: }
321:
322: }
323:
324: #--- Clean response type for display
325: #--- Currently filters option/rank/radiobutton/match/essay/Task
326: # response types only.
327: sub cleanRecord {
328: my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
329: $uname,$udom,$type,$trial,$rndseed) = @_;
330: my $grayFont = '<span class="LC_internal_info">';
331: if ($response =~ /^(option|rank)$/) {
332: my %answer=&Apache::lonnet::str2hash($answer);
333: my @answer = %answer;
334: %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
335: my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
336: my ($toprow,$bottomrow);
337: foreach my $foil (@$order) {
338: if ($grading{$foil} == 1) {
339: $toprow.='<td><b>'.$answer{$foil}.' </b></td>';
340: } else {
341: $toprow.='<td><i>'.$answer{$foil}.' </i></td>';
342: }
343: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
344: }
345: return '<blockquote><table border="1">'.
346: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
347: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
348: $bottomrow.'</tr></table></blockquote>';
349: } elsif ($response eq 'match') {
350: my %answer=&Apache::lonnet::str2hash($answer);
351: my @answer = %answer;
352: %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
353: my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
354: my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
355: my ($toprow,$middlerow,$bottomrow);
356: foreach my $foil (@$order) {
357: my $item=shift(@items);
358: if ($grading{$foil} == 1) {
359: $toprow.='<td><b>'.$item.' </b></td>';
360: $middlerow.='<td><b>'.$grayFont.$answer{$foil}.' </span></b></td>';
361: } else {
362: $toprow.='<td><i>'.$item.' </i></td>';
363: $middlerow.='<td><i>'.$grayFont.$answer{$foil}.' </span></i></td>';
364: }
365: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
366: }
367: return '<blockquote><table border="1">'.
368: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
369: '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
370: $middlerow.'</tr>'.
371: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
372: $bottomrow.'</tr></table></blockquote>';
373: } elsif ($response eq 'radiobutton') {
374: my %answer=&Apache::lonnet::str2hash($answer);
375: my @answer = %answer;
376: %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
377: my ($toprow,$bottomrow);
378: my $correct =
379: &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
380: foreach my $foil (@$order) {
381: if (exists($answer{$foil})) {
382: if ($foil eq $correct) {
383: $toprow.='<td><b>'.&mt('true').'</b></td>';
384: } else {
385: $toprow.='<td><i>'.&mt('true').'</i></td>';
386: }
387: } else {
388: $toprow.='<td>'.&mt('false').'</td>';
389: }
390: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
391: }
392: return '<blockquote><table border="1">'.
393: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
394: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
395: $bottomrow.'</tr></table></blockquote>';
396: } elsif ($response eq 'essay') {
397: if (! exists ($env{'form.'.$symb})) {
398: my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
399: $env{'course.'.$env{'request.course.id'}.'.domain'},
400: $env{'course.'.$env{'request.course.id'}.'.num'});
401:
402: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
403: $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
404: $env{'form.kwclr'} = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
405: $env{'form.kwsize'} = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
406: $env{'form.kwstyle'} = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
407: $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
408: }
409: return '<br /><br /><blockquote><tt>'.&keywords_highlight(&HTML::Entities::encode($answer, '"<>&')).'</tt></blockquote>';
410:
411: } elsif ( $response eq 'organic') {
412: my $result=&mt('Smile representation: [_1]',
413: '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
414: my $jme=$record->{$version."resource.$partid.$respid.molecule"};
415: $result.=&Apache::chemresponse::jme_img($jme,$answer,400);
416: return $result;
417: } elsif ( $response eq 'Task') {
418: if ( $answer eq 'SUBMITTED') {
419: my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
420: my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
421: return $result;
422: } elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
423: my @matches = grep(/^\Q$version\E.*?\.instance$/,
424: keys(%{$record}));
425: return join('<br />',($version,@matches));
426:
427:
428: } else {
429: my $result =
430: '<p>'
431: .&mt('Overall result: [_1]',
432: $record->{$version."resource.$respid.$partid.status"})
433: .'</p>';
434:
435: $result .= '<ul>';
436: my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
437: keys(%{$record}));
438: foreach my $grade (sort(@grade)) {
439: my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
440: $result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
441: $dim, $record->{$grade}).
442: '</li>';
443: }
444: $result.='</ul>';
445: return $result;
446: }
447: } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
448: # Respect multiple input fields, see Bug #5409
449: $answer =
450: &Apache::loncommon::format_previous_attempt_value('submission',
451: $answer);
452: return $answer;
453: }
454: return &HTML::Entities::encode($answer, '"<>&');
455: }
456:
457: #-- A couple of common js functions
458: sub commonJSfunctions {
459: my $request = shift;
460: $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
461: function radioSelection(radioButton) {
462: var selection=null;
463: if (radioButton.length > 1) {
464: for (var i=0; i<radioButton.length; i++) {
465: if (radioButton[i].checked) {
466: return radioButton[i].value;
467: }
468: }
469: } else {
470: if (radioButton.checked) return radioButton.value;
471: }
472: return selection;
473: }
474:
475: function pullDownSelection(selectOne) {
476: var selection="";
477: if (selectOne.length > 1) {
478: for (var i=0; i<selectOne.length; i++) {
479: if (selectOne[i].selected) {
480: return selectOne[i].value;
481: }
482: }
483: } else {
484: // only one value it must be the selected one
485: return selectOne.value;
486: }
487: }
488: COMMONJSFUNCTIONS
489: }
490:
491: #--- Dumps the class list with usernames,list of sections,
492: #--- section, ids and fullnames for each user.
493: sub getclasslist {
494: my ($getsec,$filterlist,$getgroup) = @_;
495: my @getsec;
496: my @getgroup;
497: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
498: if (!ref($getsec)) {
499: if ($getsec ne '' && $getsec ne 'all') {
500: @getsec=($getsec);
501: }
502: } else {
503: @getsec=@{$getsec};
504: }
505: if (grep(/^all$/,@getsec)) { undef(@getsec); }
506: if (!ref($getgroup)) {
507: if ($getgroup ne '' && $getgroup ne 'all') {
508: @getgroup=($getgroup);
509: }
510: } else {
511: @getgroup=@{$getgroup};
512: }
513: if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
514:
515: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
516: # Bail out if we were unable to get the classlist
517: return if (! defined($classlist));
518: &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
519: #
520: my %sections;
521: my %fullnames;
522: foreach my $student (keys(%$classlist)) {
523: my $end =
524: $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
525: my $start =
526: $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
527: my $id =
528: $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
529: my $section =
530: $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
531: my $fullname =
532: $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
533: my $status =
534: $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
535: my $group =
536: $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
537: # filter students according to status selected
538: if ($filterlist && (!($stu_status =~ /Any/))) {
539: if (!($stu_status =~ $status)) {
540: delete($classlist->{$student});
541: next;
542: }
543: }
544: # filter students according to groups selected
545: my @stu_groups = split(/,/,$group);
546: if (@getgroup) {
547: my $exclude = 1;
548: foreach my $grp (@getgroup) {
549: foreach my $stu_group (@stu_groups) {
550: if ($stu_group eq $grp) {
551: $exclude = 0;
552: }
553: }
554: if (($grp eq 'none') && !$group) {
555: $exclude = 0;
556: }
557: }
558: if ($exclude) {
559: delete($classlist->{$student});
560: }
561: }
562: $section = ($section ne '' ? $section : 'none');
563: if (&canview($section)) {
564: if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
565: $sections{$section}++;
566: if ($classlist->{$student}) {
567: $fullnames{$student}=$fullname;
568: }
569: } else {
570: delete($classlist->{$student});
571: }
572: } else {
573: delete($classlist->{$student});
574: }
575: }
576: my %seen = ();
577: my @sections = sort(keys(%sections));
578: return ($classlist,\@sections,\%fullnames);
579: }
580:
581: sub canmodify {
582: my ($sec)=@_;
583: if ($perm{'mgr'}) {
584: if (!defined($perm{'mgr_section'})) {
585: # can modify whole class
586: return 1;
587: } else {
588: if ($sec eq $perm{'mgr_section'}) {
589: #can modify the requested section
590: return 1;
591: } else {
592: # can't modify the request section
593: return 0;
594: }
595: }
596: }
597: #can't modify
598: return 0;
599: }
600:
601: sub canview {
602: my ($sec)=@_;
603: if ($perm{'vgr'}) {
604: if (!defined($perm{'vgr_section'})) {
605: # can modify whole class
606: return 1;
607: } else {
608: if ($sec eq $perm{'vgr_section'}) {
609: #can modify the requested section
610: return 1;
611: } else {
612: # can't modify the request section
613: return 0;
614: }
615: }
616: }
617: #can't modify
618: return 0;
619: }
620:
621: #--- Retrieve the grade status of a student for all the parts
622: sub student_gradeStatus {
623: my ($symb,$udom,$uname,$partlist) = @_;
624: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
625: my %partstatus = ();
626: foreach (@$partlist) {
627: my ($status,undef) = split(/_/,$record{"resource.$_.solved"},2);
628: $status = 'nothing' if ($status eq '');
629: $partstatus{$_} = $status;
630: my $subkey = "resource.$_.submitted_by";
631: $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
632: }
633: return %partstatus;
634: }
635:
636: # hidden form and javascript that calls the form
637: # Use by verifyscript and viewgrades
638: # Shows a student's view of problem and submission
639: sub jscriptNform {
640: my ($symb) = @_;
641: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
642: my $jscript= &Apache::lonhtmlcommon::scripttag(
643: ' function viewOneStudent(user,domain) {'."\n".
644: ' document.onestudent.student.value = user;'."\n".
645: ' document.onestudent.userdom.value = domain;'."\n".
646: ' document.onestudent.submit();'."\n".
647: ' }'."\n".
648: "\n");
649: $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
650: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
651: '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
652: '<input type="hidden" name="command" value="submission" />'."\n".
653: '<input type="hidden" name="student" value="" />'."\n".
654: '<input type="hidden" name="userdom" value="" />'."\n".
655: '</form>'."\n";
656: return $jscript;
657: }
658:
659:
660:
661: # Given the score (as a number [0-1] and the weight) what is the final
662: # point value? This function will round to the nearest tenth, third,
663: # or quarter if one of those is within the tolerance of .00001.
664: sub compute_points {
665: my ($score, $weight) = @_;
666:
667: my $tolerance = .00001;
668: my $points = $score * $weight;
669:
670: # Check for nearness to 1/x.
671: my $check_for_nearness = sub {
672: my ($factor) = @_;
673: my $num = ($points * $factor) + $tolerance;
674: my $floored_num = floor($num);
675: if ($num - $floored_num < 2 * $tolerance * $factor) {
676: return $floored_num / $factor;
677: }
678: return $points;
679: };
680:
681: $points = $check_for_nearness->(10);
682: $points = $check_for_nearness->(3);
683: $points = $check_for_nearness->(4);
684:
685: return $points;
686: }
687:
688: #------------------ End of general use routines --------------------
689:
690: #
691: # Find most similar essay
692: #
693:
694: sub most_similar {
695: my ($uname,$udom,$symb,$uessay)=@_;
696:
697: unless ($symb) { return ''; }
698:
699: unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
700:
701: # ignore spaces and punctuation
702:
703: $uessay=~s/\W+/ /gs;
704:
705: # ignore empty submissions (occuring when only files are sent)
706:
707: unless ($uessay=~/\w+/s) { return ''; }
708:
709: # these will be returned. Do not care if not at least 50 percent similar
710: my $limit=0.6;
711: my $sname='';
712: my $sdom='';
713: my $scrsid='';
714: my $sessay='';
715: # go through all essays ...
716: foreach my $tkey (keys(%{$old_essays{$symb}})) {
717: my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
718: # ... except the same student
719: next if (($tname eq $uname) && ($tdom eq $udom));
720: my $tessay=$old_essays{$symb}{$tkey};
721: $tessay=~s/\W+/ /gs;
722: # String similarity gives up if not even limit
723: my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
724: # Found one
725: if ($tsimilar>$limit) {
726: $limit=$tsimilar;
727: $sname=$tname;
728: $sdom=$tdom;
729: $scrsid=$tcrsid;
730: $sessay=$old_essays{$symb}{$tkey};
731: }
732: }
733: if ($limit>0.6) {
734: return ($sname,$sdom,$scrsid,$sessay,$limit);
735: } else {
736: return ('','','','',0);
737: }
738: }
739:
740: #-------------------------------------------------------------------
741:
742: #------------------------------------ Receipt Verification Routines
743: #
744:
745: sub initialverifyreceipt {
746: my ($request,$symb) = @_;
747: &commonJSfunctions($request);
748: return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
749: &Apache::lonnet::recprefix($env{'request.course.id'}).
750: '-<input type="text" name="receipt" size="4" />'.
751: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
752: '<input type="hidden" name="command" value="verify" />'.
753: "</form>\n";
754: }
755:
756: #--- Check whether a receipt number is valid.---
757: sub verifyreceipt {
758: my ($request,$symb) = @_;
759:
760: my $courseid = $env{'request.course.id'};
761: my $receipt = &Apache::lonnet::recprefix($courseid).'-'.
762: $env{'form.receipt'};
763: $receipt =~ s/[^\-\d]//g;
764:
765: my $title.=
766: '<h3><span class="LC_info">'.
767: &mt('Verifying Receipt Number [_1]',$receipt).
768: '</span></h3>'."\n";
769:
770: my ($string,$contents,$matches) = ('','',0);
771: my (undef,undef,$fullname) = &getclasslist('all','0');
772:
773: my $receiptparts=0;
774: if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
775: $env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
776: my $parts=['0'];
777: if ($receiptparts) {
778: my $res_error;
779: ($parts)=&response_type($symb,\$res_error);
780: if ($res_error) {
781: return &navmap_errormsg();
782: }
783: }
784:
785: my $header =
786: &Apache::loncommon::start_data_table().
787: &Apache::loncommon::start_data_table_header_row().
788: '<th> '.&mt('Fullname').' </th>'."\n".
789: '<th> '.&mt('Username').' </th>'."\n".
790: '<th> '.&mt('Domain').' </th>';
791: if ($receiptparts) {
792: $header.='<th> '.&mt('Problem Part').' </th>';
793: }
794: $header.=
795: &Apache::loncommon::end_data_table_header_row();
796:
797: foreach (sort
798: {
799: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
800: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
801: }
802: return $a cmp $b;
803: } (keys(%$fullname))) {
804: my ($uname,$udom)=split(/\:/);
805: foreach my $part (@$parts) {
806: if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
807: $contents.=
808: &Apache::loncommon::start_data_table_row().
809: '<td> '."\n".
810: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
811: '\');" target="_self">'.$$fullname{$_}.'</a> </td>'."\n".
812: '<td> '.$uname.' </td>'.
813: '<td> '.$udom.' </td>';
814: if ($receiptparts) {
815: $contents.='<td> '.$part.' </td>';
816: }
817: $contents.=
818: &Apache::loncommon::end_data_table_row()."\n";
819:
820: $matches++;
821: }
822: }
823: }
824: if ($matches == 0) {
825: $string = $title
826: .'<p class="LC_warning">'
827: .&mt('No match found for the above receipt number.')
828: .'</p>';
829: } else {
830: $string = &jscriptNform($symb).$title.
831: '<p>'.
832: &mt('The above receipt number matches the following [quant,_1,student].',$matches).
833: '</p>'.
834: $header.
835: $contents.
836: &Apache::loncommon::end_data_table()."\n";
837: }
838: return $string;
839: }
840:
841: #--- This is called by a number of programs.
842: #--- Called from the Grading Menu - View/Grade an individual student
843: #--- Also called directly when one clicks on the subm button
844: # on the problem page.
845: sub listStudents {
846: my ($request,$symb,$submitonly) = @_;
847:
848: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
849: my $cnum = $env{"course.$env{'request.course.id'}.num"};
850: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
851: my $getgroup = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
852: unless ($submitonly) {
853: $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
854: }
855:
856: my $result='';
857: my $res_error;
858: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
859:
860: my %lt = &Apache::lonlocal::texthash (
861: 'multiple' => 'Please select a student or group of students before clicking on the Next button.',
862: 'single' => 'Please select the student before clicking on the Next button.',
863: );
864: $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
865: function checkSelect(checkBox) {
866: var ctr=0;
867: var sense="";
868: if (checkBox.length > 1) {
869: for (var i=0; i<checkBox.length; i++) {
870: if (checkBox[i].checked) {
871: ctr++;
872: }
873: }
874: sense = '$lt{'multiple'}';
875: } else {
876: if (checkBox.checked) {
877: ctr = 1;
878: }
879: sense = '$lt{'single'}';
880: }
881: if (ctr == 0) {
882: alert(sense);
883: return false;
884: }
885: document.gradesub.submit();
886: }
887:
888: function reLoadList(formname) {
889: if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
890: formname.command.value = 'submission';
891: formname.submit();
892: }
893: LISTJAVASCRIPT
894:
895: &commonJSfunctions($request);
896: $request->print($result);
897:
898: my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
899: "\n";
900:
901: $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
902: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
903: .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
904: .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
905: .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
906: .&Apache::lonhtmlcommon::row_closure();
907: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
908: .'<label><input type="radio" name="vAns" value="no" /> '.&mt('no').' </label>'."\n"
909: .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
910: .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
911: .&Apache::lonhtmlcommon::row_closure();
912:
913: my $submission_options;
914: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
915: my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
916: $env{'form.Status'} = $saveStatus;
917: $submission_options.=
918: '<span class="LC_nobreak">'.
919: '<label><input type="radio" name="lastSub" value="lastonly" /> '.
920: &mt('last submission').' </label></span>'."\n".
921: '<span class="LC_nobreak">'.
922: '<label><input type="radio" name="lastSub" value="last" /> '.
923: &mt('last submission with details').' </label></span>'."\n".
924: '<span class="LC_nobreak">'.
925: '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
926: &mt('all submissions').'</label></span>'."\n".
927: '<span class="LC_nobreak">'.
928: '<label><input type="radio" name="lastSub" value="all" /> '.
929: &mt('all submissions with details').'</label></span>';
930: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
931: .$submission_options
932: .&Apache::lonhtmlcommon::row_closure();
933:
934: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
935: .'<select name="increment">'
936: .'<option value="1">'.&mt('Whole Points').'</option>'
937: .'<option value=".5">'.&mt('Half Points').'</option>'
938: .'<option value=".25">'.&mt('Quarter Points').'</option>'
939: .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
940: .'</select>'
941: .&Apache::lonhtmlcommon::row_closure();
942:
943: $gradeTable .=
944: &build_section_inputs().
945: '<input type="hidden" name="submitonly" value="'.$submitonly.'" />'."\n".
946: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
947: '<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
948:
949: if (exists($env{'form.Status'})) {
950: $gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
951: } else {
952: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
953: .&Apache::lonhtmlcommon::StatusOptions(
954: $saveStatus,undef,1,'javascript:reLoadList(this.form);')
955: .&Apache::lonhtmlcommon::row_closure();
956: }
957:
958: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
959: .'<input type="checkbox" name="checkPlag" checked="checked" />'
960: .&Apache::lonhtmlcommon::row_closure(1)
961: .&Apache::lonhtmlcommon::end_pick_box();
962:
963: $gradeTable .= '<p>'
964: .&mt("To view/grade/regrade a submission or a group of submissions, click on the check box(es) next to the student's name(s). Then click on the Next button.")."\n"
965: .'<input type="hidden" name="command" value="processGroup" />'
966: .'</p>';
967:
968: # checkall buttons
969: $gradeTable.=&check_script('gradesub', 'stuinfo');
970: $gradeTable.='<input type="button" '."\n".
971: 'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
972: 'value="'.&mt('Next').' →" /> <br />'."\n";
973: $gradeTable.=&check_buttons();
974: my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
975: $gradeTable.= &Apache::loncommon::start_data_table().
976: &Apache::loncommon::start_data_table_header_row();
977: my $loop = 0;
978: while ($loop < 2) {
979: $gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
980: '<th>'.&nameUserString('header').' '.&mt('Section/Group').'</th>';
981: if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
982: foreach my $part (sort(@$partlist)) {
983: my $display_part=
984: &get_display_part((split(/_/,$part))[0],$symb);
985: $gradeTable.=
986: '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
987: }
988: } elsif ($submitonly eq 'queued') {
989: $gradeTable.='<th>'.&mt('Queue Status').' </th>';
990: }
991: $loop++;
992: # $gradeTable.='<td></td>' if ($loop%2 ==1);
993: }
994: $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
995:
996: my $ctr = 0;
997: foreach my $student (sort
998: {
999: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
1000: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
1001: }
1002: return $a cmp $b;
1003: }
1004: (keys(%$fullname))) {
1005: my ($uname,$udom) = split(/:/,$student);
1006:
1007: my %status = ();
1008:
1009: if ($submitonly eq 'queued') {
1010: my %queue_status =
1011: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
1012: $udom,$uname);
1013: next if (!defined($queue_status{'gradingqueue'}));
1014: $status{'gradingqueue'} = $queue_status{'gradingqueue'};
1015: }
1016:
1017: if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1018: (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1019: my $submitted = 0;
1020: my $graded = 0;
1021: my $incorrect = 0;
1022: foreach (keys(%status)) {
1023: $submitted = 1 if ($status{$_} ne 'nothing');
1024: $graded = 1 if ($status{$_} =~ /^ungraded/);
1025: $incorrect = 1 if ($status{$_} =~ /^incorrect/);
1026:
1027: my ($foo,$partid,$foo1) = split(/\./,$_);
1028: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1029: $submitted = 0;
1030: my ($part)=split(/\./,$partid);
1031: $gradeTable.='<input type="hidden" name="'.
1032: $student.':'.$part.':submitted_by" value="'.
1033: $status{'resource.'.$partid.'.submitted_by'}.'" />';
1034: }
1035: }
1036:
1037: next if (!$submitted && ($submitonly eq 'yes' ||
1038: $submitonly eq 'incorrect' ||
1039: $submitonly eq 'graded'));
1040: next if (!$graded && ($submitonly eq 'graded'));
1041: next if (!$incorrect && $submitonly eq 'incorrect');
1042: }
1043:
1044: $ctr++;
1045: my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1046: my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1047: if ( $perm{'vgr'} eq 'F' ) {
1048: if ($ctr%2 ==1) {
1049: $gradeTable.= &Apache::loncommon::start_data_table_row();
1050: }
1051: $gradeTable.='<td align="right">'.$ctr.' </td>'.
1052: '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1053: $student.':'.$$fullname{$student}.':::SECTION'.$section.
1054: ') " /> </label></td>'."\n".'<td>'.
1055: &nameUserString(undef,$$fullname{$student},$uname,$udom).
1056: ' '.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1057:
1058: if ($submitonly ne 'all') {
1059: foreach (sort(keys(%status))) {
1060: next if ($_ =~ /^resource.*?submitted_by$/);
1061: $gradeTable.='<td align="center"> '.&mt($status{$_}).' </td>'."\n";
1062: }
1063: }
1064: # $gradeTable.='<td></td>' if ($ctr%2 ==1);
1065: if ($ctr%2 ==0) {
1066: $gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
1067: }
1068: }
1069: }
1070: if ($ctr%2 ==1) {
1071: $gradeTable.='<td> </td><td> </td><td> </td>';
1072: if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1073: foreach (@$partlist) {
1074: $gradeTable.='<td> </td>';
1075: }
1076: } elsif ($submitonly eq 'queued') {
1077: $gradeTable.='<td> </td>';
1078: }
1079: $gradeTable.=&Apache::loncommon::end_data_table_row();
1080: }
1081:
1082: $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1083: '<input type="button" '.
1084: 'onclick="javascript:checkSelect(this.form.stuinfo);" '.
1085: 'value="'.&mt('Next').' →" /></form>'."\n";
1086: if ($ctr == 0) {
1087: my $num_students=(scalar(keys(%$fullname)));
1088: if ($num_students eq 0) {
1089: $gradeTable='<br /> <span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1090: } else {
1091: my $submissions='submissions';
1092: if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
1093: if ($submitonly eq 'graded' ) { $submissions = 'ungraded submissions'; }
1094: if ($submitonly eq 'queued' ) { $submissions = 'queued submissions'; }
1095: $gradeTable='<br /> <span class="LC_warning">'.
1096: &mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
1097: $num_students).
1098: '</span><br />';
1099: }
1100: } elsif ($ctr == 1) {
1101: $gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1102: }
1103: $request->print($gradeTable);
1104: return '';
1105: }
1106:
1107: #---- Called from the listStudents routine
1108:
1109: sub check_script {
1110: my ($form, $type)=@_;
1111: my $chkallscript= &Apache::lonhtmlcommon::scripttag('
1112: function checkall() {
1113: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1114: ele = document.forms.'.$form.'.elements[i];
1115: if (ele.name == "'.$type.'") {
1116: document.forms.'.$form.'.elements[i].checked=true;
1117: }
1118: }
1119: }
1120:
1121: function checksec() {
1122: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1123: ele = document.forms.'.$form.'.elements[i];
1124: string = document.forms.'.$form.'.chksec.value;
1125: if
1126: (ele.value.indexOf(":::SECTION"+string)>0) {
1127: document.forms.'.$form.'.elements[i].checked=true;
1128: }
1129: }
1130: }
1131:
1132:
1133: function uncheckall() {
1134: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1135: ele = document.forms.'.$form.'.elements[i];
1136: if (ele.name == "'.$type.'") {
1137: document.forms.'.$form.'.elements[i].checked=false;
1138: }
1139: }
1140: }
1141:
1142: '."\n");
1143: return $chkallscript;
1144: }
1145:
1146: sub check_buttons {
1147: my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
1148: $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" /> ';
1149: $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1150: $buttons.='<input type="text" size="5" name="chksec" /> ';
1151: return $buttons;
1152: }
1153:
1154: # Displays the submissions for one student or a group of students
1155: sub processGroup {
1156: my ($request,$symb) = @_;
1157: my $ctr = 0;
1158: my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1159: my $total = scalar(@stuchecked)-1;
1160:
1161: foreach my $student (@stuchecked) {
1162: my ($uname,$udom,$fullname) = split(/:/,$student);
1163: $env{'form.student'} = $uname;
1164: $env{'form.userdom'} = $udom;
1165: $env{'form.fullname'} = $fullname;
1166: &submission($request,$ctr,$total,$symb);
1167: $ctr++;
1168: }
1169: return '';
1170: }
1171:
1172: #------------------------------------------------------------------------------------
1173: #
1174: #-------------------------- Next few routines handles grading by student, essentially
1175: # handles essay response type problem/part
1176: #
1177: #--- Javascript to handle the submission page functionality ---
1178: sub sub_page_js {
1179: my $request = shift;
1180: my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1181: $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1182: function updateRadio(formname,id,weight) {
1183: var gradeBox = formname["GD_BOX"+id];
1184: var radioButton = formname["RADVAL"+id];
1185: var oldpts = formname["oldpts"+id].value;
1186: var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1187: gradeBox.value = pts;
1188: var resetbox = false;
1189: if (isNaN(pts) || pts < 0) {
1190: alert("$alertmsg"+pts);
1191: for (var i=0; i<radioButton.length; i++) {
1192: if (radioButton[i].checked) {
1193: gradeBox.value = i;
1194: resetbox = true;
1195: }
1196: }
1197: if (!resetbox) {
1198: formtextbox.value = "";
1199: }
1200: return;
1201: }
1202:
1203: if (pts > weight) {
1204: var resp = confirm("You entered a value ("+pts+
1205: ") greater than the weight for the part. Accept?");
1206: if (resp == false) {
1207: gradeBox.value = oldpts;
1208: return;
1209: }
1210: }
1211:
1212: for (var i=0; i<radioButton.length; i++) {
1213: radioButton[i].checked=false;
1214: if (pts == i && pts != "") {
1215: radioButton[i].checked=true;
1216: }
1217: }
1218: updateSelect(formname,id);
1219: formname["stores"+id].value = "0";
1220: }
1221:
1222: function writeBox(formname,id,pts) {
1223: var gradeBox = formname["GD_BOX"+id];
1224: if (checkSolved(formname,id) == 'update') {
1225: gradeBox.value = pts;
1226: } else {
1227: var oldpts = formname["oldpts"+id].value;
1228: gradeBox.value = oldpts;
1229: var radioButton = formname["RADVAL"+id];
1230: for (var i=0; i<radioButton.length; i++) {
1231: radioButton[i].checked=false;
1232: if (i == oldpts) {
1233: radioButton[i].checked=true;
1234: }
1235: }
1236: }
1237: formname["stores"+id].value = "0";
1238: updateSelect(formname,id);
1239: return;
1240: }
1241:
1242: function clearRadBox(formname,id) {
1243: if (checkSolved(formname,id) == 'noupdate') {
1244: updateSelect(formname,id);
1245: return;
1246: }
1247: gradeSelect = formname["GD_SEL"+id];
1248: for (var i=0; i<gradeSelect.length; i++) {
1249: if (gradeSelect[i].selected) {
1250: var selectx=i;
1251: }
1252: }
1253: var stores = formname["stores"+id];
1254: if (selectx == stores.value) { return };
1255: var gradeBox = formname["GD_BOX"+id];
1256: gradeBox.value = "";
1257: var radioButton = formname["RADVAL"+id];
1258: for (var i=0; i<radioButton.length; i++) {
1259: radioButton[i].checked=false;
1260: }
1261: stores.value = selectx;
1262: }
1263:
1264: function checkSolved(formname,id) {
1265: if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1266: var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
1267: if (!reply) {return "noupdate";}
1268: formname.overRideScore.value = 'yes';
1269: }
1270: return "update";
1271: }
1272:
1273: function updateSelect(formname,id) {
1274: formname["GD_SEL"+id][0].selected = true;
1275: return;
1276: }
1277:
1278: //=========== Check that a point is assigned for all the parts ============
1279: function checksubmit(formname,val,total,parttot) {
1280: formname.gradeOpt.value = val;
1281: if (val == "Save & Next") {
1282: for (i=0;i<=total;i++) {
1283: for (j=0;j<parttot;j++) {
1284: var partid = formname["partid"+i+"_"+j].value;
1285: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1286: var points = formname["GD_BOX"+i+"_"+partid].value;
1287: if (points == "") {
1288: var name = formname["name"+i].value;
1289: var studentID = (name != '' ? name : formname["unamedom"+i].value);
1290: var resp = confirm("You did not assign a score for "+studentID+
1291: ", part "+partid+". Continue?");
1292: if (resp == false) {
1293: formname["GD_BOX"+i+"_"+partid].focus();
1294: return false;
1295: }
1296: }
1297: }
1298:
1299: }
1300: }
1301:
1302: }
1303: formname.submit();
1304: }
1305:
1306: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
1307: function checkSubmitPage(formname,total) {
1308: noscore = new Array(100);
1309: var ptr = 0;
1310: for (i=1;i<total;i++) {
1311: var partid = formname["q_"+i].value;
1312: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1313: var points = formname["GD_BOX"+i+"_"+partid].value;
1314: var status = formname["solved"+i+"_"+partid].value;
1315: if (points == "" && status != "correct_by_student") {
1316: noscore[ptr] = i;
1317: ptr++;
1318: }
1319: }
1320: }
1321: if (ptr != 0) {
1322: var sense = ptr == 1 ? ": " : "s: ";
1323: var prolist = "";
1324: if (ptr == 1) {
1325: prolist = noscore[0];
1326: } else {
1327: var i = 0;
1328: while (i < ptr-1) {
1329: prolist += noscore[i]+", ";
1330: i++;
1331: }
1332: prolist += "and "+noscore[i];
1333: }
1334: var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
1335: if (resp == false) {
1336: return false;
1337: }
1338: }
1339:
1340: formname.submit();
1341: }
1342: SUBJAVASCRIPT
1343: }
1344:
1345: #--- javascript for essay type problem --
1346: sub sub_page_kw_js {
1347: my $request = shift;
1348: my $iconpath = $request->dir_config('lonIconsURL');
1349: &commonJSfunctions($request);
1350:
1351: my $inner_js_msg_central= (<<INNERJS);
1352: <script type="text/javascript">
1353: function checkInput() {
1354: opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
1355: var nmsg = opener.document.SCORE.savemsgN.value;
1356: var usrctr = document.msgcenter.usrctr.value;
1357: var newval = opener.document.SCORE["newmsg"+usrctr];
1358: newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
1359:
1360: var msgchk = "";
1361: if (document.msgcenter.subchk.checked) {
1362: msgchk = "msgsub,";
1363: }
1364: var includemsg = 0;
1365: for (var i=1; i<=nmsg; i++) {
1366: var opnmsg = opener.document.SCORE["savemsg"+i];
1367: var frmmsg = document.msgcenter["msg"+i];
1368: opnmsg.value = opener.checkEntities(frmmsg.value);
1369: var showflg = opener.document.SCORE["shownOnce"+i];
1370: showflg.value = "1";
1371: var chkbox = document.msgcenter["msgn"+i];
1372: if (chkbox.checked) {
1373: msgchk += "savemsg"+i+",";
1374: includemsg = 1;
1375: }
1376: }
1377: if (document.msgcenter.newmsgchk.checked) {
1378: msgchk += "newmsg"+usrctr;
1379: includemsg = 1;
1380: }
1381: imgformname = opener.document.SCORE["mailicon"+usrctr];
1382: imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
1383: var includemsg = opener.document.SCORE["includemsg"+usrctr];
1384: includemsg.value = msgchk;
1385:
1386: self.close()
1387:
1388: }
1389: </script>
1390: INNERJS
1391:
1392: my $inner_js_highlight_central= (<<INNERJS);
1393: <script type="text/javascript">
1394: function updateChoice(flag) {
1395: opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
1396: opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
1397: opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
1398: opener.document.SCORE.refresh.value = "on";
1399: if (opener.document.SCORE.keywords.value!=""){
1400: opener.document.SCORE.submit();
1401: }
1402: self.close()
1403: }
1404: </script>
1405: INNERJS
1406:
1407: my $start_page_msg_central =
1408: &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
1409: {'js_ready' => 1,
1410: 'only_body' => 1,
1411: 'bgcolor' =>'#FFFFFF',});
1412: my $end_page_msg_central =
1413: &Apache::loncommon::end_page({'js_ready' => 1});
1414:
1415:
1416: my $start_page_highlight_central =
1417: &Apache::loncommon::start_page('Highlight Central',
1418: $inner_js_highlight_central,
1419: {'js_ready' => 1,
1420: 'only_body' => 1,
1421: 'bgcolor' =>'#FFFFFF',});
1422: my $end_page_highlight_central =
1423: &Apache::loncommon::end_page({'js_ready' => 1});
1424:
1425: my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1426: $docopen=~s/^document\.//;
1427: my %lt = &Apache::lonlocal::texthash(
1428: keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
1429: plse => 'Please select a word or group of words from document and then click this link.',
1430: adds => 'Add selection to keyword list? Edit if desired.',
1431: comp => 'Compose Message for: ',
1432: incl => 'Include',
1433: type => 'Type',
1434: subj => 'Subject',
1435: mesa => 'Message',
1436: new => 'New',
1437: save => 'Save',
1438: canc => 'Cancel',
1439: kehi => 'Keyword Highlight Options',
1440: txtc => 'Text Color',
1441: font => 'Font Size',
1442: fnst => 'Font Style',
1443: col1 => 'red',
1444: col2 => 'green',
1445: col3 => 'blue',
1446: siz1 => 'normal',
1447: siz2 => '+1',
1448: siz3 => '+2',
1449: sty1 => 'normal',
1450: sty2 => 'italic',
1451: sty3 => 'bold',
1452: );
1453: $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1454:
1455: //===================== Show list of keywords ====================
1456: function keywords(formname) {
1457: var nret = prompt("$lt{'keyw'}",formname.keywords.value);
1458: if (nret==null) return;
1459: formname.keywords.value = nret;
1460:
1461: if (formname.keywords.value != "") {
1462: formname.refresh.value = "on";
1463: formname.submit();
1464: }
1465: return;
1466: }
1467:
1468: //===================== Script to view submitted by ==================
1469: function viewSubmitter(submitter) {
1470: document.SCORE.refresh.value = "on";
1471: document.SCORE.NCT.value = "1";
1472: document.SCORE.unamedom0.value = submitter;
1473: document.SCORE.submit();
1474: return;
1475: }
1476:
1477: //===================== Script to add keyword(s) ==================
1478: function getSel() {
1479: if (document.getSelection) txt = document.getSelection();
1480: else if (document.selection) txt = document.selection.createRange().text;
1481: else return;
1482: var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
1483: if (cleantxt=="") {
1484: alert("$lt{'plse'}");
1485: return;
1486: }
1487: var nret = prompt("$lt{'adds'}",cleantxt);
1488: if (nret==null) return;
1489: document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1490: if (document.SCORE.keywords.value != "") {
1491: document.SCORE.refresh.value = "on";
1492: document.SCORE.submit();
1493: }
1494: return;
1495: }
1496:
1497: //====================== Script for composing message ==============
1498: // preload images
1499: img1 = new Image();
1500: img1.src = "$iconpath/mailbkgrd.gif";
1501: img2 = new Image();
1502: img2.src = "$iconpath/mailto.gif";
1503:
1504: function msgCenter(msgform,usrctr,fullname) {
1505: var Nmsg = msgform.savemsgN.value;
1506: savedMsgHeader(Nmsg,usrctr,fullname);
1507: var subject = msgform.msgsub.value;
1508: var msgchk = document.SCORE["includemsg"+usrctr].value;
1509: re = /msgsub/;
1510: var shwsel = "";
1511: if (re.test(msgchk)) { shwsel = "checked" }
1512: subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
1513: displaySubject(checkEntities(subject),shwsel);
1514: for (var i=1; i<=Nmsg; i++) {
1515: var testmsg = "savemsg"+i+",";
1516: re = new RegExp(testmsg,"g");
1517: shwsel = "";
1518: if (re.test(msgchk)) { shwsel = "checked" }
1519: var message = document.SCORE["savemsg"+i].value;
1520: message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1521: displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
1522: //any < is already converted to <, etc. However, only once!!
1523: }
1524: newmsg = document.SCORE["newmsg"+usrctr].value;
1525: shwsel = "";
1526: re = /newmsg/;
1527: if (re.test(msgchk)) { shwsel = "checked" }
1528: newMsg(newmsg,shwsel);
1529: msgTail();
1530: return;
1531: }
1532:
1533: function checkEntities(strx) {
1534: if (strx.length == 0) return strx;
1535: var orgStr = ["&", "<", ">", '"'];
1536: var newStr = ["&", "<", ">", """];
1537: var counter = 0;
1538: while (counter < 4) {
1539: strx = strReplace(strx,orgStr[counter],newStr[counter]);
1540: counter++;
1541: }
1542: return strx;
1543: }
1544:
1545: function strReplace(strx, orgStr, newStr) {
1546: return strx.split(orgStr).join(newStr);
1547: }
1548:
1549: function savedMsgHeader(Nmsg,usrctr,fullname) {
1550: var height = 70*Nmsg+250;
1551: if (height > 600) {
1552: height = 600;
1553: }
1554: var xpos = (screen.width-600)/2;
1555: xpos = (xpos < 0) ? '0' : xpos;
1556: var ypos = (screen.height-height)/2-30;
1557: ypos = (ypos < 0) ? '0' : ypos;
1558:
1559: pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1560: pWin.focus();
1561: pDoc = pWin.document;
1562: pDoc.$docopen;
1563: pDoc.write('$start_page_msg_central');
1564:
1565: pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
1566: pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1567: pDoc.write("<h1> $lt{'comp'}\"+fullname+\"<\\/h1>");
1568:
1569: pDoc.write('<table style="border:1px solid black;"><tr>');
1570: pDoc.write("<td><b>$lt{'incl'}<\\/b><\\/td><td><b>$lt{'type'}<\\/b><\\/td><td><b>$lt{'mesa'}<\\/td><\\/tr>");
1571: }
1572: function displaySubject(msg,shwsel) {
1573: pDoc = pWin.document;
1574: pDoc.write("<tr>");
1575: pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1576: pDoc.write("<td>$lt{'subj'}<\\/td>");
1577: pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1578: }
1579:
1580: function displaySavedMsg(ctr,msg,shwsel) {
1581: pDoc = pWin.document;
1582: pDoc.write("<tr>");
1583: pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1584: pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
1585: pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1586: }
1587:
1588: function newMsg(newmsg,shwsel) {
1589: pDoc = pWin.document;
1590: pDoc.write("<tr>");
1591: pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1592: pDoc.write("<td align=\\"center\\">$lt{'new'}<\\/td>");
1593: pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1594: }
1595:
1596: function msgTail() {
1597: pDoc = pWin.document;
1598: //pDoc.write("<\\/table>");
1599: pDoc.write("<\\/td><\\/tr><\\/table> ");
1600: pDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:checkInput()\\"> ");
1601: pDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1602: pDoc.write("<\\/form>");
1603: pDoc.write('$end_page_msg_central');
1604: pDoc.close();
1605: }
1606:
1607: //====================== Script for keyword highlight options ==============
1608: function kwhighlight() {
1609: var kwclr = document.SCORE.kwclr.value;
1610: var kwsize = document.SCORE.kwsize.value;
1611: var kwstyle = document.SCORE.kwstyle.value;
1612: var redsel = "";
1613: var grnsel = "";
1614: var blusel = "";
1615: var txtcol1 = "$lt{'col1'}";
1616: var txtcol2 = "$lt{'col2'}";
1617: var txtcol3 = "$lt{'col3'}";
1618: var txtsiz1 = "$lt{'siz1'}";
1619: var txtsiz2 = "$lt{'siz2'}";
1620: var txtsiz3 = "$lt{'siz3'}";
1621: var txtsty1 = "$lt{'sty1'}";
1622: var txtsty2 = "$lt{'sty2'}";
1623: var txtsty3 = "$lt{'sty3'}";
1624: if (kwclr=="red") {var redsel="checked='checked'"};
1625: if (kwclr=="green") {var grnsel="checked='checked'"};
1626: if (kwclr=="blue") {var blusel="checked='checked'"};
1627: var sznsel = "";
1628: var sz1sel = "";
1629: var sz2sel = "";
1630: if (kwsize=="0") {var sznsel="checked='checked'"};
1631: if (kwsize=="+1") {var sz1sel="checked='checked'"};
1632: if (kwsize=="+2") {var sz2sel="checked='checked'"};
1633: var synsel = "";
1634: var syisel = "";
1635: var sybsel = "";
1636: if (kwstyle=="") {var synsel="checked='checked'"};
1637: if (kwstyle=="<i>") {var syisel="checked='checked'"};
1638: if (kwstyle=="<b>") {var sybsel="checked='checked'"};
1639: highlightCentral();
1640: highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
1641: highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
1642: highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
1643: highlightend();
1644: return;
1645: }
1646:
1647: function highlightCentral() {
1648: // if (window.hwdWin) window.hwdWin.close();
1649: var xpos = (screen.width-400)/2;
1650: xpos = (xpos < 0) ? '0' : xpos;
1651: var ypos = (screen.height-330)/2-30;
1652: ypos = (ypos < 0) ? '0' : ypos;
1653:
1654: hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1655: hwdWin.focus();
1656: var hDoc = hwdWin.document;
1657: hDoc.$docopen;
1658: hDoc.write('$start_page_highlight_central');
1659: hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1660: hDoc.write("<h1>$lt{'kehi'}<\\/h1>");
1661:
1662: hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
1663: hDoc.write("<th>$lt{'txtc'}<\\/th><th>$lt{'font'}<\\/th><th>$lt{'fnst'}<\\/th><\\/tr>");
1664: }
1665:
1666: function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) {
1667: var hDoc = hwdWin.document;
1668: hDoc.write("<tr>");
1669: hDoc.write("<td align=\\"left\\">");
1670: hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/> "+clrtxt+"<\\/td>");
1671: hDoc.write("<td align=\\"left\\">");
1672: hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/> "+sztxt+"<\\/td>");
1673: hDoc.write("<td align=\\"left\\">");
1674: hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/> "+sytxt+"<\\/td>");
1675: hDoc.write("<\\/tr>");
1676: }
1677:
1678: function highlightend() {
1679: var hDoc = hwdWin.document;
1680: hDoc.write("<\\/table><br \\/>");
1681: hDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/> ");
1682: hDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
1683: hDoc.write("<\\/form>");
1684: hDoc.write('$end_page_highlight_central');
1685: hDoc.close();
1686: }
1687:
1688: SUBJAVASCRIPT
1689: }
1690:
1691: sub get_increment {
1692: my $increment = $env{'form.increment'};
1693: if ($increment != 1 && $increment != .5 && $increment != .25 &&
1694: $increment != .1) {
1695: $increment = 1;
1696: }
1697: return $increment;
1698: }
1699:
1700: sub gradeBox_start {
1701: return (
1702: &Apache::loncommon::start_data_table()
1703: .&Apache::loncommon::start_data_table_header_row()
1704: .'<th>'.&mt('Part').'</th>'
1705: .'<th>'.&mt('Points').'</th>'
1706: .'<th> </th>'
1707: .'<th>'.&mt('Assign Grade').'</th>'
1708: .'<th>'.&mt('Weight').'</th>'
1709: .'<th>'.&mt('Grade Status').'</th>'
1710: .&Apache::loncommon::end_data_table_header_row()
1711: );
1712: }
1713:
1714: sub gradeBox_end {
1715: return (
1716: &Apache::loncommon::end_data_table()
1717: );
1718: }
1719: #--- displays the grading box, used in essay type problem and grading by page/sequence
1720: sub gradeBox {
1721: my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1722: my $checkIcon = '<img alt="'.&mt('Check Mark').
1723: '" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1724: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1725: my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)')
1726: : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1727: $wgt = ($wgt > 0 ? $wgt : '1');
1728: my $score = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1729: '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1730: my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1731: my $display_part= &get_display_part($partid,$symb);
1732: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
1733: [$partid]);
1734: my $aggtries = $$record{'resource.'.$partid.'.tries'};
1735: if ($last_resets{$partid}) {
1736: $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
1737: }
1738: my $result=&Apache::loncommon::start_data_table_row();
1739: my $ctr = 0;
1740: my $thisweight = 0;
1741: my $increment = &get_increment();
1742:
1743: my $radio.='<table border="0"><tr>'."\n"; # display radio buttons in a nice table 10 across
1744: while ($thisweight<=$wgt) {
1745: $radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1746: 'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1747: $thisweight.')" value="'.$thisweight.'" '.
1748: ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1749: $radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1750: $thisweight += $increment;
1751: $ctr++;
1752: }
1753: $radio.='</tr></table>';
1754:
1755: my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1756: ($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1757: 'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1758: $wgt.')" /></td>'."\n";
1759: $line.='<td>/'.$wgt.' '.$wgtmsg.
1760: ($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? ' '.$checkIcon : '').
1761: ' </td>'."\n";
1762: $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1763: 'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1764: if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1765: $line.='<option></option>'.
1766: '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1767: } else {
1768: $line.='<option selected="selected"></option>'.
1769: '<option value="excused" >'.&mt('excused').'</option>';
1770: }
1771: $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
1772:
1773:
1774: $result .=
1775: '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
1776: $result.=&Apache::loncommon::end_data_table_row();
1777: $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
1778: $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
1779: '<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
1780: '<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1781: $$record{'resource.'.$partid.'.solved'}.'" />'."\n".
1782: '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
1783: $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
1784: '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
1785: $aggtries.'" />'."\n";
1786: my $res_error;
1787: $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1788: $result.='</td>'.&Apache::loncommon::end_data_table_row();
1789: if ($res_error) {
1790: return &navmap_errormsg();
1791: }
1792: return $result;
1793: }
1794:
1795: sub handback_box {
1796: my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
1797: my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
1798: my (@respids);
1799: my @part_response_id = &flatten_responseType($responseType);
1800: foreach my $part_response_id (@part_response_id) {
1801: my ($part,$resp) = @{ $part_response_id };
1802: if ($part eq $partid) {
1803: push(@respids,$resp);
1804: }
1805: }
1806: my $result;
1807: foreach my $respid (@respids) {
1808: my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
1809: my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
1810: next if (!@$files);
1811: my $file_counter = 0;
1812: foreach my $file (@$files) {
1813: if ($file =~ /\/portfolio\//) {
1814: $file_counter++;
1815: my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1816: my ($name,$version,$ext) = &file_name_version_ext($file_disp);
1817: $file_disp = "$name.$ext";
1818: $file = $file_path.$file_disp;
1819: $result.=&mt('Return commented version of [_1] to student.',
1820: '<span class="LC_filename">'.$file_disp.'</span>');
1821: $result.='<input type="file" name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1822: $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1823: }
1824: }
1825: if ($file_counter) {
1826: $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
1827: '<span class="LC_info">'.
1828: '('.&mt('File(s) will be uploaded when you click on Save & Next below.',$file_counter).')</span><br /><br />';
1829: }
1830: }
1831: return $result;
1832: }
1833:
1834: sub show_problem {
1835: my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1836: my $rendered;
1837: my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1838: &Apache::lonxml::remember_problem_counter();
1839: if ($mode eq 'both' or $mode eq 'text') {
1840: $rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1841: $env{'request.course.id'},
1842: undef,\%form);
1843: }
1844: if ($removeform) {
1845: $rendered=~s|<form(.*?)>||g;
1846: $rendered=~s|</form>||g;
1847: $rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1848: }
1849: my $companswer;
1850: if ($mode eq 'both' or $mode eq 'answer') {
1851: &Apache::lonxml::restore_problem_counter();
1852: $companswer=
1853: &Apache::loncommon::get_student_answers($symb,$uname,$udom,
1854: $env{'request.course.id'},
1855: %form);
1856: }
1857: if ($removeform) {
1858: $companswer=~s|<form(.*?)>||g;
1859: $companswer=~s|</form>||g;
1860: $companswer=~s|name="submit"|name="would_have_been_submit"|g;
1861: }
1862: my $renderheading = &mt('View of the problem');
1863: my $answerheading = &mt('Correct answer');
1864: if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1865: my $stu_fullname = $env{'form.fullname'};
1866: if ($stu_fullname eq '') {
1867: $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
1868: }
1869: my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
1870: if ($forwhom ne '') {
1871: $renderheading = &mt('View of the problem for[_1]',$forwhom);
1872: $answerheading = &mt('Correct answer for[_1]',$forwhom);
1873: }
1874: }
1875: $rendered=
1876: '<div class="LC_Box">'
1877: .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1878: .$rendered
1879: .'</div>';
1880: $companswer=
1881: '<div class="LC_Box">'
1882: .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1883: .$companswer
1884: .'</div>';
1885: my $result;
1886: if ($mode eq 'both') {
1887: $result=$rendered.$companswer;
1888: } elsif ($mode eq 'text') {
1889: $result=$rendered;
1890: } elsif ($mode eq 'answer') {
1891: $result=$companswer;
1892: }
1893: return $result;
1894: }
1895:
1896: sub files_exist {
1897: my ($r, $symb) = @_;
1898: my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1899:
1900: foreach my $student (@students) {
1901: my ($uname,$udom,$fullname) = split(/:/,$student);
1902: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
1903: $udom,$uname);
1904: my ($string,$timestamp)= &get_last_submission(\%record);
1905: foreach my $submission (@$string) {
1906: my ($partid,$respid) =
1907: ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1908: my $files=&get_submitted_files($udom,$uname,$partid,$respid,
1909: \%record);
1910: return 1 if (@$files);
1911: }
1912: }
1913: return 0;
1914: }
1915:
1916: sub download_all_link {
1917: my ($r,$symb) = @_;
1918: unless (&files_exist($r, $symb)) {
1919: $r->print(&mt('There are currently no submitted documents.'));
1920: return;
1921: }
1922:
1923: my $all_students =
1924: join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
1925:
1926: my $parts =
1927: join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
1928:
1929: my $identifier = &Apache::loncommon::get_cgi_id();
1930: &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
1931: 'cgi.'.$identifier.'.symb' => $symb,
1932: 'cgi.'.$identifier.'.parts' => $parts,});
1933: $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
1934: &mt('Download All Submitted Documents').'</a>');
1935: return;
1936: }
1937:
1938: sub submit_download_link {
1939: my ($request,$symb) = @_;
1940: if (!$symb) { return ''; }
1941: #FIXME: Figure out which type of problem this is and provide appropriate download
1942: &download_all_link($request,$symb);
1943: }
1944:
1945: sub build_section_inputs {
1946: my $section_inputs;
1947: if ($env{'form.section'} eq '') {
1948: $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
1949: } else {
1950: my @sections = &Apache::loncommon::get_env_multiple('form.section');
1951: foreach my $section (@sections) {
1952: $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
1953: }
1954: }
1955: return $section_inputs;
1956: }
1957:
1958: # --------------------------- show submissions of a student, option to grade
1959: sub submission {
1960: my ($request,$counter,$total,$symb) = @_;
1961: my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
1962: $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
1963: my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
1964: $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1965:
1966: my $probtitle=&Apache::lonnet::gettitle($symb);
1967: if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1968:
1969: if (!&canview($usec)) {
1970: $request->print(
1971: '<span class="LC_warning">'.
1972: &mt('Unable to view requested student.').
1973: ' '.&mt('([_1] in section [_2] in course id [_3])',
1974: $uname.':'.$udom,$usec,$env{'request.course.id'}).
1975: '</span>');
1976: return;
1977: }
1978:
1979: if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
1980: if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
1981: if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
1982: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1983: my $checkIcon = '<img alt="'.&mt('Check Mark').
1984: '" src="'.$request->dir_config('lonIconsURL').
1985: '/check.gif" height="16" border="0" />';
1986:
1987: # header info
1988: if ($counter == 0) {
1989: &sub_page_js($request);
1990: &sub_page_kw_js($request);
1991:
1992: # option to display problem, only once else it cause problems
1993: # with the form later since the problem has a form.
1994: if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1995: my $mode;
1996: if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1997: $mode='both';
1998: } elsif ($env{'form.vProb'} eq 'yes') {
1999: $mode='text';
2000: } elsif ($env{'form.vAns'} eq 'yes') {
2001: $mode='answer';
2002: }
2003: &Apache::lonxml::clear_problem_counter();
2004: $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
2005: }
2006:
2007: # kwclr is the only variable that is guaranteed not to be blank
2008: # if this subroutine has been called once.
2009: my %keyhash = ();
2010: # if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
2011: if (1) {
2012: %keyhash = &Apache::lonnet::dump('nohist_handgrade',
2013: $env{'course.'.$env{'request.course.id'}.'.domain'},
2014: $env{'course.'.$env{'request.course.id'}.'.num'});
2015:
2016: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
2017: $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
2018: $env{'form.kwclr'} = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
2019: $env{'form.kwsize'} = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
2020: $env{'form.kwstyle'} = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
2021: $env{'form.msgsub'} = $keyhash{$symb.'_subject'} ne '' ?
2022: $keyhash{$symb.'_subject'} : $probtitle;
2023: $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
2024: }
2025: my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
2026: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
2027: $request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
2028: '<input type="hidden" name="command" value="handgrade" />'."\n".
2029: '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
2030: '<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
2031: '<input type="hidden" name="refresh" value="off" />'."\n".
2032: '<input type="hidden" name="studentNo" value="" />'."\n".
2033: '<input type="hidden" name="gradeOpt" value="" />'."\n".
2034: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
2035: '<input type="hidden" name="vProb" value="'.$env{'form.vProb'}.'" />'."\n".
2036: '<input type="hidden" name="vAns" value="'.$env{'form.vAns'}.'" />'."\n".
2037: '<input type="hidden" name="lastSub" value="'.$env{'form.lastSub'}.'" />'."\n".
2038: &build_section_inputs().
2039: '<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
2040: '<input type="hidden" name="NCT"'.
2041: ' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
2042: # if ($env{'form.handgrade'} eq 'yes') {
2043: if (1) {
2044: $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
2045: '<input type="hidden" name="kwclr" value="'.$env{'form.kwclr'}.'" />'."\n".
2046: '<input type="hidden" name="kwsize" value="'.$env{'form.kwsize'}.'" />'."\n".
2047: '<input type="hidden" name="kwstyle" value="'.$env{'form.kwstyle'}.'" />'."\n".
2048: '<input type="hidden" name="msgsub" value="'.$env{'form.msgsub'}.'" />'."\n".
2049: '<input type="hidden" name="shownSub" value="0" />'."\n".
2050: '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
2051: foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
2052: $request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
2053: }
2054: }
2055:
2056: my ($cts,$prnmsg) = (1,'');
2057: while ($cts <= $env{'form.savemsgN'}) {
2058: $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
2059: (!exists($keyhash{$symb.'_savemsg'.$cts}) ?
2060: &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
2061: &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
2062: '" />'."\n".
2063: '<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
2064: $cts++;
2065: }
2066: $request->print($prnmsg);
2067:
2068: # if ($env{'form.handgrade'} eq 'yes') {
2069: if (1) {
2070:
2071: my %lt = &Apache::lonlocal::texthash(
2072: keyh => 'Keyword Highlighting for Essays',
2073: keyw => 'Keyword Options',
2074: list => 'List',
2075: past => 'Paste Selection to List',
2076: high => 'Highlight Attribute',
2077: );
2078: #
2079: # Print out the keyword options line
2080: #
2081: $request->print(
2082: '<div class="LC_columnSection">'
2083: .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
2084: .&Apache::lonhtmlcommon::funclist_from_array(
2085: ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
2086: '<a href="#" onmousedown="javascript:getSel(); return false"
2087: class="page">'.$lt{'past'}.'</a>',
2088: '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
2089: {legend => $lt{'keyw'}})
2090: .'</fieldset></div>'
2091: );
2092:
2093: #
2094: # Load the other essays for similarity check
2095: #
2096: my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
2097: my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
2098: $apath=&escape($apath);
2099: $apath=~s/\W/\_/gs;
2100: &init_old_essays($symb,$apath,$adom,$aname);
2101: }
2102: }
2103:
2104: # This is where output for one specific student would start
2105: my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
2106: $request->print(
2107: "\n\n"
2108: .'<div class="LC_grade_show_user'.$add_class.'">'
2109: .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
2110: ."\n"
2111: );
2112:
2113: # Show additional functions if allowed
2114: if ($perm{'vgr'}) {
2115: $request->print(
2116: &Apache::loncommon::track_student_link(
2117: 'View recent activity',
2118: $uname,$udom,'check')
2119: .' '
2120: );
2121: }
2122: if ($perm{'opa'}) {
2123: $request->print(
2124: &Apache::loncommon::pprmlink(
2125: &mt('Set/Change parameters'),
2126: $uname,$udom,$symb,'check'));
2127: }
2128:
2129: # Show Problem
2130: if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
2131: my $mode;
2132: if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
2133: $mode='both';
2134: } elsif ($env{'form.vProb'} eq 'all' ) {
2135: $mode='text';
2136: } elsif ($env{'form.vAns'} eq 'all') {
2137: $mode='answer';
2138: }
2139: &Apache::lonxml::clear_problem_counter();
2140: $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
2141: }
2142:
2143: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
2144: my $res_error;
2145: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
2146: if ($res_error) {
2147: $request->print(&navmap_errormsg());
2148: return;
2149: }
2150:
2151: # Display student info
2152: $request->print(($counter == 0 ? '' : '<br />'));
2153:
2154: my $result='<div class="LC_Box">'
2155: .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
2156: $result.='<input type="hidden" name="name'.$counter.
2157: '" value="'.$env{'form.fullname'}.'" />'."\n";
2158: # if ($env{'form.handgrade'} eq 'no') {
2159: if (1) {
2160: $result.='<p class="LC_info">'
2161: .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
2162: ."</p>\n";
2163: }
2164:
2165: # If any part of the problem is an essay-response (handgraded), then check for collaborators
2166: my $fullname;
2167: my $col_fullnames = [];
2168: # if ($env{'form.handgrade'} eq 'yes') {
2169: if (1) {
2170: (my $sub_result,$fullname,$col_fullnames)=
2171: &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
2172: $counter);
2173: $result.=$sub_result;
2174: }
2175: $request->print($result."\n");
2176:
2177: # print student answer/submission
2178: # Options are (1) Handgraded submission only
2179: # (2) Last submission, includes submission that is not handgraded
2180: # (for multi-response type part)
2181: # (3) Last submission plus the parts info
2182: # (4) The whole record for this student
2183:
2184: my ($string,$timestamp)= &get_last_submission(\%record);
2185:
2186: my $lastsubonly;
2187:
2188: if ($$timestamp eq '') {
2189: $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>';
2190: } else {
2191: $lastsubonly =
2192: '<div class="LC_grade_submissions_body">'
2193: .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
2194:
2195: my %seenparts;
2196: my @part_response_id = &flatten_responseType($responseType);
2197: foreach my $part (@part_response_id) {
2198: next if ($env{'form.lastSub'} eq 'hdgrade'
2199: && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
2200:
2201: my ($partid,$respid) = @{ $part };
2202: my $display_part=&get_display_part($partid,$symb);
2203: if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
2204: if (exists($seenparts{$partid})) { next; }
2205: $seenparts{$partid}=1;
2206: $request->print(
2207: '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
2208: ' <b>'.&mt('Collaborative submission by: [_1]',
2209: '<a href="javascript:viewSubmitter(\''.
2210: $env{"form.$uname:$udom:$partid:submitted_by"}.
2211: '\');" target="_self">'.
2212: $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
2213: '<br />');
2214: next;
2215: }
2216: my $responsetype = $responseType->{$partid}->{$respid};
2217: if (!exists($record{"resource.$partid.$respid.submission"})) {
2218: $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
2219: '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
2220: ' <span class="LC_internal_info">'.
2221: '('.&mt('Response ID: [_1]',$respid).')'.
2222: '</span> '.
2223: '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
2224: next;
2225: }
2226: foreach my $submission (@$string) {
2227: my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
2228: if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
2229: my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
2230: # Similarity check
2231: my $similar='';
2232: my ($type,$trial,$rndseed);
2233: if ($hide eq 'rand') {
2234: $type = 'randomizetry';
2235: $trial = $record{"resource.$partid.tries"};
2236: $rndseed = $record{"resource.$partid.rndseed"};
2237: }
2238: if ($env{'form.checkPlag'}) {
2239: my ($oname,$odom,$ocrsid,$oessay,$osim)=
2240: &most_similar($uname,$udom,$symb,$subval);
2241: if ($osim) {
2242: $osim=int($osim*100.0);
2243: my %old_course_desc =
2244: &Apache::lonnet::coursedescription($ocrsid,
2245: {'one_time' => 1});
2246:
2247: if ($hide eq 'anon') {
2248: $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
2249: &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
2250: } else {
2251: $similar="<hr /><h3><span class=\"LC_warning\">".
2252: &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
2253: $osim,
2254: &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
2255: $old_course_desc{'description'},
2256: $old_course_desc{'num'},
2257: $old_course_desc{'domain'}).
2258: '</span></h3><blockquote><i>'.
2259: &keywords_highlight($oessay).
2260: '</i></blockquote><hr />';
2261: }
2262: }
2263: }
2264: my $order=&get_order($partid,$respid,$symb,$uname,$udom,
2265: undef,$type,$trial,$rndseed);
2266: if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' &&
2267: $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
2268: my $display_part=&get_display_part($partid,$symb);
2269: $lastsubonly.='<div class="LC_grade_submission_part">'.
2270: '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
2271: ' <span class="LC_internal_info">'.
2272: '('.&mt('Response ID: [_1]',$respid).')'.
2273: '</span> ';
2274: my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
2275:
2276: if (@$files) {
2277: if ($hide eq 'anon') {
2278: $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
2279: } else {
2280: $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
2281: .'<br /><span class="LC_warning">';
2282: if(@$files == 1) {
2283: $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
2284: } else {
2285: $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
2286: }
2287: $lastsubonly .= '</span>';
2288: foreach my $file (@$files) {
2289: &Apache::lonnet::allowuploaded('/adm/grades',$file);
2290: $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
2291: }
2292: }
2293: $lastsubonly.='<br />';
2294: }
2295: if ($hide eq 'anon') {
2296: $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>';
2297: } else {
2298: $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
2299: if ($draft) {
2300: $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
2301: }
2302: $subval =
2303: &cleanRecord($subval,$responsetype,$symb,$partid,
2304: $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
2305: if ($responsetype eq 'essay') {
2306: $subval =~ s{\n}{<br />}g;
2307: }
2308: $lastsubonly.=$subval."\n";
2309: }
2310: if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
2311: $lastsubonly.='</div>';
2312: }
2313: }
2314: }
2315: $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
2316: }
2317: $request->print($lastsubonly);
2318: if ($env{'form.lastSub'} eq 'datesub') {
2319: my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
2320: $request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
2321:
2322: }
2323: if ($env{'form.lastSub'} =~ /^(last|all)$/) {
2324: $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
2325: $env{'request.course.id'},
2326: $last,'.submission',
2327: 'Apache::grades::keywords_highlight'));
2328: }
2329: $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
2330: .$udom.'" />'."\n");
2331: # return if view submission with no grading option
2332: if (!&canmodify($usec)) {
2333: $request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
2334: return;
2335: } else {
2336: $request->print('</div>'."\n");
2337: }
2338:
2339: # essay grading message center
2340: # if ($env{'form.handgrade'} eq 'yes') {
2341: if (1) {
2342: my $result='<div class="LC_grade_message_center">';
2343:
2344: $result.='<div class="LC_grade_message_center_header">'.
2345: &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
2346: my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
2347: my $msgfor = $givenn.' '.$lastname;
2348: if (scalar(@$col_fullnames) > 0) {
2349: my $lastone = pop(@$col_fullnames);
2350: $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
2351: }
2352: $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
2353: $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
2354: '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
2355: $result.=' <a href="javascript:msgCenter(document.SCORE,'.$counter.
2356: ',\''.$msgfor.'\');" target="_self">'.
2357: &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
2358: &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
2359: ' <img src="'.$request->dir_config('lonIconsURL').
2360: '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
2361: '<br /> ('.
2362: &mt('Message will be sent when you click on Save & Next below.').")\n";
2363: $result.='</div></div>';
2364: $request->print($result);
2365: }
2366:
2367: my %seen = ();
2368: my @partlist;
2369: my @gradePartRespid;
2370: my @part_response_id = &flatten_responseType($responseType);
2371: $request->print(
2372: '<div class="LC_Box">'
2373: .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
2374: );
2375: $request->print(&gradeBox_start());
2376: foreach my $part_response_id (@part_response_id) {
2377: my ($partid,$respid) = @{ $part_response_id };
2378: my $part_resp = join('_',@{ $part_response_id });
2379: next if ($seen{$partid} > 0);
2380: $seen{$partid}++;
2381: next if ($$handgrade{$part_resp} ne 'yes'
2382: && $env{'form.lastSub'} eq 'hdgrade');
2383: push(@partlist,$partid);
2384: push(@gradePartRespid,$partid.'.'.$respid);
2385: $request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
2386: }
2387: $request->print(&gradeBox_end()); # </div>
2388: $request->print('</div>');
2389:
2390: $request->print('<div class="LC_grade_info_links">');
2391: $request->print('</div>');
2392:
2393: $result='<input type="hidden" name="partlist'.$counter.
2394: '" value="'.(join ":",@partlist).'" />'."\n";
2395: $result.='<input type="hidden" name="gradePartRespid'.
2396: '" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
2397: my $ctr = 0;
2398: while ($ctr < scalar(@partlist)) {
2399: $result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
2400: $partlist[$ctr].'" />'."\n";
2401: $ctr++;
2402: }
2403: $request->print($result.''."\n");
2404:
2405: # Done with printing info for one student
2406:
2407: $request->print('</div>');#LC_grade_show_user
2408:
2409:
2410: # print end of form
2411: if ($counter == $total) {
2412: my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
2413: $endform.='<input type="button" value="'.&mt('Save & Next').'" '.
2414: 'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
2415: $total.','.scalar(@partlist).');" target="_self" /> '."\n";
2416: my $ntstu ='<select name="NTSTU">'.
2417: '<option>1</option><option>2</option>'.
2418: '<option>3</option><option>5</option>'.
2419: '<option>7</option><option>10</option></select>'."\n";
2420: my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
2421: $ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
2422: $endform.=&mt('[_1]student(s)',$ntstu);
2423: $endform.=' <input type="button" value="'.&mt('Previous').'" '.
2424: 'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> '."\n".
2425: '<input type="button" value="'.&mt('Next').'" '.
2426: 'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> ';
2427: $endform.='<span class="LC_warning">'.
2428: &mt('(Next and Previous (student) do not save the scores.)').
2429: '</span>'."\n" ;
2430: $endform.="<input type='hidden' value='".&get_increment().
2431: "' name='increment' />";
2432: $endform.='</td></tr></table></form>';
2433: $request->print($endform);
2434: }
2435: return '';
2436: }
2437:
2438: sub check_collaborators {
2439: my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
2440: my ($result,@col_fullnames);
2441: my ($classlist,undef,$fullname) = &getclasslist('all','0');
2442: foreach my $part (keys(%$handgrade)) {
2443: my $ncol = &Apache::lonnet::EXT('resource.'.$part.
2444: '.maxcollaborators',
2445: $symb,$udom,$uname);
2446: next if ($ncol <= 0);
2447: $part =~ s/\_/\./g;
2448: next if ($record->{'resource.'.$part.'.collaborators'} eq '');
2449: my (@good_collaborators, @bad_collaborators);
2450: foreach my $possible_collaborator
2451: (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) {
2452: $possible_collaborator =~ s/[\$\^\(\)]//g;
2453: next if ($possible_collaborator eq '');
2454: my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
2455: $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
2456: next if ($co_name eq $uname && $co_dom eq $udom);
2457: # Doing this grep allows 'fuzzy' specification
2458: my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i,
2459: keys(%$classlist));
2460: if (! scalar(@matches)) {
2461: push(@bad_collaborators, $possible_collaborator);
2462: } else {
2463: push(@good_collaborators, @matches);
2464: }
2465: }
2466: if (scalar(@good_collaborators) != 0) {
2467: $result.='<br />'.&mt('Collaborators:').'<ol>';
2468: foreach my $name (@good_collaborators) {
2469: my ($lastname,$givenn) = split(/,/,$$fullname{$name});
2470: push(@col_fullnames, $givenn.' '.$lastname);
2471: $result.='<li>'.$fullname->{$name}.'</li>';
2472: }
2473: $result.='</ol><br />'."\n";
2474: my ($part)=split(/\./,$part);
2475: $result.='<input type="hidden" name="collaborator'.$counter.
2476: '" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
2477: "\n";
2478: }
2479: if (scalar(@bad_collaborators) > 0) {
2480: $result.='<div class="LC_warning">';
2481: $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
2482: $result .= '</div>';
2483: }
2484: if (scalar(@bad_collaborators > $ncol)) {
2485: $result .= '<div class="LC_warning">';
2486: $result .= &mt('This student has submitted too many '.
2487: 'collaborators. Maximum is [_1].',$ncol);
2488: $result .= '</div>';
2489: }
2490: }
2491: return ($result,$fullname,\@col_fullnames);
2492: }
2493:
2494: #--- Retrieve the last submission for all the parts
2495: sub get_last_submission {
2496: my ($returnhash)=@_;
2497: my (@string,$timestamp,%lasthidden);
2498: if ($$returnhash{'version'}) {
2499: my %lasthash=();
2500: my ($version);
2501: for ($version=1;$version<=$$returnhash{'version'};$version++) {
2502: foreach my $key (sort(split(/\:/,
2503: $$returnhash{$version.':keys'}))) {
2504: $lasthash{$key}=$$returnhash{$version.':'.$key};
2505: $timestamp =
2506: &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
2507: }
2508: }
2509: my (%typeparts,%randombytry);
2510: my $showsurv =
2511: &Apache::lonnet::allowed('vas',$env{'request.course.id'});
2512: foreach my $key (sort(keys(%lasthash))) {
2513: if ($key =~ /\.type$/) {
2514: if (($lasthash{$key} eq 'anonsurvey') ||
2515: ($lasthash{$key} eq 'anonsurveycred') ||
2516: ($lasthash{$key} eq 'randomizetry')) {
2517: my ($ign,@parts) = split(/\./,$key);
2518: pop(@parts);
2519: my $id = join('.',@parts);
2520: if ($lasthash{$key} eq 'randomizetry') {
2521: $randombytry{$ign.'.'.$id} = $lasthash{$key};
2522: } else {
2523: unless ($showsurv) {
2524: $typeparts{$ign.'.'.$id} = $lasthash{$key};
2525: }
2526: }
2527: delete($lasthash{$key});
2528: }
2529: }
2530: }
2531: my @hidden = keys(%typeparts);
2532: my @randomize = keys(%randombytry);
2533: foreach my $key (keys(%lasthash)) {
2534: next if ($key !~ /\.submission$/);
2535: my $hide;
2536: if (@hidden) {
2537: foreach my $id (@hidden) {
2538: if ($key =~ /^\Q$id\E/) {
2539: $hide = 'anon';
2540: last;
2541: }
2542: }
2543: }
2544: unless ($hide) {
2545: if (@randomize) {
2546: foreach my $id (@hidden) {
2547: if ($key =~ /^\Q$id\E/) {
2548: $hide = 'rand';
2549: last;
2550: }
2551: }
2552: }
2553: }
2554: my ($partid,$foo) = split(/submission$/,$key);
2555: my $draft = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
2556: #push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
2557: push(@string, join(':', $key, $hide, $draft, (
2558: ref($lasthash{$key}) eq 'ARRAY' ?
2559: join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
2560: }
2561: }
2562: if (!@string) {
2563: $string[0] =
2564: '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
2565: }
2566: return (\@string,\$timestamp);
2567: }
2568:
2569: #--- High light keywords, with style choosen by user.
2570: sub keywords_highlight {
2571: my $string = shift;
2572: my $size = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
2573: my $styleon = $env{'form.kwstyle'} eq '' ? '' : $env{'form.kwstyle'};
2574: (my $styleoff = $styleon) =~ s/\</\<\//;
2575: my @keylist = split(/[,\s+]/,$env{'form.keywords'});
2576: foreach my $keyword (@keylist) {
2577: $string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
2578: }
2579: return $string;
2580: }
2581:
2582: # For Tasks provide a mechanism to display previous version for one specific student
2583:
2584: sub show_previous_task_version {
2585: my ($request,$symb) = @_;
2586: if ($symb eq '') {
2587: $request->print(
2588: '<span class="LC_error">'.
2589: &mt('Unable to handle ambiguous references.').
2590: '</span>');
2591: return '';
2592: }
2593: my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
2594: my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
2595: if (!&canview($usec)) {
2596: $request->print(
2597: '<span class="LC_warning">'.
2598: &mt('Unable to view previous version for requested student.').
2599: ' '.&mt('([_1] in section [_2] in course id [_3])',
2600: $uname.':'.$udom,$usec,$env{'request.course.id'}).
2601: '</span>');
2602: return;
2603: }
2604: my $mode = 'both';
2605: my $isTask = ($symb =~/\.task$/);
2606: if ($isTask) {
2607: if ($env{'form.previousversion'} =~ /^\d+$/) {
2608: if ($env{'form.fullname'} eq '') {
2609: $env{'form.fullname'} =
2610: &Apache::loncommon::plainname($uname,$udom,'lastname');
2611: }
2612: my $probtitle=&Apache::lonnet::gettitle($symb);
2613: $request->print("\n\n".
2614: '<div class="LC_grade_show_user">'.
2615: '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
2616: '</h2>'."\n");
2617: &Apache::lonxml::clear_problem_counter();
2618: $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
2619: {'previousversion' => $env{'form.previousversion'} }));
2620: $request->print("\n</div>");
2621: }
2622: }
2623: return;
2624: }
2625:
2626: sub choose_task_version_form {
2627: my ($symb,$uname,$udom,$nomenu) = @_;
2628: my $isTask = ($symb =~/\.task$/);
2629: my ($current,$version,$result,$js,$displayed,$rowtitle);
2630: if ($isTask) {
2631: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
2632: $udom,$uname);
2633: if (($record{'resource.0.version'} eq '') ||
2634: ($record{'resource.0.version'} < 2)) {
2635: return ($record{'resource.0.version'},
2636: $record{'resource.0.version'},$result,$js);
2637: } else {
2638: $current = $record{'resource.0.version'};
2639: }
2640: if ($env{'form.previousversion'}) {
2641: $displayed = $env{'form.previousversion'};
2642: $rowtitle = &mt('Choose another version:')
2643: } else {
2644: $displayed = $current;
2645: $rowtitle = &mt('Show earlier version:');
2646: }
2647: $result = '<div class="LC_left_float">';
2648: my $list;
2649: my $numversions = 0;
2650: for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
2651: if ($i == $current) {
2652: if (!$env{'form.previousversion'} || $nomenu) {
2653: next;
2654: } else {
2655: $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
2656: $numversions ++;
2657: }
2658: } elsif (defined($record{'resource.'.$i.'.0.status'})) {
2659: unless ($i == $env{'form.previousversion'}) {
2660: $numversions ++;
2661: }
2662: $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
2663: }
2664: }
2665: if ($numversions) {
2666: $symb = &HTML::Entities::encode($symb,'<>"&');
2667: $result .=
2668: '<form name="getprev" method="post" action=""'.
2669: ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
2670: &Apache::loncommon::start_data_table().
2671: &Apache::loncommon::start_data_table_row().
2672: '<th align="left">'.$rowtitle.'</th>'.
2673: '<td><select name="version">'.
2674: '<option>'.&mt('Select').'</option>'.
2675: $list.
2676: '</select></td>'.
2677: &Apache::loncommon::end_data_table_row();
2678: unless ($nomenu) {
2679: $result .= &Apache::loncommon::start_data_table_row().
2680: '<th align="left">'.&mt('Open in new window').'</th>'.
2681: '<td><span class="LC_nobreak">'.
2682: '<label><input type="radio" name="prevwin" value="1" />'.
2683: &mt('Yes').'</label>'.
2684: '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
2685: '</span></td>'.
2686: &Apache::loncommon::end_data_table_row();
2687: }
2688: $result .=
2689: &Apache::loncommon::start_data_table_row().
2690: '<th align="left"> </th>'.
2691: '<td>'.
2692: '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
2693: '</td>'.
2694: &Apache::loncommon::end_data_table_row().
2695: &Apache::loncommon::end_data_table().
2696: '</form>';
2697: $js = &previous_display_javascript($nomenu,$current);
2698: } elsif ($displayed && $nomenu) {
2699: $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
2700: } else {
2701: $result .= &mt('No previous versions to show for this student');
2702: }
2703: $result .= '</div>';
2704: }
2705: return ($current,$displayed,$result,$js);
2706: }
2707:
2708: sub previous_display_javascript {
2709: my ($nomenu,$current) = @_;
2710: my $js = <<"JSONE";
2711: <script type="text/javascript">
2712: // <![CDATA[
2713: function previousVersion(uname,udom,symb) {
2714: var current = '$current';
2715: var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
2716: var prevstr = new RegExp("^\\\\d+\$");
2717: if (!prevstr.test(version)) {
2718: return false;
2719: }
2720: var url = '';
2721: if (version == current) {
2722: url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
2723: } else {
2724: url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
2725: }
2726: JSONE
2727: if ($nomenu) {
2728: $js .= <<"JSTWO";
2729: document.location.href = url;
2730: JSTWO
2731: } else {
2732: $js .= <<"JSTHREE";
2733: var newwin = 0;
2734: for (var i=0; i<document.getprev.prevwin.length; i++) {
2735: if (document.getprev.prevwin[i].checked == true) {
2736: newwin = document.getprev.prevwin[i].value;
2737: }
2738: }
2739: if (newwin == 1) {
2740: var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
2741: url = url+'&inhibitmenu=yes';
2742: if (typeof(previousWin) == 'undefined' || previousWin.closed) {
2743: previousWin = window.open(url,'',options,1);
2744: } else {
2745: previousWin.location.href = url;
2746: }
2747: previousWin.focus();
2748: return false;
2749: } else {
2750: document.location.href = url;
2751: return false;
2752: }
2753: JSTHREE
2754: }
2755: $js .= <<"ENDJS";
2756: return false;
2757: }
2758: // ]]>
2759: </script>
2760: ENDJS
2761:
2762: }
2763:
2764: #--- Called from submission routine
2765: sub processHandGrade {
2766: my ($request,$symb) = @_;
2767: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
2768: my $button = $env{'form.gradeOpt'};
2769: my $ngrade = $env{'form.NCT'};
2770: my $ntstu = $env{'form.NTSTU'};
2771: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2772: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2773:
2774: if ($button eq 'Save & Next') {
2775: my $ctr = 0;
2776: while ($ctr < $ngrade) {
2777: my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
2778: my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
2779: if ($errorflag eq 'no_score') {
2780: $ctr++;
2781: next;
2782: }
2783: if ($errorflag eq 'not_allowed') {
2784: $request->print(
2785: '<span class="LC_error">'
2786: .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
2787: .'</span>');
2788: $ctr++;
2789: next;
2790: }
2791: my $includemsg = $env{'form.includemsg'.$ctr};
2792: my ($subject,$message,$msgstatus) = ('','','');
2793: my $restitle = &Apache::lonnet::gettitle($symb);
2794: my ($feedurl,$showsymb) =
2795: &get_feedurl_and_symb($symb,$uname,$udom);
2796: my $messagetail;
2797: if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
2798: $subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
2799: unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
2800: $subject.=' ['.$restitle.']';
2801: my (@msgnum) = split(/,/,$includemsg);
2802: foreach (@msgnum) {
2803: $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
2804: }
2805: $message =&Apache::lonfeedback::clear_out_html($message);
2806: if ($env{'form.withgrades'.$ctr}) {
2807: $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
2808: $messagetail = " for <a href=\"".
2809: $feedurl."?symb=$showsymb\">$restitle</a>";
2810: }
2811: $msgstatus =
2812: &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
2813: $message.$messagetail,
2814: undef,$feedurl,undef,
2815: undef,undef,$showsymb,
2816: $restitle);
2817: $request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
2818: $msgstatus.'<br />');
2819: }
2820: if ($env{'form.collaborator'.$ctr}) {
2821: my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
2822: foreach my $collabstr (@collabstrs) {
2823: my ($part,@collaborators) = split(/:/,$collabstr);
2824: foreach my $collaborator (@collaborators) {
2825: my ($errorflag,$pts,$wgt) =
2826: &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
2827: $env{'form.unamedom'.$ctr},$part);
2828: if ($errorflag eq 'not_allowed') {
2829: $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
2830: next;
2831: } elsif ($message ne '') {
2832: my ($baseurl,$showsymb) =
2833: &get_feedurl_and_symb($symb,$collaborator,
2834: $udom);
2835: if ($env{'form.withgrades'.$ctr}) {
2836: $messagetail = " for <a href=\"".
2837: $baseurl."?symb=$showsymb\">$restitle</a>";
2838: }
2839: $msgstatus =
2840: &Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
2841: }
2842: }
2843: }
2844: }
2845: $ctr++;
2846: }
2847: }
2848:
2849: # if ($env{'form.handgrade'} eq 'yes') {
2850: if (1) {
2851: # Keywords sorted in alphabatical order
2852: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
2853: my %keyhash = ();
2854: $env{'form.keywords'} =~ s/,\s{0,}|\s+/ /g;
2855: $env{'form.keywords'} =~ s/^\s+|\s+$//;
2856: my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
2857: $env{'form.keywords'} = join(' ',@keywords);
2858: $keyhash{$symb.'_keywords'} = $env{'form.keywords'};
2859: $keyhash{$symb.'_subject'} = $env{'form.msgsub'};
2860: $keyhash{$loginuser.'_kwclr'} = $env{'form.kwclr'};
2861: $keyhash{$loginuser.'_kwsize'} = $env{'form.kwsize'};
2862: $keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
2863:
2864: # message center - Order of message gets changed. Blank line is eliminated.
2865: # New messages are saved in env for the next student.
2866: # All messages are saved in nohist_handgrade.db
2867: my ($ctr,$idx) = (1,1);
2868: while ($ctr <= $env{'form.savemsgN'}) {
2869: if ($env{'form.savemsg'.$ctr} ne '') {
2870: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
2871: $idx++;
2872: }
2873: $ctr++;
2874: }
2875: $ctr = 0;
2876: while ($ctr < $ngrade) {
2877: if ($env{'form.newmsg'.$ctr} ne '') {
2878: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2879: $env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2880: $idx++;
2881: }
2882: $ctr++;
2883: }
2884: $env{'form.savemsgN'} = --$idx;
2885: $keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
2886: my $putresult = &Apache::lonnet::put
2887: ('nohist_handgrade',\%keyhash,$cdom,$cnum);
2888: }
2889: # Called by Save & Refresh from Highlight Attribute Window
2890: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
2891: if ($env{'form.refresh'} eq 'on') {
2892: my ($ctr,$total) = (0,0);
2893: while ($ctr < $ngrade) {
2894: $total++ if $env{'form.unamedom'.$ctr} ne '';
2895: $ctr++;
2896: }
2897: $env{'form.NTSTU'}=$ngrade;
2898: $ctr = 0;
2899: while ($ctr < $total) {
2900: my $processUser = $env{'form.unamedom'.$ctr};
2901: ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
2902: $env{'form.fullname'} = $$fullname{$processUser};
2903: &submission($request,$ctr,$total-1,$symb);
2904: $ctr++;
2905: }
2906: return '';
2907: }
2908:
2909: # Get the next/previous one or group of students
2910: my $firststu = $env{'form.unamedom0'};
2911: my $laststu = $env{'form.unamedom'.($ngrade-1)};
2912: my $ctr = 2;
2913: while ($laststu eq '') {
2914: $laststu = $env{'form.unamedom'.($ngrade-$ctr)};
2915: $ctr++;
2916: $laststu = $firststu if ($ctr > $ngrade);
2917: }
2918:
2919: my (@parsedlist,@nextlist);
2920: my ($nextflg) = 0;
2921: foreach my $item (sort
2922: {
2923: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
2924: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
2925: }
2926: return $a cmp $b;
2927: } (keys(%$fullname))) {
2928: # FIXME: this is fishy, looks like the button label
2929: if ($nextflg == 1 && $button =~ /Next$/) {
2930: push(@parsedlist,$item);
2931: }
2932: $nextflg = 1 if ($item eq $laststu);
2933: if ($button eq 'Previous') {
2934: last if ($item eq $firststu);
2935: push(@parsedlist,$item);
2936: }
2937: }
2938: $ctr = 0;
2939: # FIXME: this is fishy, looks like the button label
2940: @parsedlist = reverse @parsedlist if ($button eq 'Previous');
2941: my $res_error;
2942: my ($partlist) = &response_type($symb,\$res_error);
2943: if ($res_error) {
2944: $request->print(&navmap_errormsg());
2945: return;
2946: }
2947: foreach my $student (@parsedlist) {
2948: my $submitonly=$env{'form.submitonly'};
2949: my ($uname,$udom) = split(/:/,$student);
2950:
2951: if ($submitonly eq 'queued') {
2952: my %queue_status =
2953: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
2954: $udom,$uname);
2955: next if (!defined($queue_status{'gradingqueue'}));
2956: }
2957:
2958: if ($submitonly =~ /^(yes|graded|incorrect)$/) {
2959: # my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
2960: my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
2961: my $submitted = 0;
2962: my $ungraded = 0;
2963: my $incorrect = 0;
2964: foreach my $item (keys(%status)) {
2965: $submitted = 1 if ($status{$item} ne 'nothing');
2966: $ungraded = 1 if ($status{$item} =~ /^ungraded/);
2967: $incorrect = 1 if ($status{$item} =~ /^incorrect/);
2968: my ($foo,$partid,$foo1) = split(/\./,$item);
2969: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
2970: $submitted = 0;
2971: }
2972: }
2973: next if (!$submitted && ($submitonly eq 'yes' ||
2974: $submitonly eq 'incorrect' ||
2975: $submitonly eq 'graded'));
2976: next if (!$ungraded && ($submitonly eq 'graded'));
2977: next if (!$incorrect && $submitonly eq 'incorrect');
2978: }
2979: push(@nextlist,$student) if ($ctr < $ntstu);
2980: last if ($ctr == $ntstu);
2981: $ctr++;
2982: }
2983:
2984: $ctr = 0;
2985: my $total = scalar(@nextlist)-1;
2986:
2987: foreach (sort(@nextlist)) {
2988: my ($uname,$udom,$submitter) = split(/:/);
2989: $env{'form.student'} = $uname;
2990: $env{'form.userdom'} = $udom;
2991: $env{'form.fullname'} = $$fullname{$_};
2992: &submission($request,$ctr,$total,$symb);
2993: $ctr++;
2994: }
2995: if ($total < 0) {
2996: my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
2997: $request->print($the_end);
2998: }
2999: return '';
3000: }
3001:
3002: #---- Save the score and award for each student, if changed
3003: sub saveHandGrade {
3004: my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
3005: my @version_parts;
3006: my $usec = &Apache::lonnet::getsection($domain,$stuname,
3007: $env{'request.course.id'});
3008: if (!&canmodify($usec)) { return('not_allowed'); }
3009: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
3010: my @parts_graded;
3011: my %newrecord = ();
3012: my ($pts,$wgt) = ('','');
3013: my %aggregate = ();
3014: my $aggregateflag = 0;
3015: my @parts = split(/:/,$env{'form.partlist'.$newflg});
3016: foreach my $new_part (@parts) {
3017: #collaborator ($submi may vary for different parts
3018: if ($submitter && $new_part ne $part) { next; }
3019: my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
3020: if ($dropMenu eq 'excused') {
3021: if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
3022: $newrecord{'resource.'.$new_part.'.solved'} = 'excused';
3023: if (exists($record{'resource.'.$new_part.'.awarded'})) {
3024: $newrecord{'resource.'.$new_part.'.awarded'} = '';
3025: }
3026: $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
3027: }
3028: } elsif ($dropMenu eq 'reset status'
3029: && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
3030: foreach my $key (keys(%record)) {
3031: if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
3032: }
3033: $newrecord{'resource.'.$new_part.'.regrader'}=
3034: "$env{'user.name'}:$env{'user.domain'}";
3035: my $totaltries = $record{'resource.'.$part.'.tries'};
3036:
3037: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
3038: [$new_part]);
3039: my $aggtries =$totaltries;
3040: if ($last_resets{$new_part}) {
3041: $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
3042: $new_part);
3043: }
3044:
3045: my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
3046: if ($aggtries > 0) {
3047: &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
3048: $aggregateflag = 1;
3049: }
3050: } elsif ($dropMenu eq '') {
3051: $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ?
3052: $env{'form.GD_BOX'.$newflg.'_'.$new_part} :
3053: $env{'form.RADVAL'.$newflg.'_'.$new_part});
3054: if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
3055: next;
3056: }
3057: $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 :
3058: $env{'form.WGT'.$newflg.'_'.$new_part};
3059: my $partial= $pts/$wgt;
3060: if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
3061: #do not update score for part if not changed.
3062: &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
3063: next;
3064: } else {
3065: push(@parts_graded,$new_part);
3066: }
3067: if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
3068: $newrecord{'resource.'.$new_part.'.awarded'} = $partial;
3069: }
3070: my $reckey = 'resource.'.$new_part.'.solved';
3071: if ($partial == 0) {
3072: if ($record{$reckey} ne 'incorrect_by_override') {
3073: $newrecord{$reckey} = 'incorrect_by_override';
3074: }
3075: } else {
3076: if ($record{$reckey} ne 'correct_by_override') {
3077: $newrecord{$reckey} = 'correct_by_override';
3078: }
3079: }
3080: if ($submitter &&
3081: ($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
3082: $newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
3083: }
3084: $newrecord{'resource.'.$new_part.'.regrader'}=
3085: "$env{'user.name'}:$env{'user.domain'}";
3086: }
3087: # unless problem has been graded, set flag to version the submitted files
3088: unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/ ||
3089: $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
3090: $dropMenu eq 'reset status')
3091: {
3092: push(@version_parts,$new_part);
3093: }
3094: }
3095: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3096: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3097:
3098: if (%newrecord) {
3099: if (@version_parts) {
3100: my @changed_keys = &version_portfiles(\%record, \@parts_graded,
3101: $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
3102: @newrecord{@changed_keys} = @record{@changed_keys};
3103: foreach my $new_part (@version_parts) {
3104: &handback_files($request,$symb,$stuname,$domain,$newflg,
3105: $new_part,\%newrecord);
3106: }
3107: }
3108: &Apache::lonnet::cstore(\%newrecord,$symb,
3109: $env{'request.course.id'},$domain,$stuname);
3110: &check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
3111: $cdom,$cnum,$domain,$stuname);
3112: }
3113: if ($aggregateflag) {
3114: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
3115: $cdom,$cnum);
3116: }
3117: return ('',$pts,$wgt);
3118: }
3119:
3120: sub check_and_remove_from_queue {
3121: my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
3122: my @ungraded_parts;
3123: foreach my $part (@{$parts}) {
3124: if ( $record->{ 'resource.'.$part.'.awarded'} eq ''
3125: && $record->{ 'resource.'.$part.'.solved' } ne 'excused'
3126: && $newrecord->{'resource.'.$part.'.awarded'} eq ''
3127: && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
3128: ) {
3129: push(@ungraded_parts, $part);
3130: }
3131: }
3132: if ( !@ungraded_parts ) {
3133: &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
3134: $cnum,$domain,$stuname);
3135: }
3136: }
3137:
3138: sub handback_files {
3139: my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
3140: my $portfolio_root = '/userfiles/portfolio';
3141: my $res_error;
3142: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
3143: if ($res_error) {
3144: $request->print('<br />'.&navmap_errormsg().'<br />');
3145: return;
3146: }
3147: my @handedback;
3148: my $file_msg;
3149: my @part_response_id = &flatten_responseType($responseType);
3150: foreach my $part_response_id (@part_response_id) {
3151: my ($part_id,$resp_id) = @{ $part_response_id };
3152: my $part_resp = join('_',@{ $part_response_id });
3153: if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
3154: for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
3155: # if multiple files are uploaded names will be 'returndoc2','returndoc3'
3156: if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
3157: my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
3158: my ($directory,$answer_file) =
3159: ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
3160: my ($answer_name,$answer_ver,$answer_ext) =
3161: &file_name_version_ext($answer_file);
3162: my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
3163: my $getpropath = 1;
3164: my ($dir_list,$listerror) =
3165: &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
3166: $domain,$stuname,$getpropath);
3167: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
3168: # fix filename
3169: my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
3170: my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
3171: $newflg.'_'.$part_resp.'_returndoc'.$counter,
3172: $save_file_name);
3173: if ($result !~ m|^/uploaded/|) {
3174: $request->print('<br /><span class="LC_error">'.
3175: &mt('An error occurred ([_1]) while trying to upload [_2].',
3176: $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
3177: '</span>');
3178: } else {
3179: # mark the file as read only
3180: push(@handedback,$save_file_name);
3181: if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
3182: $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
3183: }
3184: $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
3185: $file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
3186: }
3187: $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>'));
3188: }
3189: }
3190: }
3191: }
3192: if (@handedback > 0) {
3193: $request->print('<br />');
3194: my @what = ($symb,$env{'request.course.id'},'handback');
3195: &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
3196: my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});
3197: my ($subject,$message);
3198: if (scalar(@handedback) == 1) {
3199: $subject = &mt_user($user_lh,'File Handed Back by Instructor');
3200: $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
3201: } else {
3202: $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
3203: $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
3204: }
3205: $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
3206: $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
3207: &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
3208: my ($feedurl,$showsymb) =
3209: &get_feedurl_and_symb($symb,$domain,$stuname);
3210: my $restitle = &Apache::lonnet::gettitle($symb);
3211: $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
3212: my $msgstatus =
3213: &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
3214: $message,undef,$feedurl,undef,undef,undef,$showsymb,
3215: $restitle);
3216: if ($msgstatus) {
3217: $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
3218: }
3219: }
3220: return;
3221: }
3222:
3223: sub get_feedurl_and_symb {
3224: my ($symb,$uname,$udom) = @_;
3225: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3226: $url = &Apache::lonnet::clutter($url);
3227: my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
3228: $symb,$udom,$uname);
3229: if ($encrypturl =~ /^yes$/i) {
3230: &Apache::lonenc::encrypted(\$url,1);
3231: &Apache::lonenc::encrypted(\$symb,1);
3232: }
3233: return ($url,$symb);
3234: }
3235:
3236: sub get_submitted_files {
3237: my ($udom,$uname,$partid,$respid,$record) = @_;
3238: my @files;
3239: if ($$record{"resource.$partid.$respid.portfiles"}) {
3240: my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
3241: foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
3242: push(@files,$file_url.$file);
3243: }
3244: }
3245: if ($$record{"resource.$partid.$respid.uploadedurl"}) {
3246: push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
3247: }
3248: return (\@files);
3249: }
3250:
3251: # ----------- Provides number of tries since last reset.
3252: sub get_num_tries {
3253: my ($record,$last_reset,$part) = @_;
3254: my $timestamp = '';
3255: my $num_tries = 0;
3256: if ($$record{'version'}) {
3257: for (my $version=$$record{'version'};$version>=1;$version--) {
3258: if (exists($$record{$version.':resource.'.$part.'.solved'})) {
3259: $timestamp = $$record{$version.':timestamp'};
3260: if ($timestamp > $last_reset) {
3261: $num_tries ++;
3262: } else {
3263: last;
3264: }
3265: }
3266: }
3267: }
3268: return $num_tries;
3269: }
3270:
3271: # ----------- Determine decrements required in aggregate totals
3272: sub decrement_aggs {
3273: my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
3274: my %decrement = (
3275: attempts => 0,
3276: users => 0,
3277: correct => 0
3278: );
3279: $decrement{'attempts'} = $aggtries;
3280: if ($solvedstatus =~ /^correct/) {
3281: $decrement{'correct'} = 1;
3282: }
3283: if ($aggtries == $totaltries) {
3284: $decrement{'users'} = 1;
3285: }
3286: foreach my $type (keys(%decrement)) {
3287: $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
3288: }
3289: return;
3290: }
3291:
3292: # ----------- Determine timestamps for last reset of aggregate totals for parts
3293: sub get_last_resets {
3294: my ($symb,$courseid,$partids) =@_;
3295: my %last_resets;
3296: my $cdom = $env{'course.'.$courseid.'.domain'};
3297: my $cname = $env{'course.'.$courseid.'.num'};
3298: my @keys;
3299: foreach my $part (@{$partids}) {
3300: push(@keys,"$symb\0$part\0resettime");
3301: }
3302: my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
3303: $cdom,$cname);
3304: foreach my $part (@{$partids}) {
3305: $last_resets{$part}=$results{"$symb\0$part\0resettime"};
3306: }
3307: return %last_resets;
3308: }
3309:
3310: # ----------- Handles creating versions for portfolio files as answers
3311: sub version_portfiles {
3312: my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
3313: my $version_parts = join('|',@$v_flag);
3314: my @returned_keys;
3315: my $parts = join('|', @$parts_graded);
3316: my $portfolio_root = '/userfiles/portfolio';
3317: foreach my $key (keys(%$record)) {
3318: my $new_portfiles;
3319: if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
3320: my @versioned_portfiles;
3321: my @portfiles = split(/\s*,\s*/,$$record{$key});
3322: foreach my $file (@portfiles) {
3323: &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
3324: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
3325: my ($answer_name,$answer_ver,$answer_ext) =
3326: &file_name_version_ext($answer_file);
3327: my $getpropath = 1;
3328: my ($dir_list,$listerror) =
3329: &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
3330: $stu_name,$getpropath);
3331: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
3332: my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
3333: if ($new_answer ne 'problem getting file') {
3334: push(@versioned_portfiles, $directory.$new_answer);
3335: &Apache::lonnet::mark_as_readonly($domain,$stu_name,
3336: [$directory.$new_answer],
3337: [$symb,$env{'request.course.id'},'graded']);
3338: }
3339: }
3340: $$record{$key} = join(',',@versioned_portfiles);
3341: push(@returned_keys,$key);
3342: }
3343: }
3344: return (@returned_keys);
3345: }
3346:
3347: sub get_next_version {
3348: my ($answer_name, $answer_ext, $dir_list) = @_;
3349: my $version;
3350: if (ref($dir_list) eq 'ARRAY') {
3351: foreach my $row (@{$dir_list}) {
3352: my ($file) = split(/\&/,$row,2);
3353: my ($file_name,$file_version,$file_ext) =
3354: &file_name_version_ext($file);
3355: if (($file_name eq $answer_name) &&
3356: ($file_ext eq $answer_ext)) {
3357: # gets here if filename and extension match,
3358: # regardless of version
3359: if ($file_version ne '') {
3360: # a versioned file is found so save it for later
3361: if ($file_version > $version) {
3362: $version = $file_version;
3363: }
3364: }
3365: }
3366: }
3367: }
3368: $version ++;
3369: return($version);
3370: }
3371:
3372: sub version_selected_portfile {
3373: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
3374: my ($answer_name,$answer_ver,$answer_ext) =
3375: &file_name_version_ext($file_name);
3376: my $new_answer;
3377: $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
3378: if($env{'form.copy'} eq '-1') {
3379: $new_answer = 'problem getting file';
3380: } else {
3381: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
3382: my $copy_result = &Apache::lonnet::finishuserfileupload(
3383: $stu_name,$domain,'copy',
3384: '/portfolio'.$directory.$new_answer);
3385: }
3386: return ($new_answer);
3387: }
3388:
3389: sub file_name_version_ext {
3390: my ($file)=@_;
3391: my @file_parts = split(/\./, $file);
3392: my ($name,$version,$ext);
3393: if (@file_parts > 1) {
3394: $ext=pop(@file_parts);
3395: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
3396: $version=pop(@file_parts);
3397: }
3398: $name=join('.',@file_parts);
3399: } else {
3400: $name=join('.',@file_parts);
3401: }
3402: return($name,$version,$ext);
3403: }
3404:
3405: #--------------------------------------------------------------------------------------
3406: #
3407: #-------------------------- Next few routines handles grading by section or whole class
3408: #
3409: #--- Javascript to handle grading by section or whole class
3410: sub viewgrades_js {
3411: my ($request) = shift;
3412:
3413: my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
3414: $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
3415: function writePoint(partid,weight,point) {
3416: var radioButton = document.classgrade["RADVAL_"+partid];
3417: var textbox = document.classgrade["TEXTVAL_"+partid];
3418: if (point == "textval") {
3419: point = document.classgrade["TEXTVAL_"+partid].value;
3420: if (isNaN(point) || parseFloat(point) < 0) {
3421: alert("$alertmsg"+parseFloat(point));
3422: var resetbox = false;
3423: for (var i=0; i<radioButton.length; i++) {
3424: if (radioButton[i].checked) {
3425: textbox.value = i;
3426: resetbox = true;
3427: }
3428: }
3429: if (!resetbox) {
3430: textbox.value = "";
3431: }
3432: return;
3433: }
3434: if (parseFloat(point) > parseFloat(weight)) {
3435: var resp = confirm("You entered a value ("+parseFloat(point)+
3436: ") greater than the weight for the part. Accept?");
3437: if (resp == false) {
3438: textbox.value = "";
3439: return;
3440: }
3441: }
3442: for (var i=0; i<radioButton.length; i++) {
3443: radioButton[i].checked=false;
3444: if (parseFloat(point) == i) {
3445: radioButton[i].checked=true;
3446: }
3447: }
3448:
3449: } else {
3450: textbox.value = parseFloat(point);
3451: }
3452: for (i=0;i<document.classgrade.total.value;i++) {
3453: var user = document.classgrade["ctr"+i].value;
3454: user = user.replace(new RegExp(':', 'g'),"_");
3455: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3456: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3457: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3458: if (saveval != "correct") {
3459: scorename.value = point;
3460: if (selname[0].selected != true) {
3461: selname[0].selected = true;
3462: }
3463: }
3464: }
3465: document.classgrade["SELVAL_"+partid][0].selected = true;
3466: }
3467:
3468: function writeRadText(partid,weight) {
3469: var selval = document.classgrade["SELVAL_"+partid];
3470: var radioButton = document.classgrade["RADVAL_"+partid];
3471: var override = document.classgrade["FORCE_"+partid].checked;
3472: var textbox = document.classgrade["TEXTVAL_"+partid];
3473: if (selval[1].selected || selval[2].selected) {
3474: for (var i=0; i<radioButton.length; i++) {
3475: radioButton[i].checked=false;
3476:
3477: }
3478: textbox.value = "";
3479:
3480: for (i=0;i<document.classgrade.total.value;i++) {
3481: var user = document.classgrade["ctr"+i].value;
3482: user = user.replace(new RegExp(':', 'g'),"_");
3483: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3484: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3485: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3486: if ((saveval != "correct") || override) {
3487: scorename.value = "";
3488: if (selval[1].selected) {
3489: selname[1].selected = true;
3490: } else {
3491: selname[2].selected = true;
3492: if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value))
3493: {document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
3494: }
3495: }
3496: }
3497: } else {
3498: for (i=0;i<document.classgrade.total.value;i++) {
3499: var user = document.classgrade["ctr"+i].value;
3500: user = user.replace(new RegExp(':', 'g'),"_");
3501: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3502: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3503: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3504: if ((saveval != "correct") || override) {
3505: scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
3506: selname[0].selected = true;
3507: }
3508: }
3509: }
3510: }
3511:
3512: function changeSelect(partid,user) {
3513: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
3514: var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
3515: var point = textbox.value;
3516: var weight = document.classgrade["weight_"+partid].value;
3517:
3518: if (isNaN(point) || parseFloat(point) < 0) {
3519: alert("$alertmsg"+parseFloat(point));
3520: textbox.value = "";
3521: return;
3522: }
3523: if (parseFloat(point) > parseFloat(weight)) {
3524: var resp = confirm("You entered a value ("+parseFloat(point)+
3525: ") greater than the weight of the part. Accept?");
3526: if (resp == false) {
3527: textbox.value = "";
3528: return;
3529: }
3530: }
3531: selval[0].selected = true;
3532: }
3533:
3534: function changeOneScore(partid,user) {
3535: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
3536: if (selval[1].selected || selval[2].selected) {
3537: document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
3538: if (selval[2].selected) {
3539: document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
3540: }
3541: }
3542: }
3543:
3544: function resetEntry(numpart) {
3545: for (ctpart=0;ctpart<numpart;ctpart++) {
3546: var partid = document.classgrade["partid_"+ctpart].value;
3547: var radioButton = document.classgrade["RADVAL_"+partid];
3548: var textbox = document.classgrade["TEXTVAL_"+partid];
3549: var selval = document.classgrade["SELVAL_"+partid];
3550: for (var i=0; i<radioButton.length; i++) {
3551: radioButton[i].checked=false;
3552:
3553: }
3554: textbox.value = "";
3555: selval[0].selected = true;
3556:
3557: for (i=0;i<document.classgrade.total.value;i++) {
3558: var user = document.classgrade["ctr"+i].value;
3559: user = user.replace(new RegExp(':', 'g'),"_");
3560: var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3561: resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
3562: var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
3563: resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
3564: var saveselval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3565: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3566: if (saveselval == "excused") {
3567: if (selname[1].selected == false) { selname[1].selected = true;}
3568: } else {
3569: if (selname[0].selected == false) {selname[0].selected = true};
3570: }
3571: }
3572: }
3573: }
3574:
3575: VIEWJAVASCRIPT
3576: }
3577:
3578: #--- show scores for a section or whole class w/ option to change/update a score
3579: sub viewgrades {
3580: my ($request,$symb) = @_;
3581: &viewgrades_js($request);
3582:
3583: #need to make sure we have the correct data for later EXT calls,
3584: #thus invalidate the cache
3585: &Apache::lonnet::devalidatecourseresdata(
3586: $env{'course.'.$env{'request.course.id'}.'.num'},
3587: $env{'course.'.$env{'request.course.id'}.'.domain'});
3588: &Apache::lonnet::clear_EXT_cache_status();
3589:
3590: my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
3591:
3592: #view individual student submission form - called using Javascript viewOneStudent
3593: $result.=&jscriptNform($symb);
3594:
3595: #beginning of class grading form
3596: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
3597: $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
3598: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
3599: '<input type="hidden" name="command" value="editgrades" />'."\n".
3600: &build_section_inputs().
3601: '<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
3602:
3603: my ($common_header,$specific_header);
3604: if ($env{'form.section'} eq 'all') {
3605: $common_header = &mt('Assign Common Grade to Class');
3606: $specific_header = &mt('Assign Grade to Specific Students in Class');
3607: } elsif ($env{'form.section'} eq 'none') {
3608: $common_header = &mt('Assign Common Grade to Students in no Section');
3609: $specific_header = &mt('Assign Grade to Specific Students in no Section');
3610: } else {
3611: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3612: $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
3613: $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
3614: }
3615: $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
3616: #radio buttons/text box for assigning points for a section or class.
3617: #handles different parts of a problem
3618: my $res_error;
3619: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
3620: if ($res_error) {
3621: return &navmap_errormsg();
3622: }
3623: my %weight = ();
3624: my $ctsparts = 0;
3625: my %seen = ();
3626: my @part_response_id = &flatten_responseType($responseType);
3627: foreach my $part_response_id (@part_response_id) {
3628: my ($partid,$respid) = @{ $part_response_id };
3629: my $part_resp = join('_',@{ $part_response_id });
3630: next if $seen{$partid};
3631: $seen{$partid}++;
3632: my $handgrade=$$handgrade{$part_resp};
3633: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
3634: $weight{$partid} = $wgt eq '' ? '1' : $wgt;
3635:
3636: my $display_part=&get_display_part($partid,$symb);
3637: my $radio.='<table border="0"><tr>';
3638: my $ctr = 0;
3639: while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
3640: $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
3641: 'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
3642: ','.$ctr.')" />'.$ctr."</label></td>\n";
3643: $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
3644: $ctr++;
3645: }
3646: $radio.='</tr></table>';
3647: my $line = '<input type="text" name="TEXTVAL_'.
3648: $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
3649: $partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
3650: $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
3651: $line.= '<td><b>'.&mt('Grade Status').':</b>'.
3652: '<select name="SELVAL_'.$partid.'" '.
3653: 'onchange="javascript:writeRadText(\''.$partid.'\','.
3654: $weight{$partid}.')"> '.
3655: '<option selected="selected"> </option>'.
3656: '<option value="excused">'.&mt('excused').'</option>'.
3657: '<option value="reset status">'.&mt('reset status').'</option>'.
3658: '</select></td>'.
3659: '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
3660: $line.='<input type="hidden" name="partid_'.
3661: $ctsparts.'" value="'.$partid.'" />'."\n";
3662: $line.='<input type="hidden" name="weight_'.
3663: $partid.'" value="'.$weight{$partid}.'" />'."\n";
3664:
3665: $result.=
3666: &Apache::loncommon::start_data_table_row()."\n".
3667: '<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>'.
3668: &Apache::loncommon::end_data_table_row()."\n";
3669: $ctsparts++;
3670: }
3671: $result.=&Apache::loncommon::end_data_table()."\n".
3672: '<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
3673: $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
3674: 'onclick="javascript:resetEntry('.$ctsparts.');" />';
3675:
3676: #table listing all the students in a section/class
3677: #header of table
3678: $result.= '<h3>'.$specific_header.'</h3>'.
3679: &Apache::loncommon::start_data_table().
3680: &Apache::loncommon::start_data_table_header_row().
3681: '<th>'.&mt('No.').'</th>'.
3682: '<th>'.&nameUserString('header')."</th>\n";
3683: my $partserror;
3684: my (@parts) = sort(&getpartlist($symb,\$partserror));
3685: if ($partserror) {
3686: return &navmap_errormsg();
3687: }
3688: my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
3689: my @partids = ();
3690: foreach my $part (@parts) {
3691: my $display=&Apache::lonnet::metadata($url,$part.'.display');
3692: my $narrowtext = &mt('Tries');
3693: $display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
3694: if (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
3695: my ($partid) = &split_part_type($part);
3696: push(@partids,$partid);
3697: #
3698: # FIXME: Looks like $display looks at English text
3699: #
3700: my $display_part=&get_display_part($partid,$symb);
3701: if ($display =~ /^Partial Credit Factor/) {
3702: $result.='<th>'.
3703: &mt('Score Part: [_1][_2](weight = [_3])',
3704: $display_part,'<br />',$weight{$partid}).'</th>'."\n";
3705: next;
3706:
3707: } else {
3708: if ($display =~ /Problem Status/) {
3709: my $grade_status_mt = &mt('Grade Status');
3710: $display =~ s{Problem Status}{$grade_status_mt<br />};
3711: }
3712: my $part_mt = &mt('Part:');
3713: $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
3714: }
3715:
3716: $result.='<th>'.$display.'</th>'."\n";
3717: }
3718: $result.=&Apache::loncommon::end_data_table_header_row();
3719:
3720: my %last_resets =
3721: &get_last_resets($symb,$env{'request.course.id'},\@partids);
3722:
3723: #get info for each student
3724: #list all the students - with points and grade status
3725: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
3726: my $ctr = 0;
3727: foreach (sort
3728: {
3729: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
3730: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
3731: }
3732: return $a cmp $b;
3733: } (keys(%$fullname))) {
3734: $ctr++;
3735: $result.=&viewstudentgrade($symb,$env{'request.course.id'},
3736: $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
3737: }
3738: $result.=&Apache::loncommon::end_data_table();
3739: $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
3740: $result.='<input type="button" value="'.&mt('Save').'" '.
3741: 'onclick="javascript:submit();" target="_self" /></form>'."\n";
3742: if (scalar(%$fullname) eq 0) {
3743: my $colspan=3+scalar(@parts);
3744: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3745: my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
3746: $result='<span class="LC_warning">'.
3747: &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
3748: $section_display, $stu_status).
3749: '</span>';
3750: }
3751: return $result;
3752: }
3753:
3754: #--- call by previous routine to display each student
3755: sub viewstudentgrade {
3756: my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
3757: my ($uname,$udom) = split(/:/,$student);
3758: my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
3759: my %aggregates = ();
3760: my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
3761: '<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
3762: "\n".$ctr.' </td><td> '.
3763: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
3764: '\');" target="_self">'.$fullname.'</a> '.
3765: '<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
3766: $student=~s/:/_/; # colon doen't work in javascript for names
3767: foreach my $apart (@$parts) {
3768: my ($part,$type) = &split_part_type($apart);
3769: my $score=$record{"resource.$part.$type"};
3770: $result.='<td align="center">';
3771: my ($aggtries,$totaltries);
3772: unless (exists($aggregates{$part})) {
3773: $totaltries = $record{'resource.'.$part.'.tries'};
3774:
3775: $aggtries = $totaltries;
3776: if ($$last_resets{$part}) {
3777: $aggtries = &get_num_tries(\%record,$$last_resets{$part},
3778: $part);
3779: }
3780: $result.='<input type="hidden" name="'.
3781: 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
3782: $result.='<input type="hidden" name="'.
3783: 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
3784: $aggregates{$part} = 1;
3785: }
3786: if ($type eq 'awarded') {
3787: my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
3788: $result.='<input type="hidden" name="'.
3789: 'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
3790: $result.='<input type="text" name="'.
3791: 'GD_'.$student.'_'.$part.'_awarded" '.
3792: 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
3793: '\')" value="'.$pts.'" size="4" /></td>'."\n";
3794: } elsif ($type eq 'solved') {
3795: my ($status,$foo)=split(/_/,$score,2);
3796: $status = 'nothing' if ($status eq '');
3797: $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
3798: $part.'_solved_s" value="'.$status.'" />'."\n";
3799: $result.=' <select name="'.
3800: 'GD_'.$student.'_'.$part.'_solved" '.
3801: 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
3802: $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>'
3803: : '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
3804: $result.='<option value="reset status">'.&mt('reset status').'</option>';
3805: $result.="</select> </td>\n";
3806: } else {
3807: $result.='<input type="hidden" name="'.
3808: 'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
3809: "\n";
3810: $result.='<input type="text" name="'.
3811: 'GD_'.$student.'_'.$part.'_'.$type.'" '.
3812: 'value="'.$score.'" size="4" /></td>'."\n";
3813: }
3814: }
3815: $result.=&Apache::loncommon::end_data_table_row();
3816: return $result;
3817: }
3818:
3819: #--- change scores for all the students in a section/class
3820: # record does not get update if unchanged
3821: sub editgrades {
3822: my ($request,$symb) = @_;
3823:
3824: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3825: my $title='<h2>'.&mt('Current Grade Status').'</h2>';
3826: $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
3827:
3828: my $result= &Apache::loncommon::start_data_table().
3829: &Apache::loncommon::start_data_table_header_row().
3830: '<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
3831: '<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
3832: my %scoreptr = (
3833: 'correct' =>'correct_by_override',
3834: 'incorrect'=>'incorrect_by_override',
3835: 'excused' =>'excused',
3836: 'ungraded' =>'ungraded_attempted',
3837: 'credited' =>'credit_attempted',
3838: 'nothing' => '',
3839: );
3840: my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
3841:
3842: my (@partid);
3843: my %weight = ();
3844: my %columns = ();
3845: my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
3846:
3847: my $partserror;
3848: my (@parts) = sort(&getpartlist($symb,\$partserror));
3849: if ($partserror) {
3850: return &navmap_errormsg();
3851: }
3852: my $header;
3853: while ($ctr < $env{'form.totalparts'}) {
3854: my $partid = $env{'form.partid_'.$ctr};
3855: push(@partid,$partid);
3856: $weight{$partid} = $env{'form.weight_'.$partid};
3857: $ctr++;
3858: }
3859: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3860: foreach my $partid (@partid) {
3861: $header .= '<th align="center">'.&mt('Old Score').'</th>'.
3862: '<th align="center">'.&mt('New Score').'</th>';
3863: $columns{$partid}=2;
3864: foreach my $stores (@parts) {
3865: my ($part,$type) = &split_part_type($stores);
3866: if ($part !~ m/^\Q$partid\E/) { next;}
3867: if ($type eq 'awarded' || $type eq 'solved') { next; }
3868: my $display=&Apache::lonnet::metadata($url,$stores.'.display');
3869: $display =~ s/\[Part: \Q$part\E\]//;
3870: my $narrowtext = &mt('Tries');
3871: $display =~ s/Number of Attempts/$narrowtext/;
3872: $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
3873: '<th align="center">'.&mt('New').' '.$display.'</th>';
3874: $columns{$partid}+=2;
3875: }
3876: }
3877: foreach my $partid (@partid) {
3878: my $display_part=&get_display_part($partid,$symb);
3879: $result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
3880: &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
3881: '</th>';
3882:
3883: }
3884: $result .= &Apache::loncommon::end_data_table_header_row().
3885: &Apache::loncommon::start_data_table_header_row().
3886: $header.
3887: &Apache::loncommon::end_data_table_header_row();
3888: my @noupdate;
3889: my ($updateCtr,$noupdateCtr) = (1,1);
3890: for ($i=0; $i<$env{'form.total'}; $i++) {
3891: my $line;
3892: my $user = $env{'form.ctr'.$i};
3893: my ($uname,$udom)=split(/:/,$user);
3894: my %newrecord;
3895: my $updateflag = 0;
3896: $line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
3897: my $usec=$classlist->{"$uname:$udom"}[5];
3898: if (!&canmodify($usec)) {
3899: my $numcols=scalar(@partid)*4+2;
3900: push(@noupdate,
3901: $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
3902: &mt('Not allowed to modify student')."</span></td></tr>");
3903: next;
3904: }
3905: my %aggregate = ();
3906: my $aggregateflag = 0;
3907: $user=~s/:/_/; # colon doen't work in javascript for names
3908: foreach (@partid) {
3909: my $old_aw = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
3910: my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
3911: my $old_part = $old_aw eq '' ? '' : $old_part_pcr;
3912: my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
3913: my $awarded = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
3914: my $pcr = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
3915: my $partial = $awarded eq '' ? '' : $pcr;
3916: my $score;
3917: if ($partial eq '') {
3918: $score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
3919: } elsif ($partial > 0) {
3920: $score = 'correct_by_override';
3921: } elsif ($partial == 0) {
3922: $score = 'incorrect_by_override';
3923: }
3924: my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
3925: $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
3926:
3927: $newrecord{'resource.'.$_.'.regrader'}=
3928: "$env{'user.name'}:$env{'user.domain'}";
3929: if ($dropMenu eq 'reset status' &&
3930: $old_score ne '') { # ignore if no previous attempts => nothing to reset
3931: $newrecord{'resource.'.$_.'.tries'} = '';
3932: $newrecord{'resource.'.$_.'.solved'} = '';
3933: $newrecord{'resource.'.$_.'.award'} = '';
3934: $newrecord{'resource.'.$_.'.awarded'} = '';
3935: $updateflag = 1;
3936: if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
3937: my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
3938: my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
3939: my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
3940: &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
3941: $aggregateflag = 1;
3942: }
3943: } elsif (!($old_part eq $partial && $old_score eq $score)) {
3944: $updateflag = 1;
3945: $newrecord{'resource.'.$_.'.awarded'} = $partial if $partial ne '';
3946: $newrecord{'resource.'.$_.'.solved'} = $score;
3947: $rec_update++;
3948: }
3949:
3950: $line .= '<td align="center">'.$old_aw.' </td>'.
3951: '<td align="center">'.$awarded.
3952: ($score eq 'excused' ? $score : '').' </td>';
3953:
3954:
3955: my $partid=$_;
3956: foreach my $stores (@parts) {
3957: my ($part,$type) = &split_part_type($stores);
3958: if ($part !~ m/^\Q$partid\E/) { next;}
3959: if ($type eq 'awarded' || $type eq 'solved') { next; }
3960: my $old_aw = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
3961: my $awarded = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
3962: if ($awarded ne '' && $awarded ne $old_aw) {
3963: $newrecord{'resource.'.$part.'.'.$type}= $awarded;
3964: $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
3965: $updateflag=1;
3966: }
3967: $line .= '<td align="center">'.$old_aw.' </td>'.
3968: '<td align="center">'.$awarded.' </td>';
3969: }
3970: }
3971: $line.="\n";
3972:
3973: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3974: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3975:
3976: if ($updateflag) {
3977: $count++;
3978: &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
3979: $udom,$uname);
3980:
3981: if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
3982: $cnum,$udom,$uname)) {
3983: # need to figure out if should be in queue.
3984: my %record =
3985: &Apache::lonnet::restore($symb,$env{'request.course.id'},
3986: $udom,$uname);
3987: my $all_graded = 1;
3988: my $none_graded = 1;
3989: foreach my $part (@parts) {
3990: if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
3991: $all_graded = 0;
3992: } else {
3993: $none_graded = 0;
3994: }
3995: }
3996:
3997: if ($all_graded || $none_graded) {
3998: &Apache::bridgetask::remove_from_queue('gradingqueue',
3999: $symb,$cdom,$cnum,
4000: $udom,$uname);
4001: }
4002: }
4003:
4004: $result.=&Apache::loncommon::start_data_table_row().
4005: '<td align="right"> '.$updateCtr.' </td>'.$line.
4006: &Apache::loncommon::end_data_table_row();
4007: $updateCtr++;
4008: } else {
4009: push(@noupdate,
4010: '<td align="right"> '.$noupdateCtr.' </td>'.$line);
4011: $noupdateCtr++;
4012: }
4013: if ($aggregateflag) {
4014: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
4015: $cdom,$cnum);
4016: }
4017: }
4018: if (@noupdate) {
4019: # my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
4020: my $numcols=scalar(@partid)*4+2;
4021: $result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
4022: '<td align="center" colspan="'.$numcols.'">'.
4023: &mt('No Changes Occurred For the Students Below').
4024: '</td>'.
4025: &Apache::loncommon::end_data_table_row();
4026: foreach my $line (@noupdate) {
4027: $result.=
4028: &Apache::loncommon::start_data_table_row().
4029: $line.
4030: &Apache::loncommon::end_data_table_row();
4031: }
4032: }
4033: $result .= &Apache::loncommon::end_data_table();
4034: my $msg = '<p><b>'.
4035: &mt('Number of records updated = [_1] for [quant,_2,student].',
4036: $rec_update,$count).'</b><br />'.
4037: '<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
4038: '</b></p>';
4039: return $title.$msg.$result;
4040: }
4041:
4042: sub split_part_type {
4043: my ($partstr) = @_;
4044: my ($temp,@allparts)=split(/_/,$partstr);
4045: my $type=pop(@allparts);
4046: my $part=join('_',@allparts);
4047: return ($part,$type);
4048: }
4049:
4050: #------------- end of section for handling grading by section/class ---------
4051: #
4052: #----------------------------------------------------------------------------
4053:
4054:
4055: #----------------------------------------------------------------------------
4056: #
4057: #-------------------------- Next few routines handles grading by csv upload
4058: #
4059: #--- Javascript to handle csv upload
4060: sub csvupload_javascript_reverse_associate {
4061: my $error1=&mt('You need to specify the username or the student/employee ID');
4062: my $error2=&mt('You need to specify at least one grading field');
4063: return(<<ENDPICK);
4064: function verify(vf) {
4065: var foundsomething=0;
4066: var founduname=0;
4067: var foundID=0;
4068: for (i=0;i<=vf.nfields.value;i++) {
4069: tw=eval('vf.f'+i+'.selectedIndex');
4070: if (i==0 && tw!=0) { foundID=1; }
4071: if (i==1 && tw!=0) { founduname=1; }
4072: if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
4073: }
4074: if (founduname==0 && foundID==0) {
4075: alert('$error1');
4076: return;
4077: }
4078: if (foundsomething==0) {
4079: alert('$error2');
4080: return;
4081: }
4082: vf.submit();
4083: }
4084: function flip(vf,tf) {
4085: var nw=eval('vf.f'+tf+'.selectedIndex');
4086: var i;
4087: for (i=0;i<=vf.nfields.value;i++) {
4088: //can not pick the same destination field for both name and domain
4089: if (((i ==0)||(i ==1)) &&
4090: ((tf==0)||(tf==1)) &&
4091: (i!=tf) &&
4092: (eval('vf.f'+i+'.selectedIndex')==nw)) {
4093: eval('vf.f'+i+'.selectedIndex=0;')
4094: }
4095: }
4096: }
4097: ENDPICK
4098: }
4099:
4100: sub csvupload_javascript_forward_associate {
4101: my $error1=&mt('You need to specify the username or the student/employee ID');
4102: my $error2=&mt('You need to specify at least one grading field');
4103: return(<<ENDPICK);
4104: function verify(vf) {
4105: var foundsomething=0;
4106: var founduname=0;
4107: var foundID=0;
4108: for (i=0;i<=vf.nfields.value;i++) {
4109: tw=eval('vf.f'+i+'.selectedIndex');
4110: if (tw==1) { foundID=1; }
4111: if (tw==2) { founduname=1; }
4112: if (tw>3) { foundsomething=1; }
4113: }
4114: if (founduname==0 && foundID==0) {
4115: alert('$error1');
4116: return;
4117: }
4118: if (foundsomething==0) {
4119: alert('$error2');
4120: return;
4121: }
4122: vf.submit();
4123: }
4124: function flip(vf,tf) {
4125: var nw=eval('vf.f'+tf+'.selectedIndex');
4126: var i;
4127: //can not pick the same destination field twice
4128: for (i=0;i<=vf.nfields.value;i++) {
4129: if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
4130: eval('vf.f'+i+'.selectedIndex=0;')
4131: }
4132: }
4133: }
4134: ENDPICK
4135: }
4136:
4137: sub csvuploadmap_header {
4138: my ($request,$symb,$datatoken,$distotal)= @_;
4139: my $javascript;
4140: if ($env{'form.upfile_associate'} eq 'reverse') {
4141: $javascript=&csvupload_javascript_reverse_associate();
4142: } else {
4143: $javascript=&csvupload_javascript_forward_associate();
4144: }
4145:
4146: $symb = &Apache::lonenc::check_encrypt($symb);
4147: $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
4148: &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
4149: &mt('Associate entries from the uploaded file with as many fields as you can.'));
4150: my $reverse=&mt("Reverse Association");
4151: $request->print(<<ENDPICK);
4152: <br />
4153: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
4154: <input type="hidden" name="associate" value="" />
4155: <input type="hidden" name="phase" value="three" />
4156: <input type="hidden" name="datatoken" value="$datatoken" />
4157: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
4158: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
4159: <input type="hidden" name="upfile_associate"
4160: value="$env{'form.upfile_associate'}" />
4161: <input type="hidden" name="symb" value="$symb" />
4162: <input type="hidden" name="command" value="csvuploadoptions" />
4163: <hr />
4164: ENDPICK
4165: $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
4166: return '';
4167:
4168: }
4169:
4170: sub csvupload_fields {
4171: my ($symb,$errorref) = @_;
4172: my (@parts) = &getpartlist($symb,$errorref);
4173: if (ref($errorref)) {
4174: if ($$errorref) {
4175: return;
4176: }
4177: }
4178:
4179: my @fields=(['ID','Student/Employee ID'],
4180: ['username','Student Username'],
4181: ['domain','Student Domain']);
4182: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
4183: foreach my $part (sort(@parts)) {
4184: my @datum;
4185: my $display=&Apache::lonnet::metadata($url,$part.'.display');
4186: my $name=$part;
4187: if (!$display) { $display = $name; }
4188: @datum=($name,$display);
4189: if ($name=~/^stores_(.*)_awarded/) {
4190: push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
4191: }
4192: push(@fields,\@datum);
4193: }
4194: return (@fields);
4195: }
4196:
4197: sub csvuploadmap_footer {
4198: my ($request,$i,$keyfields) =@_;
4199: my $buttontext = &mt('Assign Grades');
4200: $request->print(<<ENDPICK);
4201: </table>
4202: <input type="hidden" name="nfields" value="$i" />
4203: <input type="hidden" name="keyfields" value="$keyfields" />
4204: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
4205: </form>
4206: ENDPICK
4207: }
4208:
4209: sub checkforfile_js {
4210: my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
4211: my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
4212: function checkUpload(formname) {
4213: if (formname.upfile.value == "") {
4214: alert("$alertmsg");
4215: return false;
4216: }
4217: formname.submit();
4218: }
4219: CSVFORMJS
4220: return $result;
4221: }
4222:
4223: sub upcsvScores_form {
4224: my ($request,$symb) = @_;
4225: if (!$symb) {return '';}
4226: my $result=&checkforfile_js();
4227: $result.=&Apache::loncommon::start_data_table().
4228: &Apache::loncommon::start_data_table_header_row().
4229: '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
4230: &Apache::loncommon::end_data_table_header_row().
4231: &Apache::loncommon::start_data_table_row().'<td>';
4232: my $upload=&mt("Upload Scores");
4233: my $upfile_select=&Apache::loncommon::upfile_select_html();
4234: my $ignore=&mt('Ignore First Line');
4235: $symb = &Apache::lonenc::check_encrypt($symb);
4236: $result.=<<ENDUPFORM;
4237: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
4238: <input type="hidden" name="symb" value="$symb" />
4239: <input type="hidden" name="command" value="csvuploadmap" />
4240: $upfile_select
4241: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
4242: </form>
4243: ENDUPFORM
4244: $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
4245: &mt("How do I create a CSV file from a spreadsheet")).
4246: '</td>'.
4247: &Apache::loncommon::end_data_table_row().
4248: &Apache::loncommon::end_data_table();
4249: return $result;
4250: }
4251:
4252:
4253: sub csvuploadmap {
4254: my ($request,$symb)= @_;
4255: if (!$symb) {return '';}
4256:
4257: my $datatoken;
4258: if (!$env{'form.datatoken'}) {
4259: $datatoken=&Apache::loncommon::upfile_store($request);
4260: } else {
4261: $datatoken=$env{'form.datatoken'};
4262: &Apache::loncommon::load_tmp_file($request);
4263: }
4264: my @records=&Apache::loncommon::upfile_record_sep();
4265: &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
4266: my ($i,$keyfields);
4267: if (@records) {
4268: my $fieldserror;
4269: my @fields=&csvupload_fields($symb,\$fieldserror);
4270: if ($fieldserror) {
4271: $request->print(&navmap_errormsg());
4272: return;
4273: }
4274: if ($env{'form.upfile_associate'} eq 'reverse') {
4275: &Apache::loncommon::csv_print_samples($request,\@records);
4276: $i=&Apache::loncommon::csv_print_select_table($request,\@records,
4277: \@fields);
4278: foreach (@fields) { $keyfields.=$_->[0].','; }
4279: chop($keyfields);
4280: } else {
4281: unshift(@fields,['none','']);
4282: $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
4283: \@fields);
4284: foreach my $rec (@records) {
4285: my %temp = &Apache::loncommon::record_sep($rec);
4286: if (%temp) {
4287: $keyfields=join(',',sort(keys(%temp)));
4288: last;
4289: }
4290: }
4291: }
4292: }
4293: &csvuploadmap_footer($request,$i,$keyfields);
4294:
4295: return '';
4296: }
4297:
4298: sub csvuploadoptions {
4299: my ($request,$symb)= @_;
4300: my $overwrite=&mt('Overwrite any existing score');
4301: $request->print(<<ENDPICK);
4302: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
4303: <input type="hidden" name="command" value="csvuploadassign" />
4304: <p>
4305: <label>
4306: <input type="checkbox" name="overwite_scores" checked="checked" />
4307: $overwrite
4308: </label>
4309: </p>
4310: ENDPICK
4311: my %fields=&get_fields();
4312: if (!defined($fields{'domain'})) {
4313: my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
4314: $request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
4315: }
4316: foreach my $key (sort(keys(%env))) {
4317: if ($key !~ /^form\.(.*)$/) { next; }
4318: my $cleankey=$1;
4319: if ($cleankey eq 'command') { next; }
4320: $request->print('<input type="hidden" name="'.$cleankey.
4321: '" value="'.$env{$key}.'" />'."\n");
4322: }
4323: # FIXME do a check for any duplicated user ids...
4324: # FIXME do a check for any invalid user ids?...
4325: $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
4326: <hr /></form>'."\n");
4327: return '';
4328: }
4329:
4330: sub get_fields {
4331: my %fields;
4332: my @keyfields = split(/\,/,$env{'form.keyfields'});
4333: for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
4334: if ($env{'form.upfile_associate'} eq 'reverse') {
4335: if ($env{'form.f'.$i} ne 'none') {
4336: $fields{$keyfields[$i]}=$env{'form.f'.$i};
4337: }
4338: } else {
4339: if ($env{'form.f'.$i} ne 'none') {
4340: $fields{$env{'form.f'.$i}}=$keyfields[$i];
4341: }
4342: }
4343: }
4344: return %fields;
4345: }
4346:
4347: sub csvuploadassign {
4348: my ($request,$symb)= @_;
4349: if (!$symb) {return '';}
4350: my $error_msg = '';
4351: &Apache::loncommon::load_tmp_file($request);
4352: my @gradedata = &Apache::loncommon::upfile_record_sep();
4353: my %fields=&get_fields();
4354: my $courseid=$env{'request.course.id'};
4355: my ($classlist) = &getclasslist('all',0);
4356: my @notallowed;
4357: my @skipped;
4358: my @warnings;
4359: my $countdone=0;
4360: foreach my $grade (@gradedata) {
4361: my %entries=&Apache::loncommon::record_sep($grade);
4362: my $domain;
4363: if ($entries{$fields{'domain'}}) {
4364: $domain=$entries{$fields{'domain'}};
4365: } else {
4366: $domain=$env{'form.default_domain'};
4367: }
4368: $domain=~s/\s//g;
4369: my $username=$entries{$fields{'username'}};
4370: $username=~s/\s//g;
4371: if (!$username) {
4372: my $id=$entries{$fields{'ID'}};
4373: $id=~s/\s//g;
4374: my %ids=&Apache::lonnet::idget($domain,$id);
4375: $username=$ids{$id};
4376: }
4377: if (!exists($$classlist{"$username:$domain"})) {
4378: my $id=$entries{$fields{'ID'}};
4379: $id=~s/\s//g;
4380: if ($id) {
4381: push(@skipped,"$id:$domain");
4382: } else {
4383: push(@skipped,"$username:$domain");
4384: }
4385: next;
4386: }
4387: my $usec=$classlist->{"$username:$domain"}[5];
4388: if (!&canmodify($usec)) {
4389: push(@notallowed,"$username:$domain");
4390: next;
4391: }
4392: my %points;
4393: my %grades;
4394: foreach my $dest (keys(%fields)) {
4395: if ($dest eq 'ID' || $dest eq 'username' ||
4396: $dest eq 'domain') { next; }
4397: if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
4398: if ($dest=~/stores_(.*)_points/) {
4399: my $part=$1;
4400: my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
4401: $symb,$domain,$username);
4402: if ($wgt) {
4403: $entries{$fields{$dest}}=~s/\s//g;
4404: my $pcr=$entries{$fields{$dest}} / $wgt;
4405: my $award=($pcr == 0) ? 'incorrect_by_override'
4406: : 'correct_by_override';
4407: if ($pcr>1) {
4408: push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
4409: }
4410: $grades{"resource.$part.awarded"}=$pcr;
4411: $grades{"resource.$part.solved"}=$award;
4412: $points{$part}=1;
4413: } else {
4414: $error_msg = "<br />" .
4415: &mt("Some point values were assigned"
4416: ." for problems with a weight "
4417: ."of zero. These values were "
4418: ."ignored.");
4419: }
4420: } else {
4421: if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
4422: if ($dest=~/stores_(.*)_solved/) { if ($points{$1}) {next;} }
4423: my $store_key=$dest;
4424: $store_key=~s/^stores/resource/;
4425: $store_key=~s/_/\./g;
4426: $grades{$store_key}=$entries{$fields{$dest}};
4427: }
4428: }
4429: if (! %grades) {
4430: push(@skipped,&mt("[_1]: no data to save","$username:$domain"));
4431: } else {
4432: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
4433: my $result=&Apache::lonnet::cstore(\%grades,$symb,
4434: $env{'request.course.id'},
4435: $domain,$username);
4436: if ($result eq 'ok') {
4437: # Successfully stored
4438: $request->print('.');
4439: # Remove from grading queue
4440: &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
4441: $env{'course.'.$env{'request.course.id'}.'.domain'},
4442: $env{'course.'.$env{'request.course.id'}.'.num'},
4443: $domain,$username);
4444: $countdone++;
4445: } else {
4446: $request->print("<p><span class=\"LC_error\">".
4447: &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
4448: "$username:$domain",$result)."</span></p>");
4449: }
4450: $request->rflush();
4451: }
4452: }
4453: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
4454: if (@warnings) {
4455: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
4456: $request->print(join(', ',@warnings));
4457: }
4458: if (@skipped) {
4459: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
4460: $request->print(join(', ',@skipped));
4461: }
4462: if (@notallowed) {
4463: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
4464: $request->print(join(', ',@notallowed));
4465: }
4466: $request->print("<br />\n");
4467: return $error_msg;
4468: }
4469: #------------- end of section for handling csv file upload ---------
4470: #
4471: #-------------------------------------------------------------------
4472: #
4473: #-------------- Next few routines handle grading by page/sequence
4474: #
4475: #--- Select a page/sequence and a student to grade
4476: sub pickStudentPage {
4477: my ($request,$symb) = @_;
4478:
4479: my $alertmsg = &mt('Please select the student you wish to grade.');
4480: $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
4481:
4482: function checkPickOne(formname) {
4483: if (radioSelection(formname.student) == null) {
4484: alert("$alertmsg");
4485: return;
4486: }
4487: ptr = pullDownSelection(formname.selectpage);
4488: formname.page.value = formname["page"+ptr].value;
4489: formname.title.value = formname["title"+ptr].value;
4490: formname.submit();
4491: }
4492:
4493: LISTJAVASCRIPT
4494: &commonJSfunctions($request);
4495:
4496: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4497: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4498: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4499:
4500: my $result='<h3><span class="LC_info"> '.
4501: &mt('Manual Grading by Page or Sequence').'</span></h3>';
4502:
4503: $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
4504: my $map_error;
4505: my ($titles,$symbx) = &getSymbMap($map_error);
4506: if ($map_error) {
4507: $request->print(&navmap_errormsg());
4508: return;
4509: }
4510: my ($curpage) =&Apache::lonnet::decode_symb($symb);
4511: # my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb);
4512: # my $type=($curpage =~ /\.(page|sequence)/);
4513:
4514: # Collection of hidden fields
4515: my $ctr=0;
4516: foreach (@$titles) {
4517: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4518: $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
4519: $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
4520: $ctr++;
4521: }
4522: $result.='<input type="hidden" name="page" />'."\n".
4523: '<input type="hidden" name="title" />'."\n";
4524:
4525: $result.=&build_section_inputs();
4526: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
4527: $result.='<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
4528: '<input type="hidden" name="command" value="displayPage" />'."\n".
4529: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
4530:
4531: # Show grading options
4532: $result.=&Apache::lonhtmlcommon::start_pick_box();
4533: my $select = '<select name="selectpage">'."\n";
4534: $ctr=0;
4535: foreach (@$titles) {
4536: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4537: $select.='<option value="'.$ctr.'"'.
4538: ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
4539: '>'.$showtitle.'</option>'."\n";
4540: $ctr++;
4541: }
4542: $select.= '</select>';
4543:
4544: $result.=
4545: &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
4546: .$select
4547: .&Apache::lonhtmlcommon::row_closure();
4548:
4549: $result.=
4550: &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
4551: .'<label><input type="radio" name="vProb" value="no"'
4552: .' checked="checked" /> '.&mt('no').' </label>'."\n"
4553: .'<label><input type="radio" name="vProb" value="yes" />'
4554: .&mt('yes').'</label>'."\n"
4555: .&Apache::lonhtmlcommon::row_closure();
4556:
4557: $result.=
4558: &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
4559: .'<label><input type="radio" name="lastSub" value="none" /> '
4560: .&mt('none').' </label>'."\n"
4561: .'<label><input type="radio" name="lastSub" value="datesub"'
4562: .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
4563: .'<label><input type="radio" name="lastSub" value="all" /> '
4564: .&mt('all submissions with details').' </label>'
4565: .&Apache::lonhtmlcommon::row_closure();
4566:
4567: $result.=
4568: &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
4569: .'<input type="text" name="CODE" value="" />'
4570: .&Apache::lonhtmlcommon::row_closure(1)
4571: .&Apache::lonhtmlcommon::end_pick_box();
4572:
4573: # Show list of students to select for grading
4574: $result.='<br /><input type="button" '.
4575: 'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' →" /><br />'."\n";
4576:
4577: $request->print($result);
4578:
4579: my $studentTable.=' <b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
4580: &Apache::loncommon::start_data_table().
4581: &Apache::loncommon::start_data_table_header_row().
4582: '<th align="right"> '.&mt('No.').'</th>'.
4583: '<th>'.&nameUserString('header').'</th>'.
4584: '<th align="right"> '.&mt('No.').'</th>'.
4585: '<th>'.&nameUserString('header').'</th>'.
4586: &Apache::loncommon::end_data_table_header_row();
4587:
4588: my (undef,undef,$fullname) = &getclasslist($getsec,'1');
4589: my $ptr = 1;
4590: foreach my $student (sort
4591: {
4592: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
4593: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
4594: }
4595: return $a cmp $b;
4596: } (keys(%$fullname))) {
4597: my ($uname,$udom) = split(/:/,$student);
4598: $studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
4599: : '</td>');
4600: $studentTable.='<td align="right">'.$ptr.' </td>';
4601: $studentTable.='<td> <label><input type="radio" name="student" value="'.$student.'" /> '
4602: .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
4603: $studentTable.=
4604: ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row()
4605: : '');
4606: $ptr++;
4607: }
4608: if ($ptr%2 == 0) {
4609: $studentTable.='</td><td> </td><td> </td>'.
4610: &Apache::loncommon::end_data_table_row();
4611: }
4612: $studentTable.=&Apache::loncommon::end_data_table()."\n";
4613: $studentTable.='<input type="button" '.
4614: 'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' →" /></form>'."\n";
4615:
4616: $request->print($studentTable);
4617:
4618: return '';
4619: }
4620:
4621: sub getSymbMap {
4622: my ($map_error) = @_;
4623: my $navmap = Apache::lonnavmaps::navmap->new();
4624: unless (ref($navmap)) {
4625: if (ref($map_error)) {
4626: $$map_error = 'navmap';
4627: }
4628: return;
4629: }
4630: my %symbx = ();
4631: my @titles = ();
4632: my $minder = 0;
4633:
4634: # Gather every sequence that has problems.
4635: my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
4636: 1,0,1);
4637: for my $sequence ($navmap->getById('0.0'), @sequences) {
4638: if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
4639: my $title = $minder.'.'.
4640: &HTML::Entities::encode($sequence->compTitle(),'"\'&');
4641: push(@titles, $title); # minder in case two titles are identical
4642: $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
4643: $minder++;
4644: }
4645: }
4646: return \@titles,\%symbx;
4647: }
4648:
4649: #
4650: #--- Displays a page/sequence w/wo problems, w/wo submissions
4651: sub displayPage {
4652: my ($request,$symb) = @_;
4653: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4654: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4655: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4656: my $pageTitle = $env{'form.page'};
4657: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
4658: my ($uname,$udom) = split(/:/,$env{'form.student'});
4659: my $usec=$classlist->{$env{'form.student'}}[5];
4660:
4661: #need to make sure we have the correct data for later EXT calls,
4662: #thus invalidate the cache
4663: &Apache::lonnet::devalidatecourseresdata(
4664: $env{'course.'.$env{'request.course.id'}.'.num'},
4665: $env{'course.'.$env{'request.course.id'}.'.domain'});
4666: &Apache::lonnet::clear_EXT_cache_status();
4667:
4668: if (!&canview($usec)) {
4669: $request->print(
4670: '<span class="LC_warning">'.
4671: &mt('Unable to view requested student. ([_1])',
4672: $env{'form.student'}).
4673: '</span>');
4674: return;
4675: }
4676: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
4677: $result.='<h3> '.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
4678: '</h3>'."\n";
4679: $env{'form.CODE'} = uc($env{'form.CODE'});
4680: if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
4681: $result.='<h3> '.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
4682: } else {
4683: delete($env{'form.CODE'});
4684: }
4685: &sub_page_js($request);
4686: $request->print($result);
4687:
4688: my $navmap = Apache::lonnavmaps::navmap->new();
4689: unless (ref($navmap)) {
4690: $request->print(&navmap_errormsg());
4691: return;
4692: }
4693: my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
4694: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
4695: if (!$map) {
4696: $request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
4697: return;
4698: }
4699: my $iterator = $navmap->getIterator($map->map_start(),
4700: $map->map_finish());
4701:
4702: my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
4703: '<input type="hidden" name="command" value="gradeByPage" />'."\n".
4704: '<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
4705: '<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
4706: '<input type="hidden" name="page" value="'.$pageTitle.'" />'."\n".
4707: '<input type="hidden" name="title" value="'.$env{'form.title'}.'" />'."\n".
4708: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
4709: '<input type="hidden" name="overRideScore" value="no" />'."\n";
4710:
4711: if (defined($env{'form.CODE'})) {
4712: $studentTable.=
4713: '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
4714: }
4715: my $checkIcon = '<img alt="'.&mt('Check Mark').
4716: '" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
4717:
4718: $studentTable.=' <span class="LC_info">'.
4719: &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
4720: '</span>'."\n".
4721: &Apache::loncommon::start_data_table().
4722: &Apache::loncommon::start_data_table_header_row().
4723: '<th>'.&mt('Prob.').'</th>'.
4724: '<th> '.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
4725: &Apache::loncommon::end_data_table_header_row();
4726:
4727: &Apache::lonxml::clear_problem_counter();
4728: my ($depth,$question,$prob) = (1,1,1);
4729: $iterator->next(); # skip the first BEGIN_MAP
4730: my $curRes = $iterator->next(); # for "current resource"
4731: while ($depth > 0) {
4732: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
4733: if($curRes == $iterator->END_MAP) { $depth--; }
4734:
4735: if (ref($curRes) && $curRes->is_problem()) {
4736: my $parts = $curRes->parts();
4737: my $title = $curRes->compTitle();
4738: my $symbx = $curRes->symb();
4739: $studentTable.=
4740: &Apache::loncommon::start_data_table_row().
4741: '<td align="center" valign="top" >'.$prob.
4742: (scalar(@{$parts}) == 1 ? ''
4743: : '<br />('.&mt('[_1]parts',
4744: scalar(@{$parts}).' ').')'
4745: ).
4746: '</td>';
4747: $studentTable.='<td valign="top">';
4748: my %form = ('CODE' => $env{'form.CODE'},);
4749: if ($env{'form.vProb'} eq 'yes' ) {
4750: $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
4751: undef,'both',\%form);
4752: } else {
4753: my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
4754: $companswer =~ s|<form(.*?)>||g;
4755: $companswer =~ s|</form>||g;
4756: # while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
4757: # $companswer =~ s/$1/ /ms;
4758: # $request->print('match='.$1."<br />\n");
4759: # }
4760: # $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
4761: $studentTable.=' <b>'.$title.'</b> <br /> <b>'.&mt('Correct answer').':</b><br />'.$companswer;
4762: }
4763:
4764: my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
4765:
4766: if ($env{'form.lastSub'} eq 'datesub') {
4767: if ($record{'version'} eq '') {
4768: $studentTable.='<br /> <span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
4769: } else {
4770: my %responseType = ();
4771: foreach my $partid (@{$parts}) {
4772: my @responseIds =$curRes->responseIds($partid);
4773: my @responseType =$curRes->responseType($partid);
4774: my %responseIds;
4775: for (my $i=0;$i<=$#responseIds;$i++) {
4776: $responseIds{$responseIds[$i]}=$responseType[$i];
4777: }
4778: $responseType{$partid} = \%responseIds;
4779: }
4780: $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
4781:
4782: }
4783: } elsif ($env{'form.lastSub'} eq 'all') {
4784: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
4785: $studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
4786: $env{'request.course.id'},
4787: '','.submission');
4788:
4789: }
4790: if (&canmodify($usec)) {
4791: $studentTable.=&gradeBox_start();
4792: foreach my $partid (@{$parts}) {
4793: $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
4794: $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
4795: $question++;
4796: }
4797: $studentTable.=&gradeBox_end();
4798: $prob++;
4799: }
4800: $studentTable.='</td></tr>';
4801:
4802: }
4803: $curRes = $iterator->next();
4804: }
4805:
4806: $studentTable.=
4807: '</table>'."\n".
4808: '<input type="button" value="'.&mt('Save').'" '.
4809: 'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
4810: '</form>'."\n";
4811: $request->print($studentTable);
4812:
4813: return '';
4814: }
4815:
4816: sub displaySubByDates {
4817: my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
4818: my $isCODE=0;
4819: my $isTask = ($symb =~/\.task$/);
4820: if (exists($record->{'resource.CODE'})) { $isCODE=1; }
4821: my $studentTable=&Apache::loncommon::start_data_table().
4822: &Apache::loncommon::start_data_table_header_row().
4823: '<th>'.&mt('Date/Time').'</th>'.
4824: ($isCODE?'<th>'.&mt('CODE').'</th>':'').
4825: ($isTask?'<th>'.&mt('Version').'</th>':'').
4826: '<th>'.&mt('Submission').'</th>'.
4827: '<th>'.&mt('Status').'</th>'.
4828: &Apache::loncommon::end_data_table_header_row();
4829: my ($version);
4830: my %mark;
4831: my %orders;
4832: $mark{'correct_by_student'} = $checkIcon;
4833: if (!exists($$record{'1:timestamp'})) {
4834: return '<br /> <span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
4835: }
4836:
4837: my $interaction;
4838: my $no_increment = 1;
4839: my %lastrndseed;
4840: for ($version=1;$version<=$$record{'version'};$version++) {
4841: my $timestamp =
4842: &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
4843: if (exists($$record{$version.':resource.0.version'})) {
4844: $interaction = $$record{$version.':resource.0.version'};
4845: }
4846: if ($isTask && $env{'form.previousversion'}) {
4847: next unless ($interaction == $env{'form.previousversion'});
4848: }
4849: my $where = ($isTask ? "$version:resource.$interaction"
4850: : "$version:resource");
4851: $studentTable.=&Apache::loncommon::start_data_table_row().
4852: '<td>'.$timestamp.'</td>';
4853: if ($isCODE) {
4854: $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
4855: }
4856: if ($isTask) {
4857: $studentTable.='<td>'.$interaction.'</td>';
4858: }
4859: my @versionKeys = split(/\:/,$$record{$version.':keys'});
4860: my @displaySub = ();
4861: foreach my $partid (@{$parts}) {
4862: my ($hidden,$type);
4863: $type = $$record{$version.':resource.'.$partid.'.type'};
4864: if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
4865: $hidden = 1;
4866: }
4867: my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
4868: : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
4869:
4870: # next if ($$record{"$version:resource.$partid.solved"} eq '');
4871: my $display_part=&get_display_part($partid,$symb);
4872: foreach my $matchKey (@matchKey) {
4873: if (exists($$record{$version.':'.$matchKey}) &&
4874: $$record{$version.':'.$matchKey} ne '') {
4875:
4876: my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
4877: : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
4878: $displaySub[0].='<span class="LC_nobreak">';
4879: $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
4880: .' <span class="LC_internal_info">'
4881: .'('.&mt('Response ID: [_1]',$responseId).')'
4882: .'</span>'
4883: .' <b>';
4884: if ($hidden) {
4885: $displaySub[0].= &mt('Anonymous Survey').'</b>';
4886: } else {
4887: my ($trial,$rndseed,$newvariation);
4888: if ($type eq 'randomizetry') {
4889: $trial = $$record{"$where.$partid.tries"};
4890: $rndseed = $$record{"$where.$partid.rndseed"};
4891: }
4892: if ($$record{"$where.$partid.tries"} eq '') {
4893: $displaySub[0].=&mt('Trial not counted');
4894: } else {
4895: $displaySub[0].=&mt('Trial: [_1]',
4896: $$record{"$where.$partid.tries"});
4897: if ($rndseed || $lastrndseed{$partid}) {
4898: if ($rndseed ne $lastrndseed{$partid}) {
4899: $newvariation = ' ('.&mt('New variation this try').')';
4900: }
4901: }
4902: $lastrndseed{$partid} = $rndseed;
4903: }
4904: my $responseType=($isTask ? 'Task'
4905: : $responseType->{$partid}->{$responseId});
4906: if (!exists($orders{$partid})) { $orders{$partid}={}; }
4907: if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
4908: $orders{$partid}->{$responseId}=
4909: &get_order($partid,$responseId,$symb,$uname,$udom,
4910: $no_increment,$type,$trial,$rndseed);
4911: }
4912: $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
4913: $displaySub[0].=' '.
4914: &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
4915: }
4916: }
4917: }
4918: if (exists($$record{"$where.$partid.checkedin"})) {
4919: $displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
4920: $$record{"$where.$partid.checkedin"},
4921: $$record{"$where.$partid.checkedin.slot"}).
4922: '<br />';
4923: }
4924: if (exists $$record{"$where.$partid.award"}) {
4925: $displaySub[1].='<b>'.&mt('Part:').'</b> '.$display_part.' '.
4926: lc($$record{"$where.$partid.award"}).' '.
4927: $mark{$$record{"$where.$partid.solved"}}.
4928: '<br />';
4929: }
4930: if (exists $$record{"$where.$partid.regrader"}) {
4931: $displaySub[2].=$$record{"$where.$partid.regrader"}.
4932: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
4933: } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
4934: $displaySub[2].=
4935: $$record{"$version:resource.$partid.regrader"}.
4936: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
4937: }
4938: }
4939: # needed because old essay regrader has not parts info
4940: if (exists $$record{"$version:resource.regrader"}) {
4941: $displaySub[2].=$$record{"$version:resource.regrader"};
4942: }
4943: $studentTable.='<td>'.$displaySub[0].' </td><td>'.$displaySub[1];
4944: if ($displaySub[2]) {
4945: $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
4946: }
4947: $studentTable.=' </td>'.
4948: &Apache::loncommon::end_data_table_row();
4949: }
4950: $studentTable.=&Apache::loncommon::end_data_table();
4951: return $studentTable;
4952: }
4953:
4954: sub updateGradeByPage {
4955: my ($request,$symb) = @_;
4956:
4957: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4958: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4959: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4960: my $pageTitle = $env{'form.page'};
4961: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
4962: my ($uname,$udom) = split(/:/,$env{'form.student'});
4963: my $usec=$classlist->{$env{'form.student'}}[5];
4964: if (!&canmodify($usec)) {
4965: $request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
4966: return;
4967: }
4968: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
4969: $result.='<h3> '.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
4970: '</h3>'."\n";
4971:
4972: $request->print($result);
4973:
4974:
4975: my $navmap = Apache::lonnavmaps::navmap->new();
4976: unless (ref($navmap)) {
4977: $request->print(&navmap_errormsg());
4978: return;
4979: }
4980: my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
4981: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
4982: if (!$map) {
4983: $request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
4984: return;
4985: }
4986: my $iterator = $navmap->getIterator($map->map_start(),
4987: $map->map_finish());
4988:
4989: my $studentTable=
4990: &Apache::loncommon::start_data_table().
4991: &Apache::loncommon::start_data_table_header_row().
4992: '<th align="center"> '.&mt('Prob.').' </th>'.
4993: '<th> '.&mt('Title').' </th>'.
4994: '<th> '.&mt('Previous Score').' </th>'.
4995: '<th> '.&mt('New Score').' </th>'.
4996: &Apache::loncommon::end_data_table_header_row();
4997:
4998: $iterator->next(); # skip the first BEGIN_MAP
4999: my $curRes = $iterator->next(); # for "current resource"
5000: my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
5001: while ($depth > 0) {
5002: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
5003: if($curRes == $iterator->END_MAP) { $depth--; }
5004:
5005: if (ref($curRes) && $curRes->is_problem()) {
5006: my $parts = $curRes->parts();
5007: my $title = $curRes->compTitle();
5008: my $symbx = $curRes->symb();
5009: $studentTable.=
5010: &Apache::loncommon::start_data_table_row().
5011: '<td align="center" valign="top" >'.$prob.
5012: (scalar(@{$parts}) == 1 ? ''
5013: : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
5014: .')').'</td>';
5015: $studentTable.='<td valign="top"> <b>'.$title.'</b> </td>';
5016:
5017: my %newrecord=();
5018: my @displayPts=();
5019: my %aggregate = ();
5020: my $aggregateflag = 0;
5021: foreach my $partid (@{$parts}) {
5022: my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
5023: my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
5024:
5025: my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ?
5026: $env{'form.WGT'.$question.'_'.$partid} : 1;
5027: my $partial = $newpts/$wgt;
5028: my $score;
5029: if ($partial > 0) {
5030: $score = 'correct_by_override';
5031: } elsif ($newpts ne '') { #empty is taken as 0
5032: $score = 'incorrect_by_override';
5033: }
5034: my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
5035: if ($dropMenu eq 'excused') {
5036: $partial = '';
5037: $score = 'excused';
5038: } elsif ($dropMenu eq 'reset status'
5039: && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
5040: $newrecord{'resource.'.$partid.'.tries'} = 0;
5041: $newrecord{'resource.'.$partid.'.solved'} = '';
5042: $newrecord{'resource.'.$partid.'.award'} = '';
5043: $newrecord{'resource.'.$partid.'.awarded'} = 0;
5044: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
5045: $changeflag++;
5046: $newpts = '';
5047:
5048: my $aggtries = $env{'form.aggtries'.$question.'_'.$partid};
5049: my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
5050: my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
5051: if ($aggtries > 0) {
5052: &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
5053: $aggregateflag = 1;
5054: }
5055: }
5056: my $display_part=&get_display_part($partid,$curRes->symb());
5057: my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
5058: $displayPts[0].=' <b>'.&mt('Part').':</b> '.$display_part.' = '.
5059: (($oldstatus eq 'excused') ? 'excused' : $oldpts).
5060: ' <br />';
5061: $displayPts[1].=' <b>'.&mt('Part').':</b> '.$display_part.' = '.
5062: (($score eq 'excused') ? 'excused' : $newpts).
5063: ' <br />';
5064: $question++;
5065: next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
5066:
5067: $newrecord{'resource.'.$partid.'.awarded'} = $partial if $partial ne '';
5068: $newrecord{'resource.'.$partid.'.solved'} = $score if $score ne '';
5069: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
5070: if (scalar(keys(%newrecord)) > 0);
5071:
5072: $changeflag++;
5073: }
5074: if (scalar(keys(%newrecord)) > 0) {
5075: my %record =
5076: &Apache::lonnet::restore($symbx,$env{'request.course.id'},
5077: $udom,$uname);
5078:
5079: if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
5080: $newrecord{'resource.CODE'} = $env{'form.CODE'};
5081: } elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
5082: $newrecord{'resource.CODE'} = '';
5083: }
5084: &Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
5085: $udom,$uname);
5086: %record = &Apache::lonnet::restore($symbx,
5087: $env{'request.course.id'},
5088: $udom,$uname);
5089: &check_and_remove_from_queue($parts,\%record,undef,$symbx,
5090: $cdom,$cnum,$udom,$uname);
5091: }
5092:
5093: if ($aggregateflag) {
5094: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
5095: $env{'course.'.$env{'request.course.id'}.'.domain'},
5096: $env{'course.'.$env{'request.course.id'}.'.num'});
5097: }
5098:
5099: $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
5100: '<td valign="top">'.$displayPts[1].'</td>'.
5101: &Apache::loncommon::end_data_table_row();
5102:
5103: $prob++;
5104: }
5105: $curRes = $iterator->next();
5106: }
5107:
5108: $studentTable.=&Apache::loncommon::end_data_table();
5109: my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
5110: &mt('The scores were changed for [quant,_1,problem].',
5111: $changeflag));
5112: $request->print($grademsg.$studentTable);
5113:
5114: return '';
5115: }
5116:
5117: #-------- end of section for handling grading by page/sequence ---------
5118: #
5119: #-------------------------------------------------------------------
5120:
5121: #-------------------- Bubblesheet (Scantron) Grading -------------------
5122: #
5123: #------ start of section for handling grading by page/sequence ---------
5124:
5125: =pod
5126:
5127: =head1 Bubble sheet grading routines
5128:
5129: For this documentation:
5130:
5131: 'scanline' refers to the full line of characters
5132: from the file that we are parsing that represents one entire sheet
5133:
5134: 'bubble line' refers to the data
5135: representing the line of bubbles that are on the physical bubblesheet
5136:
5137:
5138: The overall process is that a scanned in bubblesheet data is uploaded
5139: into a course. When a user wants to grade, they select a
5140: sequence/folder of resources, a file of bubblesheet info, and pick
5141: one of the predefined configurations for what each scanline looks
5142: like.
5143:
5144: Next each scanline is checked for any errors of either 'missing
5145: bubbles' (it's an error because it may have been mis-scanned
5146: because too light bubbling), 'double bubble' (each bubble line should
5147: have no more than one letter picked), invalid or duplicated CODE,
5148: invalid student/employee ID
5149:
5150: If the CODE option is used that determines the randomization of the
5151: homework problems, either way the student/employee ID is looked up into a
5152: username:domain.
5153:
5154: During the validation phase the instructor can choose to skip scanlines.
5155:
5156: After the validation phase, there are now 3 bubblesheet files
5157:
5158: scantron_original_filename (unmodified original file)
5159: scantron_corrected_filename (file where the corrected information has replaced the original information)
5160: scantron_skipped_filename (contains the exact text of scanlines that where skipped)
5161:
5162: Also there is a separate hash nohist_scantrondata that contains extra
5163: correction information that isn't representable in the bubblesheet
5164: file (see &scantron_getfile() for more information)
5165:
5166: After all scanlines are either valid, marked as valid or skipped, then
5167: foreach line foreach problem in the picked sequence, an ssi request is
5168: made that simulates a user submitting their selected letter(s) against
5169: the homework problem.
5170:
5171: =over 4
5172:
5173:
5174:
5175: =item defaultFormData
5176:
5177: Returns html hidden inputs used to hold context/default values.
5178:
5179: Arguments:
5180: $symb - $symb of the current resource
5181:
5182: =cut
5183:
5184: sub defaultFormData {
5185: my ($symb)=@_;
5186: return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
5187: }
5188:
5189:
5190: =pod
5191:
5192: =item getSequenceDropDown
5193:
5194: Return html dropdown of possible sequences to grade
5195:
5196: Arguments:
5197: $symb - $symb of the current resource
5198: $map_error - ref to scalar which will container error if
5199: $navmap object is unavailable in &getSymbMap().
5200:
5201: =cut
5202:
5203: sub getSequenceDropDown {
5204: my ($symb,$map_error)=@_;
5205: my $result='<select name="selectpage">'."\n";
5206: my ($titles,$symbx) = &getSymbMap($map_error);
5207: if (ref($map_error)) {
5208: return if ($$map_error);
5209: }
5210: my ($curpage)=&Apache::lonnet::decode_symb($symb);
5211: my $ctr=0;
5212: foreach (@$titles) {
5213: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
5214: $result.='<option value="'.$$symbx{$_}.'" '.
5215: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
5216: '>'.$showtitle.'</option>'."\n";
5217: $ctr++;
5218: }
5219: $result.= '</select>';
5220: return $result;
5221: }
5222:
5223: my %bubble_lines_per_response; # no. bubble lines for each response.
5224: # key is zero-based index - 0, 1, 2 ...
5225:
5226: my %first_bubble_line; # First bubble line no. for each bubble.
5227:
5228: my %subdivided_bubble_lines; # no. bubble lines for optionresponse,
5229: # matchresponse or rankresponse, where
5230: # an individual response can have multiple
5231: # lines
5232:
5233: my %responsetype_per_response; # responsetype for each response
5234:
5235: my %masterseq_id_responsenum; # src_id (e.g., 12.3_0.11 etc.) for each
5236: # numbered response. Needed when randomorder
5237: # or randompick are in use. Key is ID, value
5238: # is response number.
5239:
5240: # Save and restore the bubble lines array to the form env.
5241:
5242:
5243: sub save_bubble_lines {
5244: foreach my $line (keys(%bubble_lines_per_response)) {
5245: $env{"form.scantron.bubblelines.$line"} = $bubble_lines_per_response{$line};
5246: $env{"form.scantron.first_bubble_line.$line"} =
5247: $first_bubble_line{$line};
5248: $env{"form.scantron.sub_bubblelines.$line"} =
5249: $subdivided_bubble_lines{$line};
5250: $env{"form.scantron.responsetype.$line"} =
5251: $responsetype_per_response{$line};
5252: }
5253: foreach my $resid (keys(%masterseq_id_responsenum)) {
5254: my $line = $masterseq_id_responsenum{$resid};
5255: $env{"form.scantron.residpart.$line"} = $resid;
5256: }
5257: }
5258:
5259:
5260: sub restore_bubble_lines {
5261: my $line = 0;
5262: %bubble_lines_per_response = ();
5263: %masterseq_id_responsenum = ();
5264: while ($env{"form.scantron.bubblelines.$line"}) {
5265: my $value = $env{"form.scantron.bubblelines.$line"};
5266: $bubble_lines_per_response{$line} = $value;
5267: $first_bubble_line{$line} =
5268: $env{"form.scantron.first_bubble_line.$line"};
5269: $subdivided_bubble_lines{$line} =
5270: $env{"form.scantron.sub_bubblelines.$line"};
5271: $responsetype_per_response{$line} =
5272: $env{"form.scantron.responsetype.$line"};
5273: my $id = $env{"form.scantron.residpart.$line"};
5274: $masterseq_id_responsenum{$id} = $line;
5275: $line++;
5276: }
5277: }
5278:
5279: =pod
5280:
5281: =item scantron_filenames
5282:
5283: Returns a list of the scantron files in the current course
5284:
5285: =cut
5286:
5287: sub scantron_filenames {
5288: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5289: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5290: my $getpropath = 1;
5291: my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
5292: $cname,$getpropath);
5293: my @possiblenames;
5294: if (ref($dirlist) eq 'ARRAY') {
5295: foreach my $filename (sort(@{$dirlist})) {
5296: ($filename)=split(/&/,$filename);
5297: if ($filename!~/^scantron_orig_/) { next ; }
5298: $filename=~s/^scantron_orig_//;
5299: push(@possiblenames,$filename);
5300: }
5301: }
5302: return @possiblenames;
5303: }
5304:
5305: =pod
5306:
5307: =item scantron_uploads
5308:
5309: Returns html drop-down list of scantron files in current course.
5310:
5311: Arguments:
5312: $file2grade - filename to set as selected in the dropdown
5313:
5314: =cut
5315:
5316: sub scantron_uploads {
5317: my ($file2grade) = @_;
5318: my $result= '<select name="scantron_selectfile">';
5319: $result.="<option></option>";
5320: foreach my $filename (sort(&scantron_filenames())) {
5321: $result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
5322: }
5323: $result.="</select>";
5324: return $result;
5325: }
5326:
5327: =pod
5328:
5329: =item scantron_scantab
5330:
5331: Returns html drop down of the scantron formats in the scantronformat.tab
5332: file.
5333:
5334: =cut
5335:
5336: sub scantron_scantab {
5337: my $result='<select name="scantron_format">'."\n";
5338: $result.='<option></option>'."\n";
5339: my @lines = &get_scantronformat_file();
5340: if (@lines > 0) {
5341: foreach my $line (@lines) {
5342: next if (($line =~ /^\#/) || ($line eq ''));
5343: my ($name,$descrip)=split(/:/,$line);
5344: $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
5345: }
5346: }
5347: $result.='</select>'."\n";
5348: return $result;
5349: }
5350:
5351: =pod
5352:
5353: =item get_scantronformat_file
5354:
5355: Returns an array containing lines from the scantron format file for
5356: the domain of the course.
5357:
5358: If a url for a custom.tab file is listed in domain's configuration.db,
5359: lines are from this file.
5360:
5361: Otherwise, if a default.tab has been published in RES space by the
5362: domainconfig user, lines are from this file.
5363:
5364: Otherwise, fall back to getting lines from the legacy file on the
5365: local server: /home/httpd/lonTabs/default_scantronformat.tab
5366:
5367: =cut
5368:
5369: sub get_scantronformat_file {
5370: my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
5371: my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
5372: my $gottab = 0;
5373: my @lines;
5374: if (ref($domconfig{'scantron'}) eq 'HASH') {
5375: if ($domconfig{'scantron'}{'scantronformat'} ne '') {
5376: my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
5377: if ($formatfile ne '-1') {
5378: @lines = split("\n",$formatfile,-1);
5379: $gottab = 1;
5380: }
5381: }
5382: }
5383: if (!$gottab) {
5384: my $confname = $cdom.'-domainconfig';
5385: my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
5386: my $formatfile = &Apache::lonnet::getfile($default);
5387: if ($formatfile ne '-1') {
5388: @lines = split("\n",$formatfile,-1);
5389: $gottab = 1;
5390: }
5391: }
5392: if (!$gottab) {
5393: my @domains = &Apache::lonnet::current_machine_domains();
5394: if (grep(/^\Q$cdom\E$/,@domains)) {
5395: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
5396: @lines = <$fh>;
5397: close($fh);
5398: } else {
5399: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
5400: @lines = <$fh>;
5401: close($fh);
5402: }
5403: }
5404: return @lines;
5405: }
5406:
5407: =pod
5408:
5409: =item scantron_CODElist
5410:
5411: Returns html drop down of the saved CODE lists from current course,
5412: generated from earlier printings.
5413:
5414: =cut
5415:
5416: sub scantron_CODElist {
5417: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5418: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5419: my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
5420: my $namechoice='<option></option>';
5421: foreach my $name (sort {uc($a) cmp uc($b)} @names) {
5422: if ($name =~ /^error: 2 /) { next; }
5423: if ($name =~ /^type\0/) { next; }
5424: $namechoice.='<option value="'.$name.'">'.$name.'</option>';
5425: }
5426: $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
5427: return $namechoice;
5428: }
5429:
5430: =pod
5431:
5432: =item scantron_CODEunique
5433:
5434: Returns the html for "Each CODE to be used once" radio.
5435:
5436: =cut
5437:
5438: sub scantron_CODEunique {
5439: my $result='<span class="LC_nobreak">
5440: <label><input type="radio" name="scantron_CODEunique"
5441: value="yes" checked="checked" />'.&mt('Yes').' </label>
5442: </span>
5443: <span class="LC_nobreak">
5444: <label><input type="radio" name="scantron_CODEunique"
5445: value="no" />'.&mt('No').' </label>
5446: </span>';
5447: return $result;
5448: }
5449:
5450: =pod
5451:
5452: =item scantron_selectphase
5453:
5454: Generates the initial screen to start the bubblesheet process.
5455: Allows for - starting a grading run.
5456: - downloading existing scan data (original, corrected
5457: or skipped info)
5458:
5459: - uploading new scan data
5460:
5461: Arguments:
5462: $r - The Apache request object
5463: $file2grade - name of the file that contain the scanned data to score
5464:
5465: =cut
5466:
5467: sub scantron_selectphase {
5468: my ($r,$file2grade,$symb) = @_;
5469: if (!$symb) {return '';}
5470: my $map_error;
5471: my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
5472: if ($map_error) {
5473: $r->print('<br />'.&navmap_errormsg().'<br />');
5474: return;
5475: }
5476: my $default_form_data=&defaultFormData($symb);
5477: my $file_selector=&scantron_uploads($file2grade);
5478: my $format_selector=&scantron_scantab();
5479: my $CODE_selector=&scantron_CODElist();
5480: my $CODE_unique=&scantron_CODEunique();
5481: my $result;
5482:
5483: $ssi_error = 0;
5484:
5485: if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
5486: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
5487:
5488: # Chunk of form to prompt for a scantron file upload.
5489:
5490: $r->print('
5491: <br />
5492: '.&Apache::loncommon::start_data_table('LC_scantron_action').'
5493: '.&Apache::loncommon::start_data_table_header_row().'
5494: <th>
5495: '.&mt('Specify a bubblesheet data file to upload.').'
5496: </th>
5497: '.&Apache::loncommon::end_data_table_header_row().'
5498: '.&Apache::loncommon::start_data_table_row().'
5499: <td>
5500: ');
5501: my $default_form_data=&defaultFormData($symb);
5502: my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
5503: my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
5504: $r->print(&Apache::lonhtmlcommon::scripttag('
5505: function checkUpload(formname) {
5506: if (formname.upfile.value == "") {
5507: alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
5508: return false;
5509: }
5510: formname.submit();
5511: }'));
5512: $r->print('
5513: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
5514: '.$default_form_data.'
5515: <input name="courseid" type="hidden" value="'.$cnum.'" />
5516: <input name="domainid" type="hidden" value="'.$cdom.'" />
5517: <input name="command" value="scantronupload_save" type="hidden" />
5518: '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
5519: <br />
5520: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
5521: </form>
5522: ');
5523:
5524: $r->print('
5525: </td>
5526: '.&Apache::loncommon::end_data_table_row().'
5527: '.&Apache::loncommon::end_data_table().'
5528: ');
5529: }
5530:
5531: # Chunk of form to prompt for a file to grade and how:
5532:
5533: $result.= '
5534: <br />
5535: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
5536: <input type="hidden" name="command" value="scantron_warning" />
5537: '.$default_form_data.'
5538: '.&Apache::loncommon::start_data_table('LC_scantron_action').'
5539: '.&Apache::loncommon::start_data_table_header_row().'
5540: <th colspan="2">
5541: '.&mt('Specify file and which Folder/Sequence to grade').'
5542: </th>
5543: '.&Apache::loncommon::end_data_table_header_row().'
5544: '.&Apache::loncommon::start_data_table_row().'
5545: <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
5546: '.&Apache::loncommon::end_data_table_row().'
5547: '.&Apache::loncommon::start_data_table_row().'
5548: <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
5549: '.&Apache::loncommon::end_data_table_row().'
5550: '.&Apache::loncommon::start_data_table_row().'
5551: <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
5552: '.&Apache::loncommon::end_data_table_row().'
5553: '.&Apache::loncommon::start_data_table_row().'
5554: <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
5555: '.&Apache::loncommon::end_data_table_row().'
5556: '.&Apache::loncommon::start_data_table_row().'
5557: <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
5558: '.&Apache::loncommon::end_data_table_row().'
5559: '.&Apache::loncommon::start_data_table_row().'
5560: <td> '.&mt('Options:').' </td>
5561: <td>
5562: <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
5563: <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
5564: <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
5565: </td>
5566: '.&Apache::loncommon::end_data_table_row().'
5567: '.&Apache::loncommon::start_data_table_row().'
5568: <td colspan="2">
5569: <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
5570: </td>
5571: '.&Apache::loncommon::end_data_table_row().'
5572: '.&Apache::loncommon::end_data_table().'
5573: </form>
5574: ';
5575:
5576: $r->print($result);
5577:
5578:
5579:
5580: # Chunk of the form that prompts to view a scoring office file,
5581: # corrected file, skipped records in a file.
5582:
5583: $r->print('
5584: <br />
5585: <form action="/adm/grades" name="scantron_download">
5586: '.$default_form_data.'
5587: <input type="hidden" name="command" value="scantron_download" />
5588: '.&Apache::loncommon::start_data_table('LC_scantron_action').'
5589: '.&Apache::loncommon::start_data_table_header_row().'
5590: <th>
5591: '.&mt('Download a scoring office file').'
5592: </th>
5593: '.&Apache::loncommon::end_data_table_header_row().'
5594: '.&Apache::loncommon::start_data_table_row().'
5595: <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).'
5596: <br />
5597: <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
5598: '.&Apache::loncommon::end_data_table_row().'
5599: '.&Apache::loncommon::end_data_table().'
5600: </form>
5601: <br />
5602: ');
5603:
5604: &Apache::lonpickcode::code_list($r,2);
5605:
5606: $r->print('<br /><form method="post" name="checkscantron" action="">'.
5607: $default_form_data."\n".
5608: &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
5609: &Apache::loncommon::start_data_table_header_row()."\n".
5610: '<th colspan="2">
5611: '.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
5612: '</th>'."\n".
5613: &Apache::loncommon::end_data_table_header_row()."\n".
5614: &Apache::loncommon::start_data_table_row()."\n".
5615: '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
5616: '<td> '.$sequence_selector.' </td>'.
5617: &Apache::loncommon::end_data_table_row()."\n".
5618: &Apache::loncommon::start_data_table_row()."\n".
5619: '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
5620: '<td> '.$file_selector.' </td>'."\n".
5621: &Apache::loncommon::end_data_table_row()."\n".
5622: &Apache::loncommon::start_data_table_row()."\n".
5623: '<td> '.&mt('Format of data file:').' </td>'."\n".
5624: '<td> '.$format_selector.' </td>'."\n".
5625: &Apache::loncommon::end_data_table_row()."\n".
5626: &Apache::loncommon::start_data_table_row()."\n".
5627: '<td> '.&mt('Options').' </td>'."\n".
5628: '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
5629: &Apache::loncommon::end_data_table_row()."\n".
5630: &Apache::loncommon::start_data_table_row()."\n".
5631: '<td colspan="2">'."\n".
5632: '<input type="hidden" name="command" value="checksubmissions" />'."\n".
5633: '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
5634: '</td>'."\n".
5635: &Apache::loncommon::end_data_table_row()."\n".
5636: &Apache::loncommon::end_data_table()."\n".
5637: '</form><br />');
5638: return;
5639: }
5640:
5641: =pod
5642:
5643: =item get_scantron_config
5644:
5645: Parse and return the bubblesheet configuration line selected as a
5646: hash of configuration file fields.
5647:
5648: Arguments:
5649: which - the name of the configuration to parse from the file.
5650:
5651:
5652: Returns:
5653: If the named configuration is not in the file, an empty
5654: hash is returned.
5655: a hash with the fields
5656: name - internal name for the this configuration setup
5657: description - text to display to operator that describes this config
5658: CODElocation - if 0 or the string 'none'
5659: - no CODE exists for this config
5660: if -1 || the string 'letter'
5661: - a CODE exists for this config and is
5662: a string of letters
5663: Unsupported value (but planned for future support)
5664: if a positive integer
5665: - The CODE exists as the first n items from
5666: the question section of the form
5667: if the string 'number'
5668: - The CODE exists for this config and is
5669: a string of numbers
5670: CODEstart - (only matter if a CODE exists) column in the line where
5671: the CODE starts
5672: CODElength - length of the CODE
5673: IDstart - column where the student/employee ID starts
5674: IDlength - length of the student/employee ID info
5675: Qstart - column where the information from the bubbled
5676: 'questions' start
5677: Qlength - number of columns comprising a single bubble line from
5678: the sheet. (usually either 1 or 10)
5679: Qon - either a single character representing the character used
5680: to signal a bubble was chosen in the positional setup, or
5681: the string 'letter' if the letter of the chosen bubble is
5682: in the final, or 'number' if a number representing the
5683: chosen bubble is in the file (1->A 0->J)
5684: Qoff - the character used to represent that a bubble was
5685: left blank
5686: PaperID - if the scanning process generates a unique number for each
5687: sheet scanned the column that this ID number starts in
5688: PaperIDlength - number of columns that comprise the unique ID number
5689: for the sheet of paper
5690: FirstName - column that the first name starts in
5691: FirstNameLength - number of columns that the first name spans
5692:
5693: LastName - column that the last name starts in
5694: LastNameLength - number of columns that the last name spans
5695: BubblesPerRow - number of bubbles available in each row used to
5696: bubble an answer. (If not specified, 10 assumed).
5697:
5698: =cut
5699:
5700: sub get_scantron_config {
5701: my ($which) = @_;
5702: my @lines = &get_scantronformat_file();
5703: my %config;
5704: #FIXME probably should move to XML it has already gotten a bit much now
5705: foreach my $line (@lines) {
5706: my ($name,$descrip)=split(/:/,$line);
5707: if ($name ne $which ) { next; }
5708: chomp($line);
5709: my @config=split(/:/,$line);
5710: $config{'name'}=$config[0];
5711: $config{'description'}=$config[1];
5712: $config{'CODElocation'}=$config[2];
5713: $config{'CODEstart'}=$config[3];
5714: $config{'CODElength'}=$config[4];
5715: $config{'IDstart'}=$config[5];
5716: $config{'IDlength'}=$config[6];
5717: $config{'Qstart'}=$config[7];
5718: $config{'Qlength'}=$config[8];
5719: $config{'Qoff'}=$config[9];
5720: $config{'Qon'}=$config[10];
5721: $config{'PaperID'}=$config[11];
5722: $config{'PaperIDlength'}=$config[12];
5723: $config{'FirstName'}=$config[13];
5724: $config{'FirstNamelength'}=$config[14];
5725: $config{'LastName'}=$config[15];
5726: $config{'LastNamelength'}=$config[16];
5727: $config{'BubblesPerRow'}=$config[17];
5728: last;
5729: }
5730: return %config;
5731: }
5732:
5733: =pod
5734:
5735: =item username_to_idmap
5736:
5737: creates a hash keyed by student/employee ID with values of the corresponding
5738: student username:domain.
5739:
5740: Arguments:
5741:
5742: $classlist - reference to the class list hash. This is a hash
5743: keyed by student name:domain whose elements are references
5744: to arrays containing various chunks of information
5745: about the student. (See loncoursedata for more info).
5746:
5747: Returns
5748: %idmap - the constructed hash
5749:
5750: =cut
5751:
5752: sub username_to_idmap {
5753: my ($classlist)= @_;
5754: my %idmap;
5755: foreach my $student (keys(%$classlist)) {
5756: $idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
5757: $student;
5758: }
5759: return %idmap;
5760: }
5761:
5762: =pod
5763:
5764: =item scantron_fixup_scanline
5765:
5766: Process a requested correction to a scanline.
5767:
5768: Arguments:
5769: $scantron_config - hash from &get_scantron_config()
5770: $scan_data - hash of correction information
5771: (see &scantron_getfile())
5772: $line - existing scanline
5773: $whichline - line number of the passed in scanline
5774: $field - type of change to process
5775: (either
5776: 'ID' -> correct the student/employee ID
5777: 'CODE' -> correct the CODE
5778: 'answer' -> fixup the submitted answers)
5779:
5780: $args - hash of additional info,
5781: - 'ID'
5782: 'newid' -> studentID to use in replacement
5783: of existing one
5784: - 'CODE'
5785: 'CODE_ignore_dup' - set to true if duplicates
5786: should be ignored.
5787: 'CODE' - is new code or 'use_unfound'
5788: if the existing unfound code should
5789: be used as is
5790: - 'answer'
5791: 'response' - new answer or 'none' if blank
5792: 'question' - the bubble line to change
5793: 'questionnum' - the question identifier,
5794: may include subquestion.
5795:
5796: Returns:
5797: $line - the modified scanline
5798:
5799: Side effects:
5800: $scan_data - may be updated
5801:
5802: =cut
5803:
5804:
5805: sub scantron_fixup_scanline {
5806: my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
5807: if ($field eq 'ID') {
5808: if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
5809: return ($line,1,'New value too large');
5810: }
5811: if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
5812: $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
5813: $args->{'newid'});
5814: }
5815: substr($line,$$scantron_config{'IDstart'}-1,
5816: $$scantron_config{'IDlength'})=$args->{'newid'};
5817: if ($args->{'newid'}=~/^\s*$/) {
5818: &scan_data($scan_data,"$whichline.user",
5819: $args->{'username'}.':'.$args->{'domain'});
5820: }
5821: } elsif ($field eq 'CODE') {
5822: if ($args->{'CODE_ignore_dup'}) {
5823: &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
5824: }
5825: &scan_data($scan_data,"$whichline.useCODE",'1');
5826: if ($args->{'CODE'} ne 'use_unfound') {
5827: if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
5828: return ($line,1,'New CODE value too large');
5829: }
5830: if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
5831: $args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
5832: }
5833: substr($line,$$scantron_config{'CODEstart'}-1,
5834: $$scantron_config{'CODElength'})=$args->{'CODE'};
5835: }
5836: } elsif ($field eq 'answer') {
5837: my $length=$scantron_config->{'Qlength'};
5838: my $off=$scantron_config->{'Qoff'};
5839: my $on=$scantron_config->{'Qon'};
5840: my $answer=${off}x$length;
5841: if ($args->{'response'} eq 'none') {
5842: &scan_data($scan_data,
5843: "$whichline.no_bubble.".$args->{'questionnum'},'1');
5844: } else {
5845: if ($on eq 'letter') {
5846: my @alphabet=('A'..'Z');
5847: $answer=$alphabet[$args->{'response'}];
5848: } elsif ($on eq 'number') {
5849: $answer=$args->{'response'}+1;
5850: if ($answer == 10) { $answer = '0'; }
5851: } else {
5852: substr($answer,$args->{'response'},1)=$on;
5853: }
5854: &scan_data($scan_data,
5855: "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
5856: }
5857: my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
5858: substr($line,$where-1,$length)=$answer;
5859: }
5860: return $line;
5861: }
5862:
5863: =pod
5864:
5865: =item scan_data
5866:
5867: Edit or look up an item in the scan_data hash.
5868:
5869: Arguments:
5870: $scan_data - The hash (see scantron_getfile)
5871: $key - shorthand of the key to edit (actual key is
5872: scantronfilename_key).
5873: $data - New value of the hash entry.
5874: $delete - If true, the entry is removed from the hash.
5875:
5876: Returns:
5877: The new value of the hash table field (undefined if deleted).
5878:
5879: =cut
5880:
5881:
5882: sub scan_data {
5883: my ($scan_data,$key,$value,$delete)=@_;
5884: my $filename=$env{'form.scantron_selectfile'};
5885: if (defined($value)) {
5886: $scan_data->{$filename.'_'.$key} = $value;
5887: }
5888: if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
5889: return $scan_data->{$filename.'_'.$key};
5890: }
5891:
5892: # ----- These first few routines are general use routines.----
5893:
5894: # Return the number of occurences of a pattern in a string.
5895:
5896: sub occurence_count {
5897: my ($string, $pattern) = @_;
5898:
5899: my @matches = ($string =~ /$pattern/g);
5900:
5901: return scalar(@matches);
5902: }
5903:
5904:
5905: # Take a string known to have digits and convert all the
5906: # digits into letters in the range J,A..I.
5907:
5908: sub digits_to_letters {
5909: my ($input) = @_;
5910:
5911: my @alphabet = ('J', 'A'..'I');
5912:
5913: my @input = split(//, $input);
5914: my $output ='';
5915: for (my $i = 0; $i < scalar(@input); $i++) {
5916: if ($input[$i] =~ /\d/) {
5917: $output .= $alphabet[$input[$i]];
5918: } else {
5919: $output .= $input[$i];
5920: }
5921: }
5922: return $output;
5923: }
5924:
5925: =pod
5926:
5927: =item scantron_parse_scanline
5928:
5929: Decodes a scanline from the selected bubblesheet file
5930:
5931: Arguments:
5932: line - The text of the bubblesheet file line to process
5933: whichline - Line number
5934: scantron_config - Hash describing the format of the bubblesheet lines.
5935: scan_data - Hash of extra information about the scanline
5936: (see scantron_getfile for more information)
5937: just_header - True if should not process question answers but only
5938: the stuff to the left of the answers.
5939: randomorder - True if randomorder in use
5940: randompick - True if randompick in use
5941: sequence - Exam folder URL
5942: master_seq - Ref to array containing symbs in exam folder
5943: symb_to_resource - Ref to hash of symbs for resources in exam folder
5944: (corresponding values are resource objects)
5945: partids_by_symb - Ref to hash of symb -> array ref of partIDs
5946: orderedforcode - Ref to hash of arrays. keys are CODEs and values
5947: are refs to an array of resource objects, ordered
5948: according to order used for CODE, when randomorder
5949: and or randompick are in use.
5950: respnumlookup - Ref to hash mapping question numbers in bubble lines
5951: for current line to question number used for same question
5952: in "Master Sequence" (as seen by Course Coordinator).
5953: startline - Ref to hash where key is question number (0 is first)
5954: and value is number of first bubble line for current
5955: student or code-based randompick and/or randomorder.
5956: totalref - Ref of scalar used to score total number of bubble
5957: lines needed for responses in a scan line (used when
5958: randompick in use.
5959:
5960: Returns:
5961: Hash containing the result of parsing the scanline
5962:
5963: Keys are all proceeded by the string 'scantron.'
5964:
5965: CODE - the CODE in use for this scanline
5966: useCODE - 1 if the CODE is invalid but it usage has been forced
5967: by the operator
5968: CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
5969: CODEs were selected, but the usage has been
5970: forced by the operator
5971: ID - student/employee ID
5972: PaperID - if used, the ID number printed on the sheet when the
5973: paper was scanned
5974: FirstName - first name from the sheet
5975: LastName - last name from the sheet
5976:
5977: if just_header was not true these key may also exist
5978:
5979: missingerror - a list of bubble ranges that are considered to be answers
5980: to a single question that don't have any bubbles filled in.
5981: Of the form questionnumber:firstbubblenumber:count.
5982: doubleerror - a list of bubble ranges that are considered to be answers
5983: to a single question that have more than one bubble filled in.
5984: Of the form questionnumber::firstbubblenumber:count
5985:
5986: In the above, count is the number of bubble responses in the
5987: input line needed to represent the possible answers to the question.
5988: e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
5989: per line would have count = 2.
5990:
5991: maxquest - the number of the last bubble line that was parsed
5992:
5993: (<number> starts at 1)
5994: <number>.answer - zero or more letters representing the selected
5995: letters from the scanline for the bubble line
5996: <number>.
5997: if blank there was either no bubble or there where
5998: multiple bubbles, (consult the keys missingerror and
5999: doubleerror if this is an error condition)
6000:
6001: =cut
6002:
6003: sub scantron_parse_scanline {
6004: my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
6005: $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
6006: $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
6007:
6008: my %record;
6009: my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
6010: if (!($$scantron_config{'CODElocation'} eq 0 ||
6011: $$scantron_config{'CODElocation'} eq 'none')) {
6012: if ($$scantron_config{'CODElocation'} < 0 ||
6013: $$scantron_config{'CODElocation'} eq 'letter' ||
6014: $$scantron_config{'CODElocation'} eq 'number') {
6015: $record{'scantron.CODE'}=substr($data,
6016: $$scantron_config{'CODEstart'}-1,
6017: $$scantron_config{'CODElength'});
6018: if (&scan_data($scan_data,"$whichline.useCODE")) {
6019: $record{'scantron.useCODE'}=1;
6020: }
6021: if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
6022: $record{'scantron.CODE_ignore_dup'}=1;
6023: }
6024: } else {
6025: #FIXME interpret first N questions
6026: }
6027: }
6028: $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
6029: $$scantron_config{'IDlength'});
6030: $record{'scantron.PaperID'}=
6031: substr($data,$$scantron_config{'PaperID'}-1,
6032: $$scantron_config{'PaperIDlength'});
6033: $record{'scantron.FirstName'}=
6034: substr($data,$$scantron_config{'FirstName'}-1,
6035: $$scantron_config{'FirstNamelength'});
6036: $record{'scantron.LastName'}=
6037: substr($data,$$scantron_config{'LastName'}-1,
6038: $$scantron_config{'LastNamelength'});
6039: if ($just_header) { return \%record; }
6040:
6041: my @alphabet=('A'..'Z');
6042: my $questnum=0;
6043: my $ansnum =1; # Multiple 'answer lines'/question.
6044:
6045: my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
6046: if ($randompick || $randomorder) {
6047: my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
6048: $master_seq,$symb_to_resource,
6049: $partids_by_symb,$orderedforcode,
6050: $respnumlookup,$startline);
6051: if ($total) {
6052: $lastpos = $total*$$scantron_config{'Qlength'};
6053: }
6054: if (ref($totalref)) {
6055: $$totalref = $total;
6056: }
6057: }
6058: my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos); # Answers
6059: chomp($questions); # Get rid of any trailing \n.
6060: $questions =~ s/\r$//; # Get rid of trailing \r too (MAC or Win uploads).
6061: while (length($questions)) {
6062: my $answers_needed;
6063: if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
6064: $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
6065: } else {
6066: $answers_needed = $bubble_lines_per_response{$questnum};
6067: }
6068: my $answer_length = ($$scantron_config{'Qlength'} * $answers_needed)
6069: || 1;
6070: $questnum++;
6071: my $quest_id = $questnum;
6072: my $currentquest = substr($questions,0,$answer_length);
6073: $questions = substr($questions,$answer_length);
6074: if (length($currentquest) < $answer_length) { next; }
6075:
6076: my $subdivided;
6077: if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
6078: $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
6079: } else {
6080: $subdivided = $subdivided_bubble_lines{$questnum-1};
6081: }
6082: if ($subdivided =~ /,/) {
6083: my $subquestnum = 1;
6084: my $subquestions = $currentquest;
6085: my @subanswers_needed = split(/,/,$subdivided);
6086: foreach my $subans (@subanswers_needed) {
6087: my $subans_length =
6088: ($$scantron_config{'Qlength'} * $subans) || 1;
6089: my $currsubquest = substr($subquestions,0,$subans_length);
6090: $subquestions = substr($subquestions,$subans_length);
6091: $quest_id = "$questnum.$subquestnum";
6092: if (($$scantron_config{'Qon'} eq 'letter') ||
6093: ($$scantron_config{'Qon'} eq 'number')) {
6094: $ansnum = &scantron_validator_lettnum($ansnum,
6095: $questnum,$quest_id,$subans,$currsubquest,$whichline,
6096: \@alphabet,\%record,$scantron_config,$scan_data,
6097: $randomorder,$randompick,$respnumlookup);
6098: } else {
6099: $ansnum = &scantron_validator_positional($ansnum,
6100: $questnum,$quest_id,$subans,$currsubquest,$whichline,
6101: \@alphabet,\%record,$scantron_config,$scan_data,
6102: $randomorder,$randompick,$respnumlookup);
6103: }
6104: $subquestnum ++;
6105: }
6106: } else {
6107: if (($$scantron_config{'Qon'} eq 'letter') ||
6108: ($$scantron_config{'Qon'} eq 'number')) {
6109: $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
6110: $quest_id,$answers_needed,$currentquest,$whichline,
6111: \@alphabet,\%record,$scantron_config,$scan_data,
6112: $randomorder,$randompick,$respnumlookup);
6113: } else {
6114: $ansnum = &scantron_validator_positional($ansnum,$questnum,
6115: $quest_id,$answers_needed,$currentquest,$whichline,
6116: \@alphabet,\%record,$scantron_config,$scan_data,
6117: $randomorder,$randompick,$respnumlookup);
6118: }
6119: }
6120: }
6121: $record{'scantron.maxquest'}=$questnum;
6122: return \%record;
6123: }
6124:
6125: sub get_master_seq {
6126: my ($resources,$master_seq,$symb_to_resource) = @_;
6127: return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') &&
6128: (ref($symb_to_resource) eq 'HASH'));
6129: my $resource_error;
6130: foreach my $resource (@{$resources}) {
6131: my $ressymb;
6132: if (ref($resource)) {
6133: $ressymb = $resource->symb();
6134: push(@{$master_seq},$ressymb);
6135: $symb_to_resource->{$ressymb} = $resource;
6136: } else {
6137: $resource_error = 1;
6138: last;
6139: }
6140: }
6141: return $resource_error;
6142: }
6143:
6144: sub get_respnum_lookups {
6145: my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
6146: $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
6147: return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
6148: (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
6149: (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
6150: (ref($startline) eq 'HASH'));
6151: my ($user,$scancode);
6152: if ((exists($record->{'scantron.CODE'})) &&
6153: (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
6154: $scancode = $record->{'scantron.CODE'};
6155: } else {
6156: $user = &scantron_find_student($record,$scan_data,$idmap,$line);
6157: }
6158: my @mapresources =
6159: &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
6160: $orderedforcode);
6161: my $total = 0;
6162: my $count = 0;
6163: foreach my $resource (@mapresources) {
6164: my $id = $resource->id();
6165: my $symb = $resource->symb();
6166: if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
6167: foreach my $partid (@{$partids_by_symb->{$symb}}) {
6168: my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
6169: if ($respnum ne '') {
6170: $respnumlookup->{$count} = $respnum;
6171: $startline->{$count} = $total;
6172: $total += $bubble_lines_per_response{$respnum};
6173: $count ++;
6174: }
6175: }
6176: }
6177: }
6178: return $total;
6179: }
6180:
6181: sub scantron_validator_lettnum {
6182: my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
6183: $alphabet,$record,$scantron_config,$scan_data,$randomorder,
6184: $randompick,$respnumlookup) = @_;
6185:
6186: # Qon 'letter' implies for each slot in currquest we have:
6187: # ? or * for doubles, a letter in A-Z for a bubble, and
6188: # about anything else (esp. a value of Qoff) for missing
6189: # bubbles.
6190: #
6191: # Qon 'number' implies each slot gives a digit that indexes the
6192: # bubbles filled, or Qoff, or a non-number for unbubbled lines,
6193: # and * or ? for double bubbles on a single line.
6194: #
6195:
6196: my $matchon;
6197: if ($$scantron_config{'Qon'} eq 'letter') {
6198: $matchon = '[A-Z]';
6199: } elsif ($$scantron_config{'Qon'} eq 'number') {
6200: $matchon = '\d';
6201: }
6202: my $occurrences = 0;
6203: my $responsenum = $questnum-1;
6204: if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
6205: $responsenum = $respnumlookup->{$questnum-1}
6206: }
6207: if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
6208: ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
6209: ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
6210: ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
6211: ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
6212: ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
6213: my @singlelines = split('',$currquest);
6214: foreach my $entry (@singlelines) {
6215: $occurrences = &occurence_count($entry,$matchon);
6216: if ($occurrences > 1) {
6217: last;
6218: }
6219: }
6220: } else {
6221: $occurrences = &occurence_count($currquest,$matchon);
6222: }
6223: if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
6224: push(@{$record->{'scantron.doubleerror'}},$quest_id);
6225: for (my $ans=0; $ans<$answers_needed; $ans++) {
6226: my $bubble = substr($currquest,$ans,1);
6227: if ($bubble =~ /$matchon/ ) {
6228: if ($$scantron_config{'Qon'} eq 'number') {
6229: if ($bubble == 0) {
6230: $bubble = 10;
6231: }
6232: $record->{"scantron.$ansnum.answer"} =
6233: $alphabet->[$bubble-1];
6234: } else {
6235: $record->{"scantron.$ansnum.answer"} = $bubble;
6236: }
6237: } else {
6238: $record->{"scantron.$ansnum.answer"}='';
6239: }
6240: $ansnum++;
6241: }
6242: } elsif (!defined($currquest)
6243: || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
6244: || (&occurence_count($currquest,$matchon) == 0)) {
6245: for (my $ans=0; $ans<$answers_needed; $ans++ ) {
6246: $record->{"scantron.$ansnum.answer"}='';
6247: $ansnum++;
6248: }
6249: if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
6250: push(@{$record->{'scantron.missingerror'}},$quest_id);
6251: }
6252: } else {
6253: if ($$scantron_config{'Qon'} eq 'number') {
6254: $currquest = &digits_to_letters($currquest);
6255: }
6256: for (my $ans=0; $ans<$answers_needed; $ans++) {
6257: my $bubble = substr($currquest,$ans,1);
6258: $record->{"scantron.$ansnum.answer"} = $bubble;
6259: $ansnum++;
6260: }
6261: }
6262: return $ansnum;
6263: }
6264:
6265: sub scantron_validator_positional {
6266: my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
6267: $whichline,$alphabet,$record,$scantron_config,$scan_data,
6268: $randomorder,$randompick,$respnumlookup) = @_;
6269:
6270: # Otherwise there's a positional notation;
6271: # each bubble line requires Qlength items, and there are filled in
6272: # bubbles for each case where there 'Qon' characters.
6273: #
6274:
6275: my @array=split($$scantron_config{'Qon'},$currquest,-1);
6276:
6277: # If the split only gives us one element.. the full length of the
6278: # answer string, no bubbles are filled in:
6279:
6280: if ($answers_needed eq '') {
6281: return;
6282: }
6283:
6284: if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
6285: for (my $ans=0; $ans<$answers_needed; $ans++ ) {
6286: $record->{"scantron.$ansnum.answer"}='';
6287: $ansnum++;
6288: }
6289: if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
6290: push(@{$record->{"scantron.missingerror"}},$quest_id);
6291: }
6292: } elsif (scalar(@array) == 2) {
6293: my $location = length($array[0]);
6294: my $line_num = int($location / $$scantron_config{'Qlength'});
6295: my $bubble = $alphabet->[$location % $$scantron_config{'Qlength'}];
6296: for (my $ans=0; $ans<$answers_needed; $ans++) {
6297: if ($ans eq $line_num) {
6298: $record->{"scantron.$ansnum.answer"} = $bubble;
6299: } else {
6300: $record->{"scantron.$ansnum.answer"} = ' ';
6301: }
6302: $ansnum++;
6303: }
6304: } else {
6305: # If there's more than one instance of a bubble character
6306: # That's a double bubble; with positional notation we can
6307: # record all the bubbles filled in as well as the
6308: # fact this response consists of multiple bubbles.
6309: #
6310: my $responsenum = $questnum-1;
6311: if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
6312: $responsenum = $respnumlookup->{$questnum-1}
6313: }
6314: if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
6315: ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
6316: ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
6317: ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
6318: ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
6319: ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
6320: my $doubleerror = 0;
6321: while (($currquest >= $$scantron_config{'Qlength'}) &&
6322: (!$doubleerror)) {
6323: my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
6324: $currquest = substr($currquest,$$scantron_config{'Qlength'});
6325: my @currarray = split($$scantron_config{'Qon'},$currline,-1);
6326: if (length(@currarray) > 2) {
6327: $doubleerror = 1;
6328: }
6329: }
6330: if ($doubleerror) {
6331: push(@{$record->{'scantron.doubleerror'}},$quest_id);
6332: }
6333: } else {
6334: push(@{$record->{'scantron.doubleerror'}},$quest_id);
6335: }
6336: my $item = $ansnum;
6337: for (my $ans=0; $ans<$answers_needed; $ans++) {
6338: $record->{"scantron.$item.answer"} = '';
6339: $item ++;
6340: }
6341:
6342: my @ans=@array;
6343: my $i=0;
6344: my $increment = 0;
6345: while ($#ans) {
6346: $i+=length($ans[0]) + $increment;
6347: my $line = int($i/$$scantron_config{'Qlength'} + $ansnum);
6348: my $bubble = $i%$$scantron_config{'Qlength'};
6349: $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
6350: shift(@ans);
6351: $increment = 1;
6352: }
6353: $ansnum += $answers_needed;
6354: }
6355: return $ansnum;
6356: }
6357:
6358: =pod
6359:
6360: =item scantron_add_delay
6361:
6362: Adds an error message that occurred during the grading phase to a
6363: queue of messages to be shown after grading pass is complete
6364:
6365: Arguments:
6366: $delayqueue - arrary ref of hash ref of error messages
6367: $scanline - the scanline that caused the error
6368: $errormesage - the error message
6369: $errorcode - a numeric code for the error
6370:
6371: Side Effects:
6372: updates the $delayqueue to have a new hash ref of the error
6373:
6374: =cut
6375:
6376: sub scantron_add_delay {
6377: my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
6378: push(@$delayqueue,
6379: {'line' => $scanline, 'emsg' => $errormessage,
6380: 'ecode' => $errorcode }
6381: );
6382: }
6383:
6384: =pod
6385:
6386: =item scantron_find_student
6387:
6388: Finds the username for the current scanline
6389:
6390: Arguments:
6391: $scantron_record - hash result from scantron_parse_scanline
6392: $scan_data - hash of correction information
6393: (see &scantron_getfile() form more information)
6394: $idmap - hash from &username_to_idmap()
6395: $line - number of current scanline
6396:
6397: Returns:
6398: Either 'username:domain' or undef if unknown
6399:
6400: =cut
6401:
6402: sub scantron_find_student {
6403: my ($scantron_record,$scan_data,$idmap,$line)=@_;
6404: my $scanID=$$scantron_record{'scantron.ID'};
6405: if ($scanID =~ /^\s*$/) {
6406: return &scan_data($scan_data,"$line.user");
6407: }
6408: foreach my $id (keys(%$idmap)) {
6409: if (lc($id) eq lc($scanID)) {
6410: return $$idmap{$id};
6411: }
6412: }
6413: return undef;
6414: }
6415:
6416: =pod
6417:
6418: =item scantron_filter
6419:
6420: Filter sub for lonnavmaps, filters out hidden resources if ignore
6421: hidden resources was selected
6422:
6423: =cut
6424:
6425: sub scantron_filter {
6426: my ($curres)=@_;
6427:
6428: if (ref($curres) && $curres->is_problem()) {
6429: # if the user has asked to not have either hidden
6430: # or 'randomout' controlled resources to be graded
6431: # don't include them
6432: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
6433: && $curres->randomout) {
6434: return 0;
6435: }
6436: return 1;
6437: }
6438: return 0;
6439: }
6440:
6441: =pod
6442:
6443: =item scantron_process_corrections
6444:
6445: Gets correction information out of submitted form data and corrects
6446: the scanline
6447:
6448: =cut
6449:
6450: sub scantron_process_corrections {
6451: my ($r) = @_;
6452: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6453: my ($scanlines,$scan_data)=&scantron_getfile();
6454: my $classlist=&Apache::loncoursedata::get_classlist();
6455: my $which=$env{'form.scantron_line'};
6456: my $line=&scantron_get_line($scanlines,$scan_data,$which);
6457: my ($skip,$err,$errmsg);
6458: if ($env{'form.scantron_skip_record'}) {
6459: $skip=1;
6460: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
6461: my $newstudent=$env{'form.scantron_username'}.':'.
6462: $env{'form.scantron_domain'};
6463: my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
6464: ($line,$err,$errmsg)=
6465: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
6466: 'ID',{'newid'=>$newid,
6467: 'username'=>$env{'form.scantron_username'},
6468: 'domain'=>$env{'form.scantron_domain'}});
6469: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
6470: my $resolution=$env{'form.scantron_CODE_resolution'};
6471: my $newCODE;
6472: my %args;
6473: if ($resolution eq 'use_unfound') {
6474: $newCODE='use_unfound';
6475: } elsif ($resolution eq 'use_found') {
6476: $newCODE=$env{'form.scantron_CODE_selectedvalue'};
6477: } elsif ($resolution eq 'use_typed') {
6478: $newCODE=$env{'form.scantron_CODE_newvalue'};
6479: } elsif ($resolution =~ /^use_closest_(\d+)/) {
6480: $newCODE=$env{"form.scantron_CODE_closest_$1"};
6481: }
6482: if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
6483: $args{'CODE_ignore_dup'}=1;
6484: }
6485: $args{'CODE'}=$newCODE;
6486: ($line,$err,$errmsg)=
6487: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
6488: 'CODE',\%args);
6489: } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
6490: foreach my $question (split(',',$env{'form.scantron_questions'})) {
6491: ($line,$err,$errmsg)=
6492: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
6493: $which,'answer',
6494: { 'question'=>$question,
6495: 'response'=>$env{"form.scantron_correct_Q_$question"},
6496: 'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
6497: if ($err) { last; }
6498: }
6499: }
6500: if ($err) {
6501: $r->print(
6502: '<p class="LC_error">'
6503: .&mt('Unable to accept last correction, an error occurred: [_1]',
6504: $errmsg)
6505: .'</p>');
6506: } else {
6507: &scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
6508: &scantron_putfile($scanlines,$scan_data);
6509: }
6510: }
6511:
6512: =pod
6513:
6514: =item reset_skipping_status
6515:
6516: Forgets the current set of remember skipped scanlines (and thus
6517: reverts back to considering all lines in the
6518: scantron_skipped_<filename> file)
6519:
6520: =cut
6521:
6522: sub reset_skipping_status {
6523: my ($scanlines,$scan_data)=&scantron_getfile();
6524: &scan_data($scan_data,'remember_skipping',undef,1);
6525: &scantron_putfile(undef,$scan_data);
6526: }
6527:
6528: =pod
6529:
6530: =item start_skipping
6531:
6532: Marks a scanline to be skipped.
6533:
6534: =cut
6535:
6536: sub start_skipping {
6537: my ($scan_data,$i)=@_;
6538: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
6539: if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
6540: $remembered{$i}=2;
6541: } else {
6542: $remembered{$i}=1;
6543: }
6544: &scan_data($scan_data,'remember_skipping',join(':',%remembered));
6545: }
6546:
6547: =pod
6548:
6549: =item should_be_skipped
6550:
6551: Checks whether a scanline should be skipped.
6552:
6553: =cut
6554:
6555: sub should_be_skipped {
6556: my ($scanlines,$scan_data,$i)=@_;
6557: if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
6558: # not redoing old skips
6559: if ($scanlines->{'skipped'}[$i]) { return 1; }
6560: return 0;
6561: }
6562: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
6563:
6564: if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
6565: return 0;
6566: }
6567: return 1;
6568: }
6569:
6570: =pod
6571:
6572: =item remember_current_skipped
6573:
6574: Discovers what scanlines are in the scantron_skipped_<filename>
6575: file and remembers them into scan_data for later use.
6576:
6577: =cut
6578:
6579: sub remember_current_skipped {
6580: my ($scanlines,$scan_data)=&scantron_getfile();
6581: my %to_remember;
6582: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6583: if ($scanlines->{'skipped'}[$i]) {
6584: $to_remember{$i}=1;
6585: }
6586: }
6587:
6588: &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
6589: &scantron_putfile(undef,$scan_data);
6590: }
6591:
6592: =pod
6593:
6594: =item check_for_error
6595:
6596: Checks if there was an error when attempting to remove a specific
6597: scantron_.. bubblesheet data file. Prints out an error if
6598: something went wrong.
6599:
6600: =cut
6601:
6602: sub check_for_error {
6603: my ($r,$result)=@_;
6604: if ($result ne 'ok' && $result ne 'not_found' ) {
6605: $r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
6606: }
6607: }
6608:
6609: =pod
6610:
6611: =item scantron_warning_screen
6612:
6613: Interstitial screen to make sure the operator has selected the
6614: correct options before we start the validation phase.
6615:
6616: =cut
6617:
6618: sub scantron_warning_screen {
6619: my ($button_text,$symb)=@_;
6620: my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
6621: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6622: my $CODElist;
6623: if ($scantron_config{'CODElocation'} &&
6624: $scantron_config{'CODEstart'} &&
6625: $scantron_config{'CODElength'}) {
6626: $CODElist=$env{'form.scantron_CODElist'};
6627: if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
6628: $CODElist=
6629: '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
6630: $env{'form.scantron_CODElist'}.'</tt></td></tr>';
6631: }
6632: my $lastbubblepoints;
6633: if ($env{'form.scantron_lastbubblepoints'} ne '') {
6634: $lastbubblepoints =
6635: '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
6636: $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
6637: }
6638: return ('
6639: <p>
6640: <span class="LC_warning">
6641: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
6642: </p>
6643: <table>
6644: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
6645: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
6646: '.$CODElist.$lastbubblepoints.'
6647: </table>
6648: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
6649: '.&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>
6650:
6651: <br />
6652: ');
6653: }
6654:
6655: =pod
6656:
6657: =item scantron_do_warning
6658:
6659: Check if the operator has picked something for all required
6660: fields. Error out if something is missing.
6661:
6662: =cut
6663:
6664: sub scantron_do_warning {
6665: my ($r,$symb)=@_;
6666: if (!$symb) {return '';}
6667: my $default_form_data=&defaultFormData($symb);
6668: $r->print(&scantron_form_start().$default_form_data);
6669: if ( $env{'form.selectpage'} eq '' ||
6670: $env{'form.scantron_selectfile'} eq '' ||
6671: $env{'form.scantron_format'} eq '' ) {
6672: $r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
6673: if ( $env{'form.selectpage'} eq '') {
6674: $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
6675: }
6676: if ( $env{'form.scantron_selectfile'} eq '') {
6677: $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
6678: }
6679: if ( $env{'form.scantron_format'} eq '') {
6680: $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
6681: }
6682: } else {
6683: my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
6684: my $bubbledbyhand=&hand_bubble_option();
6685: $r->print('
6686: '.$warning.$bubbledbyhand.'
6687: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
6688: <input type="hidden" name="command" value="scantron_validate" />
6689: ');
6690: }
6691: $r->print("</form><br />");
6692: return '';
6693: }
6694:
6695: =pod
6696:
6697: =item scantron_form_start
6698:
6699: html hidden input for remembering all selected grading options
6700:
6701: =cut
6702:
6703: sub scantron_form_start {
6704: my ($max_bubble)=@_;
6705: my $result= <<SCANTRONFORM;
6706: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
6707: <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
6708: <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
6709: <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
6710: <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
6711: <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
6712: <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
6713: <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
6714: <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
6715: <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
6716: SCANTRONFORM
6717:
6718: my $line = 0;
6719: while (defined($env{"form.scantron.bubblelines.$line"})) {
6720: my $chunk =
6721: '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
6722: $chunk .=
6723: '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
6724: $chunk .=
6725: '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
6726: $chunk .=
6727: '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
6728: $chunk .=
6729: '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
6730: $result .= $chunk;
6731: $line++;
6732: }
6733: return $result;
6734: }
6735:
6736: =pod
6737:
6738: =item scantron_validate_file
6739:
6740: Dispatch routine for doing validation of a bubblesheet data file.
6741:
6742: Also processes any necessary information resets that need to
6743: occur before validation begins (ignore previous corrections,
6744: restarting the skipped records processing)
6745:
6746: =cut
6747:
6748: sub scantron_validate_file {
6749: my ($r,$symb) = @_;
6750: if (!$symb) {return '';}
6751: my $default_form_data=&defaultFormData($symb);
6752:
6753: # do the detection of only doing skipped records first before we delete
6754: # them when doing the corrections reset
6755: if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
6756: &reset_skipping_status();
6757: }
6758: if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
6759: &remember_current_skipped();
6760: $env{'form.scantron_options_redo'}='redo_skipped_ready';
6761: }
6762:
6763: if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
6764: &check_for_error($r,&scantron_remove_file('corrected'));
6765: &check_for_error($r,&scantron_remove_file('skipped'));
6766: &check_for_error($r,&scantron_remove_scan_data());
6767: $env{'form.scantron_options_ignore'}='done';
6768: }
6769:
6770: if ($env{'form.scantron_corrections'}) {
6771: &scantron_process_corrections($r);
6772: }
6773: $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
6774: #get the student pick code ready
6775: $r->print(&Apache::loncommon::studentbrowser_javascript());
6776: my $nav_error;
6777: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6778: my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
6779: if ($nav_error) {
6780: $r->print(&navmap_errormsg());
6781: return '';
6782: }
6783: my $result=&scantron_form_start($max_bubble).$default_form_data;
6784: if ($env{'form.scantron_lastbubblepoints'} ne '') {
6785: $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
6786: }
6787: $r->print($result);
6788:
6789: my @validate_phases=( 'sequence',
6790: 'ID',
6791: 'CODE',
6792: 'doublebubble',
6793: 'missingbubbles');
6794: if (!$env{'form.validatepass'}) {
6795: $env{'form.validatepass'} = 0;
6796: }
6797: my $currentphase=$env{'form.validatepass'};
6798:
6799:
6800: my $stop=0;
6801: while (!$stop && $currentphase < scalar(@validate_phases)) {
6802: $r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
6803: $r->rflush();
6804:
6805: my $which="scantron_validate_".$validate_phases[$currentphase];
6806: {
6807: no strict 'refs';
6808: ($stop,$currentphase)=&$which($r,$currentphase);
6809: }
6810: }
6811: if (!$stop) {
6812: my $warning=&scantron_warning_screen('Start Grading',$symb);
6813: $r->print(&mt('Validation process complete.').'<br />'.
6814: $warning.
6815: &mt('Perform verification for each student after storage of submissions?').
6816: ' <span class="LC_nobreak"><label>'.
6817: '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
6818: (' 'x3).'<label>'.
6819: '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
6820: '</label></span><br />'.
6821: &mt('Grading will take longer if you use verification.').'<br />'.
6822: &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','»').'<br /><br />'.
6823: '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
6824: '<input type="hidden" name="command" value="scantron_process" />'."\n");
6825: } else {
6826: $r->print('<input type="hidden" name="command" value="scantron_validate" />');
6827: $r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
6828: }
6829: if ($stop) {
6830: if ($validate_phases[$currentphase] eq 'sequence') {
6831: $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' → " />');
6832: $r->print(' '.&mt('this error').' <br />');
6833:
6834: $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>');
6835: } else {
6836: if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
6837: $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' →" onclick="javascript:verify_bubble_radio(this.form)" />');
6838: } else {
6839: $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' →" />');
6840: }
6841: $r->print(' '.&mt('using corrected info').' <br />');
6842: $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
6843: $r->print(" ".&mt("this scanline saving it for later."));
6844: }
6845: }
6846: $r->print(" </form><br />");
6847: return '';
6848: }
6849:
6850:
6851: =pod
6852:
6853: =item scantron_remove_file
6854:
6855: Removes the requested bubblesheet data file, makes sure that
6856: scantron_original_<filename> is never removed
6857:
6858:
6859: =cut
6860:
6861: sub scantron_remove_file {
6862: my ($which)=@_;
6863: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6864: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6865: my $file='scantron_';
6866: if ($which eq 'corrected' || $which eq 'skipped') {
6867: $file.=$which.'_';
6868: } else {
6869: return 'refused';
6870: }
6871: $file.=$env{'form.scantron_selectfile'};
6872: return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
6873: }
6874:
6875:
6876: =pod
6877:
6878: =item scantron_remove_scan_data
6879:
6880: Removes all scan_data correction for the requested bubblesheet
6881: data file. (In the case that both the are doing skipped records we need
6882: to remember the old skipped lines for the time being so that element
6883: persists for a while.)
6884:
6885: =cut
6886:
6887: sub scantron_remove_scan_data {
6888: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6889: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6890: my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
6891: my @todelete;
6892: my $filename=$env{'form.scantron_selectfile'};
6893: foreach my $key (@keys) {
6894: if ($key=~/^\Q$filename\E_/) {
6895: if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
6896: $key=~/remember_skipping/) {
6897: next;
6898: }
6899: push(@todelete,$key);
6900: }
6901: }
6902: my $result;
6903: if (@todelete) {
6904: $result = &Apache::lonnet::del('nohist_scantrondata',
6905: \@todelete,$cdom,$cname);
6906: } else {
6907: $result = 'ok';
6908: }
6909: return $result;
6910: }
6911:
6912:
6913: =pod
6914:
6915: =item scantron_getfile
6916:
6917: Fetches the requested bubblesheet data file (all 3 versions), and
6918: the scan_data hash
6919:
6920: Arguments:
6921: None
6922:
6923: Returns:
6924: 2 hash references
6925:
6926: - first one has
6927: orig -
6928: corrected -
6929: skipped - each of which points to an array ref of the specified
6930: file broken up into individual lines
6931: count - number of scanlines
6932:
6933: - second is the scan_data hash possible keys are
6934: ($number refers to scanline numbered $number and thus the key affects
6935: only that scanline
6936: $bubline refers to the specific bubble line element and the aspects
6937: refers to that specific bubble line element)
6938:
6939: $number.user - username:domain to use
6940: $number.CODE_ignore_dup
6941: - ignore the duplicate CODE error
6942: $number.useCODE
6943: - use the CODE in the scanline as is
6944: $number.no_bubble.$bubline
6945: - it is valid that there is no bubbled in bubble
6946: at $number $bubline
6947: remember_skipping
6948: - a frozen hash containing keys of $number and values
6949: of either
6950: 1 - we are on a 'do skipped records pass' and plan
6951: on processing this line
6952: 2 - we are on a 'do skipped records pass' and this
6953: scanline has been marked to skip yet again
6954:
6955: =cut
6956:
6957: sub scantron_getfile {
6958: #FIXME really would prefer a scantron directory
6959: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6960: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6961: my $lines;
6962: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
6963: 'scantron_orig_'.$env{'form.scantron_selectfile'});
6964: my %scanlines;
6965: $scanlines{'orig'}=[(split("\n",$lines,-1))];
6966: my $temp=$scanlines{'orig'};
6967: $scanlines{'count'}=$#$temp;
6968:
6969: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
6970: 'scantron_corrected_'.$env{'form.scantron_selectfile'});
6971: if ($lines eq '-1') {
6972: $scanlines{'corrected'}=[];
6973: } else {
6974: $scanlines{'corrected'}=[(split("\n",$lines,-1))];
6975: }
6976: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
6977: 'scantron_skipped_'.$env{'form.scantron_selectfile'});
6978: if ($lines eq '-1') {
6979: $scanlines{'skipped'}=[];
6980: } else {
6981: $scanlines{'skipped'}=[(split("\n",$lines,-1))];
6982: }
6983: my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
6984: if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
6985: my %scan_data = @tmp;
6986: return (\%scanlines,\%scan_data);
6987: }
6988:
6989: =pod
6990:
6991: =item lonnet_putfile
6992:
6993: Wrapper routine to call &Apache::lonnet::finishuserfileupload
6994:
6995: Arguments:
6996: $contents - data to store
6997: $filename - filename to store $contents into
6998:
6999: Returns:
7000: result value from &Apache::lonnet::finishuserfileupload
7001:
7002: =cut
7003:
7004: sub lonnet_putfile {
7005: my ($contents,$filename)=@_;
7006: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
7007: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7008: $env{'form.sillywaytopassafilearound'}=$contents;
7009: &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
7010:
7011: }
7012:
7013: =pod
7014:
7015: =item scantron_putfile
7016:
7017: Stores the current version of the bubblesheet data files, and the
7018: scan_data hash. (Does not modify the original version only the
7019: corrected and skipped versions.
7020:
7021: Arguments:
7022: $scanlines - hash ref that looks like the first return value from
7023: &scantron_getfile()
7024: $scan_data - hash ref that looks like the second return value from
7025: &scantron_getfile()
7026:
7027: =cut
7028:
7029: sub scantron_putfile {
7030: my ($scanlines,$scan_data) = @_;
7031: #FIXME really would prefer a scantron directory
7032: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7033: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7034: if ($scanlines) {
7035: my $prefix='scantron_';
7036: # no need to update orig, shouldn't change
7037: # &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
7038: # $env{'form.scantron_selectfile'});
7039: &lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
7040: $prefix.'corrected_'.
7041: $env{'form.scantron_selectfile'});
7042: &lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
7043: $prefix.'skipped_'.
7044: $env{'form.scantron_selectfile'});
7045: }
7046: &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
7047: }
7048:
7049: =pod
7050:
7051: =item scantron_get_line
7052:
7053: Returns the correct version of the scanline
7054:
7055: Arguments:
7056: $scanlines - hash ref that looks like the first return value from
7057: &scantron_getfile()
7058: $scan_data - hash ref that looks like the second return value from
7059: &scantron_getfile()
7060: $i - number of the requested line (starts at 0)
7061:
7062: Returns:
7063: A scanline, (either the original or the corrected one if it
7064: exists), or undef if the requested scanline should be
7065: skipped. (Either because it's an skipped scanline, or it's an
7066: unskipped scanline and we are not doing a 'do skipped scanlines'
7067: pass.
7068:
7069: =cut
7070:
7071: sub scantron_get_line {
7072: my ($scanlines,$scan_data,$i)=@_;
7073: if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
7074: #if ($scanlines->{'skipped'}[$i]) { return undef; }
7075: if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
7076: return $scanlines->{'orig'}[$i];
7077: }
7078:
7079: =pod
7080:
7081: =item scantron_todo_count
7082:
7083: Counts the number of scanlines that need processing.
7084:
7085: Arguments:
7086: $scanlines - hash ref that looks like the first return value from
7087: &scantron_getfile()
7088: $scan_data - hash ref that looks like the second return value from
7089: &scantron_getfile()
7090:
7091: Returns:
7092: $count - number of scanlines to process
7093:
7094: =cut
7095:
7096: sub get_todo_count {
7097: my ($scanlines,$scan_data)=@_;
7098: my $count=0;
7099: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7100: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7101: if ($line=~/^[\s\cz]*$/) { next; }
7102: $count++;
7103: }
7104: return $count;
7105: }
7106:
7107: =pod
7108:
7109: =item scantron_put_line
7110:
7111: Updates the 'corrected' or 'skipped' versions of the bubblesheet
7112: data file.
7113:
7114: Arguments:
7115: $scanlines - hash ref that looks like the first return value from
7116: &scantron_getfile()
7117: $scan_data - hash ref that looks like the second return value from
7118: &scantron_getfile()
7119: $i - line number to update
7120: $newline - contents of the updated scanline
7121: $skip - if true make the line for skipping and update the
7122: 'skipped' file
7123:
7124: =cut
7125:
7126: sub scantron_put_line {
7127: my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
7128: if ($skip) {
7129: $scanlines->{'skipped'}[$i]=$newline;
7130: &start_skipping($scan_data,$i);
7131: return;
7132: }
7133: $scanlines->{'corrected'}[$i]=$newline;
7134: }
7135:
7136: =pod
7137:
7138: =item scantron_clear_skip
7139:
7140: Remove a line from the 'skipped' file
7141:
7142: Arguments:
7143: $scanlines - hash ref that looks like the first return value from
7144: &scantron_getfile()
7145: $scan_data - hash ref that looks like the second return value from
7146: &scantron_getfile()
7147: $i - line number to update
7148:
7149: =cut
7150:
7151: sub scantron_clear_skip {
7152: my ($scanlines,$scan_data,$i)=@_;
7153: if (exists($scanlines->{'skipped'}[$i])) {
7154: undef($scanlines->{'skipped'}[$i]);
7155: return 1;
7156: }
7157: return 0;
7158: }
7159:
7160: =pod
7161:
7162: =item scantron_filter_not_exam
7163:
7164: Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
7165: filter out resources that are not marked as 'exam' mode
7166:
7167: =cut
7168:
7169: sub scantron_filter_not_exam {
7170: my ($curres)=@_;
7171:
7172: if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
7173: # if the user has asked to not have either hidden
7174: # or 'randomout' controlled resources to be graded
7175: # don't include them
7176: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
7177: && $curres->randomout) {
7178: return 0;
7179: }
7180: return 1;
7181: }
7182: return 0;
7183: }
7184:
7185: =pod
7186:
7187: =item scantron_validate_sequence
7188:
7189: Validates the selected sequence, checking for resource that are
7190: not set to exam mode.
7191:
7192: =cut
7193:
7194: sub scantron_validate_sequence {
7195: my ($r,$currentphase) = @_;
7196:
7197: my $navmap=Apache::lonnavmaps::navmap->new();
7198: unless (ref($navmap)) {
7199: $r->print(&navmap_errormsg());
7200: return (1,$currentphase);
7201: }
7202: my (undef,undef,$sequence)=
7203: &Apache::lonnet::decode_symb($env{'form.selectpage'});
7204:
7205: my $map=$navmap->getResourceByUrl($sequence);
7206:
7207: $r->print('<input type="hidden" name="validate_sequence_exam"
7208: value="ignore" />');
7209: if ($env{'form.validate_sequence_exam'} ne 'ignore') {
7210: my @resources=
7211: $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
7212: if (@resources) {
7213: $r->print(
7214: '<p class="LC_warning">'
7215: .&mt('Some resources in the sequence currently are not set to'
7216: .' bubblesheet exam mode. Grading these resources currently may not'
7217: .' work correctly.')
7218: .'</p>'
7219: );
7220: return (1,$currentphase);
7221: }
7222: }
7223:
7224: return (0,$currentphase+1);
7225: }
7226:
7227:
7228:
7229: sub scantron_validate_ID {
7230: my ($r,$currentphase) = @_;
7231:
7232: #get student info
7233: my $classlist=&Apache::loncoursedata::get_classlist();
7234: my %idmap=&username_to_idmap($classlist);
7235:
7236: #get scantron line setup
7237: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7238: my ($scanlines,$scan_data)=&scantron_getfile();
7239:
7240: my $nav_error;
7241: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
7242: if ($nav_error) {
7243: $r->print(&navmap_errormsg());
7244: return(1,$currentphase);
7245: }
7246:
7247: my %found=('ids'=>{},'usernames'=>{});
7248: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7249: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7250: if ($line=~/^[\s\cz]*$/) { next; }
7251: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7252: $scan_data);
7253: my $id=$$scan_record{'scantron.ID'};
7254: my $found;
7255: foreach my $checkid (keys(%idmap)) {
7256: if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
7257: }
7258: if ($found) {
7259: my $username=$idmap{$found};
7260: if ($found{'ids'}{$found}) {
7261: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
7262: $line,'duplicateID',$found);
7263: return(1,$currentphase);
7264: } elsif ($found{'usernames'}{$username}) {
7265: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
7266: $line,'duplicateID',$username);
7267: return(1,$currentphase);
7268: }
7269: #FIXME store away line we previously saw the ID on to use above
7270: $found{'ids'}{$found}++;
7271: $found{'usernames'}{$username}++;
7272: } else {
7273: if ($id =~ /^\s*$/) {
7274: my $username=&scan_data($scan_data,"$i.user");
7275: if (defined($username) && $found{'usernames'}{$username}) {
7276: &scantron_get_correction($r,$i,$scan_record,
7277: \%scantron_config,
7278: $line,'duplicateID',$username);
7279: return(1,$currentphase);
7280: } elsif (!defined($username)) {
7281: &scantron_get_correction($r,$i,$scan_record,
7282: \%scantron_config,
7283: $line,'incorrectID');
7284: return(1,$currentphase);
7285: }
7286: $found{'usernames'}{$username}++;
7287: } else {
7288: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
7289: $line,'incorrectID');
7290: return(1,$currentphase);
7291: }
7292: }
7293: }
7294:
7295: return (0,$currentphase+1);
7296: }
7297:
7298:
7299: sub scantron_get_correction {
7300: my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
7301: $randomorder,$randompick,$respnumlookup,$startline)=@_;
7302: #FIXME in the case of a duplicated ID the previous line, probably need
7303: #to show both the current line and the previous one and allow skipping
7304: #the previous one or the current one
7305:
7306: if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
7307: $r->print(
7308: '<p class="LC_warning">'
7309: .&mt('An error was detected ([_1]) for PaperID [_2]',
7310: "<b>$error</b>",
7311: '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
7312: ."</p> \n");
7313: } else {
7314: $r->print(
7315: '<p class="LC_warning">'
7316: .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
7317: "<b>$error</b>", $i, "<pre>$line</pre>")
7318: ."</p> \n");
7319: }
7320: my $message =
7321: '<p>'
7322: .&mt('The ID on the form is [_1]',
7323: "<tt>$$scan_record{'scantron.ID'}</tt>")
7324: .'<br />'
7325: .&mt('The name on the paper is [_1], [_2]',
7326: $$scan_record{'scantron.LastName'},
7327: $$scan_record{'scantron.FirstName'})
7328: .'</p>';
7329:
7330: $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
7331: $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
7332: # Array populated for doublebubble or
7333: my @lines_to_correct; # missingbubble errors to build javascript
7334: # to validate radio button checking
7335:
7336: if ($error =~ /ID$/) {
7337: if ($error eq 'incorrectID') {
7338: $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
7339: "</p>\n");
7340: } elsif ($error eq 'duplicateID') {
7341: $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
7342: }
7343: $r->print($message);
7344: $r->print("<p>".&mt("How should I handle this?")." <br /> \n");
7345: $r->print("\n<ul><li> ");
7346: #FIXME it would be nice if this sent back the user ID and
7347: #could do partial userID matches
7348: $r->print(&Apache::loncommon::selectstudent_link('scantronupload',
7349: 'scantron_username','scantron_domain'));
7350: $r->print(": <input type='text' name='scantron_username' value='' />");
7351: $r->print("\n:\n".
7352: &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
7353:
7354: $r->print('</li>');
7355: } elsif ($error =~ /CODE$/) {
7356: if ($error eq 'incorrectCODE') {
7357: $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
7358: } elsif ($error eq 'duplicateCODE') {
7359: $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");
7360: }
7361: $r->print("<p>".&mt('The CODE on the form is [_1]',
7362: "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
7363: ."</p>\n");
7364: $r->print($message);
7365: $r->print("<p>".&mt("How should I handle this?")."</p>\n");
7366: $r->print("\n<br /> ");
7367: my $i=0;
7368: if ($error eq 'incorrectCODE'
7369: && $$scan_record{'scantron.CODE'}=~/\S/ ) {
7370: my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
7371: if ($closest > 0) {
7372: foreach my $testcode (@{$closest}) {
7373: my $checked='';
7374: if (!$i) { $checked=' checked="checked"'; }
7375: $r->print("
7376: <label>
7377: <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
7378: ".&mt("Use the similar CODE [_1] instead.",
7379: "<b><tt>".$testcode."</tt></b>")."
7380: </label>
7381: <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
7382: $r->print("\n<br />");
7383: $i++;
7384: }
7385: }
7386: }
7387: if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
7388: my $checked; if (!$i) { $checked=' checked="checked"'; }
7389: $r->print("
7390: <label>
7391: <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
7392: ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
7393: "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
7394: </label>");
7395: $r->print("\n<br />");
7396: }
7397:
7398: $r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
7399: function change_radio(field) {
7400: var slct=document.scantronupload.scantron_CODE_resolution;
7401: var i;
7402: for (i=0;i<slct.length;i++) {
7403: if (slct[i].value==field) { slct[i].checked=true; }
7404: }
7405: }
7406: ENDSCRIPT
7407: my $href="/adm/pickcode?".
7408: "form=".&escape("scantronupload").
7409: "&scantron_format=".&escape($env{'form.scantron_format'}).
7410: "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
7411: "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
7412: "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
7413: if ($env{'form.scantron_CODElist'} =~ /\S/) {
7414: $r->print("
7415: <label>
7416: <input type='radio' name='scantron_CODE_resolution' value='use_found' />
7417: ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
7418: "<a target='_blank' href='$href'>","</a>")."
7419: </label>
7420: ".&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\')" />'));
7421: $r->print("\n<br />");
7422: }
7423: $r->print("
7424: <label>
7425: <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
7426: ".&mt("Use [_1] as the CODE.",
7427: "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
7428: $r->print("\n<br /><br />");
7429: } elsif ($error eq 'doublebubble') {
7430: $r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
7431:
7432: # The form field scantron_questions is acutally a list of line numbers.
7433: # represented by this form so:
7434:
7435: my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
7436: $respnumlookup,$startline);
7437:
7438: $r->print('<input type="hidden" name="scantron_questions" value="'.
7439: $line_list.'" />');
7440: $r->print($message);
7441: $r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
7442: foreach my $question (@{$arg}) {
7443: my @linenums = &prompt_for_corrections($r,$question,$scan_config,
7444: $scan_record, $error,
7445: $randomorder,$randompick,
7446: $respnumlookup,$startline);
7447: push(@lines_to_correct,@linenums);
7448: }
7449: $r->print(&verify_bubbles_checked(@lines_to_correct));
7450: } elsif ($error eq 'missingbubble') {
7451: $r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
7452: $r->print($message);
7453: $r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
7454: $r->print(&mt("Some questions have no scanned bubbles.")."\n");
7455:
7456: # The form field scantron_questions is actually a list of line numbers not
7457: # a list of question numbers. Therefore:
7458: #
7459:
7460: my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
7461: $respnumlookup,$startline);
7462:
7463: $r->print('<input type="hidden" name="scantron_questions" value="'.
7464: $line_list.'" />');
7465: foreach my $question (@{$arg}) {
7466: my @linenums = &prompt_for_corrections($r,$question,$scan_config,
7467: $scan_record, $error,
7468: $randomorder,$randompick,
7469: $respnumlookup,$startline);
7470: push(@lines_to_correct,@linenums);
7471: }
7472: $r->print(&verify_bubbles_checked(@lines_to_correct));
7473: } else {
7474: $r->print("\n<ul>");
7475: }
7476: $r->print("\n</li></ul>");
7477: }
7478:
7479: sub verify_bubbles_checked {
7480: my (@ansnums) = @_;
7481: my $ansnumstr = join('","',@ansnums);
7482: my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
7483: my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
7484: function verify_bubble_radio(form) {
7485: var ansnumArray = new Array ("$ansnumstr");
7486: var need_bubble_count = 0;
7487: for (var i=0; i<ansnumArray.length; i++) {
7488: if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
7489: var bubble_picked = 0;
7490: for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
7491: if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
7492: bubble_picked = 1;
7493: }
7494: }
7495: if (bubble_picked == 0) {
7496: need_bubble_count ++;
7497: }
7498: }
7499: }
7500: if (need_bubble_count) {
7501: alert("$warning");
7502: return;
7503: }
7504: form.submit();
7505: }
7506: ENDSCRIPT
7507: return $output;
7508: }
7509:
7510: =pod
7511:
7512: =item questions_to_line_list
7513:
7514: Converts a list of questions into a string of comma separated
7515: line numbers in the answer sheet used by the questions. This is
7516: used to fill in the scantron_questions form field.
7517:
7518: Arguments:
7519: questions - Reference to an array of questions.
7520: randomorder - True if randomorder in use.
7521: randompick - True if randompick in use.
7522: respnumlookup - Reference to HASH mapping question numbers in bubble lines
7523: for current line to question number used for same question
7524: in "Master Seqence" (as seen by Course Coordinator).
7525: startline - Reference to hash where key is question number (0 is first)
7526: and key is number of first bubble line for current student
7527: or code-based randompick and/or randomorder.
7528:
7529: =cut
7530:
7531:
7532: sub questions_to_line_list {
7533: my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
7534: my @lines;
7535:
7536: foreach my $item (@{$questions}) {
7537: my $question = $item;
7538: my ($first,$count,$last);
7539: if ($item =~ /^(\d+)\.(\d+)$/) {
7540: $question = $1;
7541: my $subquestion = $2;
7542: my $responsenum = $question-1;
7543: if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
7544: $responsenum = $respnumlookup->{$question-1};
7545: if (ref($startline) eq 'HASH') {
7546: $first = $startline->{$question-1} + 1;
7547: }
7548: } else {
7549: $first = $first_bubble_line{$responsenum} + 1;
7550: }
7551: my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
7552: my $subcount = 1;
7553: while ($subcount<$subquestion) {
7554: $first += $subans[$subcount-1];
7555: $subcount ++;
7556: }
7557: $count = $subans[$subquestion-1];
7558: } else {
7559: my $responsenum = $question-1;
7560: if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
7561: $responsenum = $respnumlookup->{$question-1};
7562: if (ref($startline) eq 'HASH') {
7563: $first = $startline->{$question-1} + 1;
7564: }
7565: } else {
7566: $first = $first_bubble_line{$responsenum} + 1;
7567: }
7568: $count = $bubble_lines_per_response{$responsenum};
7569: }
7570: $last = $first+$count-1;
7571: push(@lines, ($first..$last));
7572: }
7573: return join(',', @lines);
7574: }
7575:
7576: =pod
7577:
7578: =item prompt_for_corrections
7579:
7580: Prompts for a potentially multiline correction to the
7581: user's bubbling (factors out common code from scantron_get_correction
7582: for multi and missing bubble cases).
7583:
7584: Arguments:
7585: $r - Apache request object.
7586: $question - The question number to prompt for.
7587: $scan_config - The scantron file configuration hash.
7588: $scan_record - Reference to the hash that has the the parsed scanlines.
7589: $error - Type of error
7590: $randomorder - True if randomorder in use.
7591: $randompick - True if randompick in use.
7592: $respnumlookup - Reference to HASH mapping question numbers in bubble lines
7593: for current line to question number used for same question
7594: in "Master Seqence" (as seen by Course Coordinator).
7595: $startline - Reference to hash where key is question number (0 is first)
7596: and value is number of first bubble line for current student
7597: or code-based randompick and/or randomorder.
7598:
7599:
7600: Implicit inputs:
7601: %bubble_lines_per_response - Starting line numbers for each question.
7602: Numbered from 0 (but question numbers are from
7603: 1.
7604: %first_bubble_line - Starting bubble line for each question.
7605: %subdivided_bubble_lines - optionresponse, matchresponse and rankresponse
7606: type problems render as separate sub-questions,
7607: in exam mode. This hash contains a
7608: comma-separated list of the lines per
7609: sub-question.
7610: %responsetype_per_response - essayresponse, formularesponse,
7611: stringresponse, imageresponse, reactionresponse,
7612: and organicresponse type problem parts can have
7613: multiple lines per response if the weight
7614: assigned exceeds 10. In this case, only
7615: one bubble per line is permitted, but more
7616: than one line might contain bubbles, e.g.
7617: bubbling of: line 1 - J, line 2 - J,
7618: line 3 - B would assign 22 points.
7619:
7620: =cut
7621:
7622: sub prompt_for_corrections {
7623: my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
7624: $randompick, $respnumlookup, $startline) = @_;
7625: my ($current_line,$lines);
7626: my @linenums;
7627: my $questionnum = $question;
7628: my ($first,$responsenum);
7629: if ($question =~ /^(\d+)\.(\d+)$/) {
7630: $question = $1;
7631: my $subquestion = $2;
7632: if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
7633: $responsenum = $respnumlookup->{$question-1};
7634: if (ref($startline) eq 'HASH') {
7635: $first = $startline->{$question-1};
7636: }
7637: } else {
7638: $responsenum = $question-1;
7639: $first = $first_bubble_line{$responsenum};
7640: }
7641: $current_line = $first + 1 ;
7642: my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
7643: my $subcount = 1;
7644: while ($subcount<$subquestion) {
7645: $current_line += $subans[$subcount-1];
7646: $subcount ++;
7647: }
7648: $lines = $subans[$subquestion-1];
7649: } else {
7650: if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
7651: $responsenum = $respnumlookup->{$question-1};
7652: if (ref($startline) eq 'HASH') {
7653: $first = $startline->{$question-1};
7654: }
7655: } else {
7656: $responsenum = $question-1;
7657: $first = $first_bubble_line{$responsenum};
7658: }
7659: $current_line = $first + 1;
7660: $lines = $bubble_lines_per_response{$responsenum};
7661: }
7662: if ($lines > 1) {
7663: $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
7664: if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
7665: ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
7666: ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
7667: ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
7668: ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
7669: ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
7670: $r->print(
7671: &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)
7672: .'<br /><br />'
7673: .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
7674: .'<br />'
7675: .&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.')
7676: .'<br />'
7677: .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
7678: .'<br /><br />'
7679: );
7680: } else {
7681: $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
7682: }
7683: }
7684: for (my $i =0; $i < $lines; $i++) {
7685: my $selected = $$scan_record{"scantron.$current_line.answer"};
7686: &scantron_bubble_selector($r,$scan_config,$current_line,
7687: $questionnum,$error,split('', $selected));
7688: push(@linenums,$current_line);
7689: $current_line++;
7690: }
7691: if ($lines > 1) {
7692: $r->print("<hr /><br />");
7693: }
7694: return @linenums;
7695: }
7696:
7697: =pod
7698:
7699: =item scantron_bubble_selector
7700:
7701: Generates the html radiobuttons to correct a single bubble line
7702: possibly showing the existing the selected bubbles if known
7703:
7704: Arguments:
7705: $r - Apache request object
7706: $scan_config - hash from &get_scantron_config()
7707: $line - Number of the line being displayed.
7708: $questionnum - Question number (may include subquestion)
7709: $error - Type of error.
7710: @selected - Array of bubbles picked on this line.
7711:
7712: =cut
7713:
7714: sub scantron_bubble_selector {
7715: my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
7716: my $max=$$scan_config{'Qlength'};
7717:
7718: my $scmode=$$scan_config{'Qon'};
7719: if ($scmode eq 'number' || $scmode eq 'letter') {
7720: if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
7721: ($$scan_config{'BubblesPerRow'} > 0)) {
7722: $max=$$scan_config{'BubblesPerRow'};
7723: if (($scmode eq 'number') && ($max > 10)) {
7724: $max = 10;
7725: } elsif (($scmode eq 'letter') && $max > 26) {
7726: $max = 26;
7727: }
7728: } else {
7729: $max = 10;
7730: }
7731: }
7732:
7733: my @alphabet=('A'..'Z');
7734: $r->print(&Apache::loncommon::start_data_table().
7735: &Apache::loncommon::start_data_table_row());
7736: $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
7737: for (my $i=0;$i<$max+1;$i++) {
7738: $r->print("\n".'<td align="center">');
7739: if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
7740: else { $r->print(' '); }
7741: $r->print('</td>');
7742: }
7743: $r->print(&Apache::loncommon::end_data_table_row().
7744: &Apache::loncommon::start_data_table_row());
7745: for (my $i=0;$i<$max;$i++) {
7746: $r->print("\n".
7747: '<td><label><input type="radio" name="scantron_correct_Q_'.
7748: $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
7749: }
7750: my $nobub_checked = ' ';
7751: if ($error eq 'missingbubble') {
7752: $nobub_checked = ' checked = "checked" ';
7753: }
7754: $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
7755: $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
7756: '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
7757: $line.'" value="'.$questionnum.'" /></td>');
7758: $r->print(&Apache::loncommon::end_data_table_row().
7759: &Apache::loncommon::end_data_table());
7760: }
7761:
7762: =pod
7763:
7764: =item num_matches
7765:
7766: Counts the number of characters that are the same between the two arguments.
7767:
7768: Arguments:
7769: $orig - CODE from the scanline
7770: $code - CODE to match against
7771:
7772: Returns:
7773: $count - integer count of the number of same characters between the
7774: two arguments
7775:
7776: =cut
7777:
7778: sub num_matches {
7779: my ($orig,$code) = @_;
7780: my @code=split(//,$code);
7781: my @orig=split(//,$orig);
7782: my $same=0;
7783: for (my $i=0;$i<scalar(@code);$i++) {
7784: if ($code[$i] eq $orig[$i]) { $same++; }
7785: }
7786: return $same;
7787: }
7788:
7789: =pod
7790:
7791: =item scantron_get_closely_matching_CODEs
7792:
7793: Cycles through all CODEs and finds the set that has the greatest
7794: number of same characters as the provided CODE
7795:
7796: Arguments:
7797: $allcodes - hash ref returned by &get_codes()
7798: $CODE - CODE from the current scanline
7799:
7800: Returns:
7801: 2 element list
7802: - first elements is number of how closely matching the best fit is
7803: (5 means best set has 5 matching characters)
7804: - second element is an arrary ref containing the set of valid CODEs
7805: that best fit the passed in CODE
7806:
7807: =cut
7808:
7809: sub scantron_get_closely_matching_CODEs {
7810: my ($allcodes,$CODE)=@_;
7811: my @CODEs;
7812: foreach my $testcode (sort(keys(%{$allcodes}))) {
7813: push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
7814: }
7815:
7816: return ($#CODEs,$CODEs[-1]);
7817: }
7818:
7819: =pod
7820:
7821: =item get_codes
7822:
7823: Builds a hash which has keys of all of the valid CODEs from the selected
7824: set of remembered CODEs.
7825:
7826: Arguments:
7827: $old_name - name of the set of remembered CODEs
7828: $cdom - domain of the course
7829: $cnum - internal course name
7830:
7831: Returns:
7832: %allcodes - keys are the valid CODEs, values are all 1
7833:
7834: =cut
7835:
7836: sub get_codes {
7837: my ($old_name, $cdom, $cnum) = @_;
7838: if (!$old_name) {
7839: $old_name=$env{'form.scantron_CODElist'};
7840: }
7841: if (!$cdom) {
7842: $cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
7843: }
7844: if (!$cnum) {
7845: $cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
7846: }
7847: my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
7848: $cdom,$cnum);
7849: my %allcodes;
7850: if ($result{"type\0$old_name"} eq 'number') {
7851: %allcodes=map {($_,1)} split(',',$result{$old_name});
7852: } else {
7853: %allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
7854: }
7855: return %allcodes;
7856: }
7857:
7858: =pod
7859:
7860: =item scantron_validate_CODE
7861:
7862: Validates all scanlines in the selected file to not have any
7863: invalid or underspecified CODEs and that none of the codes are
7864: duplicated if this was requested.
7865:
7866: =cut
7867:
7868: sub scantron_validate_CODE {
7869: my ($r,$currentphase) = @_;
7870: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7871: if ($scantron_config{'CODElocation'} &&
7872: $scantron_config{'CODEstart'} &&
7873: $scantron_config{'CODElength'}) {
7874: if (!defined($env{'form.scantron_CODElist'})) {
7875: &FIXME_blow_up()
7876: }
7877: } else {
7878: return (0,$currentphase+1);
7879: }
7880:
7881: my %usedCODEs;
7882:
7883: my %allcodes=&get_codes();
7884:
7885: my $nav_error;
7886: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
7887: if ($nav_error) {
7888: $r->print(&navmap_errormsg());
7889: return(1,$currentphase);
7890: }
7891:
7892: my ($scanlines,$scan_data)=&scantron_getfile();
7893: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7894: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7895: if ($line=~/^[\s\cz]*$/) { next; }
7896: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7897: $scan_data);
7898: my $CODE=$$scan_record{'scantron.CODE'};
7899: my $error=0;
7900: if (!&Apache::lonnet::validCODE($CODE)) {
7901: &scantron_get_correction($r,$i,$scan_record,
7902: \%scantron_config,
7903: $line,'incorrectCODE',\%allcodes);
7904: return(1,$currentphase);
7905: }
7906: if (%allcodes && !exists($allcodes{$CODE})
7907: && !$$scan_record{'scantron.useCODE'}) {
7908: &scantron_get_correction($r,$i,$scan_record,
7909: \%scantron_config,
7910: $line,'incorrectCODE',\%allcodes);
7911: return(1,$currentphase);
7912: }
7913: if (exists($usedCODEs{$CODE})
7914: && $env{'form.scantron_CODEunique'} eq 'yes'
7915: && !$$scan_record{'scantron.CODE_ignore_dup'}) {
7916: &scantron_get_correction($r,$i,$scan_record,
7917: \%scantron_config,
7918: $line,'duplicateCODE',$usedCODEs{$CODE});
7919: return(1,$currentphase);
7920: }
7921: push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
7922: }
7923: return (0,$currentphase+1);
7924: }
7925:
7926: =pod
7927:
7928: =item scantron_validate_doublebubble
7929:
7930: Validates all scanlines in the selected file to not have any
7931: bubble lines with multiple bubbles marked.
7932:
7933: =cut
7934:
7935: sub scantron_validate_doublebubble {
7936: my ($r,$currentphase) = @_;
7937: #get student info
7938: my $classlist=&Apache::loncoursedata::get_classlist();
7939: my %idmap=&username_to_idmap($classlist);
7940: my (undef,undef,$sequence)=
7941: &Apache::lonnet::decode_symb($env{'form.selectpage'});
7942:
7943: #get scantron line setup
7944: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7945: my ($scanlines,$scan_data)=&scantron_getfile();
7946:
7947: my $navmap = Apache::lonnavmaps::navmap->new();
7948: unless (ref($navmap)) {
7949: $r->print(&navmap_errormsg());
7950: return(1,$currentphase);
7951: }
7952: my $map=$navmap->getResourceByUrl($sequence);
7953: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
7954: my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
7955: %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
7956: my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
7957:
7958: my $nav_error;
7959: if (ref($map)) {
7960: $randomorder = $map->randomorder();
7961: $randompick = $map->randompick();
7962: if ($randomorder || $randompick) {
7963: $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
7964: if ($nav_error) {
7965: $r->print(&navmap_errormsg());
7966: return(1,$currentphase);
7967: }
7968: &graders_resources_pass(\@resources,\%grader_partids_by_symb,
7969: \%grader_randomlists_by_symb,$bubbles_per_row);
7970: }
7971: } else {
7972: $r->print(&navmap_errormsg());
7973: return(1,$currentphase);
7974: }
7975:
7976: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
7977: if ($nav_error) {
7978: $r->print(&navmap_errormsg());
7979: return(1,$currentphase);
7980: }
7981:
7982: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7983: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7984: if ($line=~/^[\s\cz]*$/) { next; }
7985: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7986: $scan_data,undef,\%idmap,$randomorder,
7987: $randompick,$sequence,\@master_seq,
7988: \%symb_to_resource,\%grader_partids_by_symb,
7989: \%orderedforcode,\%respnumlookup,\%startline);
7990: if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
7991: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
7992: 'doublebubble',
7993: $$scan_record{'scantron.doubleerror'},
7994: $randomorder,$randompick,\%respnumlookup,\%startline);
7995: return (1,$currentphase);
7996: }
7997: return (0,$currentphase+1);
7998: }
7999:
8000:
8001: sub scantron_get_maxbubble {
8002: my ($nav_error,$scantron_config) = @_;
8003: if (defined($env{'form.scantron_maxbubble'}) &&
8004: $env{'form.scantron_maxbubble'}) {
8005: &restore_bubble_lines();
8006: return $env{'form.scantron_maxbubble'};
8007: }
8008:
8009: my (undef, undef, $sequence) =
8010: &Apache::lonnet::decode_symb($env{'form.selectpage'});
8011:
8012: my $navmap=Apache::lonnavmaps::navmap->new();
8013: unless (ref($navmap)) {
8014: if (ref($nav_error)) {
8015: $$nav_error = 1;
8016: }
8017: return;
8018: }
8019: my $map=$navmap->getResourceByUrl($sequence);
8020: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
8021: my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
8022:
8023: &Apache::lonxml::clear_problem_counter();
8024:
8025: my $uname = $env{'user.name'};
8026: my $udom = $env{'user.domain'};
8027: my $cid = $env{'request.course.id'};
8028: my $total_lines = 0;
8029: %bubble_lines_per_response = ();
8030: %first_bubble_line = ();
8031: %subdivided_bubble_lines = ();
8032: %responsetype_per_response = ();
8033: %masterseq_id_responsenum = ();
8034:
8035: my $response_number = 0;
8036: my $bubble_line = 0;
8037: foreach my $resource (@resources) {
8038: my $resid = $resource->id();
8039: my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
8040: $udom,undef,$bubbles_per_row);
8041: if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
8042: foreach my $part_id (@{$parts}) {
8043: my $lines;
8044:
8045: # TODO - make this a persistent hash not an array.
8046:
8047: # optionresponse, matchresponse and rankresponse type items
8048: # render as separate sub-questions in exam mode.
8049: if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
8050: ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
8051: ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
8052: my ($numbub,$numshown);
8053: if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
8054: if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
8055: $numbub = scalar(@{$analysis->{$part_id.'.options'}});
8056: }
8057: } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
8058: if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
8059: $numbub = scalar(@{$analysis->{$part_id.'.items'}});
8060: }
8061: } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
8062: if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
8063: $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
8064: }
8065: }
8066: if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
8067: $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
8068: }
8069: my $bubbles_per_row =
8070: &bubblesheet_bubbles_per_row($scantron_config);
8071: my $inner_bubble_lines = int($numbub/$bubbles_per_row);
8072: if (($numbub % $bubbles_per_row) != 0) {
8073: $inner_bubble_lines++;
8074: }
8075: for (my $i=0; $i<$numshown; $i++) {
8076: $subdivided_bubble_lines{$response_number} .=
8077: $inner_bubble_lines.',';
8078: }
8079: $subdivided_bubble_lines{$response_number} =~ s/,$//;
8080: $lines = $numshown * $inner_bubble_lines;
8081: } else {
8082: $lines = $analysis->{"$part_id.bubble_lines"};
8083: }
8084:
8085: $first_bubble_line{$response_number} = $bubble_line;
8086: $bubble_lines_per_response{$response_number} = $lines;
8087: $responsetype_per_response{$response_number} =
8088: $analysis->{$part_id.'.type'};
8089: $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;
8090: $response_number++;
8091:
8092: $bubble_line += $lines;
8093: $total_lines += $lines;
8094: }
8095: }
8096: }
8097: &Apache::lonnet::delenv('scantron.');
8098:
8099: &save_bubble_lines();
8100: $env{'form.scantron_maxbubble'} =
8101: $total_lines;
8102: return $env{'form.scantron_maxbubble'};
8103: }
8104:
8105: sub bubblesheet_bubbles_per_row {
8106: my ($scantron_config) = @_;
8107: my $bubbles_per_row;
8108: if (ref($scantron_config) eq 'HASH') {
8109: $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
8110: }
8111: if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
8112: $bubbles_per_row = 10;
8113: }
8114: return $bubbles_per_row;
8115: }
8116:
8117: sub scantron_validate_missingbubbles {
8118: my ($r,$currentphase) = @_;
8119: #get student info
8120: my $classlist=&Apache::loncoursedata::get_classlist();
8121: my %idmap=&username_to_idmap($classlist);
8122: my (undef,undef,$sequence)=
8123: &Apache::lonnet::decode_symb($env{'form.selectpage'});
8124:
8125: #get scantron line setup
8126: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
8127: my ($scanlines,$scan_data)=&scantron_getfile();
8128:
8129: my $navmap = Apache::lonnavmaps::navmap->new();
8130: unless (ref($navmap)) {
8131: $r->print(&navmap_errormsg());
8132: return(1,$currentphase);
8133: }
8134:
8135: my $map=$navmap->getResourceByUrl($sequence);
8136: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
8137: my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
8138: %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
8139: my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
8140:
8141: my $nav_error;
8142: if (ref($map)) {
8143: $randomorder = $map->randomorder();
8144: $randompick = $map->randompick();
8145: if ($randomorder || $randompick) {
8146: $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
8147: if ($nav_error) {
8148: $r->print(&navmap_errormsg());
8149: return(1,$currentphase);
8150: }
8151: &graders_resources_pass(\@resources,\%grader_partids_by_symb,
8152: \%grader_randomlists_by_symb,$bubbles_per_row);
8153: }
8154: } else {
8155: $r->print(&navmap_errormsg());
8156: return(1,$currentphase);
8157: }
8158:
8159:
8160: my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
8161: if ($nav_error) {
8162: $r->print(&navmap_errormsg());
8163: return(1,$currentphase);
8164: }
8165:
8166: if (!$max_bubble) { $max_bubble=2**31; }
8167: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
8168: my $line=&scantron_get_line($scanlines,$scan_data,$i);
8169: if ($line=~/^[\s\cz]*$/) { next; }
8170: my $scan_record =
8171: &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
8172: $randomorder,$randompick,$sequence,\@master_seq,
8173: \%symb_to_resource,\%grader_partids_by_symb,
8174: \%orderedforcode,\%respnumlookup,\%startline);
8175: if (!defined($$scan_record{'scantron.missingerror'})) { next; }
8176: my @to_correct;
8177:
8178: # Probably here's where the error is...
8179:
8180: foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
8181: my $lastbubble;
8182: if ($missing =~ /^(\d+)\.(\d+)$/) {
8183: my $question = $1;
8184: my $subquestion = $2;
8185: my ($first,$responsenum);
8186: if ($randomorder || $randompick) {
8187: $responsenum = $respnumlookup{$question-1};
8188: $first = $startline{$question-1};
8189: } else {
8190: $responsenum = $question-1;
8191: $first = $first_bubble_line{$responsenum};
8192: }
8193: if (!defined($first)) { next; }
8194: my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
8195: my $subcount = 1;
8196: while ($subcount<$subquestion) {
8197: $first += $subans[$subcount-1];
8198: $subcount ++;
8199: }
8200: my $count = $subans[$subquestion-1];
8201: $lastbubble = $first + $count;
8202: } else {
8203: my ($first,$responsenum);
8204: if ($randomorder || $randompick) {
8205: $responsenum = $respnumlookup{$missing-1};
8206: $first = $startline{$missing-1};
8207: } else {
8208: $responsenum = $missing-1;
8209: $first = $first_bubble_line{$responsenum};
8210: }
8211: if (!defined($first)) { next; }
8212: $lastbubble = $first + $bubble_lines_per_response{$responsenum};
8213: }
8214: if ($lastbubble > $max_bubble) { next; }
8215: push(@to_correct,$missing);
8216: }
8217: if (@to_correct) {
8218: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
8219: $line,'missingbubble',\@to_correct,
8220: $randomorder,$randompick,\%respnumlookup,
8221: \%startline);
8222: return (1,$currentphase);
8223: }
8224:
8225: }
8226: return (0,$currentphase+1);
8227: }
8228:
8229: sub hand_bubble_option {
8230: my (undef, undef, $sequence) =
8231: &Apache::lonnet::decode_symb($env{'form.selectpage'});
8232: return if ($sequence eq '');
8233: my $navmap = Apache::lonnavmaps::navmap->new();
8234: unless (ref($navmap)) {
8235: return;
8236: }
8237: my $needs_hand_bubbles;
8238: my $map=$navmap->getResourceByUrl($sequence);
8239: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
8240: foreach my $res (@resources) {
8241: if (ref($res)) {
8242: if ($res->is_problem()) {
8243: my $partlist = $res->parts();
8244: foreach my $part (@{ $partlist }) {
8245: my @types = $res->responseType($part);
8246: if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
8247: $needs_hand_bubbles = 1;
8248: last;
8249: }
8250: }
8251: }
8252: }
8253: }
8254: if ($needs_hand_bubbles) {
8255: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
8256: my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
8257: return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
8258: &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 />').
8259: '<label><input type="radio" name="scantron_lastbubblepoints" value="'.$bubbles_per_row.'" checked="checked" />'.&mt('[quant,_1,point]',$bubbles_per_row).'</label> '.&mt('or').' '.
8260: '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
8261: }
8262: return;
8263: }
8264:
8265: sub scantron_process_students {
8266: my ($r,$symb) = @_;
8267:
8268: my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
8269: if (!$symb) {
8270: return '';
8271: }
8272: my $default_form_data=&defaultFormData($symb);
8273:
8274: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
8275: my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
8276: my ($scanlines,$scan_data)=&scantron_getfile();
8277: my $classlist=&Apache::loncoursedata::get_classlist();
8278: my %idmap=&username_to_idmap($classlist);
8279: my $navmap=Apache::lonnavmaps::navmap->new();
8280: unless (ref($navmap)) {
8281: $r->print(&navmap_errormsg());
8282: return '';
8283: }
8284: my $map=$navmap->getResourceByUrl($sequence);
8285: my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
8286: %grader_randomlists_by_symb);
8287: if (ref($map)) {
8288: $randomorder = $map->randomorder();
8289: $randompick = $map->randompick();
8290: } else {
8291: $r->print(&navmap_errormsg());
8292: return '';
8293: }
8294: my $nav_error;
8295: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
8296: if ($randomorder || $randompick) {
8297: $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
8298: if ($nav_error) {
8299: $r->print(&navmap_errormsg());
8300: return '';
8301: }
8302: }
8303: &graders_resources_pass(\@resources,\%grader_partids_by_symb,
8304: \%grader_randomlists_by_symb,$bubbles_per_row);
8305:
8306: my ($uname,$udom);
8307: my $result= <<SCANTRONFORM;
8308: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
8309: <input type="hidden" name="command" value="scantron_configphase" />
8310: $default_form_data
8311: SCANTRONFORM
8312: $r->print($result);
8313:
8314: my @delayqueue;
8315: my (%completedstudents,%scandata);
8316:
8317: my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
8318: my $count=&get_todo_count($scanlines,$scan_data);
8319: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
8320: &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
8321: $r->print('<br />');
8322: my $start=&Time::HiRes::time();
8323: my $i=-1;
8324: my $started;
8325:
8326: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
8327: if ($nav_error) {
8328: $r->print(&navmap_errormsg());
8329: return '';
8330: }
8331:
8332: # If an ssi failed in scantron_get_maxbubble, put an error message out to
8333: # the user and return.
8334:
8335: if ($ssi_error) {
8336: $r->print("</form>");
8337: &ssi_print_error($r);
8338: &Apache::lonnet::remove_lock($lock);
8339: return ''; # Dunno why the other returns return '' rather than just returning.
8340: }
8341:
8342: my %lettdig = &letter_to_digits();
8343: my $numletts = scalar(keys(%lettdig));
8344: my %orderedforcode;
8345:
8346: while ($i<$scanlines->{'count'}) {
8347: ($uname,$udom)=('','');
8348: $i++;
8349: my $line=&scantron_get_line($scanlines,$scan_data,$i);
8350: if ($line=~/^[\s\cz]*$/) { next; }
8351: if ($started) {
8352: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
8353: }
8354: $started=1;
8355: my %respnumlookup = ();
8356: my %startline = ();
8357: my $total;
8358: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
8359: $scan_data,undef,\%idmap,$randomorder,
8360: $randompick,$sequence,\@master_seq,
8361: \%symb_to_resource,\%grader_partids_by_symb,
8362: \%orderedforcode,\%respnumlookup,\%startline,
8363: \$total);
8364: unless ($uname=&scantron_find_student($scan_record,$scan_data,
8365: \%idmap,$i)) {
8366: &scantron_add_delay(\@delayqueue,$line,
8367: 'Unable to find a student that matches',1);
8368: next;
8369: }
8370: if (exists $completedstudents{$uname}) {
8371: &scantron_add_delay(\@delayqueue,$line,
8372: 'Student '.$uname.' has multiple sheets',2);
8373: next;
8374: }
8375: my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
8376: my $user = $uname.':'.$usec;
8377: ($uname,$udom)=split(/:/,$uname);
8378:
8379: my $scancode;
8380: if ((exists($scan_record->{'scantron.CODE'})) &&
8381: (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
8382: $scancode = $scan_record->{'scantron.CODE'};
8383: } else {
8384: $scancode = '';
8385: }
8386:
8387: my @mapresources = @resources;
8388: if ($randomorder || $randompick) {
8389: @mapresources =
8390: &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
8391: \%orderedforcode);
8392: }
8393: my (%partids_by_symb,$res_error);
8394: foreach my $resource (@mapresources) {
8395: my $ressymb;
8396: if (ref($resource)) {
8397: $ressymb = $resource->symb();
8398: } else {
8399: $res_error = 1;
8400: last;
8401: }
8402: if ((exists($grader_randomlists_by_symb{$ressymb})) ||
8403: (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
8404: my ($analysis,$parts) =
8405: &scantron_partids_tograde($resource,$env{'request.course.id'},
8406: $uname,$udom,undef,$bubbles_per_row);
8407: $partids_by_symb{$ressymb} = $parts;
8408: } else {
8409: $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
8410: }
8411: }
8412:
8413: if ($res_error) {
8414: &scantron_add_delay(\@delayqueue,$line,
8415: 'An error occurred while grading student '.$uname,2);
8416: next;
8417: }
8418:
8419: &Apache::lonxml::clear_problem_counter();
8420: &Apache::lonnet::appenv($scan_record);
8421:
8422: if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
8423: &scantron_putfile($scanlines,$scan_data);
8424: }
8425:
8426: if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
8427: \@mapresources,\%partids_by_symb,
8428: $bubbles_per_row,$randomorder,$randompick,
8429: \%respnumlookup,\%startline)
8430: eq 'ssi_error') {
8431: $ssi_error = 0; # So end of handler error message does not trigger.
8432: $r->print("</form>");
8433: &ssi_print_error($r);
8434: &Apache::lonnet::remove_lock($lock);
8435: return ''; # Why return ''? Beats me.
8436: }
8437:
8438: if (($scancode) && ($randomorder || $randompick)) {
8439: my $parmresult =
8440: &Apache::lonparmset::storeparm_by_symb($symb,
8441: '0_examcode',2,$scancode,
8442: 'string_examcode',$uname,
8443: $udom);
8444: }
8445: $completedstudents{$uname}={'line'=>$line};
8446: if ($env{'form.verifyrecord'}) {
8447: my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
8448: if ($randompick) {
8449: if ($total) {
8450: $lastpos = $total*$scantron_config{'Qlength'};
8451: }
8452: }
8453:
8454: my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
8455: chomp($studentdata);
8456: $studentdata =~ s/\r$//;
8457: my $studentrecord = '';
8458: my $counter = -1;
8459: foreach my $resource (@mapresources) {
8460: my $ressymb = $resource->symb();
8461: ($counter,my $recording) =
8462: &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
8463: $counter,$studentdata,$partids_by_symb{$ressymb},
8464: \%scantron_config,\%lettdig,$numletts,$randomorder,
8465: $randompick,\%respnumlookup,\%startline);
8466: $studentrecord .= $recording;
8467: }
8468: if ($studentrecord ne $studentdata) {
8469: &Apache::lonxml::clear_problem_counter();
8470: if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
8471: \@mapresources,\%partids_by_symb,
8472: $bubbles_per_row,$randomorder,$randompick,
8473: \%respnumlookup,\%startline)
8474: eq 'ssi_error') {
8475: $ssi_error = 0; # So end of handler error message does not trigger.
8476: $r->print("</form>");
8477: &ssi_print_error($r);
8478: &Apache::lonnet::remove_lock($lock);
8479: delete($completedstudents{$uname});
8480: return '';
8481: }
8482: $counter = -1;
8483: $studentrecord = '';
8484: foreach my $resource (@mapresources) {
8485: my $ressymb = $resource->symb();
8486: ($counter,my $recording) =
8487: &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
8488: $counter,$studentdata,$partids_by_symb{$ressymb},
8489: \%scantron_config,\%lettdig,$numletts,
8490: $randomorder,$randompick,\%respnumlookup,
8491: \%startline);
8492: $studentrecord .= $recording;
8493: }
8494: if ($studentrecord ne $studentdata) {
8495: $r->print('<p><span class="LC_warning">');
8496: if ($scancode eq '') {
8497: $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
8498: $uname.':'.$udom,$scan_record->{'scantron.ID'}));
8499: } else {
8500: $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
8501: $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
8502: }
8503: $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
8504: &Apache::loncommon::start_data_table_header_row()."\n".
8505: '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
8506: &Apache::loncommon::end_data_table_header_row()."\n".
8507: &Apache::loncommon::start_data_table_row().
8508: '<td>'.&mt('Bubblesheet').'</td>'.
8509: '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
8510: &Apache::loncommon::end_data_table_row().
8511: &Apache::loncommon::start_data_table_row().
8512: '<td>'.&mt('Stored submissions').'</td>'.
8513: '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
8514: &Apache::loncommon::end_data_table_row().
8515: &Apache::loncommon::end_data_table().'</p>');
8516: } else {
8517: $r->print('<br /><span class="LC_warning">'.
8518: &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 />'.
8519: &mt("As a consequence, this user's submission history records two tries.").
8520: '</span><br />');
8521: }
8522: }
8523: }
8524: if (&Apache::loncommon::connection_aborted($r)) { last; }
8525: } continue {
8526: &Apache::lonxml::clear_problem_counter();
8527: &Apache::lonnet::delenv('scantron.');
8528: }
8529: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
8530: &Apache::lonnet::remove_lock($lock);
8531: # my $lasttime = &Time::HiRes::time()-$start;
8532: # $r->print("<p>took $lasttime</p>");
8533:
8534: $r->print("</form>");
8535: return '';
8536: }
8537:
8538: sub graders_resources_pass {
8539: my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
8540: $bubbles_per_row) = @_;
8541: if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) &&
8542: (ref($grader_randomlists_by_symb) eq 'HASH')) {
8543: foreach my $resource (@{$resources}) {
8544: my $ressymb = $resource->symb();
8545: my ($analysis,$parts) =
8546: &scantron_partids_tograde($resource,$env{'request.course.id'},
8547: $env{'user.name'},$env{'user.domain'},
8548: 1,$bubbles_per_row);
8549: $grader_partids_by_symb->{$ressymb} = $parts;
8550: if (ref($analysis) eq 'HASH') {
8551: if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
8552: $grader_randomlists_by_symb->{$ressymb} =
8553: $analysis->{'parts_withrandomlist'};
8554: }
8555: }
8556: }
8557: }
8558: return;
8559: }
8560:
8561: =pod
8562:
8563: =item users_order
8564:
8565: Returns array of resources in current map, ordered based on either CODE,
8566: if this is a CODEd exam, or based on student's identity if this is a
8567: "NAMEd" exam.
8568:
8569: Should be used when randomorder and/or randompick applied when the
8570: corresponding exam was printed, prior to students completing bubblesheets
8571: for the version of the exam the student received.
8572:
8573: =cut
8574:
8575: sub users_order {
8576: my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
8577: my @mapresources;
8578: unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
8579: return @mapresources;
8580: }
8581: if ($scancode) {
8582: if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
8583: @mapresources = @{$orderedforcode->{$scancode}};
8584: } else {
8585: $env{'form.CODE'} = $scancode;
8586: my $actual_seq =
8587: &Apache::lonprintout::master_seq_to_person_seq($mapurl,
8588: $master_seq,
8589: $user,$scancode,1);
8590: if (ref($actual_seq) eq 'ARRAY') {
8591: @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
8592: if (ref($orderedforcode) eq 'HASH') {
8593: if (@mapresources > 0) {
8594: $orderedforcode->{$scancode} = \@mapresources;
8595: }
8596: }
8597: }
8598: delete($env{'form.CODE'});
8599: }
8600: } else {
8601: my $actual_seq =
8602: &Apache::lonprintout::master_seq_to_person_seq($mapurl,
8603: $master_seq,
8604: $user,undef,1);
8605: if (ref($actual_seq) eq 'ARRAY') {
8606: @mapresources =
8607: map { $symb_to_resource->{$_}; } @{$actual_seq};
8608: }
8609: }
8610: return @mapresources;
8611: }
8612:
8613: sub grade_student_bubbles {
8614: my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
8615: $randomorder,$randompick,$respnumlookup,$startline) = @_;
8616: my $uselookup = 0;
8617: if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
8618: (ref($startline) eq 'HASH')) {
8619: $uselookup = 1;
8620: }
8621:
8622: if (ref($resources) eq 'ARRAY') {
8623: my $count = 0;
8624: foreach my $resource (@{$resources}) {
8625: my $ressymb = $resource->symb();
8626: my %form = ('submitted' => 'scantron',
8627: 'grade_target' => 'grade',
8628: 'grade_username' => $uname,
8629: 'grade_domain' => $udom,
8630: 'grade_courseid' => $env{'request.course.id'},
8631: 'grade_symb' => $ressymb,
8632: 'CODE' => $scancode
8633: );
8634: if ($bubbles_per_row ne '') {
8635: $form{'bubbles_per_row'} = $bubbles_per_row;
8636: }
8637: if ($env{'form.scantron_lastbubblepoints'} ne '') {
8638: $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
8639: }
8640: if (ref($parts) eq 'HASH') {
8641: if (ref($parts->{$ressymb}) eq 'ARRAY') {
8642: foreach my $part (@{$parts->{$ressymb}}) {
8643: if ($uselookup) {
8644: $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
8645: } else {
8646: $form{'scantron_questnum_start.'.$part} =
8647: 1+$env{'form.scantron.first_bubble_line.'.$count};
8648: }
8649: $count++;
8650: }
8651: }
8652: }
8653: my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
8654: return 'ssi_error' if ($ssi_error);
8655: last if (&Apache::loncommon::connection_aborted($r));
8656: }
8657: }
8658: return;
8659: }
8660:
8661: sub scantron_upload_scantron_data {
8662: my ($r,$symb)=@_;
8663: my $dom = $env{'request.role.domain'};
8664: my $domdesc = &Apache::lonnet::domain($dom,'description');
8665: $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
8666: my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
8667: 'domainid',
8668: 'coursename',$dom);
8669: my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
8670: (' 'x2).&mt('(shows course personnel)');
8671: my $default_form_data=&defaultFormData($symb);
8672: my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
8673: 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.");
8674: $r->print(&Apache::lonhtmlcommon::scripttag('
8675: function checkUpload(formname) {
8676: if (formname.upfile.value == "") {
8677: alert("'.$nofile_alert.'");
8678: return false;
8679: }
8680: if (formname.courseid.value == "") {
8681: alert("'.$nocourseid_alert.'");
8682: return false;
8683: }
8684: formname.submit();
8685: }
8686:
8687: function ToSyllabus() {
8688: var cdom = '."'$dom'".';
8689: var cnum = document.rules.courseid.value;
8690: if (cdom == "" || cdom == null) {
8691: return;
8692: }
8693: if (cnum == "" || cnum == null) {
8694: return;
8695: }
8696: syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
8697: "height=350,width=350,scrollbars=yes,menubar=no");
8698: return;
8699: }
8700:
8701: '));
8702: $r->print('
8703: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
8704:
8705: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
8706: '.$default_form_data.
8707: &Apache::lonhtmlcommon::start_pick_box().
8708: &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
8709: '<input name="courseid" type="text" size="30" />'.$select_link.
8710: &Apache::lonhtmlcommon::row_closure().
8711: &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
8712: '<input name="coursename" type="text" size="30" />'.$syllabuslink.
8713: &Apache::lonhtmlcommon::row_closure().
8714: &Apache::lonhtmlcommon::row_title(&mt('Domain')).
8715: '<input name="domainid" type="hidden" />'.$domdesc.
8716: &Apache::lonhtmlcommon::row_closure().
8717: &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
8718: '<input type="file" name="upfile" size="50" />'.
8719: &Apache::lonhtmlcommon::row_closure(1).
8720: &Apache::lonhtmlcommon::end_pick_box().'<br />
8721:
8722: <input name="command" value="scantronupload_save" type="hidden" />
8723: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
8724: </form>
8725: ');
8726: return '';
8727: }
8728:
8729:
8730: sub scantron_upload_scantron_data_save {
8731: my($r,$symb)=@_;
8732: my $doanotherupload=
8733: '<br /><form action="/adm/grades" method="post">'."\n".
8734: '<input type="hidden" name="command" value="scantronupload" />'."\n".
8735: '<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
8736: '</form>'."\n";
8737: if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
8738: !&Apache::lonnet::allowed('usc',
8739: $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
8740: $r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
8741: unless ($symb) {
8742: $r->print($doanotherupload);
8743: }
8744: return '';
8745: }
8746: my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
8747: my $uploadedfile;
8748: $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
8749: if (length($env{'form.upfile'}) < 2) {
8750: $r->print(
8751: &Apache::lonhtmlcommon::confirm_success(
8752: &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
8753: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
8754: } else {
8755: my $result =
8756: &Apache::lonnet::userfileupload('upfile','','scantron','','','',
8757: $env{'form.courseid'},$env{'form.domainid'});
8758: if ($result =~ m{^/uploaded/}) {
8759: $r->print(
8760: &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
8761: &mt('Uploaded [_1] bytes of data into location: [_2]',
8762: (length($env{'form.upfile'})-1),
8763: '<span class="LC_filename">'.$result.'</span>'));
8764: ($uploadedfile) = ($result =~ m{/([^/]+)$});
8765: $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
8766: $env{'form.courseid'},$uploadedfile));
8767: } else {
8768: $r->print(
8769: &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
8770: &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
8771: $result,
8772: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
8773: }
8774: }
8775: if ($symb) {
8776: $r->print(&scantron_selectphase($r,$uploadedfile,$symb));
8777: } else {
8778: $r->print($doanotherupload);
8779: }
8780: return '';
8781: }
8782:
8783: sub validate_uploaded_scantron_file {
8784: my ($cdom,$cname,$fname) = @_;
8785: my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
8786: my @lines;
8787: if ($scanlines ne '-1') {
8788: @lines=split("\n",$scanlines,-1);
8789: }
8790: my $output;
8791: if (@lines) {
8792: my (%counts,$max_match_format);
8793: my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
8794: my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
8795: my %idmap = &username_to_idmap($classlist);
8796: foreach my $key (keys(%idmap)) {
8797: my $lckey = lc($key);
8798: $idmap{$lckey} = $idmap{$key};
8799: }
8800: my %unique_formats;
8801: my @formatlines = &get_scantronformat_file();
8802: foreach my $line (@formatlines) {
8803: chomp($line);
8804: my @config = split(/:/,$line);
8805: my $idstart = $config[5];
8806: my $idlength = $config[6];
8807: if (($idstart ne '') && ($idlength > 0)) {
8808: if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
8809: push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]);
8810: } else {
8811: $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
8812: }
8813: }
8814: }
8815: foreach my $key (keys(%unique_formats)) {
8816: my ($idstart,$idlength) = split(':',$key);
8817: %{$counts{$key}} = (
8818: 'found' => 0,
8819: 'total' => 0,
8820: );
8821: foreach my $line (@lines) {
8822: next if ($line =~ /^#/);
8823: next if ($line =~ /^[\s\cz]*$/);
8824: my $id = substr($line,$idstart-1,$idlength);
8825: $id = lc($id);
8826: if (exists($idmap{$id})) {
8827: $counts{$key}{'found'} ++;
8828: }
8829: $counts{$key}{'total'} ++;
8830: }
8831: if ($counts{$key}{'total'}) {
8832: my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
8833: if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
8834: $max_match_pct = $percent_match;
8835: $max_match_format = $key;
8836: $found_match_count = $counts{$key}{'found'};
8837: $max_match_count = $counts{$key}{'total'};
8838: }
8839: }
8840: }
8841: if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
8842: my $format_descs;
8843: my $numwithformat = @{$unique_formats{$max_match_format}};
8844: for (my $i=0; $i<$numwithformat; $i++) {
8845: my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
8846: if ($i<$numwithformat-2) {
8847: $format_descs .= '"<i>'.$desc.'</i>", ';
8848: } elsif ($i==$numwithformat-2) {
8849: $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
8850: } elsif ($i==$numwithformat-1) {
8851: $format_descs .= '"<i>'.$desc.'</i>"';
8852: }
8853: }
8854: my $showpct = sprintf("%.0f",$max_match_pct).'%';
8855: $output .= '<br />';
8856: if ($found_match_count == $max_match_count) {
8857: # 100% matching entries
8858: $output .= &Apache::lonhtmlcommon::confirm_success(
8859: &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
8860: '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
8861: &mt('Comparison of student IDs in the uploaded file with'.
8862: ' the course roster found matches for [_1] of the [_2] entries'.
8863: ' in the file (for the format defined for [_3]).',
8864: '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
8865: } else {
8866: # Not all entries matching? -> Show warning and additional info
8867: $output .=
8868: &Apache::lonhtmlcommon::confirm_success(
8869: &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
8870: '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
8871: &mt('Not all entries could be matched!'),1).'<br />'.
8872: &mt('Comparison of student IDs in the uploaded file with'.
8873: ' the course roster found matches for [_1] of the [_2] entries'.
8874: ' in the file (for the format defined for [_3]).',
8875: '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
8876: '<p class="LC_info">'.
8877: &mt('A low percentage of matches results from one of the following:').
8878: '</p><ul>'.
8879: '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
8880: '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
8881: '<i>'.$cdom.'</i>').'</li>'.
8882: '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
8883: '<li>'.&mt('The course roster is not up to date.').'</li>'.
8884: '</ul>';
8885: }
8886: }
8887: } else {
8888: $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
8889: }
8890: return $output;
8891: }
8892:
8893: sub valid_file {
8894: my ($requested_file)=@_;
8895: foreach my $filename (sort(&scantron_filenames())) {
8896: if ($requested_file eq $filename) { return 1; }
8897: }
8898: return 0;
8899: }
8900:
8901: sub scantron_download_scantron_data {
8902: my ($r,$symb)=@_;
8903: my $default_form_data=&defaultFormData($symb);
8904: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
8905: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
8906: my $file=$env{'form.scantron_selectfile'};
8907: if (! &valid_file($file)) {
8908: $r->print('
8909: <p>
8910: '.&mt('The requested filename was invalid.').'
8911: </p>
8912: ');
8913: return;
8914: }
8915: my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
8916: my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
8917: my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
8918: &Apache::lonnet::allowuploaded('/adm/grades',$orig);
8919: &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
8920: &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
8921: $r->print('
8922: <p>
8923: '.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
8924: '<a href="'.$orig.'">','</a>').'
8925: </p>
8926: <p>
8927: '.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
8928: '<a href="'.$corrected.'">','</a>').'
8929: </p>
8930: <p>
8931: '.&mt('[_1]Skipped[_2], a file of records that were skipped.',
8932: '<a href="'.$skipped.'">','</a>').'
8933: </p>
8934: ');
8935: return '';
8936: }
8937:
8938: sub checkscantron_results {
8939: my ($r,$symb) = @_;
8940: if (!$symb) {return '';}
8941: my $cid = $env{'request.course.id'};
8942: my %lettdig = &letter_to_digits();
8943: my $numletts = scalar(keys(%lettdig));
8944: my $cnum = $env{'course.'.$cid.'.num'};
8945: my $cdom = $env{'course.'.$cid.'.domain'};
8946: my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
8947: my %record;
8948: my %scantron_config =
8949: &Apache::grades::get_scantron_config($env{'form.scantron_format'});
8950: my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
8951: my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
8952: my $classlist=&Apache::loncoursedata::get_classlist();
8953: my %idmap=&Apache::grades::username_to_idmap($classlist);
8954: my $navmap=Apache::lonnavmaps::navmap->new();
8955: unless (ref($navmap)) {
8956: $r->print(&navmap_errormsg());
8957: return '';
8958: }
8959: my $map=$navmap->getResourceByUrl($sequence);
8960: my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
8961: %grader_randomlists_by_symb,%orderedforcode);
8962: if (ref($map)) {
8963: $randomorder=$map->randomorder();
8964: $randompick=$map->randompick();
8965: }
8966: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
8967: my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
8968: if ($nav_error) {
8969: $r->print(&navmap_errormsg());
8970: return '';
8971: }
8972: &graders_resources_pass(\@resources,\%grader_partids_by_symb,
8973: \%grader_randomlists_by_symb,$bubbles_per_row);
8974: my ($uname,$udom);
8975: my (%scandata,%lastname,%bylast);
8976: $r->print('
8977: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
8978:
8979: my @delayqueue;
8980: my %completedstudents;
8981:
8982: my $count=&get_todo_count($scanlines,$scan_data);
8983: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
8984: my ($username,$domain,$started);
8985: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
8986: if ($nav_error) {
8987: $r->print(&navmap_errormsg());
8988: return '';
8989: }
8990:
8991: &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
8992: my $start=&Time::HiRes::time();
8993: my $i=-1;
8994:
8995: while ($i<$scanlines->{'count'}) {
8996: ($username,$domain,$uname)=('','','');
8997: $i++;
8998: my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
8999: if ($line=~/^[\s\cz]*$/) { next; }
9000: if ($started) {
9001: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
9002: }
9003: $started=1;
9004: my $scan_record=
9005: &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
9006: $scan_data);
9007: unless ($uname=&scantron_find_student($scan_record,$scan_data,
9008: \%idmap,$i)) {
9009: &Apache::grades::scantron_add_delay(\@delayqueue,$line,
9010: 'Unable to find a student that matches',1);
9011: next;
9012: }
9013: if (exists $completedstudents{$uname}) {
9014: &Apache::grades::scantron_add_delay(\@delayqueue,$line,
9015: 'Student '.$uname.' has multiple sheets',2);
9016: next;
9017: }
9018: my $pid = $scan_record->{'scantron.ID'};
9019: $lastname{$pid} = $scan_record->{'scantron.LastName'};
9020: push(@{$bylast{$lastname{$pid}}},$pid);
9021: my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
9022: my $user = $uname.':'.$usec;
9023: ($username,$domain)=split(/:/,$uname);
9024:
9025: my $scancode;
9026: if ((exists($scan_record->{'scantron.CODE'})) &&
9027: (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
9028: $scancode = $scan_record->{'scantron.CODE'};
9029: } else {
9030: $scancode = '';
9031: }
9032:
9033: my @mapresources = @resources;
9034: my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
9035: my %respnumlookup=();
9036: my %startline=();
9037: if ($randomorder || $randompick) {
9038: @mapresources =
9039: &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
9040: \%orderedforcode);
9041: my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
9042: $scan_record,\@master_seq,\%symb_to_resource,
9043: \%grader_partids_by_symb,\%orderedforcode,
9044: \%respnumlookup,\%startline);
9045: if ($randompick && $total) {
9046: $lastpos = $total*$scantron_config{'Qlength'};
9047: }
9048: }
9049: $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
9050: chomp($scandata{$pid});
9051: $scandata{$pid} =~ s/\r$//;
9052:
9053: my $counter = -1;
9054: foreach my $resource (@mapresources) {
9055: my $parts;
9056: my $ressymb = $resource->symb();
9057: if ((exists($grader_randomlists_by_symb{$ressymb})) ||
9058: (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
9059: (my $analysis,$parts) =
9060: &scantron_partids_tograde($resource,$env{'request.course.id'},
9061: $username,$domain,undef,
9062: $bubbles_per_row);
9063: } else {
9064: $parts = $grader_partids_by_symb{$ressymb};
9065: }
9066: ($counter,my $recording) =
9067: &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
9068: $scandata{$pid},$parts,
9069: \%scantron_config,\%lettdig,$numletts,
9070: $randomorder,$randompick,
9071: \%respnumlookup,\%startline);
9072: $record{$pid} .= $recording;
9073: }
9074: }
9075: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
9076: $r->print('<br />');
9077: my ($okstudents,$badstudents,$numstudents,$passed,$failed);
9078: $passed = 0;
9079: $failed = 0;
9080: $numstudents = 0;
9081: foreach my $last (sort(keys(%bylast))) {
9082: if (ref($bylast{$last}) eq 'ARRAY') {
9083: foreach my $pid (sort(@{$bylast{$last}})) {
9084: my $showscandata = $scandata{$pid};
9085: my $showrecord = $record{$pid};
9086: $showscandata =~ s/\s/ /g;
9087: $showrecord =~ s/\s/ /g;
9088: if ($scandata{$pid} eq $record{$pid}) {
9089: my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
9090: $okstudents .= '<tr class="'.$css_class.'">'.
9091: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
9092: '</tr>'."\n".
9093: '<tr class="'.$css_class.'">'."\n".
9094: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
9095: $passed ++;
9096: } else {
9097: my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
9098: $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".
9099: '</tr>'."\n".
9100: '<tr class="'.$css_class.'">'."\n".
9101: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
9102: '</tr>'."\n";
9103: $failed ++;
9104: }
9105: $numstudents ++;
9106: }
9107: }
9108: }
9109: $r->print(
9110: '<p>'
9111: .&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).',
9112: '<b>',
9113: $numstudents,
9114: '</b>',
9115: $env{'form.scantron_maxbubble'})
9116: .'</p>'
9117: );
9118: $r->print('<p>'
9119: .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
9120: .'<br />'
9121: .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
9122: .'</p>'
9123: );
9124: if ($passed) {
9125: $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
9126: $r->print(&Apache::loncommon::start_data_table()."\n".
9127: &Apache::loncommon::start_data_table_header_row()."\n".
9128: '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
9129: &Apache::loncommon::end_data_table_header_row()."\n".
9130: $okstudents."\n".
9131: &Apache::loncommon::end_data_table().'<br />');
9132: }
9133: if ($failed) {
9134: $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
9135: $r->print(&Apache::loncommon::start_data_table()."\n".
9136: &Apache::loncommon::start_data_table_header_row()."\n".
9137: '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
9138: &Apache::loncommon::end_data_table_header_row()."\n".
9139: $badstudents."\n".
9140: &Apache::loncommon::end_data_table()).'<br />'.
9141: &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.');
9142: }
9143: $r->print('</form><br />');
9144: return;
9145: }
9146:
9147: sub verify_scantron_grading {
9148: my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
9149: $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
9150: $respnumlookup,$startline) = @_;
9151: my ($record,%expected,%startpos);
9152: return ($counter,$record) if (!ref($resource));
9153: return ($counter,$record) if (!$resource->is_problem());
9154: my $symb = $resource->symb();
9155: return ($counter,$record) if (ref($partids) ne 'ARRAY');
9156: foreach my $part_id (@{$partids}) {
9157: $counter ++;
9158: $expected{$part_id} = 0;
9159: my $respnum = $counter;
9160: if ($randomorder || $randompick) {
9161: $respnum = $respnumlookup->{$counter};
9162: $startpos{$part_id} = $startline->{$counter} + 1;
9163: } else {
9164: $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
9165: }
9166: if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
9167: my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
9168: foreach my $item (@sub_lines) {
9169: $expected{$part_id} += $item;
9170: }
9171: } else {
9172: $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
9173: }
9174: }
9175: if ($symb) {
9176: my %recorded;
9177: my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
9178: if ($returnhash{'version'}) {
9179: my %lasthash=();
9180: my $version;
9181: for ($version=1;$version<=$returnhash{'version'};$version++) {
9182: foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
9183: $lasthash{$key}=$returnhash{$version.':'.$key};
9184: }
9185: }
9186: foreach my $key (keys(%lasthash)) {
9187: if ($key =~ /\.scantron$/) {
9188: my $value = &unescape($lasthash{$key});
9189: my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
9190: if ($value eq '') {
9191: for (my $i=0; $i<$expected{$part_id}; $i++) {
9192: for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
9193: $recorded{$part_id} .= $scantron_config->{'Qoff'};
9194: }
9195: }
9196: } else {
9197: my @tocheck;
9198: my @items = split(//,$value);
9199: if (($scantron_config->{'Qon'} eq 'letter') ||
9200: ($scantron_config->{'Qon'} eq 'number')) {
9201: if (@items < $expected{$part_id}) {
9202: my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
9203: my @singles = split(//,$fragment);
9204: foreach my $pos (@singles) {
9205: if ($pos eq ' ') {
9206: push(@tocheck,$pos);
9207: } else {
9208: my $next = shift(@items);
9209: push(@tocheck,$next);
9210: }
9211: }
9212: } else {
9213: @tocheck = @items;
9214: }
9215: foreach my $letter (@tocheck) {
9216: if ($scantron_config->{'Qon'} eq 'letter') {
9217: if ($letter !~ /^[A-J]$/) {
9218: $letter = $scantron_config->{'Qoff'};
9219: }
9220: $recorded{$part_id} .= $letter;
9221: } elsif ($scantron_config->{'Qon'} eq 'number') {
9222: my $digit;
9223: if ($letter !~ /^[A-J]$/) {
9224: $digit = $scantron_config->{'Qoff'};
9225: } else {
9226: $digit = $lettdig->{$letter};
9227: }
9228: $recorded{$part_id} .= $digit;
9229: }
9230: }
9231: } else {
9232: @tocheck = @items;
9233: for (my $i=0; $i<$expected{$part_id}; $i++) {
9234: my $curr_sub = shift(@tocheck);
9235: my $digit;
9236: if ($curr_sub =~ /^[A-J]$/) {
9237: $digit = $lettdig->{$curr_sub}-1;
9238: }
9239: if ($curr_sub eq 'J') {
9240: $digit += scalar($numletts);
9241: }
9242: for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
9243: if ($j == $digit) {
9244: $recorded{$part_id} .= $scantron_config->{'Qon'};
9245: } else {
9246: $recorded{$part_id} .= $scantron_config->{'Qoff'};
9247: }
9248: }
9249: }
9250: }
9251: }
9252: }
9253: }
9254: }
9255: foreach my $part_id (@{$partids}) {
9256: if ($recorded{$part_id} eq '') {
9257: for (my $i=0; $i<$expected{$part_id}; $i++) {
9258: for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
9259: $recorded{$part_id} .= $scantron_config->{'Qoff'};
9260: }
9261: }
9262: }
9263: $record .= $recorded{$part_id};
9264: }
9265: }
9266: return ($counter,$record);
9267: }
9268:
9269: sub letter_to_digits {
9270: my %lettdig = (
9271: A => 1,
9272: B => 2,
9273: C => 3,
9274: D => 4,
9275: E => 5,
9276: F => 6,
9277: G => 7,
9278: H => 8,
9279: I => 9,
9280: J => 0,
9281: );
9282: return %lettdig;
9283: }
9284:
9285:
9286: #-------- end of section for handling grading scantron forms -------
9287: #
9288: #-------------------------------------------------------------------
9289:
9290: #-------------------------- Menu interface -------------------------
9291: #
9292: #--- Href with symb and command ---
9293:
9294: sub href_symb_cmd {
9295: my ($symb,$cmd)=@_;
9296: return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&command='.$cmd;
9297: }
9298:
9299: sub grading_menu {
9300: my ($request,$symb) = @_;
9301: if (!$symb) {return '';}
9302:
9303: my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
9304: 'command'=>'individual');
9305:
9306: my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
9307:
9308: $fields{'command'}='ungraded';
9309: my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
9310:
9311: $fields{'command'}='table';
9312: my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
9313:
9314: $fields{'command'}='all_for_one';
9315: my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
9316:
9317: $fields{'command'}='downloadfilesselect';
9318: my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
9319:
9320: $fields{'command'} = 'csvform';
9321: my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
9322:
9323: $fields{'command'} = 'processclicker';
9324: my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
9325:
9326: $fields{'command'} = 'scantron_selectphase';
9327: my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
9328:
9329: $fields{'command'} = 'initialverifyreceipt';
9330: my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
9331:
9332: my @menu = ({ categorytitle=>'Hand Grading',
9333: items =>[
9334: { linktext => 'Select individual students to grade',
9335: url => $url1a,
9336: permission => 'F',
9337: icon => 'grade_students.png',
9338: linktitle => 'Grade current resource for a selection of students.'
9339: },
9340: { linktext => 'Grade ungraded submissions.',
9341: url => $url1b,
9342: permission => 'F',
9343: icon => 'ungrade_sub.png',
9344: linktitle => 'Grade all submissions that have not been graded yet.'
9345: },
9346:
9347: { linktext => 'Grading table',
9348: url => $url1c,
9349: permission => 'F',
9350: icon => 'grading_table.png',
9351: linktitle => 'Grade current resource for all students.'
9352: },
9353: { linktext => 'Grade page/folder for one student',
9354: url => $url1d,
9355: permission => 'F',
9356: icon => 'grade_PageFolder.png',
9357: linktitle => 'Grade all resources in current page/sequence/folder for one student.'
9358: },
9359: { linktext => 'Download submissions',
9360: url => $url1e,
9361: permission => 'F',
9362: icon => 'download_sub.png',
9363: linktitle => 'Download all students submissions.'
9364: }]},
9365: { categorytitle=>'Automated Grading',
9366: items =>[
9367:
9368: { linktext => 'Upload Scores',
9369: url => $url2,
9370: permission => 'F',
9371: icon => 'uploadscores.png',
9372: linktitle => 'Specify a file containing the class scores for current resource.'
9373: },
9374: { linktext => 'Process Clicker',
9375: url => $url3,
9376: permission => 'F',
9377: icon => 'addClickerInfoFile.png',
9378: linktitle => 'Specify a file containing the clicker information for this resource.'
9379: },
9380: { linktext => 'Grade/Manage/Review Bubblesheets',
9381: url => $url4,
9382: permission => 'F',
9383: icon => 'bubblesheet.png',
9384: linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
9385: },
9386: { linktext => 'Verify Receipt Number',
9387: url => $url5,
9388: permission => 'F',
9389: icon => 'receipt_number.png',
9390: linktitle => 'Verify a system-generated receipt number for correct problem solution.'
9391: }
9392:
9393: ]
9394: });
9395:
9396: # Create the menu
9397: my $Str;
9398: $Str .= '<form method="post" action="" name="gradingMenu">';
9399: $Str .= '<input type="hidden" name="command" value="" />'.
9400: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
9401:
9402: $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
9403: return $Str;
9404: }
9405:
9406:
9407: sub ungraded {
9408: my ($request)=@_;
9409: &submit_options($request);
9410: }
9411:
9412: sub submit_options_sequence {
9413: my ($request,$symb) = @_;
9414: if (!$symb) {return '';}
9415: &commonJSfunctions($request);
9416: my $result;
9417:
9418: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
9419: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
9420: $result.=&selectfield(0).
9421: '<input type="hidden" name="command" value="pickStudentPage" />
9422: <div>
9423: <input type="submit" value="'.&mt('Next').' →" />
9424: </div>
9425: </div>
9426: </form>';
9427: return $result;
9428: }
9429:
9430: sub submit_options_table {
9431: my ($request,$symb) = @_;
9432: if (!$symb) {return '';}
9433: &commonJSfunctions($request);
9434: my $result;
9435:
9436: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
9437: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
9438:
9439: $result.=&selectfield(0).
9440: '<input type="hidden" name="command" value="viewgrades" />
9441: <div>
9442: <input type="submit" value="'.&mt('Next').' →" />
9443: </div>
9444: </div>
9445: </form>';
9446: return $result;
9447: }
9448:
9449: sub submit_options_download {
9450: my ($request,$symb) = @_;
9451: if (!$symb) {return '';}
9452:
9453: &commonJSfunctions($request);
9454:
9455: my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
9456: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
9457: $result.='
9458: <h2>
9459: '.&mt('Select Students for Which to Download Submissions').'
9460: </h2>'.&selectfield(1).'
9461: <input type="hidden" name="command" value="downloadfileslink" />
9462: <input type="submit" value="'.&mt('Next').' →" />
9463: </div>
9464: </div>
9465:
9466:
9467: </form>';
9468: return $result;
9469: }
9470:
9471: #--- Displays the submissions first page -------
9472: sub submit_options {
9473: my ($request,$symb) = @_;
9474: if (!$symb) {return '';}
9475:
9476: &commonJSfunctions($request);
9477: my $result;
9478:
9479: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
9480: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
9481: $result.=&selectfield(1).'
9482: <input type="hidden" name="command" value="submission" />
9483: <input type="submit" value="'.&mt('Next').' →" />
9484: </div>
9485: </div>
9486:
9487:
9488: </form>';
9489: return $result;
9490: }
9491:
9492: sub selectfield {
9493: my ($full)=@_;
9494: my %options =
9495: (&Apache::lonlocal::texthash(
9496: 'yes' => 'with submissions',
9497: 'queued' => 'in grading queue',
9498: 'graded' => 'with ungraded submissions',
9499: 'incorrect' => 'with incorrect submissions',
9500: 'all' => 'with any status'),
9501: 'select_form_order' => ['yes','queued','graded','incorrect','all']);
9502: my $result='<div class="LC_columnSection">
9503:
9504: <fieldset>
9505: <legend>
9506: '.&mt('Sections').'
9507: </legend>
9508: '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
9509: </fieldset>
9510:
9511: <fieldset>
9512: <legend>
9513: '.&mt('Groups').'
9514: </legend>
9515: '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
9516: </fieldset>
9517:
9518: <fieldset>
9519: <legend>
9520: '.&mt('Access Status').'
9521: </legend>
9522: '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
9523: </fieldset>';
9524: if ($full) {
9525: $result.='
9526: <fieldset>
9527: <legend>
9528: '.&mt('Submission Status').'
9529: </legend>'.
9530: &Apache::loncommon::select_form('all','submitonly',\%options).
9531: '</fieldset>';
9532: }
9533: $result.='</div><br />';
9534: return $result;
9535: }
9536:
9537: sub reset_perm {
9538: undef(%perm);
9539: }
9540:
9541: sub init_perm {
9542: &reset_perm();
9543: foreach my $test_perm ('vgr','mgr','opa') {
9544:
9545: my $scope = $env{'request.course.id'};
9546: if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
9547:
9548: $scope .= '/'.$env{'request.course.sec'};
9549: if ( $perm{$test_perm}=
9550: &Apache::lonnet::allowed($test_perm,$scope)) {
9551: $perm{$test_perm.'_section'}=$env{'request.course.sec'};
9552: } else {
9553: delete($perm{$test_perm});
9554: }
9555: }
9556: }
9557: }
9558:
9559: sub init_old_essays {
9560: my ($symb,$apath,$adom,$aname) = @_;
9561: if ($symb ne '') {
9562: my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
9563: if (keys(%essays) > 0) {
9564: $old_essays{$symb} = \%essays;
9565: }
9566: }
9567: return;
9568: }
9569:
9570: sub reset_old_essays {
9571: undef(%old_essays);
9572: }
9573:
9574: sub gather_clicker_ids {
9575: my %clicker_ids;
9576:
9577: my $classlist = &Apache::loncoursedata::get_classlist();
9578:
9579: # Set up a couple variables.
9580: my $username_idx = &Apache::loncoursedata::CL_SNAME();
9581: my $domain_idx = &Apache::loncoursedata::CL_SDOM();
9582: my $status_idx = &Apache::loncoursedata::CL_STATUS();
9583:
9584: foreach my $student (keys(%$classlist)) {
9585: if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
9586: my $username = $classlist->{$student}->[$username_idx];
9587: my $domain = $classlist->{$student}->[$domain_idx];
9588: my $clickers =
9589: (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
9590: foreach my $id (split(/\,/,$clickers)) {
9591: $id=~s/^[\#0]+//;
9592: $id=~s/[\-\:]//g;
9593: if (exists($clicker_ids{$id})) {
9594: $clicker_ids{$id}.=','.$username.':'.$domain;
9595: } else {
9596: $clicker_ids{$id}=$username.':'.$domain;
9597: }
9598: }
9599: }
9600: return %clicker_ids;
9601: }
9602:
9603: sub gather_adv_clicker_ids {
9604: my %clicker_ids;
9605: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
9606: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
9607: my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
9608: foreach my $element (sort(keys(%coursepersonnel))) {
9609: foreach my $person (split(/\,/,$coursepersonnel{$element})) {
9610: my ($puname,$pudom)=split(/\:/,$person);
9611: my $clickers =
9612: (&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
9613: foreach my $id (split(/\,/,$clickers)) {
9614: $id=~s/^[\#0]+//;
9615: $id=~s/[\-\:]//g;
9616: if (exists($clicker_ids{$id})) {
9617: $clicker_ids{$id}.=','.$puname.':'.$pudom;
9618: } else {
9619: $clicker_ids{$id}=$puname.':'.$pudom;
9620: }
9621: }
9622: }
9623: }
9624: return %clicker_ids;
9625: }
9626:
9627: sub clicker_grading_parameters {
9628: return ('gradingmechanism' => 'scalar',
9629: 'upfiletype' => 'scalar',
9630: 'specificid' => 'scalar',
9631: 'pcorrect' => 'scalar',
9632: 'pincorrect' => 'scalar');
9633: }
9634:
9635: sub process_clicker {
9636: my ($r,$symb)=@_;
9637: if (!$symb) {return '';}
9638: my $result=&checkforfile_js();
9639: $result.=&Apache::loncommon::start_data_table().
9640: &Apache::loncommon::start_data_table_header_row().
9641: '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
9642: &Apache::loncommon::end_data_table_header_row().
9643: &Apache::loncommon::start_data_table_row()."<td>\n";
9644: # Attempt to restore parameters from last session, set defaults if not present
9645: my %Saveable_Parameters=&clicker_grading_parameters();
9646: &Apache::loncommon::restore_course_settings('grades_clicker',
9647: \%Saveable_Parameters);
9648: if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
9649: if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
9650: if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
9651: if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
9652:
9653: my %checked;
9654: foreach my $gradingmechanism ('attendance','personnel','specific','given') {
9655: if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
9656: $checked{$gradingmechanism}=' checked="checked"';
9657: }
9658: }
9659:
9660: my $upload=&mt("Evaluate File");
9661: my $type=&mt("Type");
9662: my $attendance=&mt("Award points just for participation");
9663: my $personnel=&mt("Correctness determined from response by course personnel");
9664: my $specific=&mt("Correctness determined from response with clicker ID(s)");
9665: my $given=&mt("Correctness determined from given list of answers").' '.
9666: '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
9667: my $pcorrect=&mt("Percentage points for correct solution");
9668: my $pincorrect=&mt("Percentage points for incorrect solution");
9669: my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
9670: {'iclicker' => 'i>clicker',
9671: 'interwrite' => 'interwrite PRS',
9672: 'turning' => 'Turning Technologies'});
9673: $symb = &Apache::lonenc::check_encrypt($symb);
9674: $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
9675: function sanitycheck() {
9676: // Accept only integer percentages
9677: document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
9678: document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
9679: // Find out grading choice
9680: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
9681: if (document.forms.gradesupload.gradingmechanism[i].checked) {
9682: gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
9683: }
9684: }
9685: // By default, new choice equals user selection
9686: newgradingchoice=gradingchoice;
9687: // Not good to give more points for false answers than correct ones
9688: if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
9689: document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
9690: }
9691: // If new choice is attendance only, and old choice was correctness-based, restore defaults
9692: if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
9693: document.forms.gradesupload.pcorrect.value=100;
9694: document.forms.gradesupload.pincorrect.value=100;
9695: }
9696: // If the values are different, cannot be attendance only
9697: if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
9698: (gradingchoice=='attendance')) {
9699: newgradingchoice='personnel';
9700: }
9701: // Change grading choice to new one
9702: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
9703: if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
9704: document.forms.gradesupload.gradingmechanism[i].checked=true;
9705: } else {
9706: document.forms.gradesupload.gradingmechanism[i].checked=false;
9707: }
9708: }
9709: // Remember the old state
9710: document.forms.gradesupload.waschecked.value=newgradingchoice;
9711: }
9712: ENDUPFORM
9713: $result.= <<ENDUPFORM;
9714: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
9715: <input type="hidden" name="symb" value="$symb" />
9716: <input type="hidden" name="command" value="processclickerfile" />
9717: <input type="file" name="upfile" size="50" />
9718: <br /><label>$type: $selectform</label>
9719: ENDUPFORM
9720: $result.='</td>'.&Apache::loncommon::end_data_table_row().
9721: &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
9722: <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
9723: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
9724: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
9725: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
9726: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
9727: <br />
9728: <input type="text" name="givenanswer" size="50" />
9729: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
9730: ENDGRADINGFORM
9731: $result.='</td>'.&Apache::loncommon::end_data_table_row().
9732: &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
9733: <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
9734: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
9735: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
9736: </form>'
9737: ENDPERCFORM
9738: $result.='</td>'.
9739: &Apache::loncommon::end_data_table_row().
9740: &Apache::loncommon::end_data_table();
9741: return $result;
9742: }
9743:
9744: sub process_clicker_file {
9745: my ($r,$symb)=@_;
9746: if (!$symb) {return '';}
9747:
9748: my %Saveable_Parameters=&clicker_grading_parameters();
9749: &Apache::loncommon::store_course_settings('grades_clicker',
9750: \%Saveable_Parameters);
9751: my $result='';
9752: if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
9753: $result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
9754: return $result;
9755: }
9756: if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
9757: $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
9758: return $result;
9759: }
9760: my $foundgiven=0;
9761: if ($env{'form.gradingmechanism'} eq 'given') {
9762: $env{'form.givenanswer'}=~s/^\s*//gs;
9763: $env{'form.givenanswer'}=~s/\s*$//gs;
9764: $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
9765: $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
9766: my @answers=split(/\,/,$env{'form.givenanswer'});
9767: $foundgiven=$#answers+1;
9768: }
9769: my %clicker_ids=&gather_clicker_ids();
9770: my %correct_ids;
9771: if ($env{'form.gradingmechanism'} eq 'personnel') {
9772: %correct_ids=&gather_adv_clicker_ids();
9773: }
9774: if ($env{'form.gradingmechanism'} eq 'specific') {
9775: foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
9776: $correct_id=~tr/a-z/A-Z/;
9777: $correct_id=~s/\s//gs;
9778: $correct_id=~s/^[\#0]+//;
9779: $correct_id=~s/[\-\:]//g;
9780: if ($correct_id) {
9781: $correct_ids{$correct_id}='specified';
9782: }
9783: }
9784: }
9785: if ($env{'form.gradingmechanism'} eq 'attendance') {
9786: $result.=&mt('Score based on attendance only');
9787: } elsif ($env{'form.gradingmechanism'} eq 'given') {
9788: $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
9789: } else {
9790: my $number=0;
9791: $result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
9792: foreach my $id (sort(keys(%correct_ids))) {
9793: $result.='<br /><tt>'.$id.'</tt> - ';
9794: if ($correct_ids{$id} eq 'specified') {
9795: $result.=&mt('specified');
9796: } else {
9797: my ($uname,$udom)=split(/\:/,$correct_ids{$id});
9798: $result.=&Apache::loncommon::plainname($uname,$udom);
9799: }
9800: $number++;
9801: }
9802: $result.="</p>\n";
9803: if ($number==0) {
9804: $result .=
9805: &Apache::lonhtmlcommon::confirm_success(
9806: &mt('No IDs found to determine correct answer'),1);
9807: return $result;
9808: }
9809: }
9810: if (length($env{'form.upfile'}) < 2) {
9811: $result .=
9812: &Apache::lonhtmlcommon::confirm_success(
9813: &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
9814: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
9815: return $result;
9816: }
9817:
9818: # Were able to get all the info needed, now analyze the file
9819:
9820: $result.=&Apache::loncommon::studentbrowser_javascript();
9821: $symb = &Apache::lonenc::check_encrypt($symb);
9822: $result.=&Apache::loncommon::start_data_table().
9823: &Apache::loncommon::start_data_table_header_row().
9824: '<th>'.&mt('Evaluate clicker file').'</th>'.
9825: &Apache::loncommon::end_data_table_header_row().
9826: &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
9827: <td>
9828: <form method="post" action="/adm/grades" name="clickeranalysis">
9829: <input type="hidden" name="symb" value="$symb" />
9830: <input type="hidden" name="command" value="assignclickergrades" />
9831: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
9832: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
9833: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
9834: ENDHEADER
9835: if ($env{'form.gradingmechanism'} eq 'given') {
9836: $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
9837: }
9838: my %responses;
9839: my @questiontitles;
9840: my $errormsg='';
9841: my $number=0;
9842: if ($env{'form.upfiletype'} eq 'iclicker') {
9843: ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
9844: }
9845: if ($env{'form.upfiletype'} eq 'interwrite') {
9846: ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
9847: }
9848: if ($env{'form.upfiletype'} eq 'turning') {
9849: ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
9850: }
9851: $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
9852: '<input type="hidden" name="number" value="'.$number.'" />'.
9853: &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
9854: $env{'form.pcorrect'},$env{'form.pincorrect'}).
9855: '<br />';
9856: if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
9857: $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
9858: return $result;
9859: }
9860: # Remember Question Titles
9861: # FIXME: Possibly need delimiter other than ":"
9862: for (my $i=0;$i<$number;$i++) {
9863: $result.='<input type="hidden" name="question:'.$i.'" value="'.
9864: &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
9865: }
9866: my $correct_count=0;
9867: my $student_count=0;
9868: my $unknown_count=0;
9869: # Match answers with usernames
9870: # FIXME: Possibly need delimiter other than ":"
9871: foreach my $id (keys(%responses)) {
9872: if ($correct_ids{$id}) {
9873: $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
9874: $correct_count++;
9875: } elsif ($clicker_ids{$id}) {
9876: if ($clicker_ids{$id}=~/\,/) {
9877: # More than one user with the same clicker!
9878: $result.="</td>".&Apache::loncommon::end_data_table_row().
9879: &Apache::loncommon::start_data_table_row()."<td>".
9880: &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
9881: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
9882: "<select name='multi".$id."'>";
9883: foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
9884: $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
9885: }
9886: $result.='</select>';
9887: $unknown_count++;
9888: } else {
9889: # Good: found one and only one user with the right clicker
9890: $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
9891: $student_count++;
9892: }
9893: } else {
9894: $result.="</td>".&Apache::loncommon::end_data_table_row().
9895: &Apache::loncommon::start_data_table_row()."<td>".
9896: &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
9897: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
9898: "\n".&mt("Username").": <input type='text' name='uname".$id."' /> ".
9899: "\n".&mt("Domain").": ".
9900: &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).' '.
9901: &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
9902: $unknown_count++;
9903: }
9904: }
9905: $result.='<hr />'.
9906: &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
9907: if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
9908: if ($correct_count==0) {
9909: $errormsg.="Found no correct answers for grading!";
9910: } elsif ($correct_count>1) {
9911: $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
9912: }
9913: }
9914: if ($number<1) {
9915: $errormsg.="Found no questions.";
9916: }
9917: if ($errormsg) {
9918: $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
9919: } else {
9920: $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
9921: }
9922: $result.='</form></td>'.
9923: &Apache::loncommon::end_data_table_row().
9924: &Apache::loncommon::end_data_table();
9925: return $result;
9926: }
9927:
9928: sub iclicker_eval {
9929: my ($questiontitles,$responses)=@_;
9930: my $number=0;
9931: my $errormsg='';
9932: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
9933: my %components=&Apache::loncommon::record_sep($line);
9934: my @entries=map {$components{$_}} (sort(keys(%components)));
9935: if ($entries[0] eq 'Question') {
9936: for (my $i=3;$i<$#entries;$i+=6) {
9937: $$questiontitles[$number]=$entries[$i];
9938: $number++;
9939: }
9940: }
9941: if ($entries[0]=~/^\#/) {
9942: my $id=$entries[0];
9943: my @idresponses;
9944: $id=~s/^[\#0]+//;
9945: for (my $i=0;$i<$number;$i++) {
9946: my $idx=3+$i*6;
9947: $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
9948: push(@idresponses,$entries[$idx]);
9949: }
9950: $$responses{$id}=join(',',@idresponses);
9951: }
9952: }
9953: return ($errormsg,$number);
9954: }
9955:
9956: sub interwrite_eval {
9957: my ($questiontitles,$responses)=@_;
9958: my $number=0;
9959: my $errormsg='';
9960: my $skipline=1;
9961: my $questionnumber=0;
9962: my %idresponses=();
9963: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
9964: my %components=&Apache::loncommon::record_sep($line);
9965: my @entries=map {$components{$_}} (sort(keys(%components)));
9966: if ($entries[1] eq 'Time') { $skipline=0; next; }
9967: if ($entries[1] eq 'Response') { $skipline=1; }
9968: next if $skipline;
9969: if ($entries[0]!=$questionnumber) {
9970: $questionnumber=$entries[0];
9971: $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
9972: $number++;
9973: }
9974: my $id=$entries[4];
9975: $id=~s/^[\#0]+//;
9976: $id=~s/^v\d*\://i;
9977: $id=~s/[\-\:]//g;
9978: $idresponses{$id}[$number]=$entries[6];
9979: }
9980: foreach my $id (keys(%idresponses)) {
9981: $$responses{$id}=join(',',@{$idresponses{$id}});
9982: $$responses{$id}=~s/^\s*\,//;
9983: }
9984: return ($errormsg,$number);
9985: }
9986:
9987: sub turning_eval {
9988: my ($questiontitles,$responses)=@_;
9989: my $number=0;
9990: my $errormsg='';
9991: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
9992: my %components=&Apache::loncommon::record_sep($line);
9993: my @entries=map {$components{$_}} (sort(keys(%components)));
9994: if ($#entries>$number) { $number=$#entries; }
9995: my $id=$entries[0];
9996: my @idresponses;
9997: $id=~s/^[\#0]+//;
9998: unless ($id) { next; }
9999: for (my $idx=1;$idx<=$#entries;$idx++) {
10000: $entries[$idx]=~s/\,/\;/g;
10001: $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
10002: push(@idresponses,$entries[$idx]);
10003: }
10004: $$responses{$id}=join(',',@idresponses);
10005: }
10006: for (my $i=1; $i<=$number; $i++) {
10007: $$questiontitles[$i]=&mt('Question [_1]',$i);
10008: }
10009: return ($errormsg,$number);
10010: }
10011:
10012:
10013: sub assign_clicker_grades {
10014: my ($r,$symb)=@_;
10015: if (!$symb) {return '';}
10016: # See which part we are saving to
10017: my $res_error;
10018: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
10019: if ($res_error) {
10020: return &navmap_errormsg();
10021: }
10022: # FIXME: This should probably look for the first handgradeable part
10023: my $part=$$partlist[0];
10024: # Start screen output
10025: my $result=&Apache::loncommon::start_data_table().
10026: &Apache::loncommon::start_data_table_header_row().
10027: '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
10028: &Apache::loncommon::end_data_table_header_row().
10029: &Apache::loncommon::start_data_table_row().'<td>';
10030: # Get correct result
10031: # FIXME: Possibly need delimiter other than ":"
10032: my @correct=();
10033: my $gradingmechanism=$env{'form.gradingmechanism'};
10034: my $number=$env{'form.number'};
10035: if ($gradingmechanism ne 'attendance') {
10036: foreach my $key (keys(%env)) {
10037: if ($key=~/^form\.correct\:/) {
10038: my @input=split(/\,/,$env{$key});
10039: for (my $i=0;$i<=$#input;$i++) {
10040: if (($correct[$i]) && ($input[$i]) &&
10041: ($correct[$i] ne $input[$i])) {
10042: $result.='<br /><span class="LC_warning">'.
10043: &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
10044: $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
10045: } elsif (($input[$i]) || ($input[$i] eq '0')) {
10046: $correct[$i]=$input[$i];
10047: }
10048: }
10049: }
10050: }
10051: for (my $i=0;$i<$number;$i++) {
10052: if ((!$correct[$i]) && ($correct[$i] ne '0')) {
10053: $result.='<br /><span class="LC_error">'.
10054: &mt('No correct result given for question "[_1]"!',
10055: $env{'form.question:'.$i}).'</span>';
10056: }
10057: }
10058: $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
10059: }
10060: # Start grading
10061: my $pcorrect=$env{'form.pcorrect'};
10062: my $pincorrect=$env{'form.pincorrect'};
10063: my $storecount=0;
10064: my %users=();
10065: foreach my $key (keys(%env)) {
10066: my $user='';
10067: if ($key=~/^form\.student\:(.*)$/) {
10068: $user=$1;
10069: }
10070: if ($key=~/^form\.unknown\:(.*)$/) {
10071: my $id=$1;
10072: if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
10073: $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
10074: } elsif ($env{'form.multi'.$id}) {
10075: $user=$env{'form.multi'.$id};
10076: }
10077: }
10078: if ($user) {
10079: if ($users{$user}) {
10080: $result.='<br /><span class="LC_warning">'.
10081: &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
10082: '</span><br />';
10083: }
10084: $users{$user}=1;
10085: my @answer=split(/\,/,$env{$key});
10086: my $sum=0;
10087: my $realnumber=$number;
10088: for (my $i=0;$i<$number;$i++) {
10089: if ($correct[$i] eq '-') {
10090: $realnumber--;
10091: } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
10092: if ($gradingmechanism eq 'attendance') {
10093: $sum+=$pcorrect;
10094: } elsif ($correct[$i] eq '*') {
10095: $sum+=$pcorrect;
10096: } else {
10097: # We actually grade if correct or not
10098: my $increment=$pincorrect;
10099: # Special case: numerical answer "0"
10100: if ($correct[$i] eq '0') {
10101: if ($answer[$i]=~/^[0\.]+$/) {
10102: $increment=$pcorrect;
10103: }
10104: # General numerical answer, both evaluate to something non-zero
10105: } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
10106: if (1.0*$correct[$i]==1.0*$answer[$i]) {
10107: $increment=$pcorrect;
10108: }
10109: # Must be just alphanumeric
10110: } elsif ($answer[$i] eq $correct[$i]) {
10111: $increment=$pcorrect;
10112: }
10113: $sum+=$increment;
10114: }
10115: }
10116: }
10117: my $ave=$sum/(100*$realnumber);
10118: # Store
10119: my ($username,$domain)=split(/\:/,$user);
10120: my %grades=();
10121: $grades{"resource.$part.solved"}='correct_by_override';
10122: $grades{"resource.$part.awarded"}=$ave;
10123: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
10124: my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
10125: $env{'request.course.id'},
10126: $domain,$username);
10127: if ($returncode ne 'ok') {
10128: $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
10129: } else {
10130: $storecount++;
10131: }
10132: }
10133: }
10134: # We are done
10135: $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
10136: '</td>'.
10137: &Apache::loncommon::end_data_table_row().
10138: &Apache::loncommon::end_data_table();
10139: return $result;
10140: }
10141:
10142: sub navmap_errormsg {
10143: return '<div class="LC_error">'.
10144: &mt('An error occurred retrieving information about resources in the course.').'<br />'.
10145: &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>').
10146: '</div>';
10147: }
10148:
10149: sub startpage {
10150: my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
10151: if ($nomenu) {
10152: $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
10153: } else {
10154: unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
10155: $r->print(&Apache::loncommon::start_page('Grading',$js,
10156: {'bread_crumbs' => $crumbs}));
10157: &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
10158: }
10159: unless ($nodisplayflag) {
10160: $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
10161: }
10162: }
10163:
10164: sub select_problem {
10165: my ($r)=@_;
10166: $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
10167: $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
10168: $r->print('<input type="hidden" name="command" value="gradingmenu" />');
10169: $r->print('<input type="submit" value="'.&mt('Next').' →" /></form>');
10170: }
10171:
10172: sub handler {
10173: my $request=$_[0];
10174: &reset_caches();
10175: if ($request->header_only) {
10176: &Apache::loncommon::content_type($request,'text/html');
10177: $request->send_http_header;
10178: return OK;
10179: }
10180: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
10181:
10182: # see what command we need to execute
10183:
10184: my @commands=&Apache::loncommon::get_env_multiple('form.command');
10185: my $command=$commands[0];
10186:
10187: &init_perm();
10188: if (!$env{'request.course.id'}) {
10189: unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
10190: ($command =~ /^scantronupload/)) {
10191: # Not in a course.
10192: $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
10193: return HTTP_NOT_ACCEPTABLE;
10194: }
10195: } elsif (!%perm) {
10196: $request->internal_redirect('/adm/quickgrades');
10197: return OK;
10198: }
10199: &Apache::loncommon::content_type($request,'text/html');
10200: $request->send_http_header;
10201:
10202: if ($#commands > 0) {
10203: &Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
10204: }
10205:
10206: # see what the symb is
10207:
10208: my $symb=$env{'form.symb'};
10209: unless ($symb) {
10210: (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
10211: $symb=&Apache::lonnet::symbread($url);
10212: }
10213: &Apache::lonenc::check_decrypt(\$symb);
10214:
10215: $ssi_error = 0;
10216: if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
10217: #
10218: # Not called from a resource, but inside a course
10219: #
10220: &startpage($request,undef,[],1,1);
10221: &select_problem($request);
10222: } else {
10223: if ($command eq 'submission' && $perm{'vgr'}) {
10224: my ($stuvcurrent,$stuvdisp,$versionform,$js);
10225: if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
10226: ($stuvcurrent,$stuvdisp,$versionform,$js) =
10227: &choose_task_version_form($symb,$env{'form.student'},
10228: $env{'form.userdom'});
10229: }
10230: &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
10231: if ($versionform) {
10232: $request->print($versionform);
10233: }
10234: $request->print('<br clear="all" />');
10235: ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
10236: } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
10237: my ($stuvcurrent,$stuvdisp,$versionform,$js) =
10238: &choose_task_version_form($symb,$env{'form.student'},
10239: $env{'form.userdom'},
10240: $env{'form.inhibitmenu'});
10241: &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
10242: if ($versionform) {
10243: $request->print($versionform);
10244: }
10245: $request->print('<br clear="all" />');
10246: $request->print(&show_previous_task_version($request,$symb));
10247: } elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
10248: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10249: {href=>'',text=>'Select student'}],1,1);
10250: &pickStudentPage($request,$symb);
10251: } elsif ($command eq 'displayPage' && $perm{'vgr'}) {
10252: &startpage($request,$symb,
10253: [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10254: {href=>'',text=>'Select student'},
10255: {href=>'',text=>'Grade student'}],1,1);
10256: &displayPage($request,$symb);
10257: } elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
10258: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10259: {href=>'',text=>'Select student'},
10260: {href=>'',text=>'Grade student'},
10261: {href=>'',text=>'Store grades'}],1,1);
10262: &updateGradeByPage($request,$symb);
10263: } elsif ($command eq 'processGroup' && $perm{'vgr'}) {
10264: &startpage($request,$symb,[{href=>'',text=>'...'},
10265: {href=>'',text=>'Modify grades'}]);
10266: &processGroup($request,$symb);
10267: } elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
10268: &startpage($request,$symb);
10269: $request->print(&grading_menu($request,$symb));
10270: } elsif ($command eq 'individual' && $perm{'vgr'}) {
10271: &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
10272: $request->print(&submit_options($request,$symb));
10273: } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
10274: &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
10275: $request->print(&listStudents($request,$symb,'graded'));
10276: } elsif ($command eq 'table' && $perm{'vgr'}) {
10277: &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
10278: $request->print(&submit_options_table($request,$symb));
10279: } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
10280: &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
10281: $request->print(&submit_options_sequence($request,$symb));
10282: } elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
10283: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
10284: $request->print(&viewgrades($request,$symb));
10285: } elsif ($command eq 'handgrade' && $perm{'mgr'}) {
10286: &startpage($request,$symb,[{href=>'',text=>'...'},
10287: {href=>'',text=>'Store grades'}]);
10288: $request->print(&processHandGrade($request,$symb));
10289: } elsif ($command eq 'editgrades' && $perm{'mgr'}) {
10290: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
10291: {href=>&href_symb_cmd($symb,'viewgrades').'&group=all§ion=all&Status=Active',
10292: text=>"Modify grades"},
10293: {href=>'', text=>"Store grades"}]);
10294: $request->print(&editgrades($request,$symb));
10295: } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
10296: &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
10297: $request->print(&initialverifyreceipt($request,$symb));
10298: } elsif ($command eq 'verify' && $perm{'vgr'}) {
10299: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
10300: {href=>'',text=>'Verification Result'}]);
10301: $request->print(&verifyreceipt($request,$symb));
10302: } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
10303: &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
10304: $request->print(&process_clicker($request,$symb));
10305: } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
10306: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
10307: {href=>'', text=>'Process clicker file'}]);
10308: $request->print(&process_clicker_file($request,$symb));
10309: } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
10310: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
10311: {href=>'', text=>'Process clicker file'},
10312: {href=>'', text=>'Store grades'}]);
10313: $request->print(&assign_clicker_grades($request,$symb));
10314: } elsif ($command eq 'csvform' && $perm{'mgr'}) {
10315: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10316: $request->print(&upcsvScores_form($request,$symb));
10317: } elsif ($command eq 'csvupload' && $perm{'mgr'}) {
10318: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10319: $request->print(&csvupload($request,$symb));
10320: } elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
10321: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10322: $request->print(&csvuploadmap($request,$symb));
10323: } elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
10324: if ($env{'form.associate'} ne 'Reverse Association') {
10325: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10326: $request->print(&csvuploadoptions($request,$symb));
10327: } else {
10328: if ( $env{'form.upfile_associate'} ne 'reverse' ) {
10329: $env{'form.upfile_associate'} = 'reverse';
10330: } else {
10331: $env{'form.upfile_associate'} = 'forward';
10332: }
10333: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10334: $request->print(&csvuploadmap($request,$symb));
10335: }
10336: } elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
10337: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10338: $request->print(&csvuploadassign($request,$symb));
10339: } elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
10340: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10341: $request->print(&scantron_selectphase($request,undef,$symb));
10342: } elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
10343: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10344: $request->print(&scantron_do_warning($request,$symb));
10345: } elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
10346: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10347: $request->print(&scantron_validate_file($request,$symb));
10348: } elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
10349: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10350: $request->print(&scantron_process_students($request,$symb));
10351: } elsif ($command eq 'scantronupload' &&
10352: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10353: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10354: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10355: $request->print(&scantron_upload_scantron_data($request,$symb));
10356: } elsif ($command eq 'scantronupload_save' &&
10357: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10358: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10359: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10360: $request->print(&scantron_upload_scantron_data_save($request,$symb));
10361: } elsif ($command eq 'scantron_download' &&
10362: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
10363: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10364: $request->print(&scantron_download_scantron_data($request,$symb));
10365: } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
10366: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10367: $request->print(&checkscantron_results($request,$symb));
10368: } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
10369: &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
10370: $request->print(&submit_options_download($request,$symb));
10371: } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
10372: &startpage($request,$symb,
10373: [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
10374: {href=>'', text=>'Download submissions'}]);
10375: &submit_download_link($request,$symb);
10376: } elsif ($command) {
10377: &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
10378: $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
10379: }
10380: }
10381: if ($ssi_error) {
10382: &ssi_print_error($request);
10383: }
10384: if ($env{'form.inhibitmenu'}) {
10385: $request->print(&Apache::loncommon::end_page());
10386: } else {
10387: &Apache::lonquickgrades::endGradeScreen($request);
10388: }
10389: &reset_caches();
10390: return OK;
10391: }
10392:
10393: 1;
10394:
10395: __END__;
10396:
10397:
10398: =head1 NAME
10399:
10400: Apache::grades
10401:
10402: =head1 SYNOPSIS
10403:
10404: Handles the viewing of grades.
10405:
10406: This is part of the LearningOnline Network with CAPA project
10407: described at http://www.lon-capa.org.
10408:
10409: =head1 OVERVIEW
10410:
10411: Do an ssi with retries:
10412: While I'd love to factor out this with the version in lonprintout,
10413: 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
10414: I'm not quite ready to invent (e.g. an ssi_with_retry object).
10415:
10416: At least the logic that drives this has been pulled out into loncommon.
10417:
10418:
10419:
10420: ssi_with_retries - Does the server side include of a resource.
10421: if the ssi call returns an error we'll retry it up to
10422: the number of times requested by the caller.
10423: If we still have a problem, no text is appended to the
10424: output and we set some global variables.
10425: to indicate to the caller an SSI error occurred.
10426: All of this is supposed to deal with the issues described
10427: in LON-CAPA BZ 5631 see:
10428: http://bugs.lon-capa.org/show_bug.cgi?id=5631
10429: by informing the user that this happened.
10430:
10431: Parameters:
10432: resource - The resource to include. This is passed directly, without
10433: interpretation to lonnet::ssi.
10434: form - The form hash parameters that guide the interpretation of the resource
10435:
10436: retries - Number of retries allowed before giving up completely.
10437: Returns:
10438: On success, returns the rendered resource identified by the resource parameter.
10439: Side Effects:
10440: The following global variables can be set:
10441: ssi_error - If an unrecoverable error occurred this becomes true.
10442: It is up to the caller to initialize this to false
10443: if desired.
10444: ssi_error_resource - If an unrecoverable error occurred, this is the value
10445: of the resource that could not be rendered by the ssi
10446: call.
10447: ssi_error_message - The error string fetched from the ssi response
10448: in the event of an error.
10449:
10450:
10451: =head1 HANDLER SUBROUTINE
10452:
10453: ssi_with_retries()
10454:
10455: =head1 SUBROUTINES
10456:
10457: =over
10458:
10459: =head1 Routines to display previous version of a Task for a specific student
10460:
10461: Tasks are graded pass/fail. Students who have yet to pass a particular Task
10462: can receive another opportunity. Access to tasks is slot-based. If a slot
10463: requires a proctor to check-in the student, a new version of the Task will
10464: be created when the student is checked in to the new opportunity.
10465:
10466: If a particular student has tried two or more versions of a particular task,
10467: the submission screen provides a user with vgr privileges (e.g., a Course
10468: Coordinator) the ability to display a previous version worked on by the
10469: student. By default, the current version is displayed. If a previous version
10470: has been selected for display, submission data are only shown that pertain
10471: to that particular version, and the interface to submit grades is not shown.
10472:
10473: =over 4
10474:
10475: =item show_previous_task_version()
10476:
10477: Displays a specified version of a student's Task, as the student sees it.
10478:
10479: Inputs: 2
10480: request - request object
10481: symb - unique symb for current instance of resource
10482:
10483: Output: None.
10484:
10485: Side Effects: calls &show_problem() to print version of Task, with
10486: version contained in form item: $env{'form.previousversion'}
10487:
10488: =item choose_task_version_form()
10489:
10490: Displays a web form used to select which version of a student's view of a
10491: Task should be displayed. Either launches a pop-up window, or replaces
10492: content in existing pop-up, or replaces page in main window.
10493:
10494: Inputs: 4
10495: symb - unique symb for current instance of resource
10496: uname - username of student
10497: udom - domain of student
10498: nomenu - 1 if display is in a pop-up window, and hence no menu
10499: breadcrumbs etc., are displayed
10500:
10501: Output: 4
10502: current - student's current version
10503: displayed - student's version being displayed
10504: result - scalar containing HTML for web form used to switch to
10505: a different version (or a link to close window, if pop-up).
10506: js - javascript for processing selection in versions web form
10507:
10508: Side Effects: None.
10509:
10510: =item previous_display_javascript()
10511:
10512: Inputs: 2
10513: nomenu - 1 if display is in a pop-up window, and hence no menu
10514: breadcrumbs etc., are displayed.
10515: current - student's current version number.
10516:
10517: Output: 1
10518: js - javascript for processing selection in versions web form.
10519:
10520: Side Effects: None.
10521:
10522: =back
10523:
10524: =head1 Routines to process bubblesheet data.
10525:
10526: =over 4
10527:
10528: =item scantron_get_correction() :
10529:
10530: Builds the interface screen to interact with the operator to fix a
10531: specific error condition in a specific scanline
10532:
10533: Arguments:
10534: $r - Apache request object
10535: $i - number of the current scanline
10536: $scan_record - hash ref as returned from &scantron_parse_scanline()
10537: $scan_config - hash ref as returned from &get_scantron_config()
10538: $line - full contents of the current scanline
10539: $error - error condition, valid values are
10540: 'incorrectCODE', 'duplicateCODE',
10541: 'doublebubble', 'missingbubble',
10542: 'duplicateID', 'incorrectID'
10543: $arg - extra information needed
10544: For errors:
10545: - duplicateID - paper number that this studentID was seen before on
10546: - duplicateCODE - array ref of the paper numbers this CODE was
10547: seen on before
10548: - incorrectCODE - current incorrect CODE
10549: - doublebubble - array ref of the bubble lines that have double
10550: bubble errors
10551: - missingbubble - array ref of the bubble lines that have missing
10552: bubble errors
10553:
10554: $randomorder - True if exam folder has randomorder set
10555: $randompick - True if exam folder has randompick set
10556: $respnumlookup - Reference to HASH mapping question numbers in bubble lines
10557: for current line to question number used for same question
10558: in "Master Seqence" (as seen by Course Coordinator).
10559: $startline - Reference to hash where key is question number (0 is first)
10560: and value is number of first bubble line for current student
10561: or code-based randompick and/or randomorder.
10562:
10563:
10564:
10565: =item scantron_get_maxbubble() :
10566:
10567: Arguments:
10568: $nav_error - Reference to scalar which is a flag to indicate a
10569: failure to retrieve a navmap object.
10570: if $nav_error is set to 1 by scantron_get_maxbubble(), the
10571: calling routine should trap the error condition and display the warning
10572: found in &navmap_errormsg().
10573:
10574: $scantron_config - Reference to bubblesheet format configuration hash.
10575:
10576: Returns the maximum number of bubble lines that are expected to
10577: occur. Does this by walking the selected sequence rendering the
10578: resource and then checking &Apache::lonxml::get_problem_counter()
10579: for what the current value of the problem counter is.
10580:
10581: Caches the results to $env{'form.scantron_maxbubble'},
10582: $env{'form.scantron.bubble_lines.n'},
10583: $env{'form.scantron.first_bubble_line.n'} and
10584: $env{"form.scantron.sub_bubblelines.n"}
10585: which are the total number of bubble lines, the number of bubble
10586: lines for response n and number of the first bubble line for response n,
10587: and a comma separated list of numbers of bubble lines for sub-questions
10588: (for optionresponse, matchresponse, and rankresponse items), for response n.
10589:
10590:
10591: =item scantron_validate_missingbubbles() :
10592:
10593: Validates all scanlines in the selected file to not have any
10594: answers that don't have bubbles that have not been verified
10595: to be bubble free.
10596:
10597: =item scantron_process_students() :
10598:
10599: Routine that does the actual grading of the bubblesheet information.
10600:
10601: The parsed scanline hash is added to %env
10602:
10603: Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
10604: foreach resource , with the form data of
10605:
10606: 'submitted' =>'scantron'
10607: 'grade_target' =>'grade',
10608: 'grade_username'=> username of student
10609: 'grade_domain' => domain of student
10610: 'grade_courseid'=> of course
10611: 'grade_symb' => symb of resource to grade
10612:
10613: This triggers a grading pass. The problem grading code takes care
10614: of converting the bubbled letter information (now in %env) into a
10615: valid submission.
10616:
10617: =item scantron_upload_scantron_data() :
10618:
10619: Creates the screen for adding a new bubblesheet data file to a course.
10620:
10621: =item scantron_upload_scantron_data_save() :
10622:
10623: Adds a provided bubble information data file to the course if user
10624: has the correct privileges to do so.
10625:
10626: =item valid_file() :
10627:
10628: Validates that the requested bubble data file exists in the course.
10629:
10630: =item scantron_download_scantron_data() :
10631:
10632: Shows a list of the three internal files (original, corrected,
10633: skipped) for a specific bubblesheet data file that exists in the
10634: course.
10635:
10636: =item scantron_validate_ID() :
10637:
10638: Validates all scanlines in the selected file to not have any
10639: invalid or underspecified student/employee IDs
10640:
10641: =item navmap_errormsg() :
10642:
10643: Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
10644: Should be called whenever the request to instantiate a navmap object fails.
10645:
10646: =back
10647:
10648: =back
10649:
10650: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>