1: # The LearningOnline Network with CAPA
2: # The LON-CAPA Grading handler
3: #
4: # $Id: grades.pm,v 1.627 2010/04/20 21:53:33 www Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28:
29:
30:
31: package Apache::grades;
32: use strict;
33: use Apache::style;
34: use Apache::lonxml;
35: use Apache::lonnet;
36: use Apache::loncommon;
37: use Apache::lonhtmlcommon;
38: use Apache::lonnavmaps;
39: use Apache::lonhomework;
40: use Apache::lonpickcode;
41: use Apache::loncoursedata;
42: use Apache::lonmsg();
43: use Apache::Constants qw(:common);
44: use Apache::lonlocal;
45: use Apache::lonenc;
46: use Apache::lonstathelpers;
47: use String::Similarity;
48: use LONCAPA;
49:
50: use POSIX qw(floor);
51:
52:
53:
54: my %perm=();
55:
56: # These variables are used to recover from ssi errors
57:
58: my $ssi_retries = 5;
59: my $ssi_error;
60: my $ssi_error_resource;
61: my $ssi_error_message;
62:
63:
64: sub ssi_with_retries {
65: my ($resource, $retries, %form) = @_;
66: my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
67: if ($response->is_error) {
68: $ssi_error = 1;
69: $ssi_error_resource = $resource;
70: $ssi_error_message = $response->code . " " . $response->message;
71: }
72:
73: return $content;
74:
75: }
76: #
77: # Prodcuces an ssi retry failure error message to the user:
78: #
79:
80: sub ssi_print_error {
81: my ($r) = @_;
82: my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
83: $r->print('
84: <br />
85: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
86: <p>
87: '.&mt('Unable to retrieve a resource from a server:').'<br />
88: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
89: '.&mt('Error:').' '.$ssi_error_message.'
90: </p>
91: <p>'.
92: &mt('It is recommended that you try again later, as this error may mean the server was just temporarily unavailable, or is down for maintenance.').'<br />'.
93: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
94: '</p>');
95: return;
96: }
97:
98: #
99: # --- Retrieve the parts from the metadata file.---
100: # Returns an array of everything that the resources stores away
101: #
102:
103: sub getpartlist {
104: my ($symb,$errorref) = @_;
105:
106: my $navmap = Apache::lonnavmaps::navmap->new();
107: unless (ref($navmap)) {
108: if (ref($errorref)) {
109: $$errorref = 'navmap';
110: return;
111: }
112: }
113: my $res = $navmap->getBySymb($symb);
114: my $partlist = $res->parts();
115: my $url = $res->src();
116: my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
117:
118: my @stores;
119: foreach my $part (@{ $partlist }) {
120: foreach my $key (@metakeys) {
121: if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
122: }
123: }
124: return @stores;
125: }
126:
127: #--- Format fullname, username:domain if different for display
128: #--- Use anywhere where the student names are listed
129: sub nameUserString {
130: my ($type,$fullname,$uname,$udom) = @_;
131: if ($type eq 'header') {
132: return '<b> '.&mt('Fullname').' </b><span class="LC_internal_info">('.&mt('Username').')</span>';
133: } else {
134: return ' '.$fullname.'<span class="LC_internal_info"> ('.$uname.
135: ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
136: }
137: }
138:
139: #--- Get the partlist and the response type for a given problem. ---
140: #--- Indicate if a response type is coded handgraded or not. ---
141: #--- Sets response_error pointer to "1" if navmaps object broken ---
142: sub response_type {
143: my ($symb,$response_error) = @_;
144:
145: my $navmap = Apache::lonnavmaps::navmap->new();
146: unless (ref($navmap)) {
147: if (ref($response_error)) {
148: $$response_error = 1;
149: }
150: return;
151: }
152: my $res = $navmap->getBySymb($symb);
153: unless (ref($res)) {
154: $$response_error = 1;
155: return;
156: }
157: my $partlist = $res->parts();
158: my %vPart =
159: map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
160: my (%response_types,%handgrade);
161: foreach my $part (@{ $partlist }) {
162: next if (%vPart && !exists($vPart{$part}));
163:
164: my @types = $res->responseType($part);
165: my @ids = $res->responseIds($part);
166: for (my $i=0; $i < scalar(@ids); $i++) {
167: $response_types{$part}{$ids[$i]} = $types[$i];
168: $handgrade{$part.'_'.$ids[$i]} =
169: &Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
170: '.handgrade',$symb);
171: }
172: }
173: return ($partlist,\%handgrade,\%response_types);
174: }
175:
176: sub flatten_responseType {
177: my ($responseType) = @_;
178: my @part_response_id =
179: map {
180: my $part = $_;
181: map {
182: [$part,$_]
183: } sort(keys(%{ $responseType->{$part} }));
184: } sort(keys(%$responseType));
185: return @part_response_id;
186: }
187:
188: sub get_display_part {
189: my ($partID,$symb)=@_;
190: my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
191: if (defined($display) and $display ne '') {
192: $display.= ' (<span class="LC_internal_info">'
193: .&mt('Part ID: [_1]',$partID).'</span>)';
194: } else {
195: $display=$partID;
196: }
197: return $display;
198: }
199:
200: sub reset_caches {
201: &reset_analyze_cache();
202: &reset_perm();
203: }
204:
205: {
206: my %analyze_cache;
207: my %analyze_cache_formkeys;
208:
209: sub reset_analyze_cache {
210: undef(%analyze_cache);
211: undef(%analyze_cache_formkeys);
212: }
213:
214: sub get_analyze {
215: my ($symb,$uname,$udom,$no_increment,$add_to_hash)=@_;
216: my $key = "$symb\0$uname\0$udom";
217: if (exists($analyze_cache{$key})) {
218: my $getupdate = 0;
219: if (ref($add_to_hash) eq 'HASH') {
220: foreach my $item (keys(%{$add_to_hash})) {
221: if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
222: if (!exists($analyze_cache_formkeys{$key}{$item})) {
223: $getupdate = 1;
224: last;
225: }
226: } else {
227: $getupdate = 1;
228: }
229: }
230: }
231: if (!$getupdate) {
232: return $analyze_cache{$key};
233: }
234: }
235:
236: my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
237: $url=&Apache::lonnet::clutter($url);
238: my %form = ('grade_target' => 'analyze',
239: 'grade_domain' => $udom,
240: 'grade_symb' => $symb,
241: 'grade_courseid' => $env{'request.course.id'},
242: 'grade_username' => $uname,
243: 'grade_noincrement' => $no_increment);
244: if (ref($add_to_hash)) {
245: %form = (%form,%{$add_to_hash});
246: }
247: my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
248: (undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
249: my %analyze=&Apache::lonnet::str2hash($subresult);
250: if (ref($add_to_hash) eq 'HASH') {
251: $analyze_cache_formkeys{$key} = $add_to_hash;
252: } else {
253: $analyze_cache_formkeys{$key} = {};
254: }
255: return $analyze_cache{$key} = \%analyze;
256: }
257:
258: sub get_order {
259: my ($partid,$respid,$symb,$uname,$udom,$no_increment)=@_;
260: my $analyze = &get_analyze($symb,$uname,$udom,$no_increment);
261: return $analyze->{"$partid.$respid.shown"};
262: }
263:
264: sub get_radiobutton_correct_foil {
265: my ($partid,$respid,$symb,$uname,$udom)=@_;
266: my $analyze = &get_analyze($symb,$uname,$udom);
267: my $foils = &get_order($partid,$respid,$symb,$uname,$udom);
268: if (ref($foils) eq 'ARRAY') {
269: foreach my $foil (@{$foils}) {
270: if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
271: return $foil;
272: }
273: }
274: }
275: }
276:
277: sub scantron_partids_tograde {
278: my ($resource,$cid,$uname,$udom,$check_for_randomlist) = @_;
279: my (%analysis,@parts);
280: if (ref($resource)) {
281: my $symb = $resource->symb();
282: my $add_to_form;
283: if ($check_for_randomlist) {
284: $add_to_form = { 'check_parts_withrandomlist' => 1,};
285: }
286: my $analyze = &get_analyze($symb,$uname,$udom,undef,$add_to_form);
287: if (ref($analyze) eq 'HASH') {
288: %analysis = %{$analyze};
289: }
290: if (ref($analysis{'parts'}) eq 'ARRAY') {
291: foreach my $part (@{$analysis{'parts'}}) {
292: my ($id,$respid) = split(/\./,$part);
293: if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
294: push(@parts,$part);
295: }
296: }
297: }
298: }
299: return (\%analysis,\@parts);
300: }
301:
302: }
303:
304: #--- Clean response type for display
305: #--- Currently filters option/rank/radiobutton/match/essay/Task
306: # response types only.
307: sub cleanRecord {
308: my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
309: $uname,$udom) = @_;
310: my $grayFont = '<span class="LC_internal_info">';
311: if ($response =~ /^(option|rank)$/) {
312: my %answer=&Apache::lonnet::str2hash($answer);
313: my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
314: my ($toprow,$bottomrow);
315: foreach my $foil (@$order) {
316: if ($grading{$foil} == 1) {
317: $toprow.='<td><b>'.$answer{$foil}.' </b></td>';
318: } else {
319: $toprow.='<td><i>'.$answer{$foil}.' </i></td>';
320: }
321: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
322: }
323: return '<blockquote><table border="1">'.
324: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
325: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
326: $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
327: } elsif ($response eq 'match') {
328: my %answer=&Apache::lonnet::str2hash($answer);
329: my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
330: my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
331: my ($toprow,$middlerow,$bottomrow);
332: foreach my $foil (@$order) {
333: my $item=shift(@items);
334: if ($grading{$foil} == 1) {
335: $toprow.='<td><b>'.$item.' </b></td>';
336: $middlerow.='<td><b>'.$grayFont.$answer{$foil}.' </span></b></td>';
337: } else {
338: $toprow.='<td><i>'.$item.' </i></td>';
339: $middlerow.='<td><i>'.$grayFont.$answer{$foil}.' </span></i></td>';
340: }
341: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
342: }
343: return '<blockquote><table border="1">'.
344: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
345: '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
346: $middlerow.'</tr>'.
347: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
348: $bottomrow.'</tr>'.'</table></blockquote>';
349: } elsif ($response eq 'radiobutton') {
350: my %answer=&Apache::lonnet::str2hash($answer);
351: my ($toprow,$bottomrow);
352: my $correct =
353: &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
354: foreach my $foil (@$order) {
355: if (exists($answer{$foil})) {
356: if ($foil eq $correct) {
357: $toprow.='<td><b>'.&mt('true').'</b></td>';
358: } else {
359: $toprow.='<td><i>'.&mt('true').'</i></td>';
360: }
361: } else {
362: $toprow.='<td>'.&mt('false').'</td>';
363: }
364: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
365: }
366: return '<blockquote><table border="1">'.
367: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
368: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
369: $bottomrow.'</tr>'.'</table></blockquote>';
370: } elsif ($response eq 'essay') {
371: if (! exists ($env{'form.'.$symb})) {
372: my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
373: $env{'course.'.$env{'request.course.id'}.'.domain'},
374: $env{'course.'.$env{'request.course.id'}.'.num'});
375:
376: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
377: $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
378: $env{'form.kwclr'} = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
379: $env{'form.kwsize'} = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
380: $env{'form.kwstyle'} = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
381: $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
382: }
383: $answer =~ s-\n-<br />-g;
384: return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
385: } elsif ( $response eq 'organic') {
386: my $result='Smile representation: "<tt>'.$answer.'</tt>"';
387: my $jme=$record->{$version."resource.$partid.$respid.molecule"};
388: $result.=&Apache::chemresponse::jme_img($jme,$answer,400);
389: return $result;
390: } elsif ( $response eq 'Task') {
391: if ( $answer eq 'SUBMITTED') {
392: my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
393: my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
394: return $result;
395: } elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
396: my @matches = grep(/^\Q$version\E.*?\.instance$/,
397: keys(%{$record}));
398: return join('<br />',($version,@matches));
399:
400:
401: } else {
402: my $result =
403: '<p>'
404: .&mt('Overall result: [_1]',
405: $record->{$version."resource.$respid.$partid.status"})
406: .'</p>';
407:
408: $result .= '<ul>';
409: my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
410: keys(%{$record}));
411: foreach my $grade (sort(@grade)) {
412: my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
413: $result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
414: $dim, $record->{$grade}).
415: '</li>';
416: }
417: $result.='</ul>';
418: return $result;
419: }
420: } elsif ( $response =~ m/(?:numerical|formula)/) {
421: $answer =
422: &Apache::loncommon::format_previous_attempt_value('submission',
423: $answer);
424: }
425: return $answer;
426: }
427:
428: #-- A couple of common js functions
429: sub commonJSfunctions {
430: my $request = shift;
431: $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
432: function radioSelection(radioButton) {
433: var selection=null;
434: if (radioButton.length > 1) {
435: for (var i=0; i<radioButton.length; i++) {
436: if (radioButton[i].checked) {
437: return radioButton[i].value;
438: }
439: }
440: } else {
441: if (radioButton.checked) return radioButton.value;
442: }
443: return selection;
444: }
445:
446: function pullDownSelection(selectOne) {
447: var selection="";
448: if (selectOne.length > 1) {
449: for (var i=0; i<selectOne.length; i++) {
450: if (selectOne[i].selected) {
451: return selectOne[i].value;
452: }
453: }
454: } else {
455: // only one value it must be the selected one
456: return selectOne.value;
457: }
458: }
459: COMMONJSFUNCTIONS
460: }
461:
462: #--- Dumps the class list with usernames,list of sections,
463: #--- section, ids and fullnames for each user.
464: sub getclasslist {
465: my ($getsec,$filterlist,$getgroup) = @_;
466: my @getsec;
467: my @getgroup;
468: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
469: if (!ref($getsec)) {
470: if ($getsec ne '' && $getsec ne 'all') {
471: @getsec=($getsec);
472: }
473: } else {
474: @getsec=@{$getsec};
475: }
476: if (grep(/^all$/,@getsec)) { undef(@getsec); }
477: if (!ref($getgroup)) {
478: if ($getgroup ne '' && $getgroup ne 'all') {
479: @getgroup=($getgroup);
480: }
481: } else {
482: @getgroup=@{$getgroup};
483: }
484: if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
485:
486: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
487: # Bail out if we were unable to get the classlist
488: return if (! defined($classlist));
489: &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
490: #
491: my %sections;
492: my %fullnames;
493: foreach my $student (keys(%$classlist)) {
494: my $end =
495: $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
496: my $start =
497: $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
498: my $id =
499: $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
500: my $section =
501: $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
502: my $fullname =
503: $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
504: my $status =
505: $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
506: my $group =
507: $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
508: # filter students according to status selected
509: if ($filterlist && (!($stu_status =~ /Any/))) {
510: if (!($stu_status =~ $status)) {
511: delete($classlist->{$student});
512: next;
513: }
514: }
515: # filter students according to groups selected
516: my @stu_groups = split(/,/,$group);
517: if (@getgroup) {
518: my $exclude = 1;
519: foreach my $grp (@getgroup) {
520: foreach my $stu_group (@stu_groups) {
521: if ($stu_group eq $grp) {
522: $exclude = 0;
523: }
524: }
525: if (($grp eq 'none') && !$group) {
526: $exclude = 0;
527: }
528: }
529: if ($exclude) {
530: delete($classlist->{$student});
531: }
532: }
533: $section = ($section ne '' ? $section : 'none');
534: if (&canview($section)) {
535: if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
536: $sections{$section}++;
537: if ($classlist->{$student}) {
538: $fullnames{$student}=$fullname;
539: }
540: } else {
541: delete($classlist->{$student});
542: }
543: } else {
544: delete($classlist->{$student});
545: }
546: }
547: my %seen = ();
548: my @sections = sort(keys(%sections));
549: return ($classlist,\@sections,\%fullnames);
550: }
551:
552: sub canmodify {
553: my ($sec)=@_;
554: if ($perm{'mgr'}) {
555: if (!defined($perm{'mgr_section'})) {
556: # can modify whole class
557: return 1;
558: } else {
559: if ($sec eq $perm{'mgr_section'}) {
560: #can modify the requested section
561: return 1;
562: } else {
563: # can't modify the request section
564: return 0;
565: }
566: }
567: }
568: #can't modify
569: return 0;
570: }
571:
572: sub canview {
573: my ($sec)=@_;
574: if ($perm{'vgr'}) {
575: if (!defined($perm{'vgr_section'})) {
576: # can modify whole class
577: return 1;
578: } else {
579: if ($sec eq $perm{'vgr_section'}) {
580: #can modify the requested section
581: return 1;
582: } else {
583: # can't modify the request section
584: return 0;
585: }
586: }
587: }
588: #can't modify
589: return 0;
590: }
591:
592: #--- Retrieve the grade status of a student for all the parts
593: sub student_gradeStatus {
594: my ($symb,$udom,$uname,$partlist) = @_;
595: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
596: my %partstatus = ();
597: foreach (@$partlist) {
598: my ($status,undef) = split(/_/,$record{"resource.$_.solved"},2);
599: $status = 'nothing' if ($status eq '');
600: $partstatus{$_} = $status;
601: my $subkey = "resource.$_.submitted_by";
602: $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
603: }
604: return %partstatus;
605: }
606:
607: # hidden form and javascript that calls the form
608: # Use by verifyscript and viewgrades
609: # Shows a student's view of problem and submission
610: sub jscriptNform {
611: my ($symb) = @_;
612: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
613: my $jscript= &Apache::lonhtmlcommon::scripttag(
614: ' function viewOneStudent(user,domain) {'."\n".
615: ' document.onestudent.student.value = user;'."\n".
616: ' document.onestudent.userdom.value = domain;'."\n".
617: ' document.onestudent.submit();'."\n".
618: ' }'."\n".
619: "\n");
620: $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
621: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
622: '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
623: '<input type="hidden" name="command" value="submission" />'."\n".
624: '<input type="hidden" name="student" value="" />'."\n".
625: '<input type="hidden" name="userdom" value="" />'."\n".
626: '</form>'."\n";
627: return $jscript;
628: }
629:
630:
631:
632: # Given the score (as a number [0-1] and the weight) what is the final
633: # point value? This function will round to the nearest tenth, third,
634: # or quarter if one of those is within the tolerance of .00001.
635: sub compute_points {
636: my ($score, $weight) = @_;
637:
638: my $tolerance = .00001;
639: my $points = $score * $weight;
640:
641: # Check for nearness to 1/x.
642: my $check_for_nearness = sub {
643: my ($factor) = @_;
644: my $num = ($points * $factor) + $tolerance;
645: my $floored_num = floor($num);
646: if ($num - $floored_num < 2 * $tolerance * $factor) {
647: return $floored_num / $factor;
648: }
649: return $points;
650: };
651:
652: $points = $check_for_nearness->(10);
653: $points = $check_for_nearness->(3);
654: $points = $check_for_nearness->(4);
655:
656: return $points;
657: }
658:
659: #------------------ End of general use routines --------------------
660:
661: #
662: # Find most similar essay
663: #
664:
665: sub most_similar {
666: my ($uname,$udom,$uessay,$old_essays)=@_;
667:
668: # ignore spaces and punctuation
669:
670: $uessay=~s/\W+/ /gs;
671:
672: # ignore empty submissions (occuring when only files are sent)
673:
674: unless ($uessay=~/\w+/s) { return ''; }
675:
676: # these will be returned. Do not care if not at least 50 percent similar
677: my $limit=0.6;
678: my $sname='';
679: my $sdom='';
680: my $scrsid='';
681: my $sessay='';
682: # go through all essays ...
683: foreach my $tkey (keys(%$old_essays)) {
684: my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
685: # ... except the same student
686: next if (($tname eq $uname) && ($tdom eq $udom));
687: my $tessay=$old_essays->{$tkey};
688: $tessay=~s/\W+/ /gs;
689: # String similarity gives up if not even limit
690: my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
691: # Found one
692: if ($tsimilar>$limit) {
693: $limit=$tsimilar;
694: $sname=$tname;
695: $sdom=$tdom;
696: $scrsid=$tcrsid;
697: $sessay=$old_essays->{$tkey};
698: }
699: }
700: if ($limit>0.6) {
701: return ($sname,$sdom,$scrsid,$sessay,$limit);
702: } else {
703: return ('','','','',0);
704: }
705: }
706:
707: #-------------------------------------------------------------------
708:
709: #------------------------------------ Receipt Verification Routines
710: #
711:
712: sub initialverifyreceipt {
713: my ($request,$symb) = @_;
714: &commonJSfunctions($request);
715: return '<form name="gradingMenu"><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
716: &Apache::lonnet::recprefix($env{'request.course.id'}).
717: '-<input type="text" name="receipt" size="4" />'.
718: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
719: '<input type="hidden" name="command" value="verify" />'.
720: "</form>\n";
721: }
722:
723: #--- Check whether a receipt number is valid.---
724: sub verifyreceipt {
725: my ($request,$symb) = @_;
726:
727: my $courseid = $env{'request.course.id'};
728: my $receipt = &Apache::lonnet::recprefix($courseid).'-'.
729: $env{'form.receipt'};
730: $receipt =~ s/[^\-\d]//g;
731:
732: my $title.=
733: '<h3><span class="LC_info">'.
734: &mt('Verifying Receipt Number [_1]',$receipt).
735: '</span></h3>'."\n";
736:
737: my ($string,$contents,$matches) = ('','',0);
738: my (undef,undef,$fullname) = &getclasslist('all','0');
739:
740: my $receiptparts=0;
741: if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
742: $env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
743: my $parts=['0'];
744: if ($receiptparts) {
745: my $res_error;
746: ($parts)=&response_type($symb,\$res_error);
747: if ($res_error) {
748: return &navmap_errormsg();
749: }
750: }
751:
752: my $header =
753: &Apache::loncommon::start_data_table().
754: &Apache::loncommon::start_data_table_header_row().
755: '<th> '.&mt('Fullname').' </th>'."\n".
756: '<th> '.&mt('Username').' </th>'."\n".
757: '<th> '.&mt('Domain').' </th>';
758: if ($receiptparts) {
759: $header.='<th> '.&mt('Problem Part').' </th>';
760: }
761: $header.=
762: &Apache::loncommon::end_data_table_header_row();
763:
764: foreach (sort
765: {
766: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
767: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
768: }
769: return $a cmp $b;
770: } (keys(%$fullname))) {
771: my ($uname,$udom)=split(/\:/);
772: foreach my $part (@$parts) {
773: if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
774: $contents.=
775: &Apache::loncommon::start_data_table_row().
776: '<td> '."\n".
777: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
778: '\');" target="_self">'.$$fullname{$_}.'</a> </td>'."\n".
779: '<td> '.$uname.' </td>'.
780: '<td> '.$udom.' </td>';
781: if ($receiptparts) {
782: $contents.='<td> '.$part.' </td>';
783: }
784: $contents.=
785: &Apache::loncommon::end_data_table_row()."\n";
786:
787: $matches++;
788: }
789: }
790: }
791: if ($matches == 0) {
792: $string = $title
793: .'<p class="LC_warning">'
794: .&mt('No match found for the above receipt number.')
795: .'</p>';
796: } else {
797: $string = &jscriptNform($symb).$title.
798: '<p>'.
799: &mt('The above receipt number matches the following [quant,_1,student].',$matches).
800: '</p>'.
801: $header.
802: $contents.
803: &Apache::loncommon::end_data_table()."\n";
804: }
805: return $string;
806: }
807:
808: #--- This is called by a number of programs.
809: #--- Called from the Grading Menu - View/Grade an individual student
810: #--- Also called directly when one clicks on the subm button
811: # on the problem page.
812: sub listStudents {
813: my ($request,$symb,$submitonly) = @_;
814:
815: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
816: my $cnum = $env{"course.$env{'request.course.id'}.num"};
817: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
818: my $getgroup = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
819: unless ($submitonly) {
820: $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
821: }
822:
823: my $result='<h3><span class="LC_info"> '
824: .&mt("View/Grade/Regrade Submissions for a Student or a Group of Students")
825: .'</span></h3>';
826: my $res_error;
827: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
828:
829: my %lt = &Apache::lonlocal::texthash (
830: 'multiple' => 'Please select a student or group of students before clicking on the Next button.',
831: 'single' => 'Please select the student before clicking on the Next button.',
832: );
833: $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
834: function checkSelect(checkBox) {
835: var ctr=0;
836: var sense="";
837: if (checkBox.length > 1) {
838: for (var i=0; i<checkBox.length; i++) {
839: if (checkBox[i].checked) {
840: ctr++;
841: }
842: }
843: sense = '$lt{'multiple'}';
844: } else {
845: if (checkBox.checked) {
846: ctr = 1;
847: }
848: sense = '$lt{'single'}';
849: }
850: if (ctr == 0) {
851: alert(sense);
852: return false;
853: }
854: document.gradesub.submit();
855: }
856:
857: function reLoadList(formname) {
858: if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
859: formname.command.value = 'submission';
860: formname.submit();
861: }
862: LISTJAVASCRIPT
863:
864: &commonJSfunctions($request);
865: $request->print($result);
866:
867: my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
868: "\n";
869:
870: $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
871: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
872: .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
873: .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
874: .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
875: .&Apache::lonhtmlcommon::row_closure();
876: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
877: .'<label><input type="radio" name="vAns" value="no" /> '.&mt('no').' </label>'."\n"
878: .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
879: .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
880: .&Apache::lonhtmlcommon::row_closure();
881:
882: my $submission_options;
883: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
884: my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
885: $env{'form.Status'} = $saveStatus;
886: $submission_options.=
887: '<span class="LC_nobreak">'.
888: '<label><input type="radio" name="lastSub" value="lastonly" /> '.
889: &mt('last submission only').' </label></span>'."\n".
890: '<span class="LC_nobreak">'.
891: '<label><input type="radio" name="lastSub" value="last" /> '.
892: &mt('last submission & parts info').' </label></span>'."\n".
893: '<span class="LC_nobreak">'.
894: '<label><input type="radio" name="lastSub" value="datesub" /> '.
895: &mt('by dates and submissions').'</label></span>'."\n".
896: '<span class="LC_nobreak">'.
897: '<label><input type="radio" name="lastSub" value="all" /> '.
898: &mt('all details').'</label></span>';
899: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
900: .$submission_options
901: .&Apache::lonhtmlcommon::row_closure();
902:
903: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
904: .'<select name="increment">'
905: .'<option value="1">'.&mt('Whole Points').'</option>'
906: .'<option value=".5">'.&mt('Half Points').'</option>'
907: .'<option value=".25">'.&mt('Quarter Points').'</option>'
908: .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
909: .'</select>'
910: .&Apache::lonhtmlcommon::row_closure();
911:
912: $gradeTable .=
913: &build_section_inputs().
914: '<input type="hidden" name="submitonly" value="'.$submitonly.'" />'."\n".
915: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
916: '<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
917:
918: if (exists($env{'form.Status'})) {
919: $gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
920: } else {
921: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
922: .&Apache::lonhtmlcommon::StatusOptions(
923: $saveStatus,undef,1,'javascript:reLoadList(this.form);')
924: .&Apache::lonhtmlcommon::row_closure();
925: }
926:
927: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
928: .'<input type="checkbox" name="checkPlag" checked="checked" />'
929: .&Apache::lonhtmlcommon::row_closure(1)
930: .&Apache::lonhtmlcommon::end_pick_box();
931:
932: $gradeTable .= '<p>'
933: .&mt("To view/grade/regrade a submission or a group of submissions, click on the check box(es) next to the student's name(s). Then click on the Next button.")."\n"
934: .'<input type="hidden" name="command" value="processGroup" />'
935: .'</p>';
936:
937: # checkall buttons
938: $gradeTable.=&check_script('gradesub', 'stuinfo');
939: $gradeTable.='<input type="button" '."\n".
940: 'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
941: 'value="'.&mt('Next').' →" /> <br />'."\n";
942: $gradeTable.=&check_buttons();
943: my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
944: $gradeTable.= &Apache::loncommon::start_data_table().
945: &Apache::loncommon::start_data_table_header_row();
946: my $loop = 0;
947: while ($loop < 2) {
948: $gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
949: '<th>'.&nameUserString('header').' '.&mt('Section/Group').'</th>';
950: if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
951: foreach my $part (sort(@$partlist)) {
952: my $display_part=
953: &get_display_part((split(/_/,$part))[0],$symb);
954: $gradeTable.=
955: '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
956: }
957: } elsif ($submitonly eq 'queued') {
958: $gradeTable.='<th>'.&mt('Queue Status').' </th>';
959: }
960: $loop++;
961: # $gradeTable.='<td></td>' if ($loop%2 ==1);
962: }
963: $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
964:
965: my $ctr = 0;
966: foreach my $student (sort
967: {
968: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
969: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
970: }
971: return $a cmp $b;
972: }
973: (keys(%$fullname))) {
974: my ($uname,$udom) = split(/:/,$student);
975:
976: my %status = ();
977:
978: if ($submitonly eq 'queued') {
979: my %queue_status =
980: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
981: $udom,$uname);
982: next if (!defined($queue_status{'gradingqueue'}));
983: $status{'gradingqueue'} = $queue_status{'gradingqueue'};
984: }
985:
986: if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
987: (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
988: my $submitted = 0;
989: my $graded = 0;
990: my $incorrect = 0;
991: foreach (keys(%status)) {
992: $submitted = 1 if ($status{$_} ne 'nothing');
993: $graded = 1 if ($status{$_} =~ /^ungraded/);
994: $incorrect = 1 if ($status{$_} =~ /^incorrect/);
995:
996: my ($foo,$partid,$foo1) = split(/\./,$_);
997: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
998: $submitted = 0;
999: my ($part)=split(/\./,$partid);
1000: $gradeTable.='<input type="hidden" name="'.
1001: $student.':'.$part.':submitted_by" value="'.
1002: $status{'resource.'.$partid.'.submitted_by'}.'" />';
1003: }
1004: }
1005:
1006: next if (!$submitted && ($submitonly eq 'yes' ||
1007: $submitonly eq 'incorrect' ||
1008: $submitonly eq 'graded'));
1009: next if (!$graded && ($submitonly eq 'graded'));
1010: next if (!$incorrect && $submitonly eq 'incorrect');
1011: }
1012:
1013: $ctr++;
1014: my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1015: my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1016: if ( $perm{'vgr'} eq 'F' ) {
1017: if ($ctr%2 ==1) {
1018: $gradeTable.= &Apache::loncommon::start_data_table_row();
1019: }
1020: $gradeTable.='<td align="right">'.$ctr.' </td>'.
1021: '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1022: $student.':'.$$fullname{$student}.':::SECTION'.$section.
1023: ') " /> </label></td>'."\n".'<td>'.
1024: &nameUserString(undef,$$fullname{$student},$uname,$udom).
1025: ' '.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1026:
1027: if ($submitonly ne 'all') {
1028: foreach (sort(keys(%status))) {
1029: next if ($_ =~ /^resource.*?submitted_by$/);
1030: $gradeTable.='<td align="center"> '.&mt($status{$_}).' </td>'."\n";
1031: }
1032: }
1033: # $gradeTable.='<td></td>' if ($ctr%2 ==1);
1034: if ($ctr%2 ==0) {
1035: $gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
1036: }
1037: }
1038: }
1039: if ($ctr%2 ==1) {
1040: $gradeTable.='<td> </td><td> </td><td> </td>';
1041: if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1042: foreach (@$partlist) {
1043: $gradeTable.='<td> </td>';
1044: }
1045: } elsif ($submitonly eq 'queued') {
1046: $gradeTable.='<td> </td>';
1047: }
1048: $gradeTable.=&Apache::loncommon::end_data_table_row();
1049: }
1050:
1051: $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1052: '<input type="button" '.
1053: 'onclick="javascript:checkSelect(this.form.stuinfo);" '.
1054: 'value="'.&mt('Next').' →" /></form>'."\n";
1055: if ($ctr == 0) {
1056: my $num_students=(scalar(keys(%$fullname)));
1057: if ($num_students eq 0) {
1058: $gradeTable='<br /> <span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1059: } else {
1060: my $submissions='submissions';
1061: if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
1062: if ($submitonly eq 'graded' ) { $submissions = 'ungraded submissions'; }
1063: if ($submitonly eq 'queued' ) { $submissions = 'queued submissions'; }
1064: $gradeTable='<br /> <span class="LC_warning">'.
1065: &mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
1066: $num_students).
1067: '</span><br />';
1068: }
1069: } elsif ($ctr == 1) {
1070: $gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1071: }
1072: $request->print($gradeTable);
1073: return '';
1074: }
1075:
1076: #---- Called from the listStudents routine
1077:
1078: sub check_script {
1079: my ($form, $type)=@_;
1080: my $chkallscript= &Apache::lonhtmlcommon::scripttag('
1081: function checkall() {
1082: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1083: ele = document.forms.'.$form.'.elements[i];
1084: if (ele.name == "'.$type.'") {
1085: document.forms.'.$form.'.elements[i].checked=true;
1086: }
1087: }
1088: }
1089:
1090: function checksec() {
1091: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1092: ele = document.forms.'.$form.'.elements[i];
1093: string = document.forms.'.$form.'.chksec.value;
1094: if
1095: (ele.value.indexOf(":::SECTION"+string)>0) {
1096: document.forms.'.$form.'.elements[i].checked=true;
1097: }
1098: }
1099: }
1100:
1101:
1102: function uncheckall() {
1103: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1104: ele = document.forms.'.$form.'.elements[i];
1105: if (ele.name == "'.$type.'") {
1106: document.forms.'.$form.'.elements[i].checked=false;
1107: }
1108: }
1109: }
1110:
1111: '."\n");
1112: return $chkallscript;
1113: }
1114:
1115: sub check_buttons {
1116: my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
1117: $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" /> ';
1118: $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1119: $buttons.='<input type="text" size="5" name="chksec" /> ';
1120: return $buttons;
1121: }
1122:
1123: # Displays the submissions for one student or a group of students
1124: sub processGroup {
1125: my ($request,$symb) = @_;
1126: my $ctr = 0;
1127: my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1128: my $total = scalar(@stuchecked)-1;
1129:
1130: foreach my $student (@stuchecked) {
1131: my ($uname,$udom,$fullname) = split(/:/,$student);
1132: $env{'form.student'} = $uname;
1133: $env{'form.userdom'} = $udom;
1134: $env{'form.fullname'} = $fullname;
1135: &submission($request,$ctr,$total,$symb);
1136: $ctr++;
1137: }
1138: return '';
1139: }
1140:
1141: #------------------------------------------------------------------------------------
1142: #
1143: #-------------------------- Next few routines handles grading by student, essentially
1144: # handles essay response type problem/part
1145: #
1146: #--- Javascript to handle the submission page functionality ---
1147: sub sub_page_js {
1148: my $request = shift;
1149: my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1150: $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1151: function updateRadio(formname,id,weight) {
1152: var gradeBox = formname["GD_BOX"+id];
1153: var radioButton = formname["RADVAL"+id];
1154: var oldpts = formname["oldpts"+id].value;
1155: var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1156: gradeBox.value = pts;
1157: var resetbox = false;
1158: if (isNaN(pts) || pts < 0) {
1159: alert("$alertmsg"+pts);
1160: for (var i=0; i<radioButton.length; i++) {
1161: if (radioButton[i].checked) {
1162: gradeBox.value = i;
1163: resetbox = true;
1164: }
1165: }
1166: if (!resetbox) {
1167: formtextbox.value = "";
1168: }
1169: return;
1170: }
1171:
1172: if (pts > weight) {
1173: var resp = confirm("You entered a value ("+pts+
1174: ") greater than the weight for the part. Accept?");
1175: if (resp == false) {
1176: gradeBox.value = oldpts;
1177: return;
1178: }
1179: }
1180:
1181: for (var i=0; i<radioButton.length; i++) {
1182: radioButton[i].checked=false;
1183: if (pts == i && pts != "") {
1184: radioButton[i].checked=true;
1185: }
1186: }
1187: updateSelect(formname,id);
1188: formname["stores"+id].value = "0";
1189: }
1190:
1191: function writeBox(formname,id,pts) {
1192: var gradeBox = formname["GD_BOX"+id];
1193: if (checkSolved(formname,id) == 'update') {
1194: gradeBox.value = pts;
1195: } else {
1196: var oldpts = formname["oldpts"+id].value;
1197: gradeBox.value = oldpts;
1198: var radioButton = formname["RADVAL"+id];
1199: for (var i=0; i<radioButton.length; i++) {
1200: radioButton[i].checked=false;
1201: if (i == oldpts) {
1202: radioButton[i].checked=true;
1203: }
1204: }
1205: }
1206: formname["stores"+id].value = "0";
1207: updateSelect(formname,id);
1208: return;
1209: }
1210:
1211: function clearRadBox(formname,id) {
1212: if (checkSolved(formname,id) == 'noupdate') {
1213: updateSelect(formname,id);
1214: return;
1215: }
1216: gradeSelect = formname["GD_SEL"+id];
1217: for (var i=0; i<gradeSelect.length; i++) {
1218: if (gradeSelect[i].selected) {
1219: var selectx=i;
1220: }
1221: }
1222: var stores = formname["stores"+id];
1223: if (selectx == stores.value) { return };
1224: var gradeBox = formname["GD_BOX"+id];
1225: gradeBox.value = "";
1226: var radioButton = formname["RADVAL"+id];
1227: for (var i=0; i<radioButton.length; i++) {
1228: radioButton[i].checked=false;
1229: }
1230: stores.value = selectx;
1231: }
1232:
1233: function checkSolved(formname,id) {
1234: if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1235: var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
1236: if (!reply) {return "noupdate";}
1237: formname.overRideScore.value = 'yes';
1238: }
1239: return "update";
1240: }
1241:
1242: function updateSelect(formname,id) {
1243: formname["GD_SEL"+id][0].selected = true;
1244: return;
1245: }
1246:
1247: //=========== Check that a point is assigned for all the parts ============
1248: function checksubmit(formname,val,total,parttot) {
1249: formname.gradeOpt.value = val;
1250: if (val == "Save & Next") {
1251: for (i=0;i<=total;i++) {
1252: for (j=0;j<parttot;j++) {
1253: var partid = formname["partid"+i+"_"+j].value;
1254: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1255: var points = formname["GD_BOX"+i+"_"+partid].value;
1256: if (points == "") {
1257: var name = formname["name"+i].value;
1258: var studentID = (name != '' ? name : formname["unamedom"+i].value);
1259: var resp = confirm("You did not assign a score for "+studentID+
1260: ", part "+partid+". Continue?");
1261: if (resp == false) {
1262: formname["GD_BOX"+i+"_"+partid].focus();
1263: return false;
1264: }
1265: }
1266: }
1267:
1268: }
1269: }
1270:
1271: }
1272: if (val == "Grade Student") {
1273: if (formname.Status.value == "") {
1274: formname.Status.value = "Active";
1275: }
1276: formname.studentNo.value = total;
1277: }
1278: formname.submit();
1279: }
1280:
1281: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
1282: function checkSubmitPage(formname,total) {
1283: noscore = new Array(100);
1284: var ptr = 0;
1285: for (i=1;i<total;i++) {
1286: var partid = formname["q_"+i].value;
1287: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1288: var points = formname["GD_BOX"+i+"_"+partid].value;
1289: var status = formname["solved"+i+"_"+partid].value;
1290: if (points == "" && status != "correct_by_student") {
1291: noscore[ptr] = i;
1292: ptr++;
1293: }
1294: }
1295: }
1296: if (ptr != 0) {
1297: var sense = ptr == 1 ? ": " : "s: ";
1298: var prolist = "";
1299: if (ptr == 1) {
1300: prolist = noscore[0];
1301: } else {
1302: var i = 0;
1303: while (i < ptr-1) {
1304: prolist += noscore[i]+", ";
1305: i++;
1306: }
1307: prolist += "and "+noscore[i];
1308: }
1309: var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
1310: if (resp == false) {
1311: return false;
1312: }
1313: }
1314:
1315: formname.submit();
1316: }
1317: SUBJAVASCRIPT
1318: }
1319:
1320: #--- javascript for essay type problem --
1321: sub sub_page_kw_js {
1322: my $request = shift;
1323: my $iconpath = $request->dir_config('lonIconsURL');
1324: &commonJSfunctions($request);
1325:
1326: my $inner_js_msg_central= &Apache::lonhtmlcommon::scripttag(<<INNERJS);
1327: function checkInput() {
1328: opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
1329: var nmsg = opener.document.SCORE.savemsgN.value;
1330: var usrctr = document.msgcenter.usrctr.value;
1331: var newval = opener.document.SCORE["newmsg"+usrctr];
1332: newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
1333:
1334: var msgchk = "";
1335: if (document.msgcenter.subchk.checked) {
1336: msgchk = "msgsub,";
1337: }
1338: var includemsg = 0;
1339: for (var i=1; i<=nmsg; i++) {
1340: var opnmsg = opener.document.SCORE["savemsg"+i];
1341: var frmmsg = document.msgcenter["msg"+i];
1342: opnmsg.value = opener.checkEntities(frmmsg.value);
1343: var showflg = opener.document.SCORE["shownOnce"+i];
1344: showflg.value = "1";
1345: var chkbox = document.msgcenter["msgn"+i];
1346: if (chkbox.checked) {
1347: msgchk += "savemsg"+i+",";
1348: includemsg = 1;
1349: }
1350: }
1351: if (document.msgcenter.newmsgchk.checked) {
1352: msgchk += "newmsg"+usrctr;
1353: includemsg = 1;
1354: }
1355: imgformname = opener.document.SCORE["mailicon"+usrctr];
1356: imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
1357: var includemsg = opener.document.SCORE["includemsg"+usrctr];
1358: includemsg.value = msgchk;
1359:
1360: self.close()
1361:
1362: }
1363: INNERJS
1364:
1365: my $inner_js_highlight_central= &Apache::lonhtmlcommon::scripttag(<<INNERJS);
1366: function updateChoice(flag) {
1367: opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
1368: opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
1369: opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
1370: opener.document.SCORE.refresh.value = "on";
1371: if (opener.document.SCORE.keywords.value!=""){
1372: opener.document.SCORE.submit();
1373: }
1374: self.close()
1375: }
1376: INNERJS
1377:
1378: my $start_page_msg_central =
1379: &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
1380: {'js_ready' => 1,
1381: 'only_body' => 1,
1382: 'bgcolor' =>'#FFFFFF',});
1383: my $end_page_msg_central =
1384: &Apache::loncommon::end_page({'js_ready' => 1});
1385:
1386:
1387: my $start_page_highlight_central =
1388: &Apache::loncommon::start_page('Highlight Central',
1389: $inner_js_highlight_central,
1390: {'js_ready' => 1,
1391: 'only_body' => 1,
1392: 'bgcolor' =>'#FFFFFF',});
1393: my $end_page_highlight_central =
1394: &Apache::loncommon::end_page({'js_ready' => 1});
1395:
1396: my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1397: $docopen=~s/^document\.//;
1398: my $alertmsg = &mt('Please select a word or group of words from document and then click this link.');
1399: $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1400:
1401: //===================== Show list of keywords ====================
1402: function keywords(formname) {
1403: var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1404: if (nret==null) return;
1405: formname.keywords.value = nret;
1406:
1407: if (formname.keywords.value != "") {
1408: formname.refresh.value = "on";
1409: formname.submit();
1410: }
1411: return;
1412: }
1413:
1414: //===================== Script to view submitted by ==================
1415: function viewSubmitter(submitter) {
1416: document.SCORE.refresh.value = "on";
1417: document.SCORE.NCT.value = "1";
1418: document.SCORE.unamedom0.value = submitter;
1419: document.SCORE.submit();
1420: return;
1421: }
1422:
1423: //===================== Script to add keyword(s) ==================
1424: function getSel() {
1425: if (document.getSelection) txt = document.getSelection();
1426: else if (document.selection) txt = document.selection.createRange().text;
1427: else return;
1428: var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
1429: if (cleantxt=="") {
1430: alert("$alertmsg");
1431: return;
1432: }
1433: var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
1434: if (nret==null) return;
1435: document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1436: if (document.SCORE.keywords.value != "") {
1437: document.SCORE.refresh.value = "on";
1438: document.SCORE.submit();
1439: }
1440: return;
1441: }
1442:
1443: //====================== Script for composing message ==============
1444: // preload images
1445: img1 = new Image();
1446: img1.src = "$iconpath/mailbkgrd.gif";
1447: img2 = new Image();
1448: img2.src = "$iconpath/mailto.gif";
1449:
1450: function msgCenter(msgform,usrctr,fullname) {
1451: var Nmsg = msgform.savemsgN.value;
1452: savedMsgHeader(Nmsg,usrctr,fullname);
1453: var subject = msgform.msgsub.value;
1454: var msgchk = document.SCORE["includemsg"+usrctr].value;
1455: re = /msgsub/;
1456: var shwsel = "";
1457: if (re.test(msgchk)) { shwsel = "checked" }
1458: subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
1459: displaySubject(checkEntities(subject),shwsel);
1460: for (var i=1; i<=Nmsg; i++) {
1461: var testmsg = "savemsg"+i+",";
1462: re = new RegExp(testmsg,"g");
1463: shwsel = "";
1464: if (re.test(msgchk)) { shwsel = "checked" }
1465: var message = document.SCORE["savemsg"+i].value;
1466: message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1467: displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
1468: //any < is already converted to <, etc. However, only once!!
1469: }
1470: newmsg = document.SCORE["newmsg"+usrctr].value;
1471: shwsel = "";
1472: re = /newmsg/;
1473: if (re.test(msgchk)) { shwsel = "checked" }
1474: newMsg(newmsg,shwsel);
1475: msgTail();
1476: return;
1477: }
1478:
1479: function checkEntities(strx) {
1480: if (strx.length == 0) return strx;
1481: var orgStr = ["&", "<", ">", '"'];
1482: var newStr = ["&", "<", ">", """];
1483: var counter = 0;
1484: while (counter < 4) {
1485: strx = strReplace(strx,orgStr[counter],newStr[counter]);
1486: counter++;
1487: }
1488: return strx;
1489: }
1490:
1491: function strReplace(strx, orgStr, newStr) {
1492: return strx.split(orgStr).join(newStr);
1493: }
1494:
1495: function savedMsgHeader(Nmsg,usrctr,fullname) {
1496: var height = 70*Nmsg+250;
1497: var scrollbar = "no";
1498: if (height > 600) {
1499: height = 600;
1500: scrollbar = "yes";
1501: }
1502: var xpos = (screen.width-600)/2;
1503: xpos = (xpos < 0) ? '0' : xpos;
1504: var ypos = (screen.height-height)/2-30;
1505: ypos = (ypos < 0) ? '0' : ypos;
1506:
1507: pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1508: pWin.focus();
1509: pDoc = pWin.document;
1510: pDoc.$docopen;
1511: pDoc.write('$start_page_msg_central');
1512:
1513: pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
1514: pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1515: pDoc.write("<h3><span class=\\"LC_info\\"> Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
1516:
1517: pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
1518: pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1519: pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
1520: }
1521: function displaySubject(msg,shwsel) {
1522: pDoc = pWin.document;
1523: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1524: pDoc.write("<td>Subject<\\/td>");
1525: pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1526: pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1527: }
1528:
1529: function displaySavedMsg(ctr,msg,shwsel) {
1530: pDoc = pWin.document;
1531: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1532: pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
1533: pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1534: pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1535: }
1536:
1537: function newMsg(newmsg,shwsel) {
1538: pDoc = pWin.document;
1539: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1540: pDoc.write("<td align=\\"center\\">New<\\/td>");
1541: pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1542: pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1543: }
1544:
1545: function msgTail() {
1546: pDoc = pWin.document;
1547: pDoc.write("<\\/table>");
1548: pDoc.write("<\\/td><\\/tr><\\/table> ");
1549: pDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:checkInput()\\"> ");
1550: pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
1551: pDoc.write("<\\/form>");
1552: pDoc.write('$end_page_msg_central');
1553: pDoc.close();
1554: }
1555:
1556: //====================== Script for keyword highlight options ==============
1557: function kwhighlight() {
1558: var kwclr = document.SCORE.kwclr.value;
1559: var kwsize = document.SCORE.kwsize.value;
1560: var kwstyle = document.SCORE.kwstyle.value;
1561: var redsel = "";
1562: var grnsel = "";
1563: var blusel = "";
1564: if (kwclr=="red") {var redsel="checked"};
1565: if (kwclr=="green") {var grnsel="checked"};
1566: if (kwclr=="blue") {var blusel="checked"};
1567: var sznsel = "";
1568: var sz1sel = "";
1569: var sz2sel = "";
1570: if (kwsize=="0") {var sznsel="checked"};
1571: if (kwsize=="+1") {var sz1sel="checked"};
1572: if (kwsize=="+2") {var sz2sel="checked"};
1573: var synsel = "";
1574: var syisel = "";
1575: var sybsel = "";
1576: if (kwstyle=="") {var synsel="checked"};
1577: if (kwstyle=="<i>") {var syisel="checked"};
1578: if (kwstyle=="<b>") {var sybsel="checked"};
1579: highlightCentral();
1580: highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
1581: highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
1582: highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
1583: highlightend();
1584: return;
1585: }
1586:
1587: function highlightCentral() {
1588: // if (window.hwdWin) window.hwdWin.close();
1589: var xpos = (screen.width-400)/2;
1590: xpos = (xpos < 0) ? '0' : xpos;
1591: var ypos = (screen.height-330)/2-30;
1592: ypos = (ypos < 0) ? '0' : ypos;
1593:
1594: hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1595: hwdWin.focus();
1596: var hDoc = hwdWin.document;
1597: hDoc.$docopen;
1598: hDoc.write('$start_page_highlight_central');
1599: hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1600: hDoc.write("<h3><span class=\\"LC_info\\"> Keyword Highlight Options<\\/span><\\/h3><br /><br />");
1601:
1602: hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
1603: hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1604: hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
1605: }
1606:
1607: function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) {
1608: var hDoc = hwdWin.document;
1609: hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1610: hDoc.write("<td align=\\"left\\">");
1611: hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+"> "+clrtxt+"<\\/td>");
1612: hDoc.write("<td align=\\"left\\">");
1613: hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+"> "+sztxt+"<\\/td>");
1614: hDoc.write("<td align=\\"left\\">");
1615: hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+"> "+sytxt+"<\\/td>");
1616: hDoc.write("<\\/tr>");
1617: }
1618:
1619: function highlightend() {
1620: var hDoc = hwdWin.document;
1621: hDoc.write("<\\/table>");
1622: hDoc.write("<\\/td><\\/tr><\\/table> ");
1623: hDoc.write("<input type=\\"button\\" value=\\"Save\\" onclick=\\"javascript:updateChoice(1)\\"> ");
1624: hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onclick=\\"self.close()\\"><br /><br />");
1625: hDoc.write("<\\/form>");
1626: hDoc.write('$end_page_highlight_central');
1627: hDoc.close();
1628: }
1629:
1630: SUBJAVASCRIPT
1631: }
1632:
1633: sub get_increment {
1634: my $increment = $env{'form.increment'};
1635: if ($increment != 1 && $increment != .5 && $increment != .25 &&
1636: $increment != .1) {
1637: $increment = 1;
1638: }
1639: return $increment;
1640: }
1641:
1642: sub gradeBox_start {
1643: return (
1644: &Apache::loncommon::start_data_table()
1645: .&Apache::loncommon::start_data_table_header_row()
1646: .'<th>'.&mt('Part').'</th>'
1647: .'<th>'.&mt('Points').'</th>'
1648: .'<th> </th>'
1649: .'<th>'.&mt('Assign Grade').'</th>'
1650: .'<th>'.&mt('Weight').'</th>'
1651: .'<th>'.&mt('Grade Status').'</th>'
1652: .&Apache::loncommon::end_data_table_header_row()
1653: );
1654: }
1655:
1656: sub gradeBox_end {
1657: return (
1658: &Apache::loncommon::end_data_table()
1659: );
1660: }
1661: #--- displays the grading box, used in essay type problem and grading by page/sequence
1662: sub gradeBox {
1663: my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1664: my $checkIcon = '<img alt="'.&mt('Check Mark').
1665: '" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1666: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1667: my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)')
1668: : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1669: $wgt = ($wgt > 0 ? $wgt : '1');
1670: my $score = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1671: '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1672: my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1673: my $display_part= &get_display_part($partid,$symb);
1674: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
1675: [$partid]);
1676: my $aggtries = $$record{'resource.'.$partid.'.tries'};
1677: if ($last_resets{$partid}) {
1678: $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
1679: }
1680: $result.=&Apache::loncommon::start_data_table_row();
1681: my $ctr = 0;
1682: my $thisweight = 0;
1683: my $increment = &get_increment();
1684:
1685: my $radio.='<table border="0"><tr>'."\n"; # display radio buttons in a nice table 10 across
1686: while ($thisweight<=$wgt) {
1687: $radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1688: 'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1689: $thisweight.')" value="'.$thisweight.'" '.
1690: ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1691: $radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1692: $thisweight += $increment;
1693: $ctr++;
1694: }
1695: $radio.='</tr></table>';
1696:
1697: my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1698: ($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1699: 'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1700: $wgt.')" /></td>'."\n";
1701: $line.='<td>/'.$wgt.' '.$wgtmsg.
1702: ($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? ' '.$checkIcon : '').
1703: ' </td>'."\n";
1704: $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1705: 'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1706: if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1707: $line.='<option></option>'.
1708: '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1709: } else {
1710: $line.='<option selected="selected"></option>'.
1711: '<option value="excused" >'.&mt('excused').'</option>';
1712: }
1713: $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
1714:
1715:
1716: $result .=
1717: '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
1718: $result.=&Apache::loncommon::end_data_table_row();
1719: $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
1720: '<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
1721: '<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1722: $$record{'resource.'.$partid.'.solved'}.'" />'."\n".
1723: '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
1724: $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
1725: '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
1726: $aggtries.'" />'."\n";
1727: my $res_error;
1728: $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1729: if ($res_error) {
1730: return &navmap_errormsg();
1731: }
1732: return $result;
1733: }
1734:
1735: sub handback_box {
1736: my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
1737: my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
1738: my (@respids);
1739: my @part_response_id = &flatten_responseType($responseType);
1740: foreach my $part_response_id (@part_response_id) {
1741: my ($part,$resp) = @{ $part_response_id };
1742: if ($part eq $partid) {
1743: push(@respids,$resp);
1744: }
1745: }
1746: my $result;
1747: foreach my $respid (@respids) {
1748: my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
1749: my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
1750: next if (!@$files);
1751: my $file_counter = 1;
1752: foreach my $file (@$files) {
1753: if ($file =~ /\/portfolio\//) {
1754: my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1755: my ($name,$version,$ext) = &file_name_version_ext($file_disp);
1756: $file_disp = "$name.$ext";
1757: $file = $file_path.$file_disp;
1758: $result.=&mt('Return commented version of [_1] to student.',
1759: '<span class="LC_filename">'.$file_disp.'</span>');
1760: $result.='<input type="file" name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1761: $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1762: $result.='('.&mt('File will be uploaded when you click on Save & Next below.').')<br />';
1763: $file_counter++;
1764: }
1765: }
1766: }
1767: return $result;
1768: }
1769:
1770: sub show_problem {
1771: my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1772: my $rendered;
1773: my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1774: &Apache::lonxml::remember_problem_counter();
1775: if ($mode eq 'both' or $mode eq 'text') {
1776: $rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1777: $env{'request.course.id'},
1778: undef,\%form);
1779: }
1780: if ($removeform) {
1781: $rendered=~s|<form(.*?)>||g;
1782: $rendered=~s|</form>||g;
1783: $rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1784: }
1785: my $companswer;
1786: if ($mode eq 'both' or $mode eq 'answer') {
1787: &Apache::lonxml::restore_problem_counter();
1788: $companswer=
1789: &Apache::loncommon::get_student_answers($symb,$uname,$udom,
1790: $env{'request.course.id'},
1791: %form);
1792: }
1793: if ($removeform) {
1794: $companswer=~s|<form(.*?)>||g;
1795: $companswer=~s|</form>||g;
1796: $companswer=~s|name="submit"|name="would_have_been_submit"|g;
1797: }
1798: $rendered=
1799: '<div class="LC_Box">'
1800: .'<h3 class="LC_hcell">'.&mt('View of the problem').'</h3>'
1801: .$rendered
1802: .'</div>';
1803: $companswer=
1804: '<div class="LC_Box">'
1805: .'<h3 class="LC_hcell">'.&mt('Correct answer').'</h3>'
1806: .$companswer
1807: .'</div>';
1808: my $result;
1809: if ($mode eq 'both') {
1810: $result=$rendered.$companswer;
1811: } elsif ($mode eq 'text') {
1812: $result=$rendered;
1813: } elsif ($mode eq 'answer') {
1814: $result=$companswer;
1815: }
1816: return $result;
1817: }
1818:
1819: sub files_exist {
1820: my ($r, $symb) = @_;
1821: my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1822:
1823: foreach my $student (@students) {
1824: my ($uname,$udom,$fullname) = split(/:/,$student);
1825: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
1826: $udom,$uname);
1827: my ($string,$timestamp)= &get_last_submission(\%record);
1828: foreach my $submission (@$string) {
1829: my ($partid,$respid) =
1830: ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1831: my $files=&get_submitted_files($udom,$uname,$partid,$respid,
1832: \%record);
1833: return 1 if (@$files);
1834: }
1835: }
1836: return 0;
1837: }
1838:
1839: sub download_all_link {
1840: my ($r,$symb) = @_;
1841: unless (&files_exist($r, $symb)) {
1842: $r->print(&mt('There are currently no submitted documents.'));
1843: return;
1844: }
1845:
1846: my $all_students =
1847: join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
1848:
1849: my $parts =
1850: join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
1851:
1852: my $identifier = &Apache::loncommon::get_cgi_id();
1853: &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
1854: 'cgi.'.$identifier.'.symb' => $symb,
1855: 'cgi.'.$identifier.'.parts' => $parts,});
1856: $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
1857: &mt('Download All Submitted Documents').'</a>');
1858: return;
1859: }
1860:
1861: sub submit_download_link {
1862: my ($request,$symb) = @_;
1863: if (!$symb) { return ''; }
1864: #FIXME: Figure out which type of problem this is and provide appropriate download
1865: &download_all_link($request,$symb);
1866: }
1867:
1868: sub build_section_inputs {
1869: my $section_inputs;
1870: if ($env{'form.section'} eq '') {
1871: $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
1872: } else {
1873: my @sections = &Apache::loncommon::get_env_multiple('form.section');
1874: foreach my $section (@sections) {
1875: $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
1876: }
1877: }
1878: return $section_inputs;
1879: }
1880:
1881: # --------------------------- show submissions of a student, option to grade
1882: sub submission {
1883: my ($request,$counter,$total,$symb) = @_;
1884: my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
1885: $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
1886: my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
1887: $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1888:
1889: my $probtitle=&Apache::lonnet::gettitle($symb);
1890: if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1891:
1892: if (!&canview($usec)) {
1893: $request->print('<span class="LC_warning">Unable to view requested student.('.
1894: $uname.':'.$udom.' in section '.$usec.' in course id '.
1895: $env{'request.course.id'}.')</span>');
1896: return;
1897: }
1898:
1899: if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
1900: if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
1901: if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
1902: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1903: my $checkIcon = '<img alt="'.&mt('Check Mark').
1904: '" src="'.$request->dir_config('lonIconsURL').
1905: '/check.gif" height="16" border="0" />';
1906:
1907: my %old_essays;
1908: # header info
1909: if ($counter == 0) {
1910: &sub_page_js($request);
1911: &sub_page_kw_js($request);
1912: $request->print('<h3> <span class="LC_info">'.&mt('Submission Record').'</span></h3>');
1913:
1914: # option to display problem, only once else it cause problems
1915: # with the form later since the problem has a form.
1916: if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1917: my $mode;
1918: if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1919: $mode='both';
1920: } elsif ($env{'form.vProb'} eq 'yes') {
1921: $mode='text';
1922: } elsif ($env{'form.vAns'} eq 'yes') {
1923: $mode='answer';
1924: }
1925: &Apache::lonxml::clear_problem_counter();
1926: $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1927: }
1928:
1929: # kwclr is the only variable that is guaranteed to be non blank
1930: # if this subroutine has been called once.
1931: my %keyhash = ();
1932: # if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1933: if (1) {
1934: %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1935: $env{'course.'.$env{'request.course.id'}.'.domain'},
1936: $env{'course.'.$env{'request.course.id'}.'.num'});
1937:
1938: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1939: $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
1940: $env{'form.kwclr'} = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
1941: $env{'form.kwsize'} = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
1942: $env{'form.kwstyle'} = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
1943: $env{'form.msgsub'} = $keyhash{$symb.'_subject'} ne '' ?
1944: $keyhash{$symb.'_subject'} : $probtitle;
1945: $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1946: }
1947: my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1948: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1949: $request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1950: '<input type="hidden" name="command" value="handgrade" />'."\n".
1951: '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
1952: '<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1953: '<input type="hidden" name="refresh" value="off" />'."\n".
1954: '<input type="hidden" name="studentNo" value="" />'."\n".
1955: '<input type="hidden" name="gradeOpt" value="" />'."\n".
1956: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1957: '<input type="hidden" name="vProb" value="'.$env{'form.vProb'}.'" />'."\n".
1958: '<input type="hidden" name="vAns" value="'.$env{'form.vAns'}.'" />'."\n".
1959: '<input type="hidden" name="lastSub" value="'.$env{'form.lastSub'}.'" />'."\n".
1960: &build_section_inputs().
1961: '<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
1962: '<input type="hidden" name="NCT"'.
1963: ' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
1964: # if ($env{'form.handgrade'} eq 'yes') {
1965: if (1) {
1966: $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
1967: '<input type="hidden" name="kwclr" value="'.$env{'form.kwclr'}.'" />'."\n".
1968: '<input type="hidden" name="kwsize" value="'.$env{'form.kwsize'}.'" />'."\n".
1969: '<input type="hidden" name="kwstyle" value="'.$env{'form.kwstyle'}.'" />'."\n".
1970: '<input type="hidden" name="msgsub" value="'.$env{'form.msgsub'}.'" />'."\n".
1971: '<input type="hidden" name="shownSub" value="0" />'."\n".
1972: '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1973: foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
1974: $request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
1975: }
1976: }
1977:
1978: my ($cts,$prnmsg) = (1,'');
1979: while ($cts <= $env{'form.savemsgN'}) {
1980: $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1981: (!exists($keyhash{$symb.'_savemsg'.$cts}) ?
1982: &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1983: &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1984: '" />'."\n".
1985: '<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1986: $cts++;
1987: }
1988: $request->print($prnmsg);
1989:
1990: # if ($env{'form.handgrade'} eq 'yes') {
1991: if (1) {
1992: #
1993: # Print out the keyword options line
1994: #
1995: $request->print(<<KEYWORDS);
1996: <b>Keyword Options:</b>
1997: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>
1998: <a href="#" onmousedown="javascript:getSel(); return false"
1999: CLASS="page">Paste Selection to List</a>
2000: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
2001: KEYWORDS
2002: #
2003: # Load the other essays for similarity check
2004: #
2005: my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
2006: my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
2007: $apath=&escape($apath);
2008: $apath=~s/\W/\_/gs;
2009: %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
2010: }
2011: }
2012:
2013: # This is where output for one specific student would start
2014: my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
2015: $request->print(
2016: "\n\n"
2017: .'<div class="LC_grade_show_user'.$add_class.'">'
2018: .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
2019: ."\n"
2020: );
2021:
2022: # Show additional functions if allowed
2023: if ($perm{'vgr'}) {
2024: $request->print(
2025: &Apache::loncommon::track_student_link(
2026: &mt('View recent activity'),
2027: $uname,$udom,'check')
2028: .' '
2029: );
2030: }
2031: if ($perm{'opa'}) {
2032: $request->print(
2033: &Apache::loncommon::pprmlink(
2034: &mt('Set/Change parameters'),
2035: $uname,$udom,$symb,'check'));
2036: }
2037:
2038: # Show Problem
2039: if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
2040: my $mode;
2041: if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
2042: $mode='both';
2043: } elsif ($env{'form.vProb'} eq 'all' ) {
2044: $mode='text';
2045: } elsif ($env{'form.vAns'} eq 'all') {
2046: $mode='answer';
2047: }
2048: &Apache::lonxml::clear_problem_counter();
2049: $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
2050: }
2051:
2052: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
2053: my $res_error;
2054: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
2055: if ($res_error) {
2056: $request->print(&navmap_errormsg());
2057: return;
2058: }
2059:
2060: # Display student info
2061: $request->print(($counter == 0 ? '' : '<br />'));
2062:
2063: my $result='<div class="LC_Box">'
2064: .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
2065: $result.='<input type="hidden" name="name'.$counter.
2066: '" value="'.$env{'form.fullname'}.'" />'."\n";
2067: # if ($env{'form.handgrade'} eq 'no') {
2068: if (1) {
2069: $result.='<p class="LC_info">'
2070: .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
2071: ."</p>\n";
2072: }
2073:
2074: # If any part of the problem is an essay-response (handgraded), then check for collaborators
2075: my $fullname;
2076: my $col_fullnames = [];
2077: # if ($env{'form.handgrade'} eq 'yes') {
2078: if (1) {
2079: (my $sub_result,$fullname,$col_fullnames)=
2080: &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
2081: $counter);
2082: $result.=$sub_result;
2083: }
2084: $request->print($result."\n");
2085:
2086: # print student answer/submission
2087: # Options are (1) Handgraded submission only
2088: # (2) Last submission, includes submission that is not handgraded
2089: # (for multi-response type part)
2090: # (3) Last submission plus the parts info
2091: # (4) The whole record for this student
2092: if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
2093: my ($string,$timestamp)= &get_last_submission(\%record);
2094:
2095: my $lastsubonly;
2096:
2097: if ($$timestamp eq '') {
2098: $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>';
2099: } else {
2100: $lastsubonly =
2101: '<div class="LC_grade_submissions_body">'
2102: .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
2103:
2104: my %seenparts;
2105: my @part_response_id = &flatten_responseType($responseType);
2106: foreach my $part (@part_response_id) {
2107: next if ($env{'form.lastSub'} eq 'hdgrade'
2108: && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
2109:
2110: my ($partid,$respid) = @{ $part };
2111: my $display_part=&get_display_part($partid,$symb);
2112: if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
2113: if (exists($seenparts{$partid})) { next; }
2114: $seenparts{$partid}=1;
2115: my $submitby='<b>Part:</b> '.$display_part.
2116: ' <b>Collaborative submission by:</b> '.
2117: '<a href="javascript:viewSubmitter(\''.
2118: $env{"form.$uname:$udom:$partid:submitted_by"}.
2119: '\');" target="_self">'.
2120: $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
2121: $request->print($submitby);
2122: next;
2123: }
2124: my $responsetype = $responseType->{$partid}->{$respid};
2125: if (!exists($record{"resource.$partid.$respid.submission"})) {
2126: $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
2127: '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
2128: ' <span class="LC_internal_info">'.
2129: '('.&mt('Response ID: [_1]',$respid).')'.
2130: '</span> '.
2131: '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
2132: next;
2133: }
2134: foreach my $submission (@$string) {
2135: my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
2136: if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
2137: my ($ressub,$hide,$subval) = split(/:/,$submission,3);
2138: # Similarity check
2139: my $similar='';
2140: if($env{'form.checkPlag'}){
2141: my ($oname,$odom,$ocrsid,$oessay,$osim)=
2142: &most_similar($uname,$udom,$subval,\%old_essays);
2143: if ($osim) {
2144: $osim=int($osim*100.0);
2145: my %old_course_desc =
2146: &Apache::lonnet::coursedescription($ocrsid,
2147: {'one_time' => 1});
2148:
2149: if ($hide) {
2150: $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
2151: &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
2152: } else {
2153: $similar="<hr /><h3><span class=\"LC_warning\">".
2154: &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
2155: $osim,
2156: &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
2157: $old_course_desc{'description'},
2158: $old_course_desc{'num'},
2159: $old_course_desc{'domain'}).
2160: '</span></h3><blockquote><i>'.
2161: &keywords_highlight($oessay).
2162: '</i></blockquote><hr />';
2163: }
2164: }
2165: }
2166: my $order=&get_order($partid,$respid,$symb,$uname,$udom);
2167: if ($env{'form.lastSub'} eq 'lastonly' ||
2168: ($env{'form.lastSub'} eq 'hdgrade' &&
2169: $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
2170: my $display_part=&get_display_part($partid,$symb);
2171: $lastsubonly.='<div class="LC_grade_submission_part">'.
2172: '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
2173: ' <span class="LC_internal_info">'.
2174: '('.&mt('Response ID: [_1]',$respid).')'.
2175: '</span> ';
2176: my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
2177: if (@$files) {
2178: if ($hide) {
2179: $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
2180: } else {
2181: $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
2182: foreach my $file (@$files) {
2183: &Apache::lonnet::allowuploaded('/adm/grades',$file);
2184: $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
2185: }
2186: }
2187: $lastsubonly.='<br />';
2188: }
2189: if ($hide) {
2190: $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>';
2191: } else {
2192: $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
2193: &cleanRecord($subval,$responsetype,$symb,$partid,
2194: $respid,\%record,$order,undef,$uname,$udom);
2195: }
2196: if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
2197: $lastsubonly.='</div>';
2198: }
2199: }
2200: }
2201: $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
2202: }
2203: $request->print($lastsubonly);
2204: } elsif ($env{'form.lastSub'} eq 'datesub') {
2205: my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
2206: $request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
2207: } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
2208: $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
2209: $env{'request.course.id'},
2210: $last,'.submission',
2211: 'Apache::grades::keywords_highlight'));
2212: }
2213: $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
2214: .$udom.'" />'."\n");
2215: # return if view submission with no grading option
2216: # FIXME: the logic seems off here. Why show the grade button if you cannot grade?
2217: if (!&canmodify($usec)) {
2218: my $toGrade.='<input type="button" value="Grade Student" '.
2219: 'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
2220: .$counter.'\');" target="_self" /> '."\n" if (&canmodify($usec));
2221: $toGrade.='</div>'."\n";
2222: $request->print($toGrade);
2223: return;
2224: } else {
2225: $request->print('</div>'."\n");
2226: }
2227:
2228: # essay grading message center
2229: # if ($env{'form.handgrade'} eq 'yes') {
2230: if (1) {
2231: my $result='<div class="LC_grade_message_center">';
2232:
2233: $result.='<div class="LC_grade_message_center_header">'.
2234: &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
2235: my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
2236: my $msgfor = $givenn.' '.$lastname;
2237: if (scalar(@$col_fullnames) > 0) {
2238: my $lastone = pop(@$col_fullnames);
2239: $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
2240: }
2241: $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
2242: $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
2243: '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
2244: $result.=' <a href="javascript:msgCenter(document.SCORE,'.$counter.
2245: ',\''.$msgfor.'\');" target="_self">'.
2246: &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
2247: &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
2248: '<img src="'.$request->dir_config('lonIconsURL').
2249: '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
2250: '<br /> ('.
2251: &mt('Message will be sent when you click on Save & Next below.').")\n";
2252: $result.='</div></div>';
2253: $request->print($result);
2254: }
2255:
2256: my %seen = ();
2257: my @partlist;
2258: my @gradePartRespid;
2259: my @part_response_id = &flatten_responseType($responseType);
2260: $request->print(
2261: '<div class="LC_Box">'
2262: .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
2263: );
2264: $request->print(&gradeBox_start());
2265: foreach my $part_response_id (@part_response_id) {
2266: my ($partid,$respid) = @{ $part_response_id };
2267: my $part_resp = join('_',@{ $part_response_id });
2268: next if ($seen{$partid} > 0);
2269: $seen{$partid}++;
2270: next if ($$handgrade{$part_resp} ne 'yes'
2271: && $env{'form.lastSub'} eq 'hdgrade');
2272: push(@partlist,$partid);
2273: push(@gradePartRespid,$partid.'.'.$respid);
2274: $request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
2275: }
2276: $request->print(&gradeBox_end()); # </div>
2277: $request->print('</div>');
2278:
2279: $request->print('<div class="LC_grade_info_links">');
2280: $request->print('</div>');
2281:
2282: $result='<input type="hidden" name="partlist'.$counter.
2283: '" value="'.(join ":",@partlist).'" />'."\n";
2284: $result.='<input type="hidden" name="gradePartRespid'.
2285: '" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
2286: my $ctr = 0;
2287: while ($ctr < scalar(@partlist)) {
2288: $result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
2289: $partlist[$ctr].'" />'."\n";
2290: $ctr++;
2291: }
2292: $request->print($result.''."\n");
2293:
2294: # Done with printing info for one student
2295:
2296: $request->print('</div>');#LC_grade_show_user
2297:
2298:
2299: # print end of form
2300: if ($counter == $total) {
2301: my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
2302: $endform.='<input type="button" value="'.&mt('Save & Next').'" '.
2303: 'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
2304: $total.','.scalar(@partlist).');" target="_self" /> '."\n";
2305: my $ntstu ='<select name="NTSTU">'.
2306: '<option>1</option><option>2</option>'.
2307: '<option>3</option><option>5</option>'.
2308: '<option>7</option><option>10</option></select>'."\n";
2309: my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
2310: $ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
2311: $endform.=&mt('[_1]student(s)',$ntstu);
2312: $endform.=' <input type="button" value="'.&mt('Previous').'" '.
2313: 'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> '."\n".
2314: '<input type="button" value="'.&mt('Next').'" '.
2315: 'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> ';
2316: $endform.='<span class="LC_warning">'.
2317: &mt('(Next and Previous (student) do not save the scores.)').
2318: '</span>'."\n" ;
2319: $endform.="<input type='hidden' value='".&get_increment().
2320: "' name='increment' />";
2321: $endform.='</td></tr></table></form>';
2322: $request->print($endform);
2323: }
2324: return '';
2325: }
2326:
2327: sub check_collaborators {
2328: my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
2329: my ($result,@col_fullnames);
2330: my ($classlist,undef,$fullname) = &getclasslist('all','0');
2331: foreach my $part (keys(%$handgrade)) {
2332: my $ncol = &Apache::lonnet::EXT('resource.'.$part.
2333: '.maxcollaborators',
2334: $symb,$udom,$uname);
2335: next if ($ncol <= 0);
2336: $part =~ s/\_/\./g;
2337: next if ($record->{'resource.'.$part.'.collaborators'} eq '');
2338: my (@good_collaborators, @bad_collaborators);
2339: foreach my $possible_collaborator
2340: (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) {
2341: $possible_collaborator =~ s/[\$\^\(\)]//g;
2342: next if ($possible_collaborator eq '');
2343: my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
2344: $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
2345: next if ($co_name eq $uname && $co_dom eq $udom);
2346: # Doing this grep allows 'fuzzy' specification
2347: my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i,
2348: keys(%$classlist));
2349: if (! scalar(@matches)) {
2350: push(@bad_collaborators, $possible_collaborator);
2351: } else {
2352: push(@good_collaborators, @matches);
2353: }
2354: }
2355: if (scalar(@good_collaborators) != 0) {
2356: $result.='<br />'.&mt('Collaborators: ');
2357: foreach my $name (@good_collaborators) {
2358: my ($lastname,$givenn) = split(/,/,$$fullname{$name});
2359: push(@col_fullnames, $givenn.' '.$lastname);
2360: $result.=$fullname->{$name}.' ';
2361: }
2362: $result.='<br />'."\n";
2363: my ($part)=split(/\./,$part);
2364: $result.='<input type="hidden" name="collaborator'.$counter.
2365: '" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
2366: "\n";
2367: }
2368: if (scalar(@bad_collaborators) > 0) {
2369: $result.='<div class="LC_warning">';
2370: $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
2371: $result .= '</div>';
2372: }
2373: if (scalar(@bad_collaborators > $ncol)) {
2374: $result .= '<div class="LC_warning">';
2375: $result .= &mt('This student has submitted too many '.
2376: 'collaborators. Maximum is [_1].',$ncol);
2377: $result .= '</div>';
2378: }
2379: }
2380: return ($result,$fullname,\@col_fullnames);
2381: }
2382:
2383: #--- Retrieve the last submission for all the parts
2384: sub get_last_submission {
2385: my ($returnhash)=@_;
2386: my (@string,$timestamp,%lasthidden);
2387: if ($$returnhash{'version'}) {
2388: my %lasthash=();
2389: my ($version);
2390: for ($version=1;$version<=$$returnhash{'version'};$version++) {
2391: foreach my $key (sort(split(/\:/,
2392: $$returnhash{$version.':keys'}))) {
2393: $lasthash{$key}=$$returnhash{$version.':'.$key};
2394: $timestamp =
2395: &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
2396: }
2397: }
2398: my %typeparts;
2399: my $showsurv =
2400: &Apache::lonnet::allowed('vas',$env{'request.course.id'});
2401: foreach my $key (sort(keys(%lasthash))) {
2402: if ($key =~ /\.type$/) {
2403: if (($lasthash{$key} eq 'anonsurvey') ||
2404: ($lasthash{$key} eq 'anonsurveycred')) {
2405: my ($ign,@parts) = split(/\./,$key);
2406: pop(@parts);
2407: unless ($showsurv) {
2408: my $id = join(',',@parts);
2409: $typeparts{$ign.'.'.$id} = $lasthash{$key};
2410: }
2411: delete($lasthash{$key});
2412: }
2413: }
2414: }
2415: my @hidden = keys(%typeparts);
2416: foreach my $key (keys(%lasthash)) {
2417: next if ($key !~ /\.submission$/);
2418: my $hide;
2419: if (@hidden) {
2420: foreach my $id (@hidden) {
2421: if ($key =~ /^\Q$id\E/) {
2422: $hide = 1;
2423: last;
2424: }
2425: }
2426: }
2427: my ($partid,$foo) = split(/submission$/,$key);
2428: my $draft = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
2429: '<span class="LC_warning">Draft Copy</span> ' : '';
2430: push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
2431: }
2432: }
2433: if (!@string) {
2434: $string[0] =
2435: '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
2436: }
2437: return (\@string,\$timestamp);
2438: }
2439:
2440: #--- High light keywords, with style choosen by user.
2441: sub keywords_highlight {
2442: my $string = shift;
2443: my $size = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
2444: my $styleon = $env{'form.kwstyle'} eq '' ? '' : $env{'form.kwstyle'};
2445: (my $styleoff = $styleon) =~ s/\</\<\//;
2446: my @keylist = split(/[,\s+]/,$env{'form.keywords'});
2447: foreach my $keyword (@keylist) {
2448: $string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
2449: }
2450: return $string;
2451: }
2452:
2453: #--- Called from submission routine
2454: sub processHandGrade {
2455: my ($request,$symb) = @_;
2456: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
2457: my $button = $env{'form.gradeOpt'};
2458: my $ngrade = $env{'form.NCT'};
2459: my $ntstu = $env{'form.NTSTU'};
2460: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2461: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2462:
2463: if ($button eq 'Save & Next') {
2464: my $ctr = 0;
2465: while ($ctr < $ngrade) {
2466: my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
2467: my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
2468: if ($errorflag eq 'no_score') {
2469: $ctr++;
2470: next;
2471: }
2472: if ($errorflag eq 'not_allowed') {
2473: $request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
2474: $ctr++;
2475: next;
2476: }
2477: my $includemsg = $env{'form.includemsg'.$ctr};
2478: my ($subject,$message,$msgstatus) = ('','','');
2479: my $restitle = &Apache::lonnet::gettitle($symb);
2480: my ($feedurl,$showsymb) =
2481: &get_feedurl_and_symb($symb,$uname,$udom);
2482: my $messagetail;
2483: if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
2484: $subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
2485: unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
2486: $subject.=' ['.$restitle.']';
2487: my (@msgnum) = split(/,/,$includemsg);
2488: foreach (@msgnum) {
2489: $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
2490: }
2491: $message =&Apache::lonfeedback::clear_out_html($message);
2492: if ($env{'form.withgrades'.$ctr}) {
2493: $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
2494: $messagetail = " for <a href=\"".
2495: $feedurl."?symb=$showsymb\">$restitle</a>";
2496: }
2497: $msgstatus =
2498: &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
2499: $message.$messagetail,
2500: undef,$feedurl,undef,
2501: undef,undef,$showsymb,
2502: $restitle);
2503: $request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
2504: $msgstatus);
2505: }
2506: if ($env{'form.collaborator'.$ctr}) {
2507: my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
2508: foreach my $collabstr (@collabstrs) {
2509: my ($part,@collaborators) = split(/:/,$collabstr);
2510: foreach my $collaborator (@collaborators) {
2511: my ($errorflag,$pts,$wgt) =
2512: &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
2513: $env{'form.unamedom'.$ctr},$part);
2514: if ($errorflag eq 'not_allowed') {
2515: $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
2516: next;
2517: } elsif ($message ne '') {
2518: my ($baseurl,$showsymb) =
2519: &get_feedurl_and_symb($symb,$collaborator,
2520: $udom);
2521: if ($env{'form.withgrades'.$ctr}) {
2522: $messagetail = " for <a href=\"".
2523: $baseurl."?symb=$showsymb\">$restitle</a>";
2524: }
2525: $msgstatus =
2526: &Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
2527: }
2528: }
2529: }
2530: }
2531: $ctr++;
2532: }
2533: }
2534:
2535: # if ($env{'form.handgrade'} eq 'yes') {
2536: if (1) {
2537: # Keywords sorted in alphabatical order
2538: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
2539: my %keyhash = ();
2540: $env{'form.keywords'} =~ s/,\s{0,}|\s+/ /g;
2541: $env{'form.keywords'} =~ s/^\s+|\s+$//;
2542: my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
2543: $env{'form.keywords'} = join(' ',@keywords);
2544: $keyhash{$symb.'_keywords'} = $env{'form.keywords'};
2545: $keyhash{$symb.'_subject'} = $env{'form.msgsub'};
2546: $keyhash{$loginuser.'_kwclr'} = $env{'form.kwclr'};
2547: $keyhash{$loginuser.'_kwsize'} = $env{'form.kwsize'};
2548: $keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
2549:
2550: # message center - Order of message gets changed. Blank line is eliminated.
2551: # New messages are saved in env for the next student.
2552: # All messages are saved in nohist_handgrade.db
2553: my ($ctr,$idx) = (1,1);
2554: while ($ctr <= $env{'form.savemsgN'}) {
2555: if ($env{'form.savemsg'.$ctr} ne '') {
2556: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
2557: $idx++;
2558: }
2559: $ctr++;
2560: }
2561: $ctr = 0;
2562: while ($ctr < $ngrade) {
2563: if ($env{'form.newmsg'.$ctr} ne '') {
2564: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2565: $env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2566: $idx++;
2567: }
2568: $ctr++;
2569: }
2570: $env{'form.savemsgN'} = --$idx;
2571: $keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
2572: my $putresult = &Apache::lonnet::put
2573: ('nohist_handgrade',\%keyhash,$cdom,$cnum);
2574: }
2575: # Called by Save & Refresh from Highlight Attribute Window
2576: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
2577: if ($env{'form.refresh'} eq 'on') {
2578: my ($ctr,$total) = (0,0);
2579: while ($ctr < $ngrade) {
2580: $total++ if $env{'form.unamedom'.$ctr} ne '';
2581: $ctr++;
2582: }
2583: $env{'form.NTSTU'}=$ngrade;
2584: $ctr = 0;
2585: while ($ctr < $total) {
2586: my $processUser = $env{'form.unamedom'.$ctr};
2587: ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
2588: $env{'form.fullname'} = $$fullname{$processUser};
2589: &submission($request,$ctr,$total-1,$symb);
2590: $ctr++;
2591: }
2592: return '';
2593: }
2594:
2595: # Go directly to grade student - from submission or link from chart page
2596: # FIXME: looks like reading off the button label!
2597: if ($button eq 'Grade Student') {
2598: my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
2599: ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
2600: $env{'form.fullname'} = $$fullname{$processUser};
2601: &submission($request,0,0,$symb);
2602: return '';
2603: }
2604:
2605: # Get the next/previous one or group of students
2606: my $firststu = $env{'form.unamedom0'};
2607: my $laststu = $env{'form.unamedom'.($ngrade-1)};
2608: my $ctr = 2;
2609: while ($laststu eq '') {
2610: $laststu = $env{'form.unamedom'.($ngrade-$ctr)};
2611: $ctr++;
2612: $laststu = $firststu if ($ctr > $ngrade);
2613: }
2614:
2615: my (@parsedlist,@nextlist);
2616: my ($nextflg) = 0;
2617: foreach my $item (sort
2618: {
2619: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
2620: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
2621: }
2622: return $a cmp $b;
2623: } (keys(%$fullname))) {
2624: # FIXME: this is fishy, looks like the button label
2625: if ($nextflg == 1 && $button =~ /Next$/) {
2626: push(@parsedlist,$item);
2627: }
2628: $nextflg = 1 if ($item eq $laststu);
2629: if ($button eq 'Previous') {
2630: last if ($item eq $firststu);
2631: push(@parsedlist,$item);
2632: }
2633: }
2634: $ctr = 0;
2635: # FIXME: this is fishy, looks like the button label
2636: @parsedlist = reverse @parsedlist if ($button eq 'Previous');
2637: my $res_error;
2638: my ($partlist) = &response_type($symb,\$res_error);
2639: if ($res_error) {
2640: $request->print(&navmap_errormsg());
2641: return;
2642: }
2643: foreach my $student (@parsedlist) {
2644: my $submitonly=$env{'form.submitonly'};
2645: my ($uname,$udom) = split(/:/,$student);
2646:
2647: if ($submitonly eq 'queued') {
2648: my %queue_status =
2649: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
2650: $udom,$uname);
2651: next if (!defined($queue_status{'gradingqueue'}));
2652: }
2653:
2654: if ($submitonly =~ /^(yes|graded|incorrect)$/) {
2655: # my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
2656: my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
2657: my $submitted = 0;
2658: my $ungraded = 0;
2659: my $incorrect = 0;
2660: foreach my $item (keys(%status)) {
2661: $submitted = 1 if ($status{$item} ne 'nothing');
2662: $ungraded = 1 if ($status{$item} =~ /^ungraded/);
2663: $incorrect = 1 if ($status{$item} =~ /^incorrect/);
2664: my ($foo,$partid,$foo1) = split(/\./,$item);
2665: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
2666: $submitted = 0;
2667: }
2668: }
2669: next if (!$submitted && ($submitonly eq 'yes' ||
2670: $submitonly eq 'incorrect' ||
2671: $submitonly eq 'graded'));
2672: next if (!$ungraded && ($submitonly eq 'graded'));
2673: next if (!$incorrect && $submitonly eq 'incorrect');
2674: }
2675: push(@nextlist,$student) if ($ctr < $ntstu);
2676: last if ($ctr == $ntstu);
2677: $ctr++;
2678: }
2679:
2680: $ctr = 0;
2681: my $total = scalar(@nextlist)-1;
2682:
2683: foreach (sort(@nextlist)) {
2684: my ($uname,$udom,$submitter) = split(/:/);
2685: $env{'form.student'} = $uname;
2686: $env{'form.userdom'} = $udom;
2687: $env{'form.fullname'} = $$fullname{$_};
2688: &submission($request,$ctr,$total,$symb);
2689: $ctr++;
2690: }
2691: if ($total < 0) {
2692: my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
2693: $the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
2694: $the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
2695: $request->print($the_end);
2696: }
2697: return '';
2698: }
2699:
2700: #---- Save the score and award for each student, if changed
2701: sub saveHandGrade {
2702: my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
2703: my @version_parts;
2704: my $usec = &Apache::lonnet::getsection($domain,$stuname,
2705: $env{'request.course.id'});
2706: if (!&canmodify($usec)) { return('not_allowed'); }
2707: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
2708: my @parts_graded;
2709: my %newrecord = ();
2710: my ($pts,$wgt) = ('','');
2711: my %aggregate = ();
2712: my $aggregateflag = 0;
2713: my @parts = split(/:/,$env{'form.partlist'.$newflg});
2714: foreach my $new_part (@parts) {
2715: #collaborator ($submi may vary for different parts
2716: if ($submitter && $new_part ne $part) { next; }
2717: my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
2718: if ($dropMenu eq 'excused') {
2719: if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
2720: $newrecord{'resource.'.$new_part.'.solved'} = 'excused';
2721: if (exists($record{'resource.'.$new_part.'.awarded'})) {
2722: $newrecord{'resource.'.$new_part.'.awarded'} = '';
2723: }
2724: $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
2725: }
2726: } elsif ($dropMenu eq 'reset status'
2727: && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
2728: foreach my $key (keys(%record)) {
2729: if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
2730: }
2731: $newrecord{'resource.'.$new_part.'.regrader'}=
2732: "$env{'user.name'}:$env{'user.domain'}";
2733: my $totaltries = $record{'resource.'.$part.'.tries'};
2734:
2735: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
2736: [$new_part]);
2737: my $aggtries =$totaltries;
2738: if ($last_resets{$new_part}) {
2739: $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
2740: $new_part);
2741: }
2742:
2743: my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
2744: if ($aggtries > 0) {
2745: &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
2746: $aggregateflag = 1;
2747: }
2748: } elsif ($dropMenu eq '') {
2749: $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ?
2750: $env{'form.GD_BOX'.$newflg.'_'.$new_part} :
2751: $env{'form.RADVAL'.$newflg.'_'.$new_part});
2752: if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
2753: next;
2754: }
2755: $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 :
2756: $env{'form.WGT'.$newflg.'_'.$new_part};
2757: my $partial= $pts/$wgt;
2758: if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
2759: #do not update score for part if not changed.
2760: &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
2761: next;
2762: } else {
2763: push(@parts_graded,$new_part);
2764: }
2765: if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
2766: $newrecord{'resource.'.$new_part.'.awarded'} = $partial;
2767: }
2768: my $reckey = 'resource.'.$new_part.'.solved';
2769: if ($partial == 0) {
2770: if ($record{$reckey} ne 'incorrect_by_override') {
2771: $newrecord{$reckey} = 'incorrect_by_override';
2772: }
2773: } else {
2774: if ($record{$reckey} ne 'correct_by_override') {
2775: $newrecord{$reckey} = 'correct_by_override';
2776: }
2777: }
2778: if ($submitter &&
2779: ($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
2780: $newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
2781: }
2782: $newrecord{'resource.'.$new_part.'.regrader'}=
2783: "$env{'user.name'}:$env{'user.domain'}";
2784: }
2785: # unless problem has been graded, set flag to version the submitted files
2786: unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/ ||
2787: $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
2788: $dropMenu eq 'reset status')
2789: {
2790: push(@version_parts,$new_part);
2791: }
2792: }
2793: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2794: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2795:
2796: if (%newrecord) {
2797: if (@version_parts) {
2798: my @changed_keys = &version_portfiles(\%record, \@parts_graded,
2799: $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
2800: @newrecord{@changed_keys} = @record{@changed_keys};
2801: foreach my $new_part (@version_parts) {
2802: &handback_files($request,$symb,$stuname,$domain,$newflg,
2803: $new_part,\%newrecord);
2804: }
2805: }
2806: &Apache::lonnet::cstore(\%newrecord,$symb,
2807: $env{'request.course.id'},$domain,$stuname);
2808: &check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
2809: $cdom,$cnum,$domain,$stuname);
2810: }
2811: if ($aggregateflag) {
2812: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
2813: $cdom,$cnum);
2814: }
2815: return ('',$pts,$wgt);
2816: }
2817:
2818: sub check_and_remove_from_queue {
2819: my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
2820: my @ungraded_parts;
2821: foreach my $part (@{$parts}) {
2822: if ( $record->{ 'resource.'.$part.'.awarded'} eq ''
2823: && $record->{ 'resource.'.$part.'.solved' } ne 'excused'
2824: && $newrecord->{'resource.'.$part.'.awarded'} eq ''
2825: && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
2826: ) {
2827: push(@ungraded_parts, $part);
2828: }
2829: }
2830: if ( !@ungraded_parts ) {
2831: &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
2832: $cnum,$domain,$stuname);
2833: }
2834: }
2835:
2836: sub handback_files {
2837: my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
2838: my $portfolio_root = '/userfiles/portfolio';
2839: my $res_error;
2840: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
2841: if ($res_error) {
2842: $request->print('<br />'.&navmap_errormsg().'<br />');
2843: return;
2844: }
2845: my @part_response_id = &flatten_responseType($responseType);
2846: foreach my $part_response_id (@part_response_id) {
2847: my ($part_id,$resp_id) = @{ $part_response_id };
2848: my $part_resp = join('_',@{ $part_response_id });
2849: if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
2850: # if multiple files are uploaded names will be 'returndoc2','returndoc3'
2851: my $file_counter = 1;
2852: my $file_msg;
2853: while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
2854: my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
2855: my ($directory,$answer_file) =
2856: ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
2857: my ($answer_name,$answer_ver,$answer_ext) =
2858: &file_name_version_ext($answer_file);
2859: my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
2860: my $getpropath = 1;
2861: my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
2862: my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
2863: # fix file name
2864: my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
2865: my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
2866: $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
2867: $save_file_name);
2868: if ($result !~ m|^/uploaded/|) {
2869: $request->print('<br /><span class="LC_error">'.
2870: &mt('An error occurred ([_1]) while trying to upload [_2].',
2871: $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
2872: '</span>');
2873: } else {
2874: # mark the file as read only
2875: my @files = ($save_file_name);
2876: my @what = ($symb,$env{'request.course.id'},'handback');
2877: &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
2878: if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
2879: $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
2880: }
2881: $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
2882: $file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
2883:
2884: }
2885: $request->print("<br />".$fname." will be the uploaded file name");
2886: $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
2887: $file_counter++;
2888: }
2889: my $subject = "File Handed Back by Instructor ";
2890: my $message = "A file has been returned that was originally submitted in reponse to: <br />";
2891: $message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
2892: $message .= ' The returned file(s) are named: '. $file_msg;
2893: $message .= " and can be found in your portfolio space.";
2894: my ($feedurl,$showsymb) =
2895: &get_feedurl_and_symb($symb,$domain,$stuname);
2896: my $restitle = &Apache::lonnet::gettitle($symb);
2897: my $msgstatus =
2898: &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
2899: ' (File Returned) ['.$restitle.']',$message,undef,
2900: $feedurl,undef,undef,undef,$showsymb,$restitle);
2901: }
2902: }
2903: return;
2904: }
2905:
2906: sub get_feedurl_and_symb {
2907: my ($symb,$uname,$udom) = @_;
2908: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
2909: $url = &Apache::lonnet::clutter($url);
2910: my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
2911: $symb,$udom,$uname);
2912: if ($encrypturl =~ /^yes$/i) {
2913: &Apache::lonenc::encrypted(\$url,1);
2914: &Apache::lonenc::encrypted(\$symb,1);
2915: }
2916: return ($url,$symb);
2917: }
2918:
2919: sub get_submitted_files {
2920: my ($udom,$uname,$partid,$respid,$record) = @_;
2921: my @files;
2922: if ($$record{"resource.$partid.$respid.portfiles"}) {
2923: my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
2924: foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
2925: push(@files,$file_url.$file);
2926: }
2927: }
2928: if ($$record{"resource.$partid.$respid.uploadedurl"}) {
2929: push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
2930: }
2931: return (\@files);
2932: }
2933:
2934: # ----------- Provides number of tries since last reset.
2935: sub get_num_tries {
2936: my ($record,$last_reset,$part) = @_;
2937: my $timestamp = '';
2938: my $num_tries = 0;
2939: if ($$record{'version'}) {
2940: for (my $version=$$record{'version'};$version>=1;$version--) {
2941: if (exists($$record{$version.':resource.'.$part.'.solved'})) {
2942: $timestamp = $$record{$version.':timestamp'};
2943: if ($timestamp > $last_reset) {
2944: $num_tries ++;
2945: } else {
2946: last;
2947: }
2948: }
2949: }
2950: }
2951: return $num_tries;
2952: }
2953:
2954: # ----------- Determine decrements required in aggregate totals
2955: sub decrement_aggs {
2956: my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
2957: my %decrement = (
2958: attempts => 0,
2959: users => 0,
2960: correct => 0
2961: );
2962: $decrement{'attempts'} = $aggtries;
2963: if ($solvedstatus =~ /^correct/) {
2964: $decrement{'correct'} = 1;
2965: }
2966: if ($aggtries == $totaltries) {
2967: $decrement{'users'} = 1;
2968: }
2969: foreach my $type (keys(%decrement)) {
2970: $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
2971: }
2972: return;
2973: }
2974:
2975: # ----------- Determine timestamps for last reset of aggregate totals for parts
2976: sub get_last_resets {
2977: my ($symb,$courseid,$partids) =@_;
2978: my %last_resets;
2979: my $cdom = $env{'course.'.$courseid.'.domain'};
2980: my $cname = $env{'course.'.$courseid.'.num'};
2981: my @keys;
2982: foreach my $part (@{$partids}) {
2983: push(@keys,"$symb\0$part\0resettime");
2984: }
2985: my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
2986: $cdom,$cname);
2987: foreach my $part (@{$partids}) {
2988: $last_resets{$part}=$results{"$symb\0$part\0resettime"};
2989: }
2990: return %last_resets;
2991: }
2992:
2993: # ----------- Handles creating versions for portfolio files as answers
2994: sub version_portfiles {
2995: my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
2996: my $version_parts = join('|',@$v_flag);
2997: my @returned_keys;
2998: my $parts = join('|', @$parts_graded);
2999: my $portfolio_root = '/userfiles/portfolio';
3000: foreach my $key (keys(%$record)) {
3001: my $new_portfiles;
3002: if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
3003: my @versioned_portfiles;
3004: my @portfiles = split(/\s*,\s*/,$$record{$key});
3005: foreach my $file (@portfiles) {
3006: &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
3007: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
3008: my ($answer_name,$answer_ver,$answer_ext) =
3009: &file_name_version_ext($answer_file);
3010: my $getpropath = 1;
3011: my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
3012: my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
3013: my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
3014: if ($new_answer ne 'problem getting file') {
3015: push(@versioned_portfiles, $directory.$new_answer);
3016: &Apache::lonnet::mark_as_readonly($domain,$stu_name,
3017: [$directory.$new_answer],
3018: [$symb,$env{'request.course.id'},'graded']);
3019: }
3020: }
3021: $$record{$key} = join(',',@versioned_portfiles);
3022: push(@returned_keys,$key);
3023: }
3024: }
3025: return (@returned_keys);
3026: }
3027:
3028: sub get_next_version {
3029: my ($answer_name, $answer_ext, $dir_list) = @_;
3030: my $version;
3031: foreach my $row (@$dir_list) {
3032: my ($file) = split(/\&/,$row,2);
3033: my ($file_name,$file_version,$file_ext) =
3034: &file_name_version_ext($file);
3035: if (($file_name eq $answer_name) &&
3036: ($file_ext eq $answer_ext)) {
3037: # gets here if filename and extension match, regardless of version
3038: if ($file_version ne '') {
3039: # a versioned file is found so save it for later
3040: if ($file_version > $version) {
3041: $version = $file_version;
3042: }
3043: }
3044: }
3045: }
3046: $version ++;
3047: return($version);
3048: }
3049:
3050: sub version_selected_portfile {
3051: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
3052: my ($answer_name,$answer_ver,$answer_ext) =
3053: &file_name_version_ext($file_name);
3054: my $new_answer;
3055: $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
3056: if($env{'form.copy'} eq '-1') {
3057: $new_answer = 'problem getting file';
3058: } else {
3059: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
3060: my $copy_result = &Apache::lonnet::finishuserfileupload(
3061: $stu_name,$domain,'copy',
3062: '/portfolio'.$directory.$new_answer);
3063: }
3064: return ($new_answer);
3065: }
3066:
3067: sub file_name_version_ext {
3068: my ($file)=@_;
3069: my @file_parts = split(/\./, $file);
3070: my ($name,$version,$ext);
3071: if (@file_parts > 1) {
3072: $ext=pop(@file_parts);
3073: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
3074: $version=pop(@file_parts);
3075: }
3076: $name=join('.',@file_parts);
3077: } else {
3078: $name=join('.',@file_parts);
3079: }
3080: return($name,$version,$ext);
3081: }
3082:
3083: #--------------------------------------------------------------------------------------
3084: #
3085: #-------------------------- Next few routines handles grading by section or whole class
3086: #
3087: #--- Javascript to handle grading by section or whole class
3088: sub viewgrades_js {
3089: my ($request) = shift;
3090:
3091: my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
3092: $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
3093: function writePoint(partid,weight,point) {
3094: var radioButton = document.classgrade["RADVAL_"+partid];
3095: var textbox = document.classgrade["TEXTVAL_"+partid];
3096: if (point == "textval") {
3097: point = document.classgrade["TEXTVAL_"+partid].value;
3098: if (isNaN(point) || parseFloat(point) < 0) {
3099: alert("$alertmsg"+parseFloat(point));
3100: var resetbox = false;
3101: for (var i=0; i<radioButton.length; i++) {
3102: if (radioButton[i].checked) {
3103: textbox.value = i;
3104: resetbox = true;
3105: }
3106: }
3107: if (!resetbox) {
3108: textbox.value = "";
3109: }
3110: return;
3111: }
3112: if (parseFloat(point) > parseFloat(weight)) {
3113: var resp = confirm("You entered a value ("+parseFloat(point)+
3114: ") greater than the weight for the part. Accept?");
3115: if (resp == false) {
3116: textbox.value = "";
3117: return;
3118: }
3119: }
3120: for (var i=0; i<radioButton.length; i++) {
3121: radioButton[i].checked=false;
3122: if (parseFloat(point) == i) {
3123: radioButton[i].checked=true;
3124: }
3125: }
3126:
3127: } else {
3128: textbox.value = parseFloat(point);
3129: }
3130: for (i=0;i<document.classgrade.total.value;i++) {
3131: var user = document.classgrade["ctr"+i].value;
3132: user = user.replace(new RegExp(':', 'g'),"_");
3133: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3134: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3135: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3136: if (saveval != "correct") {
3137: scorename.value = point;
3138: if (selname[0].selected != true) {
3139: selname[0].selected = true;
3140: }
3141: }
3142: }
3143: document.classgrade["SELVAL_"+partid][0].selected = true;
3144: }
3145:
3146: function writeRadText(partid,weight) {
3147: var selval = document.classgrade["SELVAL_"+partid];
3148: var radioButton = document.classgrade["RADVAL_"+partid];
3149: var override = document.classgrade["FORCE_"+partid].checked;
3150: var textbox = document.classgrade["TEXTVAL_"+partid];
3151: if (selval[1].selected || selval[2].selected) {
3152: for (var i=0; i<radioButton.length; i++) {
3153: radioButton[i].checked=false;
3154:
3155: }
3156: textbox.value = "";
3157:
3158: for (i=0;i<document.classgrade.total.value;i++) {
3159: var user = document.classgrade["ctr"+i].value;
3160: user = user.replace(new RegExp(':', 'g'),"_");
3161: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3162: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3163: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3164: if ((saveval != "correct") || override) {
3165: scorename.value = "";
3166: if (selval[1].selected) {
3167: selname[1].selected = true;
3168: } else {
3169: selname[2].selected = true;
3170: if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value))
3171: {document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
3172: }
3173: }
3174: }
3175: } else {
3176: for (i=0;i<document.classgrade.total.value;i++) {
3177: var user = document.classgrade["ctr"+i].value;
3178: user = user.replace(new RegExp(':', 'g'),"_");
3179: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3180: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3181: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3182: if ((saveval != "correct") || override) {
3183: scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
3184: selname[0].selected = true;
3185: }
3186: }
3187: }
3188: }
3189:
3190: function changeSelect(partid,user) {
3191: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
3192: var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
3193: var point = textbox.value;
3194: var weight = document.classgrade["weight_"+partid].value;
3195:
3196: if (isNaN(point) || parseFloat(point) < 0) {
3197: alert("$alertmsg"+parseFloat(point));
3198: textbox.value = "";
3199: return;
3200: }
3201: if (parseFloat(point) > parseFloat(weight)) {
3202: var resp = confirm("You entered a value ("+parseFloat(point)+
3203: ") greater than the weight of the part. Accept?");
3204: if (resp == false) {
3205: textbox.value = "";
3206: return;
3207: }
3208: }
3209: selval[0].selected = true;
3210: }
3211:
3212: function changeOneScore(partid,user) {
3213: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
3214: if (selval[1].selected || selval[2].selected) {
3215: document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
3216: if (selval[2].selected) {
3217: document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
3218: }
3219: }
3220: }
3221:
3222: function resetEntry(numpart) {
3223: for (ctpart=0;ctpart<numpart;ctpart++) {
3224: var partid = document.classgrade["partid_"+ctpart].value;
3225: var radioButton = document.classgrade["RADVAL_"+partid];
3226: var textbox = document.classgrade["TEXTVAL_"+partid];
3227: var selval = document.classgrade["SELVAL_"+partid];
3228: for (var i=0; i<radioButton.length; i++) {
3229: radioButton[i].checked=false;
3230:
3231: }
3232: textbox.value = "";
3233: selval[0].selected = true;
3234:
3235: for (i=0;i<document.classgrade.total.value;i++) {
3236: var user = document.classgrade["ctr"+i].value;
3237: user = user.replace(new RegExp(':', 'g'),"_");
3238: var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3239: resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
3240: var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
3241: resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
3242: var saveselval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3243: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3244: if (saveselval == "excused") {
3245: if (selname[1].selected == false) { selname[1].selected = true;}
3246: } else {
3247: if (selname[0].selected == false) {selname[0].selected = true};
3248: }
3249: }
3250: }
3251: }
3252:
3253: VIEWJAVASCRIPT
3254: }
3255:
3256: #--- show scores for a section or whole class w/ option to change/update a score
3257: sub viewgrades {
3258: my ($request,$symb) = @_;
3259: &viewgrades_js($request);
3260:
3261: #need to make sure we have the correct data for later EXT calls,
3262: #thus invalidate the cache
3263: &Apache::lonnet::devalidatecourseresdata(
3264: $env{'course.'.$env{'request.course.id'}.'.num'},
3265: $env{'course.'.$env{'request.course.id'}.'.domain'});
3266: &Apache::lonnet::clear_EXT_cache_status();
3267:
3268: my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
3269:
3270: #view individual student submission form - called using Javascript viewOneStudent
3271: $result.=&jscriptNform($symb);
3272:
3273: #beginning of class grading form
3274: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
3275: $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
3276: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
3277: '<input type="hidden" name="command" value="editgrades" />'."\n".
3278: &build_section_inputs().
3279: '<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
3280:
3281: my ($common_header,$specific_header);
3282: if ($env{'form.section'} eq 'all') {
3283: $common_header = &mt('Assign Common Grade to Class');
3284: $specific_header = &mt('Assign Grade to Specific Students in Class');
3285: } elsif ($env{'form.section'} eq 'none') {
3286: $common_header = &mt('Assign Common Grade to Students in no Section');
3287: $specific_header = &mt('Assign Grade to Specific Students in no Section');
3288: } else {
3289: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3290: $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
3291: $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
3292: }
3293: $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
3294: #radio buttons/text box for assigning points for a section or class.
3295: #handles different parts of a problem
3296: my $res_error;
3297: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
3298: if ($res_error) {
3299: return &navmap_errormsg();
3300: }
3301: my %weight = ();
3302: my $ctsparts = 0;
3303: my %seen = ();
3304: my @part_response_id = &flatten_responseType($responseType);
3305: foreach my $part_response_id (@part_response_id) {
3306: my ($partid,$respid) = @{ $part_response_id };
3307: my $part_resp = join('_',@{ $part_response_id });
3308: next if $seen{$partid};
3309: $seen{$partid}++;
3310: my $handgrade=$$handgrade{$part_resp};
3311: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
3312: $weight{$partid} = $wgt eq '' ? '1' : $wgt;
3313:
3314: my $display_part=&get_display_part($partid,$symb);
3315: my $radio.='<table border="0"><tr>';
3316: my $ctr = 0;
3317: while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
3318: $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
3319: 'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
3320: ','.$ctr.')" />'.$ctr."</label></td>\n";
3321: $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
3322: $ctr++;
3323: }
3324: $radio.='</tr></table>';
3325: my $line = '<input type="text" name="TEXTVAL_'.
3326: $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
3327: $partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
3328: $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
3329: $line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
3330: 'onchange="javascript:writeRadText(\''.$partid.'\','.
3331: $weight{$partid}.')"> '.
3332: '<option selected="selected"> </option>'.
3333: '<option value="excused">'.&mt('excused').'</option>'.
3334: '<option value="reset status">'.&mt('reset status').'</option>'.
3335: '</select></td>'.
3336: '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
3337: $line.='<input type="hidden" name="partid_'.
3338: $ctsparts.'" value="'.$partid.'" />'."\n";
3339: $line.='<input type="hidden" name="weight_'.
3340: $partid.'" value="'.$weight{$partid}.'" />'."\n";
3341:
3342: $result.=
3343: &Apache::loncommon::start_data_table_row()."\n".
3344: '<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>'.
3345: &Apache::loncommon::end_data_table_row()."\n";
3346: $ctsparts++;
3347: }
3348: $result.=&Apache::loncommon::end_data_table()."\n".
3349: '<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
3350: $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
3351: 'onclick="javascript:resetEntry('.$ctsparts.');" />';
3352:
3353: #table listing all the students in a section/class
3354: #header of table
3355: $result.= '<h3>'.$specific_header.'</h3>'.
3356: &Apache::loncommon::start_data_table().
3357: &Apache::loncommon::start_data_table_header_row().
3358: '<th>'.&mt('No.').'</th>'.
3359: '<th>'.&nameUserString('header')."</th>\n";
3360: my $partserror;
3361: my (@parts) = sort(&getpartlist($symb,\$partserror));
3362: if ($partserror) {
3363: return &navmap_errormsg();
3364: }
3365: my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
3366: my @partids = ();
3367: foreach my $part (@parts) {
3368: my $display=&Apache::lonnet::metadata($url,$part.'.display');
3369: my $narrowtext = &mt('Tries');
3370: $display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
3371: if (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
3372: my ($partid) = &split_part_type($part);
3373: push(@partids,$partid);
3374: my $display_part=&get_display_part($partid,$symb);
3375: if ($display =~ /^Partial Credit Factor/) {
3376: $result.='<th>'.
3377: &mt('Score Part: [_1]<br /> (weight = [_2])',
3378: $display_part,$weight{$partid}).'</th>'."\n";
3379: next;
3380:
3381: } else {
3382: if ($display =~ /Problem Status/) {
3383: my $grade_status_mt = &mt('Grade Status');
3384: $display =~ s{Problem Status}{$grade_status_mt<br />};
3385: }
3386: my $part_mt = &mt('Part:');
3387: $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
3388: }
3389:
3390: $result.='<th>'.$display.'</th>'."\n";
3391: }
3392: $result.=&Apache::loncommon::end_data_table_header_row();
3393:
3394: my %last_resets =
3395: &get_last_resets($symb,$env{'request.course.id'},\@partids);
3396:
3397: #get info for each student
3398: #list all the students - with points and grade status
3399: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
3400: my $ctr = 0;
3401: foreach (sort
3402: {
3403: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
3404: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
3405: }
3406: return $a cmp $b;
3407: } (keys(%$fullname))) {
3408: $ctr++;
3409: $result.=&viewstudentgrade($symb,$env{'request.course.id'},
3410: $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
3411: }
3412: $result.=&Apache::loncommon::end_data_table();
3413: $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
3414: $result.='<input type="button" value="'.&mt('Save').'" '.
3415: 'onclick="javascript:submit();" target="_self" /></form>'."\n";
3416: if (scalar(%$fullname) eq 0) {
3417: my $colspan=3+scalar(@parts);
3418: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3419: my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
3420: $result='<span class="LC_warning">'.
3421: &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
3422: $section_display, $stu_status).
3423: '</span>';
3424: }
3425: return $result;
3426: }
3427:
3428: #--- call by previous routine to display each student
3429: sub viewstudentgrade {
3430: my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
3431: my ($uname,$udom) = split(/:/,$student);
3432: my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
3433: my %aggregates = ();
3434: my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
3435: '<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
3436: "\n".$ctr.' </td><td> '.
3437: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
3438: '\');" target="_self">'.$fullname.'</a> '.
3439: '<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
3440: $student=~s/:/_/; # colon doen't work in javascript for names
3441: foreach my $apart (@$parts) {
3442: my ($part,$type) = &split_part_type($apart);
3443: my $score=$record{"resource.$part.$type"};
3444: $result.='<td align="center">';
3445: my ($aggtries,$totaltries);
3446: unless (exists($aggregates{$part})) {
3447: $totaltries = $record{'resource.'.$part.'.tries'};
3448:
3449: $aggtries = $totaltries;
3450: if ($$last_resets{$part}) {
3451: $aggtries = &get_num_tries(\%record,$$last_resets{$part},
3452: $part);
3453: }
3454: $result.='<input type="hidden" name="'.
3455: 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
3456: $result.='<input type="hidden" name="'.
3457: 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
3458: $aggregates{$part} = 1;
3459: }
3460: if ($type eq 'awarded') {
3461: my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
3462: $result.='<input type="hidden" name="'.
3463: 'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
3464: $result.='<input type="text" name="'.
3465: 'GD_'.$student.'_'.$part.'_awarded" '.
3466: 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
3467: '\')" value="'.$pts.'" size="4" /></td>'."\n";
3468: } elsif ($type eq 'solved') {
3469: my ($status,$foo)=split(/_/,$score,2);
3470: $status = 'nothing' if ($status eq '');
3471: $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
3472: $part.'_solved_s" value="'.$status.'" />'."\n";
3473: $result.=' <select name="'.
3474: 'GD_'.$student.'_'.$part.'_solved" '.
3475: 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
3476: $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>'
3477: : '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
3478: $result.='<option value="reset status">'.&mt('reset status').'</option>';
3479: $result.="</select> </td>\n";
3480: } else {
3481: $result.='<input type="hidden" name="'.
3482: 'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
3483: "\n";
3484: $result.='<input type="text" name="'.
3485: 'GD_'.$student.'_'.$part.'_'.$type.'" '.
3486: 'value="'.$score.'" size="4" /></td>'."\n";
3487: }
3488: }
3489: $result.=&Apache::loncommon::end_data_table_row();
3490: return $result;
3491: }
3492:
3493: #--- change scores for all the students in a section/class
3494: # record does not get update if unchanged
3495: sub editgrades {
3496: my ($request,$symb) = @_;
3497:
3498: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3499: my $title='<h2>'.&mt('Current Grade Status').'</h2>';
3500: $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
3501:
3502: my $result= &Apache::loncommon::start_data_table().
3503: &Apache::loncommon::start_data_table_header_row().
3504: '<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
3505: '<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
3506: my %scoreptr = (
3507: 'correct' =>'correct_by_override',
3508: 'incorrect'=>'incorrect_by_override',
3509: 'excused' =>'excused',
3510: 'ungraded' =>'ungraded_attempted',
3511: 'credited' =>'credit_attempted',
3512: 'nothing' => '',
3513: );
3514: my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
3515:
3516: my (@partid);
3517: my %weight = ();
3518: my %columns = ();
3519: my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
3520:
3521: my $partserror;
3522: my (@parts) = sort(&getpartlist($symb,\$partserror));
3523: if ($partserror) {
3524: return &navmap_errormsg();
3525: }
3526: my $header;
3527: while ($ctr < $env{'form.totalparts'}) {
3528: my $partid = $env{'form.partid_'.$ctr};
3529: push(@partid,$partid);
3530: $weight{$partid} = $env{'form.weight_'.$partid};
3531: $ctr++;
3532: }
3533: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3534: foreach my $partid (@partid) {
3535: $header .= '<th align="center">'.&mt('Old Score').'</th>'.
3536: '<th align="center">'.&mt('New Score').'</th>';
3537: $columns{$partid}=2;
3538: foreach my $stores (@parts) {
3539: my ($part,$type) = &split_part_type($stores);
3540: if ($part !~ m/^\Q$partid\E/) { next;}
3541: if ($type eq 'awarded' || $type eq 'solved') { next; }
3542: my $display=&Apache::lonnet::metadata($url,$stores.'.display');
3543: $display =~ s/\[Part: \Q$part\E\]//;
3544: my $narrowtext = &mt('Tries');
3545: $display =~ s/Number of Attempts/$narrowtext/;
3546: $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
3547: '<th align="center">'.&mt('New').' '.$display.'</th>';
3548: $columns{$partid}+=2;
3549: }
3550: }
3551: foreach my $partid (@partid) {
3552: my $display_part=&get_display_part($partid,$symb);
3553: $result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
3554: &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
3555: '</th>';
3556:
3557: }
3558: $result .= &Apache::loncommon::end_data_table_header_row().
3559: &Apache::loncommon::start_data_table_header_row().
3560: $header.
3561: &Apache::loncommon::end_data_table_header_row();
3562: my @noupdate;
3563: my ($updateCtr,$noupdateCtr) = (1,1);
3564: for ($i=0; $i<$env{'form.total'}; $i++) {
3565: my $line;
3566: my $user = $env{'form.ctr'.$i};
3567: my ($uname,$udom)=split(/:/,$user);
3568: my %newrecord;
3569: my $updateflag = 0;
3570: $line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
3571: my $usec=$classlist->{"$uname:$udom"}[5];
3572: if (!&canmodify($usec)) {
3573: my $numcols=scalar(@partid)*4+2;
3574: push(@noupdate,
3575: $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
3576: &mt('Not allowed to modify student')."</span></td></tr>");
3577: next;
3578: }
3579: my %aggregate = ();
3580: my $aggregateflag = 0;
3581: $user=~s/:/_/; # colon doen't work in javascript for names
3582: foreach (@partid) {
3583: my $old_aw = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
3584: my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
3585: my $old_part = $old_aw eq '' ? '' : $old_part_pcr;
3586: my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
3587: my $awarded = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
3588: my $pcr = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
3589: my $partial = $awarded eq '' ? '' : $pcr;
3590: my $score;
3591: if ($partial eq '') {
3592: $score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
3593: } elsif ($partial > 0) {
3594: $score = 'correct_by_override';
3595: } elsif ($partial == 0) {
3596: $score = 'incorrect_by_override';
3597: }
3598: my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
3599: $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
3600:
3601: $newrecord{'resource.'.$_.'.regrader'}=
3602: "$env{'user.name'}:$env{'user.domain'}";
3603: if ($dropMenu eq 'reset status' &&
3604: $old_score ne '') { # ignore if no previous attempts => nothing to reset
3605: $newrecord{'resource.'.$_.'.tries'} = '';
3606: $newrecord{'resource.'.$_.'.solved'} = '';
3607: $newrecord{'resource.'.$_.'.award'} = '';
3608: $newrecord{'resource.'.$_.'.awarded'} = '';
3609: $updateflag = 1;
3610: if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
3611: my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
3612: my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
3613: my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
3614: &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
3615: $aggregateflag = 1;
3616: }
3617: } elsif (!($old_part eq $partial && $old_score eq $score)) {
3618: $updateflag = 1;
3619: $newrecord{'resource.'.$_.'.awarded'} = $partial if $partial ne '';
3620: $newrecord{'resource.'.$_.'.solved'} = $score;
3621: $rec_update++;
3622: }
3623:
3624: $line .= '<td align="center">'.$old_aw.' </td>'.
3625: '<td align="center">'.$awarded.
3626: ($score eq 'excused' ? $score : '').' </td>';
3627:
3628:
3629: my $partid=$_;
3630: foreach my $stores (@parts) {
3631: my ($part,$type) = &split_part_type($stores);
3632: if ($part !~ m/^\Q$partid\E/) { next;}
3633: if ($type eq 'awarded' || $type eq 'solved') { next; }
3634: my $old_aw = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
3635: my $awarded = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
3636: if ($awarded ne '' && $awarded ne $old_aw) {
3637: $newrecord{'resource.'.$part.'.'.$type}= $awarded;
3638: $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
3639: $updateflag=1;
3640: }
3641: $line .= '<td align="center">'.$old_aw.' </td>'.
3642: '<td align="center">'.$awarded.' </td>';
3643: }
3644: }
3645: $line.="\n";
3646:
3647: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3648: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3649:
3650: if ($updateflag) {
3651: $count++;
3652: &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
3653: $udom,$uname);
3654:
3655: if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
3656: $cnum,$udom,$uname)) {
3657: # need to figure out if should be in queue.
3658: my %record =
3659: &Apache::lonnet::restore($symb,$env{'request.course.id'},
3660: $udom,$uname);
3661: my $all_graded = 1;
3662: my $none_graded = 1;
3663: foreach my $part (@parts) {
3664: if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
3665: $all_graded = 0;
3666: } else {
3667: $none_graded = 0;
3668: }
3669: }
3670:
3671: if ($all_graded || $none_graded) {
3672: &Apache::bridgetask::remove_from_queue('gradingqueue',
3673: $symb,$cdom,$cnum,
3674: $udom,$uname);
3675: }
3676: }
3677:
3678: $result.=&Apache::loncommon::start_data_table_row().
3679: '<td align="right"> '.$updateCtr.' </td>'.$line.
3680: &Apache::loncommon::end_data_table_row();
3681: $updateCtr++;
3682: } else {
3683: push(@noupdate,
3684: '<td align="right"> '.$noupdateCtr.' </td>'.$line);
3685: $noupdateCtr++;
3686: }
3687: if ($aggregateflag) {
3688: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
3689: $cdom,$cnum);
3690: }
3691: }
3692: if (@noupdate) {
3693: # my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
3694: my $numcols=scalar(@partid)*4+2;
3695: $result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
3696: '<td align="center" colspan="'.$numcols.'">'.
3697: &mt('No Changes Occurred For the Students Below').
3698: '</td>'.
3699: &Apache::loncommon::end_data_table_row();
3700: foreach my $line (@noupdate) {
3701: $result.=
3702: &Apache::loncommon::start_data_table_row().
3703: $line.
3704: &Apache::loncommon::end_data_table_row();
3705: }
3706: }
3707: $result .= &Apache::loncommon::end_data_table();
3708: my $msg = '<p><b>'.
3709: &mt('Number of records updated = [_1] for [quant,_2,student].',
3710: $rec_update,$count).'</b><br />'.
3711: '<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
3712: '</b></p>';
3713: return $title.$msg.$result;
3714: }
3715:
3716: sub split_part_type {
3717: my ($partstr) = @_;
3718: my ($temp,@allparts)=split(/_/,$partstr);
3719: my $type=pop(@allparts);
3720: my $part=join('_',@allparts);
3721: return ($part,$type);
3722: }
3723:
3724: #------------- end of section for handling grading by section/class ---------
3725: #
3726: #----------------------------------------------------------------------------
3727:
3728:
3729: #----------------------------------------------------------------------------
3730: #
3731: #-------------------------- Next few routines handles grading by csv upload
3732: #
3733: #--- Javascript to handle csv upload
3734: sub csvupload_javascript_reverse_associate {
3735: my $error1=&mt('You need to specify the username or the student/employee ID');
3736: my $error2=&mt('You need to specify at least one grading field');
3737: return(<<ENDPICK);
3738: function verify(vf) {
3739: var foundsomething=0;
3740: var founduname=0;
3741: var foundID=0;
3742: for (i=0;i<=vf.nfields.value;i++) {
3743: tw=eval('vf.f'+i+'.selectedIndex');
3744: if (i==0 && tw!=0) { foundID=1; }
3745: if (i==1 && tw!=0) { founduname=1; }
3746: if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
3747: }
3748: if (founduname==0 && foundID==0) {
3749: alert('$error1');
3750: return;
3751: }
3752: if (foundsomething==0) {
3753: alert('$error2');
3754: return;
3755: }
3756: vf.submit();
3757: }
3758: function flip(vf,tf) {
3759: var nw=eval('vf.f'+tf+'.selectedIndex');
3760: var i;
3761: for (i=0;i<=vf.nfields.value;i++) {
3762: //can not pick the same destination field for both name and domain
3763: if (((i ==0)||(i ==1)) &&
3764: ((tf==0)||(tf==1)) &&
3765: (i!=tf) &&
3766: (eval('vf.f'+i+'.selectedIndex')==nw)) {
3767: eval('vf.f'+i+'.selectedIndex=0;')
3768: }
3769: }
3770: }
3771: ENDPICK
3772: }
3773:
3774: sub csvupload_javascript_forward_associate {
3775: my $error1=&mt('You need to specify the username or the student/employee ID');
3776: my $error2=&mt('You need to specify at least one grading field');
3777: return(<<ENDPICK);
3778: function verify(vf) {
3779: var foundsomething=0;
3780: var founduname=0;
3781: var foundID=0;
3782: for (i=0;i<=vf.nfields.value;i++) {
3783: tw=eval('vf.f'+i+'.selectedIndex');
3784: if (tw==1) { foundID=1; }
3785: if (tw==2) { founduname=1; }
3786: if (tw>3) { foundsomething=1; }
3787: }
3788: if (founduname==0 && foundID==0) {
3789: alert('$error1');
3790: return;
3791: }
3792: if (foundsomething==0) {
3793: alert('$error2');
3794: return;
3795: }
3796: vf.submit();
3797: }
3798: function flip(vf,tf) {
3799: var nw=eval('vf.f'+tf+'.selectedIndex');
3800: var i;
3801: //can not pick the same destination field twice
3802: for (i=0;i<=vf.nfields.value;i++) {
3803: if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
3804: eval('vf.f'+i+'.selectedIndex=0;')
3805: }
3806: }
3807: }
3808: ENDPICK
3809: }
3810:
3811: sub csvuploadmap_header {
3812: my ($request,$symb,$datatoken,$distotal)= @_;
3813: my $javascript;
3814: if ($env{'form.upfile_associate'} eq 'reverse') {
3815: $javascript=&csvupload_javascript_reverse_associate();
3816: } else {
3817: $javascript=&csvupload_javascript_forward_associate();
3818: }
3819:
3820: my $result='';
3821: $symb = &Apache::lonenc::check_encrypt($symb);
3822: $request->print(<<ENDPICK);
3823: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3824: <h3><span class="LC_info">Uploading Class Grades</span></h3>
3825: $result
3826: <hr />
3827: <h3>Identify fields</h3>
3828: Total number of records found in file: $distotal <hr />
3829: Enter as many fields as you can. The system will inform you and bring you back
3830: to this page if the data selected is insufficient to run your class.<hr />
3831: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
3832: <input type="hidden" name="associate" value="" />
3833: <input type="hidden" name="phase" value="three" />
3834: <input type="hidden" name="datatoken" value="$datatoken" />
3835: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
3836: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
3837: <input type="hidden" name="upfile_associate"
3838: value="$env{'form.upfile_associate'}" />
3839: <input type="hidden" name="symb" value="$symb" />
3840: <input type="hidden" name="command" value="csvuploadoptions" />
3841: <hr />
3842: ENDPICK
3843: $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
3844: return '';
3845:
3846: }
3847:
3848: sub csvupload_fields {
3849: my ($symb,$errorref) = @_;
3850: my (@parts) = &getpartlist($symb,$errorref);
3851: if (ref($errorref)) {
3852: if ($$errorref) {
3853: return;
3854: }
3855: }
3856:
3857: my @fields=(['ID','Student/Employee ID'],
3858: ['username','Student Username'],
3859: ['domain','Student Domain']);
3860: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3861: foreach my $part (sort(@parts)) {
3862: my @datum;
3863: my $display=&Apache::lonnet::metadata($url,$part.'.display');
3864: my $name=$part;
3865: if (!$display) { $display = $name; }
3866: @datum=($name,$display);
3867: if ($name=~/^stores_(.*)_awarded/) {
3868: push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
3869: }
3870: push(@fields,\@datum);
3871: }
3872: return (@fields);
3873: }
3874:
3875: sub csvuploadmap_footer {
3876: my ($request,$i,$keyfields) =@_;
3877: $request->print(<<ENDPICK);
3878: </table>
3879: <input type="hidden" name="nfields" value="$i" />
3880: <input type="hidden" name="keyfields" value="$keyfields" />
3881: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
3882: </form>
3883: ENDPICK
3884: }
3885:
3886: sub checkforfile_js {
3887: my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
3888: my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
3889: function checkUpload(formname) {
3890: if (formname.upfile.value == "") {
3891: alert("$alertmsg");
3892: return false;
3893: }
3894: formname.submit();
3895: }
3896: CSVFORMJS
3897: return $result;
3898: }
3899:
3900: sub upcsvScores_form {
3901: my ($request,$symb) = @_;
3902: if (!$symb) {return '';}
3903: my $result=&checkforfile_js();
3904: $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
3905: $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
3906: $result.=' <b>'.&mt('Specify a file containing the class scores for current resource.').
3907: '</b></td></tr>'."\n";
3908: $result.='<tr bgcolor=#ffffe6><td>'."\n";
3909: my $upload=&mt("Upload Scores");
3910: my $upfile_select=&Apache::loncommon::upfile_select_html();
3911: my $ignore=&mt('Ignore First Line');
3912: $symb = &Apache::lonenc::check_encrypt($symb);
3913: $result.=<<ENDUPFORM;
3914: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3915: <input type="hidden" name="symb" value="$symb" />
3916: <input type="hidden" name="command" value="csvuploadmap" />
3917: $upfile_select
3918: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
3919: </form>
3920: ENDUPFORM
3921: $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
3922: &mt("How do I create a CSV file from a spreadsheet"))
3923: .'</td></tr></table>'."\n";
3924: $result.='</td></tr></table><br /><br />'."\n";
3925: return $result;
3926: }
3927:
3928:
3929: sub csvuploadmap {
3930: my ($request,$symb)= @_;
3931: if (!$symb) {return '';}
3932:
3933: my $datatoken;
3934: if (!$env{'form.datatoken'}) {
3935: $datatoken=&Apache::loncommon::upfile_store($request);
3936: } else {
3937: $datatoken=$env{'form.datatoken'};
3938: &Apache::loncommon::load_tmp_file($request);
3939: }
3940: my @records=&Apache::loncommon::upfile_record_sep();
3941: &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
3942: my ($i,$keyfields);
3943: if (@records) {
3944: my $fieldserror;
3945: my @fields=&csvupload_fields($symb,\$fieldserror);
3946: if ($fieldserror) {
3947: $request->print(&navmap_errormsg());
3948: return;
3949: }
3950: if ($env{'form.upfile_associate'} eq 'reverse') {
3951: &Apache::loncommon::csv_print_samples($request,\@records);
3952: $i=&Apache::loncommon::csv_print_select_table($request,\@records,
3953: \@fields);
3954: foreach (@fields) { $keyfields.=$_->[0].','; }
3955: chop($keyfields);
3956: } else {
3957: unshift(@fields,['none','']);
3958: $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
3959: \@fields);
3960: foreach my $rec (@records) {
3961: my %temp = &Apache::loncommon::record_sep($rec);
3962: if (%temp) {
3963: $keyfields=join(',',sort(keys(%temp)));
3964: last;
3965: }
3966: }
3967: }
3968: }
3969: &csvuploadmap_footer($request,$i,$keyfields);
3970:
3971: return '';
3972: }
3973:
3974: sub csvuploadoptions {
3975: my ($request,$symb)= @_;
3976: $request->print(<<ENDPICK);
3977: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
3978: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
3979: <input type="hidden" name="command" value="csvuploadassign" />
3980: <!--
3981: <p>
3982: <label>
3983: <input type="checkbox" name="show_full_results" />
3984: Show a table of all changes
3985: </label>
3986: </p>
3987: -->
3988: <p>
3989: <label>
3990: <input type="checkbox" name="overwite_scores" checked="checked" />
3991: Overwrite any existing score
3992: </label>
3993: </p>
3994: ENDPICK
3995: my %fields=&get_fields();
3996: if (!defined($fields{'domain'})) {
3997: my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
3998: $request->print("\n<p> Users are in domain: ".$domform."</p>\n");
3999: }
4000: foreach my $key (sort(keys(%env))) {
4001: if ($key !~ /^form\.(.*)$/) { next; }
4002: my $cleankey=$1;
4003: if ($cleankey eq 'command') { next; }
4004: $request->print('<input type="hidden" name="'.$cleankey.
4005: '" value="'.$env{$key}.'" />'."\n");
4006: }
4007: # FIXME do a check for any duplicated user ids...
4008: # FIXME do a check for any invalid user ids?...
4009: $request->print('<input type="submit" value="Assign Grades" /><br />
4010: <hr /></form>'."\n");
4011: return '';
4012: }
4013:
4014: sub get_fields {
4015: my %fields;
4016: my @keyfields = split(/\,/,$env{'form.keyfields'});
4017: for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
4018: if ($env{'form.upfile_associate'} eq 'reverse') {
4019: if ($env{'form.f'.$i} ne 'none') {
4020: $fields{$keyfields[$i]}=$env{'form.f'.$i};
4021: }
4022: } else {
4023: if ($env{'form.f'.$i} ne 'none') {
4024: $fields{$env{'form.f'.$i}}=$keyfields[$i];
4025: }
4026: }
4027: }
4028: return %fields;
4029: }
4030:
4031: sub csvuploadassign {
4032: my ($request,$symb)= @_;
4033: if (!$symb) {return '';}
4034: my $error_msg = '';
4035: &Apache::loncommon::load_tmp_file($request);
4036: my @gradedata = &Apache::loncommon::upfile_record_sep();
4037: my %fields=&get_fields();
4038: $request->print('<h3>Assigning Grades</h3>');
4039: my $courseid=$env{'request.course.id'};
4040: my ($classlist) = &getclasslist('all',0);
4041: my @notallowed;
4042: my @skipped;
4043: my $countdone=0;
4044: foreach my $grade (@gradedata) {
4045: my %entries=&Apache::loncommon::record_sep($grade);
4046: my $domain;
4047: if ($entries{$fields{'domain'}}) {
4048: $domain=$entries{$fields{'domain'}};
4049: } else {
4050: $domain=$env{'form.default_domain'};
4051: }
4052: $domain=~s/\s//g;
4053: my $username=$entries{$fields{'username'}};
4054: $username=~s/\s//g;
4055: if (!$username) {
4056: my $id=$entries{$fields{'ID'}};
4057: $id=~s/\s//g;
4058: my %ids=&Apache::lonnet::idget($domain,$id);
4059: $username=$ids{$id};
4060: }
4061: if (!exists($$classlist{"$username:$domain"})) {
4062: my $id=$entries{$fields{'ID'}};
4063: $id=~s/\s//g;
4064: if ($id) {
4065: push(@skipped,"$id:$domain");
4066: } else {
4067: push(@skipped,"$username:$domain");
4068: }
4069: next;
4070: }
4071: my $usec=$classlist->{"$username:$domain"}[5];
4072: if (!&canmodify($usec)) {
4073: push(@notallowed,"$username:$domain");
4074: next;
4075: }
4076: my %points;
4077: my %grades;
4078: foreach my $dest (keys(%fields)) {
4079: if ($dest eq 'ID' || $dest eq 'username' ||
4080: $dest eq 'domain') { next; }
4081: if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
4082: if ($dest=~/stores_(.*)_points/) {
4083: my $part=$1;
4084: my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
4085: $symb,$domain,$username);
4086: if ($wgt) {
4087: $entries{$fields{$dest}}=~s/\s//g;
4088: my $pcr=$entries{$fields{$dest}} / $wgt;
4089: my $award=($pcr == 0) ? 'incorrect_by_override'
4090: : 'correct_by_override';
4091: $grades{"resource.$part.awarded"}=$pcr;
4092: $grades{"resource.$part.solved"}=$award;
4093: $points{$part}=1;
4094: } else {
4095: $error_msg = "<br />" .
4096: &mt("Some point values were assigned"
4097: ." for problems with a weight "
4098: ."of zero. These values were "
4099: ."ignored.");
4100: }
4101: } else {
4102: if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
4103: if ($dest=~/stores_(.*)_solved/) { if ($points{$1}) {next;} }
4104: my $store_key=$dest;
4105: $store_key=~s/^stores/resource/;
4106: $store_key=~s/_/\./g;
4107: $grades{$store_key}=$entries{$fields{$dest}};
4108: }
4109: }
4110: if (! %grades) {
4111: push(@skipped,&mt("[_1]: no data to save","$username:$domain"));
4112: } else {
4113: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
4114: my $result=&Apache::lonnet::cstore(\%grades,$symb,
4115: $env{'request.course.id'},
4116: $domain,$username);
4117: if ($result eq 'ok') {
4118: # Successfully stored
4119: $request->print('.');
4120: # Remove from grading queue
4121: &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
4122: $env{'course.'.$env{'request.course.id'}.'.domain'},
4123: $env{'course.'.$env{'request.course.id'}.'.num'},
4124: $domain,$username);
4125: $countdone++;
4126: } else {
4127: $request->print("<p><span class=\"LC_error\">".
4128: &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
4129: "$username:$domain",$result)."</span></p>");
4130: }
4131: $request->rflush();
4132: }
4133: }
4134: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
4135: if (@skipped) {
4136: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
4137: $request->print(join(', ',@skipped));
4138: }
4139: if (@notallowed) {
4140: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
4141: $request->print(join(', ',@notallowed));
4142: }
4143: $request->print("<br />\n");
4144: return $error_msg;
4145: }
4146: #------------- end of section for handling csv file upload ---------
4147: #
4148: #-------------------------------------------------------------------
4149: #
4150: #-------------- Next few routines handle grading by page/sequence
4151: #
4152: #--- Select a page/sequence and a student to grade
4153: sub pickStudentPage {
4154: my ($request,$symb) = @_;
4155:
4156: my $alertmsg = &mt('Please select the student you wish to grade.');
4157: $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
4158:
4159: function checkPickOne(formname) {
4160: if (radioSelection(formname.student) == null) {
4161: alert("$alertmsg");
4162: return;
4163: }
4164: ptr = pullDownSelection(formname.selectpage);
4165: formname.page.value = formname["page"+ptr].value;
4166: formname.title.value = formname["title"+ptr].value;
4167: formname.submit();
4168: }
4169:
4170: LISTJAVASCRIPT
4171: &commonJSfunctions($request);
4172:
4173: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4174: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4175: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4176:
4177: my $result='<h3><span class="LC_info"> '.
4178: &mt('Manual Grading by Page or Sequence').'</span></h3>';
4179:
4180: $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
4181: my $map_error;
4182: my ($titles,$symbx) = &getSymbMap($map_error);
4183: if ($map_error) {
4184: $request->print(&navmap_errormsg());
4185: return;
4186: }
4187: my ($curpage) =&Apache::lonnet::decode_symb($symb);
4188: # my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb);
4189: # my $type=($curpage =~ /\.(page|sequence)/);
4190: my $select = '<select name="selectpage">'."\n";
4191: my $ctr=0;
4192: foreach (@$titles) {
4193: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4194: $select.='<option value="'.$ctr.'" '.
4195: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
4196: '>'.$showtitle.'</option>'."\n";
4197: $ctr++;
4198: }
4199: $select.= '</select>';
4200: $result.=' <b>'.&mt('Problems from').':</b> '.$select."<br />\n";
4201:
4202: $ctr=0;
4203: foreach (@$titles) {
4204: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4205: $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
4206: $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
4207: $ctr++;
4208: }
4209: $result.='<input type="hidden" name="page" />'."\n".
4210: '<input type="hidden" name="title" />'."\n";
4211:
4212: my $options =
4213: '<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
4214: '<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
4215: $result.=' <b>'.&mt('View Problem Text').': </b>'.$options;
4216:
4217: $options =
4218: '<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
4219: '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
4220: '<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
4221: $result.=' <b>'.&mt('Submissions').': </b>'.$options;
4222:
4223: $result.=&build_section_inputs();
4224: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
4225: $result.='<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
4226: '<input type="hidden" name="command" value="displayPage" />'."\n".
4227: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."<br />\n";
4228:
4229: $result.=' <b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
4230:
4231: $result.=' <input type="button" '.
4232: 'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' →" /><br />'."\n";
4233:
4234: $request->print($result);
4235:
4236: my $studentTable.=' <b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
4237: &Apache::loncommon::start_data_table().
4238: &Apache::loncommon::start_data_table_header_row().
4239: '<th align="right"> '.&mt('No.').'</th>'.
4240: '<th>'.&nameUserString('header').'</th>'.
4241: '<th align="right"> '.&mt('No.').'</th>'.
4242: '<th>'.&nameUserString('header').'</th>'.
4243: &Apache::loncommon::end_data_table_header_row();
4244:
4245: my (undef,undef,$fullname) = &getclasslist($getsec,'1');
4246: my $ptr = 1;
4247: foreach my $student (sort
4248: {
4249: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
4250: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
4251: }
4252: return $a cmp $b;
4253: } (keys(%$fullname))) {
4254: my ($uname,$udom) = split(/:/,$student);
4255: $studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
4256: : '</td>');
4257: $studentTable.='<td align="right">'.$ptr.' </td>';
4258: $studentTable.='<td> <label><input type="radio" name="student" value="'.$student.'" /> '
4259: .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
4260: $studentTable.=
4261: ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row()
4262: : '');
4263: $ptr++;
4264: }
4265: if ($ptr%2 == 0) {
4266: $studentTable.='</td><td> </td><td> </td>'.
4267: &Apache::loncommon::end_data_table_row();
4268: }
4269: $studentTable.=&Apache::loncommon::end_data_table()."\n";
4270: $studentTable.='<input type="button" '.
4271: 'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' →" /></form>'."\n";
4272:
4273: $request->print($studentTable);
4274:
4275: return '';
4276: }
4277:
4278: sub getSymbMap {
4279: my ($map_error) = @_;
4280: my $navmap = Apache::lonnavmaps::navmap->new();
4281: unless (ref($navmap)) {
4282: if (ref($map_error)) {
4283: $$map_error = 'navmap';
4284: }
4285: return;
4286: }
4287: my %symbx = ();
4288: my @titles = ();
4289: my $minder = 0;
4290:
4291: # Gather every sequence that has problems.
4292: my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
4293: 1,0,1);
4294: for my $sequence ($navmap->getById('0.0'), @sequences) {
4295: if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
4296: my $title = $minder.'.'.
4297: &HTML::Entities::encode($sequence->compTitle(),'"\'&');
4298: push(@titles, $title); # minder in case two titles are identical
4299: $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
4300: $minder++;
4301: }
4302: }
4303: return \@titles,\%symbx;
4304: }
4305:
4306: #
4307: #--- Displays a page/sequence w/wo problems, w/wo submissions
4308: sub displayPage {
4309: my ($request,$symb) = @_;
4310: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4311: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4312: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4313: my $pageTitle = $env{'form.page'};
4314: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
4315: my ($uname,$udom) = split(/:/,$env{'form.student'});
4316: my $usec=$classlist->{$env{'form.student'}}[5];
4317:
4318: #need to make sure we have the correct data for later EXT calls,
4319: #thus invalidate the cache
4320: &Apache::lonnet::devalidatecourseresdata(
4321: $env{'course.'.$env{'request.course.id'}.'.num'},
4322: $env{'course.'.$env{'request.course.id'}.'.domain'});
4323: &Apache::lonnet::clear_EXT_cache_status();
4324:
4325: if (!&canview($usec)) {
4326: $request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
4327: return;
4328: }
4329: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
4330: $result.='<h3> '.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
4331: '</h3>'."\n";
4332: $env{'form.CODE'} = uc($env{'form.CODE'});
4333: if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
4334: $result.='<h3> '.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
4335: } else {
4336: delete($env{'form.CODE'});
4337: }
4338: &sub_page_js($request);
4339: $request->print($result);
4340:
4341: my $navmap = Apache::lonnavmaps::navmap->new();
4342: unless (ref($navmap)) {
4343: $request->print(&navmap_errormsg());
4344: return;
4345: }
4346: my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
4347: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
4348: if (!$map) {
4349: $request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
4350: return;
4351: }
4352: my $iterator = $navmap->getIterator($map->map_start(),
4353: $map->map_finish());
4354:
4355: my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
4356: '<input type="hidden" name="command" value="gradeByPage" />'."\n".
4357: '<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
4358: '<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
4359: '<input type="hidden" name="page" value="'.$pageTitle.'" />'."\n".
4360: '<input type="hidden" name="title" value="'.$env{'form.title'}.'" />'."\n".
4361: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
4362: '<input type="hidden" name="overRideScore" value="no" />'."\n";
4363:
4364: if (defined($env{'form.CODE'})) {
4365: $studentTable.=
4366: '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
4367: }
4368: my $checkIcon = '<img alt="'.&mt('Check Mark').
4369: '" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
4370:
4371: $studentTable.=' <span class="LC_info">'.
4372: &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
4373: '</span>'."\n".
4374: &Apache::loncommon::start_data_table().
4375: &Apache::loncommon::start_data_table_header_row().
4376: '<th align="center"> Prob. </th>'.
4377: '<th> '.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
4378: &Apache::loncommon::end_data_table_header_row();
4379:
4380: &Apache::lonxml::clear_problem_counter();
4381: my ($depth,$question,$prob) = (1,1,1);
4382: $iterator->next(); # skip the first BEGIN_MAP
4383: my $curRes = $iterator->next(); # for "current resource"
4384: while ($depth > 0) {
4385: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
4386: if($curRes == $iterator->END_MAP) { $depth--; }
4387:
4388: if (ref($curRes) && $curRes->is_problem()) {
4389: my $parts = $curRes->parts();
4390: my $title = $curRes->compTitle();
4391: my $symbx = $curRes->symb();
4392: $studentTable.=
4393: &Apache::loncommon::start_data_table_row().
4394: '<td align="center" valign="top" >'.$prob.
4395: (scalar(@{$parts}) == 1 ? ''
4396: : '<br />('.&mt('[_1] parts)',
4397: scalar(@{$parts}))
4398: ).
4399: '</td>';
4400: $studentTable.='<td valign="top">';
4401: my %form = ('CODE' => $env{'form.CODE'},);
4402: if ($env{'form.vProb'} eq 'yes' ) {
4403: $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
4404: undef,'both',\%form);
4405: } else {
4406: my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
4407: $companswer =~ s|<form(.*?)>||g;
4408: $companswer =~ s|</form>||g;
4409: # while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
4410: # $companswer =~ s/$1/ /ms;
4411: # $request->print('match='.$1."<br />\n");
4412: # }
4413: # $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
4414: $studentTable.=' <b>'.$title.'</b> <br /> <b>'.&mt('Correct answer').':</b><br />'.$companswer;
4415: }
4416:
4417: my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
4418:
4419: if ($env{'form.lastSub'} eq 'datesub') {
4420: if ($record{'version'} eq '') {
4421: $studentTable.='<br /> <span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
4422: } else {
4423: my %responseType = ();
4424: foreach my $partid (@{$parts}) {
4425: my @responseIds =$curRes->responseIds($partid);
4426: my @responseType =$curRes->responseType($partid);
4427: my %responseIds;
4428: for (my $i=0;$i<=$#responseIds;$i++) {
4429: $responseIds{$responseIds[$i]}=$responseType[$i];
4430: }
4431: $responseType{$partid} = \%responseIds;
4432: }
4433: $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
4434:
4435: }
4436: } elsif ($env{'form.lastSub'} eq 'all') {
4437: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
4438: $studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
4439: $env{'request.course.id'},
4440: '','.submission');
4441:
4442: }
4443: if (&canmodify($usec)) {
4444: $studentTable.=&gradeBox_start();
4445: foreach my $partid (@{$parts}) {
4446: $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
4447: $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
4448: $question++;
4449: }
4450: $studentTable.=&gradeBox_end();
4451: $prob++;
4452: }
4453: $studentTable.='</td></tr>';
4454:
4455: }
4456: $curRes = $iterator->next();
4457: }
4458:
4459: $studentTable.=
4460: '</table>'."\n".
4461: '<input type="button" value="'.&mt('Save').'" '.
4462: 'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
4463: '</form>'."\n";
4464: $request->print($studentTable);
4465:
4466: return '';
4467: }
4468:
4469: sub displaySubByDates {
4470: my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
4471: my $isCODE=0;
4472: my $isTask = ($symb =~/\.task$/);
4473: if (exists($record->{'resource.CODE'})) { $isCODE=1; }
4474: my $studentTable=&Apache::loncommon::start_data_table().
4475: &Apache::loncommon::start_data_table_header_row().
4476: '<th>'.&mt('Date/Time').'</th>'.
4477: ($isCODE?'<th>'.&mt('CODE').'</th>':'').
4478: '<th>'.&mt('Submission').'</th>'.
4479: '<th>'.&mt('Status').'</th>'.
4480: &Apache::loncommon::end_data_table_header_row();
4481: my ($version);
4482: my %mark;
4483: my %orders;
4484: $mark{'correct_by_student'} = $checkIcon;
4485: if (!exists($$record{'1:timestamp'})) {
4486: return '<br /> <span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
4487: }
4488:
4489: my $interaction;
4490: my $no_increment = 1;
4491: for ($version=1;$version<=$$record{'version'};$version++) {
4492: my $timestamp =
4493: &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
4494: if (exists($$record{$version.':resource.0.version'})) {
4495: $interaction = $$record{$version.':resource.0.version'};
4496: }
4497:
4498: my $where = ($isTask ? "$version:resource.$interaction"
4499: : "$version:resource");
4500: $studentTable.=&Apache::loncommon::start_data_table_row().
4501: '<td>'.$timestamp.'</td>';
4502: if ($isCODE) {
4503: $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
4504: }
4505: my @versionKeys = split(/\:/,$$record{$version.':keys'});
4506: my @displaySub = ();
4507: foreach my $partid (@{$parts}) {
4508: my $hidden;
4509: if (($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurvey') ||
4510: ($$record{$version.':resource.'.$partid.'.type'} eq 'anonsurveycred')) {
4511: $hidden = 1;
4512: }
4513: my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
4514: : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
4515:
4516: # next if ($$record{"$version:resource.$partid.solved"} eq '');
4517: my $display_part=&get_display_part($partid,$symb);
4518: foreach my $matchKey (@matchKey) {
4519: if (exists($$record{$version.':'.$matchKey}) &&
4520: $$record{$version.':'.$matchKey} ne '') {
4521:
4522: my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
4523: : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
4524: $displaySub[0].='<span class="LC_nobreak"';
4525: $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
4526: .' <span class="LC_internal_info">'
4527: .'('.&mt('Response ID: [_1]',$responseId).')'
4528: .'</span>'
4529: .' <b>';
4530: if ($hidden) {
4531: $displaySub[0].= &mt('Anonymous Survey').'</b>';
4532: } else {
4533: if ($$record{"$where.$partid.tries"} eq '') {
4534: $displaySub[0].=&mt('Trial not counted');
4535: } else {
4536: $displaySub[0].=&mt('Trial: [_1]',
4537: $$record{"$where.$partid.tries"});
4538: }
4539: my $responseType=($isTask ? 'Task'
4540: : $responseType->{$partid}->{$responseId});
4541: if (!exists($orders{$partid})) { $orders{$partid}={}; }
4542: if (!exists($orders{$partid}->{$responseId})) {
4543: $orders{$partid}->{$responseId}=
4544: &get_order($partid,$responseId,$symb,$uname,$udom,
4545: $no_increment);
4546: }
4547: $displaySub[0].='</b></span>'; # /nobreak
4548: $displaySub[0].=' '.
4549: &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
4550: }
4551: }
4552: }
4553: if (exists($$record{"$where.$partid.checkedin"})) {
4554: $displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
4555: $$record{"$where.$partid.checkedin"},
4556: $$record{"$where.$partid.checkedin.slot"}).
4557: '<br />';
4558: }
4559: if (exists $$record{"$where.$partid.award"}) {
4560: $displaySub[1].='<b>'.&mt('Part:').'</b> '.$display_part.' '.
4561: lc($$record{"$where.$partid.award"}).' '.
4562: $mark{$$record{"$where.$partid.solved"}}.
4563: '<br />';
4564: }
4565: if (exists $$record{"$where.$partid.regrader"}) {
4566: $displaySub[2].=$$record{"$where.$partid.regrader"}.
4567: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
4568: } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
4569: $displaySub[2].=
4570: $$record{"$version:resource.$partid.regrader"}.
4571: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
4572: }
4573: }
4574: # needed because old essay regrader has not parts info
4575: if (exists $$record{"$version:resource.regrader"}) {
4576: $displaySub[2].=$$record{"$version:resource.regrader"};
4577: }
4578: $studentTable.='<td>'.$displaySub[0].' </td><td>'.$displaySub[1];
4579: if ($displaySub[2]) {
4580: $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
4581: }
4582: $studentTable.=' </td>'.
4583: &Apache::loncommon::end_data_table_row();
4584: }
4585: $studentTable.=&Apache::loncommon::end_data_table();
4586: return $studentTable;
4587: }
4588:
4589: sub updateGradeByPage {
4590: my ($request,$symb) = @_;
4591:
4592: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4593: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4594: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4595: my $pageTitle = $env{'form.page'};
4596: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
4597: my ($uname,$udom) = split(/:/,$env{'form.student'});
4598: my $usec=$classlist->{$env{'form.student'}}[5];
4599: if (!&canmodify($usec)) {
4600: $request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
4601: return;
4602: }
4603: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
4604: $result.='<h3> '.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
4605: '</h3>'."\n";
4606:
4607: $request->print($result);
4608:
4609:
4610: my $navmap = Apache::lonnavmaps::navmap->new();
4611: unless (ref($navmap)) {
4612: $request->print(&navmap_errormsg());
4613: return;
4614: }
4615: my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
4616: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
4617: if (!$map) {
4618: $request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
4619: return;
4620: }
4621: my $iterator = $navmap->getIterator($map->map_start(),
4622: $map->map_finish());
4623:
4624: my $studentTable=
4625: &Apache::loncommon::start_data_table().
4626: &Apache::loncommon::start_data_table_header_row().
4627: '<th align="center"> '.&mt('Prob.').' </th>'.
4628: '<th> '.&mt('Title').' </th>'.
4629: '<th> '.&mt('Previous Score').' </th>'.
4630: '<th> '.&mt('New Score').' </th>'.
4631: &Apache::loncommon::end_data_table_header_row();
4632:
4633: $iterator->next(); # skip the first BEGIN_MAP
4634: my $curRes = $iterator->next(); # for "current resource"
4635: my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
4636: while ($depth > 0) {
4637: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
4638: if($curRes == $iterator->END_MAP) { $depth--; }
4639:
4640: if (ref($curRes) && $curRes->is_problem()) {
4641: my $parts = $curRes->parts();
4642: my $title = $curRes->compTitle();
4643: my $symbx = $curRes->symb();
4644: $studentTable.=
4645: &Apache::loncommon::start_data_table_row().
4646: '<td align="center" valign="top" >'.$prob.
4647: (scalar(@{$parts}) == 1 ? ''
4648: : '<br />('.&mt('[quant,_1, part]',scalar(@{$parts}))
4649: .')').'</td>';
4650: $studentTable.='<td valign="top"> <b>'.$title.'</b> </td>';
4651:
4652: my %newrecord=();
4653: my @displayPts=();
4654: my %aggregate = ();
4655: my $aggregateflag = 0;
4656: foreach my $partid (@{$parts}) {
4657: my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
4658: my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
4659:
4660: my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ?
4661: $env{'form.WGT'.$question.'_'.$partid} : 1;
4662: my $partial = $newpts/$wgt;
4663: my $score;
4664: if ($partial > 0) {
4665: $score = 'correct_by_override';
4666: } elsif ($newpts ne '') { #empty is taken as 0
4667: $score = 'incorrect_by_override';
4668: }
4669: my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
4670: if ($dropMenu eq 'excused') {
4671: $partial = '';
4672: $score = 'excused';
4673: } elsif ($dropMenu eq 'reset status'
4674: && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
4675: $newrecord{'resource.'.$partid.'.tries'} = 0;
4676: $newrecord{'resource.'.$partid.'.solved'} = '';
4677: $newrecord{'resource.'.$partid.'.award'} = '';
4678: $newrecord{'resource.'.$partid.'.awarded'} = 0;
4679: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
4680: $changeflag++;
4681: $newpts = '';
4682:
4683: my $aggtries = $env{'form.aggtries'.$question.'_'.$partid};
4684: my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
4685: my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
4686: if ($aggtries > 0) {
4687: &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
4688: $aggregateflag = 1;
4689: }
4690: }
4691: my $display_part=&get_display_part($partid,$curRes->symb());
4692: my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
4693: $displayPts[0].=' <b>'.&mt('Part').':</b> '.$display_part.' = '.
4694: (($oldstatus eq 'excused') ? 'excused' : $oldpts).
4695: ' <br />';
4696: $displayPts[1].=' <b>'.&mt('Part').':</b> '.$display_part.' = '.
4697: (($score eq 'excused') ? 'excused' : $newpts).
4698: ' <br />';
4699: $question++;
4700: next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
4701:
4702: $newrecord{'resource.'.$partid.'.awarded'} = $partial if $partial ne '';
4703: $newrecord{'resource.'.$partid.'.solved'} = $score if $score ne '';
4704: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
4705: if (scalar(keys(%newrecord)) > 0);
4706:
4707: $changeflag++;
4708: }
4709: if (scalar(keys(%newrecord)) > 0) {
4710: my %record =
4711: &Apache::lonnet::restore($symbx,$env{'request.course.id'},
4712: $udom,$uname);
4713:
4714: if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
4715: $newrecord{'resource.CODE'} = $env{'form.CODE'};
4716: } elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
4717: $newrecord{'resource.CODE'} = '';
4718: }
4719: &Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
4720: $udom,$uname);
4721: %record = &Apache::lonnet::restore($symbx,
4722: $env{'request.course.id'},
4723: $udom,$uname);
4724: &check_and_remove_from_queue($parts,\%record,undef,$symbx,
4725: $cdom,$cnum,$udom,$uname);
4726: }
4727:
4728: if ($aggregateflag) {
4729: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
4730: $env{'course.'.$env{'request.course.id'}.'.domain'},
4731: $env{'course.'.$env{'request.course.id'}.'.num'});
4732: }
4733:
4734: $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
4735: '<td valign="top">'.$displayPts[1].'</td>'.
4736: &Apache::loncommon::end_data_table_row();
4737:
4738: $prob++;
4739: }
4740: $curRes = $iterator->next();
4741: }
4742:
4743: $studentTable.=&Apache::loncommon::end_data_table();
4744: my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
4745: &mt('The scores were changed for [quant,_1,problem].',
4746: $changeflag));
4747: $request->print($grademsg.$studentTable);
4748:
4749: return '';
4750: }
4751:
4752: #-------- end of section for handling grading by page/sequence ---------
4753: #
4754: #-------------------------------------------------------------------
4755:
4756: #-------------------- Bubblesheet (Scantron) Grading -------------------
4757: #
4758: #------ start of section for handling grading by page/sequence ---------
4759:
4760: =pod
4761:
4762: =head1 Bubble sheet grading routines
4763:
4764: For this documentation:
4765:
4766: 'scanline' refers to the full line of characters
4767: from the file that we are parsing that represents one entire sheet
4768:
4769: 'bubble line' refers to the data
4770: representing the line of bubbles that are on the physical bubble sheet
4771:
4772:
4773: The overall process is that a scanned in bubble sheet data is uploaded
4774: into a course. When a user wants to grade, they select a
4775: sequence/folder of resources, a file of bubble sheet info, and pick
4776: one of the predefined configurations for what each scanline looks
4777: like.
4778:
4779: Next each scanline is checked for any errors of either 'missing
4780: bubbles' (it's an error because it may have been mis-scanned
4781: because too light bubbling), 'double bubble' (each bubble line should
4782: have no more that one letter picked), invalid or duplicated CODE,
4783: invalid student/employee ID
4784:
4785: If the CODE option is used that determines the randomization of the
4786: homework problems, either way the student/employee ID is looked up into a
4787: username:domain.
4788:
4789: During the validation phase the instructor can choose to skip scanlines.
4790:
4791: After the validation phase, there are now 3 bubble sheet files
4792:
4793: scantron_original_filename (unmodified original file)
4794: scantron_corrected_filename (file where the corrected information has replaced the original information)
4795: scantron_skipped_filename (contains the exact text of scanlines that where skipped)
4796:
4797: Also there is a separate hash nohist_scantrondata that contains extra
4798: correction information that isn't representable in the bubble sheet
4799: file (see &scantron_getfile() for more information)
4800:
4801: After all scanlines are either valid, marked as valid or skipped, then
4802: foreach line foreach problem in the picked sequence, an ssi request is
4803: made that simulates a user submitting their selected letter(s) against
4804: the homework problem.
4805:
4806: =over 4
4807:
4808:
4809:
4810: =item defaultFormData
4811:
4812: Returns html hidden inputs used to hold context/default values.
4813:
4814: Arguments:
4815: $symb - $symb of the current resource
4816:
4817: =cut
4818:
4819: sub defaultFormData {
4820: my ($symb)=@_;
4821: return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
4822: }
4823:
4824:
4825: =pod
4826:
4827: =item getSequenceDropDown
4828:
4829: Return html dropdown of possible sequences to grade
4830:
4831: Arguments:
4832: $symb - $symb of the current resource
4833: $map_error - ref to scalar which will container error if
4834: $navmap object is unavailable in &getSymbMap().
4835:
4836: =cut
4837:
4838: sub getSequenceDropDown {
4839: my ($symb,$map_error)=@_;
4840: my $result='<select name="selectpage">'."\n";
4841: my ($titles,$symbx) = &getSymbMap($map_error);
4842: if (ref($map_error)) {
4843: return if ($$map_error);
4844: }
4845: my ($curpage)=&Apache::lonnet::decode_symb($symb);
4846: my $ctr=0;
4847: foreach (@$titles) {
4848: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4849: $result.='<option value="'.$$symbx{$_}.'" '.
4850: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
4851: '>'.$showtitle.'</option>'."\n";
4852: $ctr++;
4853: }
4854: $result.= '</select>';
4855: return $result;
4856: }
4857:
4858: my %bubble_lines_per_response; # no. bubble lines for each response.
4859: # key is zero-based index - 0, 1, 2 ...
4860:
4861: my %first_bubble_line; # First bubble line no. for each bubble.
4862:
4863: my %subdivided_bubble_lines; # no. bubble lines for optionresponse,
4864: # matchresponse or rankresponse, where
4865: # an individual response can have multiple
4866: # lines
4867:
4868: my %responsetype_per_response; # responsetype for each response
4869:
4870: # Save and restore the bubble lines array to the form env.
4871:
4872:
4873: sub save_bubble_lines {
4874: foreach my $line (keys(%bubble_lines_per_response)) {
4875: $env{"form.scantron.bubblelines.$line"} = $bubble_lines_per_response{$line};
4876: $env{"form.scantron.first_bubble_line.$line"} =
4877: $first_bubble_line{$line};
4878: $env{"form.scantron.sub_bubblelines.$line"} =
4879: $subdivided_bubble_lines{$line};
4880: $env{"form.scantron.responsetype.$line"} =
4881: $responsetype_per_response{$line};
4882: }
4883: }
4884:
4885:
4886: sub restore_bubble_lines {
4887: my $line = 0;
4888: %bubble_lines_per_response = ();
4889: while ($env{"form.scantron.bubblelines.$line"}) {
4890: my $value = $env{"form.scantron.bubblelines.$line"};
4891: $bubble_lines_per_response{$line} = $value;
4892: $first_bubble_line{$line} =
4893: $env{"form.scantron.first_bubble_line.$line"};
4894: $subdivided_bubble_lines{$line} =
4895: $env{"form.scantron.sub_bubblelines.$line"};
4896: $responsetype_per_response{$line} =
4897: $env{"form.scantron.responsetype.$line"};
4898: $line++;
4899: }
4900: }
4901:
4902: # Given the parsed scanline, get the response for
4903: # 'answer' number n:
4904:
4905: sub get_response_bubbles {
4906: my ($parsed_line, $response) = @_;
4907:
4908: my $bubble_line = $first_bubble_line{$response-1} +1;
4909: my $bubble_lines= $bubble_lines_per_response{$response-1};
4910:
4911: my $selected = "";
4912:
4913: for (my $bline = 0; $bline < $bubble_lines; $bline++) {
4914: $selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
4915: $bubble_line++;
4916: }
4917: return $selected;
4918: }
4919:
4920: =pod
4921:
4922: =item scantron_filenames
4923:
4924: Returns a list of the scantron files in the current course
4925:
4926: =cut
4927:
4928: sub scantron_filenames {
4929: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
4930: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
4931: my $getpropath = 1;
4932: my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
4933: $getpropath);
4934: my @possiblenames;
4935: foreach my $filename (sort(@files)) {
4936: ($filename)=split(/&/,$filename);
4937: if ($filename!~/^scantron_orig_/) { next ; }
4938: $filename=~s/^scantron_orig_//;
4939: push(@possiblenames,$filename);
4940: }
4941: return @possiblenames;
4942: }
4943:
4944: =pod
4945:
4946: =item scantron_uploads
4947:
4948: Returns html drop-down list of scantron files in current course.
4949:
4950: Arguments:
4951: $file2grade - filename to set as selected in the dropdown
4952:
4953: =cut
4954:
4955: sub scantron_uploads {
4956: my ($file2grade) = @_;
4957: my $result= '<select name="scantron_selectfile">';
4958: $result.="<option></option>";
4959: foreach my $filename (sort(&scantron_filenames())) {
4960: $result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
4961: }
4962: $result.="</select>";
4963: return $result;
4964: }
4965:
4966: =pod
4967:
4968: =item scantron_scantab
4969:
4970: Returns html drop down of the scantron formats in the scantronformat.tab
4971: file.
4972:
4973: =cut
4974:
4975: sub scantron_scantab {
4976: my $result='<select name="scantron_format">'."\n";
4977: $result.='<option></option>'."\n";
4978: my @lines = &get_scantronformat_file();
4979: if (@lines > 0) {
4980: foreach my $line (@lines) {
4981: next if (($line =~ /^\#/) || ($line eq ''));
4982: my ($name,$descrip)=split(/:/,$line);
4983: $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
4984: }
4985: }
4986: $result.='</select>'."\n";
4987: return $result;
4988: }
4989:
4990: =pod
4991:
4992: =item get_scantronformat_file
4993:
4994: Returns an array containing lines from the scantron format file for
4995: the domain of the course.
4996:
4997: If a url for a custom.tab file is listed in domain's configuration.db,
4998: lines are from this file.
4999:
5000: Otherwise, if a default.tab has been published in RES space by the
5001: domainconfig user, lines are from this file.
5002:
5003: Otherwise, fall back to getting lines from the legacy file on the
5004: local server: /home/httpd/lonTabs/default_scantronformat.tab
5005:
5006: =cut
5007:
5008: sub get_scantronformat_file {
5009: my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
5010: my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
5011: my $gottab = 0;
5012: my @lines;
5013: if (ref($domconfig{'scantron'}) eq 'HASH') {
5014: if ($domconfig{'scantron'}{'scantronformat'} ne '') {
5015: my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
5016: if ($formatfile ne '-1') {
5017: @lines = split("\n",$formatfile,-1);
5018: $gottab = 1;
5019: }
5020: }
5021: }
5022: if (!$gottab) {
5023: my $confname = $cdom.'-domainconfig';
5024: my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
5025: my $formatfile = &Apache::lonnet::getfile($default);
5026: if ($formatfile ne '-1') {
5027: @lines = split("\n",$formatfile,-1);
5028: $gottab = 1;
5029: }
5030: }
5031: if (!$gottab) {
5032: my @domains = &Apache::lonnet::current_machine_domains();
5033: if (grep(/^\Q$cdom\E$/,@domains)) {
5034: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
5035: @lines = <$fh>;
5036: close($fh);
5037: } else {
5038: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
5039: @lines = <$fh>;
5040: close($fh);
5041: }
5042: }
5043: return @lines;
5044: }
5045:
5046: =pod
5047:
5048: =item scantron_CODElist
5049:
5050: Returns html drop down of the saved CODE lists from current course,
5051: generated from earlier printings.
5052:
5053: =cut
5054:
5055: sub scantron_CODElist {
5056: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5057: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5058: my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
5059: my $namechoice='<option></option>';
5060: foreach my $name (sort {uc($a) cmp uc($b)} @names) {
5061: if ($name =~ /^error: 2 /) { next; }
5062: if ($name =~ /^type\0/) { next; }
5063: $namechoice.='<option value="'.$name.'">'.$name.'</option>';
5064: }
5065: $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
5066: return $namechoice;
5067: }
5068:
5069: =pod
5070:
5071: =item scantron_CODEunique
5072:
5073: Returns the html for "Each CODE to be used once" radio.
5074:
5075: =cut
5076:
5077: sub scantron_CODEunique {
5078: my $result='<span class="LC_nobreak">
5079: <label><input type="radio" name="scantron_CODEunique"
5080: value="yes" checked="checked" />'.&mt('Yes').' </label>
5081: </span>
5082: <span class="LC_nobreak">
5083: <label><input type="radio" name="scantron_CODEunique"
5084: value="no" />'.&mt('No').' </label>
5085: </span>';
5086: return $result;
5087: }
5088:
5089: =pod
5090:
5091: =item scantron_selectphase
5092:
5093: Generates the initial screen to start the bubble sheet process.
5094: Allows for - starting a grading run.
5095: - downloading existing scan data (original, corrected
5096: or skipped info)
5097:
5098: - uploading new scan data
5099:
5100: Arguments:
5101: $r - The Apache request object
5102: $file2grade - name of the file that contain the scanned data to score
5103:
5104: =cut
5105:
5106: sub scantron_selectphase {
5107: my ($r,$file2grade,$symb) = @_;
5108: if (!$symb) {return '';}
5109: my $map_error;
5110: my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
5111: if ($map_error) {
5112: $r->print('<br />'.&navmap_errormsg().'<br />');
5113: return;
5114: }
5115: my $default_form_data=&defaultFormData($symb);
5116: my $file_selector=&scantron_uploads($file2grade);
5117: my $format_selector=&scantron_scantab();
5118: my $CODE_selector=&scantron_CODElist();
5119: my $CODE_unique=&scantron_CODEunique();
5120: my $result;
5121:
5122: $ssi_error = 0;
5123:
5124: if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
5125: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
5126:
5127: # Chunk of form to prompt for a scantron file upload.
5128:
5129: $r->print('
5130: <br />
5131: '.&Apache::loncommon::start_data_table('LC_scantron_action').'
5132: '.&Apache::loncommon::start_data_table_header_row().'
5133: <th>
5134: '.&mt('Specify a bubblesheet data file to upload.').'
5135: </th>
5136: '.&Apache::loncommon::end_data_table_header_row().'
5137: '.&Apache::loncommon::start_data_table_row().'
5138: <td>
5139: ');
5140: my $default_form_data=&defaultFormData($symb);
5141: my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
5142: my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
5143: $r->print(&Apache::lonhtmlcommon::scripttag('
5144: function checkUpload(formname) {
5145: if (formname.upfile.value == "") {
5146: alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
5147: return false;
5148: }
5149: formname.submit();
5150: }'));
5151: $r->print('
5152: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
5153: '.$default_form_data.'
5154: <input name="courseid" type="hidden" value="'.$cnum.'" />
5155: <input name="domainid" type="hidden" value="'.$cdom.'" />
5156: <input name="command" value="scantronupload_save" type="hidden" />
5157: '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
5158: <br />
5159: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
5160: </form>
5161: ');
5162:
5163: $r->print('
5164: </td>
5165: '.&Apache::loncommon::end_data_table_row().'
5166: '.&Apache::loncommon::end_data_table().'
5167: ');
5168: }
5169:
5170: # Chunk of form to prompt for a file to grade and how:
5171:
5172: $result.= '
5173: <br />
5174: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
5175: <input type="hidden" name="command" value="scantron_warning" />
5176: '.$default_form_data.'
5177: '.&Apache::loncommon::start_data_table('LC_scantron_action').'
5178: '.&Apache::loncommon::start_data_table_header_row().'
5179: <th colspan="2">
5180: '.&mt('Specify file and which Folder/Sequence to grade').'
5181: </th>
5182: '.&Apache::loncommon::end_data_table_header_row().'
5183: '.&Apache::loncommon::start_data_table_row().'
5184: <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
5185: '.&Apache::loncommon::end_data_table_row().'
5186: '.&Apache::loncommon::start_data_table_row().'
5187: <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
5188: '.&Apache::loncommon::end_data_table_row().'
5189: '.&Apache::loncommon::start_data_table_row().'
5190: <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
5191: '.&Apache::loncommon::end_data_table_row().'
5192: '.&Apache::loncommon::start_data_table_row().'
5193: <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
5194: '.&Apache::loncommon::end_data_table_row().'
5195: '.&Apache::loncommon::start_data_table_row().'
5196: <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
5197: '.&Apache::loncommon::end_data_table_row().'
5198: '.&Apache::loncommon::start_data_table_row().'
5199: <td> '.&mt('Options:').' </td>
5200: <td>
5201: <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
5202: <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
5203: <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
5204: </td>
5205: '.&Apache::loncommon::end_data_table_row().'
5206: '.&Apache::loncommon::start_data_table_row().'
5207: <td colspan="2">
5208: <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
5209: </td>
5210: '.&Apache::loncommon::end_data_table_row().'
5211: '.&Apache::loncommon::end_data_table().'
5212: </form>
5213: ';
5214:
5215: $r->print($result);
5216:
5217:
5218:
5219: # Chunk of the form that prompts to view a scoring office file,
5220: # corrected file, skipped records in a file.
5221:
5222: $r->print('
5223: <br />
5224: <form action="/adm/grades" name="scantron_download">
5225: '.$default_form_data.'
5226: <input type="hidden" name="command" value="scantron_download" />
5227: '.&Apache::loncommon::start_data_table('LC_scantron_action').'
5228: '.&Apache::loncommon::start_data_table_header_row().'
5229: <th>
5230: '.&mt('Download a scoring office file').'
5231: </th>
5232: '.&Apache::loncommon::end_data_table_header_row().'
5233: '.&Apache::loncommon::start_data_table_row().'
5234: <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).'
5235: <br />
5236: <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
5237: '.&Apache::loncommon::end_data_table_row().'
5238: '.&Apache::loncommon::end_data_table().'
5239: </form>
5240: <br />
5241: ');
5242:
5243: &Apache::lonpickcode::code_list($r,2);
5244:
5245: $r->print('<br /><form method="post" name="checkscantron">'.
5246: $default_form_data."\n".
5247: &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
5248: &Apache::loncommon::start_data_table_header_row()."\n".
5249: '<th colspan="2">
5250: '.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
5251: '</th>'."\n".
5252: &Apache::loncommon::end_data_table_header_row()."\n".
5253: &Apache::loncommon::start_data_table_row()."\n".
5254: '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
5255: '<td> '.$sequence_selector.' </td>'.
5256: &Apache::loncommon::end_data_table_row()."\n".
5257: &Apache::loncommon::start_data_table_row()."\n".
5258: '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
5259: '<td> '.$file_selector.' </td>'."\n".
5260: &Apache::loncommon::end_data_table_row()."\n".
5261: &Apache::loncommon::start_data_table_row()."\n".
5262: '<td> '.&mt('Format of data file:').' </td>'."\n".
5263: '<td> '.$format_selector.' </td>'."\n".
5264: &Apache::loncommon::end_data_table_row()."\n".
5265: &Apache::loncommon::start_data_table_row()."\n".
5266: '<td> '.&mt('Options').' </td>'."\n".
5267: '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
5268: &Apache::loncommon::end_data_table_row()."\n".
5269: &Apache::loncommon::start_data_table_row()."\n".
5270: '<td colspan="2">'."\n".
5271: '<input type="hidden" name="command" value="checksubmissions" />'."\n".
5272: '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
5273: '</td>'."\n".
5274: &Apache::loncommon::end_data_table_row()."\n".
5275: &Apache::loncommon::end_data_table()."\n".
5276: '</form><br />');
5277: return;
5278: }
5279:
5280: =pod
5281:
5282: =item get_scantron_config
5283:
5284: Parse and return the scantron configuration line selected as a
5285: hash of configuration file fields.
5286:
5287: Arguments:
5288: which - the name of the configuration to parse from the file.
5289:
5290:
5291: Returns:
5292: If the named configuration is not in the file, an empty
5293: hash is returned.
5294: a hash with the fields
5295: name - internal name for the this configuration setup
5296: description - text to display to operator that describes this config
5297: CODElocation - if 0 or the string 'none'
5298: - no CODE exists for this config
5299: if -1 || the string 'letter'
5300: - a CODE exists for this config and is
5301: a string of letters
5302: Unsupported value (but planned for future support)
5303: if a positive integer
5304: - The CODE exists as the first n items from
5305: the question section of the form
5306: if the string 'number'
5307: - The CODE exists for this config and is
5308: a string of numbers
5309: CODEstart - (only matter if a CODE exists) column in the line where
5310: the CODE starts
5311: CODElength - length of the CODE
5312: IDstart - column where the student/employee ID starts
5313: IDlength - length of the student/employee ID info
5314: Qstart - column where the information from the bubbled
5315: 'questions' start
5316: Qlength - number of columns comprising a single bubble line from
5317: the sheet. (usually either 1 or 10)
5318: Qon - either a single character representing the character used
5319: to signal a bubble was chosen in the positional setup, or
5320: the string 'letter' if the letter of the chosen bubble is
5321: in the final, or 'number' if a number representing the
5322: chosen bubble is in the file (1->A 0->J)
5323: Qoff - the character used to represent that a bubble was
5324: left blank
5325: PaperID - if the scanning process generates a unique number for each
5326: sheet scanned the column that this ID number starts in
5327: PaperIDlength - number of columns that comprise the unique ID number
5328: for the sheet of paper
5329: FirstName - column that the first name starts in
5330: FirstNameLength - number of columns that the first name spans
5331:
5332: LastName - column that the last name starts in
5333: LastNameLength - number of columns that the last name spans
5334:
5335: =cut
5336:
5337: sub get_scantron_config {
5338: my ($which) = @_;
5339: my @lines = &get_scantronformat_file();
5340: my %config;
5341: #FIXME probably should move to XML it has already gotten a bit much now
5342: foreach my $line (@lines) {
5343: my ($name,$descrip)=split(/:/,$line);
5344: if ($name ne $which ) { next; }
5345: chomp($line);
5346: my @config=split(/:/,$line);
5347: $config{'name'}=$config[0];
5348: $config{'description'}=$config[1];
5349: $config{'CODElocation'}=$config[2];
5350: $config{'CODEstart'}=$config[3];
5351: $config{'CODElength'}=$config[4];
5352: $config{'IDstart'}=$config[5];
5353: $config{'IDlength'}=$config[6];
5354: $config{'Qstart'}=$config[7];
5355: $config{'Qlength'}=$config[8];
5356: $config{'Qoff'}=$config[9];
5357: $config{'Qon'}=$config[10];
5358: $config{'PaperID'}=$config[11];
5359: $config{'PaperIDlength'}=$config[12];
5360: $config{'FirstName'}=$config[13];
5361: $config{'FirstNamelength'}=$config[14];
5362: $config{'LastName'}=$config[15];
5363: $config{'LastNamelength'}=$config[16];
5364: last;
5365: }
5366: return %config;
5367: }
5368:
5369: =pod
5370:
5371: =item username_to_idmap
5372:
5373: creates a hash keyed by student/employee ID with values of the corresponding
5374: student username:domain.
5375:
5376: Arguments:
5377:
5378: $classlist - reference to the class list hash. This is a hash
5379: keyed by student name:domain whose elements are references
5380: to arrays containing various chunks of information
5381: about the student. (See loncoursedata for more info).
5382:
5383: Returns
5384: %idmap - the constructed hash
5385:
5386: =cut
5387:
5388: sub username_to_idmap {
5389: my ($classlist)= @_;
5390: my %idmap;
5391: foreach my $student (keys(%$classlist)) {
5392: $idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
5393: $student;
5394: }
5395: return %idmap;
5396: }
5397:
5398: =pod
5399:
5400: =item scantron_fixup_scanline
5401:
5402: Process a requested correction to a scanline.
5403:
5404: Arguments:
5405: $scantron_config - hash from &get_scantron_config()
5406: $scan_data - hash of correction information
5407: (see &scantron_getfile())
5408: $line - existing scanline
5409: $whichline - line number of the passed in scanline
5410: $field - type of change to process
5411: (either
5412: 'ID' -> correct the student/employee ID
5413: 'CODE' -> correct the CODE
5414: 'answer' -> fixup the submitted answers)
5415:
5416: $args - hash of additional info,
5417: - 'ID'
5418: 'newid' -> studentID to use in replacement
5419: of existing one
5420: - 'CODE'
5421: 'CODE_ignore_dup' - set to true if duplicates
5422: should be ignored.
5423: 'CODE' - is new code or 'use_unfound'
5424: if the existing unfound code should
5425: be used as is
5426: - 'answer'
5427: 'response' - new answer or 'none' if blank
5428: 'question' - the bubble line to change
5429: 'questionnum' - the question identifier,
5430: may include subquestion.
5431:
5432: Returns:
5433: $line - the modified scanline
5434:
5435: Side effects:
5436: $scan_data - may be updated
5437:
5438: =cut
5439:
5440:
5441: sub scantron_fixup_scanline {
5442: my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
5443: if ($field eq 'ID') {
5444: if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
5445: return ($line,1,'New value too large');
5446: }
5447: if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
5448: $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
5449: $args->{'newid'});
5450: }
5451: substr($line,$$scantron_config{'IDstart'}-1,
5452: $$scantron_config{'IDlength'})=$args->{'newid'};
5453: if ($args->{'newid'}=~/^\s*$/) {
5454: &scan_data($scan_data,"$whichline.user",
5455: $args->{'username'}.':'.$args->{'domain'});
5456: }
5457: } elsif ($field eq 'CODE') {
5458: if ($args->{'CODE_ignore_dup'}) {
5459: &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
5460: }
5461: &scan_data($scan_data,"$whichline.useCODE",'1');
5462: if ($args->{'CODE'} ne 'use_unfound') {
5463: if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
5464: return ($line,1,'New CODE value too large');
5465: }
5466: if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
5467: $args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
5468: }
5469: substr($line,$$scantron_config{'CODEstart'}-1,
5470: $$scantron_config{'CODElength'})=$args->{'CODE'};
5471: }
5472: } elsif ($field eq 'answer') {
5473: my $length=$scantron_config->{'Qlength'};
5474: my $off=$scantron_config->{'Qoff'};
5475: my $on=$scantron_config->{'Qon'};
5476: my $answer=${off}x$length;
5477: if ($args->{'response'} eq 'none') {
5478: &scan_data($scan_data,
5479: "$whichline.no_bubble.".$args->{'questionnum'},'1');
5480: } else {
5481: if ($on eq 'letter') {
5482: my @alphabet=('A'..'Z');
5483: $answer=$alphabet[$args->{'response'}];
5484: } elsif ($on eq 'number') {
5485: $answer=$args->{'response'}+1;
5486: if ($answer == 10) { $answer = '0'; }
5487: } else {
5488: substr($answer,$args->{'response'},1)=$on;
5489: }
5490: &scan_data($scan_data,
5491: "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
5492: }
5493: my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
5494: substr($line,$where-1,$length)=$answer;
5495: }
5496: return $line;
5497: }
5498:
5499: =pod
5500:
5501: =item scan_data
5502:
5503: Edit or look up an item in the scan_data hash.
5504:
5505: Arguments:
5506: $scan_data - The hash (see scantron_getfile)
5507: $key - shorthand of the key to edit (actual key is
5508: scantronfilename_key).
5509: $data - New value of the hash entry.
5510: $delete - If true, the entry is removed from the hash.
5511:
5512: Returns:
5513: The new value of the hash table field (undefined if deleted).
5514:
5515: =cut
5516:
5517:
5518: sub scan_data {
5519: my ($scan_data,$key,$value,$delete)=@_;
5520: my $filename=$env{'form.scantron_selectfile'};
5521: if (defined($value)) {
5522: $scan_data->{$filename.'_'.$key} = $value;
5523: }
5524: if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
5525: return $scan_data->{$filename.'_'.$key};
5526: }
5527:
5528: # ----- These first few routines are general use routines.----
5529:
5530: # Return the number of occurences of a pattern in a string.
5531:
5532: sub occurence_count {
5533: my ($string, $pattern) = @_;
5534:
5535: my @matches = ($string =~ /$pattern/g);
5536:
5537: return scalar(@matches);
5538: }
5539:
5540:
5541: # Take a string known to have digits and convert all the
5542: # digits into letters in the range J,A..I.
5543:
5544: sub digits_to_letters {
5545: my ($input) = @_;
5546:
5547: my @alphabet = ('J', 'A'..'I');
5548:
5549: my @input = split(//, $input);
5550: my $output ='';
5551: for (my $i = 0; $i < scalar(@input); $i++) {
5552: if ($input[$i] =~ /\d/) {
5553: $output .= $alphabet[$input[$i]];
5554: } else {
5555: $output .= $input[$i];
5556: }
5557: }
5558: return $output;
5559: }
5560:
5561: =pod
5562:
5563: =item scantron_parse_scanline
5564:
5565: Decodes a scanline from the selected scantron file
5566:
5567: Arguments:
5568: line - The text of the scantron file line to process
5569: whichline - Line number
5570: scantron_config - Hash describing the format of the scantron lines.
5571: scan_data - Hash of extra information about the scanline
5572: (see scantron_getfile for more information)
5573: just_header - True if should not process question answers but only
5574: the stuff to the left of the answers.
5575: Returns:
5576: Hash containing the result of parsing the scanline
5577:
5578: Keys are all proceeded by the string 'scantron.'
5579:
5580: CODE - the CODE in use for this scanline
5581: useCODE - 1 if the CODE is invalid but it usage has been forced
5582: by the operator
5583: CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
5584: CODEs were selected, but the usage has been
5585: forced by the operator
5586: ID - student/employee ID
5587: PaperID - if used, the ID number printed on the sheet when the
5588: paper was scanned
5589: FirstName - first name from the sheet
5590: LastName - last name from the sheet
5591:
5592: if just_header was not true these key may also exist
5593:
5594: missingerror - a list of bubble ranges that are considered to be answers
5595: to a single question that don't have any bubbles filled in.
5596: Of the form questionnumber:firstbubblenumber:count.
5597: doubleerror - a list of bubble ranges that are considered to be answers
5598: to a single question that have more than one bubble filled in.
5599: Of the form questionnumber::firstbubblenumber:count
5600:
5601: In the above, count is the number of bubble responses in the
5602: input line needed to represent the possible answers to the question.
5603: e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
5604: per line would have count = 2.
5605:
5606: maxquest - the number of the last bubble line that was parsed
5607:
5608: (<number> starts at 1)
5609: <number>.answer - zero or more letters representing the selected
5610: letters from the scanline for the bubble line
5611: <number>.
5612: if blank there was either no bubble or there where
5613: multiple bubbles, (consult the keys missingerror and
5614: doubleerror if this is an error condition)
5615:
5616: =cut
5617:
5618: sub scantron_parse_scanline {
5619: my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
5620:
5621: my %record;
5622: my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
5623: my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos); # Answers
5624: my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # earlier stuff
5625: if (!($$scantron_config{'CODElocation'} eq 0 ||
5626: $$scantron_config{'CODElocation'} eq 'none')) {
5627: if ($$scantron_config{'CODElocation'} < 0 ||
5628: $$scantron_config{'CODElocation'} eq 'letter' ||
5629: $$scantron_config{'CODElocation'} eq 'number') {
5630: $record{'scantron.CODE'}=substr($data,
5631: $$scantron_config{'CODEstart'}-1,
5632: $$scantron_config{'CODElength'});
5633: if (&scan_data($scan_data,"$whichline.useCODE")) {
5634: $record{'scantron.useCODE'}=1;
5635: }
5636: if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
5637: $record{'scantron.CODE_ignore_dup'}=1;
5638: }
5639: } else {
5640: #FIXME interpret first N questions
5641: }
5642: }
5643: $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
5644: $$scantron_config{'IDlength'});
5645: $record{'scantron.PaperID'}=
5646: substr($data,$$scantron_config{'PaperID'}-1,
5647: $$scantron_config{'PaperIDlength'});
5648: $record{'scantron.FirstName'}=
5649: substr($data,$$scantron_config{'FirstName'}-1,
5650: $$scantron_config{'FirstNamelength'});
5651: $record{'scantron.LastName'}=
5652: substr($data,$$scantron_config{'LastName'}-1,
5653: $$scantron_config{'LastNamelength'});
5654: if ($just_header) { return \%record; }
5655:
5656: my @alphabet=('A'..'Z');
5657: my $questnum=0;
5658: my $ansnum =1; # Multiple 'answer lines'/question.
5659:
5660: chomp($questions); # Get rid of any trailing \n.
5661: $questions =~ s/\r$//; # Get rid of trailing \r too (MAC or Win uploads).
5662: while (length($questions)) {
5663: my $answers_needed = $bubble_lines_per_response{$questnum};
5664: my $answer_length = ($$scantron_config{'Qlength'} * $answers_needed)
5665: || 1;
5666: $questnum++;
5667: my $quest_id = $questnum;
5668: my $currentquest = substr($questions,0,$answer_length);
5669: $questions = substr($questions,$answer_length);
5670: if (length($currentquest) < $answer_length) { next; }
5671:
5672: if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
5673: my $subquestnum = 1;
5674: my $subquestions = $currentquest;
5675: my @subanswers_needed =
5676: split(/,/,$subdivided_bubble_lines{$questnum-1});
5677: foreach my $subans (@subanswers_needed) {
5678: my $subans_length =
5679: ($$scantron_config{'Qlength'} * $subans) || 1;
5680: my $currsubquest = substr($subquestions,0,$subans_length);
5681: $subquestions = substr($subquestions,$subans_length);
5682: $quest_id = "$questnum.$subquestnum";
5683: if (($$scantron_config{'Qon'} eq 'letter') ||
5684: ($$scantron_config{'Qon'} eq 'number')) {
5685: $ansnum = &scantron_validator_lettnum($ansnum,
5686: $questnum,$quest_id,$subans,$currsubquest,$whichline,
5687: \@alphabet,\%record,$scantron_config,$scan_data);
5688: } else {
5689: $ansnum = &scantron_validator_positional($ansnum,
5690: $questnum,$quest_id,$subans,$currsubquest,$whichline, \@alphabet,\%record,$scantron_config,$scan_data);
5691: }
5692: $subquestnum ++;
5693: }
5694: } else {
5695: if (($$scantron_config{'Qon'} eq 'letter') ||
5696: ($$scantron_config{'Qon'} eq 'number')) {
5697: $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
5698: $quest_id,$answers_needed,$currentquest,$whichline,
5699: \@alphabet,\%record,$scantron_config,$scan_data);
5700: } else {
5701: $ansnum = &scantron_validator_positional($ansnum,$questnum,
5702: $quest_id,$answers_needed,$currentquest,$whichline,
5703: \@alphabet,\%record,$scantron_config,$scan_data);
5704: }
5705: }
5706: }
5707: $record{'scantron.maxquest'}=$questnum;
5708: return \%record;
5709: }
5710:
5711: sub scantron_validator_lettnum {
5712: my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
5713: $alphabet,$record,$scantron_config,$scan_data) = @_;
5714:
5715: # Qon 'letter' implies for each slot in currquest we have:
5716: # ? or * for doubles, a letter in A-Z for a bubble, and
5717: # about anything else (esp. a value of Qoff) for missing
5718: # bubbles.
5719: #
5720: # Qon 'number' implies each slot gives a digit that indexes the
5721: # bubbles filled, or Qoff, or a non-number for unbubbled lines,
5722: # and * or ? for double bubbles on a single line.
5723: #
5724:
5725: my $matchon;
5726: if ($$scantron_config{'Qon'} eq 'letter') {
5727: $matchon = '[A-Z]';
5728: } elsif ($$scantron_config{'Qon'} eq 'number') {
5729: $matchon = '\d';
5730: }
5731: my $occurrences = 0;
5732: if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
5733: ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
5734: ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
5735: ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
5736: ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
5737: ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
5738: my @singlelines = split('',$currquest);
5739: foreach my $entry (@singlelines) {
5740: $occurrences = &occurence_count($entry,$matchon);
5741: if ($occurrences > 1) {
5742: last;
5743: }
5744: }
5745: } else {
5746: $occurrences = &occurence_count($currquest,$matchon);
5747: }
5748: if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
5749: push(@{$record->{'scantron.doubleerror'}},$quest_id);
5750: for (my $ans=0; $ans<$answers_needed; $ans++) {
5751: my $bubble = substr($currquest,$ans,1);
5752: if ($bubble =~ /$matchon/ ) {
5753: if ($$scantron_config{'Qon'} eq 'number') {
5754: if ($bubble == 0) {
5755: $bubble = 10;
5756: }
5757: $record->{"scantron.$ansnum.answer"} =
5758: $alphabet->[$bubble-1];
5759: } else {
5760: $record->{"scantron.$ansnum.answer"} = $bubble;
5761: }
5762: } else {
5763: $record->{"scantron.$ansnum.answer"}='';
5764: }
5765: $ansnum++;
5766: }
5767: } elsif (!defined($currquest)
5768: || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
5769: || (&occurence_count($currquest,$matchon) == 0)) {
5770: for (my $ans=0; $ans<$answers_needed; $ans++ ) {
5771: $record->{"scantron.$ansnum.answer"}='';
5772: $ansnum++;
5773: }
5774: if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
5775: push(@{$record->{'scantron.missingerror'}},$quest_id);
5776: }
5777: } else {
5778: if ($$scantron_config{'Qon'} eq 'number') {
5779: $currquest = &digits_to_letters($currquest);
5780: }
5781: for (my $ans=0; $ans<$answers_needed; $ans++) {
5782: my $bubble = substr($currquest,$ans,1);
5783: $record->{"scantron.$ansnum.answer"} = $bubble;
5784: $ansnum++;
5785: }
5786: }
5787: return $ansnum;
5788: }
5789:
5790: sub scantron_validator_positional {
5791: my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
5792: $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
5793:
5794: # Otherwise there's a positional notation;
5795: # each bubble line requires Qlength items, and there are filled in
5796: # bubbles for each case where there 'Qon' characters.
5797: #
5798:
5799: my @array=split($$scantron_config{'Qon'},$currquest,-1);
5800:
5801: # If the split only gives us one element.. the full length of the
5802: # answer string, no bubbles are filled in:
5803:
5804: if ($answers_needed eq '') {
5805: return;
5806: }
5807:
5808: if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
5809: for (my $ans=0; $ans<$answers_needed; $ans++ ) {
5810: $record->{"scantron.$ansnum.answer"}='';
5811: $ansnum++;
5812: }
5813: if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
5814: push(@{$record->{"scantron.missingerror"}},$quest_id);
5815: }
5816: } elsif (scalar(@array) == 2) {
5817: my $location = length($array[0]);
5818: my $line_num = int($location / $$scantron_config{'Qlength'});
5819: my $bubble = $alphabet->[$location % $$scantron_config{'Qlength'}];
5820: for (my $ans=0; $ans<$answers_needed; $ans++) {
5821: if ($ans eq $line_num) {
5822: $record->{"scantron.$ansnum.answer"} = $bubble;
5823: } else {
5824: $record->{"scantron.$ansnum.answer"} = ' ';
5825: }
5826: $ansnum++;
5827: }
5828: } else {
5829: # If there's more than one instance of a bubble character
5830: # That's a double bubble; with positional notation we can
5831: # record all the bubbles filled in as well as the
5832: # fact this response consists of multiple bubbles.
5833: #
5834: if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
5835: ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
5836: ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
5837: ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
5838: ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
5839: ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
5840: my $doubleerror = 0;
5841: while (($currquest >= $$scantron_config{'Qlength'}) &&
5842: (!$doubleerror)) {
5843: my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
5844: $currquest = substr($currquest,$$scantron_config{'Qlength'});
5845: my @currarray = split($$scantron_config{'Qon'},$currline,-1);
5846: if (length(@currarray) > 2) {
5847: $doubleerror = 1;
5848: }
5849: }
5850: if ($doubleerror) {
5851: push(@{$record->{'scantron.doubleerror'}},$quest_id);
5852: }
5853: } else {
5854: push(@{$record->{'scantron.doubleerror'}},$quest_id);
5855: }
5856: my $item = $ansnum;
5857: for (my $ans=0; $ans<$answers_needed; $ans++) {
5858: $record->{"scantron.$item.answer"} = '';
5859: $item ++;
5860: }
5861:
5862: my @ans=@array;
5863: my $i=0;
5864: my $increment = 0;
5865: while ($#ans) {
5866: $i+=length($ans[0]) + $increment;
5867: my $line = int($i/$$scantron_config{'Qlength'} + $ansnum);
5868: my $bubble = $i%$$scantron_config{'Qlength'};
5869: $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
5870: shift(@ans);
5871: $increment = 1;
5872: }
5873: $ansnum += $answers_needed;
5874: }
5875: return $ansnum;
5876: }
5877:
5878: =pod
5879:
5880: =item scantron_add_delay
5881:
5882: Adds an error message that occurred during the grading phase to a
5883: queue of messages to be shown after grading pass is complete
5884:
5885: Arguments:
5886: $delayqueue - arrary ref of hash ref of error messages
5887: $scanline - the scanline that caused the error
5888: $errormesage - the error message
5889: $errorcode - a numeric code for the error
5890:
5891: Side Effects:
5892: updates the $delayqueue to have a new hash ref of the error
5893:
5894: =cut
5895:
5896: sub scantron_add_delay {
5897: my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
5898: push(@$delayqueue,
5899: {'line' => $scanline, 'emsg' => $errormessage,
5900: 'ecode' => $errorcode }
5901: );
5902: }
5903:
5904: =pod
5905:
5906: =item scantron_find_student
5907:
5908: Finds the username for the current scanline
5909:
5910: Arguments:
5911: $scantron_record - hash result from scantron_parse_scanline
5912: $scan_data - hash of correction information
5913: (see &scantron_getfile() form more information)
5914: $idmap - hash from &username_to_idmap()
5915: $line - number of current scanline
5916:
5917: Returns:
5918: Either 'username:domain' or undef if unknown
5919:
5920: =cut
5921:
5922: sub scantron_find_student {
5923: my ($scantron_record,$scan_data,$idmap,$line)=@_;
5924: my $scanID=$$scantron_record{'scantron.ID'};
5925: if ($scanID =~ /^\s*$/) {
5926: return &scan_data($scan_data,"$line.user");
5927: }
5928: foreach my $id (keys(%$idmap)) {
5929: if (lc($id) eq lc($scanID)) {
5930: return $$idmap{$id};
5931: }
5932: }
5933: return undef;
5934: }
5935:
5936: =pod
5937:
5938: =item scantron_filter
5939:
5940: Filter sub for lonnavmaps, filters out hidden resources if ignore
5941: hidden resources was selected
5942:
5943: =cut
5944:
5945: sub scantron_filter {
5946: my ($curres)=@_;
5947:
5948: if (ref($curres) && $curres->is_problem()) {
5949: # if the user has asked to not have either hidden
5950: # or 'randomout' controlled resources to be graded
5951: # don't include them
5952: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
5953: && $curres->randomout) {
5954: return 0;
5955: }
5956: return 1;
5957: }
5958: return 0;
5959: }
5960:
5961: =pod
5962:
5963: =item scantron_process_corrections
5964:
5965: Gets correction information out of submitted form data and corrects
5966: the scanline
5967:
5968: =cut
5969:
5970: sub scantron_process_corrections {
5971: my ($r) = @_;
5972: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
5973: my ($scanlines,$scan_data)=&scantron_getfile();
5974: my $classlist=&Apache::loncoursedata::get_classlist();
5975: my $which=$env{'form.scantron_line'};
5976: my $line=&scantron_get_line($scanlines,$scan_data,$which);
5977: my ($skip,$err,$errmsg);
5978: if ($env{'form.scantron_skip_record'}) {
5979: $skip=1;
5980: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
5981: my $newstudent=$env{'form.scantron_username'}.':'.
5982: $env{'form.scantron_domain'};
5983: my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
5984: ($line,$err,$errmsg)=
5985: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
5986: 'ID',{'newid'=>$newid,
5987: 'username'=>$env{'form.scantron_username'},
5988: 'domain'=>$env{'form.scantron_domain'}});
5989: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
5990: my $resolution=$env{'form.scantron_CODE_resolution'};
5991: my $newCODE;
5992: my %args;
5993: if ($resolution eq 'use_unfound') {
5994: $newCODE='use_unfound';
5995: } elsif ($resolution eq 'use_found') {
5996: $newCODE=$env{'form.scantron_CODE_selectedvalue'};
5997: } elsif ($resolution eq 'use_typed') {
5998: $newCODE=$env{'form.scantron_CODE_newvalue'};
5999: } elsif ($resolution =~ /^use_closest_(\d+)/) {
6000: $newCODE=$env{"form.scantron_CODE_closest_$1"};
6001: }
6002: if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
6003: $args{'CODE_ignore_dup'}=1;
6004: }
6005: $args{'CODE'}=$newCODE;
6006: ($line,$err,$errmsg)=
6007: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
6008: 'CODE',\%args);
6009: } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
6010: foreach my $question (split(',',$env{'form.scantron_questions'})) {
6011: ($line,$err,$errmsg)=
6012: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
6013: $which,'answer',
6014: { 'question'=>$question,
6015: 'response'=>$env{"form.scantron_correct_Q_$question"},
6016: 'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
6017: if ($err) { last; }
6018: }
6019: }
6020: if ($err) {
6021: $r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
6022: } else {
6023: &scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
6024: &scantron_putfile($scanlines,$scan_data);
6025: }
6026: }
6027:
6028: =pod
6029:
6030: =item reset_skipping_status
6031:
6032: Forgets the current set of remember skipped scanlines (and thus
6033: reverts back to considering all lines in the
6034: scantron_skipped_<filename> file)
6035:
6036: =cut
6037:
6038: sub reset_skipping_status {
6039: my ($scanlines,$scan_data)=&scantron_getfile();
6040: &scan_data($scan_data,'remember_skipping',undef,1);
6041: &scantron_putfile(undef,$scan_data);
6042: }
6043:
6044: =pod
6045:
6046: =item start_skipping
6047:
6048: Marks a scanline to be skipped.
6049:
6050: =cut
6051:
6052: sub start_skipping {
6053: my ($scan_data,$i)=@_;
6054: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
6055: if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
6056: $remembered{$i}=2;
6057: } else {
6058: $remembered{$i}=1;
6059: }
6060: &scan_data($scan_data,'remember_skipping',join(':',%remembered));
6061: }
6062:
6063: =pod
6064:
6065: =item should_be_skipped
6066:
6067: Checks whether a scanline should be skipped.
6068:
6069: =cut
6070:
6071: sub should_be_skipped {
6072: my ($scanlines,$scan_data,$i)=@_;
6073: if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
6074: # not redoing old skips
6075: if ($scanlines->{'skipped'}[$i]) { return 1; }
6076: return 0;
6077: }
6078: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
6079:
6080: if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
6081: return 0;
6082: }
6083: return 1;
6084: }
6085:
6086: =pod
6087:
6088: =item remember_current_skipped
6089:
6090: Discovers what scanlines are in the scantron_skipped_<filename>
6091: file and remembers them into scan_data for later use.
6092:
6093: =cut
6094:
6095: sub remember_current_skipped {
6096: my ($scanlines,$scan_data)=&scantron_getfile();
6097: my %to_remember;
6098: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6099: if ($scanlines->{'skipped'}[$i]) {
6100: $to_remember{$i}=1;
6101: }
6102: }
6103:
6104: &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
6105: &scantron_putfile(undef,$scan_data);
6106: }
6107:
6108: =pod
6109:
6110: =item check_for_error
6111:
6112: Checks if there was an error when attempting to remove a specific
6113: scantron_.. bubble sheet data file. Prints out an error if
6114: something went wrong.
6115:
6116: =cut
6117:
6118: sub check_for_error {
6119: my ($r,$result)=@_;
6120: if ($result ne 'ok' && $result ne 'not_found' ) {
6121: $r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
6122: }
6123: }
6124:
6125: =pod
6126:
6127: =item scantron_warning_screen
6128:
6129: Interstitial screen to make sure the operator has selected the
6130: correct options before we start the validation phase.
6131:
6132: =cut
6133:
6134: sub scantron_warning_screen {
6135: my ($button_text)=@_;
6136: my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
6137: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6138: my $CODElist;
6139: if ($scantron_config{'CODElocation'} &&
6140: $scantron_config{'CODEstart'} &&
6141: $scantron_config{'CODElength'}) {
6142: $CODElist=$env{'form.scantron_CODElist'};
6143: if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
6144: $CODElist=
6145: '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
6146: $env{'form.scantron_CODElist'}.'</tt></td></tr>';
6147: }
6148: return ('
6149: <p>
6150: <span class="LC_warning">
6151: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
6152: </p>
6153: <table>
6154: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
6155: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
6156: '.$CODElist.'
6157: </table>
6158: <br />
6159: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
6160: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
6161:
6162: <br />
6163: ');
6164: }
6165:
6166: =pod
6167:
6168: =item scantron_do_warning
6169:
6170: Check if the operator has picked something for all required
6171: fields. Error out if something is missing.
6172:
6173: =cut
6174:
6175: sub scantron_do_warning {
6176: my ($r,$symb)=@_;
6177: if (!$symb) {return '';}
6178: my $default_form_data=&defaultFormData($symb);
6179: $r->print(&scantron_form_start().$default_form_data);
6180: if ( $env{'form.selectpage'} eq '' ||
6181: $env{'form.scantron_selectfile'} eq '' ||
6182: $env{'form.scantron_format'} eq '' ) {
6183: $r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
6184: if ( $env{'form.selectpage'} eq '') {
6185: $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
6186: }
6187: if ( $env{'form.scantron_selectfile'} eq '') {
6188: $r->print('<p><span class="LC_error">'.&mt('You have not selected a file that contains the student\'s response data.').'</span></p>');
6189: }
6190: if ( $env{'form.scantron_format'} eq '') {
6191: $r->print('<p><span class="LC_error">'.&mt('You have not selected a the format of the student\'s response data.').'</span></p>');
6192: }
6193: } else {
6194: my $warning=&scantron_warning_screen('Grading: Validate Records');
6195: $r->print('
6196: '.$warning.'
6197: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
6198: <input type="hidden" name="command" value="scantron_validate" />
6199: ');
6200: }
6201: $r->print("</form><br />");
6202: return '';
6203: }
6204:
6205: =pod
6206:
6207: =item scantron_form_start
6208:
6209: html hidden input for remembering all selected grading options
6210:
6211: =cut
6212:
6213: sub scantron_form_start {
6214: my ($max_bubble)=@_;
6215: my $result= <<SCANTRONFORM;
6216: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
6217: <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
6218: <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
6219: <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
6220: <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
6221: <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
6222: <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
6223: <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
6224: <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
6225: <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
6226: SCANTRONFORM
6227:
6228: my $line = 0;
6229: while (defined($env{"form.scantron.bubblelines.$line"})) {
6230: my $chunk =
6231: '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
6232: $chunk .=
6233: '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
6234: $chunk .=
6235: '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
6236: $chunk .=
6237: '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
6238: $result .= $chunk;
6239: $line++;
6240: }
6241: return $result;
6242: }
6243:
6244: =pod
6245:
6246: =item scantron_validate_file
6247:
6248: Dispatch routine for doing validation of a bubble sheet data file.
6249:
6250: Also processes any necessary information resets that need to
6251: occur before validation begins (ignore previous corrections,
6252: restarting the skipped records processing)
6253:
6254: =cut
6255:
6256: sub scantron_validate_file {
6257: my ($r,$symb) = @_;
6258: if (!$symb) {return '';}
6259: my $default_form_data=&defaultFormData($symb);
6260:
6261: # do the detection of only doing skipped records first befroe we delete
6262: # them when doing the corrections reset
6263: if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
6264: &reset_skipping_status();
6265: }
6266: if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
6267: &remember_current_skipped();
6268: $env{'form.scantron_options_redo'}='redo_skipped_ready';
6269: }
6270:
6271: if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
6272: &check_for_error($r,&scantron_remove_file('corrected'));
6273: &check_for_error($r,&scantron_remove_file('skipped'));
6274: &check_for_error($r,&scantron_remove_scan_data());
6275: $env{'form.scantron_options_ignore'}='done';
6276: }
6277:
6278: if ($env{'form.scantron_corrections'}) {
6279: &scantron_process_corrections($r);
6280: }
6281: $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
6282: #get the student pick code ready
6283: $r->print(&Apache::loncommon::studentbrowser_javascript());
6284: my $nav_error;
6285: my $max_bubble=&scantron_get_maxbubble(\$nav_error);
6286: if ($nav_error) {
6287: $r->print(&navmap_errormsg());
6288: return '';
6289: }
6290: my $result=&scantron_form_start($max_bubble).$default_form_data;
6291: $r->print($result);
6292:
6293: my @validate_phases=( 'sequence',
6294: 'ID',
6295: 'CODE',
6296: 'doublebubble',
6297: 'missingbubbles');
6298: if (!$env{'form.validatepass'}) {
6299: $env{'form.validatepass'} = 0;
6300: }
6301: my $currentphase=$env{'form.validatepass'};
6302:
6303:
6304: my $stop=0;
6305: while (!$stop && $currentphase < scalar(@validate_phases)) {
6306: $r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
6307: $r->rflush();
6308: my $which="scantron_validate_".$validate_phases[$currentphase];
6309: {
6310: no strict 'refs';
6311: ($stop,$currentphase)=&$which($r,$currentphase);
6312: }
6313: }
6314: if (!$stop) {
6315: my $warning=&scantron_warning_screen('Start Grading');
6316: $r->print(&mt('Validation process complete.').'<br />'.
6317: $warning.
6318: &mt('Perform verification for each student after storage of submissions?').
6319: ' <span class="LC_nobreak"><label>'.
6320: '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
6321: (' 'x3).'<label>'.
6322: '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
6323: '</label></span><br />'.
6324: &mt('Grading will take longer if you use verification.').'<br />'.
6325: &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
6326: '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
6327: '<input type="hidden" name="command" value="scantron_process" />'."\n");
6328: } else {
6329: $r->print('<input type="hidden" name="command" value="scantron_validate" />');
6330: $r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
6331: }
6332: if ($stop) {
6333: if ($validate_phases[$currentphase] eq 'sequence') {
6334: $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' → " />');
6335: $r->print(' '.&mt('this error').' <br />');
6336:
6337: $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
6338: } else {
6339: if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
6340: $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' →" onclick="javascript:verify_bubble_radio(this.form)" />');
6341: } else {
6342: $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' →" />');
6343: }
6344: $r->print(' '.&mt('using corrected info').' <br />');
6345: $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
6346: $r->print(" ".&mt("this scanline saving it for later."));
6347: }
6348: }
6349: $r->print(" </form><br />");
6350: return '';
6351: }
6352:
6353:
6354: =pod
6355:
6356: =item scantron_remove_file
6357:
6358: Removes the requested bubble sheet data file, makes sure that
6359: scantron_original_<filename> is never removed
6360:
6361:
6362: =cut
6363:
6364: sub scantron_remove_file {
6365: my ($which)=@_;
6366: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6367: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6368: my $file='scantron_';
6369: if ($which eq 'corrected' || $which eq 'skipped') {
6370: $file.=$which.'_';
6371: } else {
6372: return 'refused';
6373: }
6374: $file.=$env{'form.scantron_selectfile'};
6375: return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
6376: }
6377:
6378:
6379: =pod
6380:
6381: =item scantron_remove_scan_data
6382:
6383: Removes all scan_data correction for the requested bubble sheet
6384: data file. (In the case that both the are doing skipped records we need
6385: to remember the old skipped lines for the time being so that element
6386: persists for a while.)
6387:
6388: =cut
6389:
6390: sub scantron_remove_scan_data {
6391: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6392: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6393: my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
6394: my @todelete;
6395: my $filename=$env{'form.scantron_selectfile'};
6396: foreach my $key (@keys) {
6397: if ($key=~/^\Q$filename\E_/) {
6398: if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
6399: $key=~/remember_skipping/) {
6400: next;
6401: }
6402: push(@todelete,$key);
6403: }
6404: }
6405: my $result;
6406: if (@todelete) {
6407: $result = &Apache::lonnet::del('nohist_scantrondata',
6408: \@todelete,$cdom,$cname);
6409: } else {
6410: $result = 'ok';
6411: }
6412: return $result;
6413: }
6414:
6415:
6416: =pod
6417:
6418: =item scantron_getfile
6419:
6420: Fetches the requested bubble sheet data file (all 3 versions), and
6421: the scan_data hash
6422:
6423: Arguments:
6424: None
6425:
6426: Returns:
6427: 2 hash references
6428:
6429: - first one has
6430: orig -
6431: corrected -
6432: skipped - each of which points to an array ref of the specified
6433: file broken up into individual lines
6434: count - number of scanlines
6435:
6436: - second is the scan_data hash possible keys are
6437: ($number refers to scanline numbered $number and thus the key affects
6438: only that scanline
6439: $bubline refers to the specific bubble line element and the aspects
6440: refers to that specific bubble line element)
6441:
6442: $number.user - username:domain to use
6443: $number.CODE_ignore_dup
6444: - ignore the duplicate CODE error
6445: $number.useCODE
6446: - use the CODE in the scanline as is
6447: $number.no_bubble.$bubline
6448: - it is valid that there is no bubbled in bubble
6449: at $number $bubline
6450: remember_skipping
6451: - a frozen hash containing keys of $number and values
6452: of either
6453: 1 - we are on a 'do skipped records pass' and plan
6454: on processing this line
6455: 2 - we are on a 'do skipped records pass' and this
6456: scanline has been marked to skip yet again
6457:
6458: =cut
6459:
6460: sub scantron_getfile {
6461: #FIXME really would prefer a scantron directory
6462: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6463: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6464: my $lines;
6465: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
6466: 'scantron_orig_'.$env{'form.scantron_selectfile'});
6467: my %scanlines;
6468: $scanlines{'orig'}=[(split("\n",$lines,-1))];
6469: my $temp=$scanlines{'orig'};
6470: $scanlines{'count'}=$#$temp;
6471:
6472: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
6473: 'scantron_corrected_'.$env{'form.scantron_selectfile'});
6474: if ($lines eq '-1') {
6475: $scanlines{'corrected'}=[];
6476: } else {
6477: $scanlines{'corrected'}=[(split("\n",$lines,-1))];
6478: }
6479: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
6480: 'scantron_skipped_'.$env{'form.scantron_selectfile'});
6481: if ($lines eq '-1') {
6482: $scanlines{'skipped'}=[];
6483: } else {
6484: $scanlines{'skipped'}=[(split("\n",$lines,-1))];
6485: }
6486: my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
6487: if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
6488: my %scan_data = @tmp;
6489: return (\%scanlines,\%scan_data);
6490: }
6491:
6492: =pod
6493:
6494: =item lonnet_putfile
6495:
6496: Wrapper routine to call &Apache::lonnet::finishuserfileupload
6497:
6498: Arguments:
6499: $contents - data to store
6500: $filename - filename to store $contents into
6501:
6502: Returns:
6503: result value from &Apache::lonnet::finishuserfileupload
6504:
6505: =cut
6506:
6507: sub lonnet_putfile {
6508: my ($contents,$filename)=@_;
6509: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
6510: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6511: $env{'form.sillywaytopassafilearound'}=$contents;
6512: &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
6513:
6514: }
6515:
6516: =pod
6517:
6518: =item scantron_putfile
6519:
6520: Stores the current version of the bubble sheet data files, and the
6521: scan_data hash. (Does not modify the original version only the
6522: corrected and skipped versions.
6523:
6524: Arguments:
6525: $scanlines - hash ref that looks like the first return value from
6526: &scantron_getfile()
6527: $scan_data - hash ref that looks like the second return value from
6528: &scantron_getfile()
6529:
6530: =cut
6531:
6532: sub scantron_putfile {
6533: my ($scanlines,$scan_data) = @_;
6534: #FIXME really would prefer a scantron directory
6535: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6536: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6537: if ($scanlines) {
6538: my $prefix='scantron_';
6539: # no need to update orig, shouldn't change
6540: # &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
6541: # $env{'form.scantron_selectfile'});
6542: &lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
6543: $prefix.'corrected_'.
6544: $env{'form.scantron_selectfile'});
6545: &lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
6546: $prefix.'skipped_'.
6547: $env{'form.scantron_selectfile'});
6548: }
6549: &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
6550: }
6551:
6552: =pod
6553:
6554: =item scantron_get_line
6555:
6556: Returns the correct version of the scanline
6557:
6558: Arguments:
6559: $scanlines - hash ref that looks like the first return value from
6560: &scantron_getfile()
6561: $scan_data - hash ref that looks like the second return value from
6562: &scantron_getfile()
6563: $i - number of the requested line (starts at 0)
6564:
6565: Returns:
6566: A scanline, (either the original or the corrected one if it
6567: exists), or undef if the requested scanline should be
6568: skipped. (Either because it's an skipped scanline, or it's an
6569: unskipped scanline and we are not doing a 'do skipped scanlines'
6570: pass.
6571:
6572: =cut
6573:
6574: sub scantron_get_line {
6575: my ($scanlines,$scan_data,$i)=@_;
6576: if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
6577: #if ($scanlines->{'skipped'}[$i]) { return undef; }
6578: if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
6579: return $scanlines->{'orig'}[$i];
6580: }
6581:
6582: =pod
6583:
6584: =item scantron_todo_count
6585:
6586: Counts the number of scanlines that need processing.
6587:
6588: Arguments:
6589: $scanlines - hash ref that looks like the first return value from
6590: &scantron_getfile()
6591: $scan_data - hash ref that looks like the second return value from
6592: &scantron_getfile()
6593:
6594: Returns:
6595: $count - number of scanlines to process
6596:
6597: =cut
6598:
6599: sub get_todo_count {
6600: my ($scanlines,$scan_data)=@_;
6601: my $count=0;
6602: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6603: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6604: if ($line=~/^[\s\cz]*$/) { next; }
6605: $count++;
6606: }
6607: return $count;
6608: }
6609:
6610: =pod
6611:
6612: =item scantron_put_line
6613:
6614: Updates the 'corrected' or 'skipped' versions of the bubble sheet
6615: data file.
6616:
6617: Arguments:
6618: $scanlines - hash ref that looks like the first return value from
6619: &scantron_getfile()
6620: $scan_data - hash ref that looks like the second return value from
6621: &scantron_getfile()
6622: $i - line number to update
6623: $newline - contents of the updated scanline
6624: $skip - if true make the line for skipping and update the
6625: 'skipped' file
6626:
6627: =cut
6628:
6629: sub scantron_put_line {
6630: my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
6631: if ($skip) {
6632: $scanlines->{'skipped'}[$i]=$newline;
6633: &start_skipping($scan_data,$i);
6634: return;
6635: }
6636: $scanlines->{'corrected'}[$i]=$newline;
6637: }
6638:
6639: =pod
6640:
6641: =item scantron_clear_skip
6642:
6643: Remove a line from the 'skipped' file
6644:
6645: Arguments:
6646: $scanlines - hash ref that looks like the first return value from
6647: &scantron_getfile()
6648: $scan_data - hash ref that looks like the second return value from
6649: &scantron_getfile()
6650: $i - line number to update
6651:
6652: =cut
6653:
6654: sub scantron_clear_skip {
6655: my ($scanlines,$scan_data,$i)=@_;
6656: if (exists($scanlines->{'skipped'}[$i])) {
6657: undef($scanlines->{'skipped'}[$i]);
6658: return 1;
6659: }
6660: return 0;
6661: }
6662:
6663: =pod
6664:
6665: =item scantron_filter_not_exam
6666:
6667: Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
6668: filter out resources that are not marked as 'exam' mode
6669:
6670: =cut
6671:
6672: sub scantron_filter_not_exam {
6673: my ($curres)=@_;
6674:
6675: if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
6676: # if the user has asked to not have either hidden
6677: # or 'randomout' controlled resources to be graded
6678: # don't include them
6679: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
6680: && $curres->randomout) {
6681: return 0;
6682: }
6683: return 1;
6684: }
6685: return 0;
6686: }
6687:
6688: =pod
6689:
6690: =item scantron_validate_sequence
6691:
6692: Validates the selected sequence, checking for resource that are
6693: not set to exam mode.
6694:
6695: =cut
6696:
6697: sub scantron_validate_sequence {
6698: my ($r,$currentphase) = @_;
6699:
6700: my $navmap=Apache::lonnavmaps::navmap->new();
6701: unless (ref($navmap)) {
6702: $r->print(&navmap_errormsg());
6703: return (1,$currentphase);
6704: }
6705: my (undef,undef,$sequence)=
6706: &Apache::lonnet::decode_symb($env{'form.selectpage'});
6707:
6708: my $map=$navmap->getResourceByUrl($sequence);
6709:
6710: $r->print('<input type="hidden" name="validate_sequence_exam"
6711: value="ignore" />');
6712: if ($env{'form.validate_sequence_exam'} ne 'ignore') {
6713: my @resources=
6714: $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
6715: if (@resources) {
6716: $r->print("<p>".&mt('Some resources in the sequence currently are not set to exam mode. Grading these resources currently may not work correctly.')."</p>");
6717: return (1,$currentphase);
6718: }
6719: }
6720:
6721: return (0,$currentphase+1);
6722: }
6723:
6724:
6725:
6726: sub scantron_validate_ID {
6727: my ($r,$currentphase) = @_;
6728:
6729: #get student info
6730: my $classlist=&Apache::loncoursedata::get_classlist();
6731: my %idmap=&username_to_idmap($classlist);
6732:
6733: #get scantron line setup
6734: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6735: my ($scanlines,$scan_data)=&scantron_getfile();
6736:
6737: my $nav_error;
6738: &scantron_get_maxbubble(\$nav_error); # parse needs the bubble_lines.. array.
6739: if ($nav_error) {
6740: $r->print(&navmap_errormsg());
6741: return(1,$currentphase);
6742: }
6743:
6744: my %found=('ids'=>{},'usernames'=>{});
6745: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6746: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6747: if ($line=~/^[\s\cz]*$/) { next; }
6748: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
6749: $scan_data);
6750: my $id=$$scan_record{'scantron.ID'};
6751: my $found;
6752: foreach my $checkid (keys(%idmap)) {
6753: if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
6754: }
6755: if ($found) {
6756: my $username=$idmap{$found};
6757: if ($found{'ids'}{$found}) {
6758: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6759: $line,'duplicateID',$found);
6760: return(1,$currentphase);
6761: } elsif ($found{'usernames'}{$username}) {
6762: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6763: $line,'duplicateID',$username);
6764: return(1,$currentphase);
6765: }
6766: #FIXME store away line we previously saw the ID on to use above
6767: $found{'ids'}{$found}++;
6768: $found{'usernames'}{$username}++;
6769: } else {
6770: if ($id =~ /^\s*$/) {
6771: my $username=&scan_data($scan_data,"$i.user");
6772: if (defined($username) && $found{'usernames'}{$username}) {
6773: &scantron_get_correction($r,$i,$scan_record,
6774: \%scantron_config,
6775: $line,'duplicateID',$username);
6776: return(1,$currentphase);
6777: } elsif (!defined($username)) {
6778: &scantron_get_correction($r,$i,$scan_record,
6779: \%scantron_config,
6780: $line,'incorrectID');
6781: return(1,$currentphase);
6782: }
6783: $found{'usernames'}{$username}++;
6784: } else {
6785: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
6786: $line,'incorrectID');
6787: return(1,$currentphase);
6788: }
6789: }
6790: }
6791:
6792: return (0,$currentphase+1);
6793: }
6794:
6795:
6796: sub scantron_get_correction {
6797: my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
6798: #FIXME in the case of a duplicated ID the previous line, probably need
6799: #to show both the current line and the previous one and allow skipping
6800: #the previous one or the current one
6801:
6802: if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
6803: $r->print("<p>".&mt("<b>An error was detected ($error)</b>".
6804: " for PaperID <tt>[_1]</tt>",
6805: $$scan_record{'scantron.PaperID'})."</p> \n");
6806: } else {
6807: $r->print("<p>".&mt("<b>An error was detected ($error)</b>".
6808: " in scanline [_1] <pre>[_2]</pre>",
6809: $i,$line)."</p> \n");
6810: }
6811: my $message="<p>".&mt("The ID on the form is <tt>[_1]</tt><br />".
6812: "The name on the paper is [_2],[_3]",
6813: $$scan_record{'scantron.ID'},
6814: $$scan_record{'scantron.LastName'},
6815: $$scan_record{'scantron.FirstName'})."</p>";
6816:
6817: $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
6818: $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
6819: # Array populated for doublebubble or
6820: my @lines_to_correct; # missingbubble errors to build javascript
6821: # to validate radio button checking
6822:
6823: if ($error =~ /ID$/) {
6824: if ($error eq 'incorrectID') {
6825: $r->print("<p>".&mt("The encoded ID is not in the classlist").
6826: "</p>\n");
6827: } elsif ($error eq 'duplicateID') {
6828: $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
6829: }
6830: $r->print($message);
6831: $r->print("<p>".&mt("How should I handle this?")." <br /> \n");
6832: $r->print("\n<ul><li> ");
6833: #FIXME it would be nice if this sent back the user ID and
6834: #could do partial userID matches
6835: $r->print(&Apache::loncommon::selectstudent_link('scantronupload',
6836: 'scantron_username','scantron_domain'));
6837: $r->print(": <input type='text' name='scantron_username' value='' />");
6838: $r->print("\n@".
6839: &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
6840:
6841: $r->print('</li>');
6842: } elsif ($error =~ /CODE$/) {
6843: if ($error eq 'incorrectCODE') {
6844: $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
6845: } elsif ($error eq 'duplicateCODE') {
6846: $r->print("<p>".&mt("The encoded CODE has also been used by a previous paper [_1], and CODEs are supposed to be unique.",join(', ',@{$arg}))."</p>\n");
6847: }
6848: $r->print("<p>".&mt("The CODE on the form is <tt>'[_1]'</tt>",
6849: $$scan_record{'scantron.CODE'})."<br />\n");
6850: $r->print($message);
6851: $r->print("<p>".&mt("How should I handle this?")." <br /> \n");
6852: $r->print("\n<br /> ");
6853: my $i=0;
6854: if ($error eq 'incorrectCODE'
6855: && $$scan_record{'scantron.CODE'}=~/\S/ ) {
6856: my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
6857: if ($closest > 0) {
6858: foreach my $testcode (@{$closest}) {
6859: my $checked='';
6860: if (!$i) { $checked=' checked="checked"'; }
6861: $r->print("
6862: <label>
6863: <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
6864: ".&mt("Use the similar CODE [_1] instead.",
6865: "<b><tt>".$testcode."</tt></b>")."
6866: </label>
6867: <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
6868: $r->print("\n<br />");
6869: $i++;
6870: }
6871: }
6872: }
6873: if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
6874: my $checked; if (!$i) { $checked=' checked="checked"'; }
6875: $r->print("
6876: <label>
6877: <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
6878: ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
6879: "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
6880: </label>");
6881: $r->print("\n<br />");
6882: }
6883:
6884: $r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
6885: function change_radio(field) {
6886: var slct=document.scantronupload.scantron_CODE_resolution;
6887: var i;
6888: for (i=0;i<slct.length;i++) {
6889: if (slct[i].value==field) { slct[i].checked=true; }
6890: }
6891: }
6892: ENDSCRIPT
6893: my $href="/adm/pickcode?".
6894: "form=".&escape("scantronupload").
6895: "&scantron_format=".&escape($env{'form.scantron_format'}).
6896: "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
6897: "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
6898: "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
6899: if ($env{'form.scantron_CODElist'} =~ /\S/) {
6900: $r->print("
6901: <label>
6902: <input type='radio' name='scantron_CODE_resolution' value='use_found' />
6903: ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
6904: "<a target='_blank' href='$href'>","</a>")."
6905: </label>
6906: ".&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\')" />'));
6907: $r->print("\n<br />");
6908: }
6909: $r->print("
6910: <label>
6911: <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
6912: ".&mt("Use [_1] as the CODE.",
6913: "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
6914: $r->print("\n<br /><br />");
6915: } elsif ($error eq 'doublebubble') {
6916: $r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
6917:
6918: # The form field scantron_questions is acutally a list of line numbers.
6919: # represented by this form so:
6920:
6921: my $line_list = &questions_to_line_list($arg);
6922:
6923: $r->print('<input type="hidden" name="scantron_questions" value="'.
6924: $line_list.'" />');
6925: $r->print($message);
6926: $r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
6927: foreach my $question (@{$arg}) {
6928: my @linenums = &prompt_for_corrections($r,$question,$scan_config,
6929: $scan_record, $error);
6930: push(@lines_to_correct,@linenums);
6931: }
6932: $r->print(&verify_bubbles_checked(@lines_to_correct));
6933: } elsif ($error eq 'missingbubble') {
6934: $r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
6935: $r->print($message);
6936: $r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
6937: $r->print(&mt("Some questions have no scanned bubbles.")."\n");
6938:
6939: # The form field scantron_questions is actually a list of line numbers not
6940: # a list of question numbers. Therefore:
6941: #
6942:
6943: my $line_list = &questions_to_line_list($arg);
6944:
6945: $r->print('<input type="hidden" name="scantron_questions" value="'.
6946: $line_list.'" />');
6947: foreach my $question (@{$arg}) {
6948: my @linenums = &prompt_for_corrections($r,$question,$scan_config,
6949: $scan_record, $error);
6950: push(@lines_to_correct,@linenums);
6951: }
6952: $r->print(&verify_bubbles_checked(@lines_to_correct));
6953: } else {
6954: $r->print("\n<ul>");
6955: }
6956: $r->print("\n</li></ul>");
6957: }
6958:
6959: sub verify_bubbles_checked {
6960: my (@ansnums) = @_;
6961: my $ansnumstr = join('","',@ansnums);
6962: my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
6963: my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
6964: function verify_bubble_radio(form) {
6965: var ansnumArray = new Array ("$ansnumstr");
6966: var need_bubble_count = 0;
6967: for (var i=0; i<ansnumArray.length; i++) {
6968: if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
6969: var bubble_picked = 0;
6970: for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
6971: if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
6972: bubble_picked = 1;
6973: }
6974: }
6975: if (bubble_picked == 0) {
6976: need_bubble_count ++;
6977: }
6978: }
6979: }
6980: if (need_bubble_count) {
6981: alert("$warning");
6982: return;
6983: }
6984: form.submit();
6985: }
6986: ENDSCRIPT
6987: return $output;
6988: }
6989:
6990: =pod
6991:
6992: =item questions_to_line_list
6993:
6994: Converts a list of questions into a string of comma separated
6995: line numbers in the answer sheet used by the questions. This is
6996: used to fill in the scantron_questions form field.
6997:
6998: Arguments:
6999: questions - Reference to an array of questions.
7000:
7001: =cut
7002:
7003:
7004: sub questions_to_line_list {
7005: my ($questions) = @_;
7006: my @lines;
7007:
7008: foreach my $item (@{$questions}) {
7009: my $question = $item;
7010: my ($first,$count,$last);
7011: if ($item =~ /^(\d+)\.(\d+)$/) {
7012: $question = $1;
7013: my $subquestion = $2;
7014: $first = $first_bubble_line{$question-1} + 1;
7015: my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
7016: my $subcount = 1;
7017: while ($subcount<$subquestion) {
7018: $first += $subans[$subcount-1];
7019: $subcount ++;
7020: }
7021: $count = $subans[$subquestion-1];
7022: } else {
7023: $first = $first_bubble_line{$question-1} + 1;
7024: $count = $bubble_lines_per_response{$question-1};
7025: }
7026: $last = $first+$count-1;
7027: push(@lines, ($first..$last));
7028: }
7029: return join(',', @lines);
7030: }
7031:
7032: =pod
7033:
7034: =item prompt_for_corrections
7035:
7036: Prompts for a potentially multiline correction to the
7037: user's bubbling (factors out common code from scantron_get_correction
7038: for multi and missing bubble cases).
7039:
7040: Arguments:
7041: $r - Apache request object.
7042: $question - The question number to prompt for.
7043: $scan_config - The scantron file configuration hash.
7044: $scan_record - Reference to the hash that has the the parsed scanlines.
7045: $error - Type of error
7046:
7047: Implicit inputs:
7048: %bubble_lines_per_response - Starting line numbers for each question.
7049: Numbered from 0 (but question numbers are from
7050: 1.
7051: %first_bubble_line - Starting bubble line for each question.
7052: %subdivided_bubble_lines - optionresponse, matchresponse and rankresponse
7053: type problems render as separate sub-questions,
7054: in exam mode. This hash contains a
7055: comma-separated list of the lines per
7056: sub-question.
7057: %responsetype_per_response - essayresponse, formularesponse,
7058: stringresponse, imageresponse, reactionresponse,
7059: and organicresponse type problem parts can have
7060: multiple lines per response if the weight
7061: assigned exceeds 10. In this case, only
7062: one bubble per line is permitted, but more
7063: than one line might contain bubbles, e.g.
7064: bubbling of: line 1 - J, line 2 - J,
7065: line 3 - B would assign 22 points.
7066:
7067: =cut
7068:
7069: sub prompt_for_corrections {
7070: my ($r, $question, $scan_config, $scan_record, $error) = @_;
7071: my ($current_line,$lines);
7072: my @linenums;
7073: my $questionnum = $question;
7074: if ($question =~ /^(\d+)\.(\d+)$/) {
7075: $question = $1;
7076: $current_line = $first_bubble_line{$question-1} + 1 ;
7077: my $subquestion = $2;
7078: my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
7079: my $subcount = 1;
7080: while ($subcount<$subquestion) {
7081: $current_line += $subans[$subcount-1];
7082: $subcount ++;
7083: }
7084: $lines = $subans[$subquestion-1];
7085: } else {
7086: $current_line = $first_bubble_line{$question-1} + 1 ;
7087: $lines = $bubble_lines_per_response{$question-1};
7088: }
7089: if ($lines > 1) {
7090: $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
7091: if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
7092: ($responsetype_per_response{$question-1} eq 'formularesponse') ||
7093: ($responsetype_per_response{$question-1} eq 'stringresponse') ||
7094: ($responsetype_per_response{$question-1} eq 'imageresponse') ||
7095: ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
7096: ($responsetype_per_response{$question-1} eq 'organicresponse')) {
7097: $r->print(&mt("Although this particular question type requires handgrading, the instructions for this question in the exam directed students to leave [quant,_1,line] blank on their bubblesheets.",$lines).'<br /><br />'.&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.').'<br />'.&mt('The score for this question will be a sum of the numeric values for the selected bubbles from each line, where A=1 point, B=2 points etc.').'<br />'.&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.").'<br /><br />');
7098: } else {
7099: $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
7100: }
7101: }
7102: for (my $i =0; $i < $lines; $i++) {
7103: my $selected = $$scan_record{"scantron.$current_line.answer"};
7104: &scantron_bubble_selector($r,$scan_config,$current_line,
7105: $questionnum,$error,split('', $selected));
7106: push(@linenums,$current_line);
7107: $current_line++;
7108: }
7109: if ($lines > 1) {
7110: $r->print("<hr /><br />");
7111: }
7112: return @linenums;
7113: }
7114:
7115: =pod
7116:
7117: =item scantron_bubble_selector
7118:
7119: Generates the html radiobuttons to correct a single bubble line
7120: possibly showing the existing the selected bubbles if known
7121:
7122: Arguments:
7123: $r - Apache request object
7124: $scan_config - hash from &get_scantron_config()
7125: $line - Number of the line being displayed.
7126: $questionnum - Question number (may include subquestion)
7127: $error - Type of error.
7128: @selected - Array of bubbles picked on this line.
7129:
7130: =cut
7131:
7132: sub scantron_bubble_selector {
7133: my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
7134: my $max=$$scan_config{'Qlength'};
7135:
7136: my $scmode=$$scan_config{'Qon'};
7137: if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }
7138:
7139: my @alphabet=('A'..'Z');
7140: $r->print(&Apache::loncommon::start_data_table().
7141: &Apache::loncommon::start_data_table_row());
7142: $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
7143: for (my $i=0;$i<$max+1;$i++) {
7144: $r->print("\n".'<td align="center">');
7145: if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
7146: else { $r->print(' '); }
7147: $r->print('</td>');
7148: }
7149: $r->print(&Apache::loncommon::end_data_table_row().
7150: &Apache::loncommon::start_data_table_row());
7151: for (my $i=0;$i<$max;$i++) {
7152: $r->print("\n".
7153: '<td><label><input type="radio" name="scantron_correct_Q_'.
7154: $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
7155: }
7156: my $nobub_checked = ' ';
7157: if ($error eq 'missingbubble') {
7158: $nobub_checked = ' checked = "checked" ';
7159: }
7160: $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
7161: $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
7162: '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
7163: $line.'" value="'.$questionnum.'" /></td>');
7164: $r->print(&Apache::loncommon::end_data_table_row().
7165: &Apache::loncommon::end_data_table());
7166: }
7167:
7168: =pod
7169:
7170: =item num_matches
7171:
7172: Counts the number of characters that are the same between the two arguments.
7173:
7174: Arguments:
7175: $orig - CODE from the scanline
7176: $code - CODE to match against
7177:
7178: Returns:
7179: $count - integer count of the number of same characters between the
7180: two arguments
7181:
7182: =cut
7183:
7184: sub num_matches {
7185: my ($orig,$code) = @_;
7186: my @code=split(//,$code);
7187: my @orig=split(//,$orig);
7188: my $same=0;
7189: for (my $i=0;$i<scalar(@code);$i++) {
7190: if ($code[$i] eq $orig[$i]) { $same++; }
7191: }
7192: return $same;
7193: }
7194:
7195: =pod
7196:
7197: =item scantron_get_closely_matching_CODEs
7198:
7199: Cycles through all CODEs and finds the set that has the greatest
7200: number of same characters as the provided CODE
7201:
7202: Arguments:
7203: $allcodes - hash ref returned by &get_codes()
7204: $CODE - CODE from the current scanline
7205:
7206: Returns:
7207: 2 element list
7208: - first elements is number of how closely matching the best fit is
7209: (5 means best set has 5 matching characters)
7210: - second element is an arrary ref containing the set of valid CODEs
7211: that best fit the passed in CODE
7212:
7213: =cut
7214:
7215: sub scantron_get_closely_matching_CODEs {
7216: my ($allcodes,$CODE)=@_;
7217: my @CODEs;
7218: foreach my $testcode (sort(keys(%{$allcodes}))) {
7219: push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
7220: }
7221:
7222: return ($#CODEs,$CODEs[-1]);
7223: }
7224:
7225: =pod
7226:
7227: =item get_codes
7228:
7229: Builds a hash which has keys of all of the valid CODEs from the selected
7230: set of remembered CODEs.
7231:
7232: Arguments:
7233: $old_name - name of the set of remembered CODEs
7234: $cdom - domain of the course
7235: $cnum - internal course name
7236:
7237: Returns:
7238: %allcodes - keys are the valid CODEs, values are all 1
7239:
7240: =cut
7241:
7242: sub get_codes {
7243: my ($old_name, $cdom, $cnum) = @_;
7244: if (!$old_name) {
7245: $old_name=$env{'form.scantron_CODElist'};
7246: }
7247: if (!$cdom) {
7248: $cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
7249: }
7250: if (!$cnum) {
7251: $cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
7252: }
7253: my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
7254: $cdom,$cnum);
7255: my %allcodes;
7256: if ($result{"type\0$old_name"} eq 'number') {
7257: %allcodes=map {($_,1)} split(',',$result{$old_name});
7258: } else {
7259: %allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
7260: }
7261: return %allcodes;
7262: }
7263:
7264: =pod
7265:
7266: =item scantron_validate_CODE
7267:
7268: Validates all scanlines in the selected file to not have any
7269: invalid or underspecified CODEs and that none of the codes are
7270: duplicated if this was requested.
7271:
7272: =cut
7273:
7274: sub scantron_validate_CODE {
7275: my ($r,$currentphase) = @_;
7276: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7277: if ($scantron_config{'CODElocation'} &&
7278: $scantron_config{'CODEstart'} &&
7279: $scantron_config{'CODElength'}) {
7280: if (!defined($env{'form.scantron_CODElist'})) {
7281: &FIXME_blow_up()
7282: }
7283: } else {
7284: return (0,$currentphase+1);
7285: }
7286:
7287: my %usedCODEs;
7288:
7289: my %allcodes=&get_codes();
7290:
7291: my $nav_error;
7292: &scantron_get_maxbubble(\$nav_error); # parse needs the lines per response array.
7293: if ($nav_error) {
7294: $r->print(&navmap_errormsg());
7295: return(1,$currentphase);
7296: }
7297:
7298: my ($scanlines,$scan_data)=&scantron_getfile();
7299: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7300: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7301: if ($line=~/^[\s\cz]*$/) { next; }
7302: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7303: $scan_data);
7304: my $CODE=$$scan_record{'scantron.CODE'};
7305: my $error=0;
7306: if (!&Apache::lonnet::validCODE($CODE)) {
7307: &scantron_get_correction($r,$i,$scan_record,
7308: \%scantron_config,
7309: $line,'incorrectCODE',\%allcodes);
7310: return(1,$currentphase);
7311: }
7312: if (%allcodes && !exists($allcodes{$CODE})
7313: && !$$scan_record{'scantron.useCODE'}) {
7314: &scantron_get_correction($r,$i,$scan_record,
7315: \%scantron_config,
7316: $line,'incorrectCODE',\%allcodes);
7317: return(1,$currentphase);
7318: }
7319: if (exists($usedCODEs{$CODE})
7320: && $env{'form.scantron_CODEunique'} eq 'yes'
7321: && !$$scan_record{'scantron.CODE_ignore_dup'}) {
7322: &scantron_get_correction($r,$i,$scan_record,
7323: \%scantron_config,
7324: $line,'duplicateCODE',$usedCODEs{$CODE});
7325: return(1,$currentphase);
7326: }
7327: push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
7328: }
7329: return (0,$currentphase+1);
7330: }
7331:
7332: =pod
7333:
7334: =item scantron_validate_doublebubble
7335:
7336: Validates all scanlines in the selected file to not have any
7337: bubble lines with multiple bubbles marked.
7338:
7339: =cut
7340:
7341: sub scantron_validate_doublebubble {
7342: my ($r,$currentphase) = @_;
7343: #get student info
7344: my $classlist=&Apache::loncoursedata::get_classlist();
7345: my %idmap=&username_to_idmap($classlist);
7346:
7347: #get scantron line setup
7348: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7349: my ($scanlines,$scan_data)=&scantron_getfile();
7350: my $nav_error;
7351: &scantron_get_maxbubble(\$nav_error); # parse needs the bubble line array.
7352: if ($nav_error) {
7353: $r->print(&navmap_errormsg());
7354: return(1,$currentphase);
7355: }
7356:
7357: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7358: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7359: if ($line=~/^[\s\cz]*$/) { next; }
7360: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7361: $scan_data);
7362: if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
7363: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
7364: 'doublebubble',
7365: $$scan_record{'scantron.doubleerror'});
7366: return (1,$currentphase);
7367: }
7368: return (0,$currentphase+1);
7369: }
7370:
7371:
7372: sub scantron_get_maxbubble {
7373: my ($nav_error) = @_;
7374: if (defined($env{'form.scantron_maxbubble'}) &&
7375: $env{'form.scantron_maxbubble'}) {
7376: &restore_bubble_lines();
7377: return $env{'form.scantron_maxbubble'};
7378: }
7379:
7380: my (undef, undef, $sequence) =
7381: &Apache::lonnet::decode_symb($env{'form.selectpage'});
7382:
7383: my $navmap=Apache::lonnavmaps::navmap->new();
7384: unless (ref($navmap)) {
7385: if (ref($nav_error)) {
7386: $$nav_error = 1;
7387: }
7388: return;
7389: }
7390: my $map=$navmap->getResourceByUrl($sequence);
7391: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
7392:
7393: &Apache::lonxml::clear_problem_counter();
7394:
7395: my $uname = $env{'user.name'};
7396: my $udom = $env{'user.domain'};
7397: my $cid = $env{'request.course.id'};
7398: my $total_lines = 0;
7399: %bubble_lines_per_response = ();
7400: %first_bubble_line = ();
7401: %subdivided_bubble_lines = ();
7402: %responsetype_per_response = ();
7403:
7404: my $response_number = 0;
7405: my $bubble_line = 0;
7406: foreach my $resource (@resources) {
7407: my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
7408: if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
7409: foreach my $part_id (@{$parts}) {
7410: my $lines;
7411:
7412: # TODO - make this a persistent hash not an array.
7413:
7414: # optionresponse, matchresponse and rankresponse type items
7415: # render as separate sub-questions in exam mode.
7416: if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
7417: ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
7418: ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
7419: my ($numbub,$numshown);
7420: if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
7421: if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
7422: $numbub = scalar(@{$analysis->{$part_id.'.options'}});
7423: }
7424: } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
7425: if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
7426: $numbub = scalar(@{$analysis->{$part_id.'.items'}});
7427: }
7428: } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
7429: if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
7430: $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
7431: }
7432: }
7433: if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
7434: $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
7435: }
7436: my $bubbles_per_line = 10;
7437: my $inner_bubble_lines = int($numbub/$bubbles_per_line);
7438: if (($numbub % $bubbles_per_line) != 0) {
7439: $inner_bubble_lines++;
7440: }
7441: for (my $i=0; $i<$numshown; $i++) {
7442: $subdivided_bubble_lines{$response_number} .=
7443: $inner_bubble_lines.',';
7444: }
7445: $subdivided_bubble_lines{$response_number} =~ s/,$//;
7446: $lines = $numshown * $inner_bubble_lines;
7447: } else {
7448: $lines = $analysis->{"$part_id.bubble_lines"};
7449: }
7450:
7451: $first_bubble_line{$response_number} = $bubble_line;
7452: $bubble_lines_per_response{$response_number} = $lines;
7453: $responsetype_per_response{$response_number} =
7454: $analysis->{$part_id.'.type'};
7455: $response_number++;
7456:
7457: $bubble_line += $lines;
7458: $total_lines += $lines;
7459: }
7460: }
7461: }
7462: &Apache::lonnet::delenv('scantron.');
7463:
7464: &save_bubble_lines();
7465: $env{'form.scantron_maxbubble'} =
7466: $total_lines;
7467: return $env{'form.scantron_maxbubble'};
7468: }
7469:
7470: sub scantron_validate_missingbubbles {
7471: my ($r,$currentphase) = @_;
7472: #get student info
7473: my $classlist=&Apache::loncoursedata::get_classlist();
7474: my %idmap=&username_to_idmap($classlist);
7475:
7476: #get scantron line setup
7477: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7478: my ($scanlines,$scan_data)=&scantron_getfile();
7479: my $nav_error;
7480: my $max_bubble=&scantron_get_maxbubble(\$nav_error);
7481: if ($nav_error) {
7482: return(1,$currentphase);
7483: }
7484: if (!$max_bubble) { $max_bubble=2**31; }
7485: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7486: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7487: if ($line=~/^[\s\cz]*$/) { next; }
7488: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7489: $scan_data);
7490: if (!defined($$scan_record{'scantron.missingerror'})) { next; }
7491: my @to_correct;
7492:
7493: # Probably here's where the error is...
7494:
7495: foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
7496: my $lastbubble;
7497: if ($missing =~ /^(\d+)\.(\d+)$/) {
7498: my $question = $1;
7499: my $subquestion = $2;
7500: if (!defined($first_bubble_line{$question -1})) { next; }
7501: my $first = $first_bubble_line{$question-1};
7502: my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
7503: my $subcount = 1;
7504: while ($subcount<$subquestion) {
7505: $first += $subans[$subcount-1];
7506: $subcount ++;
7507: }
7508: my $count = $subans[$subquestion-1];
7509: $lastbubble = $first + $count;
7510: } else {
7511: if (!defined($first_bubble_line{$missing - 1})) { next; }
7512: $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
7513: }
7514: if ($lastbubble > $max_bubble) { next; }
7515: push(@to_correct,$missing);
7516: }
7517: if (@to_correct) {
7518: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
7519: $line,'missingbubble',\@to_correct);
7520: return (1,$currentphase);
7521: }
7522:
7523: }
7524: return (0,$currentphase+1);
7525: }
7526:
7527:
7528: sub scantron_process_students {
7529: my ($r,$symb) = @_;
7530:
7531: my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
7532: if (!$symb) {
7533: return '';
7534: }
7535: my $default_form_data=&defaultFormData($symb);
7536:
7537: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7538: my ($scanlines,$scan_data)=&scantron_getfile();
7539: my $classlist=&Apache::loncoursedata::get_classlist();
7540: my %idmap=&username_to_idmap($classlist);
7541: my $navmap=Apache::lonnavmaps::navmap->new();
7542: unless (ref($navmap)) {
7543: $r->print(&navmap_errormsg());
7544: return '';
7545: }
7546: my $map=$navmap->getResourceByUrl($sequence);
7547: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
7548: my (%grader_partids_by_symb,%grader_randomlists_by_symb);
7549: &graders_resources_pass(\@resources,\%grader_partids_by_symb,
7550: \%grader_randomlists_by_symb);
7551: my $resource_error;
7552: foreach my $resource (@resources) {
7553: my $ressymb;
7554: if (ref($resource)) {
7555: $ressymb = $resource->symb();
7556: } else {
7557: $resource_error = 1;
7558: last;
7559: }
7560: my ($analysis,$parts) =
7561: &scantron_partids_tograde($resource,$env{'request.course.id'},
7562: $env{'user.name'},$env{'user.domain'},1);
7563: $grader_partids_by_symb{$ressymb} = $parts;
7564: if (ref($analysis) eq 'HASH') {
7565: if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
7566: $grader_randomlists_by_symb{$ressymb} =
7567: $analysis->{'parts_withrandomlist'};
7568: }
7569: }
7570: }
7571: if ($resource_error) {
7572: $r->print(&navmap_errormsg());
7573: return '';
7574: }
7575:
7576: my ($uname,$udom);
7577: my $result= <<SCANTRONFORM;
7578: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
7579: <input type="hidden" name="command" value="scantron_configphase" />
7580: $default_form_data
7581: SCANTRONFORM
7582: $r->print($result);
7583:
7584: my @delayqueue;
7585: my (%completedstudents,%scandata);
7586:
7587: my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
7588: my $count=&get_todo_count($scanlines,$scan_data);
7589: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet Status',
7590: 'Bubblesheet Progress',$count,
7591: 'inline',undef,'scantronupload');
7592: &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
7593: 'Processing first student');
7594: $r->print('<br />');
7595: my $start=&Time::HiRes::time();
7596: my $i=-1;
7597: my $started;
7598:
7599: my $nav_error;
7600: &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
7601: if ($nav_error) {
7602: $r->print(&navmap_errormsg());
7603: return '';
7604: }
7605:
7606: # If an ssi failed in scantron_get_maxbubble, put an error message out to
7607: # the user and return.
7608:
7609: if ($ssi_error) {
7610: $r->print("</form>");
7611: &ssi_print_error($r);
7612: &Apache::lonnet::remove_lock($lock);
7613: return ''; # Dunno why the other returns return '' rather than just returning.
7614: }
7615:
7616: my %lettdig = &letter_to_digits();
7617: my $numletts = scalar(keys(%lettdig));
7618:
7619: while ($i<$scanlines->{'count'}) {
7620: ($uname,$udom)=('','');
7621: $i++;
7622: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7623: if ($line=~/^[\s\cz]*$/) { next; }
7624: if ($started) {
7625: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
7626: 'last student');
7627: }
7628: $started=1;
7629: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7630: $scan_data);
7631: unless ($uname=&scantron_find_student($scan_record,$scan_data,
7632: \%idmap,$i)) {
7633: &scantron_add_delay(\@delayqueue,$line,
7634: 'Unable to find a student that matches',1);
7635: next;
7636: }
7637: if (exists $completedstudents{$uname}) {
7638: &scantron_add_delay(\@delayqueue,$line,
7639: 'Student '.$uname.' has multiple sheets',2);
7640: next;
7641: }
7642: ($uname,$udom)=split(/:/,$uname);
7643:
7644: my (%partids_by_symb,$res_error);
7645: foreach my $resource (@resources) {
7646: my $ressymb;
7647: if (ref($resource)) {
7648: $ressymb = $resource->symb();
7649: } else {
7650: $res_error = 1;
7651: last;
7652: }
7653: if ((exists($grader_randomlists_by_symb{$ressymb})) ||
7654: (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
7655: my ($analysis,$parts) =
7656: &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
7657: $partids_by_symb{$ressymb} = $parts;
7658: } else {
7659: $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
7660: }
7661: }
7662:
7663: if ($res_error) {
7664: &scantron_add_delay(\@delayqueue,$line,
7665: 'An error occurred while grading student '.$uname,2);
7666: next;
7667: }
7668:
7669: &Apache::lonxml::clear_problem_counter();
7670: &Apache::lonnet::appenv($scan_record);
7671:
7672: if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
7673: &scantron_putfile($scanlines,$scan_data);
7674: }
7675:
7676: my $scancode;
7677: if ((exists($scan_record->{'scantron.CODE'})) &&
7678: (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
7679: $scancode = $scan_record->{'scantron.CODE'};
7680: } else {
7681: $scancode = '';
7682: }
7683:
7684: if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
7685: \@resources,\%partids_by_symb) eq 'ssi_error') {
7686: $ssi_error = 0; # So end of handler error message does not trigger.
7687: $r->print("</form>");
7688: &ssi_print_error($r);
7689: &Apache::lonnet::remove_lock($lock);
7690: return ''; # Why return ''? Beats me.
7691: }
7692:
7693: $completedstudents{$uname}={'line'=>$line};
7694: if ($env{'form.verifyrecord'}) {
7695: my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
7696: my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
7697: chomp($studentdata);
7698: $studentdata =~ s/\r$//;
7699: my $studentrecord = '';
7700: my $counter = -1;
7701: foreach my $resource (@resources) {
7702: my $ressymb = $resource->symb();
7703: ($counter,my $recording) =
7704: &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
7705: $counter,$studentdata,$partids_by_symb{$ressymb},
7706: \%scantron_config,\%lettdig,$numletts);
7707: $studentrecord .= $recording;
7708: }
7709: if ($studentrecord ne $studentdata) {
7710: &Apache::lonxml::clear_problem_counter();
7711: if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
7712: \@resources,\%partids_by_symb) eq 'ssi_error') {
7713: $ssi_error = 0; # So end of handler error message does not trigger.
7714: $r->print("</form>");
7715: &ssi_print_error($r);
7716: &Apache::lonnet::remove_lock($lock);
7717: delete($completedstudents{$uname});
7718: return '';
7719: }
7720: $counter = -1;
7721: $studentrecord = '';
7722: foreach my $resource (@resources) {
7723: my $ressymb = $resource->symb();
7724: ($counter,my $recording) =
7725: &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
7726: $counter,$studentdata,$partids_by_symb{$ressymb},
7727: \%scantron_config,\%lettdig,$numletts);
7728: $studentrecord .= $recording;
7729: }
7730: if ($studentrecord ne $studentdata) {
7731: $r->print('<p><span class="LC_error">');
7732: if ($scancode eq '') {
7733: $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
7734: $uname.':'.$udom,$scan_record->{'scantron.ID'}));
7735: } else {
7736: $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
7737: $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
7738: }
7739: $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
7740: &Apache::loncommon::start_data_table_header_row()."\n".
7741: '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
7742: &Apache::loncommon::end_data_table_header_row()."\n".
7743: &Apache::loncommon::start_data_table_row().
7744: '<td>'.&mt('Bubble Sheet').'</td>'.
7745: '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
7746: &Apache::loncommon::end_data_table_row().
7747: &Apache::loncommon::start_data_table_row().
7748: '<td>Stored submissions</td>'.
7749: '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
7750: &Apache::loncommon::end_data_table_row().
7751: &Apache::loncommon::end_data_table().'</p>');
7752: } else {
7753: $r->print('<br /><span class="LC_warning">'.
7754: &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 />'.
7755: &mt("As a consequence, this user's submission history records two tries.").
7756: '</span><br />');
7757: }
7758: }
7759: }
7760: if (&Apache::loncommon::connection_aborted($r)) { last; }
7761: } continue {
7762: &Apache::lonxml::clear_problem_counter();
7763: &Apache::lonnet::delenv('scantron.');
7764: }
7765: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
7766: &Apache::lonnet::remove_lock($lock);
7767: # my $lasttime = &Time::HiRes::time()-$start;
7768: # $r->print("<p>took $lasttime</p>");
7769:
7770: $r->print("</form>");
7771: return '';
7772: }
7773:
7774: sub graders_resources_pass {
7775: my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb) = @_;
7776: if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) &&
7777: (ref($grader_randomlists_by_symb) eq 'HASH')) {
7778: foreach my $resource (@{$resources}) {
7779: my $ressymb = $resource->symb();
7780: my ($analysis,$parts) =
7781: &scantron_partids_tograde($resource,$env{'request.course.id'},
7782: $env{'user.name'},$env{'user.domain'},1);
7783: $grader_partids_by_symb->{$ressymb} = $parts;
7784: if (ref($analysis) eq 'HASH') {
7785: if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
7786: $grader_randomlists_by_symb->{$ressymb} =
7787: $analysis->{'parts_withrandomlist'};
7788: }
7789: }
7790: }
7791: }
7792: return;
7793: }
7794:
7795: sub grade_student_bubbles {
7796: my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts) = @_;
7797: if (ref($resources) eq 'ARRAY') {
7798: my $count = 0;
7799: foreach my $resource (@{$resources}) {
7800: my $ressymb = $resource->symb();
7801: my %form = ('submitted' => 'scantron',
7802: 'grade_target' => 'grade',
7803: 'grade_username' => $uname,
7804: 'grade_domain' => $udom,
7805: 'grade_courseid' => $env{'request.course.id'},
7806: 'grade_symb' => $ressymb,
7807: 'CODE' => $scancode
7808: );
7809: if (ref($parts) eq 'HASH') {
7810: if (ref($parts->{$ressymb}) eq 'ARRAY') {
7811: foreach my $part (@{$parts->{$ressymb}}) {
7812: $form{'scantron_questnum_start.'.$part} =
7813: 1+$env{'form.scantron.first_bubble_line.'.$count};
7814: $count++;
7815: }
7816: }
7817: }
7818: my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
7819: return 'ssi_error' if ($ssi_error);
7820: last if (&Apache::loncommon::connection_aborted($r));
7821: }
7822: }
7823: return;
7824: }
7825:
7826: sub scantron_upload_scantron_data {
7827: my ($r,$symb)=@_;
7828: my $dom = $env{'request.role.domain'};
7829: my $domdesc = &Apache::lonnet::domain($dom,'description');
7830: $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
7831: my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
7832: 'domainid',
7833: 'coursename',$dom);
7834: my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
7835: (' 'x2).&mt('(shows course personnel)');
7836: my $default_form_data=&defaultFormData($symb);
7837: my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
7838: 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.");
7839: $r->print(&Apache::lonhtmlcommon::scripttag('
7840: function checkUpload(formname) {
7841: if (formname.upfile.value == "") {
7842: alert("'.$nofile_alert.'");
7843: return false;
7844: }
7845: if (formname.courseid.value == "") {
7846: alert("'.$nocourseid_alert.'");
7847: return false;
7848: }
7849: formname.submit();
7850: }
7851:
7852: function ToSyllabus() {
7853: var cdom = '."'$dom'".';
7854: var cnum = document.rules.courseid.value;
7855: if (cdom == "" || cdom == null) {
7856: return;
7857: }
7858: if (cnum == "" || cnum == null) {
7859: return;
7860: }
7861: syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
7862: "height=350,width=350,scrollbars=yes,menubar=no");
7863: return;
7864: }
7865:
7866: '));
7867: $r->print('
7868: <h3>'.&mt('Send scanned bubblesheet data to a course').'</h3>
7869:
7870: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
7871: '.$default_form_data.
7872: &Apache::lonhtmlcommon::start_pick_box().
7873: &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
7874: '<input name="courseid" type="text" size="30" />'.$select_link.
7875: &Apache::lonhtmlcommon::row_closure().
7876: &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
7877: '<input name="coursename" type="text" size="30" />'.$syllabuslink.
7878: &Apache::lonhtmlcommon::row_closure().
7879: &Apache::lonhtmlcommon::row_title(&mt('Domain')).
7880: '<input name="domainid" type="hidden" />'.$domdesc.
7881: &Apache::lonhtmlcommon::row_closure().
7882: &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
7883: '<input type="file" name="upfile" size="50" />'.
7884: &Apache::lonhtmlcommon::row_closure(1).
7885: &Apache::lonhtmlcommon::end_pick_box().'<br />
7886:
7887: <input name="command" value="scantronupload_save" type="hidden" />
7888: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
7889: </form>
7890: ');
7891: return '';
7892: }
7893:
7894:
7895: sub scantron_upload_scantron_data_save {
7896: my($r,$symb)=@_;
7897: my $doanotherupload=
7898: '<br /><form action="/adm/grades" method="post">'."\n".
7899: '<input type="hidden" name="command" value="scantronupload" />'."\n".
7900: '<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
7901: '</form>'."\n";
7902: if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
7903: !&Apache::lonnet::allowed('usc',
7904: $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
7905: $r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
7906: unless ($symb) {
7907: $r->print($doanotherupload);
7908: }
7909: return '';
7910: }
7911: my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
7912: my $uploadedfile;
7913: $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
7914: if (length($env{'form.upfile'}) < 2) {
7915: $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>'));
7916: } else {
7917: my $result =
7918: &Apache::lonnet::userfileupload('upfile','','scantron','','','',
7919: $env{'form.courseid'},$env{'form.domainid'});
7920: if ($result =~ m{^/uploaded/}) {
7921: $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
7922: '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
7923: '<span class="LC_filename">'.$result.'</span>'));
7924: ($uploadedfile) = ($result =~ m{/([^/]+)$});
7925: $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
7926: $env{'form.courseid'},$uploadedfile));
7927: } else {
7928: $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
7929: '<span class="LC_error">','</span>',$result,
7930: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
7931: }
7932: }
7933: if ($symb) {
7934: $r->print(&scantron_selectphase($r,$uploadedfile,$symb));
7935: } else {
7936: $r->print($doanotherupload);
7937: }
7938: return '';
7939: }
7940:
7941: sub validate_uploaded_scantron_file {
7942: my ($cdom,$cname,$fname) = @_;
7943: my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
7944: my @lines;
7945: if ($scanlines ne '-1') {
7946: @lines=split("\n",$scanlines,-1);
7947: }
7948: my $output;
7949: if (@lines) {
7950: my (%counts,$max_match_format);
7951: my ($max_match_count,$max_match_pct) = (0,0);
7952: my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
7953: my %idmap = &username_to_idmap($classlist);
7954: foreach my $key (keys(%idmap)) {
7955: my $lckey = lc($key);
7956: $idmap{$lckey} = $idmap{$key};
7957: }
7958: my %unique_formats;
7959: my @formatlines = &get_scantronformat_file();
7960: foreach my $line (@formatlines) {
7961: chomp($line);
7962: my @config = split(/:/,$line);
7963: my $idstart = $config[5];
7964: my $idlength = $config[6];
7965: if (($idstart ne '') && ($idlength > 0)) {
7966: if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
7967: push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]);
7968: } else {
7969: $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
7970: }
7971: }
7972: }
7973: foreach my $key (keys(%unique_formats)) {
7974: my ($idstart,$idlength) = split(':',$key);
7975: %{$counts{$key}} = (
7976: 'found' => 0,
7977: 'total' => 0,
7978: );
7979: foreach my $line (@lines) {
7980: next if ($line =~ /^#/);
7981: next if ($line =~ /^[\s\cz]*$/);
7982: my $id = substr($line,$idstart-1,$idlength);
7983: $id = lc($id);
7984: if (exists($idmap{$id})) {
7985: $counts{$key}{'found'} ++;
7986: }
7987: $counts{$key}{'total'} ++;
7988: }
7989: if ($counts{$key}{'total'}) {
7990: my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
7991: if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
7992: $max_match_pct = $percent_match;
7993: $max_match_format = $key;
7994: $max_match_count = $counts{$key}{'total'};
7995: }
7996: }
7997: }
7998: if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
7999: my $format_descs;
8000: my $numwithformat = @{$unique_formats{$max_match_format}};
8001: for (my $i=0; $i<$numwithformat; $i++) {
8002: my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
8003: if ($i<$numwithformat-2) {
8004: $format_descs .= '"<i>'.$desc.'</i>", ';
8005: } elsif ($i==$numwithformat-2) {
8006: $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
8007: } elsif ($i==$numwithformat-1) {
8008: $format_descs .= '"<i>'.$desc.'</i>"';
8009: }
8010: }
8011: my $showpct = sprintf("%.0f",$max_match_pct).'%';
8012: $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).
8013: '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
8014: '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
8015: '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
8016: '<i>'.$cdom.'</i>').'</li>'.
8017: '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
8018: '<li>'.&mt('The course roster is not up to date').'</li>'.
8019: '</ul>';
8020: }
8021: } else {
8022: $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
8023: }
8024: return $output;
8025: }
8026:
8027: sub valid_file {
8028: my ($requested_file)=@_;
8029: foreach my $filename (sort(&scantron_filenames())) {
8030: if ($requested_file eq $filename) { return 1; }
8031: }
8032: return 0;
8033: }
8034:
8035: sub scantron_download_scantron_data {
8036: my ($r,$symb)=@_;
8037: my $default_form_data=&defaultFormData($symb);
8038: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
8039: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
8040: my $file=$env{'form.scantron_selectfile'};
8041: if (! &valid_file($file)) {
8042: $r->print('
8043: <p>
8044: '.&mt('The requested file name was invalid.').'
8045: </p>
8046: ');
8047: return;
8048: }
8049: my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
8050: my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
8051: my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
8052: &Apache::lonnet::allowuploaded('/adm/grades',$orig);
8053: &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
8054: &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
8055: $r->print('
8056: <p>
8057: '.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
8058: '<a href="'.$orig.'">','</a>').'
8059: </p>
8060: <p>
8061: '.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
8062: '<a href="'.$corrected.'">','</a>').'
8063: </p>
8064: <p>
8065: '.&mt('[_1]Skipped[_2], a file of records that were skipped.',
8066: '<a href="'.$skipped.'">','</a>').'
8067: </p>
8068: ');
8069: return '';
8070: }
8071:
8072: sub checkscantron_results {
8073: my ($r,$symb) = @_;
8074: if (!$symb) {return '';}
8075: my $cid = $env{'request.course.id'};
8076: my %lettdig = &letter_to_digits();
8077: my $numletts = scalar(keys(%lettdig));
8078: my $cnum = $env{'course.'.$cid.'.num'};
8079: my $cdom = $env{'course.'.$cid.'.domain'};
8080: my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
8081: my %record;
8082: my %scantron_config =
8083: &Apache::grades::get_scantron_config($env{'form.scantron_format'});
8084: my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
8085: my $classlist=&Apache::loncoursedata::get_classlist();
8086: my %idmap=&Apache::grades::username_to_idmap($classlist);
8087: my $navmap=Apache::lonnavmaps::navmap->new();
8088: unless (ref($navmap)) {
8089: $r->print(&navmap_errormsg());
8090: return '';
8091: }
8092: my $map=$navmap->getResourceByUrl($sequence);
8093: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
8094: my (%grader_partids_by_symb,%grader_randomlists_by_symb);
8095: &graders_resources_pass(\@resources,\%grader_partids_by_symb, \%grader_randomlists_by_symb);
8096:
8097: my ($uname,$udom);
8098: my (%scandata,%lastname,%bylast);
8099: $r->print('
8100: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
8101:
8102: my @delayqueue;
8103: my %completedstudents;
8104:
8105: my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
8106: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Bubblesheet/Submissions Comparison Status',
8107: 'Progress of Bubblesheet Data/Submission Records Comparison',$count,
8108: 'inline',undef,'checkscantron');
8109: my ($username,$domain,$started);
8110: my $nav_error;
8111: &scantron_get_maxbubble(\$nav_error); # Need the bubble lines array to parse.
8112: if ($nav_error) {
8113: $r->print(&navmap_errormsg());
8114: return '';
8115: }
8116:
8117: &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
8118: 'Processing first student');
8119: my $start=&Time::HiRes::time();
8120: my $i=-1;
8121:
8122: while ($i<$scanlines->{'count'}) {
8123: ($username,$domain,$uname)=('','','');
8124: $i++;
8125: my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
8126: if ($line=~/^[\s\cz]*$/) { next; }
8127: if ($started) {
8128: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
8129: 'last student');
8130: }
8131: $started=1;
8132: my $scan_record=
8133: &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
8134: $scan_data);
8135: unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
8136: \%idmap,$i)) {
8137: &Apache::grades::scantron_add_delay(\@delayqueue,$line,
8138: 'Unable to find a student that matches',1);
8139: next;
8140: }
8141: if (exists $completedstudents{$uname}) {
8142: &Apache::grades::scantron_add_delay(\@delayqueue,$line,
8143: 'Student '.$uname.' has multiple sheets',2);
8144: next;
8145: }
8146: my $pid = $scan_record->{'scantron.ID'};
8147: $lastname{$pid} = $scan_record->{'scantron.LastName'};
8148: push(@{$bylast{$lastname{$pid}}},$pid);
8149: my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
8150: $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
8151: chomp($scandata{$pid});
8152: $scandata{$pid} =~ s/\r$//;
8153: ($username,$domain)=split(/:/,$uname);
8154: my $counter = -1;
8155: foreach my $resource (@resources) {
8156: my $parts;
8157: my $ressymb = $resource->symb();
8158: if ((exists($grader_randomlists_by_symb{$ressymb})) ||
8159: (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
8160: (my $analysis,$parts) =
8161: &scantron_partids_tograde($resource,$env{'request.course.id'},$username,$domain);
8162: } else {
8163: $parts = $grader_partids_by_symb{$ressymb};
8164: }
8165: ($counter,my $recording) =
8166: &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
8167: $scandata{$pid},$parts,
8168: \%scantron_config,\%lettdig,$numletts);
8169: $record{$pid} .= $recording;
8170: }
8171: }
8172: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
8173: $r->print('<br />');
8174: my ($okstudents,$badstudents,$numstudents,$passed,$failed);
8175: $passed = 0;
8176: $failed = 0;
8177: $numstudents = 0;
8178: foreach my $last (sort(keys(%bylast))) {
8179: if (ref($bylast{$last}) eq 'ARRAY') {
8180: foreach my $pid (sort(@{$bylast{$last}})) {
8181: my $showscandata = $scandata{$pid};
8182: my $showrecord = $record{$pid};
8183: $showscandata =~ s/\s/ /g;
8184: $showrecord =~ s/\s/ /g;
8185: if ($scandata{$pid} eq $record{$pid}) {
8186: my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
8187: $okstudents .= '<tr class="'.$css_class.'">'.
8188: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
8189: '</tr>'."\n".
8190: '<tr class="'.$css_class.'">'."\n".
8191: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
8192: $passed ++;
8193: } else {
8194: my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
8195: $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".
8196: '</tr>'."\n".
8197: '<tr class="'.$css_class.'">'."\n".
8198: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
8199: '</tr>'."\n";
8200: $failed ++;
8201: }
8202: $numstudents ++;
8203: }
8204: }
8205: }
8206: $r->print('<p>'.&mt('Comparison of bubblesheet data (including corrections) with corresponding submission records (most recent submission) for <b>[quant,_1,student]</b> ([_2] scantron lines/student).',$numstudents,$env{'form.scantron_maxbubble'}).'</p>');
8207: $r->print('<p>'.&mt('Exact matches for <b>[quant,_1,student]</b>.',$passed).'<br />'.&mt('Discrepancies detected for <b>[quant,_1,student]</b>.',$failed).'</p>');
8208: if ($passed) {
8209: $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
8210: $r->print(&Apache::loncommon::start_data_table()."\n".
8211: &Apache::loncommon::start_data_table_header_row()."\n".
8212: '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
8213: &Apache::loncommon::end_data_table_header_row()."\n".
8214: $okstudents."\n".
8215: &Apache::loncommon::end_data_table().'<br />');
8216: }
8217: if ($failed) {
8218: $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
8219: $r->print(&Apache::loncommon::start_data_table()."\n".
8220: &Apache::loncommon::start_data_table_header_row()."\n".
8221: '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
8222: &Apache::loncommon::end_data_table_header_row()."\n".
8223: $badstudents."\n".
8224: &Apache::loncommon::end_data_table()).'<br />'.
8225: &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.');
8226: }
8227: $r->print('</form><br />');
8228: return;
8229: }
8230:
8231: sub verify_scantron_grading {
8232: my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
8233: $scantron_config,$lettdig,$numletts) = @_;
8234: my ($record,%expected,%startpos);
8235: return ($counter,$record) if (!ref($resource));
8236: return ($counter,$record) if (!$resource->is_problem());
8237: my $symb = $resource->symb();
8238: return ($counter,$record) if (ref($partids) ne 'ARRAY');
8239: foreach my $part_id (@{$partids}) {
8240: $counter ++;
8241: $expected{$part_id} = 0;
8242: if ($env{"form.scantron.sub_bubblelines.$counter"}) {
8243: my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
8244: foreach my $item (@sub_lines) {
8245: $expected{$part_id} += $item;
8246: }
8247: } else {
8248: $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
8249: }
8250: $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
8251: }
8252: if ($symb) {
8253: my %recorded;
8254: my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
8255: if ($returnhash{'version'}) {
8256: my %lasthash=();
8257: my $version;
8258: for ($version=1;$version<=$returnhash{'version'};$version++) {
8259: foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
8260: $lasthash{$key}=$returnhash{$version.':'.$key};
8261: }
8262: }
8263: foreach my $key (keys(%lasthash)) {
8264: if ($key =~ /\.scantron$/) {
8265: my $value = &unescape($lasthash{$key});
8266: my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
8267: if ($value eq '') {
8268: for (my $i=0; $i<$expected{$part_id}; $i++) {
8269: for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
8270: $recorded{$part_id} .= $scantron_config->{'Qoff'};
8271: }
8272: }
8273: } else {
8274: my @tocheck;
8275: my @items = split(//,$value);
8276: if (($scantron_config->{'Qon'} eq 'letter') ||
8277: ($scantron_config->{'Qon'} eq 'number')) {
8278: if (@items < $expected{$part_id}) {
8279: my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
8280: my @singles = split(//,$fragment);
8281: foreach my $pos (@singles) {
8282: if ($pos eq ' ') {
8283: push(@tocheck,$pos);
8284: } else {
8285: my $next = shift(@items);
8286: push(@tocheck,$next);
8287: }
8288: }
8289: } else {
8290: @tocheck = @items;
8291: }
8292: foreach my $letter (@tocheck) {
8293: if ($scantron_config->{'Qon'} eq 'letter') {
8294: if ($letter !~ /^[A-J]$/) {
8295: $letter = $scantron_config->{'Qoff'};
8296: }
8297: $recorded{$part_id} .= $letter;
8298: } elsif ($scantron_config->{'Qon'} eq 'number') {
8299: my $digit;
8300: if ($letter !~ /^[A-J]$/) {
8301: $digit = $scantron_config->{'Qoff'};
8302: } else {
8303: $digit = $lettdig->{$letter};
8304: }
8305: $recorded{$part_id} .= $digit;
8306: }
8307: }
8308: } else {
8309: @tocheck = @items;
8310: for (my $i=0; $i<$expected{$part_id}; $i++) {
8311: my $curr_sub = shift(@tocheck);
8312: my $digit;
8313: if ($curr_sub =~ /^[A-J]$/) {
8314: $digit = $lettdig->{$curr_sub}-1;
8315: }
8316: if ($curr_sub eq 'J') {
8317: $digit += scalar($numletts);
8318: }
8319: for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
8320: if ($j == $digit) {
8321: $recorded{$part_id} .= $scantron_config->{'Qon'};
8322: } else {
8323: $recorded{$part_id} .= $scantron_config->{'Qoff'};
8324: }
8325: }
8326: }
8327: }
8328: }
8329: }
8330: }
8331: }
8332: foreach my $part_id (@{$partids}) {
8333: if ($recorded{$part_id} eq '') {
8334: for (my $i=0; $i<$expected{$part_id}; $i++) {
8335: for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
8336: $recorded{$part_id} .= $scantron_config->{'Qoff'};
8337: }
8338: }
8339: }
8340: $record .= $recorded{$part_id};
8341: }
8342: }
8343: return ($counter,$record);
8344: }
8345:
8346: sub letter_to_digits {
8347: my %lettdig = (
8348: A => 1,
8349: B => 2,
8350: C => 3,
8351: D => 4,
8352: E => 5,
8353: F => 6,
8354: G => 7,
8355: H => 8,
8356: I => 9,
8357: J => 0,
8358: );
8359: return %lettdig;
8360: }
8361:
8362:
8363: #-------- end of section for handling grading scantron forms -------
8364: #
8365: #-------------------------------------------------------------------
8366:
8367: #-------------------------- Menu interface -------------------------
8368: #
8369: #--- Href with symb and command ---
8370:
8371: sub href_symb_cmd {
8372: my ($symb,$cmd)=@_;
8373: return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&command='.$cmd;
8374: }
8375:
8376: sub grading_menu {
8377: my ($request,$symb) = @_;
8378: if (!$symb) {return '';}
8379:
8380: my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
8381: 'command'=>'individual');
8382:
8383: my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
8384:
8385: $fields{'command'}='ungraded';
8386: my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
8387:
8388: $fields{'command'}='table';
8389: my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
8390:
8391: $fields{'command'}='all_for_one';
8392: my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
8393:
8394: $fields{'command'}='downloadfilesselect';
8395: my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
8396:
8397: $fields{'command'} = 'csvform';
8398: my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
8399:
8400: $fields{'command'} = 'processclicker';
8401: my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
8402:
8403: $fields{'command'} = 'scantron_selectphase';
8404: my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
8405:
8406: $fields{'command'} = 'initialverifyreceipt';
8407: my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
8408:
8409: my @menu = ({ categorytitle=>'Hand Grading',
8410: items =>[
8411: { linktext => 'Select individual students to grade',
8412: url => $url1a,
8413: permission => 'F',
8414: icon => 'edit-find-replace.png',
8415: linktitle => 'Grade current resource for a selection of students.'
8416: },
8417: { linktext => 'Grade ungraded submissions.',
8418: url => $url1b,
8419: permission => 'F',
8420: icon => 'edit-find-replace.png',
8421: linktitle => 'Grade all submissions that have not been graded yet.'
8422: },
8423:
8424: { linktext => 'Grading table',
8425: url => $url1c,
8426: permission => 'F',
8427: icon => 'edit-find-replace.png',
8428: linktitle => 'Grade current resource for all students.'
8429: },
8430: { linktext => 'Grade page/folder for one student',
8431: url => $url1d,
8432: permission => 'F',
8433: icon => 'edit-find-replace.png',
8434: linktitle => 'Grade all resources in current page/sequence/folder for one student.'
8435: },
8436: { linktext => 'Download submissions',
8437: url => $url1e,
8438: permission => 'F',
8439: icon => 'edit-find-replace.png',
8440: linktitle => 'Download all students submissions.'
8441: }]},
8442: { categorytitle=>'Automated Grading',
8443: items =>[
8444:
8445: { linktext => 'Upload Scores',
8446: url => $url2,
8447: permission => 'F',
8448: icon => 'uploadscores.png',
8449: linktitle => 'Specify a file containing the class scores for current resource.'
8450: },
8451: { linktext => 'Process Clicker',
8452: url => $url3,
8453: permission => 'F',
8454: icon => 'addClickerInfoFile.png',
8455: linktitle => 'Specify a file containing the clicker information for this resource.'
8456: },
8457: { linktext => 'Grade/Manage/Review Bubblesheets',
8458: url => $url4,
8459: permission => 'F',
8460: icon => 'stat.png',
8461: linktitle => 'Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.'
8462: },
8463: { linktext => 'Verify Receipt Number',
8464: url => $url5,
8465: permission => 'F',
8466: icon => 'edit-find-replace.png',
8467: linktitle => 'Verify a system-generated receipt number for correct problem solution.'
8468: }
8469:
8470: ]
8471: });
8472:
8473: # Create the menu
8474: my $Str;
8475: $Str .= '<form method="post" action="" name="gradingMenu">';
8476: $Str .= '<input type="hidden" name="command" value="" />'.
8477: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
8478:
8479: $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
8480: return $Str;
8481: }
8482:
8483:
8484: sub ungraded {
8485: my ($request)=@_;
8486: &submit_options($request);
8487: }
8488:
8489: sub submit_options_sequence {
8490: my ($request,$symb) = @_;
8491: if (!$symb) {return '';}
8492: &commonJSfunctions($request);
8493: my $result;
8494:
8495: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
8496: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
8497: $result.='
8498: <h2>
8499: '.&mt('Grade page/folder for one student').'
8500: </h2>'.
8501: &selectfield(0).
8502: '<input type="hidden" name="command" value="pickStudentPage" />
8503: <div>
8504: <input type="submit" value="'.&mt('Next').' →" />
8505: </div>
8506: </div>
8507: </form>';
8508: return $result;
8509: }
8510:
8511: sub submit_options_table {
8512: my ($request,$symb) = @_;
8513: if (!$symb) {return '';}
8514: &commonJSfunctions($request);
8515: my $result;
8516:
8517: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
8518: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
8519:
8520: $result.='
8521: <h2>
8522: '.&mt('Grading table').'
8523: </h2>'.
8524: &selectfield(0).
8525: '<input type="hidden" name="command" value="viewgrades" />
8526: <div>
8527: <input type="submit" value="'.&mt('Next').' →" />
8528: </div>
8529: </div>
8530: </form>';
8531: return $result;
8532: }
8533:
8534: sub submit_options_download {
8535: my ($request,$symb) = @_;
8536: if (!$symb) {return '';}
8537:
8538: &commonJSfunctions($request);
8539:
8540: my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
8541: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
8542: $result.='
8543: <h2>
8544: '.&mt('Select Students for Which to Download Submissions').'
8545: </h2>'.&selectfield(1).'
8546: <input type="hidden" name="command" value="downloadfileslink" />
8547: <input type="submit" value="'.&mt('Next').' →" />
8548: </div>
8549: </div>
8550:
8551:
8552: </form>';
8553: return $result;
8554: }
8555:
8556: #--- Displays the submissions first page -------
8557: sub submit_options {
8558: my ($request,$symb) = @_;
8559: if (!$symb) {return '';}
8560:
8561: &commonJSfunctions($request);
8562: my $result;
8563:
8564: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
8565: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
8566: $result.='
8567: <h2>
8568: '.&mt('Select individual students to grade').'
8569: </h2>'.&selectfield(1).'
8570: <input type="hidden" name="command" value="submission" />
8571: <input type="submit" value="'.&mt('Next').' →" />
8572: </div>
8573: </div>
8574:
8575:
8576: </form>';
8577: return $result;
8578: }
8579:
8580: sub selectfield {
8581: my ($full)=@_;
8582: my $result='<div class="LC_columnSection">
8583:
8584: <fieldset>
8585: <legend>
8586: '.&mt('Sections').'
8587: </legend>
8588: '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
8589: </fieldset>
8590:
8591: <fieldset>
8592: <legend>
8593: '.&mt('Groups').'
8594: </legend>
8595: '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
8596: </fieldset>
8597:
8598: <fieldset>
8599: <legend>
8600: '.&mt('Access Status').'
8601: </legend>
8602: '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
8603: </fieldset>';
8604: if ($full) {
8605: $result.='
8606: <fieldset>
8607: <legend>
8608: '.&mt('Submission Status').'
8609: </legend>'.
8610: &Apache::loncommon::select_form('all','submitonly',
8611: (&Apache::lonlocal::texthash(
8612: 'yes' => 'with submissions',
8613: 'queued' => 'in grading queue',
8614: 'graded' => 'with ungraded submissions',
8615: 'incorrect' => 'with incorrect submissions',
8616: 'all' => 'with any status'),
8617: 'select_form_order' => ['yes','queued','graded','incorrect','all'])).
8618: '</fieldset>';
8619: }
8620: $result.='</div><br />';
8621: return $result;
8622: }
8623:
8624: sub reset_perm {
8625: undef(%perm);
8626: }
8627:
8628: sub init_perm {
8629: &reset_perm();
8630: foreach my $test_perm ('vgr','mgr','opa') {
8631:
8632: my $scope = $env{'request.course.id'};
8633: if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
8634:
8635: $scope .= '/'.$env{'request.course.sec'};
8636: if ( $perm{$test_perm}=
8637: &Apache::lonnet::allowed($test_perm,$scope)) {
8638: $perm{$test_perm.'_section'}=$env{'request.course.sec'};
8639: } else {
8640: delete($perm{$test_perm});
8641: }
8642: }
8643: }
8644: }
8645:
8646: sub gather_clicker_ids {
8647: my %clicker_ids;
8648:
8649: my $classlist = &Apache::loncoursedata::get_classlist();
8650:
8651: # Set up a couple variables.
8652: my $username_idx = &Apache::loncoursedata::CL_SNAME();
8653: my $domain_idx = &Apache::loncoursedata::CL_SDOM();
8654: my $status_idx = &Apache::loncoursedata::CL_STATUS();
8655:
8656: foreach my $student (keys(%$classlist)) {
8657: if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
8658: my $username = $classlist->{$student}->[$username_idx];
8659: my $domain = $classlist->{$student}->[$domain_idx];
8660: my $clickers =
8661: (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
8662: foreach my $id (split(/\,/,$clickers)) {
8663: $id=~s/^[\#0]+//;
8664: $id=~s/[\-\:]//g;
8665: if (exists($clicker_ids{$id})) {
8666: $clicker_ids{$id}.=','.$username.':'.$domain;
8667: } else {
8668: $clicker_ids{$id}=$username.':'.$domain;
8669: }
8670: }
8671: }
8672: return %clicker_ids;
8673: }
8674:
8675: sub gather_adv_clicker_ids {
8676: my %clicker_ids;
8677: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
8678: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
8679: my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
8680: foreach my $element (sort(keys(%coursepersonnel))) {
8681: foreach my $person (split(/\,/,$coursepersonnel{$element})) {
8682: my ($puname,$pudom)=split(/\:/,$person);
8683: my $clickers =
8684: (&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
8685: foreach my $id (split(/\,/,$clickers)) {
8686: $id=~s/^[\#0]+//;
8687: $id=~s/[\-\:]//g;
8688: if (exists($clicker_ids{$id})) {
8689: $clicker_ids{$id}.=','.$puname.':'.$pudom;
8690: } else {
8691: $clicker_ids{$id}=$puname.':'.$pudom;
8692: }
8693: }
8694: }
8695: }
8696: return %clicker_ids;
8697: }
8698:
8699: sub clicker_grading_parameters {
8700: return ('gradingmechanism' => 'scalar',
8701: 'upfiletype' => 'scalar',
8702: 'specificid' => 'scalar',
8703: 'pcorrect' => 'scalar',
8704: 'pincorrect' => 'scalar');
8705: }
8706:
8707: sub process_clicker {
8708: my ($r,$symb)=@_;
8709: if (!$symb) {return '';}
8710: my $result=&checkforfile_js();
8711: $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
8712: $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
8713: $result.=' <b>'.&mt('Specify a file containing the clicker information for this resource.').
8714: '</b></td></tr>'."\n";
8715: $result.='<tr bgcolor="#ffffe6"><td>'."\n";
8716: # Attempt to restore parameters from last session, set defaults if not present
8717: my %Saveable_Parameters=&clicker_grading_parameters();
8718: &Apache::loncommon::restore_course_settings('grades_clicker',
8719: \%Saveable_Parameters);
8720: if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
8721: if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
8722: if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
8723: if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
8724:
8725: my %checked;
8726: foreach my $gradingmechanism ('attendance','personnel','specific','given') {
8727: if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
8728: $checked{$gradingmechanism}=' checked="checked"';
8729: }
8730: }
8731:
8732: my $upload=&mt("Upload File");
8733: my $type=&mt("Type");
8734: my $attendance=&mt("Award points just for participation");
8735: my $personnel=&mt("Correctness determined from response by course personnel");
8736: my $specific=&mt("Correctness determined from response with clicker ID(s)");
8737: my $given=&mt("Correctness determined from given list of answers").' '.
8738: '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
8739: my $pcorrect=&mt("Percentage points for correct solution");
8740: my $pincorrect=&mt("Percentage points for incorrect solution");
8741: my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
8742: ('iclicker' => 'i>clicker',
8743: 'interwrite' => 'interwrite PRS'));
8744: $symb = &Apache::lonenc::check_encrypt($symb);
8745: $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
8746: function sanitycheck() {
8747: // Accept only integer percentages
8748: document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
8749: document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
8750: // Find out grading choice
8751: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
8752: if (document.forms.gradesupload.gradingmechanism[i].checked) {
8753: gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
8754: }
8755: }
8756: // By default, new choice equals user selection
8757: newgradingchoice=gradingchoice;
8758: // Not good to give more points for false answers than correct ones
8759: if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
8760: document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
8761: }
8762: // If new choice is attendance only, and old choice was correctness-based, restore defaults
8763: if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
8764: document.forms.gradesupload.pcorrect.value=100;
8765: document.forms.gradesupload.pincorrect.value=100;
8766: }
8767: // If the values are different, cannot be attendance only
8768: if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
8769: (gradingchoice=='attendance')) {
8770: newgradingchoice='personnel';
8771: }
8772: // Change grading choice to new one
8773: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
8774: if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
8775: document.forms.gradesupload.gradingmechanism[i].checked=true;
8776: } else {
8777: document.forms.gradesupload.gradingmechanism[i].checked=false;
8778: }
8779: }
8780: // Remember the old state
8781: document.forms.gradesupload.waschecked.value=newgradingchoice;
8782: }
8783: ENDUPFORM
8784: $result.= <<ENDUPFORM;
8785: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
8786: <input type="hidden" name="symb" value="$symb" />
8787: <input type="hidden" name="command" value="processclickerfile" />
8788: <input type="file" name="upfile" size="50" />
8789: <br /><label>$type: $selectform</label>
8790: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
8791: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
8792: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
8793: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
8794: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
8795: <br />
8796: <input type="text" name="givenanswer" size="50" />
8797: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
8798: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
8799: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
8800: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
8801: </form>'
8802: ENDUPFORM
8803: $result.='</td></tr></table>'."\n".
8804: '</td></tr></table><br /><br />'."\n";
8805: return $result;
8806: }
8807:
8808: sub process_clicker_file {
8809: my ($r,$symb)=@_;
8810: if (!$symb) {return '';}
8811:
8812: my %Saveable_Parameters=&clicker_grading_parameters();
8813: &Apache::loncommon::store_course_settings('grades_clicker',
8814: \%Saveable_Parameters);
8815: my $result='';
8816: if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
8817: $result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
8818: return $result;
8819: }
8820: if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
8821: $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
8822: return $result;
8823: }
8824: my $foundgiven=0;
8825: if ($env{'form.gradingmechanism'} eq 'given') {
8826: $env{'form.givenanswer'}=~s/^\s*//gs;
8827: $env{'form.givenanswer'}=~s/\s*$//gs;
8828: $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
8829: $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
8830: my @answers=split(/\,/,$env{'form.givenanswer'});
8831: $foundgiven=$#answers+1;
8832: }
8833: my %clicker_ids=&gather_clicker_ids();
8834: my %correct_ids;
8835: if ($env{'form.gradingmechanism'} eq 'personnel') {
8836: %correct_ids=&gather_adv_clicker_ids();
8837: }
8838: if ($env{'form.gradingmechanism'} eq 'specific') {
8839: foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
8840: $correct_id=~tr/a-z/A-Z/;
8841: $correct_id=~s/\s//gs;
8842: $correct_id=~s/^[\#0]+//;
8843: $correct_id=~s/[\-\:]//g;
8844: if ($correct_id) {
8845: $correct_ids{$correct_id}='specified';
8846: }
8847: }
8848: }
8849: if ($env{'form.gradingmechanism'} eq 'attendance') {
8850: $result.=&mt('Score based on attendance only');
8851: } elsif ($env{'form.gradingmechanism'} eq 'given') {
8852: $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
8853: } else {
8854: my $number=0;
8855: $result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
8856: foreach my $id (sort(keys(%correct_ids))) {
8857: $result.='<br /><tt>'.$id.'</tt> - ';
8858: if ($correct_ids{$id} eq 'specified') {
8859: $result.=&mt('specified');
8860: } else {
8861: my ($uname,$udom)=split(/\:/,$correct_ids{$id});
8862: $result.=&Apache::loncommon::plainname($uname,$udom);
8863: }
8864: $number++;
8865: }
8866: $result.="</p>\n";
8867: if ($number==0) {
8868: $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
8869: return $result;
8870: }
8871: }
8872: if (length($env{'form.upfile'}) < 2) {
8873: $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
8874: '<span class="LC_error">',
8875: '</span>',
8876: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
8877: return $result;
8878: }
8879:
8880: # Were able to get all the info needed, now analyze the file
8881:
8882: $result.=&Apache::loncommon::studentbrowser_javascript();
8883: $symb = &Apache::lonenc::check_encrypt($symb);
8884: my $heading=&mt('Scanning clicker file');
8885: $result.=(<<ENDHEADER);
8886: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
8887: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
8888: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
8889: <form method="post" action="/adm/grades" name="clickeranalysis">
8890: <input type="hidden" name="symb" value="$symb" />
8891: <input type="hidden" name="command" value="assignclickergrades" />
8892: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
8893: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
8894: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
8895: ENDHEADER
8896: if ($env{'form.gradingmechanism'} eq 'given') {
8897: $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
8898: }
8899: my %responses;
8900: my @questiontitles;
8901: my $errormsg='';
8902: my $number=0;
8903: if ($env{'form.upfiletype'} eq 'iclicker') {
8904: ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
8905: }
8906: if ($env{'form.upfiletype'} eq 'interwrite') {
8907: ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
8908: }
8909: $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
8910: '<input type="hidden" name="number" value="'.$number.'" />'.
8911: &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
8912: $env{'form.pcorrect'},$env{'form.pincorrect'}).
8913: '<br />';
8914: if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
8915: $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
8916: return $result;
8917: }
8918: # Remember Question Titles
8919: # FIXME: Possibly need delimiter other than ":"
8920: for (my $i=0;$i<$number;$i++) {
8921: $result.='<input type="hidden" name="question:'.$i.'" value="'.
8922: &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
8923: }
8924: my $correct_count=0;
8925: my $student_count=0;
8926: my $unknown_count=0;
8927: # Match answers with usernames
8928: # FIXME: Possibly need delimiter other than ":"
8929: foreach my $id (keys(%responses)) {
8930: if ($correct_ids{$id}) {
8931: $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
8932: $correct_count++;
8933: } elsif ($clicker_ids{$id}) {
8934: if ($clicker_ids{$id}=~/\,/) {
8935: # More than one user with the same clicker!
8936: $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
8937: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
8938: "<select name='multi".$id."'>";
8939: foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
8940: $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
8941: }
8942: $result.='</select>';
8943: $unknown_count++;
8944: } else {
8945: # Good: found one and only one user with the right clicker
8946: $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
8947: $student_count++;
8948: }
8949: } else {
8950: $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
8951: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
8952: "\n".&mt("Username").": <input type='text' name='uname".$id."' /> ".
8953: "\n".&mt("Domain").": ".
8954: &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).' '.
8955: &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
8956: $unknown_count++;
8957: }
8958: }
8959: $result.='<hr />'.
8960: &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
8961: if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
8962: if ($correct_count==0) {
8963: $errormsg.="Found no correct answers answers for grading!";
8964: } elsif ($correct_count>1) {
8965: $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
8966: }
8967: }
8968: if ($number<1) {
8969: $errormsg.="Found no questions.";
8970: }
8971: if ($errormsg) {
8972: $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
8973: } else {
8974: $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
8975: }
8976: $result.='</form></td></tr></table>'."\n".
8977: '</td></tr></table><br /><br />'."\n";
8978: return $result;
8979: }
8980:
8981: sub iclicker_eval {
8982: my ($questiontitles,$responses)=@_;
8983: my $number=0;
8984: my $errormsg='';
8985: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
8986: my %components=&Apache::loncommon::record_sep($line);
8987: my @entries=map {$components{$_}} (sort(keys(%components)));
8988: if ($entries[0] eq 'Question') {
8989: for (my $i=3;$i<$#entries;$i+=6) {
8990: $$questiontitles[$number]=$entries[$i];
8991: $number++;
8992: }
8993: }
8994: if ($entries[0]=~/^\#/) {
8995: my $id=$entries[0];
8996: my @idresponses;
8997: $id=~s/^[\#0]+//;
8998: for (my $i=0;$i<$number;$i++) {
8999: my $idx=3+$i*6;
9000: push(@idresponses,$entries[$idx]);
9001: }
9002: $$responses{$id}=join(',',@idresponses);
9003: }
9004: }
9005: return ($errormsg,$number);
9006: }
9007:
9008: sub interwrite_eval {
9009: my ($questiontitles,$responses)=@_;
9010: my $number=0;
9011: my $errormsg='';
9012: my $skipline=1;
9013: my $questionnumber=0;
9014: my %idresponses=();
9015: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
9016: my %components=&Apache::loncommon::record_sep($line);
9017: my @entries=map {$components{$_}} (sort(keys(%components)));
9018: if ($entries[1] eq 'Time') { $skipline=0; next; }
9019: if ($entries[1] eq 'Response') { $skipline=1; }
9020: next if $skipline;
9021: if ($entries[0]!=$questionnumber) {
9022: $questionnumber=$entries[0];
9023: $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
9024: $number++;
9025: }
9026: my $id=$entries[4];
9027: $id=~s/^[\#0]+//;
9028: $id=~s/^v\d*\://i;
9029: $id=~s/[\-\:]//g;
9030: $idresponses{$id}[$number]=$entries[6];
9031: }
9032: foreach my $id (keys(%idresponses)) {
9033: $$responses{$id}=join(',',@{$idresponses{$id}});
9034: $$responses{$id}=~s/^\s*\,//;
9035: }
9036: return ($errormsg,$number);
9037: }
9038:
9039: sub assign_clicker_grades {
9040: my ($r,$symb)=@_;
9041: if (!$symb) {return '';}
9042: # See which part we are saving to
9043: my $res_error;
9044: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
9045: if ($res_error) {
9046: return &navmap_errormsg();
9047: }
9048: # FIXME: This should probably look for the first handgradeable part
9049: my $part=$$partlist[0];
9050: # Start screen output
9051: my $result='';
9052:
9053: my $heading=&mt('Assigning grades based on clicker file');
9054: $result.=(<<ENDHEADER);
9055: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
9056: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
9057: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
9058: ENDHEADER
9059: # Get correct result
9060: # FIXME: Possibly need delimiter other than ":"
9061: my @correct=();
9062: my $gradingmechanism=$env{'form.gradingmechanism'};
9063: my $number=$env{'form.number'};
9064: if ($gradingmechanism ne 'attendance') {
9065: foreach my $key (keys(%env)) {
9066: if ($key=~/^form\.correct\:/) {
9067: my @input=split(/\,/,$env{$key});
9068: for (my $i=0;$i<=$#input;$i++) {
9069: if (($correct[$i]) && ($input[$i]) &&
9070: ($correct[$i] ne $input[$i])) {
9071: $result.='<br /><span class="LC_warning">'.
9072: &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
9073: $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
9074: } elsif ($input[$i]) {
9075: $correct[$i]=$input[$i];
9076: }
9077: }
9078: }
9079: }
9080: for (my $i=0;$i<$number;$i++) {
9081: if (!$correct[$i]) {
9082: $result.='<br /><span class="LC_error">'.
9083: &mt('No correct result given for question "[_1]"!',
9084: $env{'form.question:'.$i}).'</span>';
9085: }
9086: }
9087: $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
9088: }
9089: # Start grading
9090: my $pcorrect=$env{'form.pcorrect'};
9091: my $pincorrect=$env{'form.pincorrect'};
9092: my $storecount=0;
9093: foreach my $key (keys(%env)) {
9094: my $user='';
9095: if ($key=~/^form\.student\:(.*)$/) {
9096: $user=$1;
9097: }
9098: if ($key=~/^form\.unknown\:(.*)$/) {
9099: my $id=$1;
9100: if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
9101: $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
9102: } elsif ($env{'form.multi'.$id}) {
9103: $user=$env{'form.multi'.$id};
9104: }
9105: }
9106: if ($user) {
9107: my @answer=split(/\,/,$env{$key});
9108: my $sum=0;
9109: my $realnumber=$number;
9110: for (my $i=0;$i<$number;$i++) {
9111: if ($correct[$i] eq '-') {
9112: $realnumber--;
9113: } elsif ($answer[$i]) {
9114: if ($gradingmechanism eq 'attendance') {
9115: $sum+=$pcorrect;
9116: } elsif ($correct[$i] eq '*') {
9117: $sum+=$pcorrect;
9118: } else {
9119: if ($answer[$i] eq $correct[$i]) {
9120: $sum+=$pcorrect;
9121: } else {
9122: $sum+=$pincorrect;
9123: }
9124: }
9125: }
9126: }
9127: my $ave=$sum/(100*$realnumber);
9128: # Store
9129: my ($username,$domain)=split(/\:/,$user);
9130: my %grades=();
9131: $grades{"resource.$part.solved"}='correct_by_override';
9132: $grades{"resource.$part.awarded"}=$ave;
9133: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
9134: my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
9135: $env{'request.course.id'},
9136: $domain,$username);
9137: if ($returncode ne 'ok') {
9138: $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
9139: } else {
9140: $storecount++;
9141: }
9142: }
9143: }
9144: # We are done
9145: $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
9146: '</td></tr></table>'."\n".
9147: '</td></tr></table><br /><br />'."\n";
9148: return $result;
9149: }
9150:
9151: sub navmap_errormsg {
9152: return '<div class="LC_error">'.
9153: &mt('An error occurred retrieving information about resources in the course.').'<br />'.
9154: &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>').
9155: '</div>';
9156: }
9157:
9158: sub startpage {
9159: my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag) = @_;
9160: unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
9161: $r->print(&Apache::loncommon::start_page('Grading',undef,
9162: {'bread_crumbs' => $crumbs}));
9163: unless ($nodisplayflag) {
9164: $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag));
9165: }
9166: }
9167:
9168: sub select_problem {
9169: my ($r)=@_;
9170: $r->print('<h2>'.&mt('Select the problem or one of the problems you want to grade').'</h2><form action="/adm/grades">');
9171: $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
9172: $r->print('<input type="hidden" name="command" value="gradingmenu" />');
9173: $r->print('<input type="submit" value="'.&mt('Next').' →" /></form>');
9174: }
9175:
9176: sub handler {
9177: my $request=$_[0];
9178: &reset_caches();
9179: if ($env{'browser.mathml'}) {
9180: &Apache::loncommon::content_type($request,'text/xml');
9181: } else {
9182: &Apache::loncommon::content_type($request,'text/html');
9183: }
9184: $request->send_http_header;
9185: return '' if $request->header_only;
9186: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
9187:
9188: # see what command we need to execute
9189:
9190: my @commands=&Apache::loncommon::get_env_multiple('form.command');
9191: my $command=$commands[0];
9192:
9193: if ($#commands > 0) {
9194: &Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
9195: }
9196:
9197: # see what the symb is
9198:
9199: my $symb=$env{'form.symb'};
9200: unless ($symb) {
9201: (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
9202: $symb=&Apache::lonnet::symbread($url);
9203: }
9204: &Apache::lonenc::check_decrypt(\$symb);
9205:
9206: $ssi_error = 0;
9207: if ($symb eq '' || $command eq '') {
9208: #
9209: # Not called from a resource
9210: #
9211: &startpage($request,undef,[],1,1);
9212: &select_problem($request);
9213: } else {
9214: &init_perm();
9215: if ($command eq 'submission' && $perm{'vgr'}) {
9216: &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}]);
9217: ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
9218: } elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
9219: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
9220: {href=>'',text=>'Select student'}],1,1);
9221: &pickStudentPage($request,$symb);
9222: } elsif ($command eq 'displayPage' && $perm{'vgr'}) {
9223: &startpage($request,$symb,
9224: [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
9225: {href=>'',text=>'Select student'},
9226: {href=>'',text=>'Grade student'}],1,1);
9227: &displayPage($request,$symb);
9228: } elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
9229: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
9230: {href=>'',text=>'Select student'},
9231: {href=>'',text=>'Grade student'},
9232: {href=>'',text=>'Store grades'}],1,1);
9233: &updateGradeByPage($request,$symb);
9234: } elsif ($command eq 'processGroup' && $perm{'vgr'}) {
9235: &startpage($request,$symb,[{href=>'',text=>'...'},
9236: {href=>'',text=>'Modify grades'}]);
9237: &processGroup($request,$symb);
9238: } elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
9239: &startpage($request,$symb);
9240: $request->print(&grading_menu($request,$symb));
9241: } elsif ($command eq 'individual' && $perm{'vgr'}) {
9242: &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
9243: $request->print(&submit_options($request,$symb));
9244: } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
9245: &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
9246: $request->print(&listStudents($request,$symb,'graded'));
9247: } elsif ($command eq 'table' && $perm{'vgr'}) {
9248: &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
9249: $request->print(&submit_options_table($request,$symb));
9250: } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
9251: &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
9252: $request->print(&submit_options_sequence($request,$symb));
9253: } elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
9254: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
9255: $request->print(&viewgrades($request,$symb));
9256: } elsif ($command eq 'handgrade' && $perm{'mgr'}) {
9257: &startpage($request,$symb,[{href=>'',text=>'...'},
9258: {href=>'',text=>'Store grades'}]);
9259: $request->print(&processHandGrade($request,$symb));
9260: } elsif ($command eq 'editgrades' && $perm{'mgr'}) {
9261: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
9262: {href=>&href_symb_cmd($symb,'viewgrades').'&group=all§ion=all&Status=Active',
9263: text=>"Modify grades"},
9264: {href=>'', text=>"Store grades"}]);
9265: $request->print(&editgrades($request,$symb));
9266: } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
9267: &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
9268: $request->print(&initialverifyreceipt($request,$symb));
9269: } elsif ($command eq 'verify' && $perm{'vgr'}) {
9270: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
9271: {href=>'',text=>'Verification Result'}]);
9272: $request->print(&verifyreceipt($request,$symb));
9273: } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
9274: &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
9275: $request->print(&process_clicker($request,$symb));
9276: } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
9277: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
9278: {href=>'', text=>'Process clicker file'}]);
9279: $request->print(&process_clicker_file($request,$symb));
9280: } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
9281: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
9282: {href=>'', text=>'Process clicker file'},
9283: {href=>'', text=>'Store grades'}]);
9284: $request->print(&assign_clicker_grades($request,$symb));
9285: } elsif ($command eq 'csvform' && $perm{'mgr'}) {
9286: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
9287: $request->print(&upcsvScores_form($request,$symb));
9288: } elsif ($command eq 'csvupload' && $perm{'mgr'}) {
9289: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
9290: $request->print(&csvupload($request,$symb));
9291: } elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
9292: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
9293: $request->print(&csvuploadmap($request,$symb));
9294: } elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
9295: if ($env{'form.associate'} ne 'Reverse Association') {
9296: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
9297: $request->print(&csvuploadoptions($request,$symb));
9298: } else {
9299: if ( $env{'form.upfile_associate'} ne 'reverse' ) {
9300: $env{'form.upfile_associate'} = 'reverse';
9301: } else {
9302: $env{'form.upfile_associate'} = 'forward';
9303: }
9304: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
9305: $request->print(&csvuploadmap($request,$symb));
9306: }
9307: } elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
9308: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
9309: $request->print(&csvuploadassign($request,$symb));
9310: } elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
9311: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9312: $request->print(&scantron_selectphase($request,undef,$symb));
9313: } elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
9314: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9315: $request->print(&scantron_do_warning($request,$symb));
9316: } elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
9317: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9318: $request->print(&scantron_validate_file($request,$symb));
9319: } elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
9320: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9321: $request->print(&scantron_process_students($request,$symb));
9322: } elsif ($command eq 'scantronupload' &&
9323: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
9324: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
9325: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9326: $request->print(&scantron_upload_scantron_data($request,$symb));
9327: } elsif ($command eq 'scantronupload_save' &&
9328: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
9329: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
9330: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9331: $request->print(&scantron_upload_scantron_data_save($request,$symb));
9332: } elsif ($command eq 'scantron_download' &&
9333: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
9334: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9335: $request->print(&scantron_download_scantron_data($request,$symb));
9336: } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
9337: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9338: $request->print(&checkscantron_results($request,$symb));
9339: } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
9340: &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
9341: $request->print(&submit_options_download($request,$symb));
9342: } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
9343: &startpage($request,$symb,
9344: [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
9345: {href=>'', text=>'Download submissions'}]);
9346: &submit_download_link($request,$symb);
9347: } elsif ($command) {
9348: &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
9349: $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
9350: }
9351: }
9352: if ($ssi_error) {
9353: &ssi_print_error($request);
9354: }
9355: $request->print(&Apache::loncommon::end_page());
9356: &reset_caches();
9357: return '';
9358: }
9359:
9360: 1;
9361:
9362: __END__;
9363:
9364:
9365: =head1 NAME
9366:
9367: Apache::grades
9368:
9369: =head1 SYNOPSIS
9370:
9371: Handles the viewing of grades.
9372:
9373: This is part of the LearningOnline Network with CAPA project
9374: described at http://www.lon-capa.org.
9375:
9376: =head1 OVERVIEW
9377:
9378: Do an ssi with retries:
9379: While I'd love to factor out this with the vesrion in lonprintout,
9380: 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
9381: I'm not quite ready to invent (e.g. an ssi_with_retry object).
9382:
9383: At least the logic that drives this has been pulled out into loncommon.
9384:
9385:
9386:
9387: ssi_with_retries - Does the server side include of a resource.
9388: if the ssi call returns an error we'll retry it up to
9389: the number of times requested by the caller.
9390: If we still have a proble, no text is appended to the
9391: output and we set some global variables.
9392: to indicate to the caller an SSI error occurred.
9393: All of this is supposed to deal with the issues described
9394: in LonCAPA BZ 5631 see:
9395: http://bugs.lon-capa.org/show_bug.cgi?id=5631
9396: by informing the user that this happened.
9397:
9398: Parameters:
9399: resource - The resource to include. This is passed directly, without
9400: interpretation to lonnet::ssi.
9401: form - The form hash parameters that guide the interpretation of the resource
9402:
9403: retries - Number of retries allowed before giving up completely.
9404: Returns:
9405: On success, returns the rendered resource identified by the resource parameter.
9406: Side Effects:
9407: The following global variables can be set:
9408: ssi_error - If an unrecoverable error occurred this becomes true.
9409: It is up to the caller to initialize this to false
9410: if desired.
9411: ssi_error_resource - If an unrecoverable error occurred, this is the value
9412: of the resource that could not be rendered by the ssi
9413: call.
9414: ssi_error_message - The error string fetched from the ssi response
9415: in the event of an error.
9416:
9417:
9418: =head1 HANDLER SUBROUTINE
9419:
9420: ssi_with_retries()
9421:
9422: =head1 SUBROUTINES
9423:
9424: =over
9425:
9426: =item scantron_get_correction() :
9427:
9428: Builds the interface screen to interact with the operator to fix a
9429: specific error condition in a specific scanline
9430:
9431: Arguments:
9432: $r - Apache request object
9433: $i - number of the current scanline
9434: $scan_record - hash ref as returned from &scantron_parse_scanline()
9435: $scan_config - hash ref as returned from &get_scantron_config()
9436: $line - full contents of the current scanline
9437: $error - error condition, valid values are
9438: 'incorrectCODE', 'duplicateCODE',
9439: 'doublebubble', 'missingbubble',
9440: 'duplicateID', 'incorrectID'
9441: $arg - extra information needed
9442: For errors:
9443: - duplicateID - paper number that this studentID was seen before on
9444: - duplicateCODE - array ref of the paper numbers this CODE was
9445: seen on before
9446: - incorrectCODE - current incorrect CODE
9447: - doublebubble - array ref of the bubble lines that have double
9448: bubble errors
9449: - missingbubble - array ref of the bubble lines that have missing
9450: bubble errors
9451:
9452: =item scantron_get_maxbubble() :
9453:
9454: Arguments:
9455: $nav_error - Reference to scalar which is a flag to indicate a
9456: failure to retrieve a navmap object.
9457: if $nav_error is set to 1 by scantron_get_maxbubble(), the
9458: calling routine should trap the error condition and display the warning
9459: found in &navmap_errormsg().
9460:
9461: Returns the maximum number of bubble lines that are expected to
9462: occur. Does this by walking the selected sequence rendering the
9463: resource and then checking &Apache::lonxml::get_problem_counter()
9464: for what the current value of the problem counter is.
9465:
9466: Caches the results to $env{'form.scantron_maxbubble'},
9467: $env{'form.scantron.bubble_lines.n'},
9468: $env{'form.scantron.first_bubble_line.n'} and
9469: $env{"form.scantron.sub_bubblelines.n"}
9470: which are the total number of bubble, lines, the number of bubble
9471: lines for response n and number of the first bubble line for response n,
9472: and a comma separated list of numbers of bubble lines for sub-questions
9473: (for optionresponse, matchresponse, and rankresponse items), for response n.
9474:
9475:
9476: =item scantron_validate_missingbubbles() :
9477:
9478: Validates all scanlines in the selected file to not have any
9479: answers that don't have bubbles that have not been verified
9480: to be bubble free.
9481:
9482: =item scantron_process_students() :
9483:
9484: Routine that does the actual grading of the bubble sheet information.
9485:
9486: The parsed scanline hash is added to %env
9487:
9488: Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
9489: foreach resource , with the form data of
9490:
9491: 'submitted' =>'scantron'
9492: 'grade_target' =>'grade',
9493: 'grade_username'=> username of student
9494: 'grade_domain' => domain of student
9495: 'grade_courseid'=> of course
9496: 'grade_symb' => symb of resource to grade
9497:
9498: This triggers a grading pass. The problem grading code takes care
9499: of converting the bubbled letter information (now in %env) into a
9500: valid submission.
9501:
9502: =item scantron_upload_scantron_data() :
9503:
9504: Creates the screen for adding a new bubble sheet data file to a course.
9505:
9506: =item scantron_upload_scantron_data_save() :
9507:
9508: Adds a provided bubble information data file to the course if user
9509: has the correct privileges to do so.
9510:
9511: =item valid_file() :
9512:
9513: Validates that the requested bubble data file exists in the course.
9514:
9515: =item scantron_download_scantron_data() :
9516:
9517: Shows a list of the three internal files (original, corrected,
9518: skipped) for a specific bubble sheet data file that exists in the
9519: course.
9520:
9521: =item scantron_validate_ID() :
9522:
9523: Validates all scanlines in the selected file to not have any
9524: invalid or underspecified student/employee IDs
9525:
9526: =item navmap_errormsg() :
9527:
9528: Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
9529: Should be called whenever the request to instantiate a navmap object fails.
9530:
9531: =back
9532:
9533: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>