File:
[LON-CAPA] /
loncom /
homework /
grades.pm
Revision
1.688:
download - view:
text,
annotated -
select for diffs
Thu May 30 05:04:31 2013 UTC (11 years, 2 months ago) by
raeburn
Branches:
MAIN
CVS tags:
HEAD
- When users with pav and vgr priv (e.g., Course Coordinators) print a
folder of resources for anonymous CODE(s) or for named student(s), e.g.,
for a bubblesheet exam, parameter in map for hiddenresource will be
ignored when retrieving resources for folder in random order.
- Supports use case where CC sets hidden for exam folder while printing
bubblesheet exam, and also while grading exam.
1: # The LearningOnline Network with CAPA
2: # The LON-CAPA Grading handler
3: #
4: # $Id: grades.pm,v 1.688 2013/05/30 05:04:31 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 %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
334: my ($toprow,$bottomrow);
335: foreach my $foil (@$order) {
336: if ($grading{$foil} == 1) {
337: $toprow.='<td><b>'.$answer{$foil}.' </b></td>';
338: } else {
339: $toprow.='<td><i>'.$answer{$foil}.' </i></td>';
340: }
341: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
342: }
343: return '<blockquote><table border="1">'.
344: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
345: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
346: $bottomrow.'</tr></table></blockquote>';
347: } elsif ($response eq 'match') {
348: my %answer=&Apache::lonnet::str2hash($answer);
349: my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
350: my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
351: my ($toprow,$middlerow,$bottomrow);
352: foreach my $foil (@$order) {
353: my $item=shift(@items);
354: if ($grading{$foil} == 1) {
355: $toprow.='<td><b>'.$item.' </b></td>';
356: $middlerow.='<td><b>'.$grayFont.$answer{$foil}.' </span></b></td>';
357: } else {
358: $toprow.='<td><i>'.$item.' </i></td>';
359: $middlerow.='<td><i>'.$grayFont.$answer{$foil}.' </span></i></td>';
360: }
361: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
362: }
363: return '<blockquote><table border="1">'.
364: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
365: '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
366: $middlerow.'</tr>'.
367: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
368: $bottomrow.'</tr></table></blockquote>';
369: } elsif ($response eq 'radiobutton') {
370: my %answer=&Apache::lonnet::str2hash($answer);
371: my ($toprow,$bottomrow);
372: my $correct =
373: &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
374: foreach my $foil (@$order) {
375: if (exists($answer{$foil})) {
376: if ($foil eq $correct) {
377: $toprow.='<td><b>'.&mt('true').'</b></td>';
378: } else {
379: $toprow.='<td><i>'.&mt('true').'</i></td>';
380: }
381: } else {
382: $toprow.='<td>'.&mt('false').'</td>';
383: }
384: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
385: }
386: return '<blockquote><table border="1">'.
387: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
388: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
389: $bottomrow.'</tr></table></blockquote>';
390: } elsif ($response eq 'essay') {
391: if (! exists ($env{'form.'.$symb})) {
392: my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
393: $env{'course.'.$env{'request.course.id'}.'.domain'},
394: $env{'course.'.$env{'request.course.id'}.'.num'});
395:
396: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
397: $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
398: $env{'form.kwclr'} = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
399: $env{'form.kwsize'} = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
400: $env{'form.kwstyle'} = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
401: $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
402: }
403: $answer =~ s-\n-<br />-g;
404: return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
405: } elsif ( $response eq 'organic') {
406: my $result='Smile representation: "<tt>'.$answer.'</tt>"';
407: my $jme=$record->{$version."resource.$partid.$respid.molecule"};
408: $result.=&Apache::chemresponse::jme_img($jme,$answer,400);
409: return $result;
410: } elsif ( $response eq 'Task') {
411: if ( $answer eq 'SUBMITTED') {
412: my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
413: my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
414: return $result;
415: } elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
416: my @matches = grep(/^\Q$version\E.*?\.instance$/,
417: keys(%{$record}));
418: return join('<br />',($version,@matches));
419:
420:
421: } else {
422: my $result =
423: '<p>'
424: .&mt('Overall result: [_1]',
425: $record->{$version."resource.$respid.$partid.status"})
426: .'</p>';
427:
428: $result .= '<ul>';
429: my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
430: keys(%{$record}));
431: foreach my $grade (sort(@grade)) {
432: my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
433: $result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
434: $dim, $record->{$grade}).
435: '</li>';
436: }
437: $result.='</ul>';
438: return $result;
439: }
440: } elsif ( $response =~ m/(?:numerical|formula)/) {
441: $answer =
442: &Apache::loncommon::format_previous_attempt_value('submission',
443: $answer);
444: }
445: return $answer;
446: }
447:
448: #-- A couple of common js functions
449: sub commonJSfunctions {
450: my $request = shift;
451: $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
452: function radioSelection(radioButton) {
453: var selection=null;
454: if (radioButton.length > 1) {
455: for (var i=0; i<radioButton.length; i++) {
456: if (radioButton[i].checked) {
457: return radioButton[i].value;
458: }
459: }
460: } else {
461: if (radioButton.checked) return radioButton.value;
462: }
463: return selection;
464: }
465:
466: function pullDownSelection(selectOne) {
467: var selection="";
468: if (selectOne.length > 1) {
469: for (var i=0; i<selectOne.length; i++) {
470: if (selectOne[i].selected) {
471: return selectOne[i].value;
472: }
473: }
474: } else {
475: // only one value it must be the selected one
476: return selectOne.value;
477: }
478: }
479: COMMONJSFUNCTIONS
480: }
481:
482: #--- Dumps the class list with usernames,list of sections,
483: #--- section, ids and fullnames for each user.
484: sub getclasslist {
485: my ($getsec,$filterlist,$getgroup) = @_;
486: my @getsec;
487: my @getgroup;
488: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
489: if (!ref($getsec)) {
490: if ($getsec ne '' && $getsec ne 'all') {
491: @getsec=($getsec);
492: }
493: } else {
494: @getsec=@{$getsec};
495: }
496: if (grep(/^all$/,@getsec)) { undef(@getsec); }
497: if (!ref($getgroup)) {
498: if ($getgroup ne '' && $getgroup ne 'all') {
499: @getgroup=($getgroup);
500: }
501: } else {
502: @getgroup=@{$getgroup};
503: }
504: if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
505:
506: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
507: # Bail out if we were unable to get the classlist
508: return if (! defined($classlist));
509: &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
510: #
511: my %sections;
512: my %fullnames;
513: foreach my $student (keys(%$classlist)) {
514: my $end =
515: $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
516: my $start =
517: $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
518: my $id =
519: $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
520: my $section =
521: $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
522: my $fullname =
523: $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
524: my $status =
525: $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
526: my $group =
527: $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
528: # filter students according to status selected
529: if ($filterlist && (!($stu_status =~ /Any/))) {
530: if (!($stu_status =~ $status)) {
531: delete($classlist->{$student});
532: next;
533: }
534: }
535: # filter students according to groups selected
536: my @stu_groups = split(/,/,$group);
537: if (@getgroup) {
538: my $exclude = 1;
539: foreach my $grp (@getgroup) {
540: foreach my $stu_group (@stu_groups) {
541: if ($stu_group eq $grp) {
542: $exclude = 0;
543: }
544: }
545: if (($grp eq 'none') && !$group) {
546: $exclude = 0;
547: }
548: }
549: if ($exclude) {
550: delete($classlist->{$student});
551: }
552: }
553: $section = ($section ne '' ? $section : 'none');
554: if (&canview($section)) {
555: if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
556: $sections{$section}++;
557: if ($classlist->{$student}) {
558: $fullnames{$student}=$fullname;
559: }
560: } else {
561: delete($classlist->{$student});
562: }
563: } else {
564: delete($classlist->{$student});
565: }
566: }
567: my %seen = ();
568: my @sections = sort(keys(%sections));
569: return ($classlist,\@sections,\%fullnames);
570: }
571:
572: sub canmodify {
573: my ($sec)=@_;
574: if ($perm{'mgr'}) {
575: if (!defined($perm{'mgr_section'})) {
576: # can modify whole class
577: return 1;
578: } else {
579: if ($sec eq $perm{'mgr_section'}) {
580: #can modify the requested section
581: return 1;
582: } else {
583: # can't modify the request section
584: return 0;
585: }
586: }
587: }
588: #can't modify
589: return 0;
590: }
591:
592: sub canview {
593: my ($sec)=@_;
594: if ($perm{'vgr'}) {
595: if (!defined($perm{'vgr_section'})) {
596: # can modify whole class
597: return 1;
598: } else {
599: if ($sec eq $perm{'vgr_section'}) {
600: #can modify the requested section
601: return 1;
602: } else {
603: # can't modify the request section
604: return 0;
605: }
606: }
607: }
608: #can't modify
609: return 0;
610: }
611:
612: #--- Retrieve the grade status of a student for all the parts
613: sub student_gradeStatus {
614: my ($symb,$udom,$uname,$partlist) = @_;
615: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
616: my %partstatus = ();
617: foreach (@$partlist) {
618: my ($status,undef) = split(/_/,$record{"resource.$_.solved"},2);
619: $status = 'nothing' if ($status eq '');
620: $partstatus{$_} = $status;
621: my $subkey = "resource.$_.submitted_by";
622: $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
623: }
624: return %partstatus;
625: }
626:
627: # hidden form and javascript that calls the form
628: # Use by verifyscript and viewgrades
629: # Shows a student's view of problem and submission
630: sub jscriptNform {
631: my ($symb) = @_;
632: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
633: my $jscript= &Apache::lonhtmlcommon::scripttag(
634: ' function viewOneStudent(user,domain) {'."\n".
635: ' document.onestudent.student.value = user;'."\n".
636: ' document.onestudent.userdom.value = domain;'."\n".
637: ' document.onestudent.submit();'."\n".
638: ' }'."\n".
639: "\n");
640: $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
641: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
642: '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
643: '<input type="hidden" name="command" value="submission" />'."\n".
644: '<input type="hidden" name="student" value="" />'."\n".
645: '<input type="hidden" name="userdom" value="" />'."\n".
646: '</form>'."\n";
647: return $jscript;
648: }
649:
650:
651:
652: # Given the score (as a number [0-1] and the weight) what is the final
653: # point value? This function will round to the nearest tenth, third,
654: # or quarter if one of those is within the tolerance of .00001.
655: sub compute_points {
656: my ($score, $weight) = @_;
657:
658: my $tolerance = .00001;
659: my $points = $score * $weight;
660:
661: # Check for nearness to 1/x.
662: my $check_for_nearness = sub {
663: my ($factor) = @_;
664: my $num = ($points * $factor) + $tolerance;
665: my $floored_num = floor($num);
666: if ($num - $floored_num < 2 * $tolerance * $factor) {
667: return $floored_num / $factor;
668: }
669: return $points;
670: };
671:
672: $points = $check_for_nearness->(10);
673: $points = $check_for_nearness->(3);
674: $points = $check_for_nearness->(4);
675:
676: return $points;
677: }
678:
679: #------------------ End of general use routines --------------------
680:
681: #
682: # Find most similar essay
683: #
684:
685: sub most_similar {
686: my ($uname,$udom,$symb,$uessay)=@_;
687:
688: unless ($symb) { return ''; }
689:
690: unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
691:
692: # ignore spaces and punctuation
693:
694: $uessay=~s/\W+/ /gs;
695:
696: # ignore empty submissions (occuring when only files are sent)
697:
698: unless ($uessay=~/\w+/s) { return ''; }
699:
700: # these will be returned. Do not care if not at least 50 percent similar
701: my $limit=0.6;
702: my $sname='';
703: my $sdom='';
704: my $scrsid='';
705: my $sessay='';
706: # go through all essays ...
707: foreach my $tkey (keys(%{$old_essays{$symb}})) {
708: my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
709: # ... except the same student
710: next if (($tname eq $uname) && ($tdom eq $udom));
711: my $tessay=$old_essays{$symb}{$tkey};
712: $tessay=~s/\W+/ /gs;
713: # String similarity gives up if not even limit
714: my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
715: # Found one
716: if ($tsimilar>$limit) {
717: $limit=$tsimilar;
718: $sname=$tname;
719: $sdom=$tdom;
720: $scrsid=$tcrsid;
721: $sessay=$old_essays{$symb}{$tkey};
722: }
723: }
724: if ($limit>0.6) {
725: return ($sname,$sdom,$scrsid,$sessay,$limit);
726: } else {
727: return ('','','','',0);
728: }
729: }
730:
731: #-------------------------------------------------------------------
732:
733: #------------------------------------ Receipt Verification Routines
734: #
735:
736: sub initialverifyreceipt {
737: my ($request,$symb) = @_;
738: &commonJSfunctions($request);
739: return '<form name="gradingMenu"><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
740: &Apache::lonnet::recprefix($env{'request.course.id'}).
741: '-<input type="text" name="receipt" size="4" />'.
742: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
743: '<input type="hidden" name="command" value="verify" />'.
744: "</form>\n";
745: }
746:
747: #--- Check whether a receipt number is valid.---
748: sub verifyreceipt {
749: my ($request,$symb) = @_;
750:
751: my $courseid = $env{'request.course.id'};
752: my $receipt = &Apache::lonnet::recprefix($courseid).'-'.
753: $env{'form.receipt'};
754: $receipt =~ s/[^\-\d]//g;
755:
756: my $title.=
757: '<h3><span class="LC_info">'.
758: &mt('Verifying Receipt Number [_1]',$receipt).
759: '</span></h3>'."\n";
760:
761: my ($string,$contents,$matches) = ('','',0);
762: my (undef,undef,$fullname) = &getclasslist('all','0');
763:
764: my $receiptparts=0;
765: if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
766: $env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
767: my $parts=['0'];
768: if ($receiptparts) {
769: my $res_error;
770: ($parts)=&response_type($symb,\$res_error);
771: if ($res_error) {
772: return &navmap_errormsg();
773: }
774: }
775:
776: my $header =
777: &Apache::loncommon::start_data_table().
778: &Apache::loncommon::start_data_table_header_row().
779: '<th> '.&mt('Fullname').' </th>'."\n".
780: '<th> '.&mt('Username').' </th>'."\n".
781: '<th> '.&mt('Domain').' </th>';
782: if ($receiptparts) {
783: $header.='<th> '.&mt('Problem Part').' </th>';
784: }
785: $header.=
786: &Apache::loncommon::end_data_table_header_row();
787:
788: foreach (sort
789: {
790: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
791: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
792: }
793: return $a cmp $b;
794: } (keys(%$fullname))) {
795: my ($uname,$udom)=split(/\:/);
796: foreach my $part (@$parts) {
797: if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
798: $contents.=
799: &Apache::loncommon::start_data_table_row().
800: '<td> '."\n".
801: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
802: '\');" target="_self">'.$$fullname{$_}.'</a> </td>'."\n".
803: '<td> '.$uname.' </td>'.
804: '<td> '.$udom.' </td>';
805: if ($receiptparts) {
806: $contents.='<td> '.$part.' </td>';
807: }
808: $contents.=
809: &Apache::loncommon::end_data_table_row()."\n";
810:
811: $matches++;
812: }
813: }
814: }
815: if ($matches == 0) {
816: $string = $title
817: .'<p class="LC_warning">'
818: .&mt('No match found for the above receipt number.')
819: .'</p>';
820: } else {
821: $string = &jscriptNform($symb).$title.
822: '<p>'.
823: &mt('The above receipt number matches the following [quant,_1,student].',$matches).
824: '</p>'.
825: $header.
826: $contents.
827: &Apache::loncommon::end_data_table()."\n";
828: }
829: return $string;
830: }
831:
832: #--- This is called by a number of programs.
833: #--- Called from the Grading Menu - View/Grade an individual student
834: #--- Also called directly when one clicks on the subm button
835: # on the problem page.
836: sub listStudents {
837: my ($request,$symb,$submitonly) = @_;
838:
839: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
840: my $cnum = $env{"course.$env{'request.course.id'}.num"};
841: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
842: my $getgroup = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
843: unless ($submitonly) {
844: $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
845: }
846:
847: my $result='';
848: my $res_error;
849: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
850:
851: my %lt = &Apache::lonlocal::texthash (
852: 'multiple' => 'Please select a student or group of students before clicking on the Next button.',
853: 'single' => 'Please select the student before clicking on the Next button.',
854: );
855: $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
856: function checkSelect(checkBox) {
857: var ctr=0;
858: var sense="";
859: if (checkBox.length > 1) {
860: for (var i=0; i<checkBox.length; i++) {
861: if (checkBox[i].checked) {
862: ctr++;
863: }
864: }
865: sense = '$lt{'multiple'}';
866: } else {
867: if (checkBox.checked) {
868: ctr = 1;
869: }
870: sense = '$lt{'single'}';
871: }
872: if (ctr == 0) {
873: alert(sense);
874: return false;
875: }
876: document.gradesub.submit();
877: }
878:
879: function reLoadList(formname) {
880: if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
881: formname.command.value = 'submission';
882: formname.submit();
883: }
884: LISTJAVASCRIPT
885:
886: &commonJSfunctions($request);
887: $request->print($result);
888:
889: my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
890: "\n";
891:
892: $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
893: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
894: .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
895: .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
896: .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
897: .&Apache::lonhtmlcommon::row_closure();
898: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
899: .'<label><input type="radio" name="vAns" value="no" /> '.&mt('no').' </label>'."\n"
900: .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
901: .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
902: .&Apache::lonhtmlcommon::row_closure();
903:
904: my $submission_options;
905: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
906: my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
907: $env{'form.Status'} = $saveStatus;
908: $submission_options.=
909: '<span class="LC_nobreak">'.
910: '<label><input type="radio" name="lastSub" value="lastonly" /> '.
911: &mt('last submission only').' </label></span>'."\n".
912: '<span class="LC_nobreak">'.
913: '<label><input type="radio" name="lastSub" value="last" /> '.
914: &mt('last submission & parts info').' </label></span>'."\n".
915: '<span class="LC_nobreak">'.
916: '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
917: &mt('by dates and submissions').'</label></span>'."\n".
918: '<span class="LC_nobreak">'.
919: '<label><input type="radio" name="lastSub" value="all" /> '.
920: &mt('all details').'</label></span>';
921: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
922: .$submission_options
923: .&Apache::lonhtmlcommon::row_closure();
924:
925: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
926: .'<select name="increment">'
927: .'<option value="1">'.&mt('Whole Points').'</option>'
928: .'<option value=".5">'.&mt('Half Points').'</option>'
929: .'<option value=".25">'.&mt('Quarter Points').'</option>'
930: .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
931: .'</select>'
932: .&Apache::lonhtmlcommon::row_closure();
933:
934: $gradeTable .=
935: &build_section_inputs().
936: '<input type="hidden" name="submitonly" value="'.$submitonly.'" />'."\n".
937: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
938: '<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
939:
940: if (exists($env{'form.Status'})) {
941: $gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
942: } else {
943: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
944: .&Apache::lonhtmlcommon::StatusOptions(
945: $saveStatus,undef,1,'javascript:reLoadList(this.form);')
946: .&Apache::lonhtmlcommon::row_closure();
947: }
948:
949: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
950: .'<input type="checkbox" name="checkPlag" checked="checked" />'
951: .&Apache::lonhtmlcommon::row_closure(1)
952: .&Apache::lonhtmlcommon::end_pick_box();
953:
954: $gradeTable .= '<p>'
955: .&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"
956: .'<input type="hidden" name="command" value="processGroup" />'
957: .'</p>';
958:
959: # checkall buttons
960: $gradeTable.=&check_script('gradesub', 'stuinfo');
961: $gradeTable.='<input type="button" '."\n".
962: 'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
963: 'value="'.&mt('Next').' →" /> <br />'."\n";
964: $gradeTable.=&check_buttons();
965: my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
966: $gradeTable.= &Apache::loncommon::start_data_table().
967: &Apache::loncommon::start_data_table_header_row();
968: my $loop = 0;
969: while ($loop < 2) {
970: $gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
971: '<th>'.&nameUserString('header').' '.&mt('Section/Group').'</th>';
972: if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
973: foreach my $part (sort(@$partlist)) {
974: my $display_part=
975: &get_display_part((split(/_/,$part))[0],$symb);
976: $gradeTable.=
977: '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
978: }
979: } elsif ($submitonly eq 'queued') {
980: $gradeTable.='<th>'.&mt('Queue Status').' </th>';
981: }
982: $loop++;
983: # $gradeTable.='<td></td>' if ($loop%2 ==1);
984: }
985: $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
986:
987: my $ctr = 0;
988: foreach my $student (sort
989: {
990: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
991: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
992: }
993: return $a cmp $b;
994: }
995: (keys(%$fullname))) {
996: my ($uname,$udom) = split(/:/,$student);
997:
998: my %status = ();
999:
1000: if ($submitonly eq 'queued') {
1001: my %queue_status =
1002: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
1003: $udom,$uname);
1004: next if (!defined($queue_status{'gradingqueue'}));
1005: $status{'gradingqueue'} = $queue_status{'gradingqueue'};
1006: }
1007:
1008: if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1009: (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1010: my $submitted = 0;
1011: my $graded = 0;
1012: my $incorrect = 0;
1013: foreach (keys(%status)) {
1014: $submitted = 1 if ($status{$_} ne 'nothing');
1015: $graded = 1 if ($status{$_} =~ /^ungraded/);
1016: $incorrect = 1 if ($status{$_} =~ /^incorrect/);
1017:
1018: my ($foo,$partid,$foo1) = split(/\./,$_);
1019: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1020: $submitted = 0;
1021: my ($part)=split(/\./,$partid);
1022: $gradeTable.='<input type="hidden" name="'.
1023: $student.':'.$part.':submitted_by" value="'.
1024: $status{'resource.'.$partid.'.submitted_by'}.'" />';
1025: }
1026: }
1027:
1028: next if (!$submitted && ($submitonly eq 'yes' ||
1029: $submitonly eq 'incorrect' ||
1030: $submitonly eq 'graded'));
1031: next if (!$graded && ($submitonly eq 'graded'));
1032: next if (!$incorrect && $submitonly eq 'incorrect');
1033: }
1034:
1035: $ctr++;
1036: my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1037: my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1038: if ( $perm{'vgr'} eq 'F' ) {
1039: if ($ctr%2 ==1) {
1040: $gradeTable.= &Apache::loncommon::start_data_table_row();
1041: }
1042: $gradeTable.='<td align="right">'.$ctr.' </td>'.
1043: '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1044: $student.':'.$$fullname{$student}.':::SECTION'.$section.
1045: ') " /> </label></td>'."\n".'<td>'.
1046: &nameUserString(undef,$$fullname{$student},$uname,$udom).
1047: ' '.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1048:
1049: if ($submitonly ne 'all') {
1050: foreach (sort(keys(%status))) {
1051: next if ($_ =~ /^resource.*?submitted_by$/);
1052: $gradeTable.='<td align="center"> '.&mt($status{$_}).' </td>'."\n";
1053: }
1054: }
1055: # $gradeTable.='<td></td>' if ($ctr%2 ==1);
1056: if ($ctr%2 ==0) {
1057: $gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
1058: }
1059: }
1060: }
1061: if ($ctr%2 ==1) {
1062: $gradeTable.='<td> </td><td> </td><td> </td>';
1063: if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1064: foreach (@$partlist) {
1065: $gradeTable.='<td> </td>';
1066: }
1067: } elsif ($submitonly eq 'queued') {
1068: $gradeTable.='<td> </td>';
1069: }
1070: $gradeTable.=&Apache::loncommon::end_data_table_row();
1071: }
1072:
1073: $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1074: '<input type="button" '.
1075: 'onclick="javascript:checkSelect(this.form.stuinfo);" '.
1076: 'value="'.&mt('Next').' →" /></form>'."\n";
1077: if ($ctr == 0) {
1078: my $num_students=(scalar(keys(%$fullname)));
1079: if ($num_students eq 0) {
1080: $gradeTable='<br /> <span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1081: } else {
1082: my $submissions='submissions';
1083: if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
1084: if ($submitonly eq 'graded' ) { $submissions = 'ungraded submissions'; }
1085: if ($submitonly eq 'queued' ) { $submissions = 'queued submissions'; }
1086: $gradeTable='<br /> <span class="LC_warning">'.
1087: &mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
1088: $num_students).
1089: '</span><br />';
1090: }
1091: } elsif ($ctr == 1) {
1092: $gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1093: }
1094: $request->print($gradeTable);
1095: return '';
1096: }
1097:
1098: #---- Called from the listStudents routine
1099:
1100: sub check_script {
1101: my ($form, $type)=@_;
1102: my $chkallscript= &Apache::lonhtmlcommon::scripttag('
1103: function checkall() {
1104: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1105: ele = document.forms.'.$form.'.elements[i];
1106: if (ele.name == "'.$type.'") {
1107: document.forms.'.$form.'.elements[i].checked=true;
1108: }
1109: }
1110: }
1111:
1112: function checksec() {
1113: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1114: ele = document.forms.'.$form.'.elements[i];
1115: string = document.forms.'.$form.'.chksec.value;
1116: if
1117: (ele.value.indexOf(":::SECTION"+string)>0) {
1118: document.forms.'.$form.'.elements[i].checked=true;
1119: }
1120: }
1121: }
1122:
1123:
1124: function uncheckall() {
1125: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1126: ele = document.forms.'.$form.'.elements[i];
1127: if (ele.name == "'.$type.'") {
1128: document.forms.'.$form.'.elements[i].checked=false;
1129: }
1130: }
1131: }
1132:
1133: '."\n");
1134: return $chkallscript;
1135: }
1136:
1137: sub check_buttons {
1138: my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
1139: $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" /> ';
1140: $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1141: $buttons.='<input type="text" size="5" name="chksec" /> ';
1142: return $buttons;
1143: }
1144:
1145: # Displays the submissions for one student or a group of students
1146: sub processGroup {
1147: my ($request,$symb) = @_;
1148: my $ctr = 0;
1149: my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1150: my $total = scalar(@stuchecked)-1;
1151:
1152: foreach my $student (@stuchecked) {
1153: my ($uname,$udom,$fullname) = split(/:/,$student);
1154: $env{'form.student'} = $uname;
1155: $env{'form.userdom'} = $udom;
1156: $env{'form.fullname'} = $fullname;
1157: &submission($request,$ctr,$total,$symb);
1158: $ctr++;
1159: }
1160: return '';
1161: }
1162:
1163: #------------------------------------------------------------------------------------
1164: #
1165: #-------------------------- Next few routines handles grading by student, essentially
1166: # handles essay response type problem/part
1167: #
1168: #--- Javascript to handle the submission page functionality ---
1169: sub sub_page_js {
1170: my $request = shift;
1171: my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1172: $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1173: function updateRadio(formname,id,weight) {
1174: var gradeBox = formname["GD_BOX"+id];
1175: var radioButton = formname["RADVAL"+id];
1176: var oldpts = formname["oldpts"+id].value;
1177: var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1178: gradeBox.value = pts;
1179: var resetbox = false;
1180: if (isNaN(pts) || pts < 0) {
1181: alert("$alertmsg"+pts);
1182: for (var i=0; i<radioButton.length; i++) {
1183: if (radioButton[i].checked) {
1184: gradeBox.value = i;
1185: resetbox = true;
1186: }
1187: }
1188: if (!resetbox) {
1189: formtextbox.value = "";
1190: }
1191: return;
1192: }
1193:
1194: if (pts > weight) {
1195: var resp = confirm("You entered a value ("+pts+
1196: ") greater than the weight for the part. Accept?");
1197: if (resp == false) {
1198: gradeBox.value = oldpts;
1199: return;
1200: }
1201: }
1202:
1203: for (var i=0; i<radioButton.length; i++) {
1204: radioButton[i].checked=false;
1205: if (pts == i && pts != "") {
1206: radioButton[i].checked=true;
1207: }
1208: }
1209: updateSelect(formname,id);
1210: formname["stores"+id].value = "0";
1211: }
1212:
1213: function writeBox(formname,id,pts) {
1214: var gradeBox = formname["GD_BOX"+id];
1215: if (checkSolved(formname,id) == 'update') {
1216: gradeBox.value = pts;
1217: } else {
1218: var oldpts = formname["oldpts"+id].value;
1219: gradeBox.value = oldpts;
1220: var radioButton = formname["RADVAL"+id];
1221: for (var i=0; i<radioButton.length; i++) {
1222: radioButton[i].checked=false;
1223: if (i == oldpts) {
1224: radioButton[i].checked=true;
1225: }
1226: }
1227: }
1228: formname["stores"+id].value = "0";
1229: updateSelect(formname,id);
1230: return;
1231: }
1232:
1233: function clearRadBox(formname,id) {
1234: if (checkSolved(formname,id) == 'noupdate') {
1235: updateSelect(formname,id);
1236: return;
1237: }
1238: gradeSelect = formname["GD_SEL"+id];
1239: for (var i=0; i<gradeSelect.length; i++) {
1240: if (gradeSelect[i].selected) {
1241: var selectx=i;
1242: }
1243: }
1244: var stores = formname["stores"+id];
1245: if (selectx == stores.value) { return };
1246: var gradeBox = formname["GD_BOX"+id];
1247: gradeBox.value = "";
1248: var radioButton = formname["RADVAL"+id];
1249: for (var i=0; i<radioButton.length; i++) {
1250: radioButton[i].checked=false;
1251: }
1252: stores.value = selectx;
1253: }
1254:
1255: function checkSolved(formname,id) {
1256: if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1257: var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
1258: if (!reply) {return "noupdate";}
1259: formname.overRideScore.value = 'yes';
1260: }
1261: return "update";
1262: }
1263:
1264: function updateSelect(formname,id) {
1265: formname["GD_SEL"+id][0].selected = true;
1266: return;
1267: }
1268:
1269: //=========== Check that a point is assigned for all the parts ============
1270: function checksubmit(formname,val,total,parttot) {
1271: formname.gradeOpt.value = val;
1272: if (val == "Save & Next") {
1273: for (i=0;i<=total;i++) {
1274: for (j=0;j<parttot;j++) {
1275: var partid = formname["partid"+i+"_"+j].value;
1276: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1277: var points = formname["GD_BOX"+i+"_"+partid].value;
1278: if (points == "") {
1279: var name = formname["name"+i].value;
1280: var studentID = (name != '' ? name : formname["unamedom"+i].value);
1281: var resp = confirm("You did not assign a score for "+studentID+
1282: ", part "+partid+". Continue?");
1283: if (resp == false) {
1284: formname["GD_BOX"+i+"_"+partid].focus();
1285: return false;
1286: }
1287: }
1288: }
1289:
1290: }
1291: }
1292:
1293: }
1294: formname.submit();
1295: }
1296:
1297: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
1298: function checkSubmitPage(formname,total) {
1299: noscore = new Array(100);
1300: var ptr = 0;
1301: for (i=1;i<total;i++) {
1302: var partid = formname["q_"+i].value;
1303: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1304: var points = formname["GD_BOX"+i+"_"+partid].value;
1305: var status = formname["solved"+i+"_"+partid].value;
1306: if (points == "" && status != "correct_by_student") {
1307: noscore[ptr] = i;
1308: ptr++;
1309: }
1310: }
1311: }
1312: if (ptr != 0) {
1313: var sense = ptr == 1 ? ": " : "s: ";
1314: var prolist = "";
1315: if (ptr == 1) {
1316: prolist = noscore[0];
1317: } else {
1318: var i = 0;
1319: while (i < ptr-1) {
1320: prolist += noscore[i]+", ";
1321: i++;
1322: }
1323: prolist += "and "+noscore[i];
1324: }
1325: var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
1326: if (resp == false) {
1327: return false;
1328: }
1329: }
1330:
1331: formname.submit();
1332: }
1333: SUBJAVASCRIPT
1334: }
1335:
1336: #--- javascript for essay type problem --
1337: sub sub_page_kw_js {
1338: my $request = shift;
1339: my $iconpath = $request->dir_config('lonIconsURL');
1340: &commonJSfunctions($request);
1341:
1342: my $inner_js_msg_central= (<<INNERJS);
1343: <script type="text/javascript">
1344: function checkInput() {
1345: opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
1346: var nmsg = opener.document.SCORE.savemsgN.value;
1347: var usrctr = document.msgcenter.usrctr.value;
1348: var newval = opener.document.SCORE["newmsg"+usrctr];
1349: newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
1350:
1351: var msgchk = "";
1352: if (document.msgcenter.subchk.checked) {
1353: msgchk = "msgsub,";
1354: }
1355: var includemsg = 0;
1356: for (var i=1; i<=nmsg; i++) {
1357: var opnmsg = opener.document.SCORE["savemsg"+i];
1358: var frmmsg = document.msgcenter["msg"+i];
1359: opnmsg.value = opener.checkEntities(frmmsg.value);
1360: var showflg = opener.document.SCORE["shownOnce"+i];
1361: showflg.value = "1";
1362: var chkbox = document.msgcenter["msgn"+i];
1363: if (chkbox.checked) {
1364: msgchk += "savemsg"+i+",";
1365: includemsg = 1;
1366: }
1367: }
1368: if (document.msgcenter.newmsgchk.checked) {
1369: msgchk += "newmsg"+usrctr;
1370: includemsg = 1;
1371: }
1372: imgformname = opener.document.SCORE["mailicon"+usrctr];
1373: imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
1374: var includemsg = opener.document.SCORE["includemsg"+usrctr];
1375: includemsg.value = msgchk;
1376:
1377: self.close()
1378:
1379: }
1380: </script>
1381: INNERJS
1382:
1383: my $inner_js_highlight_central= (<<INNERJS);
1384: <script type="text/javascript">
1385: function updateChoice(flag) {
1386: opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
1387: opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
1388: opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
1389: opener.document.SCORE.refresh.value = "on";
1390: if (opener.document.SCORE.keywords.value!=""){
1391: opener.document.SCORE.submit();
1392: }
1393: self.close()
1394: }
1395: </script>
1396: INNERJS
1397:
1398: my $start_page_msg_central =
1399: &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
1400: {'js_ready' => 1,
1401: 'only_body' => 1,
1402: 'bgcolor' =>'#FFFFFF',});
1403: my $end_page_msg_central =
1404: &Apache::loncommon::end_page({'js_ready' => 1});
1405:
1406:
1407: my $start_page_highlight_central =
1408: &Apache::loncommon::start_page('Highlight Central',
1409: $inner_js_highlight_central,
1410: {'js_ready' => 1,
1411: 'only_body' => 1,
1412: 'bgcolor' =>'#FFFFFF',});
1413: my $end_page_highlight_central =
1414: &Apache::loncommon::end_page({'js_ready' => 1});
1415:
1416: my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1417: $docopen=~s/^document\.//;
1418: my %lt = &Apache::lonlocal::texthash(
1419: keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
1420: plse => 'Please select a word or group of words from document and then click this link.',
1421: adds => 'Add selection to keyword list? Edit if desired.',
1422: comp => 'Compose Message for: ',
1423: incl => 'Include',
1424: type => 'Type',
1425: subj => 'Subject',
1426: mesa => 'Message',
1427: new => 'New',
1428: save => 'Save',
1429: canc => 'Cancel',
1430: kehi => 'Keyword Highlight Options',
1431: txtc => 'Text Color',
1432: font => 'Font Size',
1433: fnst => 'Font Style',
1434: );
1435: $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1436:
1437: //===================== Show list of keywords ====================
1438: function keywords(formname) {
1439: var nret = prompt("$lt{'keyw'}",formname.keywords.value);
1440: if (nret==null) return;
1441: formname.keywords.value = nret;
1442:
1443: if (formname.keywords.value != "") {
1444: formname.refresh.value = "on";
1445: formname.submit();
1446: }
1447: return;
1448: }
1449:
1450: //===================== Script to view submitted by ==================
1451: function viewSubmitter(submitter) {
1452: document.SCORE.refresh.value = "on";
1453: document.SCORE.NCT.value = "1";
1454: document.SCORE.unamedom0.value = submitter;
1455: document.SCORE.submit();
1456: return;
1457: }
1458:
1459: //===================== Script to add keyword(s) ==================
1460: function getSel() {
1461: if (document.getSelection) txt = document.getSelection();
1462: else if (document.selection) txt = document.selection.createRange().text;
1463: else return;
1464: var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
1465: if (cleantxt=="") {
1466: alert("$lt{'plse'}");
1467: return;
1468: }
1469: var nret = prompt("$lt{'adds'}",cleantxt);
1470: if (nret==null) return;
1471: document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1472: if (document.SCORE.keywords.value != "") {
1473: document.SCORE.refresh.value = "on";
1474: document.SCORE.submit();
1475: }
1476: return;
1477: }
1478:
1479: //====================== Script for composing message ==============
1480: // preload images
1481: img1 = new Image();
1482: img1.src = "$iconpath/mailbkgrd.gif";
1483: img2 = new Image();
1484: img2.src = "$iconpath/mailto.gif";
1485:
1486: function msgCenter(msgform,usrctr,fullname) {
1487: var Nmsg = msgform.savemsgN.value;
1488: savedMsgHeader(Nmsg,usrctr,fullname);
1489: var subject = msgform.msgsub.value;
1490: var msgchk = document.SCORE["includemsg"+usrctr].value;
1491: re = /msgsub/;
1492: var shwsel = "";
1493: if (re.test(msgchk)) { shwsel = "checked" }
1494: subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
1495: displaySubject(checkEntities(subject),shwsel);
1496: for (var i=1; i<=Nmsg; i++) {
1497: var testmsg = "savemsg"+i+",";
1498: re = new RegExp(testmsg,"g");
1499: shwsel = "";
1500: if (re.test(msgchk)) { shwsel = "checked" }
1501: var message = document.SCORE["savemsg"+i].value;
1502: message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1503: displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
1504: //any < is already converted to <, etc. However, only once!!
1505: }
1506: newmsg = document.SCORE["newmsg"+usrctr].value;
1507: shwsel = "";
1508: re = /newmsg/;
1509: if (re.test(msgchk)) { shwsel = "checked" }
1510: newMsg(newmsg,shwsel);
1511: msgTail();
1512: return;
1513: }
1514:
1515: function checkEntities(strx) {
1516: if (strx.length == 0) return strx;
1517: var orgStr = ["&", "<", ">", '"'];
1518: var newStr = ["&", "<", ">", """];
1519: var counter = 0;
1520: while (counter < 4) {
1521: strx = strReplace(strx,orgStr[counter],newStr[counter]);
1522: counter++;
1523: }
1524: return strx;
1525: }
1526:
1527: function strReplace(strx, orgStr, newStr) {
1528: return strx.split(orgStr).join(newStr);
1529: }
1530:
1531: function savedMsgHeader(Nmsg,usrctr,fullname) {
1532: var height = 70*Nmsg+250;
1533: if (height > 600) {
1534: height = 600;
1535: }
1536: var xpos = (screen.width-600)/2;
1537: xpos = (xpos < 0) ? '0' : xpos;
1538: var ypos = (screen.height-height)/2-30;
1539: ypos = (ypos < 0) ? '0' : ypos;
1540:
1541: pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1542: pWin.focus();
1543: pDoc = pWin.document;
1544: pDoc.$docopen;
1545: pDoc.write('$start_page_msg_central');
1546:
1547: pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
1548: pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1549: pDoc.write("<h1> $lt{'comp'}\"+fullname+\"<\\/h1>");
1550:
1551: pDoc.write('<table style="border:1px solid black;"><tr>');
1552: pDoc.write("<td><b>$lt{'incl'}<\\/b><\\/td><td><b>$lt{'type'}<\\/b><\\/td><td><b>$lt{'mesa'}<\\/td><\\/tr>");
1553: }
1554: function displaySubject(msg,shwsel) {
1555: pDoc = pWin.document;
1556: pDoc.write("<tr>");
1557: pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1558: pDoc.write("<td>$lt{'subj'}<\\/td>");
1559: pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1560: }
1561:
1562: function displaySavedMsg(ctr,msg,shwsel) {
1563: pDoc = pWin.document;
1564: pDoc.write("<tr>");
1565: pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1566: pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
1567: pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1568: }
1569:
1570: function newMsg(newmsg,shwsel) {
1571: pDoc = pWin.document;
1572: pDoc.write("<tr>");
1573: pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1574: pDoc.write("<td align=\\"center\\">$lt{'new'}<\\/td>");
1575: pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1576: }
1577:
1578: function msgTail() {
1579: pDoc = pWin.document;
1580: //pDoc.write("<\\/table>");
1581: pDoc.write("<\\/td><\\/tr><\\/table> ");
1582: pDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:checkInput()\\"> ");
1583: pDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1584: pDoc.write("<\\/form>");
1585: pDoc.write('$end_page_msg_central');
1586: pDoc.close();
1587: }
1588:
1589: //====================== Script for keyword highlight options ==============
1590: function kwhighlight() {
1591: var kwclr = document.SCORE.kwclr.value;
1592: var kwsize = document.SCORE.kwsize.value;
1593: var kwstyle = document.SCORE.kwstyle.value;
1594: var redsel = "";
1595: var grnsel = "";
1596: var blusel = "";
1597: if (kwclr=="red") {var redsel="checked"};
1598: if (kwclr=="green") {var grnsel="checked"};
1599: if (kwclr=="blue") {var blusel="checked"};
1600: var sznsel = "";
1601: var sz1sel = "";
1602: var sz2sel = "";
1603: if (kwsize=="0") {var sznsel="checked"};
1604: if (kwsize=="+1") {var sz1sel="checked"};
1605: if (kwsize=="+2") {var sz2sel="checked"};
1606: var synsel = "";
1607: var syisel = "";
1608: var sybsel = "";
1609: if (kwstyle=="") {var synsel="checked"};
1610: if (kwstyle=="<i>") {var syisel="checked"};
1611: if (kwstyle=="<b>") {var sybsel="checked"};
1612: highlightCentral();
1613: highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
1614: highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
1615: highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
1616: highlightend();
1617: return;
1618: }
1619:
1620: function highlightCentral() {
1621: // if (window.hwdWin) window.hwdWin.close();
1622: var xpos = (screen.width-400)/2;
1623: xpos = (xpos < 0) ? '0' : xpos;
1624: var ypos = (screen.height-330)/2-30;
1625: ypos = (ypos < 0) ? '0' : ypos;
1626:
1627: hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1628: hwdWin.focus();
1629: var hDoc = hwdWin.document;
1630: hDoc.$docopen;
1631: hDoc.write('$start_page_highlight_central');
1632: hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1633: hDoc.write("<h3><span class=\\"LC_info\\"> $lt{'kehi'}<\\/span><\\/h3><br /><br />");
1634:
1635: hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
1636: hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1637: hDoc.write("<td><b>$lt{'txtc'}<\\/b><\\/td><td><b>$lt{'font'}<\\/b><\\/td><td><b>$lt{'fnst'}<\\/td><\\/tr>");
1638: }
1639:
1640: function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) {
1641: var hDoc = hwdWin.document;
1642: hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1643: hDoc.write("<td align=\\"left\\">");
1644: hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+"> "+clrtxt+"<\\/td>");
1645: hDoc.write("<td align=\\"left\\">");
1646: hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+"> "+sztxt+"<\\/td>");
1647: hDoc.write("<td align=\\"left\\">");
1648: hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+"> "+sytxt+"<\\/td>");
1649: hDoc.write("<\\/tr>");
1650: }
1651:
1652: function highlightend() {
1653: var hDoc = hwdWin.document;
1654: hDoc.write("<\\/table>");
1655: hDoc.write("<\\/td><\\/tr><\\/table> ");
1656: hDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\"> ");
1657: hDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1658: hDoc.write("<\\/form>");
1659: hDoc.write('$end_page_highlight_central');
1660: hDoc.close();
1661: }
1662:
1663: SUBJAVASCRIPT
1664: }
1665:
1666: sub get_increment {
1667: my $increment = $env{'form.increment'};
1668: if ($increment != 1 && $increment != .5 && $increment != .25 &&
1669: $increment != .1) {
1670: $increment = 1;
1671: }
1672: return $increment;
1673: }
1674:
1675: sub gradeBox_start {
1676: return (
1677: &Apache::loncommon::start_data_table()
1678: .&Apache::loncommon::start_data_table_header_row()
1679: .'<th>'.&mt('Part').'</th>'
1680: .'<th>'.&mt('Points').'</th>'
1681: .'<th> </th>'
1682: .'<th>'.&mt('Assign Grade').'</th>'
1683: .'<th>'.&mt('Weight').'</th>'
1684: .'<th>'.&mt('Grade Status').'</th>'
1685: .&Apache::loncommon::end_data_table_header_row()
1686: );
1687: }
1688:
1689: sub gradeBox_end {
1690: return (
1691: &Apache::loncommon::end_data_table()
1692: );
1693: }
1694: #--- displays the grading box, used in essay type problem and grading by page/sequence
1695: sub gradeBox {
1696: my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1697: my $checkIcon = '<img alt="'.&mt('Check Mark').
1698: '" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1699: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1700: my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)')
1701: : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1702: $wgt = ($wgt > 0 ? $wgt : '1');
1703: my $score = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1704: '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1705: my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1706: my $display_part= &get_display_part($partid,$symb);
1707: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
1708: [$partid]);
1709: my $aggtries = $$record{'resource.'.$partid.'.tries'};
1710: if ($last_resets{$partid}) {
1711: $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
1712: }
1713: $result.=&Apache::loncommon::start_data_table_row();
1714: my $ctr = 0;
1715: my $thisweight = 0;
1716: my $increment = &get_increment();
1717:
1718: my $radio.='<table border="0"><tr>'."\n"; # display radio buttons in a nice table 10 across
1719: while ($thisweight<=$wgt) {
1720: $radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1721: 'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1722: $thisweight.')" value="'.$thisweight.'" '.
1723: ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1724: $radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1725: $thisweight += $increment;
1726: $ctr++;
1727: }
1728: $radio.='</tr></table>';
1729:
1730: my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1731: ($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1732: 'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1733: $wgt.')" /></td>'."\n";
1734: $line.='<td>/'.$wgt.' '.$wgtmsg.
1735: ($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? ' '.$checkIcon : '').
1736: ' </td>'."\n";
1737: $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1738: 'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1739: if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1740: $line.='<option></option>'.
1741: '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1742: } else {
1743: $line.='<option selected="selected"></option>'.
1744: '<option value="excused" >'.&mt('excused').'</option>';
1745: }
1746: $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
1747:
1748:
1749: $result .=
1750: '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
1751: $result.=&Apache::loncommon::end_data_table_row();
1752: $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
1753: '<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
1754: '<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1755: $$record{'resource.'.$partid.'.solved'}.'" />'."\n".
1756: '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
1757: $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
1758: '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
1759: $aggtries.'" />'."\n";
1760: my $res_error;
1761: $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1762: if ($res_error) {
1763: return &navmap_errormsg();
1764: }
1765: return $result;
1766: }
1767:
1768: sub handback_box {
1769: my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
1770: my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
1771: my (@respids);
1772: my @part_response_id = &flatten_responseType($responseType);
1773: foreach my $part_response_id (@part_response_id) {
1774: my ($part,$resp) = @{ $part_response_id };
1775: if ($part eq $partid) {
1776: push(@respids,$resp);
1777: }
1778: }
1779: my $result;
1780: foreach my $respid (@respids) {
1781: my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
1782: my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
1783: next if (!@$files);
1784: my $file_counter = 0;
1785: foreach my $file (@$files) {
1786: if ($file =~ /\/portfolio\//) {
1787: $file_counter++;
1788: my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1789: my ($name,$version,$ext) = &file_name_version_ext($file_disp);
1790: $file_disp = "$name.$ext";
1791: $file = $file_path.$file_disp;
1792: $result.=&mt('Return commented version of [_1] to student.',
1793: '<span class="LC_filename">'.$file_disp.'</span>');
1794: $result.='<input type="file" name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1795: $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1796: }
1797: }
1798: if ($file_counter) {
1799: $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
1800: '<span class="LC_info">'.
1801: '('.&mt('File(s) will be uploaded when you click on Save & Next below.',$file_counter).')</span><br /><br />';
1802: }
1803: }
1804: return $result;
1805: }
1806:
1807: sub show_problem {
1808: my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1809: my $rendered;
1810: my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1811: &Apache::lonxml::remember_problem_counter();
1812: if ($mode eq 'both' or $mode eq 'text') {
1813: $rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1814: $env{'request.course.id'},
1815: undef,\%form);
1816: }
1817: if ($removeform) {
1818: $rendered=~s|<form(.*?)>||g;
1819: $rendered=~s|</form>||g;
1820: $rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1821: }
1822: my $companswer;
1823: if ($mode eq 'both' or $mode eq 'answer') {
1824: &Apache::lonxml::restore_problem_counter();
1825: $companswer=
1826: &Apache::loncommon::get_student_answers($symb,$uname,$udom,
1827: $env{'request.course.id'},
1828: %form);
1829: }
1830: if ($removeform) {
1831: $companswer=~s|<form(.*?)>||g;
1832: $companswer=~s|</form>||g;
1833: $companswer=~s|name="submit"|name="would_have_been_submit"|g;
1834: }
1835: my $renderheading = &mt('View of the problem');
1836: my $answerheading = &mt('Correct answer');
1837: if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1838: my $stu_fullname = $env{'form.fullname'};
1839: if ($stu_fullname eq '') {
1840: $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
1841: }
1842: my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
1843: if ($forwhom ne '') {
1844: $renderheading = &mt('View of the problem for[_1]',$forwhom);
1845: $answerheading = &mt('Correct answer for[_1]',$forwhom);
1846: }
1847: }
1848: $rendered=
1849: '<div class="LC_Box">'
1850: .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1851: .$rendered
1852: .'</div>';
1853: $companswer=
1854: '<div class="LC_Box">'
1855: .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1856: .$companswer
1857: .'</div>';
1858: my $result;
1859: if ($mode eq 'both') {
1860: $result=$rendered.$companswer;
1861: } elsif ($mode eq 'text') {
1862: $result=$rendered;
1863: } elsif ($mode eq 'answer') {
1864: $result=$companswer;
1865: }
1866: return $result;
1867: }
1868:
1869: sub files_exist {
1870: my ($r, $symb) = @_;
1871: my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1872:
1873: foreach my $student (@students) {
1874: my ($uname,$udom,$fullname) = split(/:/,$student);
1875: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
1876: $udom,$uname);
1877: my ($string,$timestamp)= &get_last_submission(\%record);
1878: foreach my $submission (@$string) {
1879: my ($partid,$respid) =
1880: ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1881: my $files=&get_submitted_files($udom,$uname,$partid,$respid,
1882: \%record);
1883: return 1 if (@$files);
1884: }
1885: }
1886: return 0;
1887: }
1888:
1889: sub download_all_link {
1890: my ($r,$symb) = @_;
1891: unless (&files_exist($r, $symb)) {
1892: $r->print(&mt('There are currently no submitted documents.'));
1893: return;
1894: }
1895:
1896: my $all_students =
1897: join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
1898:
1899: my $parts =
1900: join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
1901:
1902: my $identifier = &Apache::loncommon::get_cgi_id();
1903: &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
1904: 'cgi.'.$identifier.'.symb' => $symb,
1905: 'cgi.'.$identifier.'.parts' => $parts,});
1906: $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
1907: &mt('Download All Submitted Documents').'</a>');
1908: return;
1909: }
1910:
1911: sub submit_download_link {
1912: my ($request,$symb) = @_;
1913: if (!$symb) { return ''; }
1914: #FIXME: Figure out which type of problem this is and provide appropriate download
1915: &download_all_link($request,$symb);
1916: }
1917:
1918: sub build_section_inputs {
1919: my $section_inputs;
1920: if ($env{'form.section'} eq '') {
1921: $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
1922: } else {
1923: my @sections = &Apache::loncommon::get_env_multiple('form.section');
1924: foreach my $section (@sections) {
1925: $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
1926: }
1927: }
1928: return $section_inputs;
1929: }
1930:
1931: # --------------------------- show submissions of a student, option to grade
1932: sub submission {
1933: my ($request,$counter,$total,$symb) = @_;
1934: my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
1935: $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
1936: my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
1937: $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1938:
1939: my $probtitle=&Apache::lonnet::gettitle($symb);
1940: if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1941:
1942: if (!&canview($usec)) {
1943: $request->print('<span class="LC_warning">Unable to view requested student.('.
1944: $uname.':'.$udom.' in section '.$usec.' in course id '.
1945: $env{'request.course.id'}.')</span>');
1946: return;
1947: }
1948:
1949: if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
1950: if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
1951: if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
1952: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1953: my $checkIcon = '<img alt="'.&mt('Check Mark').
1954: '" src="'.$request->dir_config('lonIconsURL').
1955: '/check.gif" height="16" border="0" />';
1956:
1957: # header info
1958: if ($counter == 0) {
1959: &sub_page_js($request);
1960: &sub_page_kw_js($request);
1961:
1962: # option to display problem, only once else it cause problems
1963: # with the form later since the problem has a form.
1964: if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1965: my $mode;
1966: if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1967: $mode='both';
1968: } elsif ($env{'form.vProb'} eq 'yes') {
1969: $mode='text';
1970: } elsif ($env{'form.vAns'} eq 'yes') {
1971: $mode='answer';
1972: }
1973: &Apache::lonxml::clear_problem_counter();
1974: $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1975: }
1976:
1977: # kwclr is the only variable that is guaranteed to be non blank
1978: # if this subroutine has been called once.
1979: my %keyhash = ();
1980: # if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1981: if (1) {
1982: %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1983: $env{'course.'.$env{'request.course.id'}.'.domain'},
1984: $env{'course.'.$env{'request.course.id'}.'.num'});
1985:
1986: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1987: $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
1988: $env{'form.kwclr'} = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
1989: $env{'form.kwsize'} = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
1990: $env{'form.kwstyle'} = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
1991: $env{'form.msgsub'} = $keyhash{$symb.'_subject'} ne '' ?
1992: $keyhash{$symb.'_subject'} : $probtitle;
1993: $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1994: }
1995: my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1996: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1997: $request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1998: '<input type="hidden" name="command" value="handgrade" />'."\n".
1999: '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
2000: '<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
2001: '<input type="hidden" name="refresh" value="off" />'."\n".
2002: '<input type="hidden" name="studentNo" value="" />'."\n".
2003: '<input type="hidden" name="gradeOpt" value="" />'."\n".
2004: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
2005: '<input type="hidden" name="vProb" value="'.$env{'form.vProb'}.'" />'."\n".
2006: '<input type="hidden" name="vAns" value="'.$env{'form.vAns'}.'" />'."\n".
2007: '<input type="hidden" name="lastSub" value="'.$env{'form.lastSub'}.'" />'."\n".
2008: &build_section_inputs().
2009: '<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
2010: '<input type="hidden" name="NCT"'.
2011: ' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
2012: # if ($env{'form.handgrade'} eq 'yes') {
2013: if (1) {
2014: $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
2015: '<input type="hidden" name="kwclr" value="'.$env{'form.kwclr'}.'" />'."\n".
2016: '<input type="hidden" name="kwsize" value="'.$env{'form.kwsize'}.'" />'."\n".
2017: '<input type="hidden" name="kwstyle" value="'.$env{'form.kwstyle'}.'" />'."\n".
2018: '<input type="hidden" name="msgsub" value="'.$env{'form.msgsub'}.'" />'."\n".
2019: '<input type="hidden" name="shownSub" value="0" />'."\n".
2020: '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
2021: foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
2022: $request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
2023: }
2024: }
2025:
2026: my ($cts,$prnmsg) = (1,'');
2027: while ($cts <= $env{'form.savemsgN'}) {
2028: $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
2029: (!exists($keyhash{$symb.'_savemsg'.$cts}) ?
2030: &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
2031: &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
2032: '" />'."\n".
2033: '<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
2034: $cts++;
2035: }
2036: $request->print($prnmsg);
2037:
2038: # if ($env{'form.handgrade'} eq 'yes') {
2039: if (1) {
2040:
2041: my %lt = &Apache::lonlocal::texthash(
2042: keyw => 'Keyword Options',
2043: list => 'List',
2044: past => 'Paste Selection to List',
2045: high => 'Highlight Attribute',
2046: );
2047: #
2048: # Print out the keyword options line
2049: #
2050: $request->print(<<KEYWORDS);
2051: <br /><b>$lt{'keyw'}:</b>
2052: <a href="javascript:keywords(document.SCORE);" target="_self">$lt{'list'}</a>
2053: <a href="#" onmousedown="javascript:getSel(); return false"
2054: CLASS="page">$lt{'past'}</a>
2055: <a href="javascript:kwhighlight();" target="_self">$lt{'high'}</a><br /><br />
2056: KEYWORDS
2057: #
2058: # Load the other essays for similarity check
2059: #
2060: my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
2061: my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
2062: $apath=&escape($apath);
2063: $apath=~s/\W/\_/gs;
2064: &init_old_essays($symb,$apath,$adom,$aname);
2065: }
2066: }
2067:
2068: # This is where output for one specific student would start
2069: my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
2070: $request->print(
2071: "\n\n"
2072: .'<div class="LC_grade_show_user'.$add_class.'">'
2073: .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
2074: ."\n"
2075: );
2076:
2077: # Show additional functions if allowed
2078: if ($perm{'vgr'}) {
2079: $request->print(
2080: &Apache::loncommon::track_student_link(
2081: &mt('View recent activity'),
2082: $uname,$udom,'check')
2083: .' '
2084: );
2085: }
2086: if ($perm{'opa'}) {
2087: $request->print(
2088: &Apache::loncommon::pprmlink(
2089: &mt('Set/Change parameters'),
2090: $uname,$udom,$symb,'check'));
2091: }
2092:
2093: # Show Problem
2094: if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
2095: my $mode;
2096: if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
2097: $mode='both';
2098: } elsif ($env{'form.vProb'} eq 'all' ) {
2099: $mode='text';
2100: } elsif ($env{'form.vAns'} eq 'all') {
2101: $mode='answer';
2102: }
2103: &Apache::lonxml::clear_problem_counter();
2104: $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
2105: }
2106:
2107: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
2108: my $res_error;
2109: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
2110: if ($res_error) {
2111: $request->print(&navmap_errormsg());
2112: return;
2113: }
2114:
2115: # Display student info
2116: $request->print(($counter == 0 ? '' : '<br />'));
2117:
2118: my $result='<div class="LC_Box">'
2119: .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
2120: $result.='<input type="hidden" name="name'.$counter.
2121: '" value="'.$env{'form.fullname'}.'" />'."\n";
2122: # if ($env{'form.handgrade'} eq 'no') {
2123: if (1) {
2124: $result.='<p class="LC_info">'
2125: .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
2126: ."</p>\n";
2127: }
2128:
2129: # If any part of the problem is an essay-response (handgraded), then check for collaborators
2130: my $fullname;
2131: my $col_fullnames = [];
2132: # if ($env{'form.handgrade'} eq 'yes') {
2133: if (1) {
2134: (my $sub_result,$fullname,$col_fullnames)=
2135: &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
2136: $counter);
2137: $result.=$sub_result;
2138: }
2139: $request->print($result."\n");
2140:
2141: # print student answer/submission
2142: # Options are (1) Handgraded submission only
2143: # (2) Last submission, includes submission that is not handgraded
2144: # (for multi-response type part)
2145: # (3) Last submission plus the parts info
2146: # (4) The whole record for this student
2147: if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
2148: my ($string,$timestamp)= &get_last_submission(\%record);
2149:
2150: my $lastsubonly;
2151:
2152: if ($$timestamp eq '') {
2153: $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>';
2154: } else {
2155: $lastsubonly =
2156: '<div class="LC_grade_submissions_body">'
2157: .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
2158:
2159: my %seenparts;
2160: my @part_response_id = &flatten_responseType($responseType);
2161: foreach my $part (@part_response_id) {
2162: next if ($env{'form.lastSub'} eq 'hdgrade'
2163: && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
2164:
2165: my ($partid,$respid) = @{ $part };
2166: my $display_part=&get_display_part($partid,$symb);
2167: if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
2168: if (exists($seenparts{$partid})) { next; }
2169: $seenparts{$partid}=1;
2170: my $submitby='<b>Part:</b> '.$display_part.
2171: ' <b>Collaborative submission by:</b> '.
2172: '<a href="javascript:viewSubmitter(\''.
2173: $env{"form.$uname:$udom:$partid:submitted_by"}.
2174: '\');" target="_self">'.
2175: $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
2176: $request->print($submitby);
2177: next;
2178: }
2179: my $responsetype = $responseType->{$partid}->{$respid};
2180: if (!exists($record{"resource.$partid.$respid.submission"})) {
2181: $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
2182: '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
2183: ' <span class="LC_internal_info">'.
2184: '('.&mt('Response ID: [_1]',$respid).')'.
2185: '</span> '.
2186: '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
2187: next;
2188: }
2189: foreach my $submission (@$string) {
2190: my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
2191: if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
2192: my ($ressub,$hide,$subval) = split(/:/,$submission,3);
2193: # Similarity check
2194: my $similar='';
2195: my ($type,$trial,$rndseed);
2196: if ($hide eq 'rand') {
2197: $type = 'randomizetry';
2198: $trial = $record{"resource.$partid.tries"};
2199: $rndseed = $record{"resource.$partid.rndseed"};
2200: }
2201: if($env{'form.checkPlag'}){
2202: my ($oname,$odom,$ocrsid,$oessay,$osim)=
2203: &most_similar($uname,$udom,$symb,$subval);
2204: if ($osim) {
2205: $osim=int($osim*100.0);
2206: my %old_course_desc =
2207: &Apache::lonnet::coursedescription($ocrsid,
2208: {'one_time' => 1});
2209:
2210: if ($hide eq 'anon') {
2211: $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
2212: &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
2213: } else {
2214: $similar="<hr /><h3><span class=\"LC_warning\">".
2215: &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
2216: $osim,
2217: &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
2218: $old_course_desc{'description'},
2219: $old_course_desc{'num'},
2220: $old_course_desc{'domain'}).
2221: '</span></h3><blockquote><i>'.
2222: &keywords_highlight($oessay).
2223: '</i></blockquote><hr />';
2224: }
2225: }
2226: }
2227: my $order=&get_order($partid,$respid,$symb,$uname,$udom,
2228: undef,$type,$trial,$rndseed);
2229: if ($env{'form.lastSub'} eq 'lastonly' ||
2230: ($env{'form.lastSub'} eq 'hdgrade' &&
2231: $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
2232: my $display_part=&get_display_part($partid,$symb);
2233: $lastsubonly.='<div class="LC_grade_submission_part">'.
2234: '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
2235: ' <span class="LC_internal_info">'.
2236: '('.&mt('Response ID: [_1]',$respid).')'.
2237: '</span> ';
2238: my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
2239: if (@$files) {
2240: if ($hide eq 'anon') {
2241: $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
2242: } else {
2243: $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
2244: foreach my $file (@$files) {
2245: &Apache::lonnet::allowuploaded('/adm/grades',$file);
2246: $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
2247: }
2248: }
2249: $lastsubonly.='<br />';
2250: }
2251: if ($hide eq 'anon') {
2252: $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>';
2253: } else {
2254: $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
2255: &cleanRecord($subval,$responsetype,$symb,$partid,
2256: $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
2257: }
2258: if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
2259: $lastsubonly.='</div>';
2260: }
2261: }
2262: }
2263: $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
2264: }
2265: $request->print($lastsubonly);
2266: } elsif ($env{'form.lastSub'} eq 'datesub') {
2267: my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
2268: $request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
2269: } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
2270: $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
2271: $env{'request.course.id'},
2272: $last,'.submission',
2273: 'Apache::grades::keywords_highlight'));
2274: }
2275: $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
2276: .$udom.'" />'."\n");
2277: # return if view submission with no grading option
2278: if (!&canmodify($usec)) {
2279: $request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
2280: return;
2281: } else {
2282: $request->print('</div>'."\n");
2283: }
2284:
2285: # essay grading message center
2286: # if ($env{'form.handgrade'} eq 'yes') {
2287: if (1) {
2288: my $result='<div class="LC_grade_message_center">';
2289:
2290: $result.='<div class="LC_grade_message_center_header">'.
2291: &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
2292: my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
2293: my $msgfor = $givenn.' '.$lastname;
2294: if (scalar(@$col_fullnames) > 0) {
2295: my $lastone = pop(@$col_fullnames);
2296: $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
2297: }
2298: $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
2299: $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
2300: '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
2301: $result.=' <a href="javascript:msgCenter(document.SCORE,'.$counter.
2302: ',\''.$msgfor.'\');" target="_self">'.
2303: &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
2304: &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
2305: '<img src="'.$request->dir_config('lonIconsURL').
2306: '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
2307: '<br /> ('.
2308: &mt('Message will be sent when you click on Save & Next below.').")\n";
2309: $result.='</div></div>';
2310: $request->print($result);
2311: }
2312:
2313: my %seen = ();
2314: my @partlist;
2315: my @gradePartRespid;
2316: my @part_response_id = &flatten_responseType($responseType);
2317: $request->print(
2318: '<div class="LC_Box">'
2319: .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
2320: );
2321: $request->print(&gradeBox_start());
2322: foreach my $part_response_id (@part_response_id) {
2323: my ($partid,$respid) = @{ $part_response_id };
2324: my $part_resp = join('_',@{ $part_response_id });
2325: next if ($seen{$partid} > 0);
2326: $seen{$partid}++;
2327: next if ($$handgrade{$part_resp} ne 'yes'
2328: && $env{'form.lastSub'} eq 'hdgrade');
2329: push(@partlist,$partid);
2330: push(@gradePartRespid,$partid.'.'.$respid);
2331: $request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
2332: }
2333: $request->print(&gradeBox_end()); # </div>
2334: $request->print('</div>');
2335:
2336: $request->print('<div class="LC_grade_info_links">');
2337: $request->print('</div>');
2338:
2339: $result='<input type="hidden" name="partlist'.$counter.
2340: '" value="'.(join ":",@partlist).'" />'."\n";
2341: $result.='<input type="hidden" name="gradePartRespid'.
2342: '" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
2343: my $ctr = 0;
2344: while ($ctr < scalar(@partlist)) {
2345: $result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
2346: $partlist[$ctr].'" />'."\n";
2347: $ctr++;
2348: }
2349: $request->print($result.''."\n");
2350:
2351: # Done with printing info for one student
2352:
2353: $request->print('</div>');#LC_grade_show_user
2354:
2355:
2356: # print end of form
2357: if ($counter == $total) {
2358: my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
2359: $endform.='<input type="button" value="'.&mt('Save & Next').'" '.
2360: 'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
2361: $total.','.scalar(@partlist).');" target="_self" /> '."\n";
2362: my $ntstu ='<select name="NTSTU">'.
2363: '<option>1</option><option>2</option>'.
2364: '<option>3</option><option>5</option>'.
2365: '<option>7</option><option>10</option></select>'."\n";
2366: my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
2367: $ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
2368: $endform.=&mt('[_1]student(s)',$ntstu);
2369: $endform.=' <input type="button" value="'.&mt('Previous').'" '.
2370: 'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> '."\n".
2371: '<input type="button" value="'.&mt('Next').'" '.
2372: 'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> ';
2373: $endform.='<span class="LC_warning">'.
2374: &mt('(Next and Previous (student) do not save the scores.)').
2375: '</span>'."\n" ;
2376: $endform.="<input type='hidden' value='".&get_increment().
2377: "' name='increment' />";
2378: $endform.='</td></tr></table></form>';
2379: $request->print($endform);
2380: }
2381: return '';
2382: }
2383:
2384: sub check_collaborators {
2385: my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
2386: my ($result,@col_fullnames);
2387: my ($classlist,undef,$fullname) = &getclasslist('all','0');
2388: foreach my $part (keys(%$handgrade)) {
2389: my $ncol = &Apache::lonnet::EXT('resource.'.$part.
2390: '.maxcollaborators',
2391: $symb,$udom,$uname);
2392: next if ($ncol <= 0);
2393: $part =~ s/\_/\./g;
2394: next if ($record->{'resource.'.$part.'.collaborators'} eq '');
2395: my (@good_collaborators, @bad_collaborators);
2396: foreach my $possible_collaborator
2397: (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) {
2398: $possible_collaborator =~ s/[\$\^\(\)]//g;
2399: next if ($possible_collaborator eq '');
2400: my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
2401: $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
2402: next if ($co_name eq $uname && $co_dom eq $udom);
2403: # Doing this grep allows 'fuzzy' specification
2404: my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i,
2405: keys(%$classlist));
2406: if (! scalar(@matches)) {
2407: push(@bad_collaborators, $possible_collaborator);
2408: } else {
2409: push(@good_collaborators, @matches);
2410: }
2411: }
2412: if (scalar(@good_collaborators) != 0) {
2413: $result.='<br />'.&mt('Collaborators:').'<ol>';
2414: foreach my $name (@good_collaborators) {
2415: my ($lastname,$givenn) = split(/,/,$$fullname{$name});
2416: push(@col_fullnames, $givenn.' '.$lastname);
2417: $result.='<li>'.$fullname->{$name}.'</li>';
2418: }
2419: $result.='</ol><br />'."\n";
2420: my ($part)=split(/\./,$part);
2421: $result.='<input type="hidden" name="collaborator'.$counter.
2422: '" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
2423: "\n";
2424: }
2425: if (scalar(@bad_collaborators) > 0) {
2426: $result.='<div class="LC_warning">';
2427: $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
2428: $result .= '</div>';
2429: }
2430: if (scalar(@bad_collaborators > $ncol)) {
2431: $result .= '<div class="LC_warning">';
2432: $result .= &mt('This student has submitted too many '.
2433: 'collaborators. Maximum is [_1].',$ncol);
2434: $result .= '</div>';
2435: }
2436: }
2437: return ($result,$fullname,\@col_fullnames);
2438: }
2439:
2440: #--- Retrieve the last submission for all the parts
2441: sub get_last_submission {
2442: my ($returnhash)=@_;
2443: my (@string,$timestamp,%lasthidden);
2444: if ($$returnhash{'version'}) {
2445: my %lasthash=();
2446: my ($version);
2447: for ($version=1;$version<=$$returnhash{'version'};$version++) {
2448: foreach my $key (sort(split(/\:/,
2449: $$returnhash{$version.':keys'}))) {
2450: $lasthash{$key}=$$returnhash{$version.':'.$key};
2451: $timestamp =
2452: &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
2453: }
2454: }
2455: my (%typeparts,%randombytry);
2456: my $showsurv =
2457: &Apache::lonnet::allowed('vas',$env{'request.course.id'});
2458: foreach my $key (sort(keys(%lasthash))) {
2459: if ($key =~ /\.type$/) {
2460: if (($lasthash{$key} eq 'anonsurvey') ||
2461: ($lasthash{$key} eq 'anonsurveycred') ||
2462: ($lasthash{$key} eq 'randomizetry')) {
2463: my ($ign,@parts) = split(/\./,$key);
2464: pop(@parts);
2465: my $id = join('.',@parts);
2466: if ($lasthash{$key} eq 'randomizetry') {
2467: $randombytry{$ign.'.'.$id} = $lasthash{$key};
2468: } else {
2469: unless ($showsurv) {
2470: $typeparts{$ign.'.'.$id} = $lasthash{$key};
2471: }
2472: }
2473: delete($lasthash{$key});
2474: }
2475: }
2476: }
2477: my @hidden = keys(%typeparts);
2478: my @randomize = keys(%randombytry);
2479: foreach my $key (keys(%lasthash)) {
2480: next if ($key !~ /\.submission$/);
2481: my $hide;
2482: if (@hidden) {
2483: foreach my $id (@hidden) {
2484: if ($key =~ /^\Q$id\E/) {
2485: $hide = 'anon';
2486: last;
2487: }
2488: }
2489: }
2490: unless ($hide) {
2491: if (@randomize) {
2492: foreach my $id (@hidden) {
2493: if ($key =~ /^\Q$id\E/) {
2494: $hide = 'rand';
2495: last;
2496: }
2497: }
2498: }
2499: }
2500: my ($partid,$foo) = split(/submission$/,$key);
2501: my $draft = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
2502: '<span class="LC_warning">Draft Copy</span> ' : '';
2503: push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
2504: }
2505: }
2506: if (!@string) {
2507: $string[0] =
2508: '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
2509: }
2510: return (\@string,\$timestamp);
2511: }
2512:
2513: #--- High light keywords, with style choosen by user.
2514: sub keywords_highlight {
2515: my $string = shift;
2516: my $size = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
2517: my $styleon = $env{'form.kwstyle'} eq '' ? '' : $env{'form.kwstyle'};
2518: (my $styleoff = $styleon) =~ s/\</\<\//;
2519: my @keylist = split(/[,\s+]/,$env{'form.keywords'});
2520: foreach my $keyword (@keylist) {
2521: $string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
2522: }
2523: return $string;
2524: }
2525:
2526: # For Tasks provide a mechanism to display previous version for one specific student
2527:
2528: sub show_previous_task_version {
2529: my ($request,$symb) = @_;
2530: if ($symb eq '') {
2531: $request->print("Unable to handle ambiguous references.");
2532:
2533: return '';
2534: }
2535: my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
2536: my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
2537: if (!&canview($usec)) {
2538: $request->print('<span class="LC_warning">Unable to view previous version for requested student.('.
2539: $uname.':'.$udom.' in section '.$usec.' in course id '.
2540: $env{'request.course.id'}.')</span>');
2541: return;
2542: }
2543: my $mode = 'both';
2544: my $isTask = ($symb =~/\.task$/);
2545: if ($isTask) {
2546: if ($env{'form.previousversion'} =~ /^\d+$/) {
2547: if ($env{'form.fullname'} eq '') {
2548: $env{'form.fullname'} =
2549: &Apache::loncommon::plainname($uname,$udom,'lastname');
2550: }
2551: my $probtitle=&Apache::lonnet::gettitle($symb);
2552: $request->print("\n\n".
2553: '<div class="LC_grade_show_user">'.
2554: '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
2555: '</h2>'."\n");
2556: &Apache::lonxml::clear_problem_counter();
2557: $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
2558: {'previousversion' => $env{'form.previousversion'} }));
2559: $request->print("\n</div>");
2560: }
2561: }
2562: return;
2563: }
2564:
2565: sub choose_task_version_form {
2566: my ($symb,$uname,$udom,$nomenu) = @_;
2567: my $isTask = ($symb =~/\.task$/);
2568: my ($current,$version,$result,$js,$displayed,$rowtitle);
2569: if ($isTask) {
2570: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
2571: $udom,$uname);
2572: if (($record{'resource.0.version'} eq '') ||
2573: ($record{'resource.0.version'} < 2)) {
2574: return ($record{'resource.0.version'},
2575: $record{'resource.0.version'},$result,$js);
2576: } else {
2577: $current = $record{'resource.0.version'};
2578: }
2579: if ($env{'form.previousversion'}) {
2580: $displayed = $env{'form.previousversion'};
2581: $rowtitle = &mt('Choose another version:')
2582: } else {
2583: $displayed = $current;
2584: $rowtitle = &mt('Show earlier version:');
2585: }
2586: $result = '<div class="LC_left_float">';
2587: my $list;
2588: my $numversions = 0;
2589: for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
2590: if ($i == $current) {
2591: if (!$env{'form.previousversion'} || $nomenu) {
2592: next;
2593: } else {
2594: $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
2595: $numversions ++;
2596: }
2597: } elsif (defined($record{'resource.'.$i.'.0.status'})) {
2598: unless ($i == $env{'form.previousversion'}) {
2599: $numversions ++;
2600: }
2601: $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
2602: }
2603: }
2604: if ($numversions) {
2605: $symb = &HTML::Entities::encode($symb,'<>"&');
2606: $result .=
2607: '<form name="getprev" method="post" action=""'.
2608: ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
2609: &Apache::loncommon::start_data_table().
2610: &Apache::loncommon::start_data_table_row().
2611: '<th align="left">'.$rowtitle.'</th>'.
2612: '<td><select name="version">'.
2613: '<option>'.&mt('Select').'</option>'.
2614: $list.
2615: '</select></td>'.
2616: &Apache::loncommon::end_data_table_row();
2617: unless ($nomenu) {
2618: $result .= &Apache::loncommon::start_data_table_row().
2619: '<th align="left">'.&mt('Open in new window').'</th>'.
2620: '<td><span class="LC_nobreak">'.
2621: '<label><input type="radio" name="prevwin" value="1" />'.
2622: &mt('Yes').'</label>'.
2623: '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
2624: '</span></td>'.
2625: &Apache::loncommon::end_data_table_row();
2626: }
2627: $result .=
2628: &Apache::loncommon::start_data_table_row().
2629: '<th align="left"> </th>'.
2630: '<td>'.
2631: '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
2632: '</td>'.
2633: &Apache::loncommon::end_data_table_row().
2634: &Apache::loncommon::end_data_table().
2635: '</form>';
2636: $js = &previous_display_javascript($nomenu,$current);
2637: } elsif ($displayed && $nomenu) {
2638: $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
2639: } else {
2640: $result .= &mt('No previous versions to show for this student');
2641: }
2642: $result .= '</div>';
2643: }
2644: return ($current,$displayed,$result,$js);
2645: }
2646:
2647: sub previous_display_javascript {
2648: my ($nomenu,$current) = @_;
2649: my $js = <<"JSONE";
2650: <script type="text/javascript">
2651: // <![CDATA[
2652: function previousVersion(uname,udom,symb) {
2653: var current = '$current';
2654: var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
2655: var prevstr = new RegExp("^\\\\d+\$");
2656: if (!prevstr.test(version)) {
2657: return false;
2658: }
2659: var url = '';
2660: if (version == current) {
2661: url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
2662: } else {
2663: url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
2664: }
2665: JSONE
2666: if ($nomenu) {
2667: $js .= <<"JSTWO";
2668: document.location.href = url;
2669: JSTWO
2670: } else {
2671: $js .= <<"JSTHREE";
2672: var newwin = 0;
2673: for (var i=0; i<document.getprev.prevwin.length; i++) {
2674: if (document.getprev.prevwin[i].checked == true) {
2675: newwin = document.getprev.prevwin[i].value;
2676: }
2677: }
2678: if (newwin == 1) {
2679: var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
2680: url = url+'&inhibitmenu=yes';
2681: if (typeof(previousWin) == 'undefined' || previousWin.closed) {
2682: previousWin = window.open(url,'',options,1);
2683: } else {
2684: previousWin.location.href = url;
2685: }
2686: previousWin.focus();
2687: return false;
2688: } else {
2689: document.location.href = url;
2690: return false;
2691: }
2692: JSTHREE
2693: }
2694: $js .= <<"ENDJS";
2695: return false;
2696: }
2697: // ]]>
2698: </script>
2699: ENDJS
2700:
2701: }
2702:
2703: #--- Called from submission routine
2704: sub processHandGrade {
2705: my ($request,$symb) = @_;
2706: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
2707: my $button = $env{'form.gradeOpt'};
2708: my $ngrade = $env{'form.NCT'};
2709: my $ntstu = $env{'form.NTSTU'};
2710: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2711: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2712:
2713: if ($button eq 'Save & Next') {
2714: my $ctr = 0;
2715: while ($ctr < $ngrade) {
2716: my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
2717: my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
2718: if ($errorflag eq 'no_score') {
2719: $ctr++;
2720: next;
2721: }
2722: if ($errorflag eq 'not_allowed') {
2723: $request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
2724: $ctr++;
2725: next;
2726: }
2727: my $includemsg = $env{'form.includemsg'.$ctr};
2728: my ($subject,$message,$msgstatus) = ('','','');
2729: my $restitle = &Apache::lonnet::gettitle($symb);
2730: my ($feedurl,$showsymb) =
2731: &get_feedurl_and_symb($symb,$uname,$udom);
2732: my $messagetail;
2733: if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
2734: $subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
2735: unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
2736: $subject.=' ['.$restitle.']';
2737: my (@msgnum) = split(/,/,$includemsg);
2738: foreach (@msgnum) {
2739: $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
2740: }
2741: $message =&Apache::lonfeedback::clear_out_html($message);
2742: if ($env{'form.withgrades'.$ctr}) {
2743: $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
2744: $messagetail = " for <a href=\"".
2745: $feedurl."?symb=$showsymb\">$restitle</a>";
2746: }
2747: $msgstatus =
2748: &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
2749: $message.$messagetail,
2750: undef,$feedurl,undef,
2751: undef,undef,$showsymb,
2752: $restitle);
2753: $request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
2754: $msgstatus.'<br />');
2755: }
2756: if ($env{'form.collaborator'.$ctr}) {
2757: my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
2758: foreach my $collabstr (@collabstrs) {
2759: my ($part,@collaborators) = split(/:/,$collabstr);
2760: foreach my $collaborator (@collaborators) {
2761: my ($errorflag,$pts,$wgt) =
2762: &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
2763: $env{'form.unamedom'.$ctr},$part);
2764: if ($errorflag eq 'not_allowed') {
2765: $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
2766: next;
2767: } elsif ($message ne '') {
2768: my ($baseurl,$showsymb) =
2769: &get_feedurl_and_symb($symb,$collaborator,
2770: $udom);
2771: if ($env{'form.withgrades'.$ctr}) {
2772: $messagetail = " for <a href=\"".
2773: $baseurl."?symb=$showsymb\">$restitle</a>";
2774: }
2775: $msgstatus =
2776: &Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
2777: }
2778: }
2779: }
2780: }
2781: $ctr++;
2782: }
2783: }
2784:
2785: # if ($env{'form.handgrade'} eq 'yes') {
2786: if (1) {
2787: # Keywords sorted in alphabatical order
2788: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
2789: my %keyhash = ();
2790: $env{'form.keywords'} =~ s/,\s{0,}|\s+/ /g;
2791: $env{'form.keywords'} =~ s/^\s+|\s+$//;
2792: my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
2793: $env{'form.keywords'} = join(' ',@keywords);
2794: $keyhash{$symb.'_keywords'} = $env{'form.keywords'};
2795: $keyhash{$symb.'_subject'} = $env{'form.msgsub'};
2796: $keyhash{$loginuser.'_kwclr'} = $env{'form.kwclr'};
2797: $keyhash{$loginuser.'_kwsize'} = $env{'form.kwsize'};
2798: $keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
2799:
2800: # message center - Order of message gets changed. Blank line is eliminated.
2801: # New messages are saved in env for the next student.
2802: # All messages are saved in nohist_handgrade.db
2803: my ($ctr,$idx) = (1,1);
2804: while ($ctr <= $env{'form.savemsgN'}) {
2805: if ($env{'form.savemsg'.$ctr} ne '') {
2806: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
2807: $idx++;
2808: }
2809: $ctr++;
2810: }
2811: $ctr = 0;
2812: while ($ctr < $ngrade) {
2813: if ($env{'form.newmsg'.$ctr} ne '') {
2814: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2815: $env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2816: $idx++;
2817: }
2818: $ctr++;
2819: }
2820: $env{'form.savemsgN'} = --$idx;
2821: $keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
2822: my $putresult = &Apache::lonnet::put
2823: ('nohist_handgrade',\%keyhash,$cdom,$cnum);
2824: }
2825: # Called by Save & Refresh from Highlight Attribute Window
2826: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
2827: if ($env{'form.refresh'} eq 'on') {
2828: my ($ctr,$total) = (0,0);
2829: while ($ctr < $ngrade) {
2830: $total++ if $env{'form.unamedom'.$ctr} ne '';
2831: $ctr++;
2832: }
2833: $env{'form.NTSTU'}=$ngrade;
2834: $ctr = 0;
2835: while ($ctr < $total) {
2836: my $processUser = $env{'form.unamedom'.$ctr};
2837: ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
2838: $env{'form.fullname'} = $$fullname{$processUser};
2839: &submission($request,$ctr,$total-1,$symb);
2840: $ctr++;
2841: }
2842: return '';
2843: }
2844:
2845: # Get the next/previous one or group of students
2846: my $firststu = $env{'form.unamedom0'};
2847: my $laststu = $env{'form.unamedom'.($ngrade-1)};
2848: my $ctr = 2;
2849: while ($laststu eq '') {
2850: $laststu = $env{'form.unamedom'.($ngrade-$ctr)};
2851: $ctr++;
2852: $laststu = $firststu if ($ctr > $ngrade);
2853: }
2854:
2855: my (@parsedlist,@nextlist);
2856: my ($nextflg) = 0;
2857: foreach my $item (sort
2858: {
2859: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
2860: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
2861: }
2862: return $a cmp $b;
2863: } (keys(%$fullname))) {
2864: # FIXME: this is fishy, looks like the button label
2865: if ($nextflg == 1 && $button =~ /Next$/) {
2866: push(@parsedlist,$item);
2867: }
2868: $nextflg = 1 if ($item eq $laststu);
2869: if ($button eq 'Previous') {
2870: last if ($item eq $firststu);
2871: push(@parsedlist,$item);
2872: }
2873: }
2874: $ctr = 0;
2875: # FIXME: this is fishy, looks like the button label
2876: @parsedlist = reverse @parsedlist if ($button eq 'Previous');
2877: my $res_error;
2878: my ($partlist) = &response_type($symb,\$res_error);
2879: if ($res_error) {
2880: $request->print(&navmap_errormsg());
2881: return;
2882: }
2883: foreach my $student (@parsedlist) {
2884: my $submitonly=$env{'form.submitonly'};
2885: my ($uname,$udom) = split(/:/,$student);
2886:
2887: if ($submitonly eq 'queued') {
2888: my %queue_status =
2889: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
2890: $udom,$uname);
2891: next if (!defined($queue_status{'gradingqueue'}));
2892: }
2893:
2894: if ($submitonly =~ /^(yes|graded|incorrect)$/) {
2895: # my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
2896: my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
2897: my $submitted = 0;
2898: my $ungraded = 0;
2899: my $incorrect = 0;
2900: foreach my $item (keys(%status)) {
2901: $submitted = 1 if ($status{$item} ne 'nothing');
2902: $ungraded = 1 if ($status{$item} =~ /^ungraded/);
2903: $incorrect = 1 if ($status{$item} =~ /^incorrect/);
2904: my ($foo,$partid,$foo1) = split(/\./,$item);
2905: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
2906: $submitted = 0;
2907: }
2908: }
2909: next if (!$submitted && ($submitonly eq 'yes' ||
2910: $submitonly eq 'incorrect' ||
2911: $submitonly eq 'graded'));
2912: next if (!$ungraded && ($submitonly eq 'graded'));
2913: next if (!$incorrect && $submitonly eq 'incorrect');
2914: }
2915: push(@nextlist,$student) if ($ctr < $ntstu);
2916: last if ($ctr == $ntstu);
2917: $ctr++;
2918: }
2919:
2920: $ctr = 0;
2921: my $total = scalar(@nextlist)-1;
2922:
2923: foreach (sort(@nextlist)) {
2924: my ($uname,$udom,$submitter) = split(/:/);
2925: $env{'form.student'} = $uname;
2926: $env{'form.userdom'} = $udom;
2927: $env{'form.fullname'} = $$fullname{$_};
2928: &submission($request,$ctr,$total,$symb);
2929: $ctr++;
2930: }
2931: if ($total < 0) {
2932: my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
2933: $request->print($the_end);
2934: }
2935: return '';
2936: }
2937:
2938: #---- Save the score and award for each student, if changed
2939: sub saveHandGrade {
2940: my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
2941: my @version_parts;
2942: my $usec = &Apache::lonnet::getsection($domain,$stuname,
2943: $env{'request.course.id'});
2944: if (!&canmodify($usec)) { return('not_allowed'); }
2945: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
2946: my @parts_graded;
2947: my %newrecord = ();
2948: my ($pts,$wgt) = ('','');
2949: my %aggregate = ();
2950: my $aggregateflag = 0;
2951: my @parts = split(/:/,$env{'form.partlist'.$newflg});
2952: foreach my $new_part (@parts) {
2953: #collaborator ($submi may vary for different parts
2954: if ($submitter && $new_part ne $part) { next; }
2955: my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
2956: if ($dropMenu eq 'excused') {
2957: if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
2958: $newrecord{'resource.'.$new_part.'.solved'} = 'excused';
2959: if (exists($record{'resource.'.$new_part.'.awarded'})) {
2960: $newrecord{'resource.'.$new_part.'.awarded'} = '';
2961: }
2962: $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
2963: }
2964: } elsif ($dropMenu eq 'reset status'
2965: && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
2966: foreach my $key (keys(%record)) {
2967: if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
2968: }
2969: $newrecord{'resource.'.$new_part.'.regrader'}=
2970: "$env{'user.name'}:$env{'user.domain'}";
2971: my $totaltries = $record{'resource.'.$part.'.tries'};
2972:
2973: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
2974: [$new_part]);
2975: my $aggtries =$totaltries;
2976: if ($last_resets{$new_part}) {
2977: $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
2978: $new_part);
2979: }
2980:
2981: my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
2982: if ($aggtries > 0) {
2983: &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
2984: $aggregateflag = 1;
2985: }
2986: } elsif ($dropMenu eq '') {
2987: $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ?
2988: $env{'form.GD_BOX'.$newflg.'_'.$new_part} :
2989: $env{'form.RADVAL'.$newflg.'_'.$new_part});
2990: if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
2991: next;
2992: }
2993: $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 :
2994: $env{'form.WGT'.$newflg.'_'.$new_part};
2995: my $partial= $pts/$wgt;
2996: if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
2997: #do not update score for part if not changed.
2998: &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
2999: next;
3000: } else {
3001: push(@parts_graded,$new_part);
3002: }
3003: if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
3004: $newrecord{'resource.'.$new_part.'.awarded'} = $partial;
3005: }
3006: my $reckey = 'resource.'.$new_part.'.solved';
3007: if ($partial == 0) {
3008: if ($record{$reckey} ne 'incorrect_by_override') {
3009: $newrecord{$reckey} = 'incorrect_by_override';
3010: }
3011: } else {
3012: if ($record{$reckey} ne 'correct_by_override') {
3013: $newrecord{$reckey} = 'correct_by_override';
3014: }
3015: }
3016: if ($submitter &&
3017: ($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
3018: $newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
3019: }
3020: $newrecord{'resource.'.$new_part.'.regrader'}=
3021: "$env{'user.name'}:$env{'user.domain'}";
3022: }
3023: # unless problem has been graded, set flag to version the submitted files
3024: unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/ ||
3025: $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
3026: $dropMenu eq 'reset status')
3027: {
3028: push(@version_parts,$new_part);
3029: }
3030: }
3031: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3032: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3033:
3034: if (%newrecord) {
3035: if (@version_parts) {
3036: my @changed_keys = &version_portfiles(\%record, \@parts_graded,
3037: $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
3038: @newrecord{@changed_keys} = @record{@changed_keys};
3039: foreach my $new_part (@version_parts) {
3040: &handback_files($request,$symb,$stuname,$domain,$newflg,
3041: $new_part,\%newrecord);
3042: }
3043: }
3044: &Apache::lonnet::cstore(\%newrecord,$symb,
3045: $env{'request.course.id'},$domain,$stuname);
3046: &check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
3047: $cdom,$cnum,$domain,$stuname);
3048: }
3049: if ($aggregateflag) {
3050: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
3051: $cdom,$cnum);
3052: }
3053: return ('',$pts,$wgt);
3054: }
3055:
3056: sub check_and_remove_from_queue {
3057: my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
3058: my @ungraded_parts;
3059: foreach my $part (@{$parts}) {
3060: if ( $record->{ 'resource.'.$part.'.awarded'} eq ''
3061: && $record->{ 'resource.'.$part.'.solved' } ne 'excused'
3062: && $newrecord->{'resource.'.$part.'.awarded'} eq ''
3063: && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
3064: ) {
3065: push(@ungraded_parts, $part);
3066: }
3067: }
3068: if ( !@ungraded_parts ) {
3069: &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
3070: $cnum,$domain,$stuname);
3071: }
3072: }
3073:
3074: sub handback_files {
3075: my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
3076: my $portfolio_root = '/userfiles/portfolio';
3077: my $res_error;
3078: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
3079: if ($res_error) {
3080: $request->print('<br />'.&navmap_errormsg().'<br />');
3081: return;
3082: }
3083: my @handedback;
3084: my $file_msg;
3085: my @part_response_id = &flatten_responseType($responseType);
3086: foreach my $part_response_id (@part_response_id) {
3087: my ($part_id,$resp_id) = @{ $part_response_id };
3088: my $part_resp = join('_',@{ $part_response_id });
3089: if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
3090: for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
3091: # if multiple files are uploaded names will be 'returndoc2','returndoc3'
3092: if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
3093: my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
3094: my ($directory,$answer_file) =
3095: ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
3096: my ($answer_name,$answer_ver,$answer_ext) =
3097: &file_name_version_ext($answer_file);
3098: my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
3099: my $getpropath = 1;
3100: my ($dir_list,$listerror) =
3101: &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
3102: $domain,$stuname,$getpropath);
3103: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
3104: # fix filename
3105: my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
3106: my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
3107: $newflg.'_'.$part_resp.'_returndoc'.$counter,
3108: $save_file_name);
3109: if ($result !~ m|^/uploaded/|) {
3110: $request->print('<br /><span class="LC_error">'.
3111: &mt('An error occurred ([_1]) while trying to upload [_2].',
3112: $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
3113: '</span>');
3114: } else {
3115: # mark the file as read only
3116: push(@handedback,$save_file_name);
3117: if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
3118: $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
3119: }
3120: $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
3121: $file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
3122: }
3123: $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>'));
3124: }
3125: }
3126: }
3127: }
3128: if (@handedback > 0) {
3129: $request->print('<br />');
3130: my @what = ($symb,$env{'request.course.id'},'handback');
3131: &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
3132: my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});
3133: my ($subject,$message);
3134: if (scalar(@handedback) == 1) {
3135: $subject = &mt_user($user_lh,'File Handed Back by Instructor');
3136: $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
3137: } else {
3138: $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
3139: $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
3140: }
3141: $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
3142: $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
3143: &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
3144: my ($feedurl,$showsymb) =
3145: &get_feedurl_and_symb($symb,$domain,$stuname);
3146: my $restitle = &Apache::lonnet::gettitle($symb);
3147: $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
3148: my $msgstatus =
3149: &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
3150: $message,undef,$feedurl,undef,undef,undef,$showsymb,
3151: $restitle);
3152: if ($msgstatus) {
3153: $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
3154: }
3155: }
3156: return;
3157: }
3158:
3159: sub get_feedurl_and_symb {
3160: my ($symb,$uname,$udom) = @_;
3161: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3162: $url = &Apache::lonnet::clutter($url);
3163: my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
3164: $symb,$udom,$uname);
3165: if ($encrypturl =~ /^yes$/i) {
3166: &Apache::lonenc::encrypted(\$url,1);
3167: &Apache::lonenc::encrypted(\$symb,1);
3168: }
3169: return ($url,$symb);
3170: }
3171:
3172: sub get_submitted_files {
3173: my ($udom,$uname,$partid,$respid,$record) = @_;
3174: my @files;
3175: if ($$record{"resource.$partid.$respid.portfiles"}) {
3176: my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
3177: foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
3178: push(@files,$file_url.$file);
3179: }
3180: }
3181: if ($$record{"resource.$partid.$respid.uploadedurl"}) {
3182: push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
3183: }
3184: return (\@files);
3185: }
3186:
3187: # ----------- Provides number of tries since last reset.
3188: sub get_num_tries {
3189: my ($record,$last_reset,$part) = @_;
3190: my $timestamp = '';
3191: my $num_tries = 0;
3192: if ($$record{'version'}) {
3193: for (my $version=$$record{'version'};$version>=1;$version--) {
3194: if (exists($$record{$version.':resource.'.$part.'.solved'})) {
3195: $timestamp = $$record{$version.':timestamp'};
3196: if ($timestamp > $last_reset) {
3197: $num_tries ++;
3198: } else {
3199: last;
3200: }
3201: }
3202: }
3203: }
3204: return $num_tries;
3205: }
3206:
3207: # ----------- Determine decrements required in aggregate totals
3208: sub decrement_aggs {
3209: my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
3210: my %decrement = (
3211: attempts => 0,
3212: users => 0,
3213: correct => 0
3214: );
3215: $decrement{'attempts'} = $aggtries;
3216: if ($solvedstatus =~ /^correct/) {
3217: $decrement{'correct'} = 1;
3218: }
3219: if ($aggtries == $totaltries) {
3220: $decrement{'users'} = 1;
3221: }
3222: foreach my $type (keys(%decrement)) {
3223: $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
3224: }
3225: return;
3226: }
3227:
3228: # ----------- Determine timestamps for last reset of aggregate totals for parts
3229: sub get_last_resets {
3230: my ($symb,$courseid,$partids) =@_;
3231: my %last_resets;
3232: my $cdom = $env{'course.'.$courseid.'.domain'};
3233: my $cname = $env{'course.'.$courseid.'.num'};
3234: my @keys;
3235: foreach my $part (@{$partids}) {
3236: push(@keys,"$symb\0$part\0resettime");
3237: }
3238: my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
3239: $cdom,$cname);
3240: foreach my $part (@{$partids}) {
3241: $last_resets{$part}=$results{"$symb\0$part\0resettime"};
3242: }
3243: return %last_resets;
3244: }
3245:
3246: # ----------- Handles creating versions for portfolio files as answers
3247: sub version_portfiles {
3248: my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
3249: my $version_parts = join('|',@$v_flag);
3250: my @returned_keys;
3251: my $parts = join('|', @$parts_graded);
3252: my $portfolio_root = '/userfiles/portfolio';
3253: foreach my $key (keys(%$record)) {
3254: my $new_portfiles;
3255: if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
3256: my @versioned_portfiles;
3257: my @portfiles = split(/\s*,\s*/,$$record{$key});
3258: foreach my $file (@portfiles) {
3259: &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
3260: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
3261: my ($answer_name,$answer_ver,$answer_ext) =
3262: &file_name_version_ext($answer_file);
3263: my $getpropath = 1;
3264: my ($dir_list,$listerror) =
3265: &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
3266: $stu_name,$getpropath);
3267: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
3268: my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
3269: if ($new_answer ne 'problem getting file') {
3270: push(@versioned_portfiles, $directory.$new_answer);
3271: &Apache::lonnet::mark_as_readonly($domain,$stu_name,
3272: [$directory.$new_answer],
3273: [$symb,$env{'request.course.id'},'graded']);
3274: }
3275: }
3276: $$record{$key} = join(',',@versioned_portfiles);
3277: push(@returned_keys,$key);
3278: }
3279: }
3280: return (@returned_keys);
3281: }
3282:
3283: sub get_next_version {
3284: my ($answer_name, $answer_ext, $dir_list) = @_;
3285: my $version;
3286: if (ref($dir_list) eq 'ARRAY') {
3287: foreach my $row (@{$dir_list}) {
3288: my ($file) = split(/\&/,$row,2);
3289: my ($file_name,$file_version,$file_ext) =
3290: &file_name_version_ext($file);
3291: if (($file_name eq $answer_name) &&
3292: ($file_ext eq $answer_ext)) {
3293: # gets here if filename and extension match,
3294: # regardless of version
3295: if ($file_version ne '') {
3296: # a versioned file is found so save it for later
3297: if ($file_version > $version) {
3298: $version = $file_version;
3299: }
3300: }
3301: }
3302: }
3303: }
3304: $version ++;
3305: return($version);
3306: }
3307:
3308: sub version_selected_portfile {
3309: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
3310: my ($answer_name,$answer_ver,$answer_ext) =
3311: &file_name_version_ext($file_name);
3312: my $new_answer;
3313: $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
3314: if($env{'form.copy'} eq '-1') {
3315: $new_answer = 'problem getting file';
3316: } else {
3317: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
3318: my $copy_result = &Apache::lonnet::finishuserfileupload(
3319: $stu_name,$domain,'copy',
3320: '/portfolio'.$directory.$new_answer);
3321: }
3322: return ($new_answer);
3323: }
3324:
3325: sub file_name_version_ext {
3326: my ($file)=@_;
3327: my @file_parts = split(/\./, $file);
3328: my ($name,$version,$ext);
3329: if (@file_parts > 1) {
3330: $ext=pop(@file_parts);
3331: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
3332: $version=pop(@file_parts);
3333: }
3334: $name=join('.',@file_parts);
3335: } else {
3336: $name=join('.',@file_parts);
3337: }
3338: return($name,$version,$ext);
3339: }
3340:
3341: #--------------------------------------------------------------------------------------
3342: #
3343: #-------------------------- Next few routines handles grading by section or whole class
3344: #
3345: #--- Javascript to handle grading by section or whole class
3346: sub viewgrades_js {
3347: my ($request) = shift;
3348:
3349: my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
3350: $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
3351: function writePoint(partid,weight,point) {
3352: var radioButton = document.classgrade["RADVAL_"+partid];
3353: var textbox = document.classgrade["TEXTVAL_"+partid];
3354: if (point == "textval") {
3355: point = document.classgrade["TEXTVAL_"+partid].value;
3356: if (isNaN(point) || parseFloat(point) < 0) {
3357: alert("$alertmsg"+parseFloat(point));
3358: var resetbox = false;
3359: for (var i=0; i<radioButton.length; i++) {
3360: if (radioButton[i].checked) {
3361: textbox.value = i;
3362: resetbox = true;
3363: }
3364: }
3365: if (!resetbox) {
3366: textbox.value = "";
3367: }
3368: return;
3369: }
3370: if (parseFloat(point) > parseFloat(weight)) {
3371: var resp = confirm("You entered a value ("+parseFloat(point)+
3372: ") greater than the weight for the part. Accept?");
3373: if (resp == false) {
3374: textbox.value = "";
3375: return;
3376: }
3377: }
3378: for (var i=0; i<radioButton.length; i++) {
3379: radioButton[i].checked=false;
3380: if (parseFloat(point) == i) {
3381: radioButton[i].checked=true;
3382: }
3383: }
3384:
3385: } else {
3386: textbox.value = parseFloat(point);
3387: }
3388: for (i=0;i<document.classgrade.total.value;i++) {
3389: var user = document.classgrade["ctr"+i].value;
3390: user = user.replace(new RegExp(':', 'g'),"_");
3391: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3392: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3393: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3394: if (saveval != "correct") {
3395: scorename.value = point;
3396: if (selname[0].selected != true) {
3397: selname[0].selected = true;
3398: }
3399: }
3400: }
3401: document.classgrade["SELVAL_"+partid][0].selected = true;
3402: }
3403:
3404: function writeRadText(partid,weight) {
3405: var selval = document.classgrade["SELVAL_"+partid];
3406: var radioButton = document.classgrade["RADVAL_"+partid];
3407: var override = document.classgrade["FORCE_"+partid].checked;
3408: var textbox = document.classgrade["TEXTVAL_"+partid];
3409: if (selval[1].selected || selval[2].selected) {
3410: for (var i=0; i<radioButton.length; i++) {
3411: radioButton[i].checked=false;
3412:
3413: }
3414: textbox.value = "";
3415:
3416: for (i=0;i<document.classgrade.total.value;i++) {
3417: var user = document.classgrade["ctr"+i].value;
3418: user = user.replace(new RegExp(':', 'g'),"_");
3419: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3420: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3421: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3422: if ((saveval != "correct") || override) {
3423: scorename.value = "";
3424: if (selval[1].selected) {
3425: selname[1].selected = true;
3426: } else {
3427: selname[2].selected = true;
3428: if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value))
3429: {document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
3430: }
3431: }
3432: }
3433: } else {
3434: for (i=0;i<document.classgrade.total.value;i++) {
3435: var user = document.classgrade["ctr"+i].value;
3436: user = user.replace(new RegExp(':', 'g'),"_");
3437: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3438: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3439: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3440: if ((saveval != "correct") || override) {
3441: scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
3442: selname[0].selected = true;
3443: }
3444: }
3445: }
3446: }
3447:
3448: function changeSelect(partid,user) {
3449: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
3450: var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
3451: var point = textbox.value;
3452: var weight = document.classgrade["weight_"+partid].value;
3453:
3454: if (isNaN(point) || parseFloat(point) < 0) {
3455: alert("$alertmsg"+parseFloat(point));
3456: textbox.value = "";
3457: return;
3458: }
3459: if (parseFloat(point) > parseFloat(weight)) {
3460: var resp = confirm("You entered a value ("+parseFloat(point)+
3461: ") greater than the weight of the part. Accept?");
3462: if (resp == false) {
3463: textbox.value = "";
3464: return;
3465: }
3466: }
3467: selval[0].selected = true;
3468: }
3469:
3470: function changeOneScore(partid,user) {
3471: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
3472: if (selval[1].selected || selval[2].selected) {
3473: document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
3474: if (selval[2].selected) {
3475: document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
3476: }
3477: }
3478: }
3479:
3480: function resetEntry(numpart) {
3481: for (ctpart=0;ctpart<numpart;ctpart++) {
3482: var partid = document.classgrade["partid_"+ctpart].value;
3483: var radioButton = document.classgrade["RADVAL_"+partid];
3484: var textbox = document.classgrade["TEXTVAL_"+partid];
3485: var selval = document.classgrade["SELVAL_"+partid];
3486: for (var i=0; i<radioButton.length; i++) {
3487: radioButton[i].checked=false;
3488:
3489: }
3490: textbox.value = "";
3491: selval[0].selected = true;
3492:
3493: for (i=0;i<document.classgrade.total.value;i++) {
3494: var user = document.classgrade["ctr"+i].value;
3495: user = user.replace(new RegExp(':', 'g'),"_");
3496: var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3497: resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
3498: var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
3499: resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
3500: var saveselval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3501: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3502: if (saveselval == "excused") {
3503: if (selname[1].selected == false) { selname[1].selected = true;}
3504: } else {
3505: if (selname[0].selected == false) {selname[0].selected = true};
3506: }
3507: }
3508: }
3509: }
3510:
3511: VIEWJAVASCRIPT
3512: }
3513:
3514: #--- show scores for a section or whole class w/ option to change/update a score
3515: sub viewgrades {
3516: my ($request,$symb) = @_;
3517: &viewgrades_js($request);
3518:
3519: #need to make sure we have the correct data for later EXT calls,
3520: #thus invalidate the cache
3521: &Apache::lonnet::devalidatecourseresdata(
3522: $env{'course.'.$env{'request.course.id'}.'.num'},
3523: $env{'course.'.$env{'request.course.id'}.'.domain'});
3524: &Apache::lonnet::clear_EXT_cache_status();
3525:
3526: my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
3527:
3528: #view individual student submission form - called using Javascript viewOneStudent
3529: $result.=&jscriptNform($symb);
3530:
3531: #beginning of class grading form
3532: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
3533: $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
3534: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
3535: '<input type="hidden" name="command" value="editgrades" />'."\n".
3536: &build_section_inputs().
3537: '<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
3538:
3539: my ($common_header,$specific_header);
3540: if ($env{'form.section'} eq 'all') {
3541: $common_header = &mt('Assign Common Grade to Class');
3542: $specific_header = &mt('Assign Grade to Specific Students in Class');
3543: } elsif ($env{'form.section'} eq 'none') {
3544: $common_header = &mt('Assign Common Grade to Students in no Section');
3545: $specific_header = &mt('Assign Grade to Specific Students in no Section');
3546: } else {
3547: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3548: $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
3549: $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
3550: }
3551: $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
3552: #radio buttons/text box for assigning points for a section or class.
3553: #handles different parts of a problem
3554: my $res_error;
3555: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
3556: if ($res_error) {
3557: return &navmap_errormsg();
3558: }
3559: my %weight = ();
3560: my $ctsparts = 0;
3561: my %seen = ();
3562: my @part_response_id = &flatten_responseType($responseType);
3563: foreach my $part_response_id (@part_response_id) {
3564: my ($partid,$respid) = @{ $part_response_id };
3565: my $part_resp = join('_',@{ $part_response_id });
3566: next if $seen{$partid};
3567: $seen{$partid}++;
3568: my $handgrade=$$handgrade{$part_resp};
3569: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
3570: $weight{$partid} = $wgt eq '' ? '1' : $wgt;
3571:
3572: my $display_part=&get_display_part($partid,$symb);
3573: my $radio.='<table border="0"><tr>';
3574: my $ctr = 0;
3575: while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
3576: $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
3577: 'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
3578: ','.$ctr.')" />'.$ctr."</label></td>\n";
3579: $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
3580: $ctr++;
3581: }
3582: $radio.='</tr></table>';
3583: my $line = '<input type="text" name="TEXTVAL_'.
3584: $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
3585: $partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
3586: $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
3587: $line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
3588: 'onchange="javascript:writeRadText(\''.$partid.'\','.
3589: $weight{$partid}.')"> '.
3590: '<option selected="selected"> </option>'.
3591: '<option value="excused">'.&mt('excused').'</option>'.
3592: '<option value="reset status">'.&mt('reset status').'</option>'.
3593: '</select></td>'.
3594: '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
3595: $line.='<input type="hidden" name="partid_'.
3596: $ctsparts.'" value="'.$partid.'" />'."\n";
3597: $line.='<input type="hidden" name="weight_'.
3598: $partid.'" value="'.$weight{$partid}.'" />'."\n";
3599:
3600: $result.=
3601: &Apache::loncommon::start_data_table_row()."\n".
3602: '<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>'.
3603: &Apache::loncommon::end_data_table_row()."\n";
3604: $ctsparts++;
3605: }
3606: $result.=&Apache::loncommon::end_data_table()."\n".
3607: '<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
3608: $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
3609: 'onclick="javascript:resetEntry('.$ctsparts.');" />';
3610:
3611: #table listing all the students in a section/class
3612: #header of table
3613: $result.= '<h3>'.$specific_header.'</h3>'.
3614: &Apache::loncommon::start_data_table().
3615: &Apache::loncommon::start_data_table_header_row().
3616: '<th>'.&mt('No.').'</th>'.
3617: '<th>'.&nameUserString('header')."</th>\n";
3618: my $partserror;
3619: my (@parts) = sort(&getpartlist($symb,\$partserror));
3620: if ($partserror) {
3621: return &navmap_errormsg();
3622: }
3623: my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
3624: my @partids = ();
3625: foreach my $part (@parts) {
3626: my $display=&Apache::lonnet::metadata($url,$part.'.display');
3627: my $narrowtext = &mt('Tries');
3628: $display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
3629: if (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
3630: my ($partid) = &split_part_type($part);
3631: push(@partids,$partid);
3632: #
3633: # FIXME: Looks like $display looks at English text
3634: #
3635: my $display_part=&get_display_part($partid,$symb);
3636: if ($display =~ /^Partial Credit Factor/) {
3637: $result.='<th>'.
3638: &mt('Score Part: [_1]<br /> (weight = [_2])',
3639: $display_part,$weight{$partid}).'</th>'."\n";
3640: next;
3641:
3642: } else {
3643: if ($display =~ /Problem Status/) {
3644: my $grade_status_mt = &mt('Grade Status');
3645: $display =~ s{Problem Status}{$grade_status_mt<br />};
3646: }
3647: my $part_mt = &mt('Part:');
3648: $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
3649: }
3650:
3651: $result.='<th>'.$display.'</th>'."\n";
3652: }
3653: $result.=&Apache::loncommon::end_data_table_header_row();
3654:
3655: my %last_resets =
3656: &get_last_resets($symb,$env{'request.course.id'},\@partids);
3657:
3658: #get info for each student
3659: #list all the students - with points and grade status
3660: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
3661: my $ctr = 0;
3662: foreach (sort
3663: {
3664: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
3665: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
3666: }
3667: return $a cmp $b;
3668: } (keys(%$fullname))) {
3669: $ctr++;
3670: $result.=&viewstudentgrade($symb,$env{'request.course.id'},
3671: $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
3672: }
3673: $result.=&Apache::loncommon::end_data_table();
3674: $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
3675: $result.='<input type="button" value="'.&mt('Save').'" '.
3676: 'onclick="javascript:submit();" target="_self" /></form>'."\n";
3677: if (scalar(%$fullname) eq 0) {
3678: my $colspan=3+scalar(@parts);
3679: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3680: my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
3681: $result='<span class="LC_warning">'.
3682: &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
3683: $section_display, $stu_status).
3684: '</span>';
3685: }
3686: return $result;
3687: }
3688:
3689: #--- call by previous routine to display each student
3690: sub viewstudentgrade {
3691: my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
3692: my ($uname,$udom) = split(/:/,$student);
3693: my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
3694: my %aggregates = ();
3695: my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
3696: '<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
3697: "\n".$ctr.' </td><td> '.
3698: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
3699: '\');" target="_self">'.$fullname.'</a> '.
3700: '<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
3701: $student=~s/:/_/; # colon doen't work in javascript for names
3702: foreach my $apart (@$parts) {
3703: my ($part,$type) = &split_part_type($apart);
3704: my $score=$record{"resource.$part.$type"};
3705: $result.='<td align="center">';
3706: my ($aggtries,$totaltries);
3707: unless (exists($aggregates{$part})) {
3708: $totaltries = $record{'resource.'.$part.'.tries'};
3709:
3710: $aggtries = $totaltries;
3711: if ($$last_resets{$part}) {
3712: $aggtries = &get_num_tries(\%record,$$last_resets{$part},
3713: $part);
3714: }
3715: $result.='<input type="hidden" name="'.
3716: 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
3717: $result.='<input type="hidden" name="'.
3718: 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
3719: $aggregates{$part} = 1;
3720: }
3721: if ($type eq 'awarded') {
3722: my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
3723: $result.='<input type="hidden" name="'.
3724: 'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
3725: $result.='<input type="text" name="'.
3726: 'GD_'.$student.'_'.$part.'_awarded" '.
3727: 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
3728: '\')" value="'.$pts.'" size="4" /></td>'."\n";
3729: } elsif ($type eq 'solved') {
3730: my ($status,$foo)=split(/_/,$score,2);
3731: $status = 'nothing' if ($status eq '');
3732: $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
3733: $part.'_solved_s" value="'.$status.'" />'."\n";
3734: $result.=' <select name="'.
3735: 'GD_'.$student.'_'.$part.'_solved" '.
3736: 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
3737: $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>'
3738: : '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
3739: $result.='<option value="reset status">'.&mt('reset status').'</option>';
3740: $result.="</select> </td>\n";
3741: } else {
3742: $result.='<input type="hidden" name="'.
3743: 'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
3744: "\n";
3745: $result.='<input type="text" name="'.
3746: 'GD_'.$student.'_'.$part.'_'.$type.'" '.
3747: 'value="'.$score.'" size="4" /></td>'."\n";
3748: }
3749: }
3750: $result.=&Apache::loncommon::end_data_table_row();
3751: return $result;
3752: }
3753:
3754: #--- change scores for all the students in a section/class
3755: # record does not get update if unchanged
3756: sub editgrades {
3757: my ($request,$symb) = @_;
3758:
3759: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3760: my $title='<h2>'.&mt('Current Grade Status').'</h2>';
3761: $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
3762:
3763: my $result= &Apache::loncommon::start_data_table().
3764: &Apache::loncommon::start_data_table_header_row().
3765: '<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
3766: '<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
3767: my %scoreptr = (
3768: 'correct' =>'correct_by_override',
3769: 'incorrect'=>'incorrect_by_override',
3770: 'excused' =>'excused',
3771: 'ungraded' =>'ungraded_attempted',
3772: 'credited' =>'credit_attempted',
3773: 'nothing' => '',
3774: );
3775: my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
3776:
3777: my (@partid);
3778: my %weight = ();
3779: my %columns = ();
3780: my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
3781:
3782: my $partserror;
3783: my (@parts) = sort(&getpartlist($symb,\$partserror));
3784: if ($partserror) {
3785: return &navmap_errormsg();
3786: }
3787: my $header;
3788: while ($ctr < $env{'form.totalparts'}) {
3789: my $partid = $env{'form.partid_'.$ctr};
3790: push(@partid,$partid);
3791: $weight{$partid} = $env{'form.weight_'.$partid};
3792: $ctr++;
3793: }
3794: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3795: foreach my $partid (@partid) {
3796: $header .= '<th align="center">'.&mt('Old Score').'</th>'.
3797: '<th align="center">'.&mt('New Score').'</th>';
3798: $columns{$partid}=2;
3799: foreach my $stores (@parts) {
3800: my ($part,$type) = &split_part_type($stores);
3801: if ($part !~ m/^\Q$partid\E/) { next;}
3802: if ($type eq 'awarded' || $type eq 'solved') { next; }
3803: my $display=&Apache::lonnet::metadata($url,$stores.'.display');
3804: $display =~ s/\[Part: \Q$part\E\]//;
3805: my $narrowtext = &mt('Tries');
3806: $display =~ s/Number of Attempts/$narrowtext/;
3807: $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
3808: '<th align="center">'.&mt('New').' '.$display.'</th>';
3809: $columns{$partid}+=2;
3810: }
3811: }
3812: foreach my $partid (@partid) {
3813: my $display_part=&get_display_part($partid,$symb);
3814: $result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
3815: &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
3816: '</th>';
3817:
3818: }
3819: $result .= &Apache::loncommon::end_data_table_header_row().
3820: &Apache::loncommon::start_data_table_header_row().
3821: $header.
3822: &Apache::loncommon::end_data_table_header_row();
3823: my @noupdate;
3824: my ($updateCtr,$noupdateCtr) = (1,1);
3825: for ($i=0; $i<$env{'form.total'}; $i++) {
3826: my $line;
3827: my $user = $env{'form.ctr'.$i};
3828: my ($uname,$udom)=split(/:/,$user);
3829: my %newrecord;
3830: my $updateflag = 0;
3831: $line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
3832: my $usec=$classlist->{"$uname:$udom"}[5];
3833: if (!&canmodify($usec)) {
3834: my $numcols=scalar(@partid)*4+2;
3835: push(@noupdate,
3836: $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
3837: &mt('Not allowed to modify student')."</span></td></tr>");
3838: next;
3839: }
3840: my %aggregate = ();
3841: my $aggregateflag = 0;
3842: $user=~s/:/_/; # colon doen't work in javascript for names
3843: foreach (@partid) {
3844: my $old_aw = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
3845: my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
3846: my $old_part = $old_aw eq '' ? '' : $old_part_pcr;
3847: my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
3848: my $awarded = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
3849: my $pcr = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
3850: my $partial = $awarded eq '' ? '' : $pcr;
3851: my $score;
3852: if ($partial eq '') {
3853: $score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
3854: } elsif ($partial > 0) {
3855: $score = 'correct_by_override';
3856: } elsif ($partial == 0) {
3857: $score = 'incorrect_by_override';
3858: }
3859: my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
3860: $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
3861:
3862: $newrecord{'resource.'.$_.'.regrader'}=
3863: "$env{'user.name'}:$env{'user.domain'}";
3864: if ($dropMenu eq 'reset status' &&
3865: $old_score ne '') { # ignore if no previous attempts => nothing to reset
3866: $newrecord{'resource.'.$_.'.tries'} = '';
3867: $newrecord{'resource.'.$_.'.solved'} = '';
3868: $newrecord{'resource.'.$_.'.award'} = '';
3869: $newrecord{'resource.'.$_.'.awarded'} = '';
3870: $updateflag = 1;
3871: if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
3872: my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
3873: my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
3874: my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
3875: &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
3876: $aggregateflag = 1;
3877: }
3878: } elsif (!($old_part eq $partial && $old_score eq $score)) {
3879: $updateflag = 1;
3880: $newrecord{'resource.'.$_.'.awarded'} = $partial if $partial ne '';
3881: $newrecord{'resource.'.$_.'.solved'} = $score;
3882: $rec_update++;
3883: }
3884:
3885: $line .= '<td align="center">'.$old_aw.' </td>'.
3886: '<td align="center">'.$awarded.
3887: ($score eq 'excused' ? $score : '').' </td>';
3888:
3889:
3890: my $partid=$_;
3891: foreach my $stores (@parts) {
3892: my ($part,$type) = &split_part_type($stores);
3893: if ($part !~ m/^\Q$partid\E/) { next;}
3894: if ($type eq 'awarded' || $type eq 'solved') { next; }
3895: my $old_aw = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
3896: my $awarded = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
3897: if ($awarded ne '' && $awarded ne $old_aw) {
3898: $newrecord{'resource.'.$part.'.'.$type}= $awarded;
3899: $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
3900: $updateflag=1;
3901: }
3902: $line .= '<td align="center">'.$old_aw.' </td>'.
3903: '<td align="center">'.$awarded.' </td>';
3904: }
3905: }
3906: $line.="\n";
3907:
3908: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3909: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3910:
3911: if ($updateflag) {
3912: $count++;
3913: &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
3914: $udom,$uname);
3915:
3916: if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
3917: $cnum,$udom,$uname)) {
3918: # need to figure out if should be in queue.
3919: my %record =
3920: &Apache::lonnet::restore($symb,$env{'request.course.id'},
3921: $udom,$uname);
3922: my $all_graded = 1;
3923: my $none_graded = 1;
3924: foreach my $part (@parts) {
3925: if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
3926: $all_graded = 0;
3927: } else {
3928: $none_graded = 0;
3929: }
3930: }
3931:
3932: if ($all_graded || $none_graded) {
3933: &Apache::bridgetask::remove_from_queue('gradingqueue',
3934: $symb,$cdom,$cnum,
3935: $udom,$uname);
3936: }
3937: }
3938:
3939: $result.=&Apache::loncommon::start_data_table_row().
3940: '<td align="right"> '.$updateCtr.' </td>'.$line.
3941: &Apache::loncommon::end_data_table_row();
3942: $updateCtr++;
3943: } else {
3944: push(@noupdate,
3945: '<td align="right"> '.$noupdateCtr.' </td>'.$line);
3946: $noupdateCtr++;
3947: }
3948: if ($aggregateflag) {
3949: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
3950: $cdom,$cnum);
3951: }
3952: }
3953: if (@noupdate) {
3954: # my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
3955: my $numcols=scalar(@partid)*4+2;
3956: $result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
3957: '<td align="center" colspan="'.$numcols.'">'.
3958: &mt('No Changes Occurred For the Students Below').
3959: '</td>'.
3960: &Apache::loncommon::end_data_table_row();
3961: foreach my $line (@noupdate) {
3962: $result.=
3963: &Apache::loncommon::start_data_table_row().
3964: $line.
3965: &Apache::loncommon::end_data_table_row();
3966: }
3967: }
3968: $result .= &Apache::loncommon::end_data_table();
3969: my $msg = '<p><b>'.
3970: &mt('Number of records updated = [_1] for [quant,_2,student].',
3971: $rec_update,$count).'</b><br />'.
3972: '<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
3973: '</b></p>';
3974: return $title.$msg.$result;
3975: }
3976:
3977: sub split_part_type {
3978: my ($partstr) = @_;
3979: my ($temp,@allparts)=split(/_/,$partstr);
3980: my $type=pop(@allparts);
3981: my $part=join('_',@allparts);
3982: return ($part,$type);
3983: }
3984:
3985: #------------- end of section for handling grading by section/class ---------
3986: #
3987: #----------------------------------------------------------------------------
3988:
3989:
3990: #----------------------------------------------------------------------------
3991: #
3992: #-------------------------- Next few routines handles grading by csv upload
3993: #
3994: #--- Javascript to handle csv upload
3995: sub csvupload_javascript_reverse_associate {
3996: my $error1=&mt('You need to specify the username or the student/employee ID');
3997: my $error2=&mt('You need to specify at least one grading field');
3998: return(<<ENDPICK);
3999: function verify(vf) {
4000: var foundsomething=0;
4001: var founduname=0;
4002: var foundID=0;
4003: for (i=0;i<=vf.nfields.value;i++) {
4004: tw=eval('vf.f'+i+'.selectedIndex');
4005: if (i==0 && tw!=0) { foundID=1; }
4006: if (i==1 && tw!=0) { founduname=1; }
4007: if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
4008: }
4009: if (founduname==0 && foundID==0) {
4010: alert('$error1');
4011: return;
4012: }
4013: if (foundsomething==0) {
4014: alert('$error2');
4015: return;
4016: }
4017: vf.submit();
4018: }
4019: function flip(vf,tf) {
4020: var nw=eval('vf.f'+tf+'.selectedIndex');
4021: var i;
4022: for (i=0;i<=vf.nfields.value;i++) {
4023: //can not pick the same destination field for both name and domain
4024: if (((i ==0)||(i ==1)) &&
4025: ((tf==0)||(tf==1)) &&
4026: (i!=tf) &&
4027: (eval('vf.f'+i+'.selectedIndex')==nw)) {
4028: eval('vf.f'+i+'.selectedIndex=0;')
4029: }
4030: }
4031: }
4032: ENDPICK
4033: }
4034:
4035: sub csvupload_javascript_forward_associate {
4036: my $error1=&mt('You need to specify the username or the student/employee ID');
4037: my $error2=&mt('You need to specify at least one grading field');
4038: return(<<ENDPICK);
4039: function verify(vf) {
4040: var foundsomething=0;
4041: var founduname=0;
4042: var foundID=0;
4043: for (i=0;i<=vf.nfields.value;i++) {
4044: tw=eval('vf.f'+i+'.selectedIndex');
4045: if (tw==1) { foundID=1; }
4046: if (tw==2) { founduname=1; }
4047: if (tw>3) { foundsomething=1; }
4048: }
4049: if (founduname==0 && foundID==0) {
4050: alert('$error1');
4051: return;
4052: }
4053: if (foundsomething==0) {
4054: alert('$error2');
4055: return;
4056: }
4057: vf.submit();
4058: }
4059: function flip(vf,tf) {
4060: var nw=eval('vf.f'+tf+'.selectedIndex');
4061: var i;
4062: //can not pick the same destination field twice
4063: for (i=0;i<=vf.nfields.value;i++) {
4064: if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
4065: eval('vf.f'+i+'.selectedIndex=0;')
4066: }
4067: }
4068: }
4069: ENDPICK
4070: }
4071:
4072: sub csvuploadmap_header {
4073: my ($request,$symb,$datatoken,$distotal)= @_;
4074: my $javascript;
4075: if ($env{'form.upfile_associate'} eq 'reverse') {
4076: $javascript=&csvupload_javascript_reverse_associate();
4077: } else {
4078: $javascript=&csvupload_javascript_forward_associate();
4079: }
4080:
4081: $symb = &Apache::lonenc::check_encrypt($symb);
4082: $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
4083: &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
4084: &mt('Associate entries from the uploaded file with as many fields as you can.'));
4085: my $reverse=&mt("Reverse Association");
4086: $request->print(<<ENDPICK);
4087: <br />
4088: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
4089: <input type="hidden" name="associate" value="" />
4090: <input type="hidden" name="phase" value="three" />
4091: <input type="hidden" name="datatoken" value="$datatoken" />
4092: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
4093: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
4094: <input type="hidden" name="upfile_associate"
4095: value="$env{'form.upfile_associate'}" />
4096: <input type="hidden" name="symb" value="$symb" />
4097: <input type="hidden" name="command" value="csvuploadoptions" />
4098: <hr />
4099: ENDPICK
4100: $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
4101: return '';
4102:
4103: }
4104:
4105: sub csvupload_fields {
4106: my ($symb,$errorref) = @_;
4107: my (@parts) = &getpartlist($symb,$errorref);
4108: if (ref($errorref)) {
4109: if ($$errorref) {
4110: return;
4111: }
4112: }
4113:
4114: my @fields=(['ID','Student/Employee ID'],
4115: ['username','Student Username'],
4116: ['domain','Student Domain']);
4117: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
4118: foreach my $part (sort(@parts)) {
4119: my @datum;
4120: my $display=&Apache::lonnet::metadata($url,$part.'.display');
4121: my $name=$part;
4122: if (!$display) { $display = $name; }
4123: @datum=($name,$display);
4124: if ($name=~/^stores_(.*)_awarded/) {
4125: push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
4126: }
4127: push(@fields,\@datum);
4128: }
4129: return (@fields);
4130: }
4131:
4132: sub csvuploadmap_footer {
4133: my ($request,$i,$keyfields) =@_;
4134: $request->print(<<ENDPICK);
4135: </table>
4136: <input type="hidden" name="nfields" value="$i" />
4137: <input type="hidden" name="keyfields" value="$keyfields" />
4138: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
4139: </form>
4140: ENDPICK
4141: }
4142:
4143: sub checkforfile_js {
4144: my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
4145: my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
4146: function checkUpload(formname) {
4147: if (formname.upfile.value == "") {
4148: alert("$alertmsg");
4149: return false;
4150: }
4151: formname.submit();
4152: }
4153: CSVFORMJS
4154: return $result;
4155: }
4156:
4157: sub upcsvScores_form {
4158: my ($request,$symb) = @_;
4159: if (!$symb) {return '';}
4160: my $result=&checkforfile_js();
4161: $result.=&Apache::loncommon::start_data_table().
4162: &Apache::loncommon::start_data_table_header_row().
4163: '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
4164: &Apache::loncommon::end_data_table_header_row().
4165: &Apache::loncommon::start_data_table_row().'<td>';
4166: my $upload=&mt("Upload Scores");
4167: my $upfile_select=&Apache::loncommon::upfile_select_html();
4168: my $ignore=&mt('Ignore First Line');
4169: $symb = &Apache::lonenc::check_encrypt($symb);
4170: $result.=<<ENDUPFORM;
4171: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
4172: <input type="hidden" name="symb" value="$symb" />
4173: <input type="hidden" name="command" value="csvuploadmap" />
4174: $upfile_select
4175: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
4176: </form>
4177: ENDUPFORM
4178: $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
4179: &mt("How do I create a CSV file from a spreadsheet")).
4180: '</td>'.
4181: &Apache::loncommon::end_data_table_row().
4182: &Apache::loncommon::end_data_table();
4183: return $result;
4184: }
4185:
4186:
4187: sub csvuploadmap {
4188: my ($request,$symb)= @_;
4189: if (!$symb) {return '';}
4190:
4191: my $datatoken;
4192: if (!$env{'form.datatoken'}) {
4193: $datatoken=&Apache::loncommon::upfile_store($request);
4194: } else {
4195: $datatoken=$env{'form.datatoken'};
4196: &Apache::loncommon::load_tmp_file($request);
4197: }
4198: my @records=&Apache::loncommon::upfile_record_sep();
4199: &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
4200: my ($i,$keyfields);
4201: if (@records) {
4202: my $fieldserror;
4203: my @fields=&csvupload_fields($symb,\$fieldserror);
4204: if ($fieldserror) {
4205: $request->print(&navmap_errormsg());
4206: return;
4207: }
4208: if ($env{'form.upfile_associate'} eq 'reverse') {
4209: &Apache::loncommon::csv_print_samples($request,\@records);
4210: $i=&Apache::loncommon::csv_print_select_table($request,\@records,
4211: \@fields);
4212: foreach (@fields) { $keyfields.=$_->[0].','; }
4213: chop($keyfields);
4214: } else {
4215: unshift(@fields,['none','']);
4216: $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
4217: \@fields);
4218: foreach my $rec (@records) {
4219: my %temp = &Apache::loncommon::record_sep($rec);
4220: if (%temp) {
4221: $keyfields=join(',',sort(keys(%temp)));
4222: last;
4223: }
4224: }
4225: }
4226: }
4227: &csvuploadmap_footer($request,$i,$keyfields);
4228:
4229: return '';
4230: }
4231:
4232: sub csvuploadoptions {
4233: my ($request,$symb)= @_;
4234: my $overwrite=&mt('Overwrite any existing score');
4235: $request->print(<<ENDPICK);
4236: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
4237: <input type="hidden" name="command" value="csvuploadassign" />
4238: <p>
4239: <label>
4240: <input type="checkbox" name="overwite_scores" checked="checked" />
4241: $overwrite
4242: </label>
4243: </p>
4244: ENDPICK
4245: my %fields=&get_fields();
4246: if (!defined($fields{'domain'})) {
4247: my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
4248: $request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
4249: }
4250: foreach my $key (sort(keys(%env))) {
4251: if ($key !~ /^form\.(.*)$/) { next; }
4252: my $cleankey=$1;
4253: if ($cleankey eq 'command') { next; }
4254: $request->print('<input type="hidden" name="'.$cleankey.
4255: '" value="'.$env{$key}.'" />'."\n");
4256: }
4257: # FIXME do a check for any duplicated user ids...
4258: # FIXME do a check for any invalid user ids?...
4259: $request->print('<input type="submit" value="Assign Grades" /><br />
4260: <hr /></form>'."\n");
4261: return '';
4262: }
4263:
4264: sub get_fields {
4265: my %fields;
4266: my @keyfields = split(/\,/,$env{'form.keyfields'});
4267: for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
4268: if ($env{'form.upfile_associate'} eq 'reverse') {
4269: if ($env{'form.f'.$i} ne 'none') {
4270: $fields{$keyfields[$i]}=$env{'form.f'.$i};
4271: }
4272: } else {
4273: if ($env{'form.f'.$i} ne 'none') {
4274: $fields{$env{'form.f'.$i}}=$keyfields[$i];
4275: }
4276: }
4277: }
4278: return %fields;
4279: }
4280:
4281: sub csvuploadassign {
4282: my ($request,$symb)= @_;
4283: if (!$symb) {return '';}
4284: my $error_msg = '';
4285: &Apache::loncommon::load_tmp_file($request);
4286: my @gradedata = &Apache::loncommon::upfile_record_sep();
4287: my %fields=&get_fields();
4288: my $courseid=$env{'request.course.id'};
4289: my ($classlist) = &getclasslist('all',0);
4290: my @notallowed;
4291: my @skipped;
4292: my @warnings;
4293: my $countdone=0;
4294: foreach my $grade (@gradedata) {
4295: my %entries=&Apache::loncommon::record_sep($grade);
4296: my $domain;
4297: if ($entries{$fields{'domain'}}) {
4298: $domain=$entries{$fields{'domain'}};
4299: } else {
4300: $domain=$env{'form.default_domain'};
4301: }
4302: $domain=~s/\s//g;
4303: my $username=$entries{$fields{'username'}};
4304: $username=~s/\s//g;
4305: if (!$username) {
4306: my $id=$entries{$fields{'ID'}};
4307: $id=~s/\s//g;
4308: my %ids=&Apache::lonnet::idget($domain,$id);
4309: $username=$ids{$id};
4310: }
4311: if (!exists($$classlist{"$username:$domain"})) {
4312: my $id=$entries{$fields{'ID'}};
4313: $id=~s/\s//g;
4314: if ($id) {
4315: push(@skipped,"$id:$domain");
4316: } else {
4317: push(@skipped,"$username:$domain");
4318: }
4319: next;
4320: }
4321: my $usec=$classlist->{"$username:$domain"}[5];
4322: if (!&canmodify($usec)) {
4323: push(@notallowed,"$username:$domain");
4324: next;
4325: }
4326: my %points;
4327: my %grades;
4328: foreach my $dest (keys(%fields)) {
4329: if ($dest eq 'ID' || $dest eq 'username' ||
4330: $dest eq 'domain') { next; }
4331: if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
4332: if ($dest=~/stores_(.*)_points/) {
4333: my $part=$1;
4334: my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
4335: $symb,$domain,$username);
4336: if ($wgt) {
4337: $entries{$fields{$dest}}=~s/\s//g;
4338: my $pcr=$entries{$fields{$dest}} / $wgt;
4339: my $award=($pcr == 0) ? 'incorrect_by_override'
4340: : 'correct_by_override';
4341: if ($pcr>1) {
4342: push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
4343: }
4344: $grades{"resource.$part.awarded"}=$pcr;
4345: $grades{"resource.$part.solved"}=$award;
4346: $points{$part}=1;
4347: } else {
4348: $error_msg = "<br />" .
4349: &mt("Some point values were assigned"
4350: ." for problems with a weight "
4351: ."of zero. These values were "
4352: ."ignored.");
4353: }
4354: } else {
4355: if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
4356: if ($dest=~/stores_(.*)_solved/) { if ($points{$1}) {next;} }
4357: my $store_key=$dest;
4358: $store_key=~s/^stores/resource/;
4359: $store_key=~s/_/\./g;
4360: $grades{$store_key}=$entries{$fields{$dest}};
4361: }
4362: }
4363: if (! %grades) {
4364: push(@skipped,&mt("[_1]: no data to save","$username:$domain"));
4365: } else {
4366: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
4367: my $result=&Apache::lonnet::cstore(\%grades,$symb,
4368: $env{'request.course.id'},
4369: $domain,$username);
4370: if ($result eq 'ok') {
4371: # Successfully stored
4372: $request->print('.');
4373: # Remove from grading queue
4374: &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
4375: $env{'course.'.$env{'request.course.id'}.'.domain'},
4376: $env{'course.'.$env{'request.course.id'}.'.num'},
4377: $domain,$username);
4378: $countdone++;
4379: } else {
4380: $request->print("<p><span class=\"LC_error\">".
4381: &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
4382: "$username:$domain",$result)."</span></p>");
4383: }
4384: $request->rflush();
4385: }
4386: }
4387: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
4388: if (@warnings) {
4389: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
4390: $request->print(join(', ',@warnings));
4391: }
4392: if (@skipped) {
4393: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
4394: $request->print(join(', ',@skipped));
4395: }
4396: if (@notallowed) {
4397: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
4398: $request->print(join(', ',@notallowed));
4399: }
4400: $request->print("<br />\n");
4401: return $error_msg;
4402: }
4403: #------------- end of section for handling csv file upload ---------
4404: #
4405: #-------------------------------------------------------------------
4406: #
4407: #-------------- Next few routines handle grading by page/sequence
4408: #
4409: #--- Select a page/sequence and a student to grade
4410: sub pickStudentPage {
4411: my ($request,$symb) = @_;
4412:
4413: my $alertmsg = &mt('Please select the student you wish to grade.');
4414: $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
4415:
4416: function checkPickOne(formname) {
4417: if (radioSelection(formname.student) == null) {
4418: alert("$alertmsg");
4419: return;
4420: }
4421: ptr = pullDownSelection(formname.selectpage);
4422: formname.page.value = formname["page"+ptr].value;
4423: formname.title.value = formname["title"+ptr].value;
4424: formname.submit();
4425: }
4426:
4427: LISTJAVASCRIPT
4428: &commonJSfunctions($request);
4429:
4430: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4431: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4432: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4433:
4434: my $result='<h3><span class="LC_info"> '.
4435: &mt('Manual Grading by Page or Sequence').'</span></h3>';
4436:
4437: $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
4438: my $map_error;
4439: my ($titles,$symbx) = &getSymbMap($map_error);
4440: if ($map_error) {
4441: $request->print(&navmap_errormsg());
4442: return;
4443: }
4444: my ($curpage) =&Apache::lonnet::decode_symb($symb);
4445: # my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb);
4446: # my $type=($curpage =~ /\.(page|sequence)/);
4447: my $select = '<select name="selectpage">'."\n";
4448: my $ctr=0;
4449: foreach (@$titles) {
4450: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4451: $select.='<option value="'.$ctr.'" '.
4452: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
4453: '>'.$showtitle.'</option>'."\n";
4454: $ctr++;
4455: }
4456: $select.= '</select>';
4457: $result.=' <b>'.&mt('Problems from').':</b> '.$select."<br />\n";
4458:
4459: $ctr=0;
4460: foreach (@$titles) {
4461: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4462: $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
4463: $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
4464: $ctr++;
4465: }
4466: $result.='<input type="hidden" name="page" />'."\n".
4467: '<input type="hidden" name="title" />'."\n";
4468:
4469: my $options =
4470: '<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
4471: '<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
4472: $result.=' <b>'.&mt('View Problem Text').': </b>'.$options;
4473:
4474: $options =
4475: '<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
4476: '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
4477: '<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
4478: $result.=' <b>'.&mt('Submissions').': </b>'.$options;
4479:
4480: $result.=&build_section_inputs();
4481: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
4482: $result.='<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
4483: '<input type="hidden" name="command" value="displayPage" />'."\n".
4484: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."<br />\n";
4485:
4486: $result.=' <b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
4487:
4488: $result.=' <input type="button" '.
4489: 'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' →" /><br />'."\n";
4490:
4491: $request->print($result);
4492:
4493: my $studentTable.=' <b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
4494: &Apache::loncommon::start_data_table().
4495: &Apache::loncommon::start_data_table_header_row().
4496: '<th align="right"> '.&mt('No.').'</th>'.
4497: '<th>'.&nameUserString('header').'</th>'.
4498: '<th align="right"> '.&mt('No.').'</th>'.
4499: '<th>'.&nameUserString('header').'</th>'.
4500: &Apache::loncommon::end_data_table_header_row();
4501:
4502: my (undef,undef,$fullname) = &getclasslist($getsec,'1');
4503: my $ptr = 1;
4504: foreach my $student (sort
4505: {
4506: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
4507: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
4508: }
4509: return $a cmp $b;
4510: } (keys(%$fullname))) {
4511: my ($uname,$udom) = split(/:/,$student);
4512: $studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
4513: : '</td>');
4514: $studentTable.='<td align="right">'.$ptr.' </td>';
4515: $studentTable.='<td> <label><input type="radio" name="student" value="'.$student.'" /> '
4516: .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
4517: $studentTable.=
4518: ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row()
4519: : '');
4520: $ptr++;
4521: }
4522: if ($ptr%2 == 0) {
4523: $studentTable.='</td><td> </td><td> </td>'.
4524: &Apache::loncommon::end_data_table_row();
4525: }
4526: $studentTable.=&Apache::loncommon::end_data_table()."\n";
4527: $studentTable.='<input type="button" '.
4528: 'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' →" /></form>'."\n";
4529:
4530: $request->print($studentTable);
4531:
4532: return '';
4533: }
4534:
4535: sub getSymbMap {
4536: my ($map_error) = @_;
4537: my $navmap = Apache::lonnavmaps::navmap->new();
4538: unless (ref($navmap)) {
4539: if (ref($map_error)) {
4540: $$map_error = 'navmap';
4541: }
4542: return;
4543: }
4544: my %symbx = ();
4545: my @titles = ();
4546: my $minder = 0;
4547:
4548: # Gather every sequence that has problems.
4549: my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
4550: 1,0,1);
4551: for my $sequence ($navmap->getById('0.0'), @sequences) {
4552: if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
4553: my $title = $minder.'.'.
4554: &HTML::Entities::encode($sequence->compTitle(),'"\'&');
4555: push(@titles, $title); # minder in case two titles are identical
4556: $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
4557: $minder++;
4558: }
4559: }
4560: return \@titles,\%symbx;
4561: }
4562:
4563: #
4564: #--- Displays a page/sequence w/wo problems, w/wo submissions
4565: sub displayPage {
4566: my ($request,$symb) = @_;
4567: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4568: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4569: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4570: my $pageTitle = $env{'form.page'};
4571: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
4572: my ($uname,$udom) = split(/:/,$env{'form.student'});
4573: my $usec=$classlist->{$env{'form.student'}}[5];
4574:
4575: #need to make sure we have the correct data for later EXT calls,
4576: #thus invalidate the cache
4577: &Apache::lonnet::devalidatecourseresdata(
4578: $env{'course.'.$env{'request.course.id'}.'.num'},
4579: $env{'course.'.$env{'request.course.id'}.'.domain'});
4580: &Apache::lonnet::clear_EXT_cache_status();
4581:
4582: if (!&canview($usec)) {
4583: $request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
4584: return;
4585: }
4586: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
4587: $result.='<h3> '.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
4588: '</h3>'."\n";
4589: $env{'form.CODE'} = uc($env{'form.CODE'});
4590: if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
4591: $result.='<h3> '.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
4592: } else {
4593: delete($env{'form.CODE'});
4594: }
4595: &sub_page_js($request);
4596: $request->print($result);
4597:
4598: my $navmap = Apache::lonnavmaps::navmap->new();
4599: unless (ref($navmap)) {
4600: $request->print(&navmap_errormsg());
4601: return;
4602: }
4603: my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
4604: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
4605: if (!$map) {
4606: $request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
4607: return;
4608: }
4609: my $iterator = $navmap->getIterator($map->map_start(),
4610: $map->map_finish());
4611:
4612: my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
4613: '<input type="hidden" name="command" value="gradeByPage" />'."\n".
4614: '<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
4615: '<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
4616: '<input type="hidden" name="page" value="'.$pageTitle.'" />'."\n".
4617: '<input type="hidden" name="title" value="'.$env{'form.title'}.'" />'."\n".
4618: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
4619: '<input type="hidden" name="overRideScore" value="no" />'."\n";
4620:
4621: if (defined($env{'form.CODE'})) {
4622: $studentTable.=
4623: '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
4624: }
4625: my $checkIcon = '<img alt="'.&mt('Check Mark').
4626: '" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
4627:
4628: $studentTable.=' <span class="LC_info">'.
4629: &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
4630: '</span>'."\n".
4631: &Apache::loncommon::start_data_table().
4632: &Apache::loncommon::start_data_table_header_row().
4633: '<th align="center"> Prob. </th>'.
4634: '<th> '.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
4635: &Apache::loncommon::end_data_table_header_row();
4636:
4637: &Apache::lonxml::clear_problem_counter();
4638: my ($depth,$question,$prob) = (1,1,1);
4639: $iterator->next(); # skip the first BEGIN_MAP
4640: my $curRes = $iterator->next(); # for "current resource"
4641: while ($depth > 0) {
4642: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
4643: if($curRes == $iterator->END_MAP) { $depth--; }
4644:
4645: if (ref($curRes) && $curRes->is_problem()) {
4646: my $parts = $curRes->parts();
4647: my $title = $curRes->compTitle();
4648: my $symbx = $curRes->symb();
4649: $studentTable.=
4650: &Apache::loncommon::start_data_table_row().
4651: '<td align="center" valign="top" >'.$prob.
4652: (scalar(@{$parts}) == 1 ? ''
4653: : '<br />('.&mt('[_1]parts',
4654: scalar(@{$parts}).' ').')'
4655: ).
4656: '</td>';
4657: $studentTable.='<td valign="top">';
4658: my %form = ('CODE' => $env{'form.CODE'},);
4659: if ($env{'form.vProb'} eq 'yes' ) {
4660: $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
4661: undef,'both',\%form);
4662: } else {
4663: my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
4664: $companswer =~ s|<form(.*?)>||g;
4665: $companswer =~ s|</form>||g;
4666: # while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
4667: # $companswer =~ s/$1/ /ms;
4668: # $request->print('match='.$1."<br />\n");
4669: # }
4670: # $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
4671: $studentTable.=' <b>'.$title.'</b> <br /> <b>'.&mt('Correct answer').':</b><br />'.$companswer;
4672: }
4673:
4674: my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
4675:
4676: if ($env{'form.lastSub'} eq 'datesub') {
4677: if ($record{'version'} eq '') {
4678: $studentTable.='<br /> <span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
4679: } else {
4680: my %responseType = ();
4681: foreach my $partid (@{$parts}) {
4682: my @responseIds =$curRes->responseIds($partid);
4683: my @responseType =$curRes->responseType($partid);
4684: my %responseIds;
4685: for (my $i=0;$i<=$#responseIds;$i++) {
4686: $responseIds{$responseIds[$i]}=$responseType[$i];
4687: }
4688: $responseType{$partid} = \%responseIds;
4689: }
4690: $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
4691:
4692: }
4693: } elsif ($env{'form.lastSub'} eq 'all') {
4694: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
4695: $studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
4696: $env{'request.course.id'},
4697: '','.submission');
4698:
4699: }
4700: if (&canmodify($usec)) {
4701: $studentTable.=&gradeBox_start();
4702: foreach my $partid (@{$parts}) {
4703: $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
4704: $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
4705: $question++;
4706: }
4707: $studentTable.=&gradeBox_end();
4708: $prob++;
4709: }
4710: $studentTable.='</td></tr>';
4711:
4712: }
4713: $curRes = $iterator->next();
4714: }
4715:
4716: $studentTable.=
4717: '</table>'."\n".
4718: '<input type="button" value="'.&mt('Save').'" '.
4719: 'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
4720: '</form>'."\n";
4721: $request->print($studentTable);
4722:
4723: return '';
4724: }
4725:
4726: sub displaySubByDates {
4727: my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
4728: my $isCODE=0;
4729: my $isTask = ($symb =~/\.task$/);
4730: if (exists($record->{'resource.CODE'})) { $isCODE=1; }
4731: my $studentTable=&Apache::loncommon::start_data_table().
4732: &Apache::loncommon::start_data_table_header_row().
4733: '<th>'.&mt('Date/Time').'</th>'.
4734: ($isCODE?'<th>'.&mt('CODE').'</th>':'').
4735: ($isTask?'<th>'.&mt('Version').'</th>':'').
4736: '<th>'.&mt('Submission').'</th>'.
4737: '<th>'.&mt('Status').'</th>'.
4738: &Apache::loncommon::end_data_table_header_row();
4739: my ($version);
4740: my %mark;
4741: my %orders;
4742: $mark{'correct_by_student'} = $checkIcon;
4743: if (!exists($$record{'1:timestamp'})) {
4744: return '<br /> <span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
4745: }
4746:
4747: my $interaction;
4748: my $no_increment = 1;
4749: my %lastrndseed;
4750: for ($version=1;$version<=$$record{'version'};$version++) {
4751: my $timestamp =
4752: &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
4753: if (exists($$record{$version.':resource.0.version'})) {
4754: $interaction = $$record{$version.':resource.0.version'};
4755: }
4756: if ($isTask && $env{'form.previousversion'}) {
4757: next unless ($interaction == $env{'form.previousversion'});
4758: }
4759: my $where = ($isTask ? "$version:resource.$interaction"
4760: : "$version:resource");
4761: $studentTable.=&Apache::loncommon::start_data_table_row().
4762: '<td>'.$timestamp.'</td>';
4763: if ($isCODE) {
4764: $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
4765: }
4766: if ($isTask) {
4767: $studentTable.='<td>'.$interaction.'</td>';
4768: }
4769: my @versionKeys = split(/\:/,$$record{$version.':keys'});
4770: my @displaySub = ();
4771: foreach my $partid (@{$parts}) {
4772: my ($hidden,$type);
4773: $type = $$record{$version.':resource.'.$partid.'.type'};
4774: if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
4775: $hidden = 1;
4776: }
4777: my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
4778: : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
4779:
4780: # next if ($$record{"$version:resource.$partid.solved"} eq '');
4781: my $display_part=&get_display_part($partid,$symb);
4782: foreach my $matchKey (@matchKey) {
4783: if (exists($$record{$version.':'.$matchKey}) &&
4784: $$record{$version.':'.$matchKey} ne '') {
4785:
4786: my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
4787: : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
4788: $displaySub[0].='<span class="LC_nobreak">';
4789: $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
4790: .' <span class="LC_internal_info">'
4791: .'('.&mt('Response ID: [_1]',$responseId).')'
4792: .'</span>'
4793: .' <b>';
4794: if ($hidden) {
4795: $displaySub[0].= &mt('Anonymous Survey').'</b>';
4796: } else {
4797: my ($trial,$rndseed,$newvariation);
4798: if ($type eq 'randomizetry') {
4799: $trial = $$record{"$where.$partid.tries"};
4800: $rndseed = $$record{"$where.$partid.rndseed"};
4801: }
4802: if ($$record{"$where.$partid.tries"} eq '') {
4803: $displaySub[0].=&mt('Trial not counted');
4804: } else {
4805: $displaySub[0].=&mt('Trial: [_1]',
4806: $$record{"$where.$partid.tries"});
4807: if ($rndseed || $lastrndseed{$partid}) {
4808: if ($rndseed ne $lastrndseed{$partid}) {
4809: $newvariation = ' ('.&mt('New variation this try').')';
4810: }
4811: }
4812: $lastrndseed{$partid} = $rndseed;
4813: }
4814: my $responseType=($isTask ? 'Task'
4815: : $responseType->{$partid}->{$responseId});
4816: if (!exists($orders{$partid})) { $orders{$partid}={}; }
4817: if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
4818: $orders{$partid}->{$responseId}=
4819: &get_order($partid,$responseId,$symb,$uname,$udom,
4820: $no_increment,$type,$trial,$rndseed);
4821: }
4822: $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
4823: $displaySub[0].=' '.
4824: &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
4825: }
4826: }
4827: }
4828: if (exists($$record{"$where.$partid.checkedin"})) {
4829: $displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
4830: $$record{"$where.$partid.checkedin"},
4831: $$record{"$where.$partid.checkedin.slot"}).
4832: '<br />';
4833: }
4834: if (exists $$record{"$where.$partid.award"}) {
4835: $displaySub[1].='<b>'.&mt('Part:').'</b> '.$display_part.' '.
4836: lc($$record{"$where.$partid.award"}).' '.
4837: $mark{$$record{"$where.$partid.solved"}}.
4838: '<br />';
4839: }
4840: if (exists $$record{"$where.$partid.regrader"}) {
4841: $displaySub[2].=$$record{"$where.$partid.regrader"}.
4842: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
4843: } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
4844: $displaySub[2].=
4845: $$record{"$version:resource.$partid.regrader"}.
4846: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
4847: }
4848: }
4849: # needed because old essay regrader has not parts info
4850: if (exists $$record{"$version:resource.regrader"}) {
4851: $displaySub[2].=$$record{"$version:resource.regrader"};
4852: }
4853: $studentTable.='<td>'.$displaySub[0].' </td><td>'.$displaySub[1];
4854: if ($displaySub[2]) {
4855: $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
4856: }
4857: $studentTable.=' </td>'.
4858: &Apache::loncommon::end_data_table_row();
4859: }
4860: $studentTable.=&Apache::loncommon::end_data_table();
4861: return $studentTable;
4862: }
4863:
4864: sub updateGradeByPage {
4865: my ($request,$symb) = @_;
4866:
4867: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4868: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4869: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4870: my $pageTitle = $env{'form.page'};
4871: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
4872: my ($uname,$udom) = split(/:/,$env{'form.student'});
4873: my $usec=$classlist->{$env{'form.student'}}[5];
4874: if (!&canmodify($usec)) {
4875: $request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
4876: return;
4877: }
4878: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
4879: $result.='<h3> '.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
4880: '</h3>'."\n";
4881:
4882: $request->print($result);
4883:
4884:
4885: my $navmap = Apache::lonnavmaps::navmap->new();
4886: unless (ref($navmap)) {
4887: $request->print(&navmap_errormsg());
4888: return;
4889: }
4890: my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
4891: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
4892: if (!$map) {
4893: $request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
4894: return;
4895: }
4896: my $iterator = $navmap->getIterator($map->map_start(),
4897: $map->map_finish());
4898:
4899: my $studentTable=
4900: &Apache::loncommon::start_data_table().
4901: &Apache::loncommon::start_data_table_header_row().
4902: '<th align="center"> '.&mt('Prob.').' </th>'.
4903: '<th> '.&mt('Title').' </th>'.
4904: '<th> '.&mt('Previous Score').' </th>'.
4905: '<th> '.&mt('New Score').' </th>'.
4906: &Apache::loncommon::end_data_table_header_row();
4907:
4908: $iterator->next(); # skip the first BEGIN_MAP
4909: my $curRes = $iterator->next(); # for "current resource"
4910: my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
4911: while ($depth > 0) {
4912: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
4913: if($curRes == $iterator->END_MAP) { $depth--; }
4914:
4915: if (ref($curRes) && $curRes->is_problem()) {
4916: my $parts = $curRes->parts();
4917: my $title = $curRes->compTitle();
4918: my $symbx = $curRes->symb();
4919: $studentTable.=
4920: &Apache::loncommon::start_data_table_row().
4921: '<td align="center" valign="top" >'.$prob.
4922: (scalar(@{$parts}) == 1 ? ''
4923: : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
4924: .')').'</td>';
4925: $studentTable.='<td valign="top"> <b>'.$title.'</b> </td>';
4926:
4927: my %newrecord=();
4928: my @displayPts=();
4929: my %aggregate = ();
4930: my $aggregateflag = 0;
4931: foreach my $partid (@{$parts}) {
4932: my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
4933: my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
4934:
4935: my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ?
4936: $env{'form.WGT'.$question.'_'.$partid} : 1;
4937: my $partial = $newpts/$wgt;
4938: my $score;
4939: if ($partial > 0) {
4940: $score = 'correct_by_override';
4941: } elsif ($newpts ne '') { #empty is taken as 0
4942: $score = 'incorrect_by_override';
4943: }
4944: my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
4945: if ($dropMenu eq 'excused') {
4946: $partial = '';
4947: $score = 'excused';
4948: } elsif ($dropMenu eq 'reset status'
4949: && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
4950: $newrecord{'resource.'.$partid.'.tries'} = 0;
4951: $newrecord{'resource.'.$partid.'.solved'} = '';
4952: $newrecord{'resource.'.$partid.'.award'} = '';
4953: $newrecord{'resource.'.$partid.'.awarded'} = 0;
4954: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
4955: $changeflag++;
4956: $newpts = '';
4957:
4958: my $aggtries = $env{'form.aggtries'.$question.'_'.$partid};
4959: my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
4960: my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
4961: if ($aggtries > 0) {
4962: &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
4963: $aggregateflag = 1;
4964: }
4965: }
4966: my $display_part=&get_display_part($partid,$curRes->symb());
4967: my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
4968: $displayPts[0].=' <b>'.&mt('Part').':</b> '.$display_part.' = '.
4969: (($oldstatus eq 'excused') ? 'excused' : $oldpts).
4970: ' <br />';
4971: $displayPts[1].=' <b>'.&mt('Part').':</b> '.$display_part.' = '.
4972: (($score eq 'excused') ? 'excused' : $newpts).
4973: ' <br />';
4974: $question++;
4975: next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
4976:
4977: $newrecord{'resource.'.$partid.'.awarded'} = $partial if $partial ne '';
4978: $newrecord{'resource.'.$partid.'.solved'} = $score if $score ne '';
4979: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
4980: if (scalar(keys(%newrecord)) > 0);
4981:
4982: $changeflag++;
4983: }
4984: if (scalar(keys(%newrecord)) > 0) {
4985: my %record =
4986: &Apache::lonnet::restore($symbx,$env{'request.course.id'},
4987: $udom,$uname);
4988:
4989: if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
4990: $newrecord{'resource.CODE'} = $env{'form.CODE'};
4991: } elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
4992: $newrecord{'resource.CODE'} = '';
4993: }
4994: &Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
4995: $udom,$uname);
4996: %record = &Apache::lonnet::restore($symbx,
4997: $env{'request.course.id'},
4998: $udom,$uname);
4999: &check_and_remove_from_queue($parts,\%record,undef,$symbx,
5000: $cdom,$cnum,$udom,$uname);
5001: }
5002:
5003: if ($aggregateflag) {
5004: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
5005: $env{'course.'.$env{'request.course.id'}.'.domain'},
5006: $env{'course.'.$env{'request.course.id'}.'.num'});
5007: }
5008:
5009: $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
5010: '<td valign="top">'.$displayPts[1].'</td>'.
5011: &Apache::loncommon::end_data_table_row();
5012:
5013: $prob++;
5014: }
5015: $curRes = $iterator->next();
5016: }
5017:
5018: $studentTable.=&Apache::loncommon::end_data_table();
5019: my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
5020: &mt('The scores were changed for [quant,_1,problem].',
5021: $changeflag));
5022: $request->print($grademsg.$studentTable);
5023:
5024: return '';
5025: }
5026:
5027: #-------- end of section for handling grading by page/sequence ---------
5028: #
5029: #-------------------------------------------------------------------
5030:
5031: #-------------------- Bubblesheet (Scantron) Grading -------------------
5032: #
5033: #------ start of section for handling grading by page/sequence ---------
5034:
5035: =pod
5036:
5037: =head1 Bubble sheet grading routines
5038:
5039: For this documentation:
5040:
5041: 'scanline' refers to the full line of characters
5042: from the file that we are parsing that represents one entire sheet
5043:
5044: 'bubble line' refers to the data
5045: representing the line of bubbles that are on the physical bubblesheet
5046:
5047:
5048: The overall process is that a scanned in bubblesheet data is uploaded
5049: into a course. When a user wants to grade, they select a
5050: sequence/folder of resources, a file of bubblesheet info, and pick
5051: one of the predefined configurations for what each scanline looks
5052: like.
5053:
5054: Next each scanline is checked for any errors of either 'missing
5055: bubbles' (it's an error because it may have been mis-scanned
5056: because too light bubbling), 'double bubble' (each bubble line should
5057: have no more that one letter picked), invalid or duplicated CODE,
5058: invalid student/employee ID
5059:
5060: If the CODE option is used that determines the randomization of the
5061: homework problems, either way the student/employee ID is looked up into a
5062: username:domain.
5063:
5064: During the validation phase the instructor can choose to skip scanlines.
5065:
5066: After the validation phase, there are now 3 bubblesheet files
5067:
5068: scantron_original_filename (unmodified original file)
5069: scantron_corrected_filename (file where the corrected information has replaced the original information)
5070: scantron_skipped_filename (contains the exact text of scanlines that where skipped)
5071:
5072: Also there is a separate hash nohist_scantrondata that contains extra
5073: correction information that isn't representable in the bubblesheet
5074: file (see &scantron_getfile() for more information)
5075:
5076: After all scanlines are either valid, marked as valid or skipped, then
5077: foreach line foreach problem in the picked sequence, an ssi request is
5078: made that simulates a user submitting their selected letter(s) against
5079: the homework problem.
5080:
5081: =over 4
5082:
5083:
5084:
5085: =item defaultFormData
5086:
5087: Returns html hidden inputs used to hold context/default values.
5088:
5089: Arguments:
5090: $symb - $symb of the current resource
5091:
5092: =cut
5093:
5094: sub defaultFormData {
5095: my ($symb)=@_;
5096: return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
5097: }
5098:
5099:
5100: =pod
5101:
5102: =item getSequenceDropDown
5103:
5104: Return html dropdown of possible sequences to grade
5105:
5106: Arguments:
5107: $symb - $symb of the current resource
5108: $map_error - ref to scalar which will container error if
5109: $navmap object is unavailable in &getSymbMap().
5110:
5111: =cut
5112:
5113: sub getSequenceDropDown {
5114: my ($symb,$map_error)=@_;
5115: my $result='<select name="selectpage">'."\n";
5116: my ($titles,$symbx) = &getSymbMap($map_error);
5117: if (ref($map_error)) {
5118: return if ($$map_error);
5119: }
5120: my ($curpage)=&Apache::lonnet::decode_symb($symb);
5121: my $ctr=0;
5122: foreach (@$titles) {
5123: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
5124: $result.='<option value="'.$$symbx{$_}.'" '.
5125: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
5126: '>'.$showtitle.'</option>'."\n";
5127: $ctr++;
5128: }
5129: $result.= '</select>';
5130: return $result;
5131: }
5132:
5133: my %bubble_lines_per_response; # no. bubble lines for each response.
5134: # key is zero-based index - 0, 1, 2 ...
5135:
5136: my %first_bubble_line; # First bubble line no. for each bubble.
5137:
5138: my %subdivided_bubble_lines; # no. bubble lines for optionresponse,
5139: # matchresponse or rankresponse, where
5140: # an individual response can have multiple
5141: # lines
5142:
5143: my %responsetype_per_response; # responsetype for each response
5144:
5145: # Save and restore the bubble lines array to the form env.
5146:
5147:
5148: sub save_bubble_lines {
5149: foreach my $line (keys(%bubble_lines_per_response)) {
5150: $env{"form.scantron.bubblelines.$line"} = $bubble_lines_per_response{$line};
5151: $env{"form.scantron.first_bubble_line.$line"} =
5152: $first_bubble_line{$line};
5153: $env{"form.scantron.sub_bubblelines.$line"} =
5154: $subdivided_bubble_lines{$line};
5155: $env{"form.scantron.responsetype.$line"} =
5156: $responsetype_per_response{$line};
5157: }
5158: }
5159:
5160:
5161: sub restore_bubble_lines {
5162: my $line = 0;
5163: %bubble_lines_per_response = ();
5164: while ($env{"form.scantron.bubblelines.$line"}) {
5165: my $value = $env{"form.scantron.bubblelines.$line"};
5166: $bubble_lines_per_response{$line} = $value;
5167: $first_bubble_line{$line} =
5168: $env{"form.scantron.first_bubble_line.$line"};
5169: $subdivided_bubble_lines{$line} =
5170: $env{"form.scantron.sub_bubblelines.$line"};
5171: $responsetype_per_response{$line} =
5172: $env{"form.scantron.responsetype.$line"};
5173: $line++;
5174: }
5175: }
5176:
5177: # Given the parsed scanline, get the response for
5178: # 'answer' number n:
5179:
5180: sub get_response_bubbles {
5181: my ($parsed_line, $response) = @_;
5182:
5183: my $bubble_line = $first_bubble_line{$response-1} +1;
5184: my $bubble_lines= $bubble_lines_per_response{$response-1};
5185:
5186: my $selected = "";
5187:
5188: for (my $bline = 0; $bline < $bubble_lines; $bline++) {
5189: $selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
5190: $bubble_line++;
5191: }
5192: return $selected;
5193: }
5194:
5195: =pod
5196:
5197: =item scantron_filenames
5198:
5199: Returns a list of the scantron files in the current course
5200:
5201: =cut
5202:
5203: sub scantron_filenames {
5204: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5205: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5206: my $getpropath = 1;
5207: my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
5208: $cname,$getpropath);
5209: my @possiblenames;
5210: if (ref($dirlist) eq 'ARRAY') {
5211: foreach my $filename (sort(@{$dirlist})) {
5212: ($filename)=split(/&/,$filename);
5213: if ($filename!~/^scantron_orig_/) { next ; }
5214: $filename=~s/^scantron_orig_//;
5215: push(@possiblenames,$filename);
5216: }
5217: }
5218: return @possiblenames;
5219: }
5220:
5221: =pod
5222:
5223: =item scantron_uploads
5224:
5225: Returns html drop-down list of scantron files in current course.
5226:
5227: Arguments:
5228: $file2grade - filename to set as selected in the dropdown
5229:
5230: =cut
5231:
5232: sub scantron_uploads {
5233: my ($file2grade) = @_;
5234: my $result= '<select name="scantron_selectfile">';
5235: $result.="<option></option>";
5236: foreach my $filename (sort(&scantron_filenames())) {
5237: $result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
5238: }
5239: $result.="</select>";
5240: return $result;
5241: }
5242:
5243: =pod
5244:
5245: =item scantron_scantab
5246:
5247: Returns html drop down of the scantron formats in the scantronformat.tab
5248: file.
5249:
5250: =cut
5251:
5252: sub scantron_scantab {
5253: my $result='<select name="scantron_format">'."\n";
5254: $result.='<option></option>'."\n";
5255: my @lines = &get_scantronformat_file();
5256: if (@lines > 0) {
5257: foreach my $line (@lines) {
5258: next if (($line =~ /^\#/) || ($line eq ''));
5259: my ($name,$descrip)=split(/:/,$line);
5260: $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
5261: }
5262: }
5263: $result.='</select>'."\n";
5264: return $result;
5265: }
5266:
5267: =pod
5268:
5269: =item get_scantronformat_file
5270:
5271: Returns an array containing lines from the scantron format file for
5272: the domain of the course.
5273:
5274: If a url for a custom.tab file is listed in domain's configuration.db,
5275: lines are from this file.
5276:
5277: Otherwise, if a default.tab has been published in RES space by the
5278: domainconfig user, lines are from this file.
5279:
5280: Otherwise, fall back to getting lines from the legacy file on the
5281: local server: /home/httpd/lonTabs/default_scantronformat.tab
5282:
5283: =cut
5284:
5285: sub get_scantronformat_file {
5286: my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
5287: my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
5288: my $gottab = 0;
5289: my @lines;
5290: if (ref($domconfig{'scantron'}) eq 'HASH') {
5291: if ($domconfig{'scantron'}{'scantronformat'} ne '') {
5292: my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
5293: if ($formatfile ne '-1') {
5294: @lines = split("\n",$formatfile,-1);
5295: $gottab = 1;
5296: }
5297: }
5298: }
5299: if (!$gottab) {
5300: my $confname = $cdom.'-domainconfig';
5301: my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
5302: my $formatfile = &Apache::lonnet::getfile($default);
5303: if ($formatfile ne '-1') {
5304: @lines = split("\n",$formatfile,-1);
5305: $gottab = 1;
5306: }
5307: }
5308: if (!$gottab) {
5309: my @domains = &Apache::lonnet::current_machine_domains();
5310: if (grep(/^\Q$cdom\E$/,@domains)) {
5311: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
5312: @lines = <$fh>;
5313: close($fh);
5314: } else {
5315: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
5316: @lines = <$fh>;
5317: close($fh);
5318: }
5319: }
5320: return @lines;
5321: }
5322:
5323: =pod
5324:
5325: =item scantron_CODElist
5326:
5327: Returns html drop down of the saved CODE lists from current course,
5328: generated from earlier printings.
5329:
5330: =cut
5331:
5332: sub scantron_CODElist {
5333: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5334: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5335: my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
5336: my $namechoice='<option></option>';
5337: foreach my $name (sort {uc($a) cmp uc($b)} @names) {
5338: if ($name =~ /^error: 2 /) { next; }
5339: if ($name =~ /^type\0/) { next; }
5340: $namechoice.='<option value="'.$name.'">'.$name.'</option>';
5341: }
5342: $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
5343: return $namechoice;
5344: }
5345:
5346: =pod
5347:
5348: =item scantron_CODEunique
5349:
5350: Returns the html for "Each CODE to be used once" radio.
5351:
5352: =cut
5353:
5354: sub scantron_CODEunique {
5355: my $result='<span class="LC_nobreak">
5356: <label><input type="radio" name="scantron_CODEunique"
5357: value="yes" checked="checked" />'.&mt('Yes').' </label>
5358: </span>
5359: <span class="LC_nobreak">
5360: <label><input type="radio" name="scantron_CODEunique"
5361: value="no" />'.&mt('No').' </label>
5362: </span>';
5363: return $result;
5364: }
5365:
5366: =pod
5367:
5368: =item scantron_selectphase
5369:
5370: Generates the initial screen to start the bubblesheet process.
5371: Allows for - starting a grading run.
5372: - downloading existing scan data (original, corrected
5373: or skipped info)
5374:
5375: - uploading new scan data
5376:
5377: Arguments:
5378: $r - The Apache request object
5379: $file2grade - name of the file that contain the scanned data to score
5380:
5381: =cut
5382:
5383: sub scantron_selectphase {
5384: my ($r,$file2grade,$symb) = @_;
5385: if (!$symb) {return '';}
5386: my $map_error;
5387: my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
5388: if ($map_error) {
5389: $r->print('<br />'.&navmap_errormsg().'<br />');
5390: return;
5391: }
5392: my $default_form_data=&defaultFormData($symb);
5393: my $file_selector=&scantron_uploads($file2grade);
5394: my $format_selector=&scantron_scantab();
5395: my $CODE_selector=&scantron_CODElist();
5396: my $CODE_unique=&scantron_CODEunique();
5397: my $result;
5398:
5399: $ssi_error = 0;
5400:
5401: if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
5402: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
5403:
5404: # Chunk of form to prompt for a scantron file upload.
5405:
5406: $r->print('
5407: <br />
5408: '.&Apache::loncommon::start_data_table('LC_scantron_action').'
5409: '.&Apache::loncommon::start_data_table_header_row().'
5410: <th>
5411: '.&mt('Specify a bubblesheet data file to upload.').'
5412: </th>
5413: '.&Apache::loncommon::end_data_table_header_row().'
5414: '.&Apache::loncommon::start_data_table_row().'
5415: <td>
5416: ');
5417: my $default_form_data=&defaultFormData($symb);
5418: my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
5419: my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
5420: $r->print(&Apache::lonhtmlcommon::scripttag('
5421: function checkUpload(formname) {
5422: if (formname.upfile.value == "") {
5423: alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
5424: return false;
5425: }
5426: formname.submit();
5427: }'));
5428: $r->print('
5429: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
5430: '.$default_form_data.'
5431: <input name="courseid" type="hidden" value="'.$cnum.'" />
5432: <input name="domainid" type="hidden" value="'.$cdom.'" />
5433: <input name="command" value="scantronupload_save" type="hidden" />
5434: '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
5435: <br />
5436: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
5437: </form>
5438: ');
5439:
5440: $r->print('
5441: </td>
5442: '.&Apache::loncommon::end_data_table_row().'
5443: '.&Apache::loncommon::end_data_table().'
5444: ');
5445: }
5446:
5447: # Chunk of form to prompt for a file to grade and how:
5448:
5449: $result.= '
5450: <br />
5451: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
5452: <input type="hidden" name="command" value="scantron_warning" />
5453: '.$default_form_data.'
5454: '.&Apache::loncommon::start_data_table('LC_scantron_action').'
5455: '.&Apache::loncommon::start_data_table_header_row().'
5456: <th colspan="2">
5457: '.&mt('Specify file and which Folder/Sequence to grade').'
5458: </th>
5459: '.&Apache::loncommon::end_data_table_header_row().'
5460: '.&Apache::loncommon::start_data_table_row().'
5461: <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
5462: '.&Apache::loncommon::end_data_table_row().'
5463: '.&Apache::loncommon::start_data_table_row().'
5464: <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
5465: '.&Apache::loncommon::end_data_table_row().'
5466: '.&Apache::loncommon::start_data_table_row().'
5467: <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
5468: '.&Apache::loncommon::end_data_table_row().'
5469: '.&Apache::loncommon::start_data_table_row().'
5470: <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
5471: '.&Apache::loncommon::end_data_table_row().'
5472: '.&Apache::loncommon::start_data_table_row().'
5473: <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
5474: '.&Apache::loncommon::end_data_table_row().'
5475: '.&Apache::loncommon::start_data_table_row().'
5476: <td> '.&mt('Options:').' </td>
5477: <td>
5478: <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
5479: <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
5480: <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
5481: </td>
5482: '.&Apache::loncommon::end_data_table_row().'
5483: '.&Apache::loncommon::start_data_table_row().'
5484: <td colspan="2">
5485: <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
5486: </td>
5487: '.&Apache::loncommon::end_data_table_row().'
5488: '.&Apache::loncommon::end_data_table().'
5489: </form>
5490: ';
5491:
5492: $r->print($result);
5493:
5494:
5495:
5496: # Chunk of the form that prompts to view a scoring office file,
5497: # corrected file, skipped records in a file.
5498:
5499: $r->print('
5500: <br />
5501: <form action="/adm/grades" name="scantron_download">
5502: '.$default_form_data.'
5503: <input type="hidden" name="command" value="scantron_download" />
5504: '.&Apache::loncommon::start_data_table('LC_scantron_action').'
5505: '.&Apache::loncommon::start_data_table_header_row().'
5506: <th>
5507: '.&mt('Download a scoring office file').'
5508: </th>
5509: '.&Apache::loncommon::end_data_table_header_row().'
5510: '.&Apache::loncommon::start_data_table_row().'
5511: <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).'
5512: <br />
5513: <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
5514: '.&Apache::loncommon::end_data_table_row().'
5515: '.&Apache::loncommon::end_data_table().'
5516: </form>
5517: <br />
5518: ');
5519:
5520: &Apache::lonpickcode::code_list($r,2);
5521:
5522: $r->print('<br /><form method="post" name="checkscantron">'.
5523: $default_form_data."\n".
5524: &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
5525: &Apache::loncommon::start_data_table_header_row()."\n".
5526: '<th colspan="2">
5527: '.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
5528: '</th>'."\n".
5529: &Apache::loncommon::end_data_table_header_row()."\n".
5530: &Apache::loncommon::start_data_table_row()."\n".
5531: '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
5532: '<td> '.$sequence_selector.' </td>'.
5533: &Apache::loncommon::end_data_table_row()."\n".
5534: &Apache::loncommon::start_data_table_row()."\n".
5535: '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
5536: '<td> '.$file_selector.' </td>'."\n".
5537: &Apache::loncommon::end_data_table_row()."\n".
5538: &Apache::loncommon::start_data_table_row()."\n".
5539: '<td> '.&mt('Format of data file:').' </td>'."\n".
5540: '<td> '.$format_selector.' </td>'."\n".
5541: &Apache::loncommon::end_data_table_row()."\n".
5542: &Apache::loncommon::start_data_table_row()."\n".
5543: '<td> '.&mt('Options').' </td>'."\n".
5544: '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
5545: &Apache::loncommon::end_data_table_row()."\n".
5546: &Apache::loncommon::start_data_table_row()."\n".
5547: '<td colspan="2">'."\n".
5548: '<input type="hidden" name="command" value="checksubmissions" />'."\n".
5549: '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
5550: '</td>'."\n".
5551: &Apache::loncommon::end_data_table_row()."\n".
5552: &Apache::loncommon::end_data_table()."\n".
5553: '</form><br />');
5554: return;
5555: }
5556:
5557: =pod
5558:
5559: =item get_scantron_config
5560:
5561: Parse and return the scantron configuration line selected as a
5562: hash of configuration file fields.
5563:
5564: Arguments:
5565: which - the name of the configuration to parse from the file.
5566:
5567:
5568: Returns:
5569: If the named configuration is not in the file, an empty
5570: hash is returned.
5571: a hash with the fields
5572: name - internal name for the this configuration setup
5573: description - text to display to operator that describes this config
5574: CODElocation - if 0 or the string 'none'
5575: - no CODE exists for this config
5576: if -1 || the string 'letter'
5577: - a CODE exists for this config and is
5578: a string of letters
5579: Unsupported value (but planned for future support)
5580: if a positive integer
5581: - The CODE exists as the first n items from
5582: the question section of the form
5583: if the string 'number'
5584: - The CODE exists for this config and is
5585: a string of numbers
5586: CODEstart - (only matter if a CODE exists) column in the line where
5587: the CODE starts
5588: CODElength - length of the CODE
5589: IDstart - column where the student/employee ID starts
5590: IDlength - length of the student/employee ID info
5591: Qstart - column where the information from the bubbled
5592: 'questions' start
5593: Qlength - number of columns comprising a single bubble line from
5594: the sheet. (usually either 1 or 10)
5595: Qon - either a single character representing the character used
5596: to signal a bubble was chosen in the positional setup, or
5597: the string 'letter' if the letter of the chosen bubble is
5598: in the final, or 'number' if a number representing the
5599: chosen bubble is in the file (1->A 0->J)
5600: Qoff - the character used to represent that a bubble was
5601: left blank
5602: PaperID - if the scanning process generates a unique number for each
5603: sheet scanned the column that this ID number starts in
5604: PaperIDlength - number of columns that comprise the unique ID number
5605: for the sheet of paper
5606: FirstName - column that the first name starts in
5607: FirstNameLength - number of columns that the first name spans
5608:
5609: LastName - column that the last name starts in
5610: LastNameLength - number of columns that the last name spans
5611: BubblesPerRow - number of bubbles available in each row used to
5612: bubble an answer. (If not specified, 10 assumed).
5613:
5614: =cut
5615:
5616: sub get_scantron_config {
5617: my ($which) = @_;
5618: my @lines = &get_scantronformat_file();
5619: my %config;
5620: #FIXME probably should move to XML it has already gotten a bit much now
5621: foreach my $line (@lines) {
5622: my ($name,$descrip)=split(/:/,$line);
5623: if ($name ne $which ) { next; }
5624: chomp($line);
5625: my @config=split(/:/,$line);
5626: $config{'name'}=$config[0];
5627: $config{'description'}=$config[1];
5628: $config{'CODElocation'}=$config[2];
5629: $config{'CODEstart'}=$config[3];
5630: $config{'CODElength'}=$config[4];
5631: $config{'IDstart'}=$config[5];
5632: $config{'IDlength'}=$config[6];
5633: $config{'Qstart'}=$config[7];
5634: $config{'Qlength'}=$config[8];
5635: $config{'Qoff'}=$config[9];
5636: $config{'Qon'}=$config[10];
5637: $config{'PaperID'}=$config[11];
5638: $config{'PaperIDlength'}=$config[12];
5639: $config{'FirstName'}=$config[13];
5640: $config{'FirstNamelength'}=$config[14];
5641: $config{'LastName'}=$config[15];
5642: $config{'LastNamelength'}=$config[16];
5643: $config{'BubblesPerRow'}=$config[17];
5644: last;
5645: }
5646: return %config;
5647: }
5648:
5649: =pod
5650:
5651: =item username_to_idmap
5652:
5653: creates a hash keyed by student/employee ID with values of the corresponding
5654: student username:domain.
5655:
5656: Arguments:
5657:
5658: $classlist - reference to the class list hash. This is a hash
5659: keyed by student name:domain whose elements are references
5660: to arrays containing various chunks of information
5661: about the student. (See loncoursedata for more info).
5662:
5663: Returns
5664: %idmap - the constructed hash
5665:
5666: =cut
5667:
5668: sub username_to_idmap {
5669: my ($classlist)= @_;
5670: my %idmap;
5671: foreach my $student (keys(%$classlist)) {
5672: $idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
5673: $student;
5674: }
5675: return %idmap;
5676: }
5677:
5678: =pod
5679:
5680: =item scantron_fixup_scanline
5681:
5682: Process a requested correction to a scanline.
5683:
5684: Arguments:
5685: $scantron_config - hash from &get_scantron_config()
5686: $scan_data - hash of correction information
5687: (see &scantron_getfile())
5688: $line - existing scanline
5689: $whichline - line number of the passed in scanline
5690: $field - type of change to process
5691: (either
5692: 'ID' -> correct the student/employee ID
5693: 'CODE' -> correct the CODE
5694: 'answer' -> fixup the submitted answers)
5695:
5696: $args - hash of additional info,
5697: - 'ID'
5698: 'newid' -> studentID to use in replacement
5699: of existing one
5700: - 'CODE'
5701: 'CODE_ignore_dup' - set to true if duplicates
5702: should be ignored.
5703: 'CODE' - is new code or 'use_unfound'
5704: if the existing unfound code should
5705: be used as is
5706: - 'answer'
5707: 'response' - new answer or 'none' if blank
5708: 'question' - the bubble line to change
5709: 'questionnum' - the question identifier,
5710: may include subquestion.
5711:
5712: Returns:
5713: $line - the modified scanline
5714:
5715: Side effects:
5716: $scan_data - may be updated
5717:
5718: =cut
5719:
5720:
5721: sub scantron_fixup_scanline {
5722: my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
5723: if ($field eq 'ID') {
5724: if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
5725: return ($line,1,'New value too large');
5726: }
5727: if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
5728: $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
5729: $args->{'newid'});
5730: }
5731: substr($line,$$scantron_config{'IDstart'}-1,
5732: $$scantron_config{'IDlength'})=$args->{'newid'};
5733: if ($args->{'newid'}=~/^\s*$/) {
5734: &scan_data($scan_data,"$whichline.user",
5735: $args->{'username'}.':'.$args->{'domain'});
5736: }
5737: } elsif ($field eq 'CODE') {
5738: if ($args->{'CODE_ignore_dup'}) {
5739: &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
5740: }
5741: &scan_data($scan_data,"$whichline.useCODE",'1');
5742: if ($args->{'CODE'} ne 'use_unfound') {
5743: if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
5744: return ($line,1,'New CODE value too large');
5745: }
5746: if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
5747: $args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
5748: }
5749: substr($line,$$scantron_config{'CODEstart'}-1,
5750: $$scantron_config{'CODElength'})=$args->{'CODE'};
5751: }
5752: } elsif ($field eq 'answer') {
5753: my $length=$scantron_config->{'Qlength'};
5754: my $off=$scantron_config->{'Qoff'};
5755: my $on=$scantron_config->{'Qon'};
5756: my $answer=${off}x$length;
5757: if ($args->{'response'} eq 'none') {
5758: &scan_data($scan_data,
5759: "$whichline.no_bubble.".$args->{'questionnum'},'1');
5760: } else {
5761: if ($on eq 'letter') {
5762: my @alphabet=('A'..'Z');
5763: $answer=$alphabet[$args->{'response'}];
5764: } elsif ($on eq 'number') {
5765: $answer=$args->{'response'}+1;
5766: if ($answer == 10) { $answer = '0'; }
5767: } else {
5768: substr($answer,$args->{'response'},1)=$on;
5769: }
5770: &scan_data($scan_data,
5771: "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
5772: }
5773: my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
5774: substr($line,$where-1,$length)=$answer;
5775: }
5776: return $line;
5777: }
5778:
5779: =pod
5780:
5781: =item scan_data
5782:
5783: Edit or look up an item in the scan_data hash.
5784:
5785: Arguments:
5786: $scan_data - The hash (see scantron_getfile)
5787: $key - shorthand of the key to edit (actual key is
5788: scantronfilename_key).
5789: $data - New value of the hash entry.
5790: $delete - If true, the entry is removed from the hash.
5791:
5792: Returns:
5793: The new value of the hash table field (undefined if deleted).
5794:
5795: =cut
5796:
5797:
5798: sub scan_data {
5799: my ($scan_data,$key,$value,$delete)=@_;
5800: my $filename=$env{'form.scantron_selectfile'};
5801: if (defined($value)) {
5802: $scan_data->{$filename.'_'.$key} = $value;
5803: }
5804: if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
5805: return $scan_data->{$filename.'_'.$key};
5806: }
5807:
5808: # ----- These first few routines are general use routines.----
5809:
5810: # Return the number of occurences of a pattern in a string.
5811:
5812: sub occurence_count {
5813: my ($string, $pattern) = @_;
5814:
5815: my @matches = ($string =~ /$pattern/g);
5816:
5817: return scalar(@matches);
5818: }
5819:
5820:
5821: # Take a string known to have digits and convert all the
5822: # digits into letters in the range J,A..I.
5823:
5824: sub digits_to_letters {
5825: my ($input) = @_;
5826:
5827: my @alphabet = ('J', 'A'..'I');
5828:
5829: my @input = split(//, $input);
5830: my $output ='';
5831: for (my $i = 0; $i < scalar(@input); $i++) {
5832: if ($input[$i] =~ /\d/) {
5833: $output .= $alphabet[$input[$i]];
5834: } else {
5835: $output .= $input[$i];
5836: }
5837: }
5838: return $output;
5839: }
5840:
5841: =pod
5842:
5843: =item scantron_parse_scanline
5844:
5845: Decodes a scanline from the selected scantron file
5846:
5847: Arguments:
5848: line - The text of the scantron file line to process
5849: whichline - Line number
5850: scantron_config - Hash describing the format of the scantron lines.
5851: scan_data - Hash of extra information about the scanline
5852: (see scantron_getfile for more information)
5853: just_header - True if should not process question answers but only
5854: the stuff to the left of the answers.
5855: Returns:
5856: Hash containing the result of parsing the scanline
5857:
5858: Keys are all proceeded by the string 'scantron.'
5859:
5860: CODE - the CODE in use for this scanline
5861: useCODE - 1 if the CODE is invalid but it usage has been forced
5862: by the operator
5863: CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
5864: CODEs were selected, but the usage has been
5865: forced by the operator
5866: ID - student/employee ID
5867: PaperID - if used, the ID number printed on the sheet when the
5868: paper was scanned
5869: FirstName - first name from the sheet
5870: LastName - last name from the sheet
5871:
5872: if just_header was not true these key may also exist
5873:
5874: missingerror - a list of bubble ranges that are considered to be answers
5875: to a single question that don't have any bubbles filled in.
5876: Of the form questionnumber:firstbubblenumber:count.
5877: doubleerror - a list of bubble ranges that are considered to be answers
5878: to a single question that have more than one bubble filled in.
5879: Of the form questionnumber::firstbubblenumber:count
5880:
5881: In the above, count is the number of bubble responses in the
5882: input line needed to represent the possible answers to the question.
5883: e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
5884: per line would have count = 2.
5885:
5886: maxquest - the number of the last bubble line that was parsed
5887:
5888: (<number> starts at 1)
5889: <number>.answer - zero or more letters representing the selected
5890: letters from the scanline for the bubble line
5891: <number>.
5892: if blank there was either no bubble or there where
5893: multiple bubbles, (consult the keys missingerror and
5894: doubleerror if this is an error condition)
5895:
5896: =cut
5897:
5898: sub scantron_parse_scanline {
5899: my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
5900:
5901: my %record;
5902: my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
5903: my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos); # Answers
5904: my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # earlier stuff
5905: if (!($$scantron_config{'CODElocation'} eq 0 ||
5906: $$scantron_config{'CODElocation'} eq 'none')) {
5907: if ($$scantron_config{'CODElocation'} < 0 ||
5908: $$scantron_config{'CODElocation'} eq 'letter' ||
5909: $$scantron_config{'CODElocation'} eq 'number') {
5910: $record{'scantron.CODE'}=substr($data,
5911: $$scantron_config{'CODEstart'}-1,
5912: $$scantron_config{'CODElength'});
5913: if (&scan_data($scan_data,"$whichline.useCODE")) {
5914: $record{'scantron.useCODE'}=1;
5915: }
5916: if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
5917: $record{'scantron.CODE_ignore_dup'}=1;
5918: }
5919: } else {
5920: #FIXME interpret first N questions
5921: }
5922: }
5923: $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
5924: $$scantron_config{'IDlength'});
5925: $record{'scantron.PaperID'}=
5926: substr($data,$$scantron_config{'PaperID'}-1,
5927: $$scantron_config{'PaperIDlength'});
5928: $record{'scantron.FirstName'}=
5929: substr($data,$$scantron_config{'FirstName'}-1,
5930: $$scantron_config{'FirstNamelength'});
5931: $record{'scantron.LastName'}=
5932: substr($data,$$scantron_config{'LastName'}-1,
5933: $$scantron_config{'LastNamelength'});
5934: if ($just_header) { return \%record; }
5935:
5936: my @alphabet=('A'..'Z');
5937: my $questnum=0;
5938: my $ansnum =1; # Multiple 'answer lines'/question.
5939:
5940: chomp($questions); # Get rid of any trailing \n.
5941: $questions =~ s/\r$//; # Get rid of trailing \r too (MAC or Win uploads).
5942: while (length($questions)) {
5943: my $answers_needed = $bubble_lines_per_response{$questnum};
5944: my $answer_length = ($$scantron_config{'Qlength'} * $answers_needed)
5945: || 1;
5946: $questnum++;
5947: my $quest_id = $questnum;
5948: my $currentquest = substr($questions,0,$answer_length);
5949: $questions = substr($questions,$answer_length);
5950: if (length($currentquest) < $answer_length) { next; }
5951:
5952: if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
5953: my $subquestnum = 1;
5954: my $subquestions = $currentquest;
5955: my @subanswers_needed =
5956: split(/,/,$subdivided_bubble_lines{$questnum-1});
5957: foreach my $subans (@subanswers_needed) {
5958: my $subans_length =
5959: ($$scantron_config{'Qlength'} * $subans) || 1;
5960: my $currsubquest = substr($subquestions,0,$subans_length);
5961: $subquestions = substr($subquestions,$subans_length);
5962: $quest_id = "$questnum.$subquestnum";
5963: if (($$scantron_config{'Qon'} eq 'letter') ||
5964: ($$scantron_config{'Qon'} eq 'number')) {
5965: $ansnum = &scantron_validator_lettnum($ansnum,
5966: $questnum,$quest_id,$subans,$currsubquest,$whichline,
5967: \@alphabet,\%record,$scantron_config,$scan_data);
5968: } else {
5969: $ansnum = &scantron_validator_positional($ansnum,
5970: $questnum,$quest_id,$subans,$currsubquest,$whichline, \@alphabet,\%record,$scantron_config,$scan_data);
5971: }
5972: $subquestnum ++;
5973: }
5974: } else {
5975: if (($$scantron_config{'Qon'} eq 'letter') ||
5976: ($$scantron_config{'Qon'} eq 'number')) {
5977: $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
5978: $quest_id,$answers_needed,$currentquest,$whichline,
5979: \@alphabet,\%record,$scantron_config,$scan_data);
5980: } else {
5981: $ansnum = &scantron_validator_positional($ansnum,$questnum,
5982: $quest_id,$answers_needed,$currentquest,$whichline,
5983: \@alphabet,\%record,$scantron_config,$scan_data);
5984: }
5985: }
5986: }
5987: $record{'scantron.maxquest'}=$questnum;
5988: return \%record;
5989: }
5990:
5991: sub scantron_validator_lettnum {
5992: my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
5993: $alphabet,$record,$scantron_config,$scan_data) = @_;
5994:
5995: # Qon 'letter' implies for each slot in currquest we have:
5996: # ? or * for doubles, a letter in A-Z for a bubble, and
5997: # about anything else (esp. a value of Qoff) for missing
5998: # bubbles.
5999: #
6000: # Qon 'number' implies each slot gives a digit that indexes the
6001: # bubbles filled, or Qoff, or a non-number for unbubbled lines,
6002: # and * or ? for double bubbles on a single line.
6003: #
6004:
6005: my $matchon;
6006: if ($$scantron_config{'Qon'} eq 'letter') {
6007: $matchon = '[A-Z]';
6008: } elsif ($$scantron_config{'Qon'} eq 'number') {
6009: $matchon = '\d';
6010: }
6011: my $occurrences = 0;
6012: if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
6013: ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
6014: ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
6015: ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
6016: ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
6017: ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
6018: my @singlelines = split('',$currquest);
6019: foreach my $entry (@singlelines) {
6020: $occurrences = &occurence_count($entry,$matchon);
6021: if ($occurrences > 1) {
6022: last;
6023: }
6024: }
6025: } else {
6026: $occurrences = &occurence_count($currquest,$matchon);
6027: }
6028: if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
6029: push(@{$record->{'scantron.doubleerror'}},$quest_id);
6030: for (my $ans=0; $ans<$answers_needed; $ans++) {
6031: my $bubble = substr($currquest,$ans,1);
6032: if ($bubble =~ /$matchon/ ) {
6033: if ($$scantron_config{'Qon'} eq 'number') {
6034: if ($bubble == 0) {
6035: $bubble = 10;
6036: }
6037: $record->{"scantron.$ansnum.answer"} =
6038: $alphabet->[$bubble-1];
6039: } else {
6040: $record->{"scantron.$ansnum.answer"} = $bubble;
6041: }
6042: } else {
6043: $record->{"scantron.$ansnum.answer"}='';
6044: }
6045: $ansnum++;
6046: }
6047: } elsif (!defined($currquest)
6048: || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
6049: || (&occurence_count($currquest,$matchon) == 0)) {
6050: for (my $ans=0; $ans<$answers_needed; $ans++ ) {
6051: $record->{"scantron.$ansnum.answer"}='';
6052: $ansnum++;
6053: }
6054: if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
6055: push(@{$record->{'scantron.missingerror'}},$quest_id);
6056: }
6057: } else {
6058: if ($$scantron_config{'Qon'} eq 'number') {
6059: $currquest = &digits_to_letters($currquest);
6060: }
6061: for (my $ans=0; $ans<$answers_needed; $ans++) {
6062: my $bubble = substr($currquest,$ans,1);
6063: $record->{"scantron.$ansnum.answer"} = $bubble;
6064: $ansnum++;
6065: }
6066: }
6067: return $ansnum;
6068: }
6069:
6070: sub scantron_validator_positional {
6071: my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
6072: $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
6073:
6074: # Otherwise there's a positional notation;
6075: # each bubble line requires Qlength items, and there are filled in
6076: # bubbles for each case where there 'Qon' characters.
6077: #
6078:
6079: my @array=split($$scantron_config{'Qon'},$currquest,-1);
6080:
6081: # If the split only gives us one element.. the full length of the
6082: # answer string, no bubbles are filled in:
6083:
6084: if ($answers_needed eq '') {
6085: return;
6086: }
6087:
6088: if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
6089: for (my $ans=0; $ans<$answers_needed; $ans++ ) {
6090: $record->{"scantron.$ansnum.answer"}='';
6091: $ansnum++;
6092: }
6093: if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
6094: push(@{$record->{"scantron.missingerror"}},$quest_id);
6095: }
6096: } elsif (scalar(@array) == 2) {
6097: my $location = length($array[0]);
6098: my $line_num = int($location / $$scantron_config{'Qlength'});
6099: my $bubble = $alphabet->[$location % $$scantron_config{'Qlength'}];
6100: for (my $ans=0; $ans<$answers_needed; $ans++) {
6101: if ($ans eq $line_num) {
6102: $record->{"scantron.$ansnum.answer"} = $bubble;
6103: } else {
6104: $record->{"scantron.$ansnum.answer"} = ' ';
6105: }
6106: $ansnum++;
6107: }
6108: } else {
6109: # If there's more than one instance of a bubble character
6110: # That's a double bubble; with positional notation we can
6111: # record all the bubbles filled in as well as the
6112: # fact this response consists of multiple bubbles.
6113: #
6114: if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
6115: ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
6116: ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
6117: ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
6118: ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
6119: ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
6120: my $doubleerror = 0;
6121: while (($currquest >= $$scantron_config{'Qlength'}) &&
6122: (!$doubleerror)) {
6123: my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
6124: $currquest = substr($currquest,$$scantron_config{'Qlength'});
6125: my @currarray = split($$scantron_config{'Qon'},$currline,-1);
6126: if (length(@currarray) > 2) {
6127: $doubleerror = 1;
6128: }
6129: }
6130: if ($doubleerror) {
6131: push(@{$record->{'scantron.doubleerror'}},$quest_id);
6132: }
6133: } else {
6134: push(@{$record->{'scantron.doubleerror'}},$quest_id);
6135: }
6136: my $item = $ansnum;
6137: for (my $ans=0; $ans<$answers_needed; $ans++) {
6138: $record->{"scantron.$item.answer"} = '';
6139: $item ++;
6140: }
6141:
6142: my @ans=@array;
6143: my $i=0;
6144: my $increment = 0;
6145: while ($#ans) {
6146: $i+=length($ans[0]) + $increment;
6147: my $line = int($i/$$scantron_config{'Qlength'} + $ansnum);
6148: my $bubble = $i%$$scantron_config{'Qlength'};
6149: $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
6150: shift(@ans);
6151: $increment = 1;
6152: }
6153: $ansnum += $answers_needed;
6154: }
6155: return $ansnum;
6156: }
6157:
6158: =pod
6159:
6160: =item scantron_add_delay
6161:
6162: Adds an error message that occurred during the grading phase to a
6163: queue of messages to be shown after grading pass is complete
6164:
6165: Arguments:
6166: $delayqueue - arrary ref of hash ref of error messages
6167: $scanline - the scanline that caused the error
6168: $errormesage - the error message
6169: $errorcode - a numeric code for the error
6170:
6171: Side Effects:
6172: updates the $delayqueue to have a new hash ref of the error
6173:
6174: =cut
6175:
6176: sub scantron_add_delay {
6177: my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
6178: push(@$delayqueue,
6179: {'line' => $scanline, 'emsg' => $errormessage,
6180: 'ecode' => $errorcode }
6181: );
6182: }
6183:
6184: =pod
6185:
6186: =item scantron_find_student
6187:
6188: Finds the username for the current scanline
6189:
6190: Arguments:
6191: $scantron_record - hash result from scantron_parse_scanline
6192: $scan_data - hash of correction information
6193: (see &scantron_getfile() form more information)
6194: $idmap - hash from &username_to_idmap()
6195: $line - number of current scanline
6196:
6197: Returns:
6198: Either 'username:domain' or undef if unknown
6199:
6200: =cut
6201:
6202: sub scantron_find_student {
6203: my ($scantron_record,$scan_data,$idmap,$line)=@_;
6204: my $scanID=$$scantron_record{'scantron.ID'};
6205: if ($scanID =~ /^\s*$/) {
6206: return &scan_data($scan_data,"$line.user");
6207: }
6208: foreach my $id (keys(%$idmap)) {
6209: if (lc($id) eq lc($scanID)) {
6210: return $$idmap{$id};
6211: }
6212: }
6213: return undef;
6214: }
6215:
6216: =pod
6217:
6218: =item scantron_filter
6219:
6220: Filter sub for lonnavmaps, filters out hidden resources if ignore
6221: hidden resources was selected
6222:
6223: =cut
6224:
6225: sub scantron_filter {
6226: my ($curres)=@_;
6227:
6228: if (ref($curres) && $curres->is_problem()) {
6229: # if the user has asked to not have either hidden
6230: # or 'randomout' controlled resources to be graded
6231: # don't include them
6232: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
6233: && $curres->randomout) {
6234: return 0;
6235: }
6236: return 1;
6237: }
6238: return 0;
6239: }
6240:
6241: =pod
6242:
6243: =item scantron_process_corrections
6244:
6245: Gets correction information out of submitted form data and corrects
6246: the scanline
6247:
6248: =cut
6249:
6250: sub scantron_process_corrections {
6251: my ($r) = @_;
6252: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6253: my ($scanlines,$scan_data)=&scantron_getfile();
6254: my $classlist=&Apache::loncoursedata::get_classlist();
6255: my $which=$env{'form.scantron_line'};
6256: my $line=&scantron_get_line($scanlines,$scan_data,$which);
6257: my ($skip,$err,$errmsg);
6258: if ($env{'form.scantron_skip_record'}) {
6259: $skip=1;
6260: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
6261: my $newstudent=$env{'form.scantron_username'}.':'.
6262: $env{'form.scantron_domain'};
6263: my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
6264: ($line,$err,$errmsg)=
6265: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
6266: 'ID',{'newid'=>$newid,
6267: 'username'=>$env{'form.scantron_username'},
6268: 'domain'=>$env{'form.scantron_domain'}});
6269: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
6270: my $resolution=$env{'form.scantron_CODE_resolution'};
6271: my $newCODE;
6272: my %args;
6273: if ($resolution eq 'use_unfound') {
6274: $newCODE='use_unfound';
6275: } elsif ($resolution eq 'use_found') {
6276: $newCODE=$env{'form.scantron_CODE_selectedvalue'};
6277: } elsif ($resolution eq 'use_typed') {
6278: $newCODE=$env{'form.scantron_CODE_newvalue'};
6279: } elsif ($resolution =~ /^use_closest_(\d+)/) {
6280: $newCODE=$env{"form.scantron_CODE_closest_$1"};
6281: }
6282: if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
6283: $args{'CODE_ignore_dup'}=1;
6284: }
6285: $args{'CODE'}=$newCODE;
6286: ($line,$err,$errmsg)=
6287: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
6288: 'CODE',\%args);
6289: } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
6290: foreach my $question (split(',',$env{'form.scantron_questions'})) {
6291: ($line,$err,$errmsg)=
6292: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
6293: $which,'answer',
6294: { 'question'=>$question,
6295: 'response'=>$env{"form.scantron_correct_Q_$question"},
6296: 'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
6297: if ($err) { last; }
6298: }
6299: }
6300: if ($err) {
6301: $r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
6302: } else {
6303: &scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
6304: &scantron_putfile($scanlines,$scan_data);
6305: }
6306: }
6307:
6308: =pod
6309:
6310: =item reset_skipping_status
6311:
6312: Forgets the current set of remember skipped scanlines (and thus
6313: reverts back to considering all lines in the
6314: scantron_skipped_<filename> file)
6315:
6316: =cut
6317:
6318: sub reset_skipping_status {
6319: my ($scanlines,$scan_data)=&scantron_getfile();
6320: &scan_data($scan_data,'remember_skipping',undef,1);
6321: &scantron_putfile(undef,$scan_data);
6322: }
6323:
6324: =pod
6325:
6326: =item start_skipping
6327:
6328: Marks a scanline to be skipped.
6329:
6330: =cut
6331:
6332: sub start_skipping {
6333: my ($scan_data,$i)=@_;
6334: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
6335: if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
6336: $remembered{$i}=2;
6337: } else {
6338: $remembered{$i}=1;
6339: }
6340: &scan_data($scan_data,'remember_skipping',join(':',%remembered));
6341: }
6342:
6343: =pod
6344:
6345: =item should_be_skipped
6346:
6347: Checks whether a scanline should be skipped.
6348:
6349: =cut
6350:
6351: sub should_be_skipped {
6352: my ($scanlines,$scan_data,$i)=@_;
6353: if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
6354: # not redoing old skips
6355: if ($scanlines->{'skipped'}[$i]) { return 1; }
6356: return 0;
6357: }
6358: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
6359:
6360: if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
6361: return 0;
6362: }
6363: return 1;
6364: }
6365:
6366: =pod
6367:
6368: =item remember_current_skipped
6369:
6370: Discovers what scanlines are in the scantron_skipped_<filename>
6371: file and remembers them into scan_data for later use.
6372:
6373: =cut
6374:
6375: sub remember_current_skipped {
6376: my ($scanlines,$scan_data)=&scantron_getfile();
6377: my %to_remember;
6378: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6379: if ($scanlines->{'skipped'}[$i]) {
6380: $to_remember{$i}=1;
6381: }
6382: }
6383:
6384: &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
6385: &scantron_putfile(undef,$scan_data);
6386: }
6387:
6388: =pod
6389:
6390: =item check_for_error
6391:
6392: Checks if there was an error when attempting to remove a specific
6393: scantron_.. bubblesheet data file. Prints out an error if
6394: something went wrong.
6395:
6396: =cut
6397:
6398: sub check_for_error {
6399: my ($r,$result)=@_;
6400: if ($result ne 'ok' && $result ne 'not_found' ) {
6401: $r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
6402: }
6403: }
6404:
6405: =pod
6406:
6407: =item scantron_warning_screen
6408:
6409: Interstitial screen to make sure the operator has selected the
6410: correct options before we start the validation phase.
6411:
6412: =cut
6413:
6414: sub scantron_warning_screen {
6415: my ($button_text,$symb)=@_;
6416: my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
6417: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6418: my $CODElist;
6419: if ($scantron_config{'CODElocation'} &&
6420: $scantron_config{'CODEstart'} &&
6421: $scantron_config{'CODElength'}) {
6422: $CODElist=$env{'form.scantron_CODElist'};
6423: if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
6424: $CODElist=
6425: '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
6426: $env{'form.scantron_CODElist'}.'</tt></td></tr>';
6427: }
6428: my $lastbubblepoints;
6429: if ($env{'form.scantron_lastbubblepoints'} ne '') {
6430: $lastbubblepoints =
6431: '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
6432: $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
6433: }
6434: return ('
6435: <p>
6436: <span class="LC_warning">
6437: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
6438: </p>
6439: <table>
6440: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
6441: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
6442: '.$CODElist.$lastbubblepoints.'
6443: </table>
6444: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
6445: '.&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>
6446:
6447: <br />
6448: ');
6449: }
6450:
6451: =pod
6452:
6453: =item scantron_do_warning
6454:
6455: Check if the operator has picked something for all required
6456: fields. Error out if something is missing.
6457:
6458: =cut
6459:
6460: sub scantron_do_warning {
6461: my ($r,$symb)=@_;
6462: if (!$symb) {return '';}
6463: my $default_form_data=&defaultFormData($symb);
6464: $r->print(&scantron_form_start().$default_form_data);
6465: if ( $env{'form.selectpage'} eq '' ||
6466: $env{'form.scantron_selectfile'} eq '' ||
6467: $env{'form.scantron_format'} eq '' ) {
6468: $r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
6469: if ( $env{'form.selectpage'} eq '') {
6470: $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
6471: }
6472: if ( $env{'form.scantron_selectfile'} eq '') {
6473: $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
6474: }
6475: if ( $env{'form.scantron_format'} eq '') {
6476: $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
6477: }
6478: } else {
6479: my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
6480: my $bubbledbyhand=&hand_bubble_option();
6481: $r->print('
6482: '.$warning.$bubbledbyhand.'
6483: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
6484: <input type="hidden" name="command" value="scantron_validate" />
6485: ');
6486: }
6487: $r->print("</form><br />");
6488: return '';
6489: }
6490:
6491: =pod
6492:
6493: =item scantron_form_start
6494:
6495: html hidden input for remembering all selected grading options
6496:
6497: =cut
6498:
6499: sub scantron_form_start {
6500: my ($max_bubble)=@_;
6501: my $result= <<SCANTRONFORM;
6502: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
6503: <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
6504: <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
6505: <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
6506: <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
6507: <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
6508: <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
6509: <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
6510: <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
6511: <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
6512: SCANTRONFORM
6513:
6514: my $line = 0;
6515: while (defined($env{"form.scantron.bubblelines.$line"})) {
6516: my $chunk =
6517: '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
6518: $chunk .=
6519: '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
6520: $chunk .=
6521: '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
6522: $chunk .=
6523: '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
6524: $result .= $chunk;
6525: $line++;
6526: }
6527: return $result;
6528: }
6529:
6530: =pod
6531:
6532: =item scantron_validate_file
6533:
6534: Dispatch routine for doing validation of a bubblesheet data file.
6535:
6536: Also processes any necessary information resets that need to
6537: occur before validation begins (ignore previous corrections,
6538: restarting the skipped records processing)
6539:
6540: =cut
6541:
6542: sub scantron_validate_file {
6543: my ($r,$symb) = @_;
6544: if (!$symb) {return '';}
6545: my $default_form_data=&defaultFormData($symb);
6546:
6547: # do the detection of only doing skipped records first befroe we delete
6548: # them when doing the corrections reset
6549: if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
6550: &reset_skipping_status();
6551: }
6552: if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
6553: &remember_current_skipped();
6554: $env{'form.scantron_options_redo'}='redo_skipped_ready';
6555: }
6556:
6557: if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
6558: &check_for_error($r,&scantron_remove_file('corrected'));
6559: &check_for_error($r,&scantron_remove_file('skipped'));
6560: &check_for_error($r,&scantron_remove_scan_data());
6561: $env{'form.scantron_options_ignore'}='done';
6562: }
6563:
6564: if ($env{'form.scantron_corrections'}) {
6565: &scantron_process_corrections($r);
6566: }
6567: $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
6568: #get the student pick code ready
6569: $r->print(&Apache::loncommon::studentbrowser_javascript());
6570: my $nav_error;
6571: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6572: my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
6573: if ($nav_error) {
6574: $r->print(&navmap_errormsg());
6575: return '';
6576: }
6577: my $result=&scantron_form_start($max_bubble).$default_form_data;
6578: if ($env{'form.scantron_lastbubblepoints'} ne '') {
6579: $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
6580: }
6581: $r->print($result);
6582:
6583: my @validate_phases=( 'sequence',
6584: 'ID',
6585: 'CODE',
6586: 'doublebubble',
6587: 'missingbubbles');
6588: if (!$env{'form.validatepass'}) {
6589: $env{'form.validatepass'} = 0;
6590: }
6591: my $currentphase=$env{'form.validatepass'};
6592:
6593:
6594: my $stop=0;
6595: while (!$stop && $currentphase < scalar(@validate_phases)) {
6596: $r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
6597: $r->rflush();
6598: my $which="scantron_validate_".$validate_phases[$currentphase];
6599: {
6600: no strict 'refs';
6601: ($stop,$currentphase)=&$which($r,$currentphase);
6602: }
6603: }
6604: if (!$stop) {
6605: my $warning=&scantron_warning_screen('Start Grading',$symb);
6606: $r->print(&mt('Validation process complete.').'<br />'.
6607: $warning.
6608: &mt('Perform verification for each student after storage of submissions?').
6609: ' <span class="LC_nobreak"><label>'.
6610: '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
6611: (' 'x3).'<label>'.
6612: '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
6613: '</label></span><br />'.
6614: &mt('Grading will take longer if you use verification.').'<br />'.
6615: &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','»').'<br /><br />'.
6616: '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
6617: '<input type="hidden" name="command" value="scantron_process" />'."\n");
6618: } else {
6619: $r->print('<input type="hidden" name="command" value="scantron_validate" />');
6620: $r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
6621: }
6622: if ($stop) {
6623: if ($validate_phases[$currentphase] eq 'sequence') {
6624: $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' → " />');
6625: $r->print(' '.&mt('this error').' <br />');
6626:
6627: $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>');
6628: } else {
6629: if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
6630: $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' →" onclick="javascript:verify_bubble_radio(this.form)" />');
6631: } else {
6632: $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' →" />');
6633: }
6634: $r->print(' '.&mt('using corrected info').' <br />');
6635: $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
6636: $r->print(" ".&mt("this scanline saving it for later."));
6637: }
6638: }
6639: $r->print(" </form><br />");
6640: return '';
6641: }
6642:
6643:
6644: =pod
6645:
6646: =item scantron_remove_file
6647:
6648: Removes the requested bubblesheet data file, makes sure that
6649: scantron_original_<filename> is never removed
6650:
6651:
6652: =cut
6653:
6654: sub scantron_remove_file {
6655: my ($which)=@_;
6656: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6657: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6658: my $file='scantron_';
6659: if ($which eq 'corrected' || $which eq 'skipped') {
6660: $file.=$which.'_';
6661: } else {
6662: return 'refused';
6663: }
6664: $file.=$env{'form.scantron_selectfile'};
6665: return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
6666: }
6667:
6668:
6669: =pod
6670:
6671: =item scantron_remove_scan_data
6672:
6673: Removes all scan_data correction for the requested bubblesheet
6674: data file. (In the case that both the are doing skipped records we need
6675: to remember the old skipped lines for the time being so that element
6676: persists for a while.)
6677:
6678: =cut
6679:
6680: sub scantron_remove_scan_data {
6681: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6682: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6683: my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
6684: my @todelete;
6685: my $filename=$env{'form.scantron_selectfile'};
6686: foreach my $key (@keys) {
6687: if ($key=~/^\Q$filename\E_/) {
6688: if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
6689: $key=~/remember_skipping/) {
6690: next;
6691: }
6692: push(@todelete,$key);
6693: }
6694: }
6695: my $result;
6696: if (@todelete) {
6697: $result = &Apache::lonnet::del('nohist_scantrondata',
6698: \@todelete,$cdom,$cname);
6699: } else {
6700: $result = 'ok';
6701: }
6702: return $result;
6703: }
6704:
6705:
6706: =pod
6707:
6708: =item scantron_getfile
6709:
6710: Fetches the requested bubblesheet data file (all 3 versions), and
6711: the scan_data hash
6712:
6713: Arguments:
6714: None
6715:
6716: Returns:
6717: 2 hash references
6718:
6719: - first one has
6720: orig -
6721: corrected -
6722: skipped - each of which points to an array ref of the specified
6723: file broken up into individual lines
6724: count - number of scanlines
6725:
6726: - second is the scan_data hash possible keys are
6727: ($number refers to scanline numbered $number and thus the key affects
6728: only that scanline
6729: $bubline refers to the specific bubble line element and the aspects
6730: refers to that specific bubble line element)
6731:
6732: $number.user - username:domain to use
6733: $number.CODE_ignore_dup
6734: - ignore the duplicate CODE error
6735: $number.useCODE
6736: - use the CODE in the scanline as is
6737: $number.no_bubble.$bubline
6738: - it is valid that there is no bubbled in bubble
6739: at $number $bubline
6740: remember_skipping
6741: - a frozen hash containing keys of $number and values
6742: of either
6743: 1 - we are on a 'do skipped records pass' and plan
6744: on processing this line
6745: 2 - we are on a 'do skipped records pass' and this
6746: scanline has been marked to skip yet again
6747:
6748: =cut
6749:
6750: sub scantron_getfile {
6751: #FIXME really would prefer a scantron directory
6752: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6753: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6754: my $lines;
6755: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
6756: 'scantron_orig_'.$env{'form.scantron_selectfile'});
6757: my %scanlines;
6758: $scanlines{'orig'}=[(split("\n",$lines,-1))];
6759: my $temp=$scanlines{'orig'};
6760: $scanlines{'count'}=$#$temp;
6761:
6762: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
6763: 'scantron_corrected_'.$env{'form.scantron_selectfile'});
6764: if ($lines eq '-1') {
6765: $scanlines{'corrected'}=[];
6766: } else {
6767: $scanlines{'corrected'}=[(split("\n",$lines,-1))];
6768: }
6769: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
6770: 'scantron_skipped_'.$env{'form.scantron_selectfile'});
6771: if ($lines eq '-1') {
6772: $scanlines{'skipped'}=[];
6773: } else {
6774: $scanlines{'skipped'}=[(split("\n",$lines,-1))];
6775: }
6776: my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
6777: if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
6778: my %scan_data = @tmp;
6779: return (\%scanlines,\%scan_data);
6780: }
6781:
6782: =pod
6783:
6784: =item lonnet_putfile
6785:
6786: Wrapper routine to call &Apache::lonnet::finishuserfileupload
6787:
6788: Arguments:
6789: $contents - data to store
6790: $filename - filename to store $contents into
6791:
6792: Returns:
6793: result value from &Apache::lonnet::finishuserfileupload
6794:
6795: =cut
6796:
6797: sub lonnet_putfile {
6798: my ($contents,$filename)=@_;
6799: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
6800: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6801: $env{'form.sillywaytopassafilearound'}=$contents;
6802: &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
6803:
6804: }
6805:
6806: =pod
6807:
6808: =item scantron_putfile
6809:
6810: Stores the current version of the bubblesheet data files, and the
6811: scan_data hash. (Does not modify the original version only the
6812: corrected and skipped versions.
6813:
6814: Arguments:
6815: $scanlines - hash ref that looks like the first return value from
6816: &scantron_getfile()
6817: $scan_data - hash ref that looks like the second return value from
6818: &scantron_getfile()
6819:
6820: =cut
6821:
6822: sub scantron_putfile {
6823: my ($scanlines,$scan_data) = @_;
6824: #FIXME really would prefer a scantron directory
6825: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6826: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6827: if ($scanlines) {
6828: my $prefix='scantron_';
6829: # no need to update orig, shouldn't change
6830: # &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
6831: # $env{'form.scantron_selectfile'});
6832: &lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
6833: $prefix.'corrected_'.
6834: $env{'form.scantron_selectfile'});
6835: &lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
6836: $prefix.'skipped_'.
6837: $env{'form.scantron_selectfile'});
6838: }
6839: &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
6840: }
6841:
6842: =pod
6843:
6844: =item scantron_get_line
6845:
6846: Returns the correct version of the scanline
6847:
6848: Arguments:
6849: $scanlines - hash ref that looks like the first return value from
6850: &scantron_getfile()
6851: $scan_data - hash ref that looks like the second return value from
6852: &scantron_getfile()
6853: $i - number of the requested line (starts at 0)
6854:
6855: Returns:
6856: A scanline, (either the original or the corrected one if it
6857: exists), or undef if the requested scanline should be
6858: skipped. (Either because it's an skipped scanline, or it's an
6859: unskipped scanline and we are not doing a 'do skipped scanlines'
6860: pass.
6861:
6862: =cut
6863:
6864: sub scantron_get_line {
6865: my ($scanlines,$scan_data,$i)=@_;
6866: if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
6867: #if ($scanlines->{'skipped'}[$i]) { return undef; }
6868: if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
6869: return $scanlines->{'orig'}[$i];
6870: }
6871:
6872: =pod
6873:
6874: =item scantron_todo_count
6875:
6876: Counts the number of scanlines that need processing.
6877:
6878: Arguments:
6879: $scanlines - hash ref that looks like the first return value from
6880: &scantron_getfile()
6881: $scan_data - hash ref that looks like the second return value from
6882: &scantron_getfile()
6883:
6884: Returns:
6885: $count - number of scanlines to process
6886:
6887: =cut
6888:
6889: sub get_todo_count {
6890: my ($scanlines,$scan_data)=@_;
6891: my $count=0;
6892: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6893: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6894: if ($line=~/^[\s\cz]*$/) { next; }
6895: $count++;
6896: }
6897: return $count;
6898: }
6899:
6900: =pod
6901:
6902: =item scantron_put_line
6903:
6904: Updates the 'corrected' or 'skipped' versions of the bubblesheet
6905: data file.
6906:
6907: Arguments:
6908: $scanlines - hash ref that looks like the first return value from
6909: &scantron_getfile()
6910: $scan_data - hash ref that looks like the second return value from
6911: &scantron_getfile()
6912: $i - line number to update
6913: $newline - contents of the updated scanline
6914: $skip - if true make the line for skipping and update the
6915: 'skipped' file
6916:
6917: =cut
6918:
6919: sub scantron_put_line {
6920: my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
6921: if ($skip) {
6922: $scanlines->{'skipped'}[$i]=$newline;
6923: &start_skipping($scan_data,$i);
6924: return;
6925: }
6926: $scanlines->{'corrected'}[$i]=$newline;
6927: }
6928:
6929: =pod
6930:
6931: =item scantron_clear_skip
6932:
6933: Remove a line from the 'skipped' file
6934:
6935: Arguments:
6936: $scanlines - hash ref that looks like the first return value from
6937: &scantron_getfile()
6938: $scan_data - hash ref that looks like the second return value from
6939: &scantron_getfile()
6940: $i - line number to update
6941:
6942: =cut
6943:
6944: sub scantron_clear_skip {
6945: my ($scanlines,$scan_data,$i)=@_;
6946: if (exists($scanlines->{'skipped'}[$i])) {
6947: undef($scanlines->{'skipped'}[$i]);
6948: return 1;
6949: }
6950: return 0;
6951: }
6952:
6953: =pod
6954:
6955: =item scantron_filter_not_exam
6956:
6957: Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
6958: filter out resources that are not marked as 'exam' mode
6959:
6960: =cut
6961:
6962: sub scantron_filter_not_exam {
6963: my ($curres)=@_;
6964:
6965: if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
6966: # if the user has asked to not have either hidden
6967: # or 'randomout' controlled resources to be graded
6968: # don't include them
6969: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
6970: && $curres->randomout) {
6971: return 0;
6972: }
6973: return 1;
6974: }
6975: return 0;
6976: }
6977:
6978: =pod
6979:
6980: =item scantron_validate_sequence
6981:
6982: Validates the selected sequence, checking for resource that are
6983: not set to exam mode.
6984:
6985: =cut
6986:
6987: sub scantron_validate_sequence {
6988: my ($r,$currentphase) = @_;
6989:
6990: my $navmap=Apache::lonnavmaps::navmap->new();
6991: unless (ref($navmap)) {
6992: $r->print(&navmap_errormsg());
6993: return (1,$currentphase);
6994: }
6995: my (undef,undef,$sequence)=
6996: &Apache::lonnet::decode_symb($env{'form.selectpage'});
6997:
6998: my $map=$navmap->getResourceByUrl($sequence);
6999:
7000: $r->print('<input type="hidden" name="validate_sequence_exam"
7001: value="ignore" />');
7002: if ($env{'form.validate_sequence_exam'} ne 'ignore') {
7003: my @resources=
7004: $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
7005: if (@resources) {
7006: $r->print(
7007: '<p class="LC_warning">'
7008: .&mt('Some resources in the sequence currently are not set to'
7009: .' bubblesheet exam mode. Grading these resources currently may not'
7010: .' work correctly.')
7011: .'</p>'
7012: );
7013: return (1,$currentphase);
7014: }
7015: }
7016:
7017: return (0,$currentphase+1);
7018: }
7019:
7020:
7021:
7022: sub scantron_validate_ID {
7023: my ($r,$currentphase) = @_;
7024:
7025: #get student info
7026: my $classlist=&Apache::loncoursedata::get_classlist();
7027: my %idmap=&username_to_idmap($classlist);
7028:
7029: #get scantron line setup
7030: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7031: my ($scanlines,$scan_data)=&scantron_getfile();
7032:
7033: my $nav_error;
7034: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
7035: if ($nav_error) {
7036: $r->print(&navmap_errormsg());
7037: return(1,$currentphase);
7038: }
7039:
7040: my %found=('ids'=>{},'usernames'=>{});
7041: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7042: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7043: if ($line=~/^[\s\cz]*$/) { next; }
7044: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7045: $scan_data);
7046: my $id=$$scan_record{'scantron.ID'};
7047: my $found;
7048: foreach my $checkid (keys(%idmap)) {
7049: if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
7050: }
7051: if ($found) {
7052: my $username=$idmap{$found};
7053: if ($found{'ids'}{$found}) {
7054: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
7055: $line,'duplicateID',$found);
7056: return(1,$currentphase);
7057: } elsif ($found{'usernames'}{$username}) {
7058: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
7059: $line,'duplicateID',$username);
7060: return(1,$currentphase);
7061: }
7062: #FIXME store away line we previously saw the ID on to use above
7063: $found{'ids'}{$found}++;
7064: $found{'usernames'}{$username}++;
7065: } else {
7066: if ($id =~ /^\s*$/) {
7067: my $username=&scan_data($scan_data,"$i.user");
7068: if (defined($username) && $found{'usernames'}{$username}) {
7069: &scantron_get_correction($r,$i,$scan_record,
7070: \%scantron_config,
7071: $line,'duplicateID',$username);
7072: return(1,$currentphase);
7073: } elsif (!defined($username)) {
7074: &scantron_get_correction($r,$i,$scan_record,
7075: \%scantron_config,
7076: $line,'incorrectID');
7077: return(1,$currentphase);
7078: }
7079: $found{'usernames'}{$username}++;
7080: } else {
7081: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
7082: $line,'incorrectID');
7083: return(1,$currentphase);
7084: }
7085: }
7086: }
7087:
7088: return (0,$currentphase+1);
7089: }
7090:
7091:
7092: sub scantron_get_correction {
7093: my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
7094: #FIXME in the case of a duplicated ID the previous line, probably need
7095: #to show both the current line and the previous one and allow skipping
7096: #the previous one or the current one
7097:
7098: if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
7099: $r->print(
7100: '<p class="LC_warning">'
7101: .&mt('An error was detected ([_1]) for PaperID [_2]',
7102: "<b>$error</b>",
7103: '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
7104: ."</p> \n");
7105: } else {
7106: $r->print(
7107: '<p class="LC_warning">'
7108: .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
7109: "<b>$error</b>", $i, "<pre>$line</pre>")
7110: ."</p> \n");
7111: }
7112: my $message =
7113: '<p>'
7114: .&mt('The ID on the form is [_1]',
7115: "<tt>$$scan_record{'scantron.ID'}</tt>")
7116: .'<br />'
7117: .&mt('The name on the paper is [_1], [_2]',
7118: $$scan_record{'scantron.LastName'},
7119: $$scan_record{'scantron.FirstName'})
7120: .'</p>';
7121:
7122: $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
7123: $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
7124: # Array populated for doublebubble or
7125: my @lines_to_correct; # missingbubble errors to build javascript
7126: # to validate radio button checking
7127:
7128: if ($error =~ /ID$/) {
7129: if ($error eq 'incorrectID') {
7130: $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
7131: "</p>\n");
7132: } elsif ($error eq 'duplicateID') {
7133: $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
7134: }
7135: $r->print($message);
7136: $r->print("<p>".&mt("How should I handle this?")." <br /> \n");
7137: $r->print("\n<ul><li> ");
7138: #FIXME it would be nice if this sent back the user ID and
7139: #could do partial userID matches
7140: $r->print(&Apache::loncommon::selectstudent_link('scantronupload',
7141: 'scantron_username','scantron_domain'));
7142: $r->print(": <input type='text' name='scantron_username' value='' />");
7143: $r->print("\n:\n".
7144: &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
7145:
7146: $r->print('</li>');
7147: } elsif ($error =~ /CODE$/) {
7148: if ($error eq 'incorrectCODE') {
7149: $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
7150: } elsif ($error eq 'duplicateCODE') {
7151: $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");
7152: }
7153: $r->print("<p>".&mt('The CODE on the form is [_1]',
7154: "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
7155: ."</p>\n");
7156: $r->print($message);
7157: $r->print("<p>".&mt("How should I handle this?")."</p>\n");
7158: $r->print("\n<br /> ");
7159: my $i=0;
7160: if ($error eq 'incorrectCODE'
7161: && $$scan_record{'scantron.CODE'}=~/\S/ ) {
7162: my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
7163: if ($closest > 0) {
7164: foreach my $testcode (@{$closest}) {
7165: my $checked='';
7166: if (!$i) { $checked=' checked="checked"'; }
7167: $r->print("
7168: <label>
7169: <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
7170: ".&mt("Use the similar CODE [_1] instead.",
7171: "<b><tt>".$testcode."</tt></b>")."
7172: </label>
7173: <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
7174: $r->print("\n<br />");
7175: $i++;
7176: }
7177: }
7178: }
7179: if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
7180: my $checked; if (!$i) { $checked=' checked="checked"'; }
7181: $r->print("
7182: <label>
7183: <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
7184: ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
7185: "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
7186: </label>");
7187: $r->print("\n<br />");
7188: }
7189:
7190: $r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
7191: function change_radio(field) {
7192: var slct=document.scantronupload.scantron_CODE_resolution;
7193: var i;
7194: for (i=0;i<slct.length;i++) {
7195: if (slct[i].value==field) { slct[i].checked=true; }
7196: }
7197: }
7198: ENDSCRIPT
7199: my $href="/adm/pickcode?".
7200: "form=".&escape("scantronupload").
7201: "&scantron_format=".&escape($env{'form.scantron_format'}).
7202: "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
7203: "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
7204: "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
7205: if ($env{'form.scantron_CODElist'} =~ /\S/) {
7206: $r->print("
7207: <label>
7208: <input type='radio' name='scantron_CODE_resolution' value='use_found' />
7209: ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
7210: "<a target='_blank' href='$href'>","</a>")."
7211: </label>
7212: ".&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\')" />'));
7213: $r->print("\n<br />");
7214: }
7215: $r->print("
7216: <label>
7217: <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
7218: ".&mt("Use [_1] as the CODE.",
7219: "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
7220: $r->print("\n<br /><br />");
7221: } elsif ($error eq 'doublebubble') {
7222: $r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
7223:
7224: # The form field scantron_questions is acutally a list of line numbers.
7225: # represented by this form so:
7226:
7227: my $line_list = &questions_to_line_list($arg);
7228:
7229: $r->print('<input type="hidden" name="scantron_questions" value="'.
7230: $line_list.'" />');
7231: $r->print($message);
7232: $r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
7233: foreach my $question (@{$arg}) {
7234: my @linenums = &prompt_for_corrections($r,$question,$scan_config,
7235: $scan_record, $error);
7236: push(@lines_to_correct,@linenums);
7237: }
7238: $r->print(&verify_bubbles_checked(@lines_to_correct));
7239: } elsif ($error eq 'missingbubble') {
7240: $r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
7241: $r->print($message);
7242: $r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
7243: $r->print(&mt("Some questions have no scanned bubbles.")."\n");
7244:
7245: # The form field scantron_questions is actually a list of line numbers not
7246: # a list of question numbers. Therefore:
7247: #
7248:
7249: my $line_list = &questions_to_line_list($arg);
7250:
7251: $r->print('<input type="hidden" name="scantron_questions" value="'.
7252: $line_list.'" />');
7253: foreach my $question (@{$arg}) {
7254: my @linenums = &prompt_for_corrections($r,$question,$scan_config,
7255: $scan_record, $error);
7256: push(@lines_to_correct,@linenums);
7257: }
7258: $r->print(&verify_bubbles_checked(@lines_to_correct));
7259: } else {
7260: $r->print("\n<ul>");
7261: }
7262: $r->print("\n</li></ul>");
7263: }
7264:
7265: sub verify_bubbles_checked {
7266: my (@ansnums) = @_;
7267: my $ansnumstr = join('","',@ansnums);
7268: my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
7269: my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
7270: function verify_bubble_radio(form) {
7271: var ansnumArray = new Array ("$ansnumstr");
7272: var need_bubble_count = 0;
7273: for (var i=0; i<ansnumArray.length; i++) {
7274: if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
7275: var bubble_picked = 0;
7276: for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
7277: if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
7278: bubble_picked = 1;
7279: }
7280: }
7281: if (bubble_picked == 0) {
7282: need_bubble_count ++;
7283: }
7284: }
7285: }
7286: if (need_bubble_count) {
7287: alert("$warning");
7288: return;
7289: }
7290: form.submit();
7291: }
7292: ENDSCRIPT
7293: return $output;
7294: }
7295:
7296: =pod
7297:
7298: =item questions_to_line_list
7299:
7300: Converts a list of questions into a string of comma separated
7301: line numbers in the answer sheet used by the questions. This is
7302: used to fill in the scantron_questions form field.
7303:
7304: Arguments:
7305: questions - Reference to an array of questions.
7306:
7307: =cut
7308:
7309:
7310: sub questions_to_line_list {
7311: my ($questions) = @_;
7312: my @lines;
7313:
7314: foreach my $item (@{$questions}) {
7315: my $question = $item;
7316: my ($first,$count,$last);
7317: if ($item =~ /^(\d+)\.(\d+)$/) {
7318: $question = $1;
7319: my $subquestion = $2;
7320: $first = $first_bubble_line{$question-1} + 1;
7321: my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
7322: my $subcount = 1;
7323: while ($subcount<$subquestion) {
7324: $first += $subans[$subcount-1];
7325: $subcount ++;
7326: }
7327: $count = $subans[$subquestion-1];
7328: } else {
7329: $first = $first_bubble_line{$question-1} + 1;
7330: $count = $bubble_lines_per_response{$question-1};
7331: }
7332: $last = $first+$count-1;
7333: push(@lines, ($first..$last));
7334: }
7335: return join(',', @lines);
7336: }
7337:
7338: =pod
7339:
7340: =item prompt_for_corrections
7341:
7342: Prompts for a potentially multiline correction to the
7343: user's bubbling (factors out common code from scantron_get_correction
7344: for multi and missing bubble cases).
7345:
7346: Arguments:
7347: $r - Apache request object.
7348: $question - The question number to prompt for.
7349: $scan_config - The scantron file configuration hash.
7350: $scan_record - Reference to the hash that has the the parsed scanlines.
7351: $error - Type of error
7352:
7353: Implicit inputs:
7354: %bubble_lines_per_response - Starting line numbers for each question.
7355: Numbered from 0 (but question numbers are from
7356: 1.
7357: %first_bubble_line - Starting bubble line for each question.
7358: %subdivided_bubble_lines - optionresponse, matchresponse and rankresponse
7359: type problems render as separate sub-questions,
7360: in exam mode. This hash contains a
7361: comma-separated list of the lines per
7362: sub-question.
7363: %responsetype_per_response - essayresponse, formularesponse,
7364: stringresponse, imageresponse, reactionresponse,
7365: and organicresponse type problem parts can have
7366: multiple lines per response if the weight
7367: assigned exceeds 10. In this case, only
7368: one bubble per line is permitted, but more
7369: than one line might contain bubbles, e.g.
7370: bubbling of: line 1 - J, line 2 - J,
7371: line 3 - B would assign 22 points.
7372:
7373: =cut
7374:
7375: sub prompt_for_corrections {
7376: my ($r, $question, $scan_config, $scan_record, $error) = @_;
7377: my ($current_line,$lines);
7378: my @linenums;
7379: my $questionnum = $question;
7380: if ($question =~ /^(\d+)\.(\d+)$/) {
7381: $question = $1;
7382: $current_line = $first_bubble_line{$question-1} + 1 ;
7383: my $subquestion = $2;
7384: my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
7385: my $subcount = 1;
7386: while ($subcount<$subquestion) {
7387: $current_line += $subans[$subcount-1];
7388: $subcount ++;
7389: }
7390: $lines = $subans[$subquestion-1];
7391: } else {
7392: $current_line = $first_bubble_line{$question-1} + 1 ;
7393: $lines = $bubble_lines_per_response{$question-1};
7394: }
7395: if ($lines > 1) {
7396: $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
7397: if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
7398: ($responsetype_per_response{$question-1} eq 'formularesponse') ||
7399: ($responsetype_per_response{$question-1} eq 'stringresponse') ||
7400: ($responsetype_per_response{$question-1} eq 'imageresponse') ||
7401: ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
7402: ($responsetype_per_response{$question-1} eq 'organicresponse')) {
7403: $r->print(
7404: &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)
7405: .'<br /><br />'
7406: .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
7407: .'<br />'
7408: .&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.')
7409: .'<br />'
7410: .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
7411: .'<br /><br />'
7412: );
7413: } else {
7414: $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
7415: }
7416: }
7417: for (my $i =0; $i < $lines; $i++) {
7418: my $selected = $$scan_record{"scantron.$current_line.answer"};
7419: &scantron_bubble_selector($r,$scan_config,$current_line,
7420: $questionnum,$error,split('', $selected));
7421: push(@linenums,$current_line);
7422: $current_line++;
7423: }
7424: if ($lines > 1) {
7425: $r->print("<hr /><br />");
7426: }
7427: return @linenums;
7428: }
7429:
7430: =pod
7431:
7432: =item scantron_bubble_selector
7433:
7434: Generates the html radiobuttons to correct a single bubble line
7435: possibly showing the existing the selected bubbles if known
7436:
7437: Arguments:
7438: $r - Apache request object
7439: $scan_config - hash from &get_scantron_config()
7440: $line - Number of the line being displayed.
7441: $questionnum - Question number (may include subquestion)
7442: $error - Type of error.
7443: @selected - Array of bubbles picked on this line.
7444:
7445: =cut
7446:
7447: sub scantron_bubble_selector {
7448: my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
7449: my $max=$$scan_config{'Qlength'};
7450:
7451: my $scmode=$$scan_config{'Qon'};
7452: if ($scmode eq 'number' || $scmode eq 'letter') {
7453: if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
7454: ($$scan_config{'BubblesPerRow'} > 0)) {
7455: $max=$$scan_config{'BubblesPerRow'};
7456: if (($scmode eq 'number') && ($max > 10)) {
7457: $max = 10;
7458: } elsif (($scmode eq 'letter') && $max > 26) {
7459: $max = 26;
7460: }
7461: } else {
7462: $max = 10;
7463: }
7464: }
7465:
7466: my @alphabet=('A'..'Z');
7467: $r->print(&Apache::loncommon::start_data_table().
7468: &Apache::loncommon::start_data_table_row());
7469: $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
7470: for (my $i=0;$i<$max+1;$i++) {
7471: $r->print("\n".'<td align="center">');
7472: if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
7473: else { $r->print(' '); }
7474: $r->print('</td>');
7475: }
7476: $r->print(&Apache::loncommon::end_data_table_row().
7477: &Apache::loncommon::start_data_table_row());
7478: for (my $i=0;$i<$max;$i++) {
7479: $r->print("\n".
7480: '<td><label><input type="radio" name="scantron_correct_Q_'.
7481: $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
7482: }
7483: my $nobub_checked = ' ';
7484: if ($error eq 'missingbubble') {
7485: $nobub_checked = ' checked = "checked" ';
7486: }
7487: $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
7488: $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
7489: '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
7490: $line.'" value="'.$questionnum.'" /></td>');
7491: $r->print(&Apache::loncommon::end_data_table_row().
7492: &Apache::loncommon::end_data_table());
7493: }
7494:
7495: =pod
7496:
7497: =item num_matches
7498:
7499: Counts the number of characters that are the same between the two arguments.
7500:
7501: Arguments:
7502: $orig - CODE from the scanline
7503: $code - CODE to match against
7504:
7505: Returns:
7506: $count - integer count of the number of same characters between the
7507: two arguments
7508:
7509: =cut
7510:
7511: sub num_matches {
7512: my ($orig,$code) = @_;
7513: my @code=split(//,$code);
7514: my @orig=split(//,$orig);
7515: my $same=0;
7516: for (my $i=0;$i<scalar(@code);$i++) {
7517: if ($code[$i] eq $orig[$i]) { $same++; }
7518: }
7519: return $same;
7520: }
7521:
7522: =pod
7523:
7524: =item scantron_get_closely_matching_CODEs
7525:
7526: Cycles through all CODEs and finds the set that has the greatest
7527: number of same characters as the provided CODE
7528:
7529: Arguments:
7530: $allcodes - hash ref returned by &get_codes()
7531: $CODE - CODE from the current scanline
7532:
7533: Returns:
7534: 2 element list
7535: - first elements is number of how closely matching the best fit is
7536: (5 means best set has 5 matching characters)
7537: - second element is an arrary ref containing the set of valid CODEs
7538: that best fit the passed in CODE
7539:
7540: =cut
7541:
7542: sub scantron_get_closely_matching_CODEs {
7543: my ($allcodes,$CODE)=@_;
7544: my @CODEs;
7545: foreach my $testcode (sort(keys(%{$allcodes}))) {
7546: push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
7547: }
7548:
7549: return ($#CODEs,$CODEs[-1]);
7550: }
7551:
7552: =pod
7553:
7554: =item get_codes
7555:
7556: Builds a hash which has keys of all of the valid CODEs from the selected
7557: set of remembered CODEs.
7558:
7559: Arguments:
7560: $old_name - name of the set of remembered CODEs
7561: $cdom - domain of the course
7562: $cnum - internal course name
7563:
7564: Returns:
7565: %allcodes - keys are the valid CODEs, values are all 1
7566:
7567: =cut
7568:
7569: sub get_codes {
7570: my ($old_name, $cdom, $cnum) = @_;
7571: if (!$old_name) {
7572: $old_name=$env{'form.scantron_CODElist'};
7573: }
7574: if (!$cdom) {
7575: $cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
7576: }
7577: if (!$cnum) {
7578: $cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
7579: }
7580: my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
7581: $cdom,$cnum);
7582: my %allcodes;
7583: if ($result{"type\0$old_name"} eq 'number') {
7584: %allcodes=map {($_,1)} split(',',$result{$old_name});
7585: } else {
7586: %allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
7587: }
7588: return %allcodes;
7589: }
7590:
7591: =pod
7592:
7593: =item scantron_validate_CODE
7594:
7595: Validates all scanlines in the selected file to not have any
7596: invalid or underspecified CODEs and that none of the codes are
7597: duplicated if this was requested.
7598:
7599: =cut
7600:
7601: sub scantron_validate_CODE {
7602: my ($r,$currentphase) = @_;
7603: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7604: if ($scantron_config{'CODElocation'} &&
7605: $scantron_config{'CODEstart'} &&
7606: $scantron_config{'CODElength'}) {
7607: if (!defined($env{'form.scantron_CODElist'})) {
7608: &FIXME_blow_up()
7609: }
7610: } else {
7611: return (0,$currentphase+1);
7612: }
7613:
7614: my %usedCODEs;
7615:
7616: my %allcodes=&get_codes();
7617:
7618: my $nav_error;
7619: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
7620: if ($nav_error) {
7621: $r->print(&navmap_errormsg());
7622: return(1,$currentphase);
7623: }
7624:
7625: my ($scanlines,$scan_data)=&scantron_getfile();
7626: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7627: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7628: if ($line=~/^[\s\cz]*$/) { next; }
7629: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7630: $scan_data);
7631: my $CODE=$$scan_record{'scantron.CODE'};
7632: my $error=0;
7633: if (!&Apache::lonnet::validCODE($CODE)) {
7634: &scantron_get_correction($r,$i,$scan_record,
7635: \%scantron_config,
7636: $line,'incorrectCODE',\%allcodes);
7637: return(1,$currentphase);
7638: }
7639: if (%allcodes && !exists($allcodes{$CODE})
7640: && !$$scan_record{'scantron.useCODE'}) {
7641: &scantron_get_correction($r,$i,$scan_record,
7642: \%scantron_config,
7643: $line,'incorrectCODE',\%allcodes);
7644: return(1,$currentphase);
7645: }
7646: if (exists($usedCODEs{$CODE})
7647: && $env{'form.scantron_CODEunique'} eq 'yes'
7648: && !$$scan_record{'scantron.CODE_ignore_dup'}) {
7649: &scantron_get_correction($r,$i,$scan_record,
7650: \%scantron_config,
7651: $line,'duplicateCODE',$usedCODEs{$CODE});
7652: return(1,$currentphase);
7653: }
7654: push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
7655: }
7656: return (0,$currentphase+1);
7657: }
7658:
7659: =pod
7660:
7661: =item scantron_validate_doublebubble
7662:
7663: Validates all scanlines in the selected file to not have any
7664: bubble lines with multiple bubbles marked.
7665:
7666: =cut
7667:
7668: sub scantron_validate_doublebubble {
7669: my ($r,$currentphase) = @_;
7670: #get student info
7671: my $classlist=&Apache::loncoursedata::get_classlist();
7672: my %idmap=&username_to_idmap($classlist);
7673:
7674: #get scantron line setup
7675: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7676: my ($scanlines,$scan_data)=&scantron_getfile();
7677: my $nav_error;
7678: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
7679: if ($nav_error) {
7680: $r->print(&navmap_errormsg());
7681: return(1,$currentphase);
7682: }
7683:
7684: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7685: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7686: if ($line=~/^[\s\cz]*$/) { next; }
7687: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7688: $scan_data);
7689: if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
7690: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
7691: 'doublebubble',
7692: $$scan_record{'scantron.doubleerror'});
7693: return (1,$currentphase);
7694: }
7695: return (0,$currentphase+1);
7696: }
7697:
7698:
7699: sub scantron_get_maxbubble {
7700: my ($nav_error,$scantron_config) = @_;
7701: if (defined($env{'form.scantron_maxbubble'}) &&
7702: $env{'form.scantron_maxbubble'}) {
7703: &restore_bubble_lines();
7704: return $env{'form.scantron_maxbubble'};
7705: }
7706:
7707: my (undef, undef, $sequence) =
7708: &Apache::lonnet::decode_symb($env{'form.selectpage'});
7709:
7710: my $navmap=Apache::lonnavmaps::navmap->new();
7711: unless (ref($navmap)) {
7712: if (ref($nav_error)) {
7713: $$nav_error = 1;
7714: }
7715: return;
7716: }
7717: my $map=$navmap->getResourceByUrl($sequence);
7718: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
7719: my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
7720:
7721: &Apache::lonxml::clear_problem_counter();
7722:
7723: my $uname = $env{'user.name'};
7724: my $udom = $env{'user.domain'};
7725: my $cid = $env{'request.course.id'};
7726: my $total_lines = 0;
7727: %bubble_lines_per_response = ();
7728: %first_bubble_line = ();
7729: %subdivided_bubble_lines = ();
7730: %responsetype_per_response = ();
7731:
7732: my $response_number = 0;
7733: my $bubble_line = 0;
7734: foreach my $resource (@resources) {
7735: my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
7736: $udom,undef,$bubbles_per_row);
7737: if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
7738: foreach my $part_id (@{$parts}) {
7739: my $lines;
7740:
7741: # TODO - make this a persistent hash not an array.
7742:
7743: # optionresponse, matchresponse and rankresponse type items
7744: # render as separate sub-questions in exam mode.
7745: if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
7746: ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
7747: ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
7748: my ($numbub,$numshown);
7749: if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
7750: if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
7751: $numbub = scalar(@{$analysis->{$part_id.'.options'}});
7752: }
7753: } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
7754: if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
7755: $numbub = scalar(@{$analysis->{$part_id.'.items'}});
7756: }
7757: } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
7758: if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
7759: $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
7760: }
7761: }
7762: if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
7763: $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
7764: }
7765: my $bubbles_per_row =
7766: &bubblesheet_bubbles_per_row($scantron_config);
7767: my $inner_bubble_lines = int($numbub/$bubbles_per_row);
7768: if (($numbub % $bubbles_per_row) != 0) {
7769: $inner_bubble_lines++;
7770: }
7771: for (my $i=0; $i<$numshown; $i++) {
7772: $subdivided_bubble_lines{$response_number} .=
7773: $inner_bubble_lines.',';
7774: }
7775: $subdivided_bubble_lines{$response_number} =~ s/,$//;
7776: $lines = $numshown * $inner_bubble_lines;
7777: } else {
7778: $lines = $analysis->{"$part_id.bubble_lines"};
7779: }
7780:
7781: $first_bubble_line{$response_number} = $bubble_line;
7782: $bubble_lines_per_response{$response_number} = $lines;
7783: $responsetype_per_response{$response_number} =
7784: $analysis->{$part_id.'.type'};
7785: $response_number++;
7786:
7787: $bubble_line += $lines;
7788: $total_lines += $lines;
7789: }
7790: }
7791: }
7792: &Apache::lonnet::delenv('scantron.');
7793:
7794: &save_bubble_lines();
7795: $env{'form.scantron_maxbubble'} =
7796: $total_lines;
7797: return $env{'form.scantron_maxbubble'};
7798: }
7799:
7800: sub bubblesheet_bubbles_per_row {
7801: my ($scantron_config) = @_;
7802: my $bubbles_per_row;
7803: if (ref($scantron_config) eq 'HASH') {
7804: $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
7805: }
7806: if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
7807: $bubbles_per_row = 10;
7808: }
7809: return $bubbles_per_row;
7810: }
7811:
7812: sub scantron_validate_missingbubbles {
7813: my ($r,$currentphase) = @_;
7814: #get student info
7815: my $classlist=&Apache::loncoursedata::get_classlist();
7816: my %idmap=&username_to_idmap($classlist);
7817:
7818: #get scantron line setup
7819: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7820: my ($scanlines,$scan_data)=&scantron_getfile();
7821: my $nav_error;
7822: my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
7823: if ($nav_error) {
7824: return(1,$currentphase);
7825: }
7826: if (!$max_bubble) { $max_bubble=2**31; }
7827: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7828: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7829: if ($line=~/^[\s\cz]*$/) { next; }
7830: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7831: $scan_data);
7832: if (!defined($$scan_record{'scantron.missingerror'})) { next; }
7833: my @to_correct;
7834:
7835: # Probably here's where the error is...
7836:
7837: foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
7838: my $lastbubble;
7839: if ($missing =~ /^(\d+)\.(\d+)$/) {
7840: my $question = $1;
7841: my $subquestion = $2;
7842: if (!defined($first_bubble_line{$question -1})) { next; }
7843: my $first = $first_bubble_line{$question-1};
7844: my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
7845: my $subcount = 1;
7846: while ($subcount<$subquestion) {
7847: $first += $subans[$subcount-1];
7848: $subcount ++;
7849: }
7850: my $count = $subans[$subquestion-1];
7851: $lastbubble = $first + $count;
7852: } else {
7853: if (!defined($first_bubble_line{$missing - 1})) { next; }
7854: $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
7855: }
7856: if ($lastbubble > $max_bubble) { next; }
7857: push(@to_correct,$missing);
7858: }
7859: if (@to_correct) {
7860: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
7861: $line,'missingbubble',\@to_correct);
7862: return (1,$currentphase);
7863: }
7864:
7865: }
7866: return (0,$currentphase+1);
7867: }
7868:
7869: sub hand_bubble_option {
7870: my (undef, undef, $sequence) =
7871: &Apache::lonnet::decode_symb($env{'form.selectpage'});
7872: return if ($sequence eq '');
7873: my $navmap = Apache::lonnavmaps::navmap->new();
7874: unless (ref($navmap)) {
7875: return;
7876: }
7877: my $needs_hand_bubbles;
7878: my $map=$navmap->getResourceByUrl($sequence);
7879: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
7880: foreach my $res (@resources) {
7881: if (ref($res)) {
7882: if ($res->is_problem()) {
7883: my $partlist = $res->parts();
7884: foreach my $part (@{ $partlist }) {
7885: my @types = $res->responseType($part);
7886: if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
7887: $needs_hand_bubbles = 1;
7888: last;
7889: }
7890: }
7891: }
7892: }
7893: }
7894: if ($needs_hand_bubbles) {
7895: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7896: my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
7897: return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
7898: &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 />').
7899: '<label><input type="radio" name="scantron_lastbubblepoints" value="'.$bubbles_per_row.'" checked="checked" />'.&mt('[quant,_1,point]',$bubbles_per_row).'</label> '.&mt('or').' '.
7900: '<label><input type="radio" name="scantron_lastbubblepoints" value="0"/>0 points</label></p>';
7901: }
7902: return;
7903: }
7904:
7905: sub scantron_process_students {
7906: my ($r,$symb) = @_;
7907:
7908: my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
7909: if (!$symb) {
7910: return '';
7911: }
7912: my $default_form_data=&defaultFormData($symb);
7913:
7914: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7915: my $bubbles_per_row =
7916: &bubblesheet_bubbles_per_row(\%scantron_config);
7917: my ($scanlines,$scan_data)=&scantron_getfile();
7918: my $classlist=&Apache::loncoursedata::get_classlist();
7919: my %idmap=&username_to_idmap($classlist);
7920: my $navmap=Apache::lonnavmaps::navmap->new();
7921: unless (ref($navmap)) {
7922: $r->print(&navmap_errormsg());
7923: return '';
7924: }
7925: my $map=$navmap->getResourceByUrl($sequence);
7926: my $randomorder;
7927: if (ref($map)) {
7928: $randomorder = $map->randomorder();
7929: }
7930: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
7931: my (%grader_partids_by_symb,%grader_randomlists_by_symb,%ordered);
7932: &graders_resources_pass(\@resources,\%grader_partids_by_symb,
7933: \%grader_randomlists_by_symb,$bubbles_per_row);
7934: my ($resource_error,%symb_to_resource,@master_seq);
7935: foreach my $resource (@resources) {
7936: my $ressymb;
7937: if (ref($resource)) {
7938: $ressymb = $resource->symb();
7939: push(@master_seq,$ressymb);
7940: $symb_to_resource{$ressymb} = $resource;
7941: } else {
7942: $resource_error = 1;
7943: last;
7944: }
7945: my ($analysis,$parts) =
7946: &scantron_partids_tograde($resource,$env{'request.course.id'},
7947: $env{'user.name'},$env{'user.domain'},
7948: 1,$bubbles_per_row);
7949: $grader_partids_by_symb{$ressymb} = $parts;
7950: if (ref($analysis) eq 'HASH') {
7951: if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
7952: $grader_randomlists_by_symb{$ressymb} =
7953: $analysis->{'parts_withrandomlist'};
7954: }
7955: }
7956: }
7957: if ($resource_error) {
7958: $r->print(&navmap_errormsg());
7959: return '';
7960: }
7961:
7962: my ($uname,$udom);
7963: my $result= <<SCANTRONFORM;
7964: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
7965: <input type="hidden" name="command" value="scantron_configphase" />
7966: $default_form_data
7967: SCANTRONFORM
7968: $r->print($result);
7969:
7970: my @delayqueue;
7971: my (%completedstudents,%scandata);
7972:
7973: my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
7974: my $count=&get_todo_count($scanlines,$scan_data);
7975: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
7976: &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
7977: $r->print('<br />');
7978: my $start=&Time::HiRes::time();
7979: my $i=-1;
7980: my $started;
7981:
7982: my $nav_error;
7983: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
7984: if ($nav_error) {
7985: $r->print(&navmap_errormsg());
7986: return '';
7987: }
7988:
7989: # If an ssi failed in scantron_get_maxbubble, put an error message out to
7990: # the user and return.
7991:
7992: if ($ssi_error) {
7993: $r->print("</form>");
7994: &ssi_print_error($r);
7995: &Apache::lonnet::remove_lock($lock);
7996: return ''; # Dunno why the other returns return '' rather than just returning.
7997: }
7998:
7999: my %lettdig = &letter_to_digits();
8000: my $numletts = scalar(keys(%lettdig));
8001:
8002: while ($i<$scanlines->{'count'}) {
8003: ($uname,$udom)=('','');
8004: $i++;
8005: my $line=&scantron_get_line($scanlines,$scan_data,$i);
8006: if ($line=~/^[\s\cz]*$/) { next; }
8007: if ($started) {
8008: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
8009: }
8010: $started=1;
8011: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
8012: $scan_data);
8013: unless ($uname=&scantron_find_student($scan_record,$scan_data,
8014: \%idmap,$i)) {
8015: &scantron_add_delay(\@delayqueue,$line,
8016: 'Unable to find a student that matches',1);
8017: next;
8018: }
8019: if (exists $completedstudents{$uname}) {
8020: &scantron_add_delay(\@delayqueue,$line,
8021: 'Student '.$uname.' has multiple sheets',2);
8022: next;
8023: }
8024: my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
8025: my $user = $uname.':'.$usec;
8026: ($uname,$udom)=split(/:/,$uname);
8027:
8028: my $scancode;
8029: if ((exists($scan_record->{'scantron.CODE'})) &&
8030: (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
8031: $scancode = $scan_record->{'scantron.CODE'};
8032: } else {
8033: $scancode = '';
8034: }
8035:
8036: my @mapresources = @resources;
8037: if ($randomorder) {
8038: @mapresources =
8039: &users_order($user,$scancode,$sequence,\@master_seq,\%ordered,
8040: \%symb_to_resource);
8041: }
8042: my (%partids_by_symb,$res_error);
8043: foreach my $resource (@mapresources) {
8044: my $ressymb;
8045: if (ref($resource)) {
8046: $ressymb = $resource->symb();
8047: } else {
8048: $res_error = 1;
8049: last;
8050: }
8051: if ((exists($grader_randomlists_by_symb{$ressymb})) ||
8052: (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
8053: my ($analysis,$parts) =
8054: &scantron_partids_tograde($resource,$env{'request.course.id'},
8055: $uname,$udom,undef,$bubbles_per_row);
8056: $partids_by_symb{$ressymb} = $parts;
8057: } else {
8058: $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
8059: }
8060: }
8061:
8062: if ($res_error) {
8063: &scantron_add_delay(\@delayqueue,$line,
8064: 'An error occurred while grading student '.$uname,2);
8065: next;
8066: }
8067:
8068: &Apache::lonxml::clear_problem_counter();
8069: &Apache::lonnet::appenv($scan_record);
8070:
8071: if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
8072: &scantron_putfile($scanlines,$scan_data);
8073: }
8074:
8075: if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
8076: \@mapresources,\%partids_by_symb,
8077: $bubbles_per_row) eq 'ssi_error') {
8078: $ssi_error = 0; # So end of handler error message does not trigger.
8079: $r->print("</form>");
8080: &ssi_print_error($r);
8081: &Apache::lonnet::remove_lock($lock);
8082: return ''; # Why return ''? Beats me.
8083: }
8084:
8085: $completedstudents{$uname}={'line'=>$line};
8086: if ($env{'form.verifyrecord'}) {
8087: my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
8088: my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
8089: chomp($studentdata);
8090: $studentdata =~ s/\r$//;
8091: my $studentrecord = '';
8092: my $counter = -1;
8093: foreach my $resource (@mapresources) {
8094: my $ressymb = $resource->symb();
8095: ($counter,my $recording) =
8096: &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
8097: $counter,$studentdata,$partids_by_symb{$ressymb},
8098: \%scantron_config,\%lettdig,$numletts);
8099: $studentrecord .= $recording;
8100: }
8101: if ($studentrecord ne $studentdata) {
8102: &Apache::lonxml::clear_problem_counter();
8103: if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
8104: \@mapresources,\%partids_by_symb,
8105: $bubbles_per_row) eq 'ssi_error') {
8106: $ssi_error = 0; # So end of handler error message does not trigger.
8107: $r->print("</form>");
8108: &ssi_print_error($r);
8109: &Apache::lonnet::remove_lock($lock);
8110: delete($completedstudents{$uname});
8111: return '';
8112: }
8113: $counter = -1;
8114: $studentrecord = '';
8115: foreach my $resource (@mapresources) {
8116: my $ressymb = $resource->symb();
8117: ($counter,my $recording) =
8118: &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
8119: $counter,$studentdata,$partids_by_symb{$ressymb},
8120: \%scantron_config,\%lettdig,$numletts);
8121: $studentrecord .= $recording;
8122: }
8123: if ($studentrecord ne $studentdata) {
8124: $r->print('<p><span class="LC_warning">');
8125: if ($scancode eq '') {
8126: $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
8127: $uname.':'.$udom,$scan_record->{'scantron.ID'}));
8128: } else {
8129: $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
8130: $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
8131: }
8132: $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
8133: &Apache::loncommon::start_data_table_header_row()."\n".
8134: '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
8135: &Apache::loncommon::end_data_table_header_row()."\n".
8136: &Apache::loncommon::start_data_table_row().
8137: '<td>'.&mt('Bubblesheet').'</td>'.
8138: '<td><span class="LC_nobreak"><tt>'.$studentdata.'</tt></span></td>'.
8139: &Apache::loncommon::end_data_table_row().
8140: &Apache::loncommon::start_data_table_row().
8141: '<td>'.&mt('Stored submissions').'</td>'.
8142: '<td><span class="LC_nobreak"><tt>'.$studentrecord.'</tt></span></td>'."\n".
8143: &Apache::loncommon::end_data_table_row().
8144: &Apache::loncommon::end_data_table().'</p>');
8145: } else {
8146: $r->print('<br /><span class="LC_warning">'.
8147: &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 />'.
8148: &mt("As a consequence, this user's submission history records two tries.").
8149: '</span><br />');
8150: }
8151: }
8152: }
8153: if (&Apache::loncommon::connection_aborted($r)) { last; }
8154: } continue {
8155: &Apache::lonxml::clear_problem_counter();
8156: &Apache::lonnet::delenv('scantron.');
8157: }
8158: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
8159: &Apache::lonnet::remove_lock($lock);
8160: # my $lasttime = &Time::HiRes::time()-$start;
8161: # $r->print("<p>took $lasttime</p>");
8162:
8163: $r->print("</form>");
8164: return '';
8165: }
8166:
8167: sub graders_resources_pass {
8168: my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
8169: $bubbles_per_row) = @_;
8170: if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) &&
8171: (ref($grader_randomlists_by_symb) eq 'HASH')) {
8172: foreach my $resource (@{$resources}) {
8173: my $ressymb = $resource->symb();
8174: my ($analysis,$parts) =
8175: &scantron_partids_tograde($resource,$env{'request.course.id'},
8176: $env{'user.name'},$env{'user.domain'},
8177: 1,$bubbles_per_row);
8178: $grader_partids_by_symb->{$ressymb} = $parts;
8179: if (ref($analysis) eq 'HASH') {
8180: if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
8181: $grader_randomlists_by_symb->{$ressymb} =
8182: $analysis->{'parts_withrandomlist'};
8183: }
8184: }
8185: }
8186: }
8187: return;
8188: }
8189:
8190: =pod
8191:
8192: =item users_order
8193:
8194: Returns array of resources in current map, ordered based on either CODE,
8195: if this is a CODEd exam, or based on student's identity if this is a
8196: "NAMEd" exam.
8197:
8198: Should be used when randomorder applied when the corresponding exam was
8199: printed, prior to students completing bubblesheets for the version of the
8200: exam the student received.
8201:
8202: =cut
8203:
8204: sub users_order {
8205: my ($user,$scancode,$mapurl,$master_seq,$ordered,$symb_to_resource) = @_;
8206: my @mapresources;
8207: unless ((ref($ordered) eq 'HASH') && (ref($symb_to_resource) eq 'HASH')) {
8208: return @mapresources;
8209: }
8210: if (($scancode) && (ref($ordered->{$scancode}) eq 'ARRAY')) {
8211: @mapresources = @{$ordered->{$scancode}};
8212: } elsif ($scancode) {
8213: $env{'form.CODE'} = $scancode;
8214: my $actual_seq =
8215: &Apache::lonprintout::master_seq_to_person_seq($mapurl,
8216: $master_seq,
8217: $user,$scancode,1);
8218: if (ref($actual_seq) eq 'ARRAY') {
8219: @{$ordered->{$scancode}} =
8220: map { $symb_to_resource->{$_}; } @{$actual_seq};
8221: @mapresources = @{$ordered->{$scancode}};
8222: }
8223: delete($env{'form.CODE'});
8224: } else {
8225: my $actual_seq =
8226: &Apache::lonprintout::master_seq_to_person_seq($mapurl,
8227: $master_seq,
8228: $user,undef,1);
8229: if (ref($actual_seq) eq 'ARRAY') {
8230: @mapresources =
8231: map { $symb_to_resource->{$_}; } @{$actual_seq};
8232: }
8233: }
8234: return @mapresources;
8235: }
8236:
8237: sub grade_student_bubbles {
8238: my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row) = @_;
8239: if (ref($resources) eq 'ARRAY') {
8240: my $count = 0;
8241: foreach my $resource (@{$resources}) {
8242: my $ressymb = $resource->symb();
8243: my %form = ('submitted' => 'scantron',
8244: 'grade_target' => 'grade',
8245: 'grade_username' => $uname,
8246: 'grade_domain' => $udom,
8247: 'grade_courseid' => $env{'request.course.id'},
8248: 'grade_symb' => $ressymb,
8249: 'CODE' => $scancode
8250: );
8251: if ($bubbles_per_row ne '') {
8252: $form{'bubbles_per_row'} = $bubbles_per_row;
8253: }
8254: if ($env{'form.scantron_lastbubblepoints'} ne '') {
8255: $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
8256: }
8257: if (ref($parts) eq 'HASH') {
8258: if (ref($parts->{$ressymb}) eq 'ARRAY') {
8259: foreach my $part (@{$parts->{$ressymb}}) {
8260: $form{'scantron_questnum_start.'.$part} =
8261: 1+$env{'form.scantron.first_bubble_line.'.$count};
8262: $count++;
8263: }
8264: }
8265: }
8266: my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
8267: return 'ssi_error' if ($ssi_error);
8268: last if (&Apache::loncommon::connection_aborted($r));
8269: }
8270: }
8271: return;
8272: }
8273:
8274: sub scantron_upload_scantron_data {
8275: my ($r,$symb)=@_;
8276: my $dom = $env{'request.role.domain'};
8277: my $domdesc = &Apache::lonnet::domain($dom,'description');
8278: $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
8279: my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
8280: 'domainid',
8281: 'coursename',$dom);
8282: my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
8283: (' 'x2).&mt('(shows course personnel)');
8284: my $default_form_data=&defaultFormData($symb);
8285: my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
8286: 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.");
8287: $r->print(&Apache::lonhtmlcommon::scripttag('
8288: function checkUpload(formname) {
8289: if (formname.upfile.value == "") {
8290: alert("'.$nofile_alert.'");
8291: return false;
8292: }
8293: if (formname.courseid.value == "") {
8294: alert("'.$nocourseid_alert.'");
8295: return false;
8296: }
8297: formname.submit();
8298: }
8299:
8300: function ToSyllabus() {
8301: var cdom = '."'$dom'".';
8302: var cnum = document.rules.courseid.value;
8303: if (cdom == "" || cdom == null) {
8304: return;
8305: }
8306: if (cnum == "" || cnum == null) {
8307: return;
8308: }
8309: syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
8310: "height=350,width=350,scrollbars=yes,menubar=no");
8311: return;
8312: }
8313:
8314: '));
8315: $r->print('
8316: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
8317:
8318: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
8319: '.$default_form_data.
8320: &Apache::lonhtmlcommon::start_pick_box().
8321: &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
8322: '<input name="courseid" type="text" size="30" />'.$select_link.
8323: &Apache::lonhtmlcommon::row_closure().
8324: &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
8325: '<input name="coursename" type="text" size="30" />'.$syllabuslink.
8326: &Apache::lonhtmlcommon::row_closure().
8327: &Apache::lonhtmlcommon::row_title(&mt('Domain')).
8328: '<input name="domainid" type="hidden" />'.$domdesc.
8329: &Apache::lonhtmlcommon::row_closure().
8330: &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
8331: '<input type="file" name="upfile" size="50" />'.
8332: &Apache::lonhtmlcommon::row_closure(1).
8333: &Apache::lonhtmlcommon::end_pick_box().'<br />
8334:
8335: <input name="command" value="scantronupload_save" type="hidden" />
8336: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
8337: </form>
8338: ');
8339: return '';
8340: }
8341:
8342:
8343: sub scantron_upload_scantron_data_save {
8344: my($r,$symb)=@_;
8345: my $doanotherupload=
8346: '<br /><form action="/adm/grades" method="post">'."\n".
8347: '<input type="hidden" name="command" value="scantronupload" />'."\n".
8348: '<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
8349: '</form>'."\n";
8350: if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
8351: !&Apache::lonnet::allowed('usc',
8352: $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
8353: $r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
8354: unless ($symb) {
8355: $r->print($doanotherupload);
8356: }
8357: return '';
8358: }
8359: my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
8360: my $uploadedfile;
8361: $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
8362: if (length($env{'form.upfile'}) < 2) {
8363: $r->print(&mt('[_1]Error:[_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.','<span class="LC_error">','</span>','<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
8364: } else {
8365: my $result =
8366: &Apache::lonnet::userfileupload('upfile','','scantron','','','',
8367: $env{'form.courseid'},$env{'form.domainid'});
8368: if ($result =~ m{^/uploaded/}) {
8369: $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
8370: '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
8371: '<span class="LC_filename">'.$result.'</span>'));
8372: ($uploadedfile) = ($result =~ m{/([^/]+)$});
8373: $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
8374: $env{'form.courseid'},$uploadedfile));
8375: } else {
8376: $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
8377: '<span class="LC_error">','</span>',$result,
8378: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
8379: }
8380: }
8381: if ($symb) {
8382: $r->print(&scantron_selectphase($r,$uploadedfile,$symb));
8383: } else {
8384: $r->print($doanotherupload);
8385: }
8386: return '';
8387: }
8388:
8389: sub validate_uploaded_scantron_file {
8390: my ($cdom,$cname,$fname) = @_;
8391: my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
8392: my @lines;
8393: if ($scanlines ne '-1') {
8394: @lines=split("\n",$scanlines,-1);
8395: }
8396: my $output;
8397: if (@lines) {
8398: my (%counts,$max_match_format);
8399: my ($max_match_count,$max_match_pct) = (0,0);
8400: my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
8401: my %idmap = &username_to_idmap($classlist);
8402: foreach my $key (keys(%idmap)) {
8403: my $lckey = lc($key);
8404: $idmap{$lckey} = $idmap{$key};
8405: }
8406: my %unique_formats;
8407: my @formatlines = &get_scantronformat_file();
8408: foreach my $line (@formatlines) {
8409: chomp($line);
8410: my @config = split(/:/,$line);
8411: my $idstart = $config[5];
8412: my $idlength = $config[6];
8413: if (($idstart ne '') && ($idlength > 0)) {
8414: if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
8415: push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]);
8416: } else {
8417: $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
8418: }
8419: }
8420: }
8421: foreach my $key (keys(%unique_formats)) {
8422: my ($idstart,$idlength) = split(':',$key);
8423: %{$counts{$key}} = (
8424: 'found' => 0,
8425: 'total' => 0,
8426: );
8427: foreach my $line (@lines) {
8428: next if ($line =~ /^#/);
8429: next if ($line =~ /^[\s\cz]*$/);
8430: my $id = substr($line,$idstart-1,$idlength);
8431: $id = lc($id);
8432: if (exists($idmap{$id})) {
8433: $counts{$key}{'found'} ++;
8434: }
8435: $counts{$key}{'total'} ++;
8436: }
8437: if ($counts{$key}{'total'}) {
8438: my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
8439: if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
8440: $max_match_pct = $percent_match;
8441: $max_match_format = $key;
8442: $max_match_count = $counts{$key}{'total'};
8443: }
8444: }
8445: }
8446: if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
8447: my $format_descs;
8448: my $numwithformat = @{$unique_formats{$max_match_format}};
8449: for (my $i=0; $i<$numwithformat; $i++) {
8450: my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
8451: if ($i<$numwithformat-2) {
8452: $format_descs .= '"<i>'.$desc.'</i>", ';
8453: } elsif ($i==$numwithformat-2) {
8454: $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
8455: } elsif ($i==$numwithformat-1) {
8456: $format_descs .= '"<i>'.$desc.'</i>"';
8457: }
8458: }
8459: my $showpct = sprintf("%.0f",$max_match_pct).'%';
8460: $output .= '<br />'.&mt('Comparison of student IDs in the uploaded file with the course roster found matches for [_1] of the [_2] entries in the file (for the format defined for [_3]).','<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
8461: '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
8462: '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
8463: '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
8464: '<i>'.$cdom.'</i>').'</li>'.
8465: '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
8466: '<li>'.&mt('The course roster is not up to date').'</li>'.
8467: '</ul>';
8468: }
8469: } else {
8470: $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
8471: }
8472: return $output;
8473: }
8474:
8475: sub valid_file {
8476: my ($requested_file)=@_;
8477: foreach my $filename (sort(&scantron_filenames())) {
8478: if ($requested_file eq $filename) { return 1; }
8479: }
8480: return 0;
8481: }
8482:
8483: sub scantron_download_scantron_data {
8484: my ($r,$symb)=@_;
8485: my $default_form_data=&defaultFormData($symb);
8486: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
8487: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
8488: my $file=$env{'form.scantron_selectfile'};
8489: if (! &valid_file($file)) {
8490: $r->print('
8491: <p>
8492: '.&mt('The requested filename was invalid.').'
8493: </p>
8494: ');
8495: return;
8496: }
8497: my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
8498: my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
8499: my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
8500: &Apache::lonnet::allowuploaded('/adm/grades',$orig);
8501: &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
8502: &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
8503: $r->print('
8504: <p>
8505: '.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
8506: '<a href="'.$orig.'">','</a>').'
8507: </p>
8508: <p>
8509: '.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
8510: '<a href="'.$corrected.'">','</a>').'
8511: </p>
8512: <p>
8513: '.&mt('[_1]Skipped[_2], a file of records that were skipped.',
8514: '<a href="'.$skipped.'">','</a>').'
8515: </p>
8516: ');
8517: return '';
8518: }
8519:
8520: sub checkscantron_results {
8521: my ($r,$symb) = @_;
8522: if (!$symb) {return '';}
8523: my $cid = $env{'request.course.id'};
8524: my %lettdig = &letter_to_digits();
8525: my $numletts = scalar(keys(%lettdig));
8526: my $cnum = $env{'course.'.$cid.'.num'};
8527: my $cdom = $env{'course.'.$cid.'.domain'};
8528: my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
8529: my %record;
8530: my %scantron_config =
8531: &Apache::grades::get_scantron_config($env{'form.scantron_format'});
8532: my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
8533: my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
8534: my $classlist=&Apache::loncoursedata::get_classlist();
8535: my %idmap=&Apache::grades::username_to_idmap($classlist);
8536: my $navmap=Apache::lonnavmaps::navmap->new();
8537: unless (ref($navmap)) {
8538: $r->print(&navmap_errormsg());
8539: return '';
8540: }
8541: my $map=$navmap->getResourceByUrl($sequence);
8542: my ($randomorder,@master_seq,%symb_to_resource);
8543: if (ref($map)) {
8544: $randomorder=$map->randomorder();
8545: }
8546: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
8547: foreach my $resource (@resources) {
8548: if (ref($resource)) {
8549: my $ressymb = $resource->symb();
8550: push(@master_seq,$ressymb);
8551: $symb_to_resource{$ressymb} = $resource;
8552: }
8553: }
8554: my (%grader_partids_by_symb,%grader_randomlists_by_symb);
8555: &graders_resources_pass(\@resources,\%grader_partids_by_symb,
8556: \%grader_randomlists_by_symb,$bubbles_per_row);
8557: my ($uname,$udom);
8558: my (%scandata,%lastname,%bylast);
8559: $r->print('
8560: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
8561:
8562: my @delayqueue;
8563: my %completedstudents;
8564:
8565: my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
8566: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
8567: my ($username,$domain,$started,%ordered);
8568: my $nav_error;
8569: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
8570: if ($nav_error) {
8571: $r->print(&navmap_errormsg());
8572: return '';
8573: }
8574:
8575: &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
8576: my $start=&Time::HiRes::time();
8577: my $i=-1;
8578:
8579: while ($i<$scanlines->{'count'}) {
8580: ($username,$domain,$uname)=('','','');
8581: $i++;
8582: my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
8583: if ($line=~/^[\s\cz]*$/) { next; }
8584: if ($started) {
8585: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
8586: }
8587: $started=1;
8588: my $scan_record=
8589: &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
8590: $scan_data);
8591: unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
8592: \%idmap,$i)) {
8593: &Apache::grades::scantron_add_delay(\@delayqueue,$line,
8594: 'Unable to find a student that matches',1);
8595: next;
8596: }
8597: if (exists $completedstudents{$uname}) {
8598: &Apache::grades::scantron_add_delay(\@delayqueue,$line,
8599: 'Student '.$uname.' has multiple sheets',2);
8600: next;
8601: }
8602: my $pid = $scan_record->{'scantron.ID'};
8603: $lastname{$pid} = $scan_record->{'scantron.LastName'};
8604: push(@{$bylast{$lastname{$pid}}},$pid);
8605: my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
8606: $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
8607: chomp($scandata{$pid});
8608: $scandata{$pid} =~ s/\r$//;
8609: my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
8610: my $user = $uname.':'.$usec;
8611: ($username,$domain)=split(/:/,$uname);
8612:
8613: my $scancode;
8614: if ((exists($scan_record->{'scantron.CODE'})) &&
8615: (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
8616: $scancode = $scan_record->{'scantron.CODE'};
8617: } else {
8618: $scancode = '';
8619: }
8620:
8621: my @mapresources = @resources;
8622: if ($randomorder) {
8623: @mapresources =
8624: &users_order($user,$scancode,$sequence,\@master_seq,\%ordered,
8625: \%symb_to_resource);
8626: }
8627: my $counter = -1;
8628: foreach my $resource (@mapresources) {
8629: my $parts;
8630: my $ressymb = $resource->symb();
8631: if ((exists($grader_randomlists_by_symb{$ressymb})) ||
8632: (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
8633: (my $analysis,$parts) =
8634: &scantron_partids_tograde($resource,$env{'request.course.id'},
8635: $username,$domain,undef,
8636: $bubbles_per_row);
8637: } else {
8638: $parts = $grader_partids_by_symb{$ressymb};
8639: }
8640: ($counter,my $recording) =
8641: &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
8642: $scandata{$pid},$parts,
8643: \%scantron_config,\%lettdig,$numletts);
8644: $record{$pid} .= $recording;
8645: }
8646: }
8647: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
8648: $r->print('<br />');
8649: my ($okstudents,$badstudents,$numstudents,$passed,$failed);
8650: $passed = 0;
8651: $failed = 0;
8652: $numstudents = 0;
8653: foreach my $last (sort(keys(%bylast))) {
8654: if (ref($bylast{$last}) eq 'ARRAY') {
8655: foreach my $pid (sort(@{$bylast{$last}})) {
8656: my $showscandata = $scandata{$pid};
8657: my $showrecord = $record{$pid};
8658: $showscandata =~ s/\s/ /g;
8659: $showrecord =~ s/\s/ /g;
8660: if ($scandata{$pid} eq $record{$pid}) {
8661: my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
8662: $okstudents .= '<tr class="'.$css_class.'">'.
8663: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
8664: '</tr>'."\n".
8665: '<tr class="'.$css_class.'">'."\n".
8666: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
8667: $passed ++;
8668: } else {
8669: my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
8670: $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".
8671: '</tr>'."\n".
8672: '<tr class="'.$css_class.'">'."\n".
8673: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
8674: '</tr>'."\n";
8675: $failed ++;
8676: }
8677: $numstudents ++;
8678: }
8679: }
8680: }
8681: $r->print(
8682: '<p>'
8683: .&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).',
8684: '<b>',
8685: $numstudents,
8686: '</b>',
8687: $env{'form.scantron_maxbubble'})
8688: .'</p>'
8689: );
8690: $r->print('<p>'
8691: .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
8692: .'<br />'
8693: .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
8694: .'</p>'
8695: );
8696: if ($passed) {
8697: $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
8698: $r->print(&Apache::loncommon::start_data_table()."\n".
8699: &Apache::loncommon::start_data_table_header_row()."\n".
8700: '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
8701: &Apache::loncommon::end_data_table_header_row()."\n".
8702: $okstudents."\n".
8703: &Apache::loncommon::end_data_table().'<br />');
8704: }
8705: if ($failed) {
8706: $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
8707: $r->print(&Apache::loncommon::start_data_table()."\n".
8708: &Apache::loncommon::start_data_table_header_row()."\n".
8709: '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
8710: &Apache::loncommon::end_data_table_header_row()."\n".
8711: $badstudents."\n".
8712: &Apache::loncommon::end_data_table()).'<br />'.
8713: &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.');
8714: }
8715: $r->print('</form><br />');
8716: return;
8717: }
8718:
8719: sub verify_scantron_grading {
8720: my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
8721: $scantron_config,$lettdig,$numletts) = @_;
8722: my ($record,%expected,%startpos);
8723: return ($counter,$record) if (!ref($resource));
8724: return ($counter,$record) if (!$resource->is_problem());
8725: my $symb = $resource->symb();
8726: return ($counter,$record) if (ref($partids) ne 'ARRAY');
8727: foreach my $part_id (@{$partids}) {
8728: $counter ++;
8729: $expected{$part_id} = 0;
8730: if ($env{"form.scantron.sub_bubblelines.$counter"}) {
8731: my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
8732: foreach my $item (@sub_lines) {
8733: $expected{$part_id} += $item;
8734: }
8735: } else {
8736: $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
8737: }
8738: $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
8739: }
8740: if ($symb) {
8741: my %recorded;
8742: my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
8743: if ($returnhash{'version'}) {
8744: my %lasthash=();
8745: my $version;
8746: for ($version=1;$version<=$returnhash{'version'};$version++) {
8747: foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
8748: $lasthash{$key}=$returnhash{$version.':'.$key};
8749: }
8750: }
8751: foreach my $key (keys(%lasthash)) {
8752: if ($key =~ /\.scantron$/) {
8753: my $value = &unescape($lasthash{$key});
8754: my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
8755: if ($value eq '') {
8756: for (my $i=0; $i<$expected{$part_id}; $i++) {
8757: for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
8758: $recorded{$part_id} .= $scantron_config->{'Qoff'};
8759: }
8760: }
8761: } else {
8762: my @tocheck;
8763: my @items = split(//,$value);
8764: if (($scantron_config->{'Qon'} eq 'letter') ||
8765: ($scantron_config->{'Qon'} eq 'number')) {
8766: if (@items < $expected{$part_id}) {
8767: my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
8768: my @singles = split(//,$fragment);
8769: foreach my $pos (@singles) {
8770: if ($pos eq ' ') {
8771: push(@tocheck,$pos);
8772: } else {
8773: my $next = shift(@items);
8774: push(@tocheck,$next);
8775: }
8776: }
8777: } else {
8778: @tocheck = @items;
8779: }
8780: foreach my $letter (@tocheck) {
8781: if ($scantron_config->{'Qon'} eq 'letter') {
8782: if ($letter !~ /^[A-J]$/) {
8783: $letter = $scantron_config->{'Qoff'};
8784: }
8785: $recorded{$part_id} .= $letter;
8786: } elsif ($scantron_config->{'Qon'} eq 'number') {
8787: my $digit;
8788: if ($letter !~ /^[A-J]$/) {
8789: $digit = $scantron_config->{'Qoff'};
8790: } else {
8791: $digit = $lettdig->{$letter};
8792: }
8793: $recorded{$part_id} .= $digit;
8794: }
8795: }
8796: } else {
8797: @tocheck = @items;
8798: for (my $i=0; $i<$expected{$part_id}; $i++) {
8799: my $curr_sub = shift(@tocheck);
8800: my $digit;
8801: if ($curr_sub =~ /^[A-J]$/) {
8802: $digit = $lettdig->{$curr_sub}-1;
8803: }
8804: if ($curr_sub eq 'J') {
8805: $digit += scalar($numletts);
8806: }
8807: for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
8808: if ($j == $digit) {
8809: $recorded{$part_id} .= $scantron_config->{'Qon'};
8810: } else {
8811: $recorded{$part_id} .= $scantron_config->{'Qoff'};
8812: }
8813: }
8814: }
8815: }
8816: }
8817: }
8818: }
8819: }
8820: foreach my $part_id (@{$partids}) {
8821: if ($recorded{$part_id} eq '') {
8822: for (my $i=0; $i<$expected{$part_id}; $i++) {
8823: for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
8824: $recorded{$part_id} .= $scantron_config->{'Qoff'};
8825: }
8826: }
8827: }
8828: $record .= $recorded{$part_id};
8829: }
8830: }
8831: return ($counter,$record);
8832: }
8833:
8834: sub letter_to_digits {
8835: my %lettdig = (
8836: A => 1,
8837: B => 2,
8838: C => 3,
8839: D => 4,
8840: E => 5,
8841: F => 6,
8842: G => 7,
8843: H => 8,
8844: I => 9,
8845: J => 0,
8846: );
8847: return %lettdig;
8848: }
8849:
8850:
8851: #-------- end of section for handling grading scantron forms -------
8852: #
8853: #-------------------------------------------------------------------
8854:
8855: #-------------------------- Menu interface -------------------------
8856: #
8857: #--- Href with symb and command ---
8858:
8859: sub href_symb_cmd {
8860: my ($symb,$cmd)=@_;
8861: return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&command='.$cmd;
8862: }
8863:
8864: sub grading_menu {
8865: my ($request,$symb) = @_;
8866: if (!$symb) {return '';}
8867:
8868: my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
8869: 'command'=>'individual');
8870:
8871: my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
8872:
8873: $fields{'command'}='ungraded';
8874: my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
8875:
8876: $fields{'command'}='table';
8877: my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
8878:
8879: $fields{'command'}='all_for_one';
8880: my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
8881:
8882: $fields{'command'}='downloadfilesselect';
8883: my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
8884:
8885: $fields{'command'} = 'csvform';
8886: my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
8887:
8888: $fields{'command'} = 'processclicker';
8889: my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
8890:
8891: $fields{'command'} = 'scantron_selectphase';
8892: my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
8893:
8894: $fields{'command'} = 'initialverifyreceipt';
8895: my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
8896:
8897: my @menu = ({ categorytitle=>'Hand Grading',
8898: items =>[
8899: { linktext => 'Select individual students to grade',
8900: url => $url1a,
8901: permission => 'F',
8902: icon => 'grade_students.png',
8903: linktitle => 'Grade current resource for a selection of students.'
8904: },
8905: { linktext => 'Grade ungraded submissions.',
8906: url => $url1b,
8907: permission => 'F',
8908: icon => 'ungrade_sub.png',
8909: linktitle => 'Grade all submissions that have not been graded yet.'
8910: },
8911:
8912: { linktext => 'Grading table',
8913: url => $url1c,
8914: permission => 'F',
8915: icon => 'grading_table.png',
8916: linktitle => 'Grade current resource for all students.'
8917: },
8918: { linktext => 'Grade page/folder for one student',
8919: url => $url1d,
8920: permission => 'F',
8921: icon => 'grade_PageFolder.png',
8922: linktitle => 'Grade all resources in current page/sequence/folder for one student.'
8923: },
8924: { linktext => 'Download submissions',
8925: url => $url1e,
8926: permission => 'F',
8927: icon => 'download_sub.png',
8928: linktitle => 'Download all students submissions.'
8929: }]},
8930: { categorytitle=>'Automated Grading',
8931: items =>[
8932:
8933: { linktext => 'Upload Scores',
8934: url => $url2,
8935: permission => 'F',
8936: icon => 'uploadscores.png',
8937: linktitle => 'Specify a file containing the class scores for current resource.'
8938: },
8939: { linktext => 'Process Clicker',
8940: url => $url3,
8941: permission => 'F',
8942: icon => 'addClickerInfoFile.png',
8943: linktitle => 'Specify a file containing the clicker information for this resource.'
8944: },
8945: { linktext => 'Grade/Manage/Review Bubblesheets',
8946: url => $url4,
8947: permission => 'F',
8948: icon => 'bubblesheet.png',
8949: linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
8950: },
8951: { linktext => 'Verify Receipt Number',
8952: url => $url5,
8953: permission => 'F',
8954: icon => 'receipt_number.png',
8955: linktitle => 'Verify a system-generated receipt number for correct problem solution.'
8956: }
8957:
8958: ]
8959: });
8960:
8961: # Create the menu
8962: my $Str;
8963: $Str .= '<form method="post" action="" name="gradingMenu">';
8964: $Str .= '<input type="hidden" name="command" value="" />'.
8965: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
8966:
8967: $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
8968: return $Str;
8969: }
8970:
8971:
8972: sub ungraded {
8973: my ($request)=@_;
8974: &submit_options($request);
8975: }
8976:
8977: sub submit_options_sequence {
8978: my ($request,$symb) = @_;
8979: if (!$symb) {return '';}
8980: &commonJSfunctions($request);
8981: my $result;
8982:
8983: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
8984: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
8985: $result.=&selectfield(0).
8986: '<input type="hidden" name="command" value="pickStudentPage" />
8987: <div>
8988: <input type="submit" value="'.&mt('Next').' →" />
8989: </div>
8990: </div>
8991: </form>';
8992: return $result;
8993: }
8994:
8995: sub submit_options_table {
8996: my ($request,$symb) = @_;
8997: if (!$symb) {return '';}
8998: &commonJSfunctions($request);
8999: my $result;
9000:
9001: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
9002: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
9003:
9004: $result.=&selectfield(0).
9005: '<input type="hidden" name="command" value="viewgrades" />
9006: <div>
9007: <input type="submit" value="'.&mt('Next').' →" />
9008: </div>
9009: </div>
9010: </form>';
9011: return $result;
9012: }
9013:
9014: sub submit_options_download {
9015: my ($request,$symb) = @_;
9016: if (!$symb) {return '';}
9017:
9018: &commonJSfunctions($request);
9019:
9020: my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
9021: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
9022: $result.='
9023: <h2>
9024: '.&mt('Select Students for Which to Download Submissions').'
9025: </h2>'.&selectfield(1).'
9026: <input type="hidden" name="command" value="downloadfileslink" />
9027: <input type="submit" value="'.&mt('Next').' →" />
9028: </div>
9029: </div>
9030:
9031:
9032: </form>';
9033: return $result;
9034: }
9035:
9036: #--- Displays the submissions first page -------
9037: sub submit_options {
9038: my ($request,$symb) = @_;
9039: if (!$symb) {return '';}
9040:
9041: &commonJSfunctions($request);
9042: my $result;
9043:
9044: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
9045: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
9046: $result.=&selectfield(1).'
9047: <input type="hidden" name="command" value="submission" />
9048: <input type="submit" value="'.&mt('Next').' →" />
9049: </div>
9050: </div>
9051:
9052:
9053: </form>';
9054: return $result;
9055: }
9056:
9057: sub selectfield {
9058: my ($full)=@_;
9059: my %options =
9060: (&Apache::lonlocal::texthash(
9061: 'yes' => 'with submissions',
9062: 'queued' => 'in grading queue',
9063: 'graded' => 'with ungraded submissions',
9064: 'incorrect' => 'with incorrect submissions',
9065: 'all' => 'with any status'),
9066: 'select_form_order' => ['yes','queued','graded','incorrect','all']);
9067: my $result='<div class="LC_columnSection">
9068:
9069: <fieldset>
9070: <legend>
9071: '.&mt('Sections').'
9072: </legend>
9073: '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
9074: </fieldset>
9075:
9076: <fieldset>
9077: <legend>
9078: '.&mt('Groups').'
9079: </legend>
9080: '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
9081: </fieldset>
9082:
9083: <fieldset>
9084: <legend>
9085: '.&mt('Access Status').'
9086: </legend>
9087: '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
9088: </fieldset>';
9089: if ($full) {
9090: $result.='
9091: <fieldset>
9092: <legend>
9093: '.&mt('Submission Status').'
9094: </legend>'.
9095: &Apache::loncommon::select_form('all','submitonly',\%options).
9096: '</fieldset>';
9097: }
9098: $result.='</div><br />';
9099: return $result;
9100: }
9101:
9102: sub reset_perm {
9103: undef(%perm);
9104: }
9105:
9106: sub init_perm {
9107: &reset_perm();
9108: foreach my $test_perm ('vgr','mgr','opa') {
9109:
9110: my $scope = $env{'request.course.id'};
9111: if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
9112:
9113: $scope .= '/'.$env{'request.course.sec'};
9114: if ( $perm{$test_perm}=
9115: &Apache::lonnet::allowed($test_perm,$scope)) {
9116: $perm{$test_perm.'_section'}=$env{'request.course.sec'};
9117: } else {
9118: delete($perm{$test_perm});
9119: }
9120: }
9121: }
9122: }
9123:
9124: sub init_old_essays {
9125: my ($symb,$apath,$adom,$aname) = @_;
9126: if ($symb ne '') {
9127: my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
9128: if (keys(%essays) > 0) {
9129: $old_essays{$symb} = \%essays;
9130: }
9131: }
9132: return;
9133: }
9134:
9135: sub reset_old_essays {
9136: undef(%old_essays);
9137: }
9138:
9139: sub gather_clicker_ids {
9140: my %clicker_ids;
9141:
9142: my $classlist = &Apache::loncoursedata::get_classlist();
9143:
9144: # Set up a couple variables.
9145: my $username_idx = &Apache::loncoursedata::CL_SNAME();
9146: my $domain_idx = &Apache::loncoursedata::CL_SDOM();
9147: my $status_idx = &Apache::loncoursedata::CL_STATUS();
9148:
9149: foreach my $student (keys(%$classlist)) {
9150: if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
9151: my $username = $classlist->{$student}->[$username_idx];
9152: my $domain = $classlist->{$student}->[$domain_idx];
9153: my $clickers =
9154: (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
9155: foreach my $id (split(/\,/,$clickers)) {
9156: $id=~s/^[\#0]+//;
9157: $id=~s/[\-\:]//g;
9158: if (exists($clicker_ids{$id})) {
9159: $clicker_ids{$id}.=','.$username.':'.$domain;
9160: } else {
9161: $clicker_ids{$id}=$username.':'.$domain;
9162: }
9163: }
9164: }
9165: return %clicker_ids;
9166: }
9167:
9168: sub gather_adv_clicker_ids {
9169: my %clicker_ids;
9170: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
9171: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
9172: my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
9173: foreach my $element (sort(keys(%coursepersonnel))) {
9174: foreach my $person (split(/\,/,$coursepersonnel{$element})) {
9175: my ($puname,$pudom)=split(/\:/,$person);
9176: my $clickers =
9177: (&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
9178: foreach my $id (split(/\,/,$clickers)) {
9179: $id=~s/^[\#0]+//;
9180: $id=~s/[\-\:]//g;
9181: if (exists($clicker_ids{$id})) {
9182: $clicker_ids{$id}.=','.$puname.':'.$pudom;
9183: } else {
9184: $clicker_ids{$id}=$puname.':'.$pudom;
9185: }
9186: }
9187: }
9188: }
9189: return %clicker_ids;
9190: }
9191:
9192: sub clicker_grading_parameters {
9193: return ('gradingmechanism' => 'scalar',
9194: 'upfiletype' => 'scalar',
9195: 'specificid' => 'scalar',
9196: 'pcorrect' => 'scalar',
9197: 'pincorrect' => 'scalar');
9198: }
9199:
9200: sub process_clicker {
9201: my ($r,$symb)=@_;
9202: if (!$symb) {return '';}
9203: my $result=&checkforfile_js();
9204: $result.=&Apache::loncommon::start_data_table().
9205: &Apache::loncommon::start_data_table_header_row().
9206: '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
9207: &Apache::loncommon::end_data_table_header_row().
9208: &Apache::loncommon::start_data_table_row()."<td>\n";
9209: # Attempt to restore parameters from last session, set defaults if not present
9210: my %Saveable_Parameters=&clicker_grading_parameters();
9211: &Apache::loncommon::restore_course_settings('grades_clicker',
9212: \%Saveable_Parameters);
9213: if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
9214: if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
9215: if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
9216: if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
9217:
9218: my %checked;
9219: foreach my $gradingmechanism ('attendance','personnel','specific','given') {
9220: if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
9221: $checked{$gradingmechanism}=' checked="checked"';
9222: }
9223: }
9224:
9225: my $upload=&mt("Evaluate File");
9226: my $type=&mt("Type");
9227: my $attendance=&mt("Award points just for participation");
9228: my $personnel=&mt("Correctness determined from response by course personnel");
9229: my $specific=&mt("Correctness determined from response with clicker ID(s)");
9230: my $given=&mt("Correctness determined from given list of answers").' '.
9231: '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
9232: my $pcorrect=&mt("Percentage points for correct solution");
9233: my $pincorrect=&mt("Percentage points for incorrect solution");
9234: my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
9235: {'iclicker' => 'i>clicker',
9236: 'interwrite' => 'interwrite PRS',
9237: 'turning' => 'Turning Technologies'});
9238: $symb = &Apache::lonenc::check_encrypt($symb);
9239: $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
9240: function sanitycheck() {
9241: // Accept only integer percentages
9242: document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
9243: document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
9244: // Find out grading choice
9245: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
9246: if (document.forms.gradesupload.gradingmechanism[i].checked) {
9247: gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
9248: }
9249: }
9250: // By default, new choice equals user selection
9251: newgradingchoice=gradingchoice;
9252: // Not good to give more points for false answers than correct ones
9253: if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
9254: document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
9255: }
9256: // If new choice is attendance only, and old choice was correctness-based, restore defaults
9257: if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
9258: document.forms.gradesupload.pcorrect.value=100;
9259: document.forms.gradesupload.pincorrect.value=100;
9260: }
9261: // If the values are different, cannot be attendance only
9262: if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
9263: (gradingchoice=='attendance')) {
9264: newgradingchoice='personnel';
9265: }
9266: // Change grading choice to new one
9267: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
9268: if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
9269: document.forms.gradesupload.gradingmechanism[i].checked=true;
9270: } else {
9271: document.forms.gradesupload.gradingmechanism[i].checked=false;
9272: }
9273: }
9274: // Remember the old state
9275: document.forms.gradesupload.waschecked.value=newgradingchoice;
9276: }
9277: ENDUPFORM
9278: $result.= <<ENDUPFORM;
9279: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
9280: <input type="hidden" name="symb" value="$symb" />
9281: <input type="hidden" name="command" value="processclickerfile" />
9282: <input type="file" name="upfile" size="50" />
9283: <br /><label>$type: $selectform</label>
9284: ENDUPFORM
9285: $result.='</td>'.&Apache::loncommon::end_data_table_row().
9286: &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
9287: <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
9288: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
9289: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
9290: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
9291: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
9292: <br />
9293: <input type="text" name="givenanswer" size="50" />
9294: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
9295: ENDGRADINGFORM
9296: $result.='</td>'.&Apache::loncommon::end_data_table_row().
9297: &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
9298: <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
9299: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
9300: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
9301: </form>'
9302: ENDPERCFORM
9303: $result.='</td>'.
9304: &Apache::loncommon::end_data_table_row().
9305: &Apache::loncommon::end_data_table();
9306: return $result;
9307: }
9308:
9309: sub process_clicker_file {
9310: my ($r,$symb)=@_;
9311: if (!$symb) {return '';}
9312:
9313: my %Saveable_Parameters=&clicker_grading_parameters();
9314: &Apache::loncommon::store_course_settings('grades_clicker',
9315: \%Saveable_Parameters);
9316: my $result='';
9317: if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
9318: $result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
9319: return $result;
9320: }
9321: if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
9322: $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
9323: return $result;
9324: }
9325: my $foundgiven=0;
9326: if ($env{'form.gradingmechanism'} eq 'given') {
9327: $env{'form.givenanswer'}=~s/^\s*//gs;
9328: $env{'form.givenanswer'}=~s/\s*$//gs;
9329: $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
9330: $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
9331: my @answers=split(/\,/,$env{'form.givenanswer'});
9332: $foundgiven=$#answers+1;
9333: }
9334: my %clicker_ids=&gather_clicker_ids();
9335: my %correct_ids;
9336: if ($env{'form.gradingmechanism'} eq 'personnel') {
9337: %correct_ids=&gather_adv_clicker_ids();
9338: }
9339: if ($env{'form.gradingmechanism'} eq 'specific') {
9340: foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
9341: $correct_id=~tr/a-z/A-Z/;
9342: $correct_id=~s/\s//gs;
9343: $correct_id=~s/^[\#0]+//;
9344: $correct_id=~s/[\-\:]//g;
9345: if ($correct_id) {
9346: $correct_ids{$correct_id}='specified';
9347: }
9348: }
9349: }
9350: if ($env{'form.gradingmechanism'} eq 'attendance') {
9351: $result.=&mt('Score based on attendance only');
9352: } elsif ($env{'form.gradingmechanism'} eq 'given') {
9353: $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
9354: } else {
9355: my $number=0;
9356: $result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
9357: foreach my $id (sort(keys(%correct_ids))) {
9358: $result.='<br /><tt>'.$id.'</tt> - ';
9359: if ($correct_ids{$id} eq 'specified') {
9360: $result.=&mt('specified');
9361: } else {
9362: my ($uname,$udom)=split(/\:/,$correct_ids{$id});
9363: $result.=&Apache::loncommon::plainname($uname,$udom);
9364: }
9365: $number++;
9366: }
9367: $result.="</p>\n";
9368: if ($number==0) {
9369: $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
9370: return $result;
9371: }
9372: }
9373: if (length($env{'form.upfile'}) < 2) {
9374: $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
9375: '<span class="LC_error">',
9376: '</span>',
9377: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
9378: return $result;
9379: }
9380:
9381: # Were able to get all the info needed, now analyze the file
9382:
9383: $result.=&Apache::loncommon::studentbrowser_javascript();
9384: $symb = &Apache::lonenc::check_encrypt($symb);
9385: $result.=&Apache::loncommon::start_data_table().
9386: &Apache::loncommon::start_data_table_header_row().
9387: '<th>'.&mt('Evaluate clicker file').'</th>'.
9388: &Apache::loncommon::end_data_table_header_row().
9389: &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
9390: <td>
9391: <form method="post" action="/adm/grades" name="clickeranalysis">
9392: <input type="hidden" name="symb" value="$symb" />
9393: <input type="hidden" name="command" value="assignclickergrades" />
9394: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
9395: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
9396: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
9397: ENDHEADER
9398: if ($env{'form.gradingmechanism'} eq 'given') {
9399: $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
9400: }
9401: my %responses;
9402: my @questiontitles;
9403: my $errormsg='';
9404: my $number=0;
9405: if ($env{'form.upfiletype'} eq 'iclicker') {
9406: ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
9407: }
9408: if ($env{'form.upfiletype'} eq 'interwrite') {
9409: ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
9410: }
9411: if ($env{'form.upfiletype'} eq 'turning') {
9412: ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
9413: }
9414: $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
9415: '<input type="hidden" name="number" value="'.$number.'" />'.
9416: &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
9417: $env{'form.pcorrect'},$env{'form.pincorrect'}).
9418: '<br />';
9419: if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
9420: $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
9421: return $result;
9422: }
9423: # Remember Question Titles
9424: # FIXME: Possibly need delimiter other than ":"
9425: for (my $i=0;$i<$number;$i++) {
9426: $result.='<input type="hidden" name="question:'.$i.'" value="'.
9427: &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
9428: }
9429: my $correct_count=0;
9430: my $student_count=0;
9431: my $unknown_count=0;
9432: # Match answers with usernames
9433: # FIXME: Possibly need delimiter other than ":"
9434: foreach my $id (keys(%responses)) {
9435: if ($correct_ids{$id}) {
9436: $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
9437: $correct_count++;
9438: } elsif ($clicker_ids{$id}) {
9439: if ($clicker_ids{$id}=~/\,/) {
9440: # More than one user with the same clicker!
9441: $result.="</td>".&Apache::loncommon::end_data_table_row().
9442: &Apache::loncommon::start_data_table_row()."<td>".
9443: &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
9444: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
9445: "<select name='multi".$id."'>";
9446: foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
9447: $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
9448: }
9449: $result.='</select>';
9450: $unknown_count++;
9451: } else {
9452: # Good: found one and only one user with the right clicker
9453: $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
9454: $student_count++;
9455: }
9456: } else {
9457: $result.="</td>".&Apache::loncommon::end_data_table_row().
9458: &Apache::loncommon::start_data_table_row()."<td>".
9459: &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
9460: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
9461: "\n".&mt("Username").": <input type='text' name='uname".$id."' /> ".
9462: "\n".&mt("Domain").": ".
9463: &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).' '.
9464: &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
9465: $unknown_count++;
9466: }
9467: }
9468: $result.='<hr />'.
9469: &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
9470: if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
9471: if ($correct_count==0) {
9472: $errormsg.="Found no correct answers answers for grading!";
9473: } elsif ($correct_count>1) {
9474: $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
9475: }
9476: }
9477: if ($number<1) {
9478: $errormsg.="Found no questions.";
9479: }
9480: if ($errormsg) {
9481: $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
9482: } else {
9483: $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
9484: }
9485: $result.='</form></td>'.
9486: &Apache::loncommon::end_data_table_row().
9487: &Apache::loncommon::end_data_table();
9488: return $result;
9489: }
9490:
9491: sub iclicker_eval {
9492: my ($questiontitles,$responses)=@_;
9493: my $number=0;
9494: my $errormsg='';
9495: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
9496: my %components=&Apache::loncommon::record_sep($line);
9497: my @entries=map {$components{$_}} (sort(keys(%components)));
9498: if ($entries[0] eq 'Question') {
9499: for (my $i=3;$i<$#entries;$i+=6) {
9500: $$questiontitles[$number]=$entries[$i];
9501: $number++;
9502: }
9503: }
9504: if ($entries[0]=~/^\#/) {
9505: my $id=$entries[0];
9506: my @idresponses;
9507: $id=~s/^[\#0]+//;
9508: for (my $i=0;$i<$number;$i++) {
9509: my $idx=3+$i*6;
9510: $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
9511: push(@idresponses,$entries[$idx]);
9512: }
9513: $$responses{$id}=join(',',@idresponses);
9514: }
9515: }
9516: return ($errormsg,$number);
9517: }
9518:
9519: sub interwrite_eval {
9520: my ($questiontitles,$responses)=@_;
9521: my $number=0;
9522: my $errormsg='';
9523: my $skipline=1;
9524: my $questionnumber=0;
9525: my %idresponses=();
9526: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
9527: my %components=&Apache::loncommon::record_sep($line);
9528: my @entries=map {$components{$_}} (sort(keys(%components)));
9529: if ($entries[1] eq 'Time') { $skipline=0; next; }
9530: if ($entries[1] eq 'Response') { $skipline=1; }
9531: next if $skipline;
9532: if ($entries[0]!=$questionnumber) {
9533: $questionnumber=$entries[0];
9534: $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
9535: $number++;
9536: }
9537: my $id=$entries[4];
9538: $id=~s/^[\#0]+//;
9539: $id=~s/^v\d*\://i;
9540: $id=~s/[\-\:]//g;
9541: $idresponses{$id}[$number]=$entries[6];
9542: }
9543: foreach my $id (keys(%idresponses)) {
9544: $$responses{$id}=join(',',@{$idresponses{$id}});
9545: $$responses{$id}=~s/^\s*\,//;
9546: }
9547: return ($errormsg,$number);
9548: }
9549:
9550: sub turning_eval {
9551: my ($questiontitles,$responses)=@_;
9552: my $number=0;
9553: my $errormsg='';
9554: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
9555: my %components=&Apache::loncommon::record_sep($line);
9556: my @entries=map {$components{$_}} (sort(keys(%components)));
9557: if ($#entries>$number) { $number=$#entries; }
9558: my $id=$entries[0];
9559: my @idresponses;
9560: $id=~s/^[\#0]+//;
9561: unless ($id) { next; }
9562: for (my $idx=1;$idx<=$#entries;$idx++) {
9563: $entries[$idx]=~s/\,/\;/g;
9564: $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
9565: push(@idresponses,$entries[$idx]);
9566: }
9567: $$responses{$id}=join(',',@idresponses);
9568: }
9569: for (my $i=1; $i<=$number; $i++) {
9570: $$questiontitles[$i]=&mt('Question [_1]',$i);
9571: }
9572: return ($errormsg,$number);
9573: }
9574:
9575:
9576: sub assign_clicker_grades {
9577: my ($r,$symb)=@_;
9578: if (!$symb) {return '';}
9579: # See which part we are saving to
9580: my $res_error;
9581: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
9582: if ($res_error) {
9583: return &navmap_errormsg();
9584: }
9585: # FIXME: This should probably look for the first handgradeable part
9586: my $part=$$partlist[0];
9587: # Start screen output
9588: my $result=&Apache::loncommon::start_data_table().
9589: &Apache::loncommon::start_data_table_header_row().
9590: '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
9591: &Apache::loncommon::end_data_table_header_row().
9592: &Apache::loncommon::start_data_table_row().'<td>';
9593: # Get correct result
9594: # FIXME: Possibly need delimiter other than ":"
9595: my @correct=();
9596: my $gradingmechanism=$env{'form.gradingmechanism'};
9597: my $number=$env{'form.number'};
9598: if ($gradingmechanism ne 'attendance') {
9599: foreach my $key (keys(%env)) {
9600: if ($key=~/^form\.correct\:/) {
9601: my @input=split(/\,/,$env{$key});
9602: for (my $i=0;$i<=$#input;$i++) {
9603: if (($correct[$i]) && ($input[$i]) &&
9604: ($correct[$i] ne $input[$i])) {
9605: $result.='<br /><span class="LC_warning">'.
9606: &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
9607: $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
9608: } elsif (($input[$i]) || ($input[$i] eq '0')) {
9609: $correct[$i]=$input[$i];
9610: }
9611: }
9612: }
9613: }
9614: for (my $i=0;$i<$number;$i++) {
9615: if ((!$correct[$i]) && ($correct[$i] ne '0')) {
9616: $result.='<br /><span class="LC_error">'.
9617: &mt('No correct result given for question "[_1]"!',
9618: $env{'form.question:'.$i}).'</span>';
9619: }
9620: }
9621: $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
9622: }
9623: # Start grading
9624: my $pcorrect=$env{'form.pcorrect'};
9625: my $pincorrect=$env{'form.pincorrect'};
9626: my $storecount=0;
9627: my %users=();
9628: foreach my $key (keys(%env)) {
9629: my $user='';
9630: if ($key=~/^form\.student\:(.*)$/) {
9631: $user=$1;
9632: }
9633: if ($key=~/^form\.unknown\:(.*)$/) {
9634: my $id=$1;
9635: if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
9636: $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
9637: } elsif ($env{'form.multi'.$id}) {
9638: $user=$env{'form.multi'.$id};
9639: }
9640: }
9641: if ($user) {
9642: if ($users{$user}) {
9643: $result.='<br /><span class="LC_warning">'.
9644: &mt("More than one entry found for <tt>[_1]</tt>!",$user).
9645: '</span><br />';
9646: }
9647: $users{$user}=1;
9648: my @answer=split(/\,/,$env{$key});
9649: my $sum=0;
9650: my $realnumber=$number;
9651: for (my $i=0;$i<$number;$i++) {
9652: if ($correct[$i] eq '-') {
9653: $realnumber--;
9654: } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
9655: if ($gradingmechanism eq 'attendance') {
9656: $sum+=$pcorrect;
9657: } elsif ($correct[$i] eq '*') {
9658: $sum+=$pcorrect;
9659: } else {
9660: # We actually grade if correct or not
9661: my $increment=$pincorrect;
9662: # Special case: numerical answer "0"
9663: if ($correct[$i] eq '0') {
9664: if ($answer[$i]=~/^[0\.]+$/) {
9665: $increment=$pcorrect;
9666: }
9667: # General numerical answer, both evaluate to something non-zero
9668: } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
9669: if (1.0*$correct[$i]==1.0*$answer[$i]) {
9670: $increment=$pcorrect;
9671: }
9672: # Must be just alphanumeric
9673: } elsif ($answer[$i] eq $correct[$i]) {
9674: $increment=$pcorrect;
9675: }
9676: $sum+=$increment;
9677: }
9678: }
9679: }
9680: my $ave=$sum/(100*$realnumber);
9681: # Store
9682: my ($username,$domain)=split(/\:/,$user);
9683: my %grades=();
9684: $grades{"resource.$part.solved"}='correct_by_override';
9685: $grades{"resource.$part.awarded"}=$ave;
9686: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
9687: my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
9688: $env{'request.course.id'},
9689: $domain,$username);
9690: if ($returncode ne 'ok') {
9691: $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
9692: } else {
9693: $storecount++;
9694: }
9695: }
9696: }
9697: # We are done
9698: $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
9699: '</td>'.
9700: &Apache::loncommon::end_data_table_row().
9701: &Apache::loncommon::end_data_table();
9702: return $result;
9703: }
9704:
9705: sub navmap_errormsg {
9706: return '<div class="LC_error">'.
9707: &mt('An error occurred retrieving information about resources in the course.').'<br />'.
9708: &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>').
9709: '</div>';
9710: }
9711:
9712: sub startpage {
9713: my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
9714: if ($nomenu) {
9715: $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
9716: } else {
9717: unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
9718: $r->print(&Apache::loncommon::start_page('Grading',$js,
9719: {'bread_crumbs' => $crumbs}));
9720: &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
9721: }
9722: unless ($nodisplayflag) {
9723: $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
9724: }
9725: }
9726:
9727: sub select_problem {
9728: my ($r)=@_;
9729: $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
9730: $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
9731: $r->print('<input type="hidden" name="command" value="gradingmenu" />');
9732: $r->print('<input type="submit" value="'.&mt('Next').' →" /></form>');
9733: }
9734:
9735: sub handler {
9736: my $request=$_[0];
9737: &reset_caches();
9738: if ($request->header_only) {
9739: &Apache::loncommon::content_type($request,'text/html');
9740: $request->send_http_header;
9741: return OK;
9742: }
9743: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
9744:
9745: # see what command we need to execute
9746:
9747: my @commands=&Apache::loncommon::get_env_multiple('form.command');
9748: my $command=$commands[0];
9749:
9750: &init_perm();
9751: if (!$env{'request.course.id'}) {
9752: unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
9753: ($command =~ /^scantronupload/)) {
9754: # Not in a course.
9755: $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
9756: return HTTP_NOT_ACCEPTABLE;
9757: }
9758: } elsif (!%perm) {
9759: $request->internal_redirect('/adm/quickgrades');
9760: return OK;
9761: }
9762: &Apache::loncommon::content_type($request,'text/html');
9763: $request->send_http_header;
9764:
9765: if ($#commands > 0) {
9766: &Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
9767: }
9768:
9769: # see what the symb is
9770:
9771: my $symb=$env{'form.symb'};
9772: unless ($symb) {
9773: (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
9774: $symb=&Apache::lonnet::symbread($url);
9775: }
9776: &Apache::lonenc::check_decrypt(\$symb);
9777:
9778: $ssi_error = 0;
9779: if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
9780: #
9781: # Not called from a resource, but inside a course
9782: #
9783: &startpage($request,undef,[],1,1);
9784: &select_problem($request);
9785: } else {
9786: if ($command eq 'submission' && $perm{'vgr'}) {
9787: my ($stuvcurrent,$stuvdisp,$versionform,$js);
9788: if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
9789: ($stuvcurrent,$stuvdisp,$versionform,$js) =
9790: &choose_task_version_form($symb,$env{'form.student'},
9791: $env{'form.userdom'});
9792: }
9793: &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
9794: if ($versionform) {
9795: $request->print($versionform);
9796: }
9797: $request->print('<br clear="all" />');
9798: ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
9799: } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
9800: my ($stuvcurrent,$stuvdisp,$versionform,$js) =
9801: &choose_task_version_form($symb,$env{'form.student'},
9802: $env{'form.userdom'},
9803: $env{'form.inhibitmenu'});
9804: &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
9805: if ($versionform) {
9806: $request->print($versionform);
9807: }
9808: $request->print('<br clear="all" />');
9809: $request->print(&show_previous_task_version($request,$symb));
9810: } elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
9811: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
9812: {href=>'',text=>'Select student'}],1,1);
9813: &pickStudentPage($request,$symb);
9814: } elsif ($command eq 'displayPage' && $perm{'vgr'}) {
9815: &startpage($request,$symb,
9816: [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
9817: {href=>'',text=>'Select student'},
9818: {href=>'',text=>'Grade student'}],1,1);
9819: &displayPage($request,$symb);
9820: } elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
9821: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
9822: {href=>'',text=>'Select student'},
9823: {href=>'',text=>'Grade student'},
9824: {href=>'',text=>'Store grades'}],1,1);
9825: &updateGradeByPage($request,$symb);
9826: } elsif ($command eq 'processGroup' && $perm{'vgr'}) {
9827: &startpage($request,$symb,[{href=>'',text=>'...'},
9828: {href=>'',text=>'Modify grades'}]);
9829: &processGroup($request,$symb);
9830: } elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
9831: &startpage($request,$symb);
9832: $request->print(&grading_menu($request,$symb));
9833: } elsif ($command eq 'individual' && $perm{'vgr'}) {
9834: &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
9835: $request->print(&submit_options($request,$symb));
9836: } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
9837: &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
9838: $request->print(&listStudents($request,$symb,'graded'));
9839: } elsif ($command eq 'table' && $perm{'vgr'}) {
9840: &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
9841: $request->print(&submit_options_table($request,$symb));
9842: } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
9843: &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
9844: $request->print(&submit_options_sequence($request,$symb));
9845: } elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
9846: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
9847: $request->print(&viewgrades($request,$symb));
9848: } elsif ($command eq 'handgrade' && $perm{'mgr'}) {
9849: &startpage($request,$symb,[{href=>'',text=>'...'},
9850: {href=>'',text=>'Store grades'}]);
9851: $request->print(&processHandGrade($request,$symb));
9852: } elsif ($command eq 'editgrades' && $perm{'mgr'}) {
9853: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
9854: {href=>&href_symb_cmd($symb,'viewgrades').'&group=all§ion=all&Status=Active',
9855: text=>"Modify grades"},
9856: {href=>'', text=>"Store grades"}]);
9857: $request->print(&editgrades($request,$symb));
9858: } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
9859: &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
9860: $request->print(&initialverifyreceipt($request,$symb));
9861: } elsif ($command eq 'verify' && $perm{'vgr'}) {
9862: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
9863: {href=>'',text=>'Verification Result'}]);
9864: $request->print(&verifyreceipt($request,$symb));
9865: } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
9866: &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
9867: $request->print(&process_clicker($request,$symb));
9868: } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
9869: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
9870: {href=>'', text=>'Process clicker file'}]);
9871: $request->print(&process_clicker_file($request,$symb));
9872: } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
9873: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
9874: {href=>'', text=>'Process clicker file'},
9875: {href=>'', text=>'Store grades'}]);
9876: $request->print(&assign_clicker_grades($request,$symb));
9877: } elsif ($command eq 'csvform' && $perm{'mgr'}) {
9878: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
9879: $request->print(&upcsvScores_form($request,$symb));
9880: } elsif ($command eq 'csvupload' && $perm{'mgr'}) {
9881: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
9882: $request->print(&csvupload($request,$symb));
9883: } elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
9884: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
9885: $request->print(&csvuploadmap($request,$symb));
9886: } elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
9887: if ($env{'form.associate'} ne 'Reverse Association') {
9888: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
9889: $request->print(&csvuploadoptions($request,$symb));
9890: } else {
9891: if ( $env{'form.upfile_associate'} ne 'reverse' ) {
9892: $env{'form.upfile_associate'} = 'reverse';
9893: } else {
9894: $env{'form.upfile_associate'} = 'forward';
9895: }
9896: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
9897: $request->print(&csvuploadmap($request,$symb));
9898: }
9899: } elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
9900: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
9901: $request->print(&csvuploadassign($request,$symb));
9902: } elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
9903: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9904: $request->print(&scantron_selectphase($request,undef,$symb));
9905: } elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
9906: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9907: $request->print(&scantron_do_warning($request,$symb));
9908: } elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
9909: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9910: $request->print(&scantron_validate_file($request,$symb));
9911: } elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
9912: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9913: $request->print(&scantron_process_students($request,$symb));
9914: } elsif ($command eq 'scantronupload' &&
9915: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
9916: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
9917: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9918: $request->print(&scantron_upload_scantron_data($request,$symb));
9919: } elsif ($command eq 'scantronupload_save' &&
9920: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
9921: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
9922: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9923: $request->print(&scantron_upload_scantron_data_save($request,$symb));
9924: } elsif ($command eq 'scantron_download' &&
9925: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
9926: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9927: $request->print(&scantron_download_scantron_data($request,$symb));
9928: } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
9929: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9930: $request->print(&checkscantron_results($request,$symb));
9931: } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
9932: &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
9933: $request->print(&submit_options_download($request,$symb));
9934: } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
9935: &startpage($request,$symb,
9936: [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
9937: {href=>'', text=>'Download submissions'}]);
9938: &submit_download_link($request,$symb);
9939: } elsif ($command) {
9940: &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
9941: $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
9942: }
9943: }
9944: if ($ssi_error) {
9945: &ssi_print_error($request);
9946: }
9947: if ($env{'form.inhibitmenu'}) {
9948: $request->print(&Apache::loncommon::end_page());
9949: } else {
9950: &Apache::lonquickgrades::endGradeScreen($request);
9951: }
9952: &reset_caches();
9953: return OK;
9954: }
9955:
9956: 1;
9957:
9958: __END__;
9959:
9960:
9961: =head1 NAME
9962:
9963: Apache::grades
9964:
9965: =head1 SYNOPSIS
9966:
9967: Handles the viewing of grades.
9968:
9969: This is part of the LearningOnline Network with CAPA project
9970: described at http://www.lon-capa.org.
9971:
9972: =head1 OVERVIEW
9973:
9974: Do an ssi with retries:
9975: While I'd love to factor out this with the vesrion in lonprintout,
9976: 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
9977: I'm not quite ready to invent (e.g. an ssi_with_retry object).
9978:
9979: At least the logic that drives this has been pulled out into loncommon.
9980:
9981:
9982:
9983: ssi_with_retries - Does the server side include of a resource.
9984: if the ssi call returns an error we'll retry it up to
9985: the number of times requested by the caller.
9986: If we still have a proble, no text is appended to the
9987: output and we set some global variables.
9988: to indicate to the caller an SSI error occurred.
9989: All of this is supposed to deal with the issues described
9990: in LonCAPA BZ 5631 see:
9991: http://bugs.lon-capa.org/show_bug.cgi?id=5631
9992: by informing the user that this happened.
9993:
9994: Parameters:
9995: resource - The resource to include. This is passed directly, without
9996: interpretation to lonnet::ssi.
9997: form - The form hash parameters that guide the interpretation of the resource
9998:
9999: retries - Number of retries allowed before giving up completely.
10000: Returns:
10001: On success, returns the rendered resource identified by the resource parameter.
10002: Side Effects:
10003: The following global variables can be set:
10004: ssi_error - If an unrecoverable error occurred this becomes true.
10005: It is up to the caller to initialize this to false
10006: if desired.
10007: ssi_error_resource - If an unrecoverable error occurred, this is the value
10008: of the resource that could not be rendered by the ssi
10009: call.
10010: ssi_error_message - The error string fetched from the ssi response
10011: in the event of an error.
10012:
10013:
10014: =head1 HANDLER SUBROUTINE
10015:
10016: ssi_with_retries()
10017:
10018: =head1 SUBROUTINES
10019:
10020: =over
10021:
10022: =head1 Routines to display previous version of a Task for a specific student
10023:
10024: Tasks are graded pass/fail. Students who have yet to pass a particular Task
10025: can receive another opportunity. Access to tasks is slot-based. If a slot
10026: requires a proctor to check-in the student, a new version of the Task will
10027: be created when the student is checked in to the new opportunity.
10028:
10029: If a particular student has tried two or more versions of a particular task,
10030: the submission screen provides a user with vgr privileges (e.g., a Course
10031: Coordinator) the ability to display a previous version worked on by the
10032: student. By default, the current version is displayed. If a previous version
10033: has been selected for display, submission data are only shown that pertain
10034: to that particular version, and the interface to submit grades is not shown.
10035:
10036: =over 4
10037:
10038: =item show_previous_task_version()
10039:
10040: Displays a specified version of a student's Task, as the student sees it.
10041:
10042: Inputs: 2
10043: request - request object
10044: symb - unique symb for current instance of resource
10045:
10046: Output: None.
10047:
10048: Side Effects: calls &show_problem() to print version of Task, with
10049: version contained in form item: $env{'form.previousversion'}
10050:
10051: =item choose_task_version_form()
10052:
10053: Displays a web form used to select which version of a student's view of a
10054: Task should be displayed. Either launches a pop-up window, or replaces
10055: content in existing pop-up, or replaces page in main window.
10056:
10057: Inputs: 4
10058: symb - unique symb for current instance of resource
10059: uname - username of student
10060: udom - domain of student
10061: nomenu - 1 if display is in a pop-up window, and hence no menu
10062: breadcrumbs etc., are displayed
10063:
10064: Output: 4
10065: current - student's current version
10066: displayed - student's version being displayed
10067: result - scalar containing HTML for web form used to switch to
10068: a different version (or a link to close window, if pop-up).
10069: js - javascript for processing selection in versions web form
10070:
10071: Side Effects: None.
10072:
10073: =item previous_display_javascript()
10074:
10075: Inputs: 2
10076: nomenu - 1 if display is in a pop-up window, and hence no menu
10077: breadcrumbs etc., are displayed.
10078: current - student's current version number.
10079:
10080: Output: 1
10081: js - javascript for processing selection in versions web form.
10082:
10083: Side Effects: None.
10084:
10085: =back
10086:
10087: =head1 Routines to process bubblesheet data.
10088:
10089: =over 4
10090:
10091: =item scantron_get_correction() :
10092:
10093: Builds the interface screen to interact with the operator to fix a
10094: specific error condition in a specific scanline
10095:
10096: Arguments:
10097: $r - Apache request object
10098: $i - number of the current scanline
10099: $scan_record - hash ref as returned from &scantron_parse_scanline()
10100: $scan_config - hash ref as returned from &get_scantron_config()
10101: $line - full contents of the current scanline
10102: $error - error condition, valid values are
10103: 'incorrectCODE', 'duplicateCODE',
10104: 'doublebubble', 'missingbubble',
10105: 'duplicateID', 'incorrectID'
10106: $arg - extra information needed
10107: For errors:
10108: - duplicateID - paper number that this studentID was seen before on
10109: - duplicateCODE - array ref of the paper numbers this CODE was
10110: seen on before
10111: - incorrectCODE - current incorrect CODE
10112: - doublebubble - array ref of the bubble lines that have double
10113: bubble errors
10114: - missingbubble - array ref of the bubble lines that have missing
10115: bubble errors
10116:
10117: =item scantron_get_maxbubble() :
10118:
10119: Arguments:
10120: $nav_error - Reference to scalar which is a flag to indicate a
10121: failure to retrieve a navmap object.
10122: if $nav_error is set to 1 by scantron_get_maxbubble(), the
10123: calling routine should trap the error condition and display the warning
10124: found in &navmap_errormsg().
10125:
10126: $scantron_config - Reference to bubblesheet format configuration hash.
10127:
10128: Returns the maximum number of bubble lines that are expected to
10129: occur. Does this by walking the selected sequence rendering the
10130: resource and then checking &Apache::lonxml::get_problem_counter()
10131: for what the current value of the problem counter is.
10132:
10133: Caches the results to $env{'form.scantron_maxbubble'},
10134: $env{'form.scantron.bubble_lines.n'},
10135: $env{'form.scantron.first_bubble_line.n'} and
10136: $env{"form.scantron.sub_bubblelines.n"}
10137: which are the total number of bubble, lines, the number of bubble
10138: lines for response n and number of the first bubble line for response n,
10139: and a comma separated list of numbers of bubble lines for sub-questions
10140: (for optionresponse, matchresponse, and rankresponse items), for response n.
10141:
10142:
10143: =item scantron_validate_missingbubbles() :
10144:
10145: Validates all scanlines in the selected file to not have any
10146: answers that don't have bubbles that have not been verified
10147: to be bubble free.
10148:
10149: =item scantron_process_students() :
10150:
10151: Routine that does the actual grading of the bubblesheet information.
10152:
10153: The parsed scanline hash is added to %env
10154:
10155: Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
10156: foreach resource , with the form data of
10157:
10158: 'submitted' =>'scantron'
10159: 'grade_target' =>'grade',
10160: 'grade_username'=> username of student
10161: 'grade_domain' => domain of student
10162: 'grade_courseid'=> of course
10163: 'grade_symb' => symb of resource to grade
10164:
10165: This triggers a grading pass. The problem grading code takes care
10166: of converting the bubbled letter information (now in %env) into a
10167: valid submission.
10168:
10169: =item scantron_upload_scantron_data() :
10170:
10171: Creates the screen for adding a new bubblesheet data file to a course.
10172:
10173: =item scantron_upload_scantron_data_save() :
10174:
10175: Adds a provided bubble information data file to the course if user
10176: has the correct privileges to do so.
10177:
10178: =item valid_file() :
10179:
10180: Validates that the requested bubble data file exists in the course.
10181:
10182: =item scantron_download_scantron_data() :
10183:
10184: Shows a list of the three internal files (original, corrected,
10185: skipped) for a specific bubblesheet data file that exists in the
10186: course.
10187:
10188: =item scantron_validate_ID() :
10189:
10190: Validates all scanlines in the selected file to not have any
10191: invalid or underspecified student/employee IDs
10192:
10193: =item navmap_errormsg() :
10194:
10195: Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
10196: Should be called whenever the request to instantiate a navmap object fails.
10197:
10198: =back
10199:
10200: =back
10201:
10202: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>