1: # The LearningOnline Network with CAPA
2: # The LON-CAPA Grading handler
3: #
4: # $Id: grades.pm,v 1.725 2014/08/25 22:12:58 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, (
2557: ref($lasthash{$key}) eq 'ARRAY' ?
2558: join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
2559: }
2560: }
2561: if (!@string) {
2562: $string[0] =
2563: '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
2564: }
2565: return (\@string,\$timestamp);
2566: }
2567:
2568: #--- High light keywords, with style choosen by user.
2569: sub keywords_highlight {
2570: my $string = shift;
2571: my $size = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
2572: my $styleon = $env{'form.kwstyle'} eq '' ? '' : $env{'form.kwstyle'};
2573: (my $styleoff = $styleon) =~ s/\</\<\//;
2574: my @keylist = split(/[,\s+]/,$env{'form.keywords'});
2575: foreach my $keyword (@keylist) {
2576: $string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
2577: }
2578: return $string;
2579: }
2580:
2581: # For Tasks provide a mechanism to display previous version for one specific student
2582:
2583: sub show_previous_task_version {
2584: my ($request,$symb) = @_;
2585: if ($symb eq '') {
2586: $request->print(
2587: '<span class="LC_error">'.
2588: &mt('Unable to handle ambiguous references.').
2589: '</span>');
2590: return '';
2591: }
2592: my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
2593: my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
2594: if (!&canview($usec)) {
2595: $request->print(
2596: '<span class="LC_warning">'.
2597: &mt('Unable to view previous version for requested student.').
2598: ' '.&mt('([_1] in section [_2] in course id [_3])',
2599: $uname.':'.$udom,$usec,$env{'request.course.id'}).
2600: '</span>');
2601: return;
2602: }
2603: my $mode = 'both';
2604: my $isTask = ($symb =~/\.task$/);
2605: if ($isTask) {
2606: if ($env{'form.previousversion'} =~ /^\d+$/) {
2607: if ($env{'form.fullname'} eq '') {
2608: $env{'form.fullname'} =
2609: &Apache::loncommon::plainname($uname,$udom,'lastname');
2610: }
2611: my $probtitle=&Apache::lonnet::gettitle($symb);
2612: $request->print("\n\n".
2613: '<div class="LC_grade_show_user">'.
2614: '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
2615: '</h2>'."\n");
2616: &Apache::lonxml::clear_problem_counter();
2617: $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
2618: {'previousversion' => $env{'form.previousversion'} }));
2619: $request->print("\n</div>");
2620: }
2621: }
2622: return;
2623: }
2624:
2625: sub choose_task_version_form {
2626: my ($symb,$uname,$udom,$nomenu) = @_;
2627: my $isTask = ($symb =~/\.task$/);
2628: my ($current,$version,$result,$js,$displayed,$rowtitle);
2629: if ($isTask) {
2630: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
2631: $udom,$uname);
2632: if (($record{'resource.0.version'} eq '') ||
2633: ($record{'resource.0.version'} < 2)) {
2634: return ($record{'resource.0.version'},
2635: $record{'resource.0.version'},$result,$js);
2636: } else {
2637: $current = $record{'resource.0.version'};
2638: }
2639: if ($env{'form.previousversion'}) {
2640: $displayed = $env{'form.previousversion'};
2641: $rowtitle = &mt('Choose another version:')
2642: } else {
2643: $displayed = $current;
2644: $rowtitle = &mt('Show earlier version:');
2645: }
2646: $result = '<div class="LC_left_float">';
2647: my $list;
2648: my $numversions = 0;
2649: for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
2650: if ($i == $current) {
2651: if (!$env{'form.previousversion'} || $nomenu) {
2652: next;
2653: } else {
2654: $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
2655: $numversions ++;
2656: }
2657: } elsif (defined($record{'resource.'.$i.'.0.status'})) {
2658: unless ($i == $env{'form.previousversion'}) {
2659: $numversions ++;
2660: }
2661: $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
2662: }
2663: }
2664: if ($numversions) {
2665: $symb = &HTML::Entities::encode($symb,'<>"&');
2666: $result .=
2667: '<form name="getprev" method="post" action=""'.
2668: ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
2669: &Apache::loncommon::start_data_table().
2670: &Apache::loncommon::start_data_table_row().
2671: '<th align="left">'.$rowtitle.'</th>'.
2672: '<td><select name="version">'.
2673: '<option>'.&mt('Select').'</option>'.
2674: $list.
2675: '</select></td>'.
2676: &Apache::loncommon::end_data_table_row();
2677: unless ($nomenu) {
2678: $result .= &Apache::loncommon::start_data_table_row().
2679: '<th align="left">'.&mt('Open in new window').'</th>'.
2680: '<td><span class="LC_nobreak">'.
2681: '<label><input type="radio" name="prevwin" value="1" />'.
2682: &mt('Yes').'</label>'.
2683: '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
2684: '</span></td>'.
2685: &Apache::loncommon::end_data_table_row();
2686: }
2687: $result .=
2688: &Apache::loncommon::start_data_table_row().
2689: '<th align="left"> </th>'.
2690: '<td>'.
2691: '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
2692: '</td>'.
2693: &Apache::loncommon::end_data_table_row().
2694: &Apache::loncommon::end_data_table().
2695: '</form>';
2696: $js = &previous_display_javascript($nomenu,$current);
2697: } elsif ($displayed && $nomenu) {
2698: $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
2699: } else {
2700: $result .= &mt('No previous versions to show for this student');
2701: }
2702: $result .= '</div>';
2703: }
2704: return ($current,$displayed,$result,$js);
2705: }
2706:
2707: sub previous_display_javascript {
2708: my ($nomenu,$current) = @_;
2709: my $js = <<"JSONE";
2710: <script type="text/javascript">
2711: // <![CDATA[
2712: function previousVersion(uname,udom,symb) {
2713: var current = '$current';
2714: var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
2715: var prevstr = new RegExp("^\\\\d+\$");
2716: if (!prevstr.test(version)) {
2717: return false;
2718: }
2719: var url = '';
2720: if (version == current) {
2721: url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
2722: } else {
2723: url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
2724: }
2725: JSONE
2726: if ($nomenu) {
2727: $js .= <<"JSTWO";
2728: document.location.href = url;
2729: JSTWO
2730: } else {
2731: $js .= <<"JSTHREE";
2732: var newwin = 0;
2733: for (var i=0; i<document.getprev.prevwin.length; i++) {
2734: if (document.getprev.prevwin[i].checked == true) {
2735: newwin = document.getprev.prevwin[i].value;
2736: }
2737: }
2738: if (newwin == 1) {
2739: var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
2740: url = url+'&inhibitmenu=yes';
2741: if (typeof(previousWin) == 'undefined' || previousWin.closed) {
2742: previousWin = window.open(url,'',options,1);
2743: } else {
2744: previousWin.location.href = url;
2745: }
2746: previousWin.focus();
2747: return false;
2748: } else {
2749: document.location.href = url;
2750: return false;
2751: }
2752: JSTHREE
2753: }
2754: $js .= <<"ENDJS";
2755: return false;
2756: }
2757: // ]]>
2758: </script>
2759: ENDJS
2760:
2761: }
2762:
2763: #--- Called from submission routine
2764: sub processHandGrade {
2765: my ($request,$symb) = @_;
2766: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
2767: my $button = $env{'form.gradeOpt'};
2768: my $ngrade = $env{'form.NCT'};
2769: my $ntstu = $env{'form.NTSTU'};
2770: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2771: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2772:
2773: if ($button eq 'Save & Next') {
2774: my $ctr = 0;
2775: while ($ctr < $ngrade) {
2776: my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
2777: my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
2778: if ($errorflag eq 'no_score') {
2779: $ctr++;
2780: next;
2781: }
2782: if ($errorflag eq 'not_allowed') {
2783: $request->print(
2784: '<span class="LC_error">'
2785: .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
2786: .'</span>');
2787: $ctr++;
2788: next;
2789: }
2790: my $includemsg = $env{'form.includemsg'.$ctr};
2791: my ($subject,$message,$msgstatus) = ('','','');
2792: my $restitle = &Apache::lonnet::gettitle($symb);
2793: my ($feedurl,$showsymb) =
2794: &get_feedurl_and_symb($symb,$uname,$udom);
2795: my $messagetail;
2796: if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
2797: $subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
2798: unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
2799: $subject.=' ['.$restitle.']';
2800: my (@msgnum) = split(/,/,$includemsg);
2801: foreach (@msgnum) {
2802: $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
2803: }
2804: $message =&Apache::lonfeedback::clear_out_html($message);
2805: if ($env{'form.withgrades'.$ctr}) {
2806: $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
2807: $messagetail = " for <a href=\"".
2808: $feedurl."?symb=$showsymb\">$restitle</a>";
2809: }
2810: $msgstatus =
2811: &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
2812: $message.$messagetail,
2813: undef,$feedurl,undef,
2814: undef,undef,$showsymb,
2815: $restitle);
2816: $request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
2817: $msgstatus.'<br />');
2818: }
2819: if ($env{'form.collaborator'.$ctr}) {
2820: my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
2821: foreach my $collabstr (@collabstrs) {
2822: my ($part,@collaborators) = split(/:/,$collabstr);
2823: foreach my $collaborator (@collaborators) {
2824: my ($errorflag,$pts,$wgt) =
2825: &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
2826: $env{'form.unamedom'.$ctr},$part);
2827: if ($errorflag eq 'not_allowed') {
2828: $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
2829: next;
2830: } elsif ($message ne '') {
2831: my ($baseurl,$showsymb) =
2832: &get_feedurl_and_symb($symb,$collaborator,
2833: $udom);
2834: if ($env{'form.withgrades'.$ctr}) {
2835: $messagetail = " for <a href=\"".
2836: $baseurl."?symb=$showsymb\">$restitle</a>";
2837: }
2838: $msgstatus =
2839: &Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
2840: }
2841: }
2842: }
2843: }
2844: $ctr++;
2845: }
2846: }
2847:
2848: # if ($env{'form.handgrade'} eq 'yes') {
2849: if (1) {
2850: # Keywords sorted in alphabatical order
2851: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
2852: my %keyhash = ();
2853: $env{'form.keywords'} =~ s/,\s{0,}|\s+/ /g;
2854: $env{'form.keywords'} =~ s/^\s+|\s+$//;
2855: my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
2856: $env{'form.keywords'} = join(' ',@keywords);
2857: $keyhash{$symb.'_keywords'} = $env{'form.keywords'};
2858: $keyhash{$symb.'_subject'} = $env{'form.msgsub'};
2859: $keyhash{$loginuser.'_kwclr'} = $env{'form.kwclr'};
2860: $keyhash{$loginuser.'_kwsize'} = $env{'form.kwsize'};
2861: $keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
2862:
2863: # message center - Order of message gets changed. Blank line is eliminated.
2864: # New messages are saved in env for the next student.
2865: # All messages are saved in nohist_handgrade.db
2866: my ($ctr,$idx) = (1,1);
2867: while ($ctr <= $env{'form.savemsgN'}) {
2868: if ($env{'form.savemsg'.$ctr} ne '') {
2869: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
2870: $idx++;
2871: }
2872: $ctr++;
2873: }
2874: $ctr = 0;
2875: while ($ctr < $ngrade) {
2876: if ($env{'form.newmsg'.$ctr} ne '') {
2877: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2878: $env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2879: $idx++;
2880: }
2881: $ctr++;
2882: }
2883: $env{'form.savemsgN'} = --$idx;
2884: $keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
2885: my $putresult = &Apache::lonnet::put
2886: ('nohist_handgrade',\%keyhash,$cdom,$cnum);
2887: }
2888: # Called by Save & Refresh from Highlight Attribute Window
2889: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
2890: if ($env{'form.refresh'} eq 'on') {
2891: my ($ctr,$total) = (0,0);
2892: while ($ctr < $ngrade) {
2893: $total++ if $env{'form.unamedom'.$ctr} ne '';
2894: $ctr++;
2895: }
2896: $env{'form.NTSTU'}=$ngrade;
2897: $ctr = 0;
2898: while ($ctr < $total) {
2899: my $processUser = $env{'form.unamedom'.$ctr};
2900: ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
2901: $env{'form.fullname'} = $$fullname{$processUser};
2902: &submission($request,$ctr,$total-1,$symb);
2903: $ctr++;
2904: }
2905: return '';
2906: }
2907:
2908: # Get the next/previous one or group of students
2909: my $firststu = $env{'form.unamedom0'};
2910: my $laststu = $env{'form.unamedom'.($ngrade-1)};
2911: my $ctr = 2;
2912: while ($laststu eq '') {
2913: $laststu = $env{'form.unamedom'.($ngrade-$ctr)};
2914: $ctr++;
2915: $laststu = $firststu if ($ctr > $ngrade);
2916: }
2917:
2918: my (@parsedlist,@nextlist);
2919: my ($nextflg) = 0;
2920: foreach my $item (sort
2921: {
2922: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
2923: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
2924: }
2925: return $a cmp $b;
2926: } (keys(%$fullname))) {
2927: # FIXME: this is fishy, looks like the button label
2928: if ($nextflg == 1 && $button =~ /Next$/) {
2929: push(@parsedlist,$item);
2930: }
2931: $nextflg = 1 if ($item eq $laststu);
2932: if ($button eq 'Previous') {
2933: last if ($item eq $firststu);
2934: push(@parsedlist,$item);
2935: }
2936: }
2937: $ctr = 0;
2938: # FIXME: this is fishy, looks like the button label
2939: @parsedlist = reverse @parsedlist if ($button eq 'Previous');
2940: my $res_error;
2941: my ($partlist) = &response_type($symb,\$res_error);
2942: if ($res_error) {
2943: $request->print(&navmap_errormsg());
2944: return;
2945: }
2946: foreach my $student (@parsedlist) {
2947: my $submitonly=$env{'form.submitonly'};
2948: my ($uname,$udom) = split(/:/,$student);
2949:
2950: if ($submitonly eq 'queued') {
2951: my %queue_status =
2952: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
2953: $udom,$uname);
2954: next if (!defined($queue_status{'gradingqueue'}));
2955: }
2956:
2957: if ($submitonly =~ /^(yes|graded|incorrect)$/) {
2958: # my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
2959: my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
2960: my $submitted = 0;
2961: my $ungraded = 0;
2962: my $incorrect = 0;
2963: foreach my $item (keys(%status)) {
2964: $submitted = 1 if ($status{$item} ne 'nothing');
2965: $ungraded = 1 if ($status{$item} =~ /^ungraded/);
2966: $incorrect = 1 if ($status{$item} =~ /^incorrect/);
2967: my ($foo,$partid,$foo1) = split(/\./,$item);
2968: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
2969: $submitted = 0;
2970: }
2971: }
2972: next if (!$submitted && ($submitonly eq 'yes' ||
2973: $submitonly eq 'incorrect' ||
2974: $submitonly eq 'graded'));
2975: next if (!$ungraded && ($submitonly eq 'graded'));
2976: next if (!$incorrect && $submitonly eq 'incorrect');
2977: }
2978: push(@nextlist,$student) if ($ctr < $ntstu);
2979: last if ($ctr == $ntstu);
2980: $ctr++;
2981: }
2982:
2983: $ctr = 0;
2984: my $total = scalar(@nextlist)-1;
2985:
2986: foreach (sort(@nextlist)) {
2987: my ($uname,$udom,$submitter) = split(/:/);
2988: $env{'form.student'} = $uname;
2989: $env{'form.userdom'} = $udom;
2990: $env{'form.fullname'} = $$fullname{$_};
2991: &submission($request,$ctr,$total,$symb);
2992: $ctr++;
2993: }
2994: if ($total < 0) {
2995: my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
2996: $request->print($the_end);
2997: }
2998: return '';
2999: }
3000:
3001: #---- Save the score and award for each student, if changed
3002: sub saveHandGrade {
3003: my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
3004: my @version_parts;
3005: my $usec = &Apache::lonnet::getsection($domain,$stuname,
3006: $env{'request.course.id'});
3007: if (!&canmodify($usec)) { return('not_allowed'); }
3008: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
3009: my @parts_graded;
3010: my %newrecord = ();
3011: my ($pts,$wgt) = ('','');
3012: my %aggregate = ();
3013: my $aggregateflag = 0;
3014: my @parts = split(/:/,$env{'form.partlist'.$newflg});
3015: foreach my $new_part (@parts) {
3016: #collaborator ($submi may vary for different parts
3017: if ($submitter && $new_part ne $part) { next; }
3018: my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
3019: if ($dropMenu eq 'excused') {
3020: if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
3021: $newrecord{'resource.'.$new_part.'.solved'} = 'excused';
3022: if (exists($record{'resource.'.$new_part.'.awarded'})) {
3023: $newrecord{'resource.'.$new_part.'.awarded'} = '';
3024: }
3025: $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
3026: }
3027: } elsif ($dropMenu eq 'reset status'
3028: && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
3029: foreach my $key (keys(%record)) {
3030: if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
3031: }
3032: $newrecord{'resource.'.$new_part.'.regrader'}=
3033: "$env{'user.name'}:$env{'user.domain'}";
3034: my $totaltries = $record{'resource.'.$part.'.tries'};
3035:
3036: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
3037: [$new_part]);
3038: my $aggtries =$totaltries;
3039: if ($last_resets{$new_part}) {
3040: $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
3041: $new_part);
3042: }
3043:
3044: my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
3045: if ($aggtries > 0) {
3046: &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
3047: $aggregateflag = 1;
3048: }
3049: } elsif ($dropMenu eq '') {
3050: $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ?
3051: $env{'form.GD_BOX'.$newflg.'_'.$new_part} :
3052: $env{'form.RADVAL'.$newflg.'_'.$new_part});
3053: if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
3054: next;
3055: }
3056: $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 :
3057: $env{'form.WGT'.$newflg.'_'.$new_part};
3058: my $partial= $pts/$wgt;
3059: if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
3060: #do not update score for part if not changed.
3061: &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
3062: next;
3063: } else {
3064: push(@parts_graded,$new_part);
3065: }
3066: if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
3067: $newrecord{'resource.'.$new_part.'.awarded'} = $partial;
3068: }
3069: my $reckey = 'resource.'.$new_part.'.solved';
3070: if ($partial == 0) {
3071: if ($record{$reckey} ne 'incorrect_by_override') {
3072: $newrecord{$reckey} = 'incorrect_by_override';
3073: }
3074: } else {
3075: if ($record{$reckey} ne 'correct_by_override') {
3076: $newrecord{$reckey} = 'correct_by_override';
3077: }
3078: }
3079: if ($submitter &&
3080: ($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
3081: $newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
3082: }
3083: $newrecord{'resource.'.$new_part.'.regrader'}=
3084: "$env{'user.name'}:$env{'user.domain'}";
3085: }
3086: # unless problem has been graded, set flag to version the submitted files
3087: unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/ ||
3088: $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
3089: $dropMenu eq 'reset status')
3090: {
3091: push(@version_parts,$new_part);
3092: }
3093: }
3094: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3095: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3096:
3097: if (%newrecord) {
3098: if (@version_parts) {
3099: my @changed_keys = &version_portfiles(\%record, \@parts_graded,
3100: $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
3101: @newrecord{@changed_keys} = @record{@changed_keys};
3102: foreach my $new_part (@version_parts) {
3103: &handback_files($request,$symb,$stuname,$domain,$newflg,
3104: $new_part,\%newrecord);
3105: }
3106: }
3107: &Apache::lonnet::cstore(\%newrecord,$symb,
3108: $env{'request.course.id'},$domain,$stuname);
3109: &check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
3110: $cdom,$cnum,$domain,$stuname);
3111: }
3112: if ($aggregateflag) {
3113: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
3114: $cdom,$cnum);
3115: }
3116: return ('',$pts,$wgt);
3117: }
3118:
3119: sub check_and_remove_from_queue {
3120: my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
3121: my @ungraded_parts;
3122: foreach my $part (@{$parts}) {
3123: if ( $record->{ 'resource.'.$part.'.awarded'} eq ''
3124: && $record->{ 'resource.'.$part.'.solved' } ne 'excused'
3125: && $newrecord->{'resource.'.$part.'.awarded'} eq ''
3126: && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
3127: ) {
3128: push(@ungraded_parts, $part);
3129: }
3130: }
3131: if ( !@ungraded_parts ) {
3132: &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
3133: $cnum,$domain,$stuname);
3134: }
3135: }
3136:
3137: sub handback_files {
3138: my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
3139: my $portfolio_root = '/userfiles/portfolio';
3140: my $res_error;
3141: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
3142: if ($res_error) {
3143: $request->print('<br />'.&navmap_errormsg().'<br />');
3144: return;
3145: }
3146: my @handedback;
3147: my $file_msg;
3148: my @part_response_id = &flatten_responseType($responseType);
3149: foreach my $part_response_id (@part_response_id) {
3150: my ($part_id,$resp_id) = @{ $part_response_id };
3151: my $part_resp = join('_',@{ $part_response_id });
3152: if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
3153: for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
3154: # if multiple files are uploaded names will be 'returndoc2','returndoc3'
3155: if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
3156: my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
3157: my ($directory,$answer_file) =
3158: ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
3159: my ($answer_name,$answer_ver,$answer_ext) =
3160: &file_name_version_ext($answer_file);
3161: my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
3162: my $getpropath = 1;
3163: my ($dir_list,$listerror) =
3164: &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
3165: $domain,$stuname,$getpropath);
3166: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
3167: # fix filename
3168: my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
3169: my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
3170: $newflg.'_'.$part_resp.'_returndoc'.$counter,
3171: $save_file_name);
3172: if ($result !~ m|^/uploaded/|) {
3173: $request->print('<br /><span class="LC_error">'.
3174: &mt('An error occurred ([_1]) while trying to upload [_2].',
3175: $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
3176: '</span>');
3177: } else {
3178: # mark the file as read only
3179: push(@handedback,$save_file_name);
3180: if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
3181: $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
3182: }
3183: $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
3184: $file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
3185: }
3186: $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>'));
3187: }
3188: }
3189: }
3190: }
3191: if (@handedback > 0) {
3192: $request->print('<br />');
3193: my @what = ($symb,$env{'request.course.id'},'handback');
3194: &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
3195: my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});
3196: my ($subject,$message);
3197: if (scalar(@handedback) == 1) {
3198: $subject = &mt_user($user_lh,'File Handed Back by Instructor');
3199: $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
3200: } else {
3201: $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
3202: $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
3203: }
3204: $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
3205: $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
3206: &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
3207: my ($feedurl,$showsymb) =
3208: &get_feedurl_and_symb($symb,$domain,$stuname);
3209: my $restitle = &Apache::lonnet::gettitle($symb);
3210: $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
3211: my $msgstatus =
3212: &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
3213: $message,undef,$feedurl,undef,undef,undef,$showsymb,
3214: $restitle);
3215: if ($msgstatus) {
3216: $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
3217: }
3218: }
3219: return;
3220: }
3221:
3222: sub get_feedurl_and_symb {
3223: my ($symb,$uname,$udom) = @_;
3224: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3225: $url = &Apache::lonnet::clutter($url);
3226: my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
3227: $symb,$udom,$uname);
3228: if ($encrypturl =~ /^yes$/i) {
3229: &Apache::lonenc::encrypted(\$url,1);
3230: &Apache::lonenc::encrypted(\$symb,1);
3231: }
3232: return ($url,$symb);
3233: }
3234:
3235: sub get_submitted_files {
3236: my ($udom,$uname,$partid,$respid,$record) = @_;
3237: my @files;
3238: if ($$record{"resource.$partid.$respid.portfiles"}) {
3239: my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
3240: foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
3241: push(@files,$file_url.$file);
3242: }
3243: }
3244: if ($$record{"resource.$partid.$respid.uploadedurl"}) {
3245: push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
3246: }
3247: return (\@files);
3248: }
3249:
3250: # ----------- Provides number of tries since last reset.
3251: sub get_num_tries {
3252: my ($record,$last_reset,$part) = @_;
3253: my $timestamp = '';
3254: my $num_tries = 0;
3255: if ($$record{'version'}) {
3256: for (my $version=$$record{'version'};$version>=1;$version--) {
3257: if (exists($$record{$version.':resource.'.$part.'.solved'})) {
3258: $timestamp = $$record{$version.':timestamp'};
3259: if ($timestamp > $last_reset) {
3260: $num_tries ++;
3261: } else {
3262: last;
3263: }
3264: }
3265: }
3266: }
3267: return $num_tries;
3268: }
3269:
3270: # ----------- Determine decrements required in aggregate totals
3271: sub decrement_aggs {
3272: my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
3273: my %decrement = (
3274: attempts => 0,
3275: users => 0,
3276: correct => 0
3277: );
3278: $decrement{'attempts'} = $aggtries;
3279: if ($solvedstatus =~ /^correct/) {
3280: $decrement{'correct'} = 1;
3281: }
3282: if ($aggtries == $totaltries) {
3283: $decrement{'users'} = 1;
3284: }
3285: foreach my $type (keys(%decrement)) {
3286: $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
3287: }
3288: return;
3289: }
3290:
3291: # ----------- Determine timestamps for last reset of aggregate totals for parts
3292: sub get_last_resets {
3293: my ($symb,$courseid,$partids) =@_;
3294: my %last_resets;
3295: my $cdom = $env{'course.'.$courseid.'.domain'};
3296: my $cname = $env{'course.'.$courseid.'.num'};
3297: my @keys;
3298: foreach my $part (@{$partids}) {
3299: push(@keys,"$symb\0$part\0resettime");
3300: }
3301: my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
3302: $cdom,$cname);
3303: foreach my $part (@{$partids}) {
3304: $last_resets{$part}=$results{"$symb\0$part\0resettime"};
3305: }
3306: return %last_resets;
3307: }
3308:
3309: # ----------- Handles creating versions for portfolio files as answers
3310: sub version_portfiles {
3311: my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
3312: my $version_parts = join('|',@$v_flag);
3313: my @returned_keys;
3314: my $parts = join('|', @$parts_graded);
3315: my $portfolio_root = '/userfiles/portfolio';
3316: foreach my $key (keys(%$record)) {
3317: my $new_portfiles;
3318: if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
3319: my @versioned_portfiles;
3320: my @portfiles = split(/\s*,\s*/,$$record{$key});
3321: foreach my $file (@portfiles) {
3322: &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
3323: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
3324: my ($answer_name,$answer_ver,$answer_ext) =
3325: &file_name_version_ext($answer_file);
3326: my $getpropath = 1;
3327: my ($dir_list,$listerror) =
3328: &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
3329: $stu_name,$getpropath);
3330: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
3331: my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
3332: if ($new_answer ne 'problem getting file') {
3333: push(@versioned_portfiles, $directory.$new_answer);
3334: &Apache::lonnet::mark_as_readonly($domain,$stu_name,
3335: [$directory.$new_answer],
3336: [$symb,$env{'request.course.id'},'graded']);
3337: }
3338: }
3339: $$record{$key} = join(',',@versioned_portfiles);
3340: push(@returned_keys,$key);
3341: }
3342: }
3343: return (@returned_keys);
3344: }
3345:
3346: sub get_next_version {
3347: my ($answer_name, $answer_ext, $dir_list) = @_;
3348: my $version;
3349: if (ref($dir_list) eq 'ARRAY') {
3350: foreach my $row (@{$dir_list}) {
3351: my ($file) = split(/\&/,$row,2);
3352: my ($file_name,$file_version,$file_ext) =
3353: &file_name_version_ext($file);
3354: if (($file_name eq $answer_name) &&
3355: ($file_ext eq $answer_ext)) {
3356: # gets here if filename and extension match,
3357: # regardless of version
3358: if ($file_version ne '') {
3359: # a versioned file is found so save it for later
3360: if ($file_version > $version) {
3361: $version = $file_version;
3362: }
3363: }
3364: }
3365: }
3366: }
3367: $version ++;
3368: return($version);
3369: }
3370:
3371: sub version_selected_portfile {
3372: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
3373: my ($answer_name,$answer_ver,$answer_ext) =
3374: &file_name_version_ext($file_name);
3375: my $new_answer;
3376: $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
3377: if($env{'form.copy'} eq '-1') {
3378: $new_answer = 'problem getting file';
3379: } else {
3380: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
3381: my $copy_result = &Apache::lonnet::finishuserfileupload(
3382: $stu_name,$domain,'copy',
3383: '/portfolio'.$directory.$new_answer);
3384: }
3385: return ($new_answer);
3386: }
3387:
3388: sub file_name_version_ext {
3389: my ($file)=@_;
3390: my @file_parts = split(/\./, $file);
3391: my ($name,$version,$ext);
3392: if (@file_parts > 1) {
3393: $ext=pop(@file_parts);
3394: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
3395: $version=pop(@file_parts);
3396: }
3397: $name=join('.',@file_parts);
3398: } else {
3399: $name=join('.',@file_parts);
3400: }
3401: return($name,$version,$ext);
3402: }
3403:
3404: #--------------------------------------------------------------------------------------
3405: #
3406: #-------------------------- Next few routines handles grading by section or whole class
3407: #
3408: #--- Javascript to handle grading by section or whole class
3409: sub viewgrades_js {
3410: my ($request) = shift;
3411:
3412: my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
3413: $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
3414: function writePoint(partid,weight,point) {
3415: var radioButton = document.classgrade["RADVAL_"+partid];
3416: var textbox = document.classgrade["TEXTVAL_"+partid];
3417: if (point == "textval") {
3418: point = document.classgrade["TEXTVAL_"+partid].value;
3419: if (isNaN(point) || parseFloat(point) < 0) {
3420: alert("$alertmsg"+parseFloat(point));
3421: var resetbox = false;
3422: for (var i=0; i<radioButton.length; i++) {
3423: if (radioButton[i].checked) {
3424: textbox.value = i;
3425: resetbox = true;
3426: }
3427: }
3428: if (!resetbox) {
3429: textbox.value = "";
3430: }
3431: return;
3432: }
3433: if (parseFloat(point) > parseFloat(weight)) {
3434: var resp = confirm("You entered a value ("+parseFloat(point)+
3435: ") greater than the weight for the part. Accept?");
3436: if (resp == false) {
3437: textbox.value = "";
3438: return;
3439: }
3440: }
3441: for (var i=0; i<radioButton.length; i++) {
3442: radioButton[i].checked=false;
3443: if (parseFloat(point) == i) {
3444: radioButton[i].checked=true;
3445: }
3446: }
3447:
3448: } else {
3449: textbox.value = parseFloat(point);
3450: }
3451: for (i=0;i<document.classgrade.total.value;i++) {
3452: var user = document.classgrade["ctr"+i].value;
3453: user = user.replace(new RegExp(':', 'g'),"_");
3454: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3455: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3456: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3457: if (saveval != "correct") {
3458: scorename.value = point;
3459: if (selname[0].selected != true) {
3460: selname[0].selected = true;
3461: }
3462: }
3463: }
3464: document.classgrade["SELVAL_"+partid][0].selected = true;
3465: }
3466:
3467: function writeRadText(partid,weight) {
3468: var selval = document.classgrade["SELVAL_"+partid];
3469: var radioButton = document.classgrade["RADVAL_"+partid];
3470: var override = document.classgrade["FORCE_"+partid].checked;
3471: var textbox = document.classgrade["TEXTVAL_"+partid];
3472: if (selval[1].selected || selval[2].selected) {
3473: for (var i=0; i<radioButton.length; i++) {
3474: radioButton[i].checked=false;
3475:
3476: }
3477: textbox.value = "";
3478:
3479: for (i=0;i<document.classgrade.total.value;i++) {
3480: var user = document.classgrade["ctr"+i].value;
3481: user = user.replace(new RegExp(':', 'g'),"_");
3482: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3483: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3484: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3485: if ((saveval != "correct") || override) {
3486: scorename.value = "";
3487: if (selval[1].selected) {
3488: selname[1].selected = true;
3489: } else {
3490: selname[2].selected = true;
3491: if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value))
3492: {document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
3493: }
3494: }
3495: }
3496: } else {
3497: for (i=0;i<document.classgrade.total.value;i++) {
3498: var user = document.classgrade["ctr"+i].value;
3499: user = user.replace(new RegExp(':', 'g'),"_");
3500: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3501: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3502: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3503: if ((saveval != "correct") || override) {
3504: scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
3505: selname[0].selected = true;
3506: }
3507: }
3508: }
3509: }
3510:
3511: function changeSelect(partid,user) {
3512: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
3513: var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
3514: var point = textbox.value;
3515: var weight = document.classgrade["weight_"+partid].value;
3516:
3517: if (isNaN(point) || parseFloat(point) < 0) {
3518: alert("$alertmsg"+parseFloat(point));
3519: textbox.value = "";
3520: return;
3521: }
3522: if (parseFloat(point) > parseFloat(weight)) {
3523: var resp = confirm("You entered a value ("+parseFloat(point)+
3524: ") greater than the weight of the part. Accept?");
3525: if (resp == false) {
3526: textbox.value = "";
3527: return;
3528: }
3529: }
3530: selval[0].selected = true;
3531: }
3532:
3533: function changeOneScore(partid,user) {
3534: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
3535: if (selval[1].selected || selval[2].selected) {
3536: document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
3537: if (selval[2].selected) {
3538: document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
3539: }
3540: }
3541: }
3542:
3543: function resetEntry(numpart) {
3544: for (ctpart=0;ctpart<numpart;ctpart++) {
3545: var partid = document.classgrade["partid_"+ctpart].value;
3546: var radioButton = document.classgrade["RADVAL_"+partid];
3547: var textbox = document.classgrade["TEXTVAL_"+partid];
3548: var selval = document.classgrade["SELVAL_"+partid];
3549: for (var i=0; i<radioButton.length; i++) {
3550: radioButton[i].checked=false;
3551:
3552: }
3553: textbox.value = "";
3554: selval[0].selected = true;
3555:
3556: for (i=0;i<document.classgrade.total.value;i++) {
3557: var user = document.classgrade["ctr"+i].value;
3558: user = user.replace(new RegExp(':', 'g'),"_");
3559: var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3560: resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
3561: var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
3562: resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
3563: var saveselval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3564: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3565: if (saveselval == "excused") {
3566: if (selname[1].selected == false) { selname[1].selected = true;}
3567: } else {
3568: if (selname[0].selected == false) {selname[0].selected = true};
3569: }
3570: }
3571: }
3572: }
3573:
3574: VIEWJAVASCRIPT
3575: }
3576:
3577: #--- show scores for a section or whole class w/ option to change/update a score
3578: sub viewgrades {
3579: my ($request,$symb) = @_;
3580: &viewgrades_js($request);
3581:
3582: #need to make sure we have the correct data for later EXT calls,
3583: #thus invalidate the cache
3584: &Apache::lonnet::devalidatecourseresdata(
3585: $env{'course.'.$env{'request.course.id'}.'.num'},
3586: $env{'course.'.$env{'request.course.id'}.'.domain'});
3587: &Apache::lonnet::clear_EXT_cache_status();
3588:
3589: my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
3590:
3591: #view individual student submission form - called using Javascript viewOneStudent
3592: $result.=&jscriptNform($symb);
3593:
3594: #beginning of class grading form
3595: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
3596: $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
3597: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
3598: '<input type="hidden" name="command" value="editgrades" />'."\n".
3599: &build_section_inputs().
3600: '<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
3601:
3602: my ($common_header,$specific_header);
3603: if ($env{'form.section'} eq 'all') {
3604: $common_header = &mt('Assign Common Grade to Class');
3605: $specific_header = &mt('Assign Grade to Specific Students in Class');
3606: } elsif ($env{'form.section'} eq 'none') {
3607: $common_header = &mt('Assign Common Grade to Students in no Section');
3608: $specific_header = &mt('Assign Grade to Specific Students in no Section');
3609: } else {
3610: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3611: $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
3612: $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
3613: }
3614: $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
3615: #radio buttons/text box for assigning points for a section or class.
3616: #handles different parts of a problem
3617: my $res_error;
3618: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
3619: if ($res_error) {
3620: return &navmap_errormsg();
3621: }
3622: my %weight = ();
3623: my $ctsparts = 0;
3624: my %seen = ();
3625: my @part_response_id = &flatten_responseType($responseType);
3626: foreach my $part_response_id (@part_response_id) {
3627: my ($partid,$respid) = @{ $part_response_id };
3628: my $part_resp = join('_',@{ $part_response_id });
3629: next if $seen{$partid};
3630: $seen{$partid}++;
3631: my $handgrade=$$handgrade{$part_resp};
3632: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
3633: $weight{$partid} = $wgt eq '' ? '1' : $wgt;
3634:
3635: my $display_part=&get_display_part($partid,$symb);
3636: my $radio.='<table border="0"><tr>';
3637: my $ctr = 0;
3638: while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
3639: $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
3640: 'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
3641: ','.$ctr.')" />'.$ctr."</label></td>\n";
3642: $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
3643: $ctr++;
3644: }
3645: $radio.='</tr></table>';
3646: my $line = '<input type="text" name="TEXTVAL_'.
3647: $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
3648: $partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
3649: $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
3650: $line.= '<td><b>'.&mt('Grade Status').':</b>'.
3651: '<select name="SELVAL_'.$partid.'" '.
3652: 'onchange="javascript:writeRadText(\''.$partid.'\','.
3653: $weight{$partid}.')"> '.
3654: '<option selected="selected"> </option>'.
3655: '<option value="excused">'.&mt('excused').'</option>'.
3656: '<option value="reset status">'.&mt('reset status').'</option>'.
3657: '</select></td>'.
3658: '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
3659: $line.='<input type="hidden" name="partid_'.
3660: $ctsparts.'" value="'.$partid.'" />'."\n";
3661: $line.='<input type="hidden" name="weight_'.
3662: $partid.'" value="'.$weight{$partid}.'" />'."\n";
3663:
3664: $result.=
3665: &Apache::loncommon::start_data_table_row()."\n".
3666: '<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>'.
3667: &Apache::loncommon::end_data_table_row()."\n";
3668: $ctsparts++;
3669: }
3670: $result.=&Apache::loncommon::end_data_table()."\n".
3671: '<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
3672: $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
3673: 'onclick="javascript:resetEntry('.$ctsparts.');" />';
3674:
3675: #table listing all the students in a section/class
3676: #header of table
3677: $result.= '<h3>'.$specific_header.'</h3>'.
3678: &Apache::loncommon::start_data_table().
3679: &Apache::loncommon::start_data_table_header_row().
3680: '<th>'.&mt('No.').'</th>'.
3681: '<th>'.&nameUserString('header')."</th>\n";
3682: my $partserror;
3683: my (@parts) = sort(&getpartlist($symb,\$partserror));
3684: if ($partserror) {
3685: return &navmap_errormsg();
3686: }
3687: my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
3688: my @partids = ();
3689: foreach my $part (@parts) {
3690: my $display=&Apache::lonnet::metadata($url,$part.'.display');
3691: my $narrowtext = &mt('Tries');
3692: $display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
3693: if (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
3694: my ($partid) = &split_part_type($part);
3695: push(@partids,$partid);
3696: #
3697: # FIXME: Looks like $display looks at English text
3698: #
3699: my $display_part=&get_display_part($partid,$symb);
3700: if ($display =~ /^Partial Credit Factor/) {
3701: $result.='<th>'.
3702: &mt('Score Part: [_1][_2](weight = [_3])',
3703: $display_part,'<br />',$weight{$partid}).'</th>'."\n";
3704: next;
3705:
3706: } else {
3707: if ($display =~ /Problem Status/) {
3708: my $grade_status_mt = &mt('Grade Status');
3709: $display =~ s{Problem Status}{$grade_status_mt<br />};
3710: }
3711: my $part_mt = &mt('Part:');
3712: $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
3713: }
3714:
3715: $result.='<th>'.$display.'</th>'."\n";
3716: }
3717: $result.=&Apache::loncommon::end_data_table_header_row();
3718:
3719: my %last_resets =
3720: &get_last_resets($symb,$env{'request.course.id'},\@partids);
3721:
3722: #get info for each student
3723: #list all the students - with points and grade status
3724: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
3725: my $ctr = 0;
3726: foreach (sort
3727: {
3728: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
3729: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
3730: }
3731: return $a cmp $b;
3732: } (keys(%$fullname))) {
3733: $ctr++;
3734: $result.=&viewstudentgrade($symb,$env{'request.course.id'},
3735: $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
3736: }
3737: $result.=&Apache::loncommon::end_data_table();
3738: $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
3739: $result.='<input type="button" value="'.&mt('Save').'" '.
3740: 'onclick="javascript:submit();" target="_self" /></form>'."\n";
3741: if (scalar(%$fullname) eq 0) {
3742: my $colspan=3+scalar(@parts);
3743: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3744: my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
3745: $result='<span class="LC_warning">'.
3746: &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
3747: $section_display, $stu_status).
3748: '</span>';
3749: }
3750: return $result;
3751: }
3752:
3753: #--- call by previous routine to display each student
3754: sub viewstudentgrade {
3755: my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
3756: my ($uname,$udom) = split(/:/,$student);
3757: my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
3758: my %aggregates = ();
3759: my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
3760: '<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
3761: "\n".$ctr.' </td><td> '.
3762: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
3763: '\');" target="_self">'.$fullname.'</a> '.
3764: '<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
3765: $student=~s/:/_/; # colon doen't work in javascript for names
3766: foreach my $apart (@$parts) {
3767: my ($part,$type) = &split_part_type($apart);
3768: my $score=$record{"resource.$part.$type"};
3769: $result.='<td align="center">';
3770: my ($aggtries,$totaltries);
3771: unless (exists($aggregates{$part})) {
3772: $totaltries = $record{'resource.'.$part.'.tries'};
3773:
3774: $aggtries = $totaltries;
3775: if ($$last_resets{$part}) {
3776: $aggtries = &get_num_tries(\%record,$$last_resets{$part},
3777: $part);
3778: }
3779: $result.='<input type="hidden" name="'.
3780: 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
3781: $result.='<input type="hidden" name="'.
3782: 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
3783: $aggregates{$part} = 1;
3784: }
3785: if ($type eq 'awarded') {
3786: my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
3787: $result.='<input type="hidden" name="'.
3788: 'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
3789: $result.='<input type="text" name="'.
3790: 'GD_'.$student.'_'.$part.'_awarded" '.
3791: 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
3792: '\')" value="'.$pts.'" size="4" /></td>'."\n";
3793: } elsif ($type eq 'solved') {
3794: my ($status,$foo)=split(/_/,$score,2);
3795: $status = 'nothing' if ($status eq '');
3796: $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
3797: $part.'_solved_s" value="'.$status.'" />'."\n";
3798: $result.=' <select name="'.
3799: 'GD_'.$student.'_'.$part.'_solved" '.
3800: 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
3801: $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>'
3802: : '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
3803: $result.='<option value="reset status">'.&mt('reset status').'</option>';
3804: $result.="</select> </td>\n";
3805: } else {
3806: $result.='<input type="hidden" name="'.
3807: 'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
3808: "\n";
3809: $result.='<input type="text" name="'.
3810: 'GD_'.$student.'_'.$part.'_'.$type.'" '.
3811: 'value="'.$score.'" size="4" /></td>'."\n";
3812: }
3813: }
3814: $result.=&Apache::loncommon::end_data_table_row();
3815: return $result;
3816: }
3817:
3818: #--- change scores for all the students in a section/class
3819: # record does not get update if unchanged
3820: sub editgrades {
3821: my ($request,$symb) = @_;
3822:
3823: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3824: my $title='<h2>'.&mt('Current Grade Status').'</h2>';
3825: $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
3826:
3827: my $result= &Apache::loncommon::start_data_table().
3828: &Apache::loncommon::start_data_table_header_row().
3829: '<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
3830: '<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
3831: my %scoreptr = (
3832: 'correct' =>'correct_by_override',
3833: 'incorrect'=>'incorrect_by_override',
3834: 'excused' =>'excused',
3835: 'ungraded' =>'ungraded_attempted',
3836: 'credited' =>'credit_attempted',
3837: 'nothing' => '',
3838: );
3839: my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
3840:
3841: my (@partid);
3842: my %weight = ();
3843: my %columns = ();
3844: my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
3845:
3846: my $partserror;
3847: my (@parts) = sort(&getpartlist($symb,\$partserror));
3848: if ($partserror) {
3849: return &navmap_errormsg();
3850: }
3851: my $header;
3852: while ($ctr < $env{'form.totalparts'}) {
3853: my $partid = $env{'form.partid_'.$ctr};
3854: push(@partid,$partid);
3855: $weight{$partid} = $env{'form.weight_'.$partid};
3856: $ctr++;
3857: }
3858: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3859: foreach my $partid (@partid) {
3860: $header .= '<th align="center">'.&mt('Old Score').'</th>'.
3861: '<th align="center">'.&mt('New Score').'</th>';
3862: $columns{$partid}=2;
3863: foreach my $stores (@parts) {
3864: my ($part,$type) = &split_part_type($stores);
3865: if ($part !~ m/^\Q$partid\E/) { next;}
3866: if ($type eq 'awarded' || $type eq 'solved') { next; }
3867: my $display=&Apache::lonnet::metadata($url,$stores.'.display');
3868: $display =~ s/\[Part: \Q$part\E\]//;
3869: my $narrowtext = &mt('Tries');
3870: $display =~ s/Number of Attempts/$narrowtext/;
3871: $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
3872: '<th align="center">'.&mt('New').' '.$display.'</th>';
3873: $columns{$partid}+=2;
3874: }
3875: }
3876: foreach my $partid (@partid) {
3877: my $display_part=&get_display_part($partid,$symb);
3878: $result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
3879: &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
3880: '</th>';
3881:
3882: }
3883: $result .= &Apache::loncommon::end_data_table_header_row().
3884: &Apache::loncommon::start_data_table_header_row().
3885: $header.
3886: &Apache::loncommon::end_data_table_header_row();
3887: my @noupdate;
3888: my ($updateCtr,$noupdateCtr) = (1,1);
3889: for ($i=0; $i<$env{'form.total'}; $i++) {
3890: my $line;
3891: my $user = $env{'form.ctr'.$i};
3892: my ($uname,$udom)=split(/:/,$user);
3893: my %newrecord;
3894: my $updateflag = 0;
3895: $line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
3896: my $usec=$classlist->{"$uname:$udom"}[5];
3897: if (!&canmodify($usec)) {
3898: my $numcols=scalar(@partid)*4+2;
3899: push(@noupdate,
3900: $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
3901: &mt('Not allowed to modify student')."</span></td></tr>");
3902: next;
3903: }
3904: my %aggregate = ();
3905: my $aggregateflag = 0;
3906: $user=~s/:/_/; # colon doen't work in javascript for names
3907: foreach (@partid) {
3908: my $old_aw = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
3909: my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
3910: my $old_part = $old_aw eq '' ? '' : $old_part_pcr;
3911: my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
3912: my $awarded = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
3913: my $pcr = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
3914: my $partial = $awarded eq '' ? '' : $pcr;
3915: my $score;
3916: if ($partial eq '') {
3917: $score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
3918: } elsif ($partial > 0) {
3919: $score = 'correct_by_override';
3920: } elsif ($partial == 0) {
3921: $score = 'incorrect_by_override';
3922: }
3923: my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
3924: $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
3925:
3926: $newrecord{'resource.'.$_.'.regrader'}=
3927: "$env{'user.name'}:$env{'user.domain'}";
3928: if ($dropMenu eq 'reset status' &&
3929: $old_score ne '') { # ignore if no previous attempts => nothing to reset
3930: $newrecord{'resource.'.$_.'.tries'} = '';
3931: $newrecord{'resource.'.$_.'.solved'} = '';
3932: $newrecord{'resource.'.$_.'.award'} = '';
3933: $newrecord{'resource.'.$_.'.awarded'} = '';
3934: $updateflag = 1;
3935: if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
3936: my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
3937: my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
3938: my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
3939: &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
3940: $aggregateflag = 1;
3941: }
3942: } elsif (!($old_part eq $partial && $old_score eq $score)) {
3943: $updateflag = 1;
3944: $newrecord{'resource.'.$_.'.awarded'} = $partial if $partial ne '';
3945: $newrecord{'resource.'.$_.'.solved'} = $score;
3946: $rec_update++;
3947: }
3948:
3949: $line .= '<td align="center">'.$old_aw.' </td>'.
3950: '<td align="center">'.$awarded.
3951: ($score eq 'excused' ? $score : '').' </td>';
3952:
3953:
3954: my $partid=$_;
3955: foreach my $stores (@parts) {
3956: my ($part,$type) = &split_part_type($stores);
3957: if ($part !~ m/^\Q$partid\E/) { next;}
3958: if ($type eq 'awarded' || $type eq 'solved') { next; }
3959: my $old_aw = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
3960: my $awarded = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
3961: if ($awarded ne '' && $awarded ne $old_aw) {
3962: $newrecord{'resource.'.$part.'.'.$type}= $awarded;
3963: $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
3964: $updateflag=1;
3965: }
3966: $line .= '<td align="center">'.$old_aw.' </td>'.
3967: '<td align="center">'.$awarded.' </td>';
3968: }
3969: }
3970: $line.="\n";
3971:
3972: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3973: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3974:
3975: if ($updateflag) {
3976: $count++;
3977: &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
3978: $udom,$uname);
3979:
3980: if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
3981: $cnum,$udom,$uname)) {
3982: # need to figure out if should be in queue.
3983: my %record =
3984: &Apache::lonnet::restore($symb,$env{'request.course.id'},
3985: $udom,$uname);
3986: my $all_graded = 1;
3987: my $none_graded = 1;
3988: foreach my $part (@parts) {
3989: if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
3990: $all_graded = 0;
3991: } else {
3992: $none_graded = 0;
3993: }
3994: }
3995:
3996: if ($all_graded || $none_graded) {
3997: &Apache::bridgetask::remove_from_queue('gradingqueue',
3998: $symb,$cdom,$cnum,
3999: $udom,$uname);
4000: }
4001: }
4002:
4003: $result.=&Apache::loncommon::start_data_table_row().
4004: '<td align="right"> '.$updateCtr.' </td>'.$line.
4005: &Apache::loncommon::end_data_table_row();
4006: $updateCtr++;
4007: } else {
4008: push(@noupdate,
4009: '<td align="right"> '.$noupdateCtr.' </td>'.$line);
4010: $noupdateCtr++;
4011: }
4012: if ($aggregateflag) {
4013: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
4014: $cdom,$cnum);
4015: }
4016: }
4017: if (@noupdate) {
4018: # my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
4019: my $numcols=scalar(@partid)*4+2;
4020: $result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
4021: '<td align="center" colspan="'.$numcols.'">'.
4022: &mt('No Changes Occurred For the Students Below').
4023: '</td>'.
4024: &Apache::loncommon::end_data_table_row();
4025: foreach my $line (@noupdate) {
4026: $result.=
4027: &Apache::loncommon::start_data_table_row().
4028: $line.
4029: &Apache::loncommon::end_data_table_row();
4030: }
4031: }
4032: $result .= &Apache::loncommon::end_data_table();
4033: my $msg = '<p><b>'.
4034: &mt('Number of records updated = [_1] for [quant,_2,student].',
4035: $rec_update,$count).'</b><br />'.
4036: '<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
4037: '</b></p>';
4038: return $title.$msg.$result;
4039: }
4040:
4041: sub split_part_type {
4042: my ($partstr) = @_;
4043: my ($temp,@allparts)=split(/_/,$partstr);
4044: my $type=pop(@allparts);
4045: my $part=join('_',@allparts);
4046: return ($part,$type);
4047: }
4048:
4049: #------------- end of section for handling grading by section/class ---------
4050: #
4051: #----------------------------------------------------------------------------
4052:
4053:
4054: #----------------------------------------------------------------------------
4055: #
4056: #-------------------------- Next few routines handles grading by csv upload
4057: #
4058: #--- Javascript to handle csv upload
4059: sub csvupload_javascript_reverse_associate {
4060: my $error1=&mt('You need to specify the username or the student/employee ID');
4061: my $error2=&mt('You need to specify at least one grading field');
4062: return(<<ENDPICK);
4063: function verify(vf) {
4064: var foundsomething=0;
4065: var founduname=0;
4066: var foundID=0;
4067: for (i=0;i<=vf.nfields.value;i++) {
4068: tw=eval('vf.f'+i+'.selectedIndex');
4069: if (i==0 && tw!=0) { foundID=1; }
4070: if (i==1 && tw!=0) { founduname=1; }
4071: if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
4072: }
4073: if (founduname==0 && foundID==0) {
4074: alert('$error1');
4075: return;
4076: }
4077: if (foundsomething==0) {
4078: alert('$error2');
4079: return;
4080: }
4081: vf.submit();
4082: }
4083: function flip(vf,tf) {
4084: var nw=eval('vf.f'+tf+'.selectedIndex');
4085: var i;
4086: for (i=0;i<=vf.nfields.value;i++) {
4087: //can not pick the same destination field for both name and domain
4088: if (((i ==0)||(i ==1)) &&
4089: ((tf==0)||(tf==1)) &&
4090: (i!=tf) &&
4091: (eval('vf.f'+i+'.selectedIndex')==nw)) {
4092: eval('vf.f'+i+'.selectedIndex=0;')
4093: }
4094: }
4095: }
4096: ENDPICK
4097: }
4098:
4099: sub csvupload_javascript_forward_associate {
4100: my $error1=&mt('You need to specify the username or the student/employee ID');
4101: my $error2=&mt('You need to specify at least one grading field');
4102: return(<<ENDPICK);
4103: function verify(vf) {
4104: var foundsomething=0;
4105: var founduname=0;
4106: var foundID=0;
4107: for (i=0;i<=vf.nfields.value;i++) {
4108: tw=eval('vf.f'+i+'.selectedIndex');
4109: if (tw==1) { foundID=1; }
4110: if (tw==2) { founduname=1; }
4111: if (tw>3) { foundsomething=1; }
4112: }
4113: if (founduname==0 && foundID==0) {
4114: alert('$error1');
4115: return;
4116: }
4117: if (foundsomething==0) {
4118: alert('$error2');
4119: return;
4120: }
4121: vf.submit();
4122: }
4123: function flip(vf,tf) {
4124: var nw=eval('vf.f'+tf+'.selectedIndex');
4125: var i;
4126: //can not pick the same destination field twice
4127: for (i=0;i<=vf.nfields.value;i++) {
4128: if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
4129: eval('vf.f'+i+'.selectedIndex=0;')
4130: }
4131: }
4132: }
4133: ENDPICK
4134: }
4135:
4136: sub csvuploadmap_header {
4137: my ($request,$symb,$datatoken,$distotal)= @_;
4138: my $javascript;
4139: if ($env{'form.upfile_associate'} eq 'reverse') {
4140: $javascript=&csvupload_javascript_reverse_associate();
4141: } else {
4142: $javascript=&csvupload_javascript_forward_associate();
4143: }
4144:
4145: $symb = &Apache::lonenc::check_encrypt($symb);
4146: $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
4147: &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
4148: &mt('Associate entries from the uploaded file with as many fields as you can.'));
4149: my $reverse=&mt("Reverse Association");
4150: $request->print(<<ENDPICK);
4151: <br />
4152: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
4153: <input type="hidden" name="associate" value="" />
4154: <input type="hidden" name="phase" value="three" />
4155: <input type="hidden" name="datatoken" value="$datatoken" />
4156: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
4157: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
4158: <input type="hidden" name="upfile_associate"
4159: value="$env{'form.upfile_associate'}" />
4160: <input type="hidden" name="symb" value="$symb" />
4161: <input type="hidden" name="command" value="csvuploadoptions" />
4162: <hr />
4163: ENDPICK
4164: $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
4165: return '';
4166:
4167: }
4168:
4169: sub csvupload_fields {
4170: my ($symb,$errorref) = @_;
4171: my (@parts) = &getpartlist($symb,$errorref);
4172: if (ref($errorref)) {
4173: if ($$errorref) {
4174: return;
4175: }
4176: }
4177:
4178: my @fields=(['ID','Student/Employee ID'],
4179: ['username','Student Username'],
4180: ['domain','Student Domain']);
4181: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
4182: foreach my $part (sort(@parts)) {
4183: my @datum;
4184: my $display=&Apache::lonnet::metadata($url,$part.'.display');
4185: my $name=$part;
4186: if (!$display) { $display = $name; }
4187: @datum=($name,$display);
4188: if ($name=~/^stores_(.*)_awarded/) {
4189: push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
4190: }
4191: push(@fields,\@datum);
4192: }
4193: return (@fields);
4194: }
4195:
4196: sub csvuploadmap_footer {
4197: my ($request,$i,$keyfields) =@_;
4198: my $buttontext = &mt('Assign Grades');
4199: $request->print(<<ENDPICK);
4200: </table>
4201: <input type="hidden" name="nfields" value="$i" />
4202: <input type="hidden" name="keyfields" value="$keyfields" />
4203: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
4204: </form>
4205: ENDPICK
4206: }
4207:
4208: sub checkforfile_js {
4209: my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
4210: my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
4211: function checkUpload(formname) {
4212: if (formname.upfile.value == "") {
4213: alert("$alertmsg");
4214: return false;
4215: }
4216: formname.submit();
4217: }
4218: CSVFORMJS
4219: return $result;
4220: }
4221:
4222: sub upcsvScores_form {
4223: my ($request,$symb) = @_;
4224: if (!$symb) {return '';}
4225: my $result=&checkforfile_js();
4226: $result.=&Apache::loncommon::start_data_table().
4227: &Apache::loncommon::start_data_table_header_row().
4228: '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
4229: &Apache::loncommon::end_data_table_header_row().
4230: &Apache::loncommon::start_data_table_row().'<td>';
4231: my $upload=&mt("Upload Scores");
4232: my $upfile_select=&Apache::loncommon::upfile_select_html();
4233: my $ignore=&mt('Ignore First Line');
4234: $symb = &Apache::lonenc::check_encrypt($symb);
4235: $result.=<<ENDUPFORM;
4236: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
4237: <input type="hidden" name="symb" value="$symb" />
4238: <input type="hidden" name="command" value="csvuploadmap" />
4239: $upfile_select
4240: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
4241: </form>
4242: ENDUPFORM
4243: $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
4244: &mt("How do I create a CSV file from a spreadsheet")).
4245: '</td>'.
4246: &Apache::loncommon::end_data_table_row().
4247: &Apache::loncommon::end_data_table();
4248: return $result;
4249: }
4250:
4251:
4252: sub csvuploadmap {
4253: my ($request,$symb)= @_;
4254: if (!$symb) {return '';}
4255:
4256: my $datatoken;
4257: if (!$env{'form.datatoken'}) {
4258: $datatoken=&Apache::loncommon::upfile_store($request);
4259: } else {
4260: $datatoken=$env{'form.datatoken'};
4261: &Apache::loncommon::load_tmp_file($request);
4262: }
4263: my @records=&Apache::loncommon::upfile_record_sep();
4264: &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
4265: my ($i,$keyfields);
4266: if (@records) {
4267: my $fieldserror;
4268: my @fields=&csvupload_fields($symb,\$fieldserror);
4269: if ($fieldserror) {
4270: $request->print(&navmap_errormsg());
4271: return;
4272: }
4273: if ($env{'form.upfile_associate'} eq 'reverse') {
4274: &Apache::loncommon::csv_print_samples($request,\@records);
4275: $i=&Apache::loncommon::csv_print_select_table($request,\@records,
4276: \@fields);
4277: foreach (@fields) { $keyfields.=$_->[0].','; }
4278: chop($keyfields);
4279: } else {
4280: unshift(@fields,['none','']);
4281: $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
4282: \@fields);
4283: foreach my $rec (@records) {
4284: my %temp = &Apache::loncommon::record_sep($rec);
4285: if (%temp) {
4286: $keyfields=join(',',sort(keys(%temp)));
4287: last;
4288: }
4289: }
4290: }
4291: }
4292: &csvuploadmap_footer($request,$i,$keyfields);
4293:
4294: return '';
4295: }
4296:
4297: sub csvuploadoptions {
4298: my ($request,$symb)= @_;
4299: my $overwrite=&mt('Overwrite any existing score');
4300: $request->print(<<ENDPICK);
4301: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
4302: <input type="hidden" name="command" value="csvuploadassign" />
4303: <p>
4304: <label>
4305: <input type="checkbox" name="overwite_scores" checked="checked" />
4306: $overwrite
4307: </label>
4308: </p>
4309: ENDPICK
4310: my %fields=&get_fields();
4311: if (!defined($fields{'domain'})) {
4312: my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
4313: $request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
4314: }
4315: foreach my $key (sort(keys(%env))) {
4316: if ($key !~ /^form\.(.*)$/) { next; }
4317: my $cleankey=$1;
4318: if ($cleankey eq 'command') { next; }
4319: $request->print('<input type="hidden" name="'.$cleankey.
4320: '" value="'.$env{$key}.'" />'."\n");
4321: }
4322: # FIXME do a check for any duplicated user ids...
4323: # FIXME do a check for any invalid user ids?...
4324: $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
4325: <hr /></form>'."\n");
4326: return '';
4327: }
4328:
4329: sub get_fields {
4330: my %fields;
4331: my @keyfields = split(/\,/,$env{'form.keyfields'});
4332: for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
4333: if ($env{'form.upfile_associate'} eq 'reverse') {
4334: if ($env{'form.f'.$i} ne 'none') {
4335: $fields{$keyfields[$i]}=$env{'form.f'.$i};
4336: }
4337: } else {
4338: if ($env{'form.f'.$i} ne 'none') {
4339: $fields{$env{'form.f'.$i}}=$keyfields[$i];
4340: }
4341: }
4342: }
4343: return %fields;
4344: }
4345:
4346: sub csvuploadassign {
4347: my ($request,$symb)= @_;
4348: if (!$symb) {return '';}
4349: my $error_msg = '';
4350: &Apache::loncommon::load_tmp_file($request);
4351: my @gradedata = &Apache::loncommon::upfile_record_sep();
4352: my %fields=&get_fields();
4353: my $courseid=$env{'request.course.id'};
4354: my ($classlist) = &getclasslist('all',0);
4355: my @notallowed;
4356: my @skipped;
4357: my @warnings;
4358: my $countdone=0;
4359: foreach my $grade (@gradedata) {
4360: my %entries=&Apache::loncommon::record_sep($grade);
4361: my $domain;
4362: if ($entries{$fields{'domain'}}) {
4363: $domain=$entries{$fields{'domain'}};
4364: } else {
4365: $domain=$env{'form.default_domain'};
4366: }
4367: $domain=~s/\s//g;
4368: my $username=$entries{$fields{'username'}};
4369: $username=~s/\s//g;
4370: if (!$username) {
4371: my $id=$entries{$fields{'ID'}};
4372: $id=~s/\s//g;
4373: my %ids=&Apache::lonnet::idget($domain,$id);
4374: $username=$ids{$id};
4375: }
4376: if (!exists($$classlist{"$username:$domain"})) {
4377: my $id=$entries{$fields{'ID'}};
4378: $id=~s/\s//g;
4379: if ($id) {
4380: push(@skipped,"$id:$domain");
4381: } else {
4382: push(@skipped,"$username:$domain");
4383: }
4384: next;
4385: }
4386: my $usec=$classlist->{"$username:$domain"}[5];
4387: if (!&canmodify($usec)) {
4388: push(@notallowed,"$username:$domain");
4389: next;
4390: }
4391: my %points;
4392: my %grades;
4393: foreach my $dest (keys(%fields)) {
4394: if ($dest eq 'ID' || $dest eq 'username' ||
4395: $dest eq 'domain') { next; }
4396: if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
4397: if ($dest=~/stores_(.*)_points/) {
4398: my $part=$1;
4399: my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
4400: $symb,$domain,$username);
4401: if ($wgt) {
4402: $entries{$fields{$dest}}=~s/\s//g;
4403: my $pcr=$entries{$fields{$dest}} / $wgt;
4404: my $award=($pcr == 0) ? 'incorrect_by_override'
4405: : 'correct_by_override';
4406: if ($pcr>1) {
4407: push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
4408: }
4409: $grades{"resource.$part.awarded"}=$pcr;
4410: $grades{"resource.$part.solved"}=$award;
4411: $points{$part}=1;
4412: } else {
4413: $error_msg = "<br />" .
4414: &mt("Some point values were assigned"
4415: ." for problems with a weight "
4416: ."of zero. These values were "
4417: ."ignored.");
4418: }
4419: } else {
4420: if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
4421: if ($dest=~/stores_(.*)_solved/) { if ($points{$1}) {next;} }
4422: my $store_key=$dest;
4423: $store_key=~s/^stores/resource/;
4424: $store_key=~s/_/\./g;
4425: $grades{$store_key}=$entries{$fields{$dest}};
4426: }
4427: }
4428: if (! %grades) {
4429: push(@skipped,&mt("[_1]: no data to save","$username:$domain"));
4430: } else {
4431: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
4432: my $result=&Apache::lonnet::cstore(\%grades,$symb,
4433: $env{'request.course.id'},
4434: $domain,$username);
4435: if ($result eq 'ok') {
4436: # Successfully stored
4437: $request->print('.');
4438: # Remove from grading queue
4439: &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
4440: $env{'course.'.$env{'request.course.id'}.'.domain'},
4441: $env{'course.'.$env{'request.course.id'}.'.num'},
4442: $domain,$username);
4443: $countdone++;
4444: } else {
4445: $request->print("<p><span class=\"LC_error\">".
4446: &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
4447: "$username:$domain",$result)."</span></p>");
4448: }
4449: $request->rflush();
4450: }
4451: }
4452: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
4453: if (@warnings) {
4454: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
4455: $request->print(join(', ',@warnings));
4456: }
4457: if (@skipped) {
4458: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
4459: $request->print(join(', ',@skipped));
4460: }
4461: if (@notallowed) {
4462: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
4463: $request->print(join(', ',@notallowed));
4464: }
4465: $request->print("<br />\n");
4466: return $error_msg;
4467: }
4468: #------------- end of section for handling csv file upload ---------
4469: #
4470: #-------------------------------------------------------------------
4471: #
4472: #-------------- Next few routines handle grading by page/sequence
4473: #
4474: #--- Select a page/sequence and a student to grade
4475: sub pickStudentPage {
4476: my ($request,$symb) = @_;
4477:
4478: my $alertmsg = &mt('Please select the student you wish to grade.');
4479: $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
4480:
4481: function checkPickOne(formname) {
4482: if (radioSelection(formname.student) == null) {
4483: alert("$alertmsg");
4484: return;
4485: }
4486: ptr = pullDownSelection(formname.selectpage);
4487: formname.page.value = formname["page"+ptr].value;
4488: formname.title.value = formname["title"+ptr].value;
4489: formname.submit();
4490: }
4491:
4492: LISTJAVASCRIPT
4493: &commonJSfunctions($request);
4494:
4495: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4496: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4497: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4498:
4499: my $result='<h3><span class="LC_info"> '.
4500: &mt('Manual Grading by Page or Sequence').'</span></h3>';
4501:
4502: $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
4503: my $map_error;
4504: my ($titles,$symbx) = &getSymbMap($map_error);
4505: if ($map_error) {
4506: $request->print(&navmap_errormsg());
4507: return;
4508: }
4509: my ($curpage) =&Apache::lonnet::decode_symb($symb);
4510: # my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb);
4511: # my $type=($curpage =~ /\.(page|sequence)/);
4512:
4513: # Collection of hidden fields
4514: my $ctr=0;
4515: foreach (@$titles) {
4516: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4517: $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
4518: $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
4519: $ctr++;
4520: }
4521: $result.='<input type="hidden" name="page" />'."\n".
4522: '<input type="hidden" name="title" />'."\n";
4523:
4524: $result.=&build_section_inputs();
4525: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
4526: $result.='<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
4527: '<input type="hidden" name="command" value="displayPage" />'."\n".
4528: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
4529:
4530: # Show grading options
4531: $result.=&Apache::lonhtmlcommon::start_pick_box();
4532: my $select = '<select name="selectpage">'."\n";
4533: $ctr=0;
4534: foreach (@$titles) {
4535: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4536: $select.='<option value="'.$ctr.'"'.
4537: ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
4538: '>'.$showtitle.'</option>'."\n";
4539: $ctr++;
4540: }
4541: $select.= '</select>';
4542:
4543: $result.=
4544: &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
4545: .$select
4546: .&Apache::lonhtmlcommon::row_closure();
4547:
4548: $result.=
4549: &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
4550: .'<label><input type="radio" name="vProb" value="no"'
4551: .' checked="checked" /> '.&mt('no').' </label>'."\n"
4552: .'<label><input type="radio" name="vProb" value="yes" />'
4553: .&mt('yes').'</label>'."\n"
4554: .&Apache::lonhtmlcommon::row_closure();
4555:
4556: $result.=
4557: &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
4558: .'<label><input type="radio" name="lastSub" value="none" /> '
4559: .&mt('none').' </label>'."\n"
4560: .'<label><input type="radio" name="lastSub" value="datesub"'
4561: .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
4562: .'<label><input type="radio" name="lastSub" value="all" /> '
4563: .&mt('all submissions with details').' </label>'
4564: .&Apache::lonhtmlcommon::row_closure();
4565:
4566: $result.=
4567: &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
4568: .'<input type="text" name="CODE" value="" />'
4569: .&Apache::lonhtmlcommon::row_closure(1)
4570: .&Apache::lonhtmlcommon::end_pick_box();
4571:
4572: # Show list of students to select for grading
4573: $result.='<br /><input type="button" '.
4574: 'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' →" /><br />'."\n";
4575:
4576: $request->print($result);
4577:
4578: my $studentTable.=' <b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
4579: &Apache::loncommon::start_data_table().
4580: &Apache::loncommon::start_data_table_header_row().
4581: '<th align="right"> '.&mt('No.').'</th>'.
4582: '<th>'.&nameUserString('header').'</th>'.
4583: '<th align="right"> '.&mt('No.').'</th>'.
4584: '<th>'.&nameUserString('header').'</th>'.
4585: &Apache::loncommon::end_data_table_header_row();
4586:
4587: my (undef,undef,$fullname) = &getclasslist($getsec,'1');
4588: my $ptr = 1;
4589: foreach my $student (sort
4590: {
4591: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
4592: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
4593: }
4594: return $a cmp $b;
4595: } (keys(%$fullname))) {
4596: my ($uname,$udom) = split(/:/,$student);
4597: $studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
4598: : '</td>');
4599: $studentTable.='<td align="right">'.$ptr.' </td>';
4600: $studentTable.='<td> <label><input type="radio" name="student" value="'.$student.'" /> '
4601: .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
4602: $studentTable.=
4603: ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row()
4604: : '');
4605: $ptr++;
4606: }
4607: if ($ptr%2 == 0) {
4608: $studentTable.='</td><td> </td><td> </td>'.
4609: &Apache::loncommon::end_data_table_row();
4610: }
4611: $studentTable.=&Apache::loncommon::end_data_table()."\n";
4612: $studentTable.='<input type="button" '.
4613: 'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' →" /></form>'."\n";
4614:
4615: $request->print($studentTable);
4616:
4617: return '';
4618: }
4619:
4620: sub getSymbMap {
4621: my ($map_error) = @_;
4622: my $navmap = Apache::lonnavmaps::navmap->new();
4623: unless (ref($navmap)) {
4624: if (ref($map_error)) {
4625: $$map_error = 'navmap';
4626: }
4627: return;
4628: }
4629: my %symbx = ();
4630: my @titles = ();
4631: my $minder = 0;
4632:
4633: # Gather every sequence that has problems.
4634: my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
4635: 1,0,1);
4636: for my $sequence ($navmap->getById('0.0'), @sequences) {
4637: if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
4638: my $title = $minder.'.'.
4639: &HTML::Entities::encode($sequence->compTitle(),'"\'&');
4640: push(@titles, $title); # minder in case two titles are identical
4641: $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
4642: $minder++;
4643: }
4644: }
4645: return \@titles,\%symbx;
4646: }
4647:
4648: #
4649: #--- Displays a page/sequence w/wo problems, w/wo submissions
4650: sub displayPage {
4651: my ($request,$symb) = @_;
4652: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4653: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4654: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4655: my $pageTitle = $env{'form.page'};
4656: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
4657: my ($uname,$udom) = split(/:/,$env{'form.student'});
4658: my $usec=$classlist->{$env{'form.student'}}[5];
4659:
4660: #need to make sure we have the correct data for later EXT calls,
4661: #thus invalidate the cache
4662: &Apache::lonnet::devalidatecourseresdata(
4663: $env{'course.'.$env{'request.course.id'}.'.num'},
4664: $env{'course.'.$env{'request.course.id'}.'.domain'});
4665: &Apache::lonnet::clear_EXT_cache_status();
4666:
4667: if (!&canview($usec)) {
4668: $request->print(
4669: '<span class="LC_warning">'.
4670: &mt('Unable to view requested student. ([_1])',
4671: $env{'form.student'}).
4672: '</span>');
4673: return;
4674: }
4675: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
4676: $result.='<h3> '.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
4677: '</h3>'."\n";
4678: $env{'form.CODE'} = uc($env{'form.CODE'});
4679: if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
4680: $result.='<h3> '.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
4681: } else {
4682: delete($env{'form.CODE'});
4683: }
4684: &sub_page_js($request);
4685: $request->print($result);
4686:
4687: my $navmap = Apache::lonnavmaps::navmap->new();
4688: unless (ref($navmap)) {
4689: $request->print(&navmap_errormsg());
4690: return;
4691: }
4692: my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
4693: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
4694: if (!$map) {
4695: $request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
4696: return;
4697: }
4698: my $iterator = $navmap->getIterator($map->map_start(),
4699: $map->map_finish());
4700:
4701: my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
4702: '<input type="hidden" name="command" value="gradeByPage" />'."\n".
4703: '<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
4704: '<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
4705: '<input type="hidden" name="page" value="'.$pageTitle.'" />'."\n".
4706: '<input type="hidden" name="title" value="'.$env{'form.title'}.'" />'."\n".
4707: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
4708: '<input type="hidden" name="overRideScore" value="no" />'."\n";
4709:
4710: if (defined($env{'form.CODE'})) {
4711: $studentTable.=
4712: '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
4713: }
4714: my $checkIcon = '<img alt="'.&mt('Check Mark').
4715: '" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
4716:
4717: $studentTable.=' <span class="LC_info">'.
4718: &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
4719: '</span>'."\n".
4720: &Apache::loncommon::start_data_table().
4721: &Apache::loncommon::start_data_table_header_row().
4722: '<th>'.&mt('Prob.').'</th>'.
4723: '<th> '.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
4724: &Apache::loncommon::end_data_table_header_row();
4725:
4726: &Apache::lonxml::clear_problem_counter();
4727: my ($depth,$question,$prob) = (1,1,1);
4728: $iterator->next(); # skip the first BEGIN_MAP
4729: my $curRes = $iterator->next(); # for "current resource"
4730: while ($depth > 0) {
4731: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
4732: if($curRes == $iterator->END_MAP) { $depth--; }
4733:
4734: if (ref($curRes) && $curRes->is_problem()) {
4735: my $parts = $curRes->parts();
4736: my $title = $curRes->compTitle();
4737: my $symbx = $curRes->symb();
4738: $studentTable.=
4739: &Apache::loncommon::start_data_table_row().
4740: '<td align="center" valign="top" >'.$prob.
4741: (scalar(@{$parts}) == 1 ? ''
4742: : '<br />('.&mt('[_1]parts',
4743: scalar(@{$parts}).' ').')'
4744: ).
4745: '</td>';
4746: $studentTable.='<td valign="top">';
4747: my %form = ('CODE' => $env{'form.CODE'},);
4748: if ($env{'form.vProb'} eq 'yes' ) {
4749: $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
4750: undef,'both',\%form);
4751: } else {
4752: my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
4753: $companswer =~ s|<form(.*?)>||g;
4754: $companswer =~ s|</form>||g;
4755: # while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
4756: # $companswer =~ s/$1/ /ms;
4757: # $request->print('match='.$1."<br />\n");
4758: # }
4759: # $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
4760: $studentTable.=' <b>'.$title.'</b> <br /> <b>'.&mt('Correct answer').':</b><br />'.$companswer;
4761: }
4762:
4763: my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
4764:
4765: if ($env{'form.lastSub'} eq 'datesub') {
4766: if ($record{'version'} eq '') {
4767: $studentTable.='<br /> <span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
4768: } else {
4769: my %responseType = ();
4770: foreach my $partid (@{$parts}) {
4771: my @responseIds =$curRes->responseIds($partid);
4772: my @responseType =$curRes->responseType($partid);
4773: my %responseIds;
4774: for (my $i=0;$i<=$#responseIds;$i++) {
4775: $responseIds{$responseIds[$i]}=$responseType[$i];
4776: }
4777: $responseType{$partid} = \%responseIds;
4778: }
4779: $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
4780:
4781: }
4782: } elsif ($env{'form.lastSub'} eq 'all') {
4783: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
4784: $studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
4785: $env{'request.course.id'},
4786: '','.submission');
4787:
4788: }
4789: if (&canmodify($usec)) {
4790: $studentTable.=&gradeBox_start();
4791: foreach my $partid (@{$parts}) {
4792: $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
4793: $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
4794: $question++;
4795: }
4796: $studentTable.=&gradeBox_end();
4797: $prob++;
4798: }
4799: $studentTable.='</td></tr>';
4800:
4801: }
4802: $curRes = $iterator->next();
4803: }
4804:
4805: $studentTable.=
4806: '</table>'."\n".
4807: '<input type="button" value="'.&mt('Save').'" '.
4808: 'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
4809: '</form>'."\n";
4810: $request->print($studentTable);
4811:
4812: return '';
4813: }
4814:
4815: sub displaySubByDates {
4816: my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
4817: my $isCODE=0;
4818: my $isTask = ($symb =~/\.task$/);
4819: if (exists($record->{'resource.CODE'})) { $isCODE=1; }
4820: my $studentTable=&Apache::loncommon::start_data_table().
4821: &Apache::loncommon::start_data_table_header_row().
4822: '<th>'.&mt('Date/Time').'</th>'.
4823: ($isCODE?'<th>'.&mt('CODE').'</th>':'').
4824: ($isTask?'<th>'.&mt('Version').'</th>':'').
4825: '<th>'.&mt('Submission').'</th>'.
4826: '<th>'.&mt('Status').'</th>'.
4827: &Apache::loncommon::end_data_table_header_row();
4828: my ($version);
4829: my %mark;
4830: my %orders;
4831: $mark{'correct_by_student'} = $checkIcon;
4832: if (!exists($$record{'1:timestamp'})) {
4833: return '<br /> <span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
4834: }
4835:
4836: my $interaction;
4837: my $no_increment = 1;
4838: my %lastrndseed;
4839: for ($version=1;$version<=$$record{'version'};$version++) {
4840: my $timestamp =
4841: &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
4842: if (exists($$record{$version.':resource.0.version'})) {
4843: $interaction = $$record{$version.':resource.0.version'};
4844: }
4845: if ($isTask && $env{'form.previousversion'}) {
4846: next unless ($interaction == $env{'form.previousversion'});
4847: }
4848: my $where = ($isTask ? "$version:resource.$interaction"
4849: : "$version:resource");
4850: $studentTable.=&Apache::loncommon::start_data_table_row().
4851: '<td>'.$timestamp.'</td>';
4852: if ($isCODE) {
4853: $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
4854: }
4855: if ($isTask) {
4856: $studentTable.='<td>'.$interaction.'</td>';
4857: }
4858: my @versionKeys = split(/\:/,$$record{$version.':keys'});
4859: my @displaySub = ();
4860: foreach my $partid (@{$parts}) {
4861: my ($hidden,$type);
4862: $type = $$record{$version.':resource.'.$partid.'.type'};
4863: if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
4864: $hidden = 1;
4865: }
4866: my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
4867: : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
4868:
4869: # next if ($$record{"$version:resource.$partid.solved"} eq '');
4870: my $display_part=&get_display_part($partid,$symb);
4871: foreach my $matchKey (@matchKey) {
4872: if (exists($$record{$version.':'.$matchKey}) &&
4873: $$record{$version.':'.$matchKey} ne '') {
4874:
4875: my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
4876: : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
4877: $displaySub[0].='<span class="LC_nobreak">';
4878: $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
4879: .' <span class="LC_internal_info">'
4880: .'('.&mt('Response ID: [_1]',$responseId).')'
4881: .'</span>'
4882: .' <b>';
4883: if ($hidden) {
4884: $displaySub[0].= &mt('Anonymous Survey').'</b>';
4885: } else {
4886: my ($trial,$rndseed,$newvariation);
4887: if ($type eq 'randomizetry') {
4888: $trial = $$record{"$where.$partid.tries"};
4889: $rndseed = $$record{"$where.$partid.rndseed"};
4890: }
4891: if ($$record{"$where.$partid.tries"} eq '') {
4892: $displaySub[0].=&mt('Trial not counted');
4893: } else {
4894: $displaySub[0].=&mt('Trial: [_1]',
4895: $$record{"$where.$partid.tries"});
4896: if ($rndseed || $lastrndseed{$partid}) {
4897: if ($rndseed ne $lastrndseed{$partid}) {
4898: $newvariation = ' ('.&mt('New variation this try').')';
4899: }
4900: }
4901: $lastrndseed{$partid} = $rndseed;
4902: }
4903: my $responseType=($isTask ? 'Task'
4904: : $responseType->{$partid}->{$responseId});
4905: if (!exists($orders{$partid})) { $orders{$partid}={}; }
4906: if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
4907: $orders{$partid}->{$responseId}=
4908: &get_order($partid,$responseId,$symb,$uname,$udom,
4909: $no_increment,$type,$trial,$rndseed);
4910: }
4911: $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
4912: $displaySub[0].=' '.
4913: &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
4914: }
4915: }
4916: }
4917: if (exists($$record{"$where.$partid.checkedin"})) {
4918: $displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
4919: $$record{"$where.$partid.checkedin"},
4920: $$record{"$where.$partid.checkedin.slot"}).
4921: '<br />';
4922: }
4923: if (exists $$record{"$where.$partid.award"}) {
4924: $displaySub[1].='<b>'.&mt('Part:').'</b> '.$display_part.' '.
4925: lc($$record{"$where.$partid.award"}).' '.
4926: $mark{$$record{"$where.$partid.solved"}}.
4927: '<br />';
4928: }
4929: if (exists $$record{"$where.$partid.regrader"}) {
4930: $displaySub[2].=$$record{"$where.$partid.regrader"}.
4931: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
4932: } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
4933: $displaySub[2].=
4934: $$record{"$version:resource.$partid.regrader"}.
4935: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
4936: }
4937: }
4938: # needed because old essay regrader has not parts info
4939: if (exists $$record{"$version:resource.regrader"}) {
4940: $displaySub[2].=$$record{"$version:resource.regrader"};
4941: }
4942: $studentTable.='<td>'.$displaySub[0].' </td><td>'.$displaySub[1];
4943: if ($displaySub[2]) {
4944: $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
4945: }
4946: $studentTable.=' </td>'.
4947: &Apache::loncommon::end_data_table_row();
4948: }
4949: $studentTable.=&Apache::loncommon::end_data_table();
4950: return $studentTable;
4951: }
4952:
4953: sub updateGradeByPage {
4954: my ($request,$symb) = @_;
4955:
4956: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4957: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4958: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4959: my $pageTitle = $env{'form.page'};
4960: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
4961: my ($uname,$udom) = split(/:/,$env{'form.student'});
4962: my $usec=$classlist->{$env{'form.student'}}[5];
4963: if (!&canmodify($usec)) {
4964: $request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
4965: return;
4966: }
4967: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
4968: $result.='<h3> '.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
4969: '</h3>'."\n";
4970:
4971: $request->print($result);
4972:
4973:
4974: my $navmap = Apache::lonnavmaps::navmap->new();
4975: unless (ref($navmap)) {
4976: $request->print(&navmap_errormsg());
4977: return;
4978: }
4979: my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
4980: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
4981: if (!$map) {
4982: $request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
4983: return;
4984: }
4985: my $iterator = $navmap->getIterator($map->map_start(),
4986: $map->map_finish());
4987:
4988: my $studentTable=
4989: &Apache::loncommon::start_data_table().
4990: &Apache::loncommon::start_data_table_header_row().
4991: '<th align="center"> '.&mt('Prob.').' </th>'.
4992: '<th> '.&mt('Title').' </th>'.
4993: '<th> '.&mt('Previous Score').' </th>'.
4994: '<th> '.&mt('New Score').' </th>'.
4995: &Apache::loncommon::end_data_table_header_row();
4996:
4997: $iterator->next(); # skip the first BEGIN_MAP
4998: my $curRes = $iterator->next(); # for "current resource"
4999: my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
5000: while ($depth > 0) {
5001: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
5002: if($curRes == $iterator->END_MAP) { $depth--; }
5003:
5004: if (ref($curRes) && $curRes->is_problem()) {
5005: my $parts = $curRes->parts();
5006: my $title = $curRes->compTitle();
5007: my $symbx = $curRes->symb();
5008: $studentTable.=
5009: &Apache::loncommon::start_data_table_row().
5010: '<td align="center" valign="top" >'.$prob.
5011: (scalar(@{$parts}) == 1 ? ''
5012: : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
5013: .')').'</td>';
5014: $studentTable.='<td valign="top"> <b>'.$title.'</b> </td>';
5015:
5016: my %newrecord=();
5017: my @displayPts=();
5018: my %aggregate = ();
5019: my $aggregateflag = 0;
5020: foreach my $partid (@{$parts}) {
5021: my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
5022: my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
5023:
5024: my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ?
5025: $env{'form.WGT'.$question.'_'.$partid} : 1;
5026: my $partial = $newpts/$wgt;
5027: my $score;
5028: if ($partial > 0) {
5029: $score = 'correct_by_override';
5030: } elsif ($newpts ne '') { #empty is taken as 0
5031: $score = 'incorrect_by_override';
5032: }
5033: my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
5034: if ($dropMenu eq 'excused') {
5035: $partial = '';
5036: $score = 'excused';
5037: } elsif ($dropMenu eq 'reset status'
5038: && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
5039: $newrecord{'resource.'.$partid.'.tries'} = 0;
5040: $newrecord{'resource.'.$partid.'.solved'} = '';
5041: $newrecord{'resource.'.$partid.'.award'} = '';
5042: $newrecord{'resource.'.$partid.'.awarded'} = 0;
5043: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
5044: $changeflag++;
5045: $newpts = '';
5046:
5047: my $aggtries = $env{'form.aggtries'.$question.'_'.$partid};
5048: my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
5049: my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
5050: if ($aggtries > 0) {
5051: &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
5052: $aggregateflag = 1;
5053: }
5054: }
5055: my $display_part=&get_display_part($partid,$curRes->symb());
5056: my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
5057: $displayPts[0].=' <b>'.&mt('Part').':</b> '.$display_part.' = '.
5058: (($oldstatus eq 'excused') ? 'excused' : $oldpts).
5059: ' <br />';
5060: $displayPts[1].=' <b>'.&mt('Part').':</b> '.$display_part.' = '.
5061: (($score eq 'excused') ? 'excused' : $newpts).
5062: ' <br />';
5063: $question++;
5064: next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
5065:
5066: $newrecord{'resource.'.$partid.'.awarded'} = $partial if $partial ne '';
5067: $newrecord{'resource.'.$partid.'.solved'} = $score if $score ne '';
5068: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
5069: if (scalar(keys(%newrecord)) > 0);
5070:
5071: $changeflag++;
5072: }
5073: if (scalar(keys(%newrecord)) > 0) {
5074: my %record =
5075: &Apache::lonnet::restore($symbx,$env{'request.course.id'},
5076: $udom,$uname);
5077:
5078: if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
5079: $newrecord{'resource.CODE'} = $env{'form.CODE'};
5080: } elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
5081: $newrecord{'resource.CODE'} = '';
5082: }
5083: &Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
5084: $udom,$uname);
5085: %record = &Apache::lonnet::restore($symbx,
5086: $env{'request.course.id'},
5087: $udom,$uname);
5088: &check_and_remove_from_queue($parts,\%record,undef,$symbx,
5089: $cdom,$cnum,$udom,$uname);
5090: }
5091:
5092: if ($aggregateflag) {
5093: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
5094: $env{'course.'.$env{'request.course.id'}.'.domain'},
5095: $env{'course.'.$env{'request.course.id'}.'.num'});
5096: }
5097:
5098: $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
5099: '<td valign="top">'.$displayPts[1].'</td>'.
5100: &Apache::loncommon::end_data_table_row();
5101:
5102: $prob++;
5103: }
5104: $curRes = $iterator->next();
5105: }
5106:
5107: $studentTable.=&Apache::loncommon::end_data_table();
5108: my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
5109: &mt('The scores were changed for [quant,_1,problem].',
5110: $changeflag));
5111: $request->print($grademsg.$studentTable);
5112:
5113: return '';
5114: }
5115:
5116: #-------- end of section for handling grading by page/sequence ---------
5117: #
5118: #-------------------------------------------------------------------
5119:
5120: #-------------------- Bubblesheet (Scantron) Grading -------------------
5121: #
5122: #------ start of section for handling grading by page/sequence ---------
5123:
5124: =pod
5125:
5126: =head1 Bubble sheet grading routines
5127:
5128: For this documentation:
5129:
5130: 'scanline' refers to the full line of characters
5131: from the file that we are parsing that represents one entire sheet
5132:
5133: 'bubble line' refers to the data
5134: representing the line of bubbles that are on the physical bubblesheet
5135:
5136:
5137: The overall process is that a scanned in bubblesheet data is uploaded
5138: into a course. When a user wants to grade, they select a
5139: sequence/folder of resources, a file of bubblesheet info, and pick
5140: one of the predefined configurations for what each scanline looks
5141: like.
5142:
5143: Next each scanline is checked for any errors of either 'missing
5144: bubbles' (it's an error because it may have been mis-scanned
5145: because too light bubbling), 'double bubble' (each bubble line should
5146: have no more than one letter picked), invalid or duplicated CODE,
5147: invalid student/employee ID
5148:
5149: If the CODE option is used that determines the randomization of the
5150: homework problems, either way the student/employee ID is looked up into a
5151: username:domain.
5152:
5153: During the validation phase the instructor can choose to skip scanlines.
5154:
5155: After the validation phase, there are now 3 bubblesheet files
5156:
5157: scantron_original_filename (unmodified original file)
5158: scantron_corrected_filename (file where the corrected information has replaced the original information)
5159: scantron_skipped_filename (contains the exact text of scanlines that where skipped)
5160:
5161: Also there is a separate hash nohist_scantrondata that contains extra
5162: correction information that isn't representable in the bubblesheet
5163: file (see &scantron_getfile() for more information)
5164:
5165: After all scanlines are either valid, marked as valid or skipped, then
5166: foreach line foreach problem in the picked sequence, an ssi request is
5167: made that simulates a user submitting their selected letter(s) against
5168: the homework problem.
5169:
5170: =over 4
5171:
5172:
5173:
5174: =item defaultFormData
5175:
5176: Returns html hidden inputs used to hold context/default values.
5177:
5178: Arguments:
5179: $symb - $symb of the current resource
5180:
5181: =cut
5182:
5183: sub defaultFormData {
5184: my ($symb)=@_;
5185: return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
5186: }
5187:
5188:
5189: =pod
5190:
5191: =item getSequenceDropDown
5192:
5193: Return html dropdown of possible sequences to grade
5194:
5195: Arguments:
5196: $symb - $symb of the current resource
5197: $map_error - ref to scalar which will container error if
5198: $navmap object is unavailable in &getSymbMap().
5199:
5200: =cut
5201:
5202: sub getSequenceDropDown {
5203: my ($symb,$map_error)=@_;
5204: my $result='<select name="selectpage">'."\n";
5205: my ($titles,$symbx) = &getSymbMap($map_error);
5206: if (ref($map_error)) {
5207: return if ($$map_error);
5208: }
5209: my ($curpage)=&Apache::lonnet::decode_symb($symb);
5210: my $ctr=0;
5211: foreach (@$titles) {
5212: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
5213: $result.='<option value="'.$$symbx{$_}.'" '.
5214: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
5215: '>'.$showtitle.'</option>'."\n";
5216: $ctr++;
5217: }
5218: $result.= '</select>';
5219: return $result;
5220: }
5221:
5222: my %bubble_lines_per_response; # no. bubble lines for each response.
5223: # key is zero-based index - 0, 1, 2 ...
5224:
5225: my %first_bubble_line; # First bubble line no. for each bubble.
5226:
5227: my %subdivided_bubble_lines; # no. bubble lines for optionresponse,
5228: # matchresponse or rankresponse, where
5229: # an individual response can have multiple
5230: # lines
5231:
5232: my %responsetype_per_response; # responsetype for each response
5233:
5234: my %masterseq_id_responsenum; # src_id (e.g., 12.3_0.11 etc.) for each
5235: # numbered response. Needed when randomorder
5236: # or randompick are in use. Key is ID, value
5237: # is response number.
5238:
5239: # Save and restore the bubble lines array to the form env.
5240:
5241:
5242: sub save_bubble_lines {
5243: foreach my $line (keys(%bubble_lines_per_response)) {
5244: $env{"form.scantron.bubblelines.$line"} = $bubble_lines_per_response{$line};
5245: $env{"form.scantron.first_bubble_line.$line"} =
5246: $first_bubble_line{$line};
5247: $env{"form.scantron.sub_bubblelines.$line"} =
5248: $subdivided_bubble_lines{$line};
5249: $env{"form.scantron.responsetype.$line"} =
5250: $responsetype_per_response{$line};
5251: }
5252: foreach my $resid (keys(%masterseq_id_responsenum)) {
5253: my $line = $masterseq_id_responsenum{$resid};
5254: $env{"form.scantron.residpart.$line"} = $resid;
5255: }
5256: }
5257:
5258:
5259: sub restore_bubble_lines {
5260: my $line = 0;
5261: %bubble_lines_per_response = ();
5262: %masterseq_id_responsenum = ();
5263: while ($env{"form.scantron.bubblelines.$line"}) {
5264: my $value = $env{"form.scantron.bubblelines.$line"};
5265: $bubble_lines_per_response{$line} = $value;
5266: $first_bubble_line{$line} =
5267: $env{"form.scantron.first_bubble_line.$line"};
5268: $subdivided_bubble_lines{$line} =
5269: $env{"form.scantron.sub_bubblelines.$line"};
5270: $responsetype_per_response{$line} =
5271: $env{"form.scantron.responsetype.$line"};
5272: my $id = $env{"form.scantron.residpart.$line"};
5273: $masterseq_id_responsenum{$id} = $line;
5274: $line++;
5275: }
5276: }
5277:
5278: =pod
5279:
5280: =item scantron_filenames
5281:
5282: Returns a list of the scantron files in the current course
5283:
5284: =cut
5285:
5286: sub scantron_filenames {
5287: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5288: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5289: my $getpropath = 1;
5290: my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
5291: $cname,$getpropath);
5292: my @possiblenames;
5293: if (ref($dirlist) eq 'ARRAY') {
5294: foreach my $filename (sort(@{$dirlist})) {
5295: ($filename)=split(/&/,$filename);
5296: if ($filename!~/^scantron_orig_/) { next ; }
5297: $filename=~s/^scantron_orig_//;
5298: push(@possiblenames,$filename);
5299: }
5300: }
5301: return @possiblenames;
5302: }
5303:
5304: =pod
5305:
5306: =item scantron_uploads
5307:
5308: Returns html drop-down list of scantron files in current course.
5309:
5310: Arguments:
5311: $file2grade - filename to set as selected in the dropdown
5312:
5313: =cut
5314:
5315: sub scantron_uploads {
5316: my ($file2grade) = @_;
5317: my $result= '<select name="scantron_selectfile">';
5318: $result.="<option></option>";
5319: foreach my $filename (sort(&scantron_filenames())) {
5320: $result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
5321: }
5322: $result.="</select>";
5323: return $result;
5324: }
5325:
5326: =pod
5327:
5328: =item scantron_scantab
5329:
5330: Returns html drop down of the scantron formats in the scantronformat.tab
5331: file.
5332:
5333: =cut
5334:
5335: sub scantron_scantab {
5336: my $result='<select name="scantron_format">'."\n";
5337: $result.='<option></option>'."\n";
5338: my @lines = &get_scantronformat_file();
5339: if (@lines > 0) {
5340: foreach my $line (@lines) {
5341: next if (($line =~ /^\#/) || ($line eq ''));
5342: my ($name,$descrip)=split(/:/,$line);
5343: $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
5344: }
5345: }
5346: $result.='</select>'."\n";
5347: return $result;
5348: }
5349:
5350: =pod
5351:
5352: =item get_scantronformat_file
5353:
5354: Returns an array containing lines from the scantron format file for
5355: the domain of the course.
5356:
5357: If a url for a custom.tab file is listed in domain's configuration.db,
5358: lines are from this file.
5359:
5360: Otherwise, if a default.tab has been published in RES space by the
5361: domainconfig user, lines are from this file.
5362:
5363: Otherwise, fall back to getting lines from the legacy file on the
5364: local server: /home/httpd/lonTabs/default_scantronformat.tab
5365:
5366: =cut
5367:
5368: sub get_scantronformat_file {
5369: my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
5370: my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
5371: my $gottab = 0;
5372: my @lines;
5373: if (ref($domconfig{'scantron'}) eq 'HASH') {
5374: if ($domconfig{'scantron'}{'scantronformat'} ne '') {
5375: my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
5376: if ($formatfile ne '-1') {
5377: @lines = split("\n",$formatfile,-1);
5378: $gottab = 1;
5379: }
5380: }
5381: }
5382: if (!$gottab) {
5383: my $confname = $cdom.'-domainconfig';
5384: my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
5385: my $formatfile = &Apache::lonnet::getfile($default);
5386: if ($formatfile ne '-1') {
5387: @lines = split("\n",$formatfile,-1);
5388: $gottab = 1;
5389: }
5390: }
5391: if (!$gottab) {
5392: my @domains = &Apache::lonnet::current_machine_domains();
5393: if (grep(/^\Q$cdom\E$/,@domains)) {
5394: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
5395: @lines = <$fh>;
5396: close($fh);
5397: } else {
5398: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
5399: @lines = <$fh>;
5400: close($fh);
5401: }
5402: }
5403: return @lines;
5404: }
5405:
5406: =pod
5407:
5408: =item scantron_CODElist
5409:
5410: Returns html drop down of the saved CODE lists from current course,
5411: generated from earlier printings.
5412:
5413: =cut
5414:
5415: sub scantron_CODElist {
5416: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5417: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5418: my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
5419: my $namechoice='<option></option>';
5420: foreach my $name (sort {uc($a) cmp uc($b)} @names) {
5421: if ($name =~ /^error: 2 /) { next; }
5422: if ($name =~ /^type\0/) { next; }
5423: $namechoice.='<option value="'.$name.'">'.$name.'</option>';
5424: }
5425: $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
5426: return $namechoice;
5427: }
5428:
5429: =pod
5430:
5431: =item scantron_CODEunique
5432:
5433: Returns the html for "Each CODE to be used once" radio.
5434:
5435: =cut
5436:
5437: sub scantron_CODEunique {
5438: my $result='<span class="LC_nobreak">
5439: <label><input type="radio" name="scantron_CODEunique"
5440: value="yes" checked="checked" />'.&mt('Yes').' </label>
5441: </span>
5442: <span class="LC_nobreak">
5443: <label><input type="radio" name="scantron_CODEunique"
5444: value="no" />'.&mt('No').' </label>
5445: </span>';
5446: return $result;
5447: }
5448:
5449: =pod
5450:
5451: =item scantron_selectphase
5452:
5453: Generates the initial screen to start the bubblesheet process.
5454: Allows for - starting a grading run.
5455: - downloading existing scan data (original, corrected
5456: or skipped info)
5457:
5458: - uploading new scan data
5459:
5460: Arguments:
5461: $r - The Apache request object
5462: $file2grade - name of the file that contain the scanned data to score
5463:
5464: =cut
5465:
5466: sub scantron_selectphase {
5467: my ($r,$file2grade,$symb) = @_;
5468: if (!$symb) {return '';}
5469: my $map_error;
5470: my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
5471: if ($map_error) {
5472: $r->print('<br />'.&navmap_errormsg().'<br />');
5473: return;
5474: }
5475: my $default_form_data=&defaultFormData($symb);
5476: my $file_selector=&scantron_uploads($file2grade);
5477: my $format_selector=&scantron_scantab();
5478: my $CODE_selector=&scantron_CODElist();
5479: my $CODE_unique=&scantron_CODEunique();
5480: my $result;
5481:
5482: $ssi_error = 0;
5483:
5484: if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
5485: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
5486:
5487: # Chunk of form to prompt for a scantron file upload.
5488:
5489: $r->print('
5490: <br />
5491: '.&Apache::loncommon::start_data_table('LC_scantron_action').'
5492: '.&Apache::loncommon::start_data_table_header_row().'
5493: <th>
5494: '.&mt('Specify a bubblesheet data file to upload.').'
5495: </th>
5496: '.&Apache::loncommon::end_data_table_header_row().'
5497: '.&Apache::loncommon::start_data_table_row().'
5498: <td>
5499: ');
5500: my $default_form_data=&defaultFormData($symb);
5501: my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
5502: my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
5503: $r->print(&Apache::lonhtmlcommon::scripttag('
5504: function checkUpload(formname) {
5505: if (formname.upfile.value == "") {
5506: alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
5507: return false;
5508: }
5509: formname.submit();
5510: }'));
5511: $r->print('
5512: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
5513: '.$default_form_data.'
5514: <input name="courseid" type="hidden" value="'.$cnum.'" />
5515: <input name="domainid" type="hidden" value="'.$cdom.'" />
5516: <input name="command" value="scantronupload_save" type="hidden" />
5517: '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
5518: <br />
5519: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
5520: </form>
5521: ');
5522:
5523: $r->print('
5524: </td>
5525: '.&Apache::loncommon::end_data_table_row().'
5526: '.&Apache::loncommon::end_data_table().'
5527: ');
5528: }
5529:
5530: # Chunk of form to prompt for a file to grade and how:
5531:
5532: $result.= '
5533: <br />
5534: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
5535: <input type="hidden" name="command" value="scantron_warning" />
5536: '.$default_form_data.'
5537: '.&Apache::loncommon::start_data_table('LC_scantron_action').'
5538: '.&Apache::loncommon::start_data_table_header_row().'
5539: <th colspan="2">
5540: '.&mt('Specify file and which Folder/Sequence to grade').'
5541: </th>
5542: '.&Apache::loncommon::end_data_table_header_row().'
5543: '.&Apache::loncommon::start_data_table_row().'
5544: <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
5545: '.&Apache::loncommon::end_data_table_row().'
5546: '.&Apache::loncommon::start_data_table_row().'
5547: <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
5548: '.&Apache::loncommon::end_data_table_row().'
5549: '.&Apache::loncommon::start_data_table_row().'
5550: <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
5551: '.&Apache::loncommon::end_data_table_row().'
5552: '.&Apache::loncommon::start_data_table_row().'
5553: <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
5554: '.&Apache::loncommon::end_data_table_row().'
5555: '.&Apache::loncommon::start_data_table_row().'
5556: <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
5557: '.&Apache::loncommon::end_data_table_row().'
5558: '.&Apache::loncommon::start_data_table_row().'
5559: <td> '.&mt('Options:').' </td>
5560: <td>
5561: <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
5562: <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
5563: <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
5564: </td>
5565: '.&Apache::loncommon::end_data_table_row().'
5566: '.&Apache::loncommon::start_data_table_row().'
5567: <td colspan="2">
5568: <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
5569: </td>
5570: '.&Apache::loncommon::end_data_table_row().'
5571: '.&Apache::loncommon::end_data_table().'
5572: </form>
5573: ';
5574:
5575: $r->print($result);
5576:
5577:
5578:
5579: # Chunk of the form that prompts to view a scoring office file,
5580: # corrected file, skipped records in a file.
5581:
5582: $r->print('
5583: <br />
5584: <form action="/adm/grades" name="scantron_download">
5585: '.$default_form_data.'
5586: <input type="hidden" name="command" value="scantron_download" />
5587: '.&Apache::loncommon::start_data_table('LC_scantron_action').'
5588: '.&Apache::loncommon::start_data_table_header_row().'
5589: <th>
5590: '.&mt('Download a scoring office file').'
5591: </th>
5592: '.&Apache::loncommon::end_data_table_header_row().'
5593: '.&Apache::loncommon::start_data_table_row().'
5594: <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).'
5595: <br />
5596: <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
5597: '.&Apache::loncommon::end_data_table_row().'
5598: '.&Apache::loncommon::end_data_table().'
5599: </form>
5600: <br />
5601: ');
5602:
5603: &Apache::lonpickcode::code_list($r,2);
5604:
5605: $r->print('<br /><form method="post" name="checkscantron" action="">'.
5606: $default_form_data."\n".
5607: &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
5608: &Apache::loncommon::start_data_table_header_row()."\n".
5609: '<th colspan="2">
5610: '.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
5611: '</th>'."\n".
5612: &Apache::loncommon::end_data_table_header_row()."\n".
5613: &Apache::loncommon::start_data_table_row()."\n".
5614: '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
5615: '<td> '.$sequence_selector.' </td>'.
5616: &Apache::loncommon::end_data_table_row()."\n".
5617: &Apache::loncommon::start_data_table_row()."\n".
5618: '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
5619: '<td> '.$file_selector.' </td>'."\n".
5620: &Apache::loncommon::end_data_table_row()."\n".
5621: &Apache::loncommon::start_data_table_row()."\n".
5622: '<td> '.&mt('Format of data file:').' </td>'."\n".
5623: '<td> '.$format_selector.' </td>'."\n".
5624: &Apache::loncommon::end_data_table_row()."\n".
5625: &Apache::loncommon::start_data_table_row()."\n".
5626: '<td> '.&mt('Options').' </td>'."\n".
5627: '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
5628: &Apache::loncommon::end_data_table_row()."\n".
5629: &Apache::loncommon::start_data_table_row()."\n".
5630: '<td colspan="2">'."\n".
5631: '<input type="hidden" name="command" value="checksubmissions" />'."\n".
5632: '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
5633: '</td>'."\n".
5634: &Apache::loncommon::end_data_table_row()."\n".
5635: &Apache::loncommon::end_data_table()."\n".
5636: '</form><br />');
5637: return;
5638: }
5639:
5640: =pod
5641:
5642: =item get_scantron_config
5643:
5644: Parse and return the bubblesheet configuration line selected as a
5645: hash of configuration file fields.
5646:
5647: Arguments:
5648: which - the name of the configuration to parse from the file.
5649:
5650:
5651: Returns:
5652: If the named configuration is not in the file, an empty
5653: hash is returned.
5654: a hash with the fields
5655: name - internal name for the this configuration setup
5656: description - text to display to operator that describes this config
5657: CODElocation - if 0 or the string 'none'
5658: - no CODE exists for this config
5659: if -1 || the string 'letter'
5660: - a CODE exists for this config and is
5661: a string of letters
5662: Unsupported value (but planned for future support)
5663: if a positive integer
5664: - The CODE exists as the first n items from
5665: the question section of the form
5666: if the string 'number'
5667: - The CODE exists for this config and is
5668: a string of numbers
5669: CODEstart - (only matter if a CODE exists) column in the line where
5670: the CODE starts
5671: CODElength - length of the CODE
5672: IDstart - column where the student/employee ID starts
5673: IDlength - length of the student/employee ID info
5674: Qstart - column where the information from the bubbled
5675: 'questions' start
5676: Qlength - number of columns comprising a single bubble line from
5677: the sheet. (usually either 1 or 10)
5678: Qon - either a single character representing the character used
5679: to signal a bubble was chosen in the positional setup, or
5680: the string 'letter' if the letter of the chosen bubble is
5681: in the final, or 'number' if a number representing the
5682: chosen bubble is in the file (1->A 0->J)
5683: Qoff - the character used to represent that a bubble was
5684: left blank
5685: PaperID - if the scanning process generates a unique number for each
5686: sheet scanned the column that this ID number starts in
5687: PaperIDlength - number of columns that comprise the unique ID number
5688: for the sheet of paper
5689: FirstName - column that the first name starts in
5690: FirstNameLength - number of columns that the first name spans
5691:
5692: LastName - column that the last name starts in
5693: LastNameLength - number of columns that the last name spans
5694: BubblesPerRow - number of bubbles available in each row used to
5695: bubble an answer. (If not specified, 10 assumed).
5696:
5697: =cut
5698:
5699: sub get_scantron_config {
5700: my ($which) = @_;
5701: my @lines = &get_scantronformat_file();
5702: my %config;
5703: #FIXME probably should move to XML it has already gotten a bit much now
5704: foreach my $line (@lines) {
5705: my ($name,$descrip)=split(/:/,$line);
5706: if ($name ne $which ) { next; }
5707: chomp($line);
5708: my @config=split(/:/,$line);
5709: $config{'name'}=$config[0];
5710: $config{'description'}=$config[1];
5711: $config{'CODElocation'}=$config[2];
5712: $config{'CODEstart'}=$config[3];
5713: $config{'CODElength'}=$config[4];
5714: $config{'IDstart'}=$config[5];
5715: $config{'IDlength'}=$config[6];
5716: $config{'Qstart'}=$config[7];
5717: $config{'Qlength'}=$config[8];
5718: $config{'Qoff'}=$config[9];
5719: $config{'Qon'}=$config[10];
5720: $config{'PaperID'}=$config[11];
5721: $config{'PaperIDlength'}=$config[12];
5722: $config{'FirstName'}=$config[13];
5723: $config{'FirstNamelength'}=$config[14];
5724: $config{'LastName'}=$config[15];
5725: $config{'LastNamelength'}=$config[16];
5726: $config{'BubblesPerRow'}=$config[17];
5727: last;
5728: }
5729: return %config;
5730: }
5731:
5732: =pod
5733:
5734: =item username_to_idmap
5735:
5736: creates a hash keyed by student/employee ID with values of the corresponding
5737: student username:domain.
5738:
5739: Arguments:
5740:
5741: $classlist - reference to the class list hash. This is a hash
5742: keyed by student name:domain whose elements are references
5743: to arrays containing various chunks of information
5744: about the student. (See loncoursedata for more info).
5745:
5746: Returns
5747: %idmap - the constructed hash
5748:
5749: =cut
5750:
5751: sub username_to_idmap {
5752: my ($classlist)= @_;
5753: my %idmap;
5754: foreach my $student (keys(%$classlist)) {
5755: $idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
5756: $student;
5757: }
5758: return %idmap;
5759: }
5760:
5761: =pod
5762:
5763: =item scantron_fixup_scanline
5764:
5765: Process a requested correction to a scanline.
5766:
5767: Arguments:
5768: $scantron_config - hash from &get_scantron_config()
5769: $scan_data - hash of correction information
5770: (see &scantron_getfile())
5771: $line - existing scanline
5772: $whichline - line number of the passed in scanline
5773: $field - type of change to process
5774: (either
5775: 'ID' -> correct the student/employee ID
5776: 'CODE' -> correct the CODE
5777: 'answer' -> fixup the submitted answers)
5778:
5779: $args - hash of additional info,
5780: - 'ID'
5781: 'newid' -> studentID to use in replacement
5782: of existing one
5783: - 'CODE'
5784: 'CODE_ignore_dup' - set to true if duplicates
5785: should be ignored.
5786: 'CODE' - is new code or 'use_unfound'
5787: if the existing unfound code should
5788: be used as is
5789: - 'answer'
5790: 'response' - new answer or 'none' if blank
5791: 'question' - the bubble line to change
5792: 'questionnum' - the question identifier,
5793: may include subquestion.
5794:
5795: Returns:
5796: $line - the modified scanline
5797:
5798: Side effects:
5799: $scan_data - may be updated
5800:
5801: =cut
5802:
5803:
5804: sub scantron_fixup_scanline {
5805: my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
5806: if ($field eq 'ID') {
5807: if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
5808: return ($line,1,'New value too large');
5809: }
5810: if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
5811: $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
5812: $args->{'newid'});
5813: }
5814: substr($line,$$scantron_config{'IDstart'}-1,
5815: $$scantron_config{'IDlength'})=$args->{'newid'};
5816: if ($args->{'newid'}=~/^\s*$/) {
5817: &scan_data($scan_data,"$whichline.user",
5818: $args->{'username'}.':'.$args->{'domain'});
5819: }
5820: } elsif ($field eq 'CODE') {
5821: if ($args->{'CODE_ignore_dup'}) {
5822: &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
5823: }
5824: &scan_data($scan_data,"$whichline.useCODE",'1');
5825: if ($args->{'CODE'} ne 'use_unfound') {
5826: if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
5827: return ($line,1,'New CODE value too large');
5828: }
5829: if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
5830: $args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
5831: }
5832: substr($line,$$scantron_config{'CODEstart'}-1,
5833: $$scantron_config{'CODElength'})=$args->{'CODE'};
5834: }
5835: } elsif ($field eq 'answer') {
5836: my $length=$scantron_config->{'Qlength'};
5837: my $off=$scantron_config->{'Qoff'};
5838: my $on=$scantron_config->{'Qon'};
5839: my $answer=${off}x$length;
5840: if ($args->{'response'} eq 'none') {
5841: &scan_data($scan_data,
5842: "$whichline.no_bubble.".$args->{'questionnum'},'1');
5843: } else {
5844: if ($on eq 'letter') {
5845: my @alphabet=('A'..'Z');
5846: $answer=$alphabet[$args->{'response'}];
5847: } elsif ($on eq 'number') {
5848: $answer=$args->{'response'}+1;
5849: if ($answer == 10) { $answer = '0'; }
5850: } else {
5851: substr($answer,$args->{'response'},1)=$on;
5852: }
5853: &scan_data($scan_data,
5854: "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
5855: }
5856: my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
5857: substr($line,$where-1,$length)=$answer;
5858: }
5859: return $line;
5860: }
5861:
5862: =pod
5863:
5864: =item scan_data
5865:
5866: Edit or look up an item in the scan_data hash.
5867:
5868: Arguments:
5869: $scan_data - The hash (see scantron_getfile)
5870: $key - shorthand of the key to edit (actual key is
5871: scantronfilename_key).
5872: $data - New value of the hash entry.
5873: $delete - If true, the entry is removed from the hash.
5874:
5875: Returns:
5876: The new value of the hash table field (undefined if deleted).
5877:
5878: =cut
5879:
5880:
5881: sub scan_data {
5882: my ($scan_data,$key,$value,$delete)=@_;
5883: my $filename=$env{'form.scantron_selectfile'};
5884: if (defined($value)) {
5885: $scan_data->{$filename.'_'.$key} = $value;
5886: }
5887: if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
5888: return $scan_data->{$filename.'_'.$key};
5889: }
5890:
5891: # ----- These first few routines are general use routines.----
5892:
5893: # Return the number of occurences of a pattern in a string.
5894:
5895: sub occurence_count {
5896: my ($string, $pattern) = @_;
5897:
5898: my @matches = ($string =~ /$pattern/g);
5899:
5900: return scalar(@matches);
5901: }
5902:
5903:
5904: # Take a string known to have digits and convert all the
5905: # digits into letters in the range J,A..I.
5906:
5907: sub digits_to_letters {
5908: my ($input) = @_;
5909:
5910: my @alphabet = ('J', 'A'..'I');
5911:
5912: my @input = split(//, $input);
5913: my $output ='';
5914: for (my $i = 0; $i < scalar(@input); $i++) {
5915: if ($input[$i] =~ /\d/) {
5916: $output .= $alphabet[$input[$i]];
5917: } else {
5918: $output .= $input[$i];
5919: }
5920: }
5921: return $output;
5922: }
5923:
5924: =pod
5925:
5926: =item scantron_parse_scanline
5927:
5928: Decodes a scanline from the selected bubblesheet file
5929:
5930: Arguments:
5931: line - The text of the bubblesheet file line to process
5932: whichline - Line number
5933: scantron_config - Hash describing the format of the bubblesheet lines.
5934: scan_data - Hash of extra information about the scanline
5935: (see scantron_getfile for more information)
5936: just_header - True if should not process question answers but only
5937: the stuff to the left of the answers.
5938: randomorder - True if randomorder in use
5939: randompick - True if randompick in use
5940: sequence - Exam folder URL
5941: master_seq - Ref to array containing symbs in exam folder
5942: symb_to_resource - Ref to hash of symbs for resources in exam folder
5943: (corresponding values are resource objects)
5944: partids_by_symb - Ref to hash of symb -> array ref of partIDs
5945: orderedforcode - Ref to hash of arrays. keys are CODEs and values
5946: are refs to an array of resource objects, ordered
5947: according to order used for CODE, when randomorder
5948: and or randompick are in use.
5949: respnumlookup - Ref to hash mapping question numbers in bubble lines
5950: for current line to question number used for same question
5951: in "Master Sequence" (as seen by Course Coordinator).
5952: startline - Ref to hash where key is question number (0 is first)
5953: and value is number of first bubble line for current
5954: student or code-based randompick and/or randomorder.
5955: totalref - Ref of scalar used to score total number of bubble
5956: lines needed for responses in a scan line (used when
5957: randompick in use.
5958:
5959: Returns:
5960: Hash containing the result of parsing the scanline
5961:
5962: Keys are all proceeded by the string 'scantron.'
5963:
5964: CODE - the CODE in use for this scanline
5965: useCODE - 1 if the CODE is invalid but it usage has been forced
5966: by the operator
5967: CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
5968: CODEs were selected, but the usage has been
5969: forced by the operator
5970: ID - student/employee ID
5971: PaperID - if used, the ID number printed on the sheet when the
5972: paper was scanned
5973: FirstName - first name from the sheet
5974: LastName - last name from the sheet
5975:
5976: if just_header was not true these key may also exist
5977:
5978: missingerror - a list of bubble ranges that are considered to be answers
5979: to a single question that don't have any bubbles filled in.
5980: Of the form questionnumber:firstbubblenumber:count.
5981: doubleerror - a list of bubble ranges that are considered to be answers
5982: to a single question that have more than one bubble filled in.
5983: Of the form questionnumber::firstbubblenumber:count
5984:
5985: In the above, count is the number of bubble responses in the
5986: input line needed to represent the possible answers to the question.
5987: e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
5988: per line would have count = 2.
5989:
5990: maxquest - the number of the last bubble line that was parsed
5991:
5992: (<number> starts at 1)
5993: <number>.answer - zero or more letters representing the selected
5994: letters from the scanline for the bubble line
5995: <number>.
5996: if blank there was either no bubble or there where
5997: multiple bubbles, (consult the keys missingerror and
5998: doubleerror if this is an error condition)
5999:
6000: =cut
6001:
6002: sub scantron_parse_scanline {
6003: my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
6004: $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
6005: $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
6006:
6007: my %record;
6008: my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
6009: if (!($$scantron_config{'CODElocation'} eq 0 ||
6010: $$scantron_config{'CODElocation'} eq 'none')) {
6011: if ($$scantron_config{'CODElocation'} < 0 ||
6012: $$scantron_config{'CODElocation'} eq 'letter' ||
6013: $$scantron_config{'CODElocation'} eq 'number') {
6014: $record{'scantron.CODE'}=substr($data,
6015: $$scantron_config{'CODEstart'}-1,
6016: $$scantron_config{'CODElength'});
6017: if (&scan_data($scan_data,"$whichline.useCODE")) {
6018: $record{'scantron.useCODE'}=1;
6019: }
6020: if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
6021: $record{'scantron.CODE_ignore_dup'}=1;
6022: }
6023: } else {
6024: #FIXME interpret first N questions
6025: }
6026: }
6027: $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
6028: $$scantron_config{'IDlength'});
6029: $record{'scantron.PaperID'}=
6030: substr($data,$$scantron_config{'PaperID'}-1,
6031: $$scantron_config{'PaperIDlength'});
6032: $record{'scantron.FirstName'}=
6033: substr($data,$$scantron_config{'FirstName'}-1,
6034: $$scantron_config{'FirstNamelength'});
6035: $record{'scantron.LastName'}=
6036: substr($data,$$scantron_config{'LastName'}-1,
6037: $$scantron_config{'LastNamelength'});
6038: if ($just_header) { return \%record; }
6039:
6040: my @alphabet=('A'..'Z');
6041: my $questnum=0;
6042: my $ansnum =1; # Multiple 'answer lines'/question.
6043:
6044: my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
6045: if ($randompick || $randomorder) {
6046: my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
6047: $master_seq,$symb_to_resource,
6048: $partids_by_symb,$orderedforcode,
6049: $respnumlookup,$startline);
6050: if ($total) {
6051: $lastpos = $total*$$scantron_config{'Qlength'};
6052: }
6053: if (ref($totalref)) {
6054: $$totalref = $total;
6055: }
6056: }
6057: my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos); # Answers
6058: chomp($questions); # Get rid of any trailing \n.
6059: $questions =~ s/\r$//; # Get rid of trailing \r too (MAC or Win uploads).
6060: while (length($questions)) {
6061: my $answers_needed;
6062: if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
6063: $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
6064: } else {
6065: $answers_needed = $bubble_lines_per_response{$questnum};
6066: }
6067: my $answer_length = ($$scantron_config{'Qlength'} * $answers_needed)
6068: || 1;
6069: $questnum++;
6070: my $quest_id = $questnum;
6071: my $currentquest = substr($questions,0,$answer_length);
6072: $questions = substr($questions,$answer_length);
6073: if (length($currentquest) < $answer_length) { next; }
6074:
6075: my $subdivided;
6076: if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
6077: $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
6078: } else {
6079: $subdivided = $subdivided_bubble_lines{$questnum-1};
6080: }
6081: if ($subdivided =~ /,/) {
6082: my $subquestnum = 1;
6083: my $subquestions = $currentquest;
6084: my @subanswers_needed = split(/,/,$subdivided);
6085: foreach my $subans (@subanswers_needed) {
6086: my $subans_length =
6087: ($$scantron_config{'Qlength'} * $subans) || 1;
6088: my $currsubquest = substr($subquestions,0,$subans_length);
6089: $subquestions = substr($subquestions,$subans_length);
6090: $quest_id = "$questnum.$subquestnum";
6091: if (($$scantron_config{'Qon'} eq 'letter') ||
6092: ($$scantron_config{'Qon'} eq 'number')) {
6093: $ansnum = &scantron_validator_lettnum($ansnum,
6094: $questnum,$quest_id,$subans,$currsubquest,$whichline,
6095: \@alphabet,\%record,$scantron_config,$scan_data,
6096: $randomorder,$randompick,$respnumlookup);
6097: } else {
6098: $ansnum = &scantron_validator_positional($ansnum,
6099: $questnum,$quest_id,$subans,$currsubquest,$whichline,
6100: \@alphabet,\%record,$scantron_config,$scan_data,
6101: $randomorder,$randompick,$respnumlookup);
6102: }
6103: $subquestnum ++;
6104: }
6105: } else {
6106: if (($$scantron_config{'Qon'} eq 'letter') ||
6107: ($$scantron_config{'Qon'} eq 'number')) {
6108: $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
6109: $quest_id,$answers_needed,$currentquest,$whichline,
6110: \@alphabet,\%record,$scantron_config,$scan_data,
6111: $randomorder,$randompick,$respnumlookup);
6112: } else {
6113: $ansnum = &scantron_validator_positional($ansnum,$questnum,
6114: $quest_id,$answers_needed,$currentquest,$whichline,
6115: \@alphabet,\%record,$scantron_config,$scan_data,
6116: $randomorder,$randompick,$respnumlookup);
6117: }
6118: }
6119: }
6120: $record{'scantron.maxquest'}=$questnum;
6121: return \%record;
6122: }
6123:
6124: sub get_master_seq {
6125: my ($resources,$master_seq,$symb_to_resource) = @_;
6126: return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') &&
6127: (ref($symb_to_resource) eq 'HASH'));
6128: my $resource_error;
6129: foreach my $resource (@{$resources}) {
6130: my $ressymb;
6131: if (ref($resource)) {
6132: $ressymb = $resource->symb();
6133: push(@{$master_seq},$ressymb);
6134: $symb_to_resource->{$ressymb} = $resource;
6135: } else {
6136: $resource_error = 1;
6137: last;
6138: }
6139: }
6140: return $resource_error;
6141: }
6142:
6143: sub get_respnum_lookups {
6144: my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
6145: $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
6146: return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
6147: (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
6148: (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
6149: (ref($startline) eq 'HASH'));
6150: my ($user,$scancode);
6151: if ((exists($record->{'scantron.CODE'})) &&
6152: (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
6153: $scancode = $record->{'scantron.CODE'};
6154: } else {
6155: $user = &scantron_find_student($record,$scan_data,$idmap,$line);
6156: }
6157: my @mapresources =
6158: &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
6159: $orderedforcode);
6160: my $total = 0;
6161: my $count = 0;
6162: foreach my $resource (@mapresources) {
6163: my $id = $resource->id();
6164: my $symb = $resource->symb();
6165: if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
6166: foreach my $partid (@{$partids_by_symb->{$symb}}) {
6167: my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
6168: if ($respnum ne '') {
6169: $respnumlookup->{$count} = $respnum;
6170: $startline->{$count} = $total;
6171: $total += $bubble_lines_per_response{$respnum};
6172: $count ++;
6173: }
6174: }
6175: }
6176: }
6177: return $total;
6178: }
6179:
6180: sub scantron_validator_lettnum {
6181: my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
6182: $alphabet,$record,$scantron_config,$scan_data,$randomorder,
6183: $randompick,$respnumlookup) = @_;
6184:
6185: # Qon 'letter' implies for each slot in currquest we have:
6186: # ? or * for doubles, a letter in A-Z for a bubble, and
6187: # about anything else (esp. a value of Qoff) for missing
6188: # bubbles.
6189: #
6190: # Qon 'number' implies each slot gives a digit that indexes the
6191: # bubbles filled, or Qoff, or a non-number for unbubbled lines,
6192: # and * or ? for double bubbles on a single line.
6193: #
6194:
6195: my $matchon;
6196: if ($$scantron_config{'Qon'} eq 'letter') {
6197: $matchon = '[A-Z]';
6198: } elsif ($$scantron_config{'Qon'} eq 'number') {
6199: $matchon = '\d';
6200: }
6201: my $occurrences = 0;
6202: my $responsenum = $questnum-1;
6203: if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
6204: $responsenum = $respnumlookup->{$questnum-1}
6205: }
6206: if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
6207: ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
6208: ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
6209: ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
6210: ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
6211: ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
6212: my @singlelines = split('',$currquest);
6213: foreach my $entry (@singlelines) {
6214: $occurrences = &occurence_count($entry,$matchon);
6215: if ($occurrences > 1) {
6216: last;
6217: }
6218: }
6219: } else {
6220: $occurrences = &occurence_count($currquest,$matchon);
6221: }
6222: if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
6223: push(@{$record->{'scantron.doubleerror'}},$quest_id);
6224: for (my $ans=0; $ans<$answers_needed; $ans++) {
6225: my $bubble = substr($currquest,$ans,1);
6226: if ($bubble =~ /$matchon/ ) {
6227: if ($$scantron_config{'Qon'} eq 'number') {
6228: if ($bubble == 0) {
6229: $bubble = 10;
6230: }
6231: $record->{"scantron.$ansnum.answer"} =
6232: $alphabet->[$bubble-1];
6233: } else {
6234: $record->{"scantron.$ansnum.answer"} = $bubble;
6235: }
6236: } else {
6237: $record->{"scantron.$ansnum.answer"}='';
6238: }
6239: $ansnum++;
6240: }
6241: } elsif (!defined($currquest)
6242: || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
6243: || (&occurence_count($currquest,$matchon) == 0)) {
6244: for (my $ans=0; $ans<$answers_needed; $ans++ ) {
6245: $record->{"scantron.$ansnum.answer"}='';
6246: $ansnum++;
6247: }
6248: if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
6249: push(@{$record->{'scantron.missingerror'}},$quest_id);
6250: }
6251: } else {
6252: if ($$scantron_config{'Qon'} eq 'number') {
6253: $currquest = &digits_to_letters($currquest);
6254: }
6255: for (my $ans=0; $ans<$answers_needed; $ans++) {
6256: my $bubble = substr($currquest,$ans,1);
6257: $record->{"scantron.$ansnum.answer"} = $bubble;
6258: $ansnum++;
6259: }
6260: }
6261: return $ansnum;
6262: }
6263:
6264: sub scantron_validator_positional {
6265: my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
6266: $whichline,$alphabet,$record,$scantron_config,$scan_data,
6267: $randomorder,$randompick,$respnumlookup) = @_;
6268:
6269: # Otherwise there's a positional notation;
6270: # each bubble line requires Qlength items, and there are filled in
6271: # bubbles for each case where there 'Qon' characters.
6272: #
6273:
6274: my @array=split($$scantron_config{'Qon'},$currquest,-1);
6275:
6276: # If the split only gives us one element.. the full length of the
6277: # answer string, no bubbles are filled in:
6278:
6279: if ($answers_needed eq '') {
6280: return;
6281: }
6282:
6283: if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
6284: for (my $ans=0; $ans<$answers_needed; $ans++ ) {
6285: $record->{"scantron.$ansnum.answer"}='';
6286: $ansnum++;
6287: }
6288: if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
6289: push(@{$record->{"scantron.missingerror"}},$quest_id);
6290: }
6291: } elsif (scalar(@array) == 2) {
6292: my $location = length($array[0]);
6293: my $line_num = int($location / $$scantron_config{'Qlength'});
6294: my $bubble = $alphabet->[$location % $$scantron_config{'Qlength'}];
6295: for (my $ans=0; $ans<$answers_needed; $ans++) {
6296: if ($ans eq $line_num) {
6297: $record->{"scantron.$ansnum.answer"} = $bubble;
6298: } else {
6299: $record->{"scantron.$ansnum.answer"} = ' ';
6300: }
6301: $ansnum++;
6302: }
6303: } else {
6304: # If there's more than one instance of a bubble character
6305: # That's a double bubble; with positional notation we can
6306: # record all the bubbles filled in as well as the
6307: # fact this response consists of multiple bubbles.
6308: #
6309: my $responsenum = $questnum-1;
6310: if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
6311: $responsenum = $respnumlookup->{$questnum-1}
6312: }
6313: if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
6314: ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
6315: ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
6316: ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
6317: ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
6318: ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
6319: my $doubleerror = 0;
6320: while (($currquest >= $$scantron_config{'Qlength'}) &&
6321: (!$doubleerror)) {
6322: my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
6323: $currquest = substr($currquest,$$scantron_config{'Qlength'});
6324: my @currarray = split($$scantron_config{'Qon'},$currline,-1);
6325: if (length(@currarray) > 2) {
6326: $doubleerror = 1;
6327: }
6328: }
6329: if ($doubleerror) {
6330: push(@{$record->{'scantron.doubleerror'}},$quest_id);
6331: }
6332: } else {
6333: push(@{$record->{'scantron.doubleerror'}},$quest_id);
6334: }
6335: my $item = $ansnum;
6336: for (my $ans=0; $ans<$answers_needed; $ans++) {
6337: $record->{"scantron.$item.answer"} = '';
6338: $item ++;
6339: }
6340:
6341: my @ans=@array;
6342: my $i=0;
6343: my $increment = 0;
6344: while ($#ans) {
6345: $i+=length($ans[0]) + $increment;
6346: my $line = int($i/$$scantron_config{'Qlength'} + $ansnum);
6347: my $bubble = $i%$$scantron_config{'Qlength'};
6348: $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
6349: shift(@ans);
6350: $increment = 1;
6351: }
6352: $ansnum += $answers_needed;
6353: }
6354: return $ansnum;
6355: }
6356:
6357: =pod
6358:
6359: =item scantron_add_delay
6360:
6361: Adds an error message that occurred during the grading phase to a
6362: queue of messages to be shown after grading pass is complete
6363:
6364: Arguments:
6365: $delayqueue - arrary ref of hash ref of error messages
6366: $scanline - the scanline that caused the error
6367: $errormesage - the error message
6368: $errorcode - a numeric code for the error
6369:
6370: Side Effects:
6371: updates the $delayqueue to have a new hash ref of the error
6372:
6373: =cut
6374:
6375: sub scantron_add_delay {
6376: my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
6377: push(@$delayqueue,
6378: {'line' => $scanline, 'emsg' => $errormessage,
6379: 'ecode' => $errorcode }
6380: );
6381: }
6382:
6383: =pod
6384:
6385: =item scantron_find_student
6386:
6387: Finds the username for the current scanline
6388:
6389: Arguments:
6390: $scantron_record - hash result from scantron_parse_scanline
6391: $scan_data - hash of correction information
6392: (see &scantron_getfile() form more information)
6393: $idmap - hash from &username_to_idmap()
6394: $line - number of current scanline
6395:
6396: Returns:
6397: Either 'username:domain' or undef if unknown
6398:
6399: =cut
6400:
6401: sub scantron_find_student {
6402: my ($scantron_record,$scan_data,$idmap,$line)=@_;
6403: my $scanID=$$scantron_record{'scantron.ID'};
6404: if ($scanID =~ /^\s*$/) {
6405: return &scan_data($scan_data,"$line.user");
6406: }
6407: foreach my $id (keys(%$idmap)) {
6408: if (lc($id) eq lc($scanID)) {
6409: return $$idmap{$id};
6410: }
6411: }
6412: return undef;
6413: }
6414:
6415: =pod
6416:
6417: =item scantron_filter
6418:
6419: Filter sub for lonnavmaps, filters out hidden resources if ignore
6420: hidden resources was selected
6421:
6422: =cut
6423:
6424: sub scantron_filter {
6425: my ($curres)=@_;
6426:
6427: if (ref($curres) && $curres->is_problem()) {
6428: # if the user has asked to not have either hidden
6429: # or 'randomout' controlled resources to be graded
6430: # don't include them
6431: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
6432: && $curres->randomout) {
6433: return 0;
6434: }
6435: return 1;
6436: }
6437: return 0;
6438: }
6439:
6440: =pod
6441:
6442: =item scantron_process_corrections
6443:
6444: Gets correction information out of submitted form data and corrects
6445: the scanline
6446:
6447: =cut
6448:
6449: sub scantron_process_corrections {
6450: my ($r) = @_;
6451: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6452: my ($scanlines,$scan_data)=&scantron_getfile();
6453: my $classlist=&Apache::loncoursedata::get_classlist();
6454: my $which=$env{'form.scantron_line'};
6455: my $line=&scantron_get_line($scanlines,$scan_data,$which);
6456: my ($skip,$err,$errmsg);
6457: if ($env{'form.scantron_skip_record'}) {
6458: $skip=1;
6459: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
6460: my $newstudent=$env{'form.scantron_username'}.':'.
6461: $env{'form.scantron_domain'};
6462: my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
6463: ($line,$err,$errmsg)=
6464: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
6465: 'ID',{'newid'=>$newid,
6466: 'username'=>$env{'form.scantron_username'},
6467: 'domain'=>$env{'form.scantron_domain'}});
6468: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
6469: my $resolution=$env{'form.scantron_CODE_resolution'};
6470: my $newCODE;
6471: my %args;
6472: if ($resolution eq 'use_unfound') {
6473: $newCODE='use_unfound';
6474: } elsif ($resolution eq 'use_found') {
6475: $newCODE=$env{'form.scantron_CODE_selectedvalue'};
6476: } elsif ($resolution eq 'use_typed') {
6477: $newCODE=$env{'form.scantron_CODE_newvalue'};
6478: } elsif ($resolution =~ /^use_closest_(\d+)/) {
6479: $newCODE=$env{"form.scantron_CODE_closest_$1"};
6480: }
6481: if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
6482: $args{'CODE_ignore_dup'}=1;
6483: }
6484: $args{'CODE'}=$newCODE;
6485: ($line,$err,$errmsg)=
6486: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
6487: 'CODE',\%args);
6488: } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
6489: foreach my $question (split(',',$env{'form.scantron_questions'})) {
6490: ($line,$err,$errmsg)=
6491: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
6492: $which,'answer',
6493: { 'question'=>$question,
6494: 'response'=>$env{"form.scantron_correct_Q_$question"},
6495: 'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
6496: if ($err) { last; }
6497: }
6498: }
6499: if ($err) {
6500: $r->print(
6501: '<p class="LC_error">'
6502: .&mt('Unable to accept last correction, an error occurred: [_1]',
6503: $errmsg)
6504: .'</p>');
6505: } else {
6506: &scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
6507: &scantron_putfile($scanlines,$scan_data);
6508: }
6509: }
6510:
6511: =pod
6512:
6513: =item reset_skipping_status
6514:
6515: Forgets the current set of remember skipped scanlines (and thus
6516: reverts back to considering all lines in the
6517: scantron_skipped_<filename> file)
6518:
6519: =cut
6520:
6521: sub reset_skipping_status {
6522: my ($scanlines,$scan_data)=&scantron_getfile();
6523: &scan_data($scan_data,'remember_skipping',undef,1);
6524: &scantron_putfile(undef,$scan_data);
6525: }
6526:
6527: =pod
6528:
6529: =item start_skipping
6530:
6531: Marks a scanline to be skipped.
6532:
6533: =cut
6534:
6535: sub start_skipping {
6536: my ($scan_data,$i)=@_;
6537: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
6538: if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
6539: $remembered{$i}=2;
6540: } else {
6541: $remembered{$i}=1;
6542: }
6543: &scan_data($scan_data,'remember_skipping',join(':',%remembered));
6544: }
6545:
6546: =pod
6547:
6548: =item should_be_skipped
6549:
6550: Checks whether a scanline should be skipped.
6551:
6552: =cut
6553:
6554: sub should_be_skipped {
6555: my ($scanlines,$scan_data,$i)=@_;
6556: if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
6557: # not redoing old skips
6558: if ($scanlines->{'skipped'}[$i]) { return 1; }
6559: return 0;
6560: }
6561: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
6562:
6563: if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
6564: return 0;
6565: }
6566: return 1;
6567: }
6568:
6569: =pod
6570:
6571: =item remember_current_skipped
6572:
6573: Discovers what scanlines are in the scantron_skipped_<filename>
6574: file and remembers them into scan_data for later use.
6575:
6576: =cut
6577:
6578: sub remember_current_skipped {
6579: my ($scanlines,$scan_data)=&scantron_getfile();
6580: my %to_remember;
6581: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6582: if ($scanlines->{'skipped'}[$i]) {
6583: $to_remember{$i}=1;
6584: }
6585: }
6586:
6587: &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
6588: &scantron_putfile(undef,$scan_data);
6589: }
6590:
6591: =pod
6592:
6593: =item check_for_error
6594:
6595: Checks if there was an error when attempting to remove a specific
6596: scantron_.. bubblesheet data file. Prints out an error if
6597: something went wrong.
6598:
6599: =cut
6600:
6601: sub check_for_error {
6602: my ($r,$result)=@_;
6603: if ($result ne 'ok' && $result ne 'not_found' ) {
6604: $r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
6605: }
6606: }
6607:
6608: =pod
6609:
6610: =item scantron_warning_screen
6611:
6612: Interstitial screen to make sure the operator has selected the
6613: correct options before we start the validation phase.
6614:
6615: =cut
6616:
6617: sub scantron_warning_screen {
6618: my ($button_text,$symb)=@_;
6619: my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
6620: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6621: my $CODElist;
6622: if ($scantron_config{'CODElocation'} &&
6623: $scantron_config{'CODEstart'} &&
6624: $scantron_config{'CODElength'}) {
6625: $CODElist=$env{'form.scantron_CODElist'};
6626: if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
6627: $CODElist=
6628: '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
6629: $env{'form.scantron_CODElist'}.'</tt></td></tr>';
6630: }
6631: my $lastbubblepoints;
6632: if ($env{'form.scantron_lastbubblepoints'} ne '') {
6633: $lastbubblepoints =
6634: '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
6635: $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
6636: }
6637: return ('
6638: <p>
6639: <span class="LC_warning">
6640: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
6641: </p>
6642: <table>
6643: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
6644: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
6645: '.$CODElist.$lastbubblepoints.'
6646: </table>
6647: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
6648: '.&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>
6649:
6650: <br />
6651: ');
6652: }
6653:
6654: =pod
6655:
6656: =item scantron_do_warning
6657:
6658: Check if the operator has picked something for all required
6659: fields. Error out if something is missing.
6660:
6661: =cut
6662:
6663: sub scantron_do_warning {
6664: my ($r,$symb)=@_;
6665: if (!$symb) {return '';}
6666: my $default_form_data=&defaultFormData($symb);
6667: $r->print(&scantron_form_start().$default_form_data);
6668: if ( $env{'form.selectpage'} eq '' ||
6669: $env{'form.scantron_selectfile'} eq '' ||
6670: $env{'form.scantron_format'} eq '' ) {
6671: $r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
6672: if ( $env{'form.selectpage'} eq '') {
6673: $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
6674: }
6675: if ( $env{'form.scantron_selectfile'} eq '') {
6676: $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
6677: }
6678: if ( $env{'form.scantron_format'} eq '') {
6679: $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
6680: }
6681: } else {
6682: my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
6683: my $bubbledbyhand=&hand_bubble_option();
6684: $r->print('
6685: '.$warning.$bubbledbyhand.'
6686: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
6687: <input type="hidden" name="command" value="scantron_validate" />
6688: ');
6689: }
6690: $r->print("</form><br />");
6691: return '';
6692: }
6693:
6694: =pod
6695:
6696: =item scantron_form_start
6697:
6698: html hidden input for remembering all selected grading options
6699:
6700: =cut
6701:
6702: sub scantron_form_start {
6703: my ($max_bubble)=@_;
6704: my $result= <<SCANTRONFORM;
6705: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
6706: <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
6707: <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
6708: <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
6709: <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
6710: <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
6711: <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
6712: <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
6713: <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
6714: <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
6715: SCANTRONFORM
6716:
6717: my $line = 0;
6718: while (defined($env{"form.scantron.bubblelines.$line"})) {
6719: my $chunk =
6720: '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
6721: $chunk .=
6722: '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
6723: $chunk .=
6724: '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
6725: $chunk .=
6726: '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
6727: $chunk .=
6728: '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
6729: $result .= $chunk;
6730: $line++;
6731: }
6732: return $result;
6733: }
6734:
6735: =pod
6736:
6737: =item scantron_validate_file
6738:
6739: Dispatch routine for doing validation of a bubblesheet data file.
6740:
6741: Also processes any necessary information resets that need to
6742: occur before validation begins (ignore previous corrections,
6743: restarting the skipped records processing)
6744:
6745: =cut
6746:
6747: sub scantron_validate_file {
6748: my ($r,$symb) = @_;
6749: if (!$symb) {return '';}
6750: my $default_form_data=&defaultFormData($symb);
6751:
6752: # do the detection of only doing skipped records first before we delete
6753: # them when doing the corrections reset
6754: if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
6755: &reset_skipping_status();
6756: }
6757: if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
6758: &remember_current_skipped();
6759: $env{'form.scantron_options_redo'}='redo_skipped_ready';
6760: }
6761:
6762: if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
6763: &check_for_error($r,&scantron_remove_file('corrected'));
6764: &check_for_error($r,&scantron_remove_file('skipped'));
6765: &check_for_error($r,&scantron_remove_scan_data());
6766: $env{'form.scantron_options_ignore'}='done';
6767: }
6768:
6769: if ($env{'form.scantron_corrections'}) {
6770: &scantron_process_corrections($r);
6771: }
6772: $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
6773: #get the student pick code ready
6774: $r->print(&Apache::loncommon::studentbrowser_javascript());
6775: my $nav_error;
6776: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6777: my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
6778: if ($nav_error) {
6779: $r->print(&navmap_errormsg());
6780: return '';
6781: }
6782: my $result=&scantron_form_start($max_bubble).$default_form_data;
6783: if ($env{'form.scantron_lastbubblepoints'} ne '') {
6784: $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
6785: }
6786: $r->print($result);
6787:
6788: my @validate_phases=( 'sequence',
6789: 'ID',
6790: 'CODE',
6791: 'doublebubble',
6792: 'missingbubbles');
6793: if (!$env{'form.validatepass'}) {
6794: $env{'form.validatepass'} = 0;
6795: }
6796: my $currentphase=$env{'form.validatepass'};
6797:
6798:
6799: my $stop=0;
6800: while (!$stop && $currentphase < scalar(@validate_phases)) {
6801: $r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
6802: $r->rflush();
6803:
6804: my $which="scantron_validate_".$validate_phases[$currentphase];
6805: {
6806: no strict 'refs';
6807: ($stop,$currentphase)=&$which($r,$currentphase);
6808: }
6809: }
6810: if (!$stop) {
6811: my $warning=&scantron_warning_screen('Start Grading',$symb);
6812: $r->print(&mt('Validation process complete.').'<br />'.
6813: $warning.
6814: &mt('Perform verification for each student after storage of submissions?').
6815: ' <span class="LC_nobreak"><label>'.
6816: '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
6817: (' 'x3).'<label>'.
6818: '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
6819: '</label></span><br />'.
6820: &mt('Grading will take longer if you use verification.').'<br />'.
6821: &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','»').'<br /><br />'.
6822: '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
6823: '<input type="hidden" name="command" value="scantron_process" />'."\n");
6824: } else {
6825: $r->print('<input type="hidden" name="command" value="scantron_validate" />');
6826: $r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
6827: }
6828: if ($stop) {
6829: if ($validate_phases[$currentphase] eq 'sequence') {
6830: $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' → " />');
6831: $r->print(' '.&mt('this error').' <br />');
6832:
6833: $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>');
6834: } else {
6835: if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
6836: $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' →" onclick="javascript:verify_bubble_radio(this.form)" />');
6837: } else {
6838: $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' →" />');
6839: }
6840: $r->print(' '.&mt('using corrected info').' <br />');
6841: $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
6842: $r->print(" ".&mt("this scanline saving it for later."));
6843: }
6844: }
6845: $r->print(" </form><br />");
6846: return '';
6847: }
6848:
6849:
6850: =pod
6851:
6852: =item scantron_remove_file
6853:
6854: Removes the requested bubblesheet data file, makes sure that
6855: scantron_original_<filename> is never removed
6856:
6857:
6858: =cut
6859:
6860: sub scantron_remove_file {
6861: my ($which)=@_;
6862: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6863: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6864: my $file='scantron_';
6865: if ($which eq 'corrected' || $which eq 'skipped') {
6866: $file.=$which.'_';
6867: } else {
6868: return 'refused';
6869: }
6870: $file.=$env{'form.scantron_selectfile'};
6871: return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
6872: }
6873:
6874:
6875: =pod
6876:
6877: =item scantron_remove_scan_data
6878:
6879: Removes all scan_data correction for the requested bubblesheet
6880: data file. (In the case that both the are doing skipped records we need
6881: to remember the old skipped lines for the time being so that element
6882: persists for a while.)
6883:
6884: =cut
6885:
6886: sub scantron_remove_scan_data {
6887: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6888: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6889: my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
6890: my @todelete;
6891: my $filename=$env{'form.scantron_selectfile'};
6892: foreach my $key (@keys) {
6893: if ($key=~/^\Q$filename\E_/) {
6894: if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
6895: $key=~/remember_skipping/) {
6896: next;
6897: }
6898: push(@todelete,$key);
6899: }
6900: }
6901: my $result;
6902: if (@todelete) {
6903: $result = &Apache::lonnet::del('nohist_scantrondata',
6904: \@todelete,$cdom,$cname);
6905: } else {
6906: $result = 'ok';
6907: }
6908: return $result;
6909: }
6910:
6911:
6912: =pod
6913:
6914: =item scantron_getfile
6915:
6916: Fetches the requested bubblesheet data file (all 3 versions), and
6917: the scan_data hash
6918:
6919: Arguments:
6920: None
6921:
6922: Returns:
6923: 2 hash references
6924:
6925: - first one has
6926: orig -
6927: corrected -
6928: skipped - each of which points to an array ref of the specified
6929: file broken up into individual lines
6930: count - number of scanlines
6931:
6932: - second is the scan_data hash possible keys are
6933: ($number refers to scanline numbered $number and thus the key affects
6934: only that scanline
6935: $bubline refers to the specific bubble line element and the aspects
6936: refers to that specific bubble line element)
6937:
6938: $number.user - username:domain to use
6939: $number.CODE_ignore_dup
6940: - ignore the duplicate CODE error
6941: $number.useCODE
6942: - use the CODE in the scanline as is
6943: $number.no_bubble.$bubline
6944: - it is valid that there is no bubbled in bubble
6945: at $number $bubline
6946: remember_skipping
6947: - a frozen hash containing keys of $number and values
6948: of either
6949: 1 - we are on a 'do skipped records pass' and plan
6950: on processing this line
6951: 2 - we are on a 'do skipped records pass' and this
6952: scanline has been marked to skip yet again
6953:
6954: =cut
6955:
6956: sub scantron_getfile {
6957: #FIXME really would prefer a scantron directory
6958: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6959: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6960: my $lines;
6961: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
6962: 'scantron_orig_'.$env{'form.scantron_selectfile'});
6963: my %scanlines;
6964: $scanlines{'orig'}=[(split("\n",$lines,-1))];
6965: my $temp=$scanlines{'orig'};
6966: $scanlines{'count'}=$#$temp;
6967:
6968: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
6969: 'scantron_corrected_'.$env{'form.scantron_selectfile'});
6970: if ($lines eq '-1') {
6971: $scanlines{'corrected'}=[];
6972: } else {
6973: $scanlines{'corrected'}=[(split("\n",$lines,-1))];
6974: }
6975: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
6976: 'scantron_skipped_'.$env{'form.scantron_selectfile'});
6977: if ($lines eq '-1') {
6978: $scanlines{'skipped'}=[];
6979: } else {
6980: $scanlines{'skipped'}=[(split("\n",$lines,-1))];
6981: }
6982: my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
6983: if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
6984: my %scan_data = @tmp;
6985: return (\%scanlines,\%scan_data);
6986: }
6987:
6988: =pod
6989:
6990: =item lonnet_putfile
6991:
6992: Wrapper routine to call &Apache::lonnet::finishuserfileupload
6993:
6994: Arguments:
6995: $contents - data to store
6996: $filename - filename to store $contents into
6997:
6998: Returns:
6999: result value from &Apache::lonnet::finishuserfileupload
7000:
7001: =cut
7002:
7003: sub lonnet_putfile {
7004: my ($contents,$filename)=@_;
7005: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
7006: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7007: $env{'form.sillywaytopassafilearound'}=$contents;
7008: &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
7009:
7010: }
7011:
7012: =pod
7013:
7014: =item scantron_putfile
7015:
7016: Stores the current version of the bubblesheet data files, and the
7017: scan_data hash. (Does not modify the original version only the
7018: corrected and skipped versions.
7019:
7020: Arguments:
7021: $scanlines - hash ref that looks like the first return value from
7022: &scantron_getfile()
7023: $scan_data - hash ref that looks like the second return value from
7024: &scantron_getfile()
7025:
7026: =cut
7027:
7028: sub scantron_putfile {
7029: my ($scanlines,$scan_data) = @_;
7030: #FIXME really would prefer a scantron directory
7031: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7032: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7033: if ($scanlines) {
7034: my $prefix='scantron_';
7035: # no need to update orig, shouldn't change
7036: # &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
7037: # $env{'form.scantron_selectfile'});
7038: &lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
7039: $prefix.'corrected_'.
7040: $env{'form.scantron_selectfile'});
7041: &lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
7042: $prefix.'skipped_'.
7043: $env{'form.scantron_selectfile'});
7044: }
7045: &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
7046: }
7047:
7048: =pod
7049:
7050: =item scantron_get_line
7051:
7052: Returns the correct version of the scanline
7053:
7054: Arguments:
7055: $scanlines - hash ref that looks like the first return value from
7056: &scantron_getfile()
7057: $scan_data - hash ref that looks like the second return value from
7058: &scantron_getfile()
7059: $i - number of the requested line (starts at 0)
7060:
7061: Returns:
7062: A scanline, (either the original or the corrected one if it
7063: exists), or undef if the requested scanline should be
7064: skipped. (Either because it's an skipped scanline, or it's an
7065: unskipped scanline and we are not doing a 'do skipped scanlines'
7066: pass.
7067:
7068: =cut
7069:
7070: sub scantron_get_line {
7071: my ($scanlines,$scan_data,$i)=@_;
7072: if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
7073: #if ($scanlines->{'skipped'}[$i]) { return undef; }
7074: if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
7075: return $scanlines->{'orig'}[$i];
7076: }
7077:
7078: =pod
7079:
7080: =item scantron_todo_count
7081:
7082: Counts the number of scanlines that need processing.
7083:
7084: Arguments:
7085: $scanlines - hash ref that looks like the first return value from
7086: &scantron_getfile()
7087: $scan_data - hash ref that looks like the second return value from
7088: &scantron_getfile()
7089:
7090: Returns:
7091: $count - number of scanlines to process
7092:
7093: =cut
7094:
7095: sub get_todo_count {
7096: my ($scanlines,$scan_data)=@_;
7097: my $count=0;
7098: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7099: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7100: if ($line=~/^[\s\cz]*$/) { next; }
7101: $count++;
7102: }
7103: return $count;
7104: }
7105:
7106: =pod
7107:
7108: =item scantron_put_line
7109:
7110: Updates the 'corrected' or 'skipped' versions of the bubblesheet
7111: data file.
7112:
7113: Arguments:
7114: $scanlines - hash ref that looks like the first return value from
7115: &scantron_getfile()
7116: $scan_data - hash ref that looks like the second return value from
7117: &scantron_getfile()
7118: $i - line number to update
7119: $newline - contents of the updated scanline
7120: $skip - if true make the line for skipping and update the
7121: 'skipped' file
7122:
7123: =cut
7124:
7125: sub scantron_put_line {
7126: my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
7127: if ($skip) {
7128: $scanlines->{'skipped'}[$i]=$newline;
7129: &start_skipping($scan_data,$i);
7130: return;
7131: }
7132: $scanlines->{'corrected'}[$i]=$newline;
7133: }
7134:
7135: =pod
7136:
7137: =item scantron_clear_skip
7138:
7139: Remove a line from the 'skipped' file
7140:
7141: Arguments:
7142: $scanlines - hash ref that looks like the first return value from
7143: &scantron_getfile()
7144: $scan_data - hash ref that looks like the second return value from
7145: &scantron_getfile()
7146: $i - line number to update
7147:
7148: =cut
7149:
7150: sub scantron_clear_skip {
7151: my ($scanlines,$scan_data,$i)=@_;
7152: if (exists($scanlines->{'skipped'}[$i])) {
7153: undef($scanlines->{'skipped'}[$i]);
7154: return 1;
7155: }
7156: return 0;
7157: }
7158:
7159: =pod
7160:
7161: =item scantron_filter_not_exam
7162:
7163: Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
7164: filter out resources that are not marked as 'exam' mode
7165:
7166: =cut
7167:
7168: sub scantron_filter_not_exam {
7169: my ($curres)=@_;
7170:
7171: if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
7172: # if the user has asked to not have either hidden
7173: # or 'randomout' controlled resources to be graded
7174: # don't include them
7175: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
7176: && $curres->randomout) {
7177: return 0;
7178: }
7179: return 1;
7180: }
7181: return 0;
7182: }
7183:
7184: =pod
7185:
7186: =item scantron_validate_sequence
7187:
7188: Validates the selected sequence, checking for resource that are
7189: not set to exam mode.
7190:
7191: =cut
7192:
7193: sub scantron_validate_sequence {
7194: my ($r,$currentphase) = @_;
7195:
7196: my $navmap=Apache::lonnavmaps::navmap->new();
7197: unless (ref($navmap)) {
7198: $r->print(&navmap_errormsg());
7199: return (1,$currentphase);
7200: }
7201: my (undef,undef,$sequence)=
7202: &Apache::lonnet::decode_symb($env{'form.selectpage'});
7203:
7204: my $map=$navmap->getResourceByUrl($sequence);
7205:
7206: $r->print('<input type="hidden" name="validate_sequence_exam"
7207: value="ignore" />');
7208: if ($env{'form.validate_sequence_exam'} ne 'ignore') {
7209: my @resources=
7210: $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
7211: if (@resources) {
7212: $r->print(
7213: '<p class="LC_warning">'
7214: .&mt('Some resources in the sequence currently are not set to'
7215: .' bubblesheet exam mode. Grading these resources currently may not'
7216: .' work correctly.')
7217: .'</p>'
7218: );
7219: return (1,$currentphase);
7220: }
7221: }
7222:
7223: return (0,$currentphase+1);
7224: }
7225:
7226:
7227:
7228: sub scantron_validate_ID {
7229: my ($r,$currentphase) = @_;
7230:
7231: #get student info
7232: my $classlist=&Apache::loncoursedata::get_classlist();
7233: my %idmap=&username_to_idmap($classlist);
7234:
7235: #get scantron line setup
7236: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7237: my ($scanlines,$scan_data)=&scantron_getfile();
7238:
7239: my $nav_error;
7240: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
7241: if ($nav_error) {
7242: $r->print(&navmap_errormsg());
7243: return(1,$currentphase);
7244: }
7245:
7246: my %found=('ids'=>{},'usernames'=>{});
7247: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7248: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7249: if ($line=~/^[\s\cz]*$/) { next; }
7250: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7251: $scan_data);
7252: my $id=$$scan_record{'scantron.ID'};
7253: my $found;
7254: foreach my $checkid (keys(%idmap)) {
7255: if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
7256: }
7257: if ($found) {
7258: my $username=$idmap{$found};
7259: if ($found{'ids'}{$found}) {
7260: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
7261: $line,'duplicateID',$found);
7262: return(1,$currentphase);
7263: } elsif ($found{'usernames'}{$username}) {
7264: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
7265: $line,'duplicateID',$username);
7266: return(1,$currentphase);
7267: }
7268: #FIXME store away line we previously saw the ID on to use above
7269: $found{'ids'}{$found}++;
7270: $found{'usernames'}{$username}++;
7271: } else {
7272: if ($id =~ /^\s*$/) {
7273: my $username=&scan_data($scan_data,"$i.user");
7274: if (defined($username) && $found{'usernames'}{$username}) {
7275: &scantron_get_correction($r,$i,$scan_record,
7276: \%scantron_config,
7277: $line,'duplicateID',$username);
7278: return(1,$currentphase);
7279: } elsif (!defined($username)) {
7280: &scantron_get_correction($r,$i,$scan_record,
7281: \%scantron_config,
7282: $line,'incorrectID');
7283: return(1,$currentphase);
7284: }
7285: $found{'usernames'}{$username}++;
7286: } else {
7287: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
7288: $line,'incorrectID');
7289: return(1,$currentphase);
7290: }
7291: }
7292: }
7293:
7294: return (0,$currentphase+1);
7295: }
7296:
7297:
7298: sub scantron_get_correction {
7299: my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
7300: $randomorder,$randompick,$respnumlookup,$startline)=@_;
7301: #FIXME in the case of a duplicated ID the previous line, probably need
7302: #to show both the current line and the previous one and allow skipping
7303: #the previous one or the current one
7304:
7305: if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
7306: $r->print(
7307: '<p class="LC_warning">'
7308: .&mt('An error was detected ([_1]) for PaperID [_2]',
7309: "<b>$error</b>",
7310: '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
7311: ."</p> \n");
7312: } else {
7313: $r->print(
7314: '<p class="LC_warning">'
7315: .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
7316: "<b>$error</b>", $i, "<pre>$line</pre>")
7317: ."</p> \n");
7318: }
7319: my $message =
7320: '<p>'
7321: .&mt('The ID on the form is [_1]',
7322: "<tt>$$scan_record{'scantron.ID'}</tt>")
7323: .'<br />'
7324: .&mt('The name on the paper is [_1], [_2]',
7325: $$scan_record{'scantron.LastName'},
7326: $$scan_record{'scantron.FirstName'})
7327: .'</p>';
7328:
7329: $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
7330: $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
7331: # Array populated for doublebubble or
7332: my @lines_to_correct; # missingbubble errors to build javascript
7333: # to validate radio button checking
7334:
7335: if ($error =~ /ID$/) {
7336: if ($error eq 'incorrectID') {
7337: $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
7338: "</p>\n");
7339: } elsif ($error eq 'duplicateID') {
7340: $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
7341: }
7342: $r->print($message);
7343: $r->print("<p>".&mt("How should I handle this?")." <br /> \n");
7344: $r->print("\n<ul><li> ");
7345: #FIXME it would be nice if this sent back the user ID and
7346: #could do partial userID matches
7347: $r->print(&Apache::loncommon::selectstudent_link('scantronupload',
7348: 'scantron_username','scantron_domain'));
7349: $r->print(": <input type='text' name='scantron_username' value='' />");
7350: $r->print("\n:\n".
7351: &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
7352:
7353: $r->print('</li>');
7354: } elsif ($error =~ /CODE$/) {
7355: if ($error eq 'incorrectCODE') {
7356: $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
7357: } elsif ($error eq 'duplicateCODE') {
7358: $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");
7359: }
7360: $r->print("<p>".&mt('The CODE on the form is [_1]',
7361: "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
7362: ."</p>\n");
7363: $r->print($message);
7364: $r->print("<p>".&mt("How should I handle this?")."</p>\n");
7365: $r->print("\n<br /> ");
7366: my $i=0;
7367: if ($error eq 'incorrectCODE'
7368: && $$scan_record{'scantron.CODE'}=~/\S/ ) {
7369: my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
7370: if ($closest > 0) {
7371: foreach my $testcode (@{$closest}) {
7372: my $checked='';
7373: if (!$i) { $checked=' checked="checked"'; }
7374: $r->print("
7375: <label>
7376: <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
7377: ".&mt("Use the similar CODE [_1] instead.",
7378: "<b><tt>".$testcode."</tt></b>")."
7379: </label>
7380: <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
7381: $r->print("\n<br />");
7382: $i++;
7383: }
7384: }
7385: }
7386: if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
7387: my $checked; if (!$i) { $checked=' checked="checked"'; }
7388: $r->print("
7389: <label>
7390: <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
7391: ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
7392: "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
7393: </label>");
7394: $r->print("\n<br />");
7395: }
7396:
7397: $r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
7398: function change_radio(field) {
7399: var slct=document.scantronupload.scantron_CODE_resolution;
7400: var i;
7401: for (i=0;i<slct.length;i++) {
7402: if (slct[i].value==field) { slct[i].checked=true; }
7403: }
7404: }
7405: ENDSCRIPT
7406: my $href="/adm/pickcode?".
7407: "form=".&escape("scantronupload").
7408: "&scantron_format=".&escape($env{'form.scantron_format'}).
7409: "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
7410: "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
7411: "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
7412: if ($env{'form.scantron_CODElist'} =~ /\S/) {
7413: $r->print("
7414: <label>
7415: <input type='radio' name='scantron_CODE_resolution' value='use_found' />
7416: ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
7417: "<a target='_blank' href='$href'>","</a>")."
7418: </label>
7419: ".&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\')" />'));
7420: $r->print("\n<br />");
7421: }
7422: $r->print("
7423: <label>
7424: <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
7425: ".&mt("Use [_1] as the CODE.",
7426: "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
7427: $r->print("\n<br /><br />");
7428: } elsif ($error eq 'doublebubble') {
7429: $r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
7430:
7431: # The form field scantron_questions is acutally a list of line numbers.
7432: # represented by this form so:
7433:
7434: my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
7435: $respnumlookup,$startline);
7436:
7437: $r->print('<input type="hidden" name="scantron_questions" value="'.
7438: $line_list.'" />');
7439: $r->print($message);
7440: $r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
7441: foreach my $question (@{$arg}) {
7442: my @linenums = &prompt_for_corrections($r,$question,$scan_config,
7443: $scan_record, $error,
7444: $randomorder,$randompick,
7445: $respnumlookup,$startline);
7446: push(@lines_to_correct,@linenums);
7447: }
7448: $r->print(&verify_bubbles_checked(@lines_to_correct));
7449: } elsif ($error eq 'missingbubble') {
7450: $r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
7451: $r->print($message);
7452: $r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
7453: $r->print(&mt("Some questions have no scanned bubbles.")."\n");
7454:
7455: # The form field scantron_questions is actually a list of line numbers not
7456: # a list of question numbers. Therefore:
7457: #
7458:
7459: my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
7460: $respnumlookup,$startline);
7461:
7462: $r->print('<input type="hidden" name="scantron_questions" value="'.
7463: $line_list.'" />');
7464: foreach my $question (@{$arg}) {
7465: my @linenums = &prompt_for_corrections($r,$question,$scan_config,
7466: $scan_record, $error,
7467: $randomorder,$randompick,
7468: $respnumlookup,$startline);
7469: push(@lines_to_correct,@linenums);
7470: }
7471: $r->print(&verify_bubbles_checked(@lines_to_correct));
7472: } else {
7473: $r->print("\n<ul>");
7474: }
7475: $r->print("\n</li></ul>");
7476: }
7477:
7478: sub verify_bubbles_checked {
7479: my (@ansnums) = @_;
7480: my $ansnumstr = join('","',@ansnums);
7481: my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
7482: my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
7483: function verify_bubble_radio(form) {
7484: var ansnumArray = new Array ("$ansnumstr");
7485: var need_bubble_count = 0;
7486: for (var i=0; i<ansnumArray.length; i++) {
7487: if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
7488: var bubble_picked = 0;
7489: for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
7490: if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
7491: bubble_picked = 1;
7492: }
7493: }
7494: if (bubble_picked == 0) {
7495: need_bubble_count ++;
7496: }
7497: }
7498: }
7499: if (need_bubble_count) {
7500: alert("$warning");
7501: return;
7502: }
7503: form.submit();
7504: }
7505: ENDSCRIPT
7506: return $output;
7507: }
7508:
7509: =pod
7510:
7511: =item questions_to_line_list
7512:
7513: Converts a list of questions into a string of comma separated
7514: line numbers in the answer sheet used by the questions. This is
7515: used to fill in the scantron_questions form field.
7516:
7517: Arguments:
7518: questions - Reference to an array of questions.
7519: randomorder - True if randomorder in use.
7520: randompick - True if randompick in use.
7521: respnumlookup - Reference to HASH mapping question numbers in bubble lines
7522: for current line to question number used for same question
7523: in "Master Seqence" (as seen by Course Coordinator).
7524: startline - Reference to hash where key is question number (0 is first)
7525: and key is number of first bubble line for current student
7526: or code-based randompick and/or randomorder.
7527:
7528: =cut
7529:
7530:
7531: sub questions_to_line_list {
7532: my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
7533: my @lines;
7534:
7535: foreach my $item (@{$questions}) {
7536: my $question = $item;
7537: my ($first,$count,$last);
7538: if ($item =~ /^(\d+)\.(\d+)$/) {
7539: $question = $1;
7540: my $subquestion = $2;
7541: my $responsenum = $question-1;
7542: if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
7543: $responsenum = $respnumlookup->{$question-1};
7544: if (ref($startline) eq 'HASH') {
7545: $first = $startline->{$question-1} + 1;
7546: }
7547: } else {
7548: $first = $first_bubble_line{$responsenum} + 1;
7549: }
7550: my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
7551: my $subcount = 1;
7552: while ($subcount<$subquestion) {
7553: $first += $subans[$subcount-1];
7554: $subcount ++;
7555: }
7556: $count = $subans[$subquestion-1];
7557: } else {
7558: my $responsenum = $question-1;
7559: if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
7560: $responsenum = $respnumlookup->{$question-1};
7561: if (ref($startline) eq 'HASH') {
7562: $first = $startline->{$question-1} + 1;
7563: }
7564: } else {
7565: $first = $first_bubble_line{$responsenum} + 1;
7566: }
7567: $count = $bubble_lines_per_response{$responsenum};
7568: }
7569: $last = $first+$count-1;
7570: push(@lines, ($first..$last));
7571: }
7572: return join(',', @lines);
7573: }
7574:
7575: =pod
7576:
7577: =item prompt_for_corrections
7578:
7579: Prompts for a potentially multiline correction to the
7580: user's bubbling (factors out common code from scantron_get_correction
7581: for multi and missing bubble cases).
7582:
7583: Arguments:
7584: $r - Apache request object.
7585: $question - The question number to prompt for.
7586: $scan_config - The scantron file configuration hash.
7587: $scan_record - Reference to the hash that has the the parsed scanlines.
7588: $error - Type of error
7589: $randomorder - True if randomorder in use.
7590: $randompick - True if randompick in use.
7591: $respnumlookup - Reference to HASH mapping question numbers in bubble lines
7592: for current line to question number used for same question
7593: in "Master Seqence" (as seen by Course Coordinator).
7594: $startline - Reference to hash where key is question number (0 is first)
7595: and value is number of first bubble line for current student
7596: or code-based randompick and/or randomorder.
7597:
7598:
7599: Implicit inputs:
7600: %bubble_lines_per_response - Starting line numbers for each question.
7601: Numbered from 0 (but question numbers are from
7602: 1.
7603: %first_bubble_line - Starting bubble line for each question.
7604: %subdivided_bubble_lines - optionresponse, matchresponse and rankresponse
7605: type problems render as separate sub-questions,
7606: in exam mode. This hash contains a
7607: comma-separated list of the lines per
7608: sub-question.
7609: %responsetype_per_response - essayresponse, formularesponse,
7610: stringresponse, imageresponse, reactionresponse,
7611: and organicresponse type problem parts can have
7612: multiple lines per response if the weight
7613: assigned exceeds 10. In this case, only
7614: one bubble per line is permitted, but more
7615: than one line might contain bubbles, e.g.
7616: bubbling of: line 1 - J, line 2 - J,
7617: line 3 - B would assign 22 points.
7618:
7619: =cut
7620:
7621: sub prompt_for_corrections {
7622: my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
7623: $randompick, $respnumlookup, $startline) = @_;
7624: my ($current_line,$lines);
7625: my @linenums;
7626: my $questionnum = $question;
7627: my ($first,$responsenum);
7628: if ($question =~ /^(\d+)\.(\d+)$/) {
7629: $question = $1;
7630: my $subquestion = $2;
7631: if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
7632: $responsenum = $respnumlookup->{$question-1};
7633: if (ref($startline) eq 'HASH') {
7634: $first = $startline->{$question-1};
7635: }
7636: } else {
7637: $responsenum = $question-1;
7638: $first = $first_bubble_line{$responsenum};
7639: }
7640: $current_line = $first + 1 ;
7641: my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
7642: my $subcount = 1;
7643: while ($subcount<$subquestion) {
7644: $current_line += $subans[$subcount-1];
7645: $subcount ++;
7646: }
7647: $lines = $subans[$subquestion-1];
7648: } else {
7649: if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
7650: $responsenum = $respnumlookup->{$question-1};
7651: if (ref($startline) eq 'HASH') {
7652: $first = $startline->{$question-1};
7653: }
7654: } else {
7655: $responsenum = $question-1;
7656: $first = $first_bubble_line{$responsenum};
7657: }
7658: $current_line = $first + 1;
7659: $lines = $bubble_lines_per_response{$responsenum};
7660: }
7661: if ($lines > 1) {
7662: $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
7663: if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
7664: ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
7665: ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
7666: ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
7667: ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
7668: ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
7669: $r->print(
7670: &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)
7671: .'<br /><br />'
7672: .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
7673: .'<br />'
7674: .&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.')
7675: .'<br />'
7676: .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
7677: .'<br /><br />'
7678: );
7679: } else {
7680: $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
7681: }
7682: }
7683: for (my $i =0; $i < $lines; $i++) {
7684: my $selected = $$scan_record{"scantron.$current_line.answer"};
7685: &scantron_bubble_selector($r,$scan_config,$current_line,
7686: $questionnum,$error,split('', $selected));
7687: push(@linenums,$current_line);
7688: $current_line++;
7689: }
7690: if ($lines > 1) {
7691: $r->print("<hr /><br />");
7692: }
7693: return @linenums;
7694: }
7695:
7696: =pod
7697:
7698: =item scantron_bubble_selector
7699:
7700: Generates the html radiobuttons to correct a single bubble line
7701: possibly showing the existing the selected bubbles if known
7702:
7703: Arguments:
7704: $r - Apache request object
7705: $scan_config - hash from &get_scantron_config()
7706: $line - Number of the line being displayed.
7707: $questionnum - Question number (may include subquestion)
7708: $error - Type of error.
7709: @selected - Array of bubbles picked on this line.
7710:
7711: =cut
7712:
7713: sub scantron_bubble_selector {
7714: my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
7715: my $max=$$scan_config{'Qlength'};
7716:
7717: my $scmode=$$scan_config{'Qon'};
7718: if ($scmode eq 'number' || $scmode eq 'letter') {
7719: if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
7720: ($$scan_config{'BubblesPerRow'} > 0)) {
7721: $max=$$scan_config{'BubblesPerRow'};
7722: if (($scmode eq 'number') && ($max > 10)) {
7723: $max = 10;
7724: } elsif (($scmode eq 'letter') && $max > 26) {
7725: $max = 26;
7726: }
7727: } else {
7728: $max = 10;
7729: }
7730: }
7731:
7732: my @alphabet=('A'..'Z');
7733: $r->print(&Apache::loncommon::start_data_table().
7734: &Apache::loncommon::start_data_table_row());
7735: $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
7736: for (my $i=0;$i<$max+1;$i++) {
7737: $r->print("\n".'<td align="center">');
7738: if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
7739: else { $r->print(' '); }
7740: $r->print('</td>');
7741: }
7742: $r->print(&Apache::loncommon::end_data_table_row().
7743: &Apache::loncommon::start_data_table_row());
7744: for (my $i=0;$i<$max;$i++) {
7745: $r->print("\n".
7746: '<td><label><input type="radio" name="scantron_correct_Q_'.
7747: $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
7748: }
7749: my $nobub_checked = ' ';
7750: if ($error eq 'missingbubble') {
7751: $nobub_checked = ' checked = "checked" ';
7752: }
7753: $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
7754: $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
7755: '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
7756: $line.'" value="'.$questionnum.'" /></td>');
7757: $r->print(&Apache::loncommon::end_data_table_row().
7758: &Apache::loncommon::end_data_table());
7759: }
7760:
7761: =pod
7762:
7763: =item num_matches
7764:
7765: Counts the number of characters that are the same between the two arguments.
7766:
7767: Arguments:
7768: $orig - CODE from the scanline
7769: $code - CODE to match against
7770:
7771: Returns:
7772: $count - integer count of the number of same characters between the
7773: two arguments
7774:
7775: =cut
7776:
7777: sub num_matches {
7778: my ($orig,$code) = @_;
7779: my @code=split(//,$code);
7780: my @orig=split(//,$orig);
7781: my $same=0;
7782: for (my $i=0;$i<scalar(@code);$i++) {
7783: if ($code[$i] eq $orig[$i]) { $same++; }
7784: }
7785: return $same;
7786: }
7787:
7788: =pod
7789:
7790: =item scantron_get_closely_matching_CODEs
7791:
7792: Cycles through all CODEs and finds the set that has the greatest
7793: number of same characters as the provided CODE
7794:
7795: Arguments:
7796: $allcodes - hash ref returned by &get_codes()
7797: $CODE - CODE from the current scanline
7798:
7799: Returns:
7800: 2 element list
7801: - first elements is number of how closely matching the best fit is
7802: (5 means best set has 5 matching characters)
7803: - second element is an arrary ref containing the set of valid CODEs
7804: that best fit the passed in CODE
7805:
7806: =cut
7807:
7808: sub scantron_get_closely_matching_CODEs {
7809: my ($allcodes,$CODE)=@_;
7810: my @CODEs;
7811: foreach my $testcode (sort(keys(%{$allcodes}))) {
7812: push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
7813: }
7814:
7815: return ($#CODEs,$CODEs[-1]);
7816: }
7817:
7818: =pod
7819:
7820: =item get_codes
7821:
7822: Builds a hash which has keys of all of the valid CODEs from the selected
7823: set of remembered CODEs.
7824:
7825: Arguments:
7826: $old_name - name of the set of remembered CODEs
7827: $cdom - domain of the course
7828: $cnum - internal course name
7829:
7830: Returns:
7831: %allcodes - keys are the valid CODEs, values are all 1
7832:
7833: =cut
7834:
7835: sub get_codes {
7836: my ($old_name, $cdom, $cnum) = @_;
7837: if (!$old_name) {
7838: $old_name=$env{'form.scantron_CODElist'};
7839: }
7840: if (!$cdom) {
7841: $cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
7842: }
7843: if (!$cnum) {
7844: $cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
7845: }
7846: my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
7847: $cdom,$cnum);
7848: my %allcodes;
7849: if ($result{"type\0$old_name"} eq 'number') {
7850: %allcodes=map {($_,1)} split(',',$result{$old_name});
7851: } else {
7852: %allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
7853: }
7854: return %allcodes;
7855: }
7856:
7857: =pod
7858:
7859: =item scantron_validate_CODE
7860:
7861: Validates all scanlines in the selected file to not have any
7862: invalid or underspecified CODEs and that none of the codes are
7863: duplicated if this was requested.
7864:
7865: =cut
7866:
7867: sub scantron_validate_CODE {
7868: my ($r,$currentphase) = @_;
7869: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7870: if ($scantron_config{'CODElocation'} &&
7871: $scantron_config{'CODEstart'} &&
7872: $scantron_config{'CODElength'}) {
7873: if (!defined($env{'form.scantron_CODElist'})) {
7874: &FIXME_blow_up()
7875: }
7876: } else {
7877: return (0,$currentphase+1);
7878: }
7879:
7880: my %usedCODEs;
7881:
7882: my %allcodes=&get_codes();
7883:
7884: my $nav_error;
7885: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
7886: if ($nav_error) {
7887: $r->print(&navmap_errormsg());
7888: return(1,$currentphase);
7889: }
7890:
7891: my ($scanlines,$scan_data)=&scantron_getfile();
7892: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7893: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7894: if ($line=~/^[\s\cz]*$/) { next; }
7895: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7896: $scan_data);
7897: my $CODE=$$scan_record{'scantron.CODE'};
7898: my $error=0;
7899: if (!&Apache::lonnet::validCODE($CODE)) {
7900: &scantron_get_correction($r,$i,$scan_record,
7901: \%scantron_config,
7902: $line,'incorrectCODE',\%allcodes);
7903: return(1,$currentphase);
7904: }
7905: if (%allcodes && !exists($allcodes{$CODE})
7906: && !$$scan_record{'scantron.useCODE'}) {
7907: &scantron_get_correction($r,$i,$scan_record,
7908: \%scantron_config,
7909: $line,'incorrectCODE',\%allcodes);
7910: return(1,$currentphase);
7911: }
7912: if (exists($usedCODEs{$CODE})
7913: && $env{'form.scantron_CODEunique'} eq 'yes'
7914: && !$$scan_record{'scantron.CODE_ignore_dup'}) {
7915: &scantron_get_correction($r,$i,$scan_record,
7916: \%scantron_config,
7917: $line,'duplicateCODE',$usedCODEs{$CODE});
7918: return(1,$currentphase);
7919: }
7920: push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
7921: }
7922: return (0,$currentphase+1);
7923: }
7924:
7925: =pod
7926:
7927: =item scantron_validate_doublebubble
7928:
7929: Validates all scanlines in the selected file to not have any
7930: bubble lines with multiple bubbles marked.
7931:
7932: =cut
7933:
7934: sub scantron_validate_doublebubble {
7935: my ($r,$currentphase) = @_;
7936: #get student info
7937: my $classlist=&Apache::loncoursedata::get_classlist();
7938: my %idmap=&username_to_idmap($classlist);
7939: my (undef,undef,$sequence)=
7940: &Apache::lonnet::decode_symb($env{'form.selectpage'});
7941:
7942: #get scantron line setup
7943: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7944: my ($scanlines,$scan_data)=&scantron_getfile();
7945:
7946: my $navmap = Apache::lonnavmaps::navmap->new();
7947: unless (ref($navmap)) {
7948: $r->print(&navmap_errormsg());
7949: return(1,$currentphase);
7950: }
7951: my $map=$navmap->getResourceByUrl($sequence);
7952: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
7953: my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
7954: %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
7955: my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
7956:
7957: my $nav_error;
7958: if (ref($map)) {
7959: $randomorder = $map->randomorder();
7960: $randompick = $map->randompick();
7961: if ($randomorder || $randompick) {
7962: $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
7963: if ($nav_error) {
7964: $r->print(&navmap_errormsg());
7965: return(1,$currentphase);
7966: }
7967: &graders_resources_pass(\@resources,\%grader_partids_by_symb,
7968: \%grader_randomlists_by_symb,$bubbles_per_row);
7969: }
7970: } else {
7971: $r->print(&navmap_errormsg());
7972: return(1,$currentphase);
7973: }
7974:
7975: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
7976: if ($nav_error) {
7977: $r->print(&navmap_errormsg());
7978: return(1,$currentphase);
7979: }
7980:
7981: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7982: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7983: if ($line=~/^[\s\cz]*$/) { next; }
7984: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7985: $scan_data,undef,\%idmap,$randomorder,
7986: $randompick,$sequence,\@master_seq,
7987: \%symb_to_resource,\%grader_partids_by_symb,
7988: \%orderedforcode,\%respnumlookup,\%startline);
7989: if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
7990: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
7991: 'doublebubble',
7992: $$scan_record{'scantron.doubleerror'},
7993: $randomorder,$randompick,\%respnumlookup,\%startline);
7994: return (1,$currentphase);
7995: }
7996: return (0,$currentphase+1);
7997: }
7998:
7999:
8000: sub scantron_get_maxbubble {
8001: my ($nav_error,$scantron_config) = @_;
8002: if (defined($env{'form.scantron_maxbubble'}) &&
8003: $env{'form.scantron_maxbubble'}) {
8004: &restore_bubble_lines();
8005: return $env{'form.scantron_maxbubble'};
8006: }
8007:
8008: my (undef, undef, $sequence) =
8009: &Apache::lonnet::decode_symb($env{'form.selectpage'});
8010:
8011: my $navmap=Apache::lonnavmaps::navmap->new();
8012: unless (ref($navmap)) {
8013: if (ref($nav_error)) {
8014: $$nav_error = 1;
8015: }
8016: return;
8017: }
8018: my $map=$navmap->getResourceByUrl($sequence);
8019: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
8020: my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
8021:
8022: &Apache::lonxml::clear_problem_counter();
8023:
8024: my $uname = $env{'user.name'};
8025: my $udom = $env{'user.domain'};
8026: my $cid = $env{'request.course.id'};
8027: my $total_lines = 0;
8028: %bubble_lines_per_response = ();
8029: %first_bubble_line = ();
8030: %subdivided_bubble_lines = ();
8031: %responsetype_per_response = ();
8032: %masterseq_id_responsenum = ();
8033:
8034: my $response_number = 0;
8035: my $bubble_line = 0;
8036: foreach my $resource (@resources) {
8037: my $resid = $resource->id();
8038: my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
8039: $udom,undef,$bubbles_per_row);
8040: if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
8041: foreach my $part_id (@{$parts}) {
8042: my $lines;
8043:
8044: # TODO - make this a persistent hash not an array.
8045:
8046: # optionresponse, matchresponse and rankresponse type items
8047: # render as separate sub-questions in exam mode.
8048: if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
8049: ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
8050: ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
8051: my ($numbub,$numshown);
8052: if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
8053: if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
8054: $numbub = scalar(@{$analysis->{$part_id.'.options'}});
8055: }
8056: } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
8057: if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
8058: $numbub = scalar(@{$analysis->{$part_id.'.items'}});
8059: }
8060: } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
8061: if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
8062: $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
8063: }
8064: }
8065: if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
8066: $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
8067: }
8068: my $bubbles_per_row =
8069: &bubblesheet_bubbles_per_row($scantron_config);
8070: my $inner_bubble_lines = int($numbub/$bubbles_per_row);
8071: if (($numbub % $bubbles_per_row) != 0) {
8072: $inner_bubble_lines++;
8073: }
8074: for (my $i=0; $i<$numshown; $i++) {
8075: $subdivided_bubble_lines{$response_number} .=
8076: $inner_bubble_lines.',';
8077: }
8078: $subdivided_bubble_lines{$response_number} =~ s/,$//;
8079: $lines = $numshown * $inner_bubble_lines;
8080: } else {
8081: $lines = $analysis->{"$part_id.bubble_lines"};
8082: }
8083:
8084: $first_bubble_line{$response_number} = $bubble_line;
8085: $bubble_lines_per_response{$response_number} = $lines;
8086: $responsetype_per_response{$response_number} =
8087: $analysis->{$part_id.'.type'};
8088: $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;
8089: $response_number++;
8090:
8091: $bubble_line += $lines;
8092: $total_lines += $lines;
8093: }
8094: }
8095: }
8096: &Apache::lonnet::delenv('scantron.');
8097:
8098: &save_bubble_lines();
8099: $env{'form.scantron_maxbubble'} =
8100: $total_lines;
8101: return $env{'form.scantron_maxbubble'};
8102: }
8103:
8104: sub bubblesheet_bubbles_per_row {
8105: my ($scantron_config) = @_;
8106: my $bubbles_per_row;
8107: if (ref($scantron_config) eq 'HASH') {
8108: $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
8109: }
8110: if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
8111: $bubbles_per_row = 10;
8112: }
8113: return $bubbles_per_row;
8114: }
8115:
8116: sub scantron_validate_missingbubbles {
8117: my ($r,$currentphase) = @_;
8118: #get student info
8119: my $classlist=&Apache::loncoursedata::get_classlist();
8120: my %idmap=&username_to_idmap($classlist);
8121: my (undef,undef,$sequence)=
8122: &Apache::lonnet::decode_symb($env{'form.selectpage'});
8123:
8124: #get scantron line setup
8125: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
8126: my ($scanlines,$scan_data)=&scantron_getfile();
8127:
8128: my $navmap = Apache::lonnavmaps::navmap->new();
8129: unless (ref($navmap)) {
8130: $r->print(&navmap_errormsg());
8131: return(1,$currentphase);
8132: }
8133:
8134: my $map=$navmap->getResourceByUrl($sequence);
8135: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
8136: my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
8137: %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
8138: my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
8139:
8140: my $nav_error;
8141: if (ref($map)) {
8142: $randomorder = $map->randomorder();
8143: $randompick = $map->randompick();
8144: if ($randomorder || $randompick) {
8145: $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
8146: if ($nav_error) {
8147: $r->print(&navmap_errormsg());
8148: return(1,$currentphase);
8149: }
8150: &graders_resources_pass(\@resources,\%grader_partids_by_symb,
8151: \%grader_randomlists_by_symb,$bubbles_per_row);
8152: }
8153: } else {
8154: $r->print(&navmap_errormsg());
8155: return(1,$currentphase);
8156: }
8157:
8158:
8159: my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
8160: if ($nav_error) {
8161: $r->print(&navmap_errormsg());
8162: return(1,$currentphase);
8163: }
8164:
8165: if (!$max_bubble) { $max_bubble=2**31; }
8166: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
8167: my $line=&scantron_get_line($scanlines,$scan_data,$i);
8168: if ($line=~/^[\s\cz]*$/) { next; }
8169: my $scan_record =
8170: &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
8171: $randomorder,$randompick,$sequence,\@master_seq,
8172: \%symb_to_resource,\%grader_partids_by_symb,
8173: \%orderedforcode,\%respnumlookup,\%startline);
8174: if (!defined($$scan_record{'scantron.missingerror'})) { next; }
8175: my @to_correct;
8176:
8177: # Probably here's where the error is...
8178:
8179: foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
8180: my $lastbubble;
8181: if ($missing =~ /^(\d+)\.(\d+)$/) {
8182: my $question = $1;
8183: my $subquestion = $2;
8184: my ($first,$responsenum);
8185: if ($randomorder || $randompick) {
8186: $responsenum = $respnumlookup{$question-1};
8187: $first = $startline{$question-1};
8188: } else {
8189: $responsenum = $question-1;
8190: $first = $first_bubble_line{$responsenum};
8191: }
8192: if (!defined($first)) { next; }
8193: my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
8194: my $subcount = 1;
8195: while ($subcount<$subquestion) {
8196: $first += $subans[$subcount-1];
8197: $subcount ++;
8198: }
8199: my $count = $subans[$subquestion-1];
8200: $lastbubble = $first + $count;
8201: } else {
8202: my ($first,$responsenum);
8203: if ($randomorder || $randompick) {
8204: $responsenum = $respnumlookup{$missing-1};
8205: $first = $startline{$missing-1};
8206: } else {
8207: $responsenum = $missing-1;
8208: $first = $first_bubble_line{$responsenum};
8209: }
8210: if (!defined($first)) { next; }
8211: $lastbubble = $first + $bubble_lines_per_response{$responsenum};
8212: }
8213: if ($lastbubble > $max_bubble) { next; }
8214: push(@to_correct,$missing);
8215: }
8216: if (@to_correct) {
8217: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
8218: $line,'missingbubble',\@to_correct,
8219: $randomorder,$randompick,\%respnumlookup,
8220: \%startline);
8221: return (1,$currentphase);
8222: }
8223:
8224: }
8225: return (0,$currentphase+1);
8226: }
8227:
8228: sub hand_bubble_option {
8229: my (undef, undef, $sequence) =
8230: &Apache::lonnet::decode_symb($env{'form.selectpage'});
8231: return if ($sequence eq '');
8232: my $navmap = Apache::lonnavmaps::navmap->new();
8233: unless (ref($navmap)) {
8234: return;
8235: }
8236: my $needs_hand_bubbles;
8237: my $map=$navmap->getResourceByUrl($sequence);
8238: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
8239: foreach my $res (@resources) {
8240: if (ref($res)) {
8241: if ($res->is_problem()) {
8242: my $partlist = $res->parts();
8243: foreach my $part (@{ $partlist }) {
8244: my @types = $res->responseType($part);
8245: if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
8246: $needs_hand_bubbles = 1;
8247: last;
8248: }
8249: }
8250: }
8251: }
8252: }
8253: if ($needs_hand_bubbles) {
8254: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
8255: my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
8256: return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
8257: &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 />').
8258: '<label><input type="radio" name="scantron_lastbubblepoints" value="'.$bubbles_per_row.'" checked="checked" />'.&mt('[quant,_1,point]',$bubbles_per_row).'</label> '.&mt('or').' '.
8259: '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
8260: }
8261: return;
8262: }
8263:
8264: sub scantron_process_students {
8265: my ($r,$symb) = @_;
8266:
8267: my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
8268: if (!$symb) {
8269: return '';
8270: }
8271: my $default_form_data=&defaultFormData($symb);
8272:
8273: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
8274: my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
8275: my ($scanlines,$scan_data)=&scantron_getfile();
8276: my $classlist=&Apache::loncoursedata::get_classlist();
8277: my %idmap=&username_to_idmap($classlist);
8278: my $navmap=Apache::lonnavmaps::navmap->new();
8279: unless (ref($navmap)) {
8280: $r->print(&navmap_errormsg());
8281: return '';
8282: }
8283: my $map=$navmap->getResourceByUrl($sequence);
8284: my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
8285: %grader_randomlists_by_symb);
8286: if (ref($map)) {
8287: $randomorder = $map->randomorder();
8288: $randompick = $map->randompick();
8289: } else {
8290: $r->print(&navmap_errormsg());
8291: return '';
8292: }
8293: my $nav_error;
8294: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
8295: if ($randomorder || $randompick) {
8296: $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
8297: if ($nav_error) {
8298: $r->print(&navmap_errormsg());
8299: return '';
8300: }
8301: }
8302: &graders_resources_pass(\@resources,\%grader_partids_by_symb,
8303: \%grader_randomlists_by_symb,$bubbles_per_row);
8304:
8305: my ($uname,$udom);
8306: my $result= <<SCANTRONFORM;
8307: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
8308: <input type="hidden" name="command" value="scantron_configphase" />
8309: $default_form_data
8310: SCANTRONFORM
8311: $r->print($result);
8312:
8313: my @delayqueue;
8314: my (%completedstudents,%scandata);
8315:
8316: my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
8317: my $count=&get_todo_count($scanlines,$scan_data);
8318: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
8319: &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
8320: $r->print('<br />');
8321: my $start=&Time::HiRes::time();
8322: my $i=-1;
8323: my $started;
8324:
8325: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
8326: if ($nav_error) {
8327: $r->print(&navmap_errormsg());
8328: return '';
8329: }
8330:
8331: # If an ssi failed in scantron_get_maxbubble, put an error message out to
8332: # the user and return.
8333:
8334: if ($ssi_error) {
8335: $r->print("</form>");
8336: &ssi_print_error($r);
8337: &Apache::lonnet::remove_lock($lock);
8338: return ''; # Dunno why the other returns return '' rather than just returning.
8339: }
8340:
8341: my %lettdig = &letter_to_digits();
8342: my $numletts = scalar(keys(%lettdig));
8343: my %orderedforcode;
8344:
8345: while ($i<$scanlines->{'count'}) {
8346: ($uname,$udom)=('','');
8347: $i++;
8348: my $line=&scantron_get_line($scanlines,$scan_data,$i);
8349: if ($line=~/^[\s\cz]*$/) { next; }
8350: if ($started) {
8351: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
8352: }
8353: $started=1;
8354: my %respnumlookup = ();
8355: my %startline = ();
8356: my $total;
8357: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
8358: $scan_data,undef,\%idmap,$randomorder,
8359: $randompick,$sequence,\@master_seq,
8360: \%symb_to_resource,\%grader_partids_by_symb,
8361: \%orderedforcode,\%respnumlookup,\%startline,
8362: \$total);
8363: unless ($uname=&scantron_find_student($scan_record,$scan_data,
8364: \%idmap,$i)) {
8365: &scantron_add_delay(\@delayqueue,$line,
8366: 'Unable to find a student that matches',1);
8367: next;
8368: }
8369: if (exists $completedstudents{$uname}) {
8370: &scantron_add_delay(\@delayqueue,$line,
8371: 'Student '.$uname.' has multiple sheets',2);
8372: next;
8373: }
8374: my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
8375: my $user = $uname.':'.$usec;
8376: ($uname,$udom)=split(/:/,$uname);
8377:
8378: my $scancode;
8379: if ((exists($scan_record->{'scantron.CODE'})) &&
8380: (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
8381: $scancode = $scan_record->{'scantron.CODE'};
8382: } else {
8383: $scancode = '';
8384: }
8385:
8386: my @mapresources = @resources;
8387: if ($randomorder || $randompick) {
8388: @mapresources =
8389: &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
8390: \%orderedforcode);
8391: }
8392: my (%partids_by_symb,$res_error);
8393: foreach my $resource (@mapresources) {
8394: my $ressymb;
8395: if (ref($resource)) {
8396: $ressymb = $resource->symb();
8397: } else {
8398: $res_error = 1;
8399: last;
8400: }
8401: if ((exists($grader_randomlists_by_symb{$ressymb})) ||
8402: (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
8403: my ($analysis,$parts) =
8404: &scantron_partids_tograde($resource,$env{'request.course.id'},
8405: $uname,$udom,undef,$bubbles_per_row);
8406: $partids_by_symb{$ressymb} = $parts;
8407: } else {
8408: $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
8409: }
8410: }
8411:
8412: if ($res_error) {
8413: &scantron_add_delay(\@delayqueue,$line,
8414: 'An error occurred while grading student '.$uname,2);
8415: next;
8416: }
8417:
8418: &Apache::lonxml::clear_problem_counter();
8419: &Apache::lonnet::appenv($scan_record);
8420:
8421: if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
8422: &scantron_putfile($scanlines,$scan_data);
8423: }
8424:
8425: if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
8426: \@mapresources,\%partids_by_symb,
8427: $bubbles_per_row,$randomorder,$randompick,
8428: \%respnumlookup,\%startline)
8429: eq 'ssi_error') {
8430: $ssi_error = 0; # So end of handler error message does not trigger.
8431: $r->print("</form>");
8432: &ssi_print_error($r);
8433: &Apache::lonnet::remove_lock($lock);
8434: return ''; # Why return ''? Beats me.
8435: }
8436:
8437: if (($scancode) && ($randomorder || $randompick)) {
8438: my $parmresult =
8439: &Apache::lonparmset::storeparm_by_symb($symb,
8440: '0_examcode',2,$scancode,
8441: 'string_examcode',$uname,
8442: $udom);
8443: }
8444: $completedstudents{$uname}={'line'=>$line};
8445: if ($env{'form.verifyrecord'}) {
8446: my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
8447: if ($randompick) {
8448: if ($total) {
8449: $lastpos = $total*$scantron_config{'Qlength'};
8450: }
8451: }
8452:
8453: my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
8454: chomp($studentdata);
8455: $studentdata =~ s/\r$//;
8456: my $studentrecord = '';
8457: my $counter = -1;
8458: foreach my $resource (@mapresources) {
8459: my $ressymb = $resource->symb();
8460: ($counter,my $recording) =
8461: &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
8462: $counter,$studentdata,$partids_by_symb{$ressymb},
8463: \%scantron_config,\%lettdig,$numletts,$randomorder,
8464: $randompick,\%respnumlookup,\%startline);
8465: $studentrecord .= $recording;
8466: }
8467: if ($studentrecord ne $studentdata) {
8468: &Apache::lonxml::clear_problem_counter();
8469: if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
8470: \@mapresources,\%partids_by_symb,
8471: $bubbles_per_row,$randomorder,$randompick,
8472: \%respnumlookup,\%startline)
8473: eq 'ssi_error') {
8474: $ssi_error = 0; # So end of handler error message does not trigger.
8475: $r->print("</form>");
8476: &ssi_print_error($r);
8477: &Apache::lonnet::remove_lock($lock);
8478: delete($completedstudents{$uname});
8479: return '';
8480: }
8481: $counter = -1;
8482: $studentrecord = '';
8483: foreach my $resource (@mapresources) {
8484: my $ressymb = $resource->symb();
8485: ($counter,my $recording) =
8486: &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
8487: $counter,$studentdata,$partids_by_symb{$ressymb},
8488: \%scantron_config,\%lettdig,$numletts,
8489: $randomorder,$randompick,\%respnumlookup,
8490: \%startline);
8491: $studentrecord .= $recording;
8492: }
8493: if ($studentrecord ne $studentdata) {
8494: $r->print('<p><span class="LC_warning">');
8495: if ($scancode eq '') {
8496: $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
8497: $uname.':'.$udom,$scan_record->{'scantron.ID'}));
8498: } else {
8499: $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
8500: $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
8501: }
8502: $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
8503: &Apache::loncommon::start_data_table_header_row()."\n".
8504: '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
8505: &Apache::loncommon::end_data_table_header_row()."\n".
8506: &Apache::loncommon::start_data_table_row().
8507: '<td>'.&mt('Bubblesheet').'</td>'.
8508: '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
8509: &Apache::loncommon::end_data_table_row().
8510: &Apache::loncommon::start_data_table_row().
8511: '<td>'.&mt('Stored submissions').'</td>'.
8512: '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
8513: &Apache::loncommon::end_data_table_row().
8514: &Apache::loncommon::end_data_table().'</p>');
8515: } else {
8516: $r->print('<br /><span class="LC_warning">'.
8517: &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 />'.
8518: &mt("As a consequence, this user's submission history records two tries.").
8519: '</span><br />');
8520: }
8521: }
8522: }
8523: if (&Apache::loncommon::connection_aborted($r)) { last; }
8524: } continue {
8525: &Apache::lonxml::clear_problem_counter();
8526: &Apache::lonnet::delenv('scantron.');
8527: }
8528: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
8529: &Apache::lonnet::remove_lock($lock);
8530: # my $lasttime = &Time::HiRes::time()-$start;
8531: # $r->print("<p>took $lasttime</p>");
8532:
8533: $r->print("</form>");
8534: return '';
8535: }
8536:
8537: sub graders_resources_pass {
8538: my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
8539: $bubbles_per_row) = @_;
8540: if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) &&
8541: (ref($grader_randomlists_by_symb) eq 'HASH')) {
8542: foreach my $resource (@{$resources}) {
8543: my $ressymb = $resource->symb();
8544: my ($analysis,$parts) =
8545: &scantron_partids_tograde($resource,$env{'request.course.id'},
8546: $env{'user.name'},$env{'user.domain'},
8547: 1,$bubbles_per_row);
8548: $grader_partids_by_symb->{$ressymb} = $parts;
8549: if (ref($analysis) eq 'HASH') {
8550: if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
8551: $grader_randomlists_by_symb->{$ressymb} =
8552: $analysis->{'parts_withrandomlist'};
8553: }
8554: }
8555: }
8556: }
8557: return;
8558: }
8559:
8560: =pod
8561:
8562: =item users_order
8563:
8564: Returns array of resources in current map, ordered based on either CODE,
8565: if this is a CODEd exam, or based on student's identity if this is a
8566: "NAMEd" exam.
8567:
8568: Should be used when randomorder and/or randompick applied when the
8569: corresponding exam was printed, prior to students completing bubblesheets
8570: for the version of the exam the student received.
8571:
8572: =cut
8573:
8574: sub users_order {
8575: my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
8576: my @mapresources;
8577: unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
8578: return @mapresources;
8579: }
8580: if ($scancode) {
8581: if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
8582: @mapresources = @{$orderedforcode->{$scancode}};
8583: } else {
8584: $env{'form.CODE'} = $scancode;
8585: my $actual_seq =
8586: &Apache::lonprintout::master_seq_to_person_seq($mapurl,
8587: $master_seq,
8588: $user,$scancode,1);
8589: if (ref($actual_seq) eq 'ARRAY') {
8590: @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
8591: if (ref($orderedforcode) eq 'HASH') {
8592: if (@mapresources > 0) {
8593: $orderedforcode->{$scancode} = \@mapresources;
8594: }
8595: }
8596: }
8597: delete($env{'form.CODE'});
8598: }
8599: } else {
8600: my $actual_seq =
8601: &Apache::lonprintout::master_seq_to_person_seq($mapurl,
8602: $master_seq,
8603: $user,undef,1);
8604: if (ref($actual_seq) eq 'ARRAY') {
8605: @mapresources =
8606: map { $symb_to_resource->{$_}; } @{$actual_seq};
8607: }
8608: }
8609: return @mapresources;
8610: }
8611:
8612: sub grade_student_bubbles {
8613: my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
8614: $randomorder,$randompick,$respnumlookup,$startline) = @_;
8615: my $uselookup = 0;
8616: if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
8617: (ref($startline) eq 'HASH')) {
8618: $uselookup = 1;
8619: }
8620:
8621: if (ref($resources) eq 'ARRAY') {
8622: my $count = 0;
8623: foreach my $resource (@{$resources}) {
8624: my $ressymb = $resource->symb();
8625: my %form = ('submitted' => 'scantron',
8626: 'grade_target' => 'grade',
8627: 'grade_username' => $uname,
8628: 'grade_domain' => $udom,
8629: 'grade_courseid' => $env{'request.course.id'},
8630: 'grade_symb' => $ressymb,
8631: 'CODE' => $scancode
8632: );
8633: if ($bubbles_per_row ne '') {
8634: $form{'bubbles_per_row'} = $bubbles_per_row;
8635: }
8636: if ($env{'form.scantron_lastbubblepoints'} ne '') {
8637: $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
8638: }
8639: if (ref($parts) eq 'HASH') {
8640: if (ref($parts->{$ressymb}) eq 'ARRAY') {
8641: foreach my $part (@{$parts->{$ressymb}}) {
8642: if ($uselookup) {
8643: $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
8644: } else {
8645: $form{'scantron_questnum_start.'.$part} =
8646: 1+$env{'form.scantron.first_bubble_line.'.$count};
8647: }
8648: $count++;
8649: }
8650: }
8651: }
8652: my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
8653: return 'ssi_error' if ($ssi_error);
8654: last if (&Apache::loncommon::connection_aborted($r));
8655: }
8656: }
8657: return;
8658: }
8659:
8660: sub scantron_upload_scantron_data {
8661: my ($r,$symb)=@_;
8662: my $dom = $env{'request.role.domain'};
8663: my $domdesc = &Apache::lonnet::domain($dom,'description');
8664: $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
8665: my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
8666: 'domainid',
8667: 'coursename',$dom);
8668: my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
8669: (' 'x2).&mt('(shows course personnel)');
8670: my $default_form_data=&defaultFormData($symb);
8671: my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
8672: 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.");
8673: $r->print(&Apache::lonhtmlcommon::scripttag('
8674: function checkUpload(formname) {
8675: if (formname.upfile.value == "") {
8676: alert("'.$nofile_alert.'");
8677: return false;
8678: }
8679: if (formname.courseid.value == "") {
8680: alert("'.$nocourseid_alert.'");
8681: return false;
8682: }
8683: formname.submit();
8684: }
8685:
8686: function ToSyllabus() {
8687: var cdom = '."'$dom'".';
8688: var cnum = document.rules.courseid.value;
8689: if (cdom == "" || cdom == null) {
8690: return;
8691: }
8692: if (cnum == "" || cnum == null) {
8693: return;
8694: }
8695: syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
8696: "height=350,width=350,scrollbars=yes,menubar=no");
8697: return;
8698: }
8699:
8700: '));
8701: $r->print('
8702: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
8703:
8704: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
8705: '.$default_form_data.
8706: &Apache::lonhtmlcommon::start_pick_box().
8707: &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
8708: '<input name="courseid" type="text" size="30" />'.$select_link.
8709: &Apache::lonhtmlcommon::row_closure().
8710: &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
8711: '<input name="coursename" type="text" size="30" />'.$syllabuslink.
8712: &Apache::lonhtmlcommon::row_closure().
8713: &Apache::lonhtmlcommon::row_title(&mt('Domain')).
8714: '<input name="domainid" type="hidden" />'.$domdesc.
8715: &Apache::lonhtmlcommon::row_closure().
8716: &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
8717: '<input type="file" name="upfile" size="50" />'.
8718: &Apache::lonhtmlcommon::row_closure(1).
8719: &Apache::lonhtmlcommon::end_pick_box().'<br />
8720:
8721: <input name="command" value="scantronupload_save" type="hidden" />
8722: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
8723: </form>
8724: ');
8725: return '';
8726: }
8727:
8728:
8729: sub scantron_upload_scantron_data_save {
8730: my($r,$symb)=@_;
8731: my $doanotherupload=
8732: '<br /><form action="/adm/grades" method="post">'."\n".
8733: '<input type="hidden" name="command" value="scantronupload" />'."\n".
8734: '<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
8735: '</form>'."\n";
8736: if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
8737: !&Apache::lonnet::allowed('usc',
8738: $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
8739: $r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
8740: unless ($symb) {
8741: $r->print($doanotherupload);
8742: }
8743: return '';
8744: }
8745: my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
8746: my $uploadedfile;
8747: $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
8748: if (length($env{'form.upfile'}) < 2) {
8749: $r->print(
8750: &Apache::lonhtmlcommon::confirm_success(
8751: &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
8752: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
8753: } else {
8754: my $result =
8755: &Apache::lonnet::userfileupload('upfile','','scantron','','','',
8756: $env{'form.courseid'},$env{'form.domainid'});
8757: if ($result =~ m{^/uploaded/}) {
8758: $r->print(
8759: &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
8760: &mt('Uploaded [_1] bytes of data into location: [_2]',
8761: (length($env{'form.upfile'})-1),
8762: '<span class="LC_filename">'.$result.'</span>'));
8763: ($uploadedfile) = ($result =~ m{/([^/]+)$});
8764: $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
8765: $env{'form.courseid'},$uploadedfile));
8766: } else {
8767: $r->print(
8768: &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
8769: &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
8770: $result,
8771: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
8772: }
8773: }
8774: if ($symb) {
8775: $r->print(&scantron_selectphase($r,$uploadedfile,$symb));
8776: } else {
8777: $r->print($doanotherupload);
8778: }
8779: return '';
8780: }
8781:
8782: sub validate_uploaded_scantron_file {
8783: my ($cdom,$cname,$fname) = @_;
8784: my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
8785: my @lines;
8786: if ($scanlines ne '-1') {
8787: @lines=split("\n",$scanlines,-1);
8788: }
8789: my $output;
8790: if (@lines) {
8791: my (%counts,$max_match_format);
8792: my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
8793: my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
8794: my %idmap = &username_to_idmap($classlist);
8795: foreach my $key (keys(%idmap)) {
8796: my $lckey = lc($key);
8797: $idmap{$lckey} = $idmap{$key};
8798: }
8799: my %unique_formats;
8800: my @formatlines = &get_scantronformat_file();
8801: foreach my $line (@formatlines) {
8802: chomp($line);
8803: my @config = split(/:/,$line);
8804: my $idstart = $config[5];
8805: my $idlength = $config[6];
8806: if (($idstart ne '') && ($idlength > 0)) {
8807: if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
8808: push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]);
8809: } else {
8810: $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
8811: }
8812: }
8813: }
8814: foreach my $key (keys(%unique_formats)) {
8815: my ($idstart,$idlength) = split(':',$key);
8816: %{$counts{$key}} = (
8817: 'found' => 0,
8818: 'total' => 0,
8819: );
8820: foreach my $line (@lines) {
8821: next if ($line =~ /^#/);
8822: next if ($line =~ /^[\s\cz]*$/);
8823: my $id = substr($line,$idstart-1,$idlength);
8824: $id = lc($id);
8825: if (exists($idmap{$id})) {
8826: $counts{$key}{'found'} ++;
8827: }
8828: $counts{$key}{'total'} ++;
8829: }
8830: if ($counts{$key}{'total'}) {
8831: my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
8832: if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
8833: $max_match_pct = $percent_match;
8834: $max_match_format = $key;
8835: $found_match_count = $counts{$key}{'found'};
8836: $max_match_count = $counts{$key}{'total'};
8837: }
8838: }
8839: }
8840: if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
8841: my $format_descs;
8842: my $numwithformat = @{$unique_formats{$max_match_format}};
8843: for (my $i=0; $i<$numwithformat; $i++) {
8844: my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
8845: if ($i<$numwithformat-2) {
8846: $format_descs .= '"<i>'.$desc.'</i>", ';
8847: } elsif ($i==$numwithformat-2) {
8848: $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
8849: } elsif ($i==$numwithformat-1) {
8850: $format_descs .= '"<i>'.$desc.'</i>"';
8851: }
8852: }
8853: my $showpct = sprintf("%.0f",$max_match_pct).'%';
8854: $output .= '<br />';
8855: if ($found_match_count == $max_match_count) {
8856: # 100% matching entries
8857: $output .= &Apache::lonhtmlcommon::confirm_success(
8858: &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
8859: '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
8860: &mt('Comparison of student IDs in the uploaded file with'.
8861: ' the course roster found matches for [_1] of the [_2] entries'.
8862: ' in the file (for the format defined for [_3]).',
8863: '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
8864: } else {
8865: # Not all entries matching? -> Show warning and additional info
8866: $output .=
8867: &Apache::lonhtmlcommon::confirm_success(
8868: &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
8869: '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
8870: &mt('Not all entries could be matched!'),1).'<br />'.
8871: &mt('Comparison of student IDs in the uploaded file with'.
8872: ' the course roster found matches for [_1] of the [_2] entries'.
8873: ' in the file (for the format defined for [_3]).',
8874: '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
8875: '<p class="LC_info">'.
8876: &mt('A low percentage of matches results from one of the following:').
8877: '</p><ul>'.
8878: '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
8879: '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
8880: '<i>'.$cdom.'</i>').'</li>'.
8881: '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
8882: '<li>'.&mt('The course roster is not up to date.').'</li>'.
8883: '</ul>';
8884: }
8885: }
8886: } else {
8887: $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
8888: }
8889: return $output;
8890: }
8891:
8892: sub valid_file {
8893: my ($requested_file)=@_;
8894: foreach my $filename (sort(&scantron_filenames())) {
8895: if ($requested_file eq $filename) { return 1; }
8896: }
8897: return 0;
8898: }
8899:
8900: sub scantron_download_scantron_data {
8901: my ($r,$symb)=@_;
8902: my $default_form_data=&defaultFormData($symb);
8903: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
8904: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
8905: my $file=$env{'form.scantron_selectfile'};
8906: if (! &valid_file($file)) {
8907: $r->print('
8908: <p>
8909: '.&mt('The requested filename was invalid.').'
8910: </p>
8911: ');
8912: return;
8913: }
8914: my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
8915: my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
8916: my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
8917: &Apache::lonnet::allowuploaded('/adm/grades',$orig);
8918: &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
8919: &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
8920: $r->print('
8921: <p>
8922: '.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
8923: '<a href="'.$orig.'">','</a>').'
8924: </p>
8925: <p>
8926: '.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
8927: '<a href="'.$corrected.'">','</a>').'
8928: </p>
8929: <p>
8930: '.&mt('[_1]Skipped[_2], a file of records that were skipped.',
8931: '<a href="'.$skipped.'">','</a>').'
8932: </p>
8933: ');
8934: return '';
8935: }
8936:
8937: sub checkscantron_results {
8938: my ($r,$symb) = @_;
8939: if (!$symb) {return '';}
8940: my $cid = $env{'request.course.id'};
8941: my %lettdig = &letter_to_digits();
8942: my $numletts = scalar(keys(%lettdig));
8943: my $cnum = $env{'course.'.$cid.'.num'};
8944: my $cdom = $env{'course.'.$cid.'.domain'};
8945: my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
8946: my %record;
8947: my %scantron_config =
8948: &Apache::grades::get_scantron_config($env{'form.scantron_format'});
8949: my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
8950: my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
8951: my $classlist=&Apache::loncoursedata::get_classlist();
8952: my %idmap=&Apache::grades::username_to_idmap($classlist);
8953: my $navmap=Apache::lonnavmaps::navmap->new();
8954: unless (ref($navmap)) {
8955: $r->print(&navmap_errormsg());
8956: return '';
8957: }
8958: my $map=$navmap->getResourceByUrl($sequence);
8959: my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
8960: %grader_randomlists_by_symb,%orderedforcode);
8961: if (ref($map)) {
8962: $randomorder=$map->randomorder();
8963: $randompick=$map->randompick();
8964: }
8965: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
8966: my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
8967: if ($nav_error) {
8968: $r->print(&navmap_errormsg());
8969: return '';
8970: }
8971: &graders_resources_pass(\@resources,\%grader_partids_by_symb,
8972: \%grader_randomlists_by_symb,$bubbles_per_row);
8973: my ($uname,$udom);
8974: my (%scandata,%lastname,%bylast);
8975: $r->print('
8976: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
8977:
8978: my @delayqueue;
8979: my %completedstudents;
8980:
8981: my $count=&get_todo_count($scanlines,$scan_data);
8982: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
8983: my ($username,$domain,$started);
8984: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
8985: if ($nav_error) {
8986: $r->print(&navmap_errormsg());
8987: return '';
8988: }
8989:
8990: &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
8991: my $start=&Time::HiRes::time();
8992: my $i=-1;
8993:
8994: while ($i<$scanlines->{'count'}) {
8995: ($username,$domain,$uname)=('','','');
8996: $i++;
8997: my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
8998: if ($line=~/^[\s\cz]*$/) { next; }
8999: if ($started) {
9000: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
9001: }
9002: $started=1;
9003: my $scan_record=
9004: &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
9005: $scan_data);
9006: unless ($uname=&scantron_find_student($scan_record,$scan_data,
9007: \%idmap,$i)) {
9008: &Apache::grades::scantron_add_delay(\@delayqueue,$line,
9009: 'Unable to find a student that matches',1);
9010: next;
9011: }
9012: if (exists $completedstudents{$uname}) {
9013: &Apache::grades::scantron_add_delay(\@delayqueue,$line,
9014: 'Student '.$uname.' has multiple sheets',2);
9015: next;
9016: }
9017: my $pid = $scan_record->{'scantron.ID'};
9018: $lastname{$pid} = $scan_record->{'scantron.LastName'};
9019: push(@{$bylast{$lastname{$pid}}},$pid);
9020: my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
9021: my $user = $uname.':'.$usec;
9022: ($username,$domain)=split(/:/,$uname);
9023:
9024: my $scancode;
9025: if ((exists($scan_record->{'scantron.CODE'})) &&
9026: (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
9027: $scancode = $scan_record->{'scantron.CODE'};
9028: } else {
9029: $scancode = '';
9030: }
9031:
9032: my @mapresources = @resources;
9033: my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
9034: my %respnumlookup=();
9035: my %startline=();
9036: if ($randomorder || $randompick) {
9037: @mapresources =
9038: &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
9039: \%orderedforcode);
9040: my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
9041: $scan_record,\@master_seq,\%symb_to_resource,
9042: \%grader_partids_by_symb,\%orderedforcode,
9043: \%respnumlookup,\%startline);
9044: if ($randompick && $total) {
9045: $lastpos = $total*$scantron_config{'Qlength'};
9046: }
9047: }
9048: $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
9049: chomp($scandata{$pid});
9050: $scandata{$pid} =~ s/\r$//;
9051:
9052: my $counter = -1;
9053: foreach my $resource (@mapresources) {
9054: my $parts;
9055: my $ressymb = $resource->symb();
9056: if ((exists($grader_randomlists_by_symb{$ressymb})) ||
9057: (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
9058: (my $analysis,$parts) =
9059: &scantron_partids_tograde($resource,$env{'request.course.id'},
9060: $username,$domain,undef,
9061: $bubbles_per_row);
9062: } else {
9063: $parts = $grader_partids_by_symb{$ressymb};
9064: }
9065: ($counter,my $recording) =
9066: &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
9067: $scandata{$pid},$parts,
9068: \%scantron_config,\%lettdig,$numletts,
9069: $randomorder,$randompick,
9070: \%respnumlookup,\%startline);
9071: $record{$pid} .= $recording;
9072: }
9073: }
9074: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
9075: $r->print('<br />');
9076: my ($okstudents,$badstudents,$numstudents,$passed,$failed);
9077: $passed = 0;
9078: $failed = 0;
9079: $numstudents = 0;
9080: foreach my $last (sort(keys(%bylast))) {
9081: if (ref($bylast{$last}) eq 'ARRAY') {
9082: foreach my $pid (sort(@{$bylast{$last}})) {
9083: my $showscandata = $scandata{$pid};
9084: my $showrecord = $record{$pid};
9085: $showscandata =~ s/\s/ /g;
9086: $showrecord =~ s/\s/ /g;
9087: if ($scandata{$pid} eq $record{$pid}) {
9088: my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
9089: $okstudents .= '<tr class="'.$css_class.'">'.
9090: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
9091: '</tr>'."\n".
9092: '<tr class="'.$css_class.'">'."\n".
9093: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
9094: $passed ++;
9095: } else {
9096: my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
9097: $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".
9098: '</tr>'."\n".
9099: '<tr class="'.$css_class.'">'."\n".
9100: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
9101: '</tr>'."\n";
9102: $failed ++;
9103: }
9104: $numstudents ++;
9105: }
9106: }
9107: }
9108: $r->print(
9109: '<p>'
9110: .&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).',
9111: '<b>',
9112: $numstudents,
9113: '</b>',
9114: $env{'form.scantron_maxbubble'})
9115: .'</p>'
9116: );
9117: $r->print('<p>'
9118: .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
9119: .'<br />'
9120: .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
9121: .'</p>'
9122: );
9123: if ($passed) {
9124: $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
9125: $r->print(&Apache::loncommon::start_data_table()."\n".
9126: &Apache::loncommon::start_data_table_header_row()."\n".
9127: '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
9128: &Apache::loncommon::end_data_table_header_row()."\n".
9129: $okstudents."\n".
9130: &Apache::loncommon::end_data_table().'<br />');
9131: }
9132: if ($failed) {
9133: $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
9134: $r->print(&Apache::loncommon::start_data_table()."\n".
9135: &Apache::loncommon::start_data_table_header_row()."\n".
9136: '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
9137: &Apache::loncommon::end_data_table_header_row()."\n".
9138: $badstudents."\n".
9139: &Apache::loncommon::end_data_table()).'<br />'.
9140: &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.');
9141: }
9142: $r->print('</form><br />');
9143: return;
9144: }
9145:
9146: sub verify_scantron_grading {
9147: my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
9148: $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
9149: $respnumlookup,$startline) = @_;
9150: my ($record,%expected,%startpos);
9151: return ($counter,$record) if (!ref($resource));
9152: return ($counter,$record) if (!$resource->is_problem());
9153: my $symb = $resource->symb();
9154: return ($counter,$record) if (ref($partids) ne 'ARRAY');
9155: foreach my $part_id (@{$partids}) {
9156: $counter ++;
9157: $expected{$part_id} = 0;
9158: my $respnum = $counter;
9159: if ($randomorder || $randompick) {
9160: $respnum = $respnumlookup->{$counter};
9161: $startpos{$part_id} = $startline->{$counter} + 1;
9162: } else {
9163: $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
9164: }
9165: if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
9166: my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
9167: foreach my $item (@sub_lines) {
9168: $expected{$part_id} += $item;
9169: }
9170: } else {
9171: $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
9172: }
9173: }
9174: if ($symb) {
9175: my %recorded;
9176: my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
9177: if ($returnhash{'version'}) {
9178: my %lasthash=();
9179: my $version;
9180: for ($version=1;$version<=$returnhash{'version'};$version++) {
9181: foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
9182: $lasthash{$key}=$returnhash{$version.':'.$key};
9183: }
9184: }
9185: foreach my $key (keys(%lasthash)) {
9186: if ($key =~ /\.scantron$/) {
9187: my $value = &unescape($lasthash{$key});
9188: my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
9189: if ($value eq '') {
9190: for (my $i=0; $i<$expected{$part_id}; $i++) {
9191: for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
9192: $recorded{$part_id} .= $scantron_config->{'Qoff'};
9193: }
9194: }
9195: } else {
9196: my @tocheck;
9197: my @items = split(//,$value);
9198: if (($scantron_config->{'Qon'} eq 'letter') ||
9199: ($scantron_config->{'Qon'} eq 'number')) {
9200: if (@items < $expected{$part_id}) {
9201: my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
9202: my @singles = split(//,$fragment);
9203: foreach my $pos (@singles) {
9204: if ($pos eq ' ') {
9205: push(@tocheck,$pos);
9206: } else {
9207: my $next = shift(@items);
9208: push(@tocheck,$next);
9209: }
9210: }
9211: } else {
9212: @tocheck = @items;
9213: }
9214: foreach my $letter (@tocheck) {
9215: if ($scantron_config->{'Qon'} eq 'letter') {
9216: if ($letter !~ /^[A-J]$/) {
9217: $letter = $scantron_config->{'Qoff'};
9218: }
9219: $recorded{$part_id} .= $letter;
9220: } elsif ($scantron_config->{'Qon'} eq 'number') {
9221: my $digit;
9222: if ($letter !~ /^[A-J]$/) {
9223: $digit = $scantron_config->{'Qoff'};
9224: } else {
9225: $digit = $lettdig->{$letter};
9226: }
9227: $recorded{$part_id} .= $digit;
9228: }
9229: }
9230: } else {
9231: @tocheck = @items;
9232: for (my $i=0; $i<$expected{$part_id}; $i++) {
9233: my $curr_sub = shift(@tocheck);
9234: my $digit;
9235: if ($curr_sub =~ /^[A-J]$/) {
9236: $digit = $lettdig->{$curr_sub}-1;
9237: }
9238: if ($curr_sub eq 'J') {
9239: $digit += scalar($numletts);
9240: }
9241: for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
9242: if ($j == $digit) {
9243: $recorded{$part_id} .= $scantron_config->{'Qon'};
9244: } else {
9245: $recorded{$part_id} .= $scantron_config->{'Qoff'};
9246: }
9247: }
9248: }
9249: }
9250: }
9251: }
9252: }
9253: }
9254: foreach my $part_id (@{$partids}) {
9255: if ($recorded{$part_id} eq '') {
9256: for (my $i=0; $i<$expected{$part_id}; $i++) {
9257: for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
9258: $recorded{$part_id} .= $scantron_config->{'Qoff'};
9259: }
9260: }
9261: }
9262: $record .= $recorded{$part_id};
9263: }
9264: }
9265: return ($counter,$record);
9266: }
9267:
9268: sub letter_to_digits {
9269: my %lettdig = (
9270: A => 1,
9271: B => 2,
9272: C => 3,
9273: D => 4,
9274: E => 5,
9275: F => 6,
9276: G => 7,
9277: H => 8,
9278: I => 9,
9279: J => 0,
9280: );
9281: return %lettdig;
9282: }
9283:
9284:
9285: #-------- end of section for handling grading scantron forms -------
9286: #
9287: #-------------------------------------------------------------------
9288:
9289: #-------------------------- Menu interface -------------------------
9290: #
9291: #--- Href with symb and command ---
9292:
9293: sub href_symb_cmd {
9294: my ($symb,$cmd)=@_;
9295: return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&command='.$cmd;
9296: }
9297:
9298: sub grading_menu {
9299: my ($request,$symb) = @_;
9300: if (!$symb) {return '';}
9301:
9302: my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
9303: 'command'=>'individual');
9304:
9305: my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
9306:
9307: $fields{'command'}='ungraded';
9308: my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
9309:
9310: $fields{'command'}='table';
9311: my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
9312:
9313: $fields{'command'}='all_for_one';
9314: my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
9315:
9316: $fields{'command'}='downloadfilesselect';
9317: my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
9318:
9319: $fields{'command'} = 'csvform';
9320: my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
9321:
9322: $fields{'command'} = 'processclicker';
9323: my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
9324:
9325: $fields{'command'} = 'scantron_selectphase';
9326: my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
9327:
9328: $fields{'command'} = 'initialverifyreceipt';
9329: my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
9330:
9331: my @menu = ({ categorytitle=>'Hand Grading',
9332: items =>[
9333: { linktext => 'Select individual students to grade',
9334: url => $url1a,
9335: permission => 'F',
9336: icon => 'grade_students.png',
9337: linktitle => 'Grade current resource for a selection of students.'
9338: },
9339: { linktext => 'Grade ungraded submissions.',
9340: url => $url1b,
9341: permission => 'F',
9342: icon => 'ungrade_sub.png',
9343: linktitle => 'Grade all submissions that have not been graded yet.'
9344: },
9345:
9346: { linktext => 'Grading table',
9347: url => $url1c,
9348: permission => 'F',
9349: icon => 'grading_table.png',
9350: linktitle => 'Grade current resource for all students.'
9351: },
9352: { linktext => 'Grade page/folder for one student',
9353: url => $url1d,
9354: permission => 'F',
9355: icon => 'grade_PageFolder.png',
9356: linktitle => 'Grade all resources in current page/sequence/folder for one student.'
9357: },
9358: { linktext => 'Download submissions',
9359: url => $url1e,
9360: permission => 'F',
9361: icon => 'download_sub.png',
9362: linktitle => 'Download all students submissions.'
9363: }]},
9364: { categorytitle=>'Automated Grading',
9365: items =>[
9366:
9367: { linktext => 'Upload Scores',
9368: url => $url2,
9369: permission => 'F',
9370: icon => 'uploadscores.png',
9371: linktitle => 'Specify a file containing the class scores for current resource.'
9372: },
9373: { linktext => 'Process Clicker',
9374: url => $url3,
9375: permission => 'F',
9376: icon => 'addClickerInfoFile.png',
9377: linktitle => 'Specify a file containing the clicker information for this resource.'
9378: },
9379: { linktext => 'Grade/Manage/Review Bubblesheets',
9380: url => $url4,
9381: permission => 'F',
9382: icon => 'bubblesheet.png',
9383: linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
9384: },
9385: { linktext => 'Verify Receipt Number',
9386: url => $url5,
9387: permission => 'F',
9388: icon => 'receipt_number.png',
9389: linktitle => 'Verify a system-generated receipt number for correct problem solution.'
9390: }
9391:
9392: ]
9393: });
9394:
9395: # Create the menu
9396: my $Str;
9397: $Str .= '<form method="post" action="" name="gradingMenu">';
9398: $Str .= '<input type="hidden" name="command" value="" />'.
9399: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
9400:
9401: $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
9402: return $Str;
9403: }
9404:
9405:
9406: sub ungraded {
9407: my ($request)=@_;
9408: &submit_options($request);
9409: }
9410:
9411: sub submit_options_sequence {
9412: my ($request,$symb) = @_;
9413: if (!$symb) {return '';}
9414: &commonJSfunctions($request);
9415: my $result;
9416:
9417: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
9418: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
9419: $result.=&selectfield(0).
9420: '<input type="hidden" name="command" value="pickStudentPage" />
9421: <div>
9422: <input type="submit" value="'.&mt('Next').' →" />
9423: </div>
9424: </div>
9425: </form>';
9426: return $result;
9427: }
9428:
9429: sub submit_options_table {
9430: my ($request,$symb) = @_;
9431: if (!$symb) {return '';}
9432: &commonJSfunctions($request);
9433: my $result;
9434:
9435: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
9436: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
9437:
9438: $result.=&selectfield(0).
9439: '<input type="hidden" name="command" value="viewgrades" />
9440: <div>
9441: <input type="submit" value="'.&mt('Next').' →" />
9442: </div>
9443: </div>
9444: </form>';
9445: return $result;
9446: }
9447:
9448: sub submit_options_download {
9449: my ($request,$symb) = @_;
9450: if (!$symb) {return '';}
9451:
9452: &commonJSfunctions($request);
9453:
9454: my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
9455: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
9456: $result.='
9457: <h2>
9458: '.&mt('Select Students for Which to Download Submissions').'
9459: </h2>'.&selectfield(1).'
9460: <input type="hidden" name="command" value="downloadfileslink" />
9461: <input type="submit" value="'.&mt('Next').' →" />
9462: </div>
9463: </div>
9464:
9465:
9466: </form>';
9467: return $result;
9468: }
9469:
9470: #--- Displays the submissions first page -------
9471: sub submit_options {
9472: my ($request,$symb) = @_;
9473: if (!$symb) {return '';}
9474:
9475: &commonJSfunctions($request);
9476: my $result;
9477:
9478: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
9479: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
9480: $result.=&selectfield(1).'
9481: <input type="hidden" name="command" value="submission" />
9482: <input type="submit" value="'.&mt('Next').' →" />
9483: </div>
9484: </div>
9485:
9486:
9487: </form>';
9488: return $result;
9489: }
9490:
9491: sub selectfield {
9492: my ($full)=@_;
9493: my %options =
9494: (&Apache::lonlocal::texthash(
9495: 'yes' => 'with submissions',
9496: 'queued' => 'in grading queue',
9497: 'graded' => 'with ungraded submissions',
9498: 'incorrect' => 'with incorrect submissions',
9499: 'all' => 'with any status'),
9500: 'select_form_order' => ['yes','queued','graded','incorrect','all']);
9501: my $result='<div class="LC_columnSection">
9502:
9503: <fieldset>
9504: <legend>
9505: '.&mt('Sections').'
9506: </legend>
9507: '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
9508: </fieldset>
9509:
9510: <fieldset>
9511: <legend>
9512: '.&mt('Groups').'
9513: </legend>
9514: '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
9515: </fieldset>
9516:
9517: <fieldset>
9518: <legend>
9519: '.&mt('Access Status').'
9520: </legend>
9521: '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
9522: </fieldset>';
9523: if ($full) {
9524: $result.='
9525: <fieldset>
9526: <legend>
9527: '.&mt('Submission Status').'
9528: </legend>'.
9529: &Apache::loncommon::select_form('all','submitonly',\%options).
9530: '</fieldset>';
9531: }
9532: $result.='</div><br />';
9533: return $result;
9534: }
9535:
9536: sub reset_perm {
9537: undef(%perm);
9538: }
9539:
9540: sub init_perm {
9541: &reset_perm();
9542: foreach my $test_perm ('vgr','mgr','opa') {
9543:
9544: my $scope = $env{'request.course.id'};
9545: if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
9546:
9547: $scope .= '/'.$env{'request.course.sec'};
9548: if ( $perm{$test_perm}=
9549: &Apache::lonnet::allowed($test_perm,$scope)) {
9550: $perm{$test_perm.'_section'}=$env{'request.course.sec'};
9551: } else {
9552: delete($perm{$test_perm});
9553: }
9554: }
9555: }
9556: }
9557:
9558: sub init_old_essays {
9559: my ($symb,$apath,$adom,$aname) = @_;
9560: if ($symb ne '') {
9561: my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
9562: if (keys(%essays) > 0) {
9563: $old_essays{$symb} = \%essays;
9564: }
9565: }
9566: return;
9567: }
9568:
9569: sub reset_old_essays {
9570: undef(%old_essays);
9571: }
9572:
9573: sub gather_clicker_ids {
9574: my %clicker_ids;
9575:
9576: my $classlist = &Apache::loncoursedata::get_classlist();
9577:
9578: # Set up a couple variables.
9579: my $username_idx = &Apache::loncoursedata::CL_SNAME();
9580: my $domain_idx = &Apache::loncoursedata::CL_SDOM();
9581: my $status_idx = &Apache::loncoursedata::CL_STATUS();
9582:
9583: foreach my $student (keys(%$classlist)) {
9584: if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
9585: my $username = $classlist->{$student}->[$username_idx];
9586: my $domain = $classlist->{$student}->[$domain_idx];
9587: my $clickers =
9588: (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
9589: foreach my $id (split(/\,/,$clickers)) {
9590: $id=~s/^[\#0]+//;
9591: $id=~s/[\-\:]//g;
9592: if (exists($clicker_ids{$id})) {
9593: $clicker_ids{$id}.=','.$username.':'.$domain;
9594: } else {
9595: $clicker_ids{$id}=$username.':'.$domain;
9596: }
9597: }
9598: }
9599: return %clicker_ids;
9600: }
9601:
9602: sub gather_adv_clicker_ids {
9603: my %clicker_ids;
9604: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
9605: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
9606: my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
9607: foreach my $element (sort(keys(%coursepersonnel))) {
9608: foreach my $person (split(/\,/,$coursepersonnel{$element})) {
9609: my ($puname,$pudom)=split(/\:/,$person);
9610: my $clickers =
9611: (&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
9612: foreach my $id (split(/\,/,$clickers)) {
9613: $id=~s/^[\#0]+//;
9614: $id=~s/[\-\:]//g;
9615: if (exists($clicker_ids{$id})) {
9616: $clicker_ids{$id}.=','.$puname.':'.$pudom;
9617: } else {
9618: $clicker_ids{$id}=$puname.':'.$pudom;
9619: }
9620: }
9621: }
9622: }
9623: return %clicker_ids;
9624: }
9625:
9626: sub clicker_grading_parameters {
9627: return ('gradingmechanism' => 'scalar',
9628: 'upfiletype' => 'scalar',
9629: 'specificid' => 'scalar',
9630: 'pcorrect' => 'scalar',
9631: 'pincorrect' => 'scalar');
9632: }
9633:
9634: sub process_clicker {
9635: my ($r,$symb)=@_;
9636: if (!$symb) {return '';}
9637: my $result=&checkforfile_js();
9638: $result.=&Apache::loncommon::start_data_table().
9639: &Apache::loncommon::start_data_table_header_row().
9640: '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
9641: &Apache::loncommon::end_data_table_header_row().
9642: &Apache::loncommon::start_data_table_row()."<td>\n";
9643: # Attempt to restore parameters from last session, set defaults if not present
9644: my %Saveable_Parameters=&clicker_grading_parameters();
9645: &Apache::loncommon::restore_course_settings('grades_clicker',
9646: \%Saveable_Parameters);
9647: if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
9648: if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
9649: if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
9650: if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
9651:
9652: my %checked;
9653: foreach my $gradingmechanism ('attendance','personnel','specific','given') {
9654: if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
9655: $checked{$gradingmechanism}=' checked="checked"';
9656: }
9657: }
9658:
9659: my $upload=&mt("Evaluate File");
9660: my $type=&mt("Type");
9661: my $attendance=&mt("Award points just for participation");
9662: my $personnel=&mt("Correctness determined from response by course personnel");
9663: my $specific=&mt("Correctness determined from response with clicker ID(s)");
9664: my $given=&mt("Correctness determined from given list of answers").' '.
9665: '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
9666: my $pcorrect=&mt("Percentage points for correct solution");
9667: my $pincorrect=&mt("Percentage points for incorrect solution");
9668: my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
9669: {'iclicker' => 'i>clicker',
9670: 'interwrite' => 'interwrite PRS',
9671: 'turning' => 'Turning Technologies'});
9672: $symb = &Apache::lonenc::check_encrypt($symb);
9673: $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
9674: function sanitycheck() {
9675: // Accept only integer percentages
9676: document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
9677: document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
9678: // Find out grading choice
9679: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
9680: if (document.forms.gradesupload.gradingmechanism[i].checked) {
9681: gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
9682: }
9683: }
9684: // By default, new choice equals user selection
9685: newgradingchoice=gradingchoice;
9686: // Not good to give more points for false answers than correct ones
9687: if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
9688: document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
9689: }
9690: // If new choice is attendance only, and old choice was correctness-based, restore defaults
9691: if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
9692: document.forms.gradesupload.pcorrect.value=100;
9693: document.forms.gradesupload.pincorrect.value=100;
9694: }
9695: // If the values are different, cannot be attendance only
9696: if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
9697: (gradingchoice=='attendance')) {
9698: newgradingchoice='personnel';
9699: }
9700: // Change grading choice to new one
9701: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
9702: if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
9703: document.forms.gradesupload.gradingmechanism[i].checked=true;
9704: } else {
9705: document.forms.gradesupload.gradingmechanism[i].checked=false;
9706: }
9707: }
9708: // Remember the old state
9709: document.forms.gradesupload.waschecked.value=newgradingchoice;
9710: }
9711: ENDUPFORM
9712: $result.= <<ENDUPFORM;
9713: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
9714: <input type="hidden" name="symb" value="$symb" />
9715: <input type="hidden" name="command" value="processclickerfile" />
9716: <input type="file" name="upfile" size="50" />
9717: <br /><label>$type: $selectform</label>
9718: ENDUPFORM
9719: $result.='</td>'.&Apache::loncommon::end_data_table_row().
9720: &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
9721: <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
9722: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
9723: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
9724: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
9725: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
9726: <br />
9727: <input type="text" name="givenanswer" size="50" />
9728: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
9729: ENDGRADINGFORM
9730: $result.='</td>'.&Apache::loncommon::end_data_table_row().
9731: &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
9732: <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
9733: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
9734: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
9735: </form>'
9736: ENDPERCFORM
9737: $result.='</td>'.
9738: &Apache::loncommon::end_data_table_row().
9739: &Apache::loncommon::end_data_table();
9740: return $result;
9741: }
9742:
9743: sub process_clicker_file {
9744: my ($r,$symb)=@_;
9745: if (!$symb) {return '';}
9746:
9747: my %Saveable_Parameters=&clicker_grading_parameters();
9748: &Apache::loncommon::store_course_settings('grades_clicker',
9749: \%Saveable_Parameters);
9750: my $result='';
9751: if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
9752: $result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
9753: return $result;
9754: }
9755: if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
9756: $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
9757: return $result;
9758: }
9759: my $foundgiven=0;
9760: if ($env{'form.gradingmechanism'} eq 'given') {
9761: $env{'form.givenanswer'}=~s/^\s*//gs;
9762: $env{'form.givenanswer'}=~s/\s*$//gs;
9763: $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
9764: $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
9765: my @answers=split(/\,/,$env{'form.givenanswer'});
9766: $foundgiven=$#answers+1;
9767: }
9768: my %clicker_ids=&gather_clicker_ids();
9769: my %correct_ids;
9770: if ($env{'form.gradingmechanism'} eq 'personnel') {
9771: %correct_ids=&gather_adv_clicker_ids();
9772: }
9773: if ($env{'form.gradingmechanism'} eq 'specific') {
9774: foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
9775: $correct_id=~tr/a-z/A-Z/;
9776: $correct_id=~s/\s//gs;
9777: $correct_id=~s/^[\#0]+//;
9778: $correct_id=~s/[\-\:]//g;
9779: if ($correct_id) {
9780: $correct_ids{$correct_id}='specified';
9781: }
9782: }
9783: }
9784: if ($env{'form.gradingmechanism'} eq 'attendance') {
9785: $result.=&mt('Score based on attendance only');
9786: } elsif ($env{'form.gradingmechanism'} eq 'given') {
9787: $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
9788: } else {
9789: my $number=0;
9790: $result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
9791: foreach my $id (sort(keys(%correct_ids))) {
9792: $result.='<br /><tt>'.$id.'</tt> - ';
9793: if ($correct_ids{$id} eq 'specified') {
9794: $result.=&mt('specified');
9795: } else {
9796: my ($uname,$udom)=split(/\:/,$correct_ids{$id});
9797: $result.=&Apache::loncommon::plainname($uname,$udom);
9798: }
9799: $number++;
9800: }
9801: $result.="</p>\n";
9802: if ($number==0) {
9803: $result .=
9804: &Apache::lonhtmlcommon::confirm_success(
9805: &mt('No IDs found to determine correct answer'),1);
9806: return $result;
9807: }
9808: }
9809: if (length($env{'form.upfile'}) < 2) {
9810: $result .=
9811: &Apache::lonhtmlcommon::confirm_success(
9812: &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
9813: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
9814: return $result;
9815: }
9816:
9817: # Were able to get all the info needed, now analyze the file
9818:
9819: $result.=&Apache::loncommon::studentbrowser_javascript();
9820: $symb = &Apache::lonenc::check_encrypt($symb);
9821: $result.=&Apache::loncommon::start_data_table().
9822: &Apache::loncommon::start_data_table_header_row().
9823: '<th>'.&mt('Evaluate clicker file').'</th>'.
9824: &Apache::loncommon::end_data_table_header_row().
9825: &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
9826: <td>
9827: <form method="post" action="/adm/grades" name="clickeranalysis">
9828: <input type="hidden" name="symb" value="$symb" />
9829: <input type="hidden" name="command" value="assignclickergrades" />
9830: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
9831: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
9832: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
9833: ENDHEADER
9834: if ($env{'form.gradingmechanism'} eq 'given') {
9835: $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
9836: }
9837: my %responses;
9838: my @questiontitles;
9839: my $errormsg='';
9840: my $number=0;
9841: if ($env{'form.upfiletype'} eq 'iclicker') {
9842: ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
9843: }
9844: if ($env{'form.upfiletype'} eq 'interwrite') {
9845: ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
9846: }
9847: if ($env{'form.upfiletype'} eq 'turning') {
9848: ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
9849: }
9850: $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
9851: '<input type="hidden" name="number" value="'.$number.'" />'.
9852: &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
9853: $env{'form.pcorrect'},$env{'form.pincorrect'}).
9854: '<br />';
9855: if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
9856: $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
9857: return $result;
9858: }
9859: # Remember Question Titles
9860: # FIXME: Possibly need delimiter other than ":"
9861: for (my $i=0;$i<$number;$i++) {
9862: $result.='<input type="hidden" name="question:'.$i.'" value="'.
9863: &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
9864: }
9865: my $correct_count=0;
9866: my $student_count=0;
9867: my $unknown_count=0;
9868: # Match answers with usernames
9869: # FIXME: Possibly need delimiter other than ":"
9870: foreach my $id (keys(%responses)) {
9871: if ($correct_ids{$id}) {
9872: $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
9873: $correct_count++;
9874: } elsif ($clicker_ids{$id}) {
9875: if ($clicker_ids{$id}=~/\,/) {
9876: # More than one user with the same clicker!
9877: $result.="</td>".&Apache::loncommon::end_data_table_row().
9878: &Apache::loncommon::start_data_table_row()."<td>".
9879: &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
9880: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
9881: "<select name='multi".$id."'>";
9882: foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
9883: $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
9884: }
9885: $result.='</select>';
9886: $unknown_count++;
9887: } else {
9888: # Good: found one and only one user with the right clicker
9889: $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
9890: $student_count++;
9891: }
9892: } else {
9893: $result.="</td>".&Apache::loncommon::end_data_table_row().
9894: &Apache::loncommon::start_data_table_row()."<td>".
9895: &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
9896: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
9897: "\n".&mt("Username").": <input type='text' name='uname".$id."' /> ".
9898: "\n".&mt("Domain").": ".
9899: &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).' '.
9900: &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
9901: $unknown_count++;
9902: }
9903: }
9904: $result.='<hr />'.
9905: &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
9906: if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
9907: if ($correct_count==0) {
9908: $errormsg.="Found no correct answers for grading!";
9909: } elsif ($correct_count>1) {
9910: $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
9911: }
9912: }
9913: if ($number<1) {
9914: $errormsg.="Found no questions.";
9915: }
9916: if ($errormsg) {
9917: $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
9918: } else {
9919: $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
9920: }
9921: $result.='</form></td>'.
9922: &Apache::loncommon::end_data_table_row().
9923: &Apache::loncommon::end_data_table();
9924: return $result;
9925: }
9926:
9927: sub iclicker_eval {
9928: my ($questiontitles,$responses)=@_;
9929: my $number=0;
9930: my $errormsg='';
9931: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
9932: my %components=&Apache::loncommon::record_sep($line);
9933: my @entries=map {$components{$_}} (sort(keys(%components)));
9934: if ($entries[0] eq 'Question') {
9935: for (my $i=3;$i<$#entries;$i+=6) {
9936: $$questiontitles[$number]=$entries[$i];
9937: $number++;
9938: }
9939: }
9940: if ($entries[0]=~/^\#/) {
9941: my $id=$entries[0];
9942: my @idresponses;
9943: $id=~s/^[\#0]+//;
9944: for (my $i=0;$i<$number;$i++) {
9945: my $idx=3+$i*6;
9946: $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
9947: push(@idresponses,$entries[$idx]);
9948: }
9949: $$responses{$id}=join(',',@idresponses);
9950: }
9951: }
9952: return ($errormsg,$number);
9953: }
9954:
9955: sub interwrite_eval {
9956: my ($questiontitles,$responses)=@_;
9957: my $number=0;
9958: my $errormsg='';
9959: my $skipline=1;
9960: my $questionnumber=0;
9961: my %idresponses=();
9962: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
9963: my %components=&Apache::loncommon::record_sep($line);
9964: my @entries=map {$components{$_}} (sort(keys(%components)));
9965: if ($entries[1] eq 'Time') { $skipline=0; next; }
9966: if ($entries[1] eq 'Response') { $skipline=1; }
9967: next if $skipline;
9968: if ($entries[0]!=$questionnumber) {
9969: $questionnumber=$entries[0];
9970: $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
9971: $number++;
9972: }
9973: my $id=$entries[4];
9974: $id=~s/^[\#0]+//;
9975: $id=~s/^v\d*\://i;
9976: $id=~s/[\-\:]//g;
9977: $idresponses{$id}[$number]=$entries[6];
9978: }
9979: foreach my $id (keys(%idresponses)) {
9980: $$responses{$id}=join(',',@{$idresponses{$id}});
9981: $$responses{$id}=~s/^\s*\,//;
9982: }
9983: return ($errormsg,$number);
9984: }
9985:
9986: sub turning_eval {
9987: my ($questiontitles,$responses)=@_;
9988: my $number=0;
9989: my $errormsg='';
9990: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
9991: my %components=&Apache::loncommon::record_sep($line);
9992: my @entries=map {$components{$_}} (sort(keys(%components)));
9993: if ($#entries>$number) { $number=$#entries; }
9994: my $id=$entries[0];
9995: my @idresponses;
9996: $id=~s/^[\#0]+//;
9997: unless ($id) { next; }
9998: for (my $idx=1;$idx<=$#entries;$idx++) {
9999: $entries[$idx]=~s/\,/\;/g;
10000: $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
10001: push(@idresponses,$entries[$idx]);
10002: }
10003: $$responses{$id}=join(',',@idresponses);
10004: }
10005: for (my $i=1; $i<=$number; $i++) {
10006: $$questiontitles[$i]=&mt('Question [_1]',$i);
10007: }
10008: return ($errormsg,$number);
10009: }
10010:
10011:
10012: sub assign_clicker_grades {
10013: my ($r,$symb)=@_;
10014: if (!$symb) {return '';}
10015: # See which part we are saving to
10016: my $res_error;
10017: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
10018: if ($res_error) {
10019: return &navmap_errormsg();
10020: }
10021: # FIXME: This should probably look for the first handgradeable part
10022: my $part=$$partlist[0];
10023: # Start screen output
10024: my $result=&Apache::loncommon::start_data_table().
10025: &Apache::loncommon::start_data_table_header_row().
10026: '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
10027: &Apache::loncommon::end_data_table_header_row().
10028: &Apache::loncommon::start_data_table_row().'<td>';
10029: # Get correct result
10030: # FIXME: Possibly need delimiter other than ":"
10031: my @correct=();
10032: my $gradingmechanism=$env{'form.gradingmechanism'};
10033: my $number=$env{'form.number'};
10034: if ($gradingmechanism ne 'attendance') {
10035: foreach my $key (keys(%env)) {
10036: if ($key=~/^form\.correct\:/) {
10037: my @input=split(/\,/,$env{$key});
10038: for (my $i=0;$i<=$#input;$i++) {
10039: if (($correct[$i]) && ($input[$i]) &&
10040: ($correct[$i] ne $input[$i])) {
10041: $result.='<br /><span class="LC_warning">'.
10042: &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
10043: $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
10044: } elsif (($input[$i]) || ($input[$i] eq '0')) {
10045: $correct[$i]=$input[$i];
10046: }
10047: }
10048: }
10049: }
10050: for (my $i=0;$i<$number;$i++) {
10051: if ((!$correct[$i]) && ($correct[$i] ne '0')) {
10052: $result.='<br /><span class="LC_error">'.
10053: &mt('No correct result given for question "[_1]"!',
10054: $env{'form.question:'.$i}).'</span>';
10055: }
10056: }
10057: $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
10058: }
10059: # Start grading
10060: my $pcorrect=$env{'form.pcorrect'};
10061: my $pincorrect=$env{'form.pincorrect'};
10062: my $storecount=0;
10063: my %users=();
10064: foreach my $key (keys(%env)) {
10065: my $user='';
10066: if ($key=~/^form\.student\:(.*)$/) {
10067: $user=$1;
10068: }
10069: if ($key=~/^form\.unknown\:(.*)$/) {
10070: my $id=$1;
10071: if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
10072: $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
10073: } elsif ($env{'form.multi'.$id}) {
10074: $user=$env{'form.multi'.$id};
10075: }
10076: }
10077: if ($user) {
10078: if ($users{$user}) {
10079: $result.='<br /><span class="LC_warning">'.
10080: &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
10081: '</span><br />';
10082: }
10083: $users{$user}=1;
10084: my @answer=split(/\,/,$env{$key});
10085: my $sum=0;
10086: my $realnumber=$number;
10087: for (my $i=0;$i<$number;$i++) {
10088: if ($correct[$i] eq '-') {
10089: $realnumber--;
10090: } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
10091: if ($gradingmechanism eq 'attendance') {
10092: $sum+=$pcorrect;
10093: } elsif ($correct[$i] eq '*') {
10094: $sum+=$pcorrect;
10095: } else {
10096: # We actually grade if correct or not
10097: my $increment=$pincorrect;
10098: # Special case: numerical answer "0"
10099: if ($correct[$i] eq '0') {
10100: if ($answer[$i]=~/^[0\.]+$/) {
10101: $increment=$pcorrect;
10102: }
10103: # General numerical answer, both evaluate to something non-zero
10104: } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
10105: if (1.0*$correct[$i]==1.0*$answer[$i]) {
10106: $increment=$pcorrect;
10107: }
10108: # Must be just alphanumeric
10109: } elsif ($answer[$i] eq $correct[$i]) {
10110: $increment=$pcorrect;
10111: }
10112: $sum+=$increment;
10113: }
10114: }
10115: }
10116: my $ave=$sum/(100*$realnumber);
10117: # Store
10118: my ($username,$domain)=split(/\:/,$user);
10119: my %grades=();
10120: $grades{"resource.$part.solved"}='correct_by_override';
10121: $grades{"resource.$part.awarded"}=$ave;
10122: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
10123: my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
10124: $env{'request.course.id'},
10125: $domain,$username);
10126: if ($returncode ne 'ok') {
10127: $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
10128: } else {
10129: $storecount++;
10130: }
10131: }
10132: }
10133: # We are done
10134: $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
10135: '</td>'.
10136: &Apache::loncommon::end_data_table_row().
10137: &Apache::loncommon::end_data_table();
10138: return $result;
10139: }
10140:
10141: sub navmap_errormsg {
10142: return '<div class="LC_error">'.
10143: &mt('An error occurred retrieving information about resources in the course.').'<br />'.
10144: &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>').
10145: '</div>';
10146: }
10147:
10148: sub startpage {
10149: my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
10150: if ($nomenu) {
10151: $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
10152: } else {
10153: unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
10154: $r->print(&Apache::loncommon::start_page('Grading',$js,
10155: {'bread_crumbs' => $crumbs}));
10156: &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
10157: }
10158: unless ($nodisplayflag) {
10159: $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
10160: }
10161: }
10162:
10163: sub select_problem {
10164: my ($r)=@_;
10165: $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
10166: $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
10167: $r->print('<input type="hidden" name="command" value="gradingmenu" />');
10168: $r->print('<input type="submit" value="'.&mt('Next').' →" /></form>');
10169: }
10170:
10171: sub handler {
10172: my $request=$_[0];
10173: &reset_caches();
10174: if ($request->header_only) {
10175: &Apache::loncommon::content_type($request,'text/html');
10176: $request->send_http_header;
10177: return OK;
10178: }
10179: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
10180:
10181: # see what command we need to execute
10182:
10183: my @commands=&Apache::loncommon::get_env_multiple('form.command');
10184: my $command=$commands[0];
10185:
10186: &init_perm();
10187: if (!$env{'request.course.id'}) {
10188: unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
10189: ($command =~ /^scantronupload/)) {
10190: # Not in a course.
10191: $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
10192: return HTTP_NOT_ACCEPTABLE;
10193: }
10194: } elsif (!%perm) {
10195: $request->internal_redirect('/adm/quickgrades');
10196: return OK;
10197: }
10198: &Apache::loncommon::content_type($request,'text/html');
10199: $request->send_http_header;
10200:
10201: if ($#commands > 0) {
10202: &Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
10203: }
10204:
10205: # see what the symb is
10206:
10207: my $symb=$env{'form.symb'};
10208: unless ($symb) {
10209: (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
10210: $symb=&Apache::lonnet::symbread($url);
10211: }
10212: &Apache::lonenc::check_decrypt(\$symb);
10213:
10214: $ssi_error = 0;
10215: if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
10216: #
10217: # Not called from a resource, but inside a course
10218: #
10219: &startpage($request,undef,[],1,1);
10220: &select_problem($request);
10221: } else {
10222: if ($command eq 'submission' && $perm{'vgr'}) {
10223: my ($stuvcurrent,$stuvdisp,$versionform,$js);
10224: if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
10225: ($stuvcurrent,$stuvdisp,$versionform,$js) =
10226: &choose_task_version_form($symb,$env{'form.student'},
10227: $env{'form.userdom'});
10228: }
10229: &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
10230: if ($versionform) {
10231: $request->print($versionform);
10232: }
10233: $request->print('<br clear="all" />');
10234: ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
10235: } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
10236: my ($stuvcurrent,$stuvdisp,$versionform,$js) =
10237: &choose_task_version_form($symb,$env{'form.student'},
10238: $env{'form.userdom'},
10239: $env{'form.inhibitmenu'});
10240: &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
10241: if ($versionform) {
10242: $request->print($versionform);
10243: }
10244: $request->print('<br clear="all" />');
10245: $request->print(&show_previous_task_version($request,$symb));
10246: } elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
10247: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10248: {href=>'',text=>'Select student'}],1,1);
10249: &pickStudentPage($request,$symb);
10250: } elsif ($command eq 'displayPage' && $perm{'vgr'}) {
10251: &startpage($request,$symb,
10252: [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10253: {href=>'',text=>'Select student'},
10254: {href=>'',text=>'Grade student'}],1,1);
10255: &displayPage($request,$symb);
10256: } elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
10257: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10258: {href=>'',text=>'Select student'},
10259: {href=>'',text=>'Grade student'},
10260: {href=>'',text=>'Store grades'}],1,1);
10261: &updateGradeByPage($request,$symb);
10262: } elsif ($command eq 'processGroup' && $perm{'vgr'}) {
10263: &startpage($request,$symb,[{href=>'',text=>'...'},
10264: {href=>'',text=>'Modify grades'}]);
10265: &processGroup($request,$symb);
10266: } elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
10267: &startpage($request,$symb);
10268: $request->print(&grading_menu($request,$symb));
10269: } elsif ($command eq 'individual' && $perm{'vgr'}) {
10270: &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
10271: $request->print(&submit_options($request,$symb));
10272: } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
10273: &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
10274: $request->print(&listStudents($request,$symb,'graded'));
10275: } elsif ($command eq 'table' && $perm{'vgr'}) {
10276: &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
10277: $request->print(&submit_options_table($request,$symb));
10278: } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
10279: &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
10280: $request->print(&submit_options_sequence($request,$symb));
10281: } elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
10282: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
10283: $request->print(&viewgrades($request,$symb));
10284: } elsif ($command eq 'handgrade' && $perm{'mgr'}) {
10285: &startpage($request,$symb,[{href=>'',text=>'...'},
10286: {href=>'',text=>'Store grades'}]);
10287: $request->print(&processHandGrade($request,$symb));
10288: } elsif ($command eq 'editgrades' && $perm{'mgr'}) {
10289: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
10290: {href=>&href_symb_cmd($symb,'viewgrades').'&group=all§ion=all&Status=Active',
10291: text=>"Modify grades"},
10292: {href=>'', text=>"Store grades"}]);
10293: $request->print(&editgrades($request,$symb));
10294: } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
10295: &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
10296: $request->print(&initialverifyreceipt($request,$symb));
10297: } elsif ($command eq 'verify' && $perm{'vgr'}) {
10298: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
10299: {href=>'',text=>'Verification Result'}]);
10300: $request->print(&verifyreceipt($request,$symb));
10301: } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
10302: &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
10303: $request->print(&process_clicker($request,$symb));
10304: } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
10305: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
10306: {href=>'', text=>'Process clicker file'}]);
10307: $request->print(&process_clicker_file($request,$symb));
10308: } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
10309: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
10310: {href=>'', text=>'Process clicker file'},
10311: {href=>'', text=>'Store grades'}]);
10312: $request->print(&assign_clicker_grades($request,$symb));
10313: } elsif ($command eq 'csvform' && $perm{'mgr'}) {
10314: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10315: $request->print(&upcsvScores_form($request,$symb));
10316: } elsif ($command eq 'csvupload' && $perm{'mgr'}) {
10317: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10318: $request->print(&csvupload($request,$symb));
10319: } elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
10320: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10321: $request->print(&csvuploadmap($request,$symb));
10322: } elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
10323: if ($env{'form.associate'} ne 'Reverse Association') {
10324: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10325: $request->print(&csvuploadoptions($request,$symb));
10326: } else {
10327: if ( $env{'form.upfile_associate'} ne 'reverse' ) {
10328: $env{'form.upfile_associate'} = 'reverse';
10329: } else {
10330: $env{'form.upfile_associate'} = 'forward';
10331: }
10332: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10333: $request->print(&csvuploadmap($request,$symb));
10334: }
10335: } elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
10336: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10337: $request->print(&csvuploadassign($request,$symb));
10338: } elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
10339: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10340: $request->print(&scantron_selectphase($request,undef,$symb));
10341: } elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
10342: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10343: $request->print(&scantron_do_warning($request,$symb));
10344: } elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
10345: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10346: $request->print(&scantron_validate_file($request,$symb));
10347: } elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
10348: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10349: $request->print(&scantron_process_students($request,$symb));
10350: } elsif ($command eq 'scantronupload' &&
10351: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10352: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10353: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10354: $request->print(&scantron_upload_scantron_data($request,$symb));
10355: } elsif ($command eq 'scantronupload_save' &&
10356: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10357: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10358: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10359: $request->print(&scantron_upload_scantron_data_save($request,$symb));
10360: } elsif ($command eq 'scantron_download' &&
10361: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
10362: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10363: $request->print(&scantron_download_scantron_data($request,$symb));
10364: } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
10365: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10366: $request->print(&checkscantron_results($request,$symb));
10367: } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
10368: &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
10369: $request->print(&submit_options_download($request,$symb));
10370: } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
10371: &startpage($request,$symb,
10372: [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
10373: {href=>'', text=>'Download submissions'}]);
10374: &submit_download_link($request,$symb);
10375: } elsif ($command) {
10376: &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
10377: $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
10378: }
10379: }
10380: if ($ssi_error) {
10381: &ssi_print_error($request);
10382: }
10383: if ($env{'form.inhibitmenu'}) {
10384: $request->print(&Apache::loncommon::end_page());
10385: } else {
10386: &Apache::lonquickgrades::endGradeScreen($request);
10387: }
10388: &reset_caches();
10389: return OK;
10390: }
10391:
10392: 1;
10393:
10394: __END__;
10395:
10396:
10397: =head1 NAME
10398:
10399: Apache::grades
10400:
10401: =head1 SYNOPSIS
10402:
10403: Handles the viewing of grades.
10404:
10405: This is part of the LearningOnline Network with CAPA project
10406: described at http://www.lon-capa.org.
10407:
10408: =head1 OVERVIEW
10409:
10410: Do an ssi with retries:
10411: While I'd love to factor out this with the version in lonprintout,
10412: 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
10413: I'm not quite ready to invent (e.g. an ssi_with_retry object).
10414:
10415: At least the logic that drives this has been pulled out into loncommon.
10416:
10417:
10418:
10419: ssi_with_retries - Does the server side include of a resource.
10420: if the ssi call returns an error we'll retry it up to
10421: the number of times requested by the caller.
10422: If we still have a problem, no text is appended to the
10423: output and we set some global variables.
10424: to indicate to the caller an SSI error occurred.
10425: All of this is supposed to deal with the issues described
10426: in LON-CAPA BZ 5631 see:
10427: http://bugs.lon-capa.org/show_bug.cgi?id=5631
10428: by informing the user that this happened.
10429:
10430: Parameters:
10431: resource - The resource to include. This is passed directly, without
10432: interpretation to lonnet::ssi.
10433: form - The form hash parameters that guide the interpretation of the resource
10434:
10435: retries - Number of retries allowed before giving up completely.
10436: Returns:
10437: On success, returns the rendered resource identified by the resource parameter.
10438: Side Effects:
10439: The following global variables can be set:
10440: ssi_error - If an unrecoverable error occurred this becomes true.
10441: It is up to the caller to initialize this to false
10442: if desired.
10443: ssi_error_resource - If an unrecoverable error occurred, this is the value
10444: of the resource that could not be rendered by the ssi
10445: call.
10446: ssi_error_message - The error string fetched from the ssi response
10447: in the event of an error.
10448:
10449:
10450: =head1 HANDLER SUBROUTINE
10451:
10452: ssi_with_retries()
10453:
10454: =head1 SUBROUTINES
10455:
10456: =over
10457:
10458: =head1 Routines to display previous version of a Task for a specific student
10459:
10460: Tasks are graded pass/fail. Students who have yet to pass a particular Task
10461: can receive another opportunity. Access to tasks is slot-based. If a slot
10462: requires a proctor to check-in the student, a new version of the Task will
10463: be created when the student is checked in to the new opportunity.
10464:
10465: If a particular student has tried two or more versions of a particular task,
10466: the submission screen provides a user with vgr privileges (e.g., a Course
10467: Coordinator) the ability to display a previous version worked on by the
10468: student. By default, the current version is displayed. If a previous version
10469: has been selected for display, submission data are only shown that pertain
10470: to that particular version, and the interface to submit grades is not shown.
10471:
10472: =over 4
10473:
10474: =item show_previous_task_version()
10475:
10476: Displays a specified version of a student's Task, as the student sees it.
10477:
10478: Inputs: 2
10479: request - request object
10480: symb - unique symb for current instance of resource
10481:
10482: Output: None.
10483:
10484: Side Effects: calls &show_problem() to print version of Task, with
10485: version contained in form item: $env{'form.previousversion'}
10486:
10487: =item choose_task_version_form()
10488:
10489: Displays a web form used to select which version of a student's view of a
10490: Task should be displayed. Either launches a pop-up window, or replaces
10491: content in existing pop-up, or replaces page in main window.
10492:
10493: Inputs: 4
10494: symb - unique symb for current instance of resource
10495: uname - username of student
10496: udom - domain of student
10497: nomenu - 1 if display is in a pop-up window, and hence no menu
10498: breadcrumbs etc., are displayed
10499:
10500: Output: 4
10501: current - student's current version
10502: displayed - student's version being displayed
10503: result - scalar containing HTML for web form used to switch to
10504: a different version (or a link to close window, if pop-up).
10505: js - javascript for processing selection in versions web form
10506:
10507: Side Effects: None.
10508:
10509: =item previous_display_javascript()
10510:
10511: Inputs: 2
10512: nomenu - 1 if display is in a pop-up window, and hence no menu
10513: breadcrumbs etc., are displayed.
10514: current - student's current version number.
10515:
10516: Output: 1
10517: js - javascript for processing selection in versions web form.
10518:
10519: Side Effects: None.
10520:
10521: =back
10522:
10523: =head1 Routines to process bubblesheet data.
10524:
10525: =over 4
10526:
10527: =item scantron_get_correction() :
10528:
10529: Builds the interface screen to interact with the operator to fix a
10530: specific error condition in a specific scanline
10531:
10532: Arguments:
10533: $r - Apache request object
10534: $i - number of the current scanline
10535: $scan_record - hash ref as returned from &scantron_parse_scanline()
10536: $scan_config - hash ref as returned from &get_scantron_config()
10537: $line - full contents of the current scanline
10538: $error - error condition, valid values are
10539: 'incorrectCODE', 'duplicateCODE',
10540: 'doublebubble', 'missingbubble',
10541: 'duplicateID', 'incorrectID'
10542: $arg - extra information needed
10543: For errors:
10544: - duplicateID - paper number that this studentID was seen before on
10545: - duplicateCODE - array ref of the paper numbers this CODE was
10546: seen on before
10547: - incorrectCODE - current incorrect CODE
10548: - doublebubble - array ref of the bubble lines that have double
10549: bubble errors
10550: - missingbubble - array ref of the bubble lines that have missing
10551: bubble errors
10552:
10553: $randomorder - True if exam folder has randomorder set
10554: $randompick - True if exam folder has randompick set
10555: $respnumlookup - Reference to HASH mapping question numbers in bubble lines
10556: for current line to question number used for same question
10557: in "Master Seqence" (as seen by Course Coordinator).
10558: $startline - Reference to hash where key is question number (0 is first)
10559: and value is number of first bubble line for current student
10560: or code-based randompick and/or randomorder.
10561:
10562:
10563:
10564: =item scantron_get_maxbubble() :
10565:
10566: Arguments:
10567: $nav_error - Reference to scalar which is a flag to indicate a
10568: failure to retrieve a navmap object.
10569: if $nav_error is set to 1 by scantron_get_maxbubble(), the
10570: calling routine should trap the error condition and display the warning
10571: found in &navmap_errormsg().
10572:
10573: $scantron_config - Reference to bubblesheet format configuration hash.
10574:
10575: Returns the maximum number of bubble lines that are expected to
10576: occur. Does this by walking the selected sequence rendering the
10577: resource and then checking &Apache::lonxml::get_problem_counter()
10578: for what the current value of the problem counter is.
10579:
10580: Caches the results to $env{'form.scantron_maxbubble'},
10581: $env{'form.scantron.bubble_lines.n'},
10582: $env{'form.scantron.first_bubble_line.n'} and
10583: $env{"form.scantron.sub_bubblelines.n"}
10584: which are the total number of bubble lines, the number of bubble
10585: lines for response n and number of the first bubble line for response n,
10586: and a comma separated list of numbers of bubble lines for sub-questions
10587: (for optionresponse, matchresponse, and rankresponse items), for response n.
10588:
10589:
10590: =item scantron_validate_missingbubbles() :
10591:
10592: Validates all scanlines in the selected file to not have any
10593: answers that don't have bubbles that have not been verified
10594: to be bubble free.
10595:
10596: =item scantron_process_students() :
10597:
10598: Routine that does the actual grading of the bubblesheet information.
10599:
10600: The parsed scanline hash is added to %env
10601:
10602: Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
10603: foreach resource , with the form data of
10604:
10605: 'submitted' =>'scantron'
10606: 'grade_target' =>'grade',
10607: 'grade_username'=> username of student
10608: 'grade_domain' => domain of student
10609: 'grade_courseid'=> of course
10610: 'grade_symb' => symb of resource to grade
10611:
10612: This triggers a grading pass. The problem grading code takes care
10613: of converting the bubbled letter information (now in %env) into a
10614: valid submission.
10615:
10616: =item scantron_upload_scantron_data() :
10617:
10618: Creates the screen for adding a new bubblesheet data file to a course.
10619:
10620: =item scantron_upload_scantron_data_save() :
10621:
10622: Adds a provided bubble information data file to the course if user
10623: has the correct privileges to do so.
10624:
10625: =item valid_file() :
10626:
10627: Validates that the requested bubble data file exists in the course.
10628:
10629: =item scantron_download_scantron_data() :
10630:
10631: Shows a list of the three internal files (original, corrected,
10632: skipped) for a specific bubblesheet data file that exists in the
10633: course.
10634:
10635: =item scantron_validate_ID() :
10636:
10637: Validates all scanlines in the selected file to not have any
10638: invalid or underspecified student/employee IDs
10639:
10640: =item navmap_errormsg() :
10641:
10642: Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
10643: Should be called whenever the request to instantiate a navmap object fails.
10644:
10645: =back
10646:
10647: =back
10648:
10649: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>