1: # The LearningOnline Network with CAPA
2: # The LON-CAPA Grading handler
3: #
4: # $Id: grades.pm,v 1.675 2012/10/02 18:03:07 bisitz Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28:
29:
30:
31: package Apache::grades;
32: use strict;
33: use Apache::style;
34: use Apache::lonxml;
35: use Apache::lonnet;
36: use Apache::loncommon;
37: use Apache::lonhtmlcommon;
38: use Apache::lonnavmaps;
39: use Apache::lonhomework;
40: use Apache::lonpickcode;
41: use Apache::loncoursedata;
42: use Apache::lonmsg();
43: use Apache::Constants qw(:common :http);
44: use Apache::lonlocal;
45: use Apache::lonenc;
46: use Apache::lonstathelpers;
47: use Apache::lonquickgrades;
48: use Apache::bridgetask();
49: use String::Similarity;
50: use LONCAPA;
51:
52: use POSIX qw(floor);
53:
54:
55:
56: my %perm=();
57: my %old_essays=();
58:
59: # These variables are used to recover from ssi errors
60:
61: my $ssi_retries = 5;
62: my $ssi_error;
63: my $ssi_error_resource;
64: my $ssi_error_message;
65:
66:
67: sub ssi_with_retries {
68: my ($resource, $retries, %form) = @_;
69: my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
70: if ($response->is_error) {
71: $ssi_error = 1;
72: $ssi_error_resource = $resource;
73: $ssi_error_message = $response->code . " " . $response->message;
74: }
75:
76: return $content;
77:
78: }
79: #
80: # Prodcuces an ssi retry failure error message to the user:
81: #
82:
83: sub ssi_print_error {
84: my ($r) = @_;
85: my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
86: $r->print('
87: <br />
88: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
89: <p>
90: '.&mt('Unable to retrieve a resource from a server:').'<br />
91: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
92: '.&mt('Error:').' '.$ssi_error_message.'
93: </p>
94: <p>'.
95: &mt('It is recommended that you try again later, as this error may mean the server was just temporarily unavailable, or is down for maintenance.').'<br />'.
96: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
97: '</p>');
98: return;
99: }
100:
101: #
102: # --- Retrieve the parts from the metadata file.---
103: # Returns an array of everything that the resources stores away
104: #
105:
106: sub getpartlist {
107: my ($symb,$errorref) = @_;
108:
109: my $navmap = Apache::lonnavmaps::navmap->new();
110: unless (ref($navmap)) {
111: if (ref($errorref)) {
112: $$errorref = 'navmap';
113: return;
114: }
115: }
116: my $res = $navmap->getBySymb($symb);
117: my $partlist = $res->parts();
118: my $url = $res->src();
119: my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
120:
121: my @stores;
122: foreach my $part (@{ $partlist }) {
123: foreach my $key (@metakeys) {
124: if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
125: }
126: }
127: return @stores;
128: }
129:
130: #--- Format fullname, username:domain if different for display
131: #--- Use anywhere where the student names are listed
132: sub nameUserString {
133: my ($type,$fullname,$uname,$udom) = @_;
134: if ($type eq 'header') {
135: return '<b> '.&mt('Fullname').' </b><span class="LC_internal_info">('.&mt('Username').')</span>';
136: } else {
137: return ' '.$fullname.'<span class="LC_internal_info"> ('.$uname.
138: ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
139: }
140: }
141:
142: #--- Get the partlist and the response type for a given problem. ---
143: #--- Indicate if a response type is coded handgraded or not. ---
144: #--- Sets response_error pointer to "1" if navmaps object broken ---
145: sub response_type {
146: my ($symb,$response_error) = @_;
147:
148: my $navmap = Apache::lonnavmaps::navmap->new();
149: unless (ref($navmap)) {
150: if (ref($response_error)) {
151: $$response_error = 1;
152: }
153: return;
154: }
155: my $res = $navmap->getBySymb($symb);
156: unless (ref($res)) {
157: $$response_error = 1;
158: return;
159: }
160: my $partlist = $res->parts();
161: my %vPart =
162: map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
163: my (%response_types,%handgrade);
164: foreach my $part (@{ $partlist }) {
165: next if (%vPart && !exists($vPart{$part}));
166:
167: my @types = $res->responseType($part);
168: my @ids = $res->responseIds($part);
169: for (my $i=0; $i < scalar(@ids); $i++) {
170: $response_types{$part}{$ids[$i]} = $types[$i];
171: $handgrade{$part.'_'.$ids[$i]} =
172: &Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
173: '.handgrade',$symb);
174: }
175: }
176: return ($partlist,\%handgrade,\%response_types);
177: }
178:
179: sub flatten_responseType {
180: my ($responseType) = @_;
181: my @part_response_id =
182: map {
183: my $part = $_;
184: map {
185: [$part,$_]
186: } sort(keys(%{ $responseType->{$part} }));
187: } sort(keys(%$responseType));
188: return @part_response_id;
189: }
190:
191: sub get_display_part {
192: my ($partID,$symb)=@_;
193: my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
194: if (defined($display) and $display ne '') {
195: $display.= ' (<span class="LC_internal_info">'
196: .&mt('Part ID: [_1]',$partID).'</span>)';
197: } else {
198: $display=$partID;
199: }
200: return $display;
201: }
202:
203: sub reset_caches {
204: &reset_analyze_cache();
205: &reset_perm();
206: &reset_old_essays();
207: }
208:
209: {
210: my %analyze_cache;
211: my %analyze_cache_formkeys;
212:
213: sub reset_analyze_cache {
214: undef(%analyze_cache);
215: undef(%analyze_cache_formkeys);
216: }
217:
218: sub get_analyze {
219: my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
220: my $key = "$symb\0$uname\0$udom";
221: if ($type eq 'randomizetry') {
222: if ($trial ne '') {
223: $key .= "\0".$trial;
224: }
225: }
226: if (exists($analyze_cache{$key})) {
227: my $getupdate = 0;
228: if (ref($add_to_hash) eq 'HASH') {
229: foreach my $item (keys(%{$add_to_hash})) {
230: if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
231: if (!exists($analyze_cache_formkeys{$key}{$item})) {
232: $getupdate = 1;
233: last;
234: }
235: } else {
236: $getupdate = 1;
237: }
238: }
239: }
240: if (!$getupdate) {
241: return $analyze_cache{$key};
242: }
243: }
244:
245: my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
246: $url=&Apache::lonnet::clutter($url);
247: my %form = ('grade_target' => 'analyze',
248: 'grade_domain' => $udom,
249: 'grade_symb' => $symb,
250: 'grade_courseid' => $env{'request.course.id'},
251: 'grade_username' => $uname,
252: 'grade_noincrement' => $no_increment);
253: if ($bubbles_per_row ne '') {
254: $form{'bubbles_per_row'} = $bubbles_per_row;
255: }
256: if ($type eq 'randomizetry') {
257: $form{'grade_questiontype'} = $type;
258: if ($rndseed ne '') {
259: $form{'grade_rndseed'} = $rndseed;
260: }
261: }
262: if (ref($add_to_hash)) {
263: %form = (%form,%{$add_to_hash});
264: }
265: my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
266: (undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
267: my %analyze=&Apache::lonnet::str2hash($subresult);
268: if (ref($add_to_hash) eq 'HASH') {
269: $analyze_cache_formkeys{$key} = $add_to_hash;
270: } else {
271: $analyze_cache_formkeys{$key} = {};
272: }
273: return $analyze_cache{$key} = \%analyze;
274: }
275:
276: sub get_order {
277: my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
278: my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
279: return $analyze->{"$partid.$respid.shown"};
280: }
281:
282: sub get_radiobutton_correct_foil {
283: my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
284: my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
285: my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
286: if (ref($foils) eq 'ARRAY') {
287: foreach my $foil (@{$foils}) {
288: if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
289: return $foil;
290: }
291: }
292: }
293: }
294:
295: sub scantron_partids_tograde {
296: my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row) = @_;
297: my (%analysis,@parts);
298: if (ref($resource)) {
299: my $symb = $resource->symb();
300: my $add_to_form;
301: if ($check_for_randomlist) {
302: $add_to_form = { 'check_parts_withrandomlist' => 1,};
303: }
304: my $analyze =
305: &get_analyze($symb,$uname,$udom,undef,$add_to_form,
306: undef,undef,undef,$bubbles_per_row);
307: if (ref($analyze) eq 'HASH') {
308: %analysis = %{$analyze};
309: }
310: if (ref($analysis{'parts'}) eq 'ARRAY') {
311: foreach my $part (@{$analysis{'parts'}}) {
312: my ($id,$respid) = split(/\./,$part);
313: if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
314: push(@parts,$part);
315: }
316: }
317: }
318: }
319: return (\%analysis,\@parts);
320: }
321:
322: }
323:
324: #--- Clean response type for display
325: #--- Currently filters option/rank/radiobutton/match/essay/Task
326: # response types only.
327: sub cleanRecord {
328: my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
329: $uname,$udom,$type,$trial,$rndseed) = @_;
330: my $grayFont = '<span class="LC_internal_info">';
331: if ($response =~ /^(option|rank)$/) {
332: my %answer=&Apache::lonnet::str2hash($answer);
333: my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
334: my ($toprow,$bottomrow);
335: foreach my $foil (@$order) {
336: if ($grading{$foil} == 1) {
337: $toprow.='<td><b>'.$answer{$foil}.' </b></td>';
338: } else {
339: $toprow.='<td><i>'.$answer{$foil}.' </i></td>';
340: }
341: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
342: }
343: return '<blockquote><table border="1">'.
344: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
345: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
346: $bottomrow.'</tr></table></blockquote>';
347: } elsif ($response eq 'match') {
348: my %answer=&Apache::lonnet::str2hash($answer);
349: my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
350: my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
351: my ($toprow,$middlerow,$bottomrow);
352: foreach my $foil (@$order) {
353: my $item=shift(@items);
354: if ($grading{$foil} == 1) {
355: $toprow.='<td><b>'.$item.' </b></td>';
356: $middlerow.='<td><b>'.$grayFont.$answer{$foil}.' </span></b></td>';
357: } else {
358: $toprow.='<td><i>'.$item.' </i></td>';
359: $middlerow.='<td><i>'.$grayFont.$answer{$foil}.' </span></i></td>';
360: }
361: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
362: }
363: return '<blockquote><table border="1">'.
364: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
365: '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
366: $middlerow.'</tr>'.
367: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
368: $bottomrow.'</tr></table></blockquote>';
369: } elsif ($response eq 'radiobutton') {
370: my %answer=&Apache::lonnet::str2hash($answer);
371: my ($toprow,$bottomrow);
372: my $correct =
373: &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
374: foreach my $foil (@$order) {
375: if (exists($answer{$foil})) {
376: if ($foil eq $correct) {
377: $toprow.='<td><b>'.&mt('true').'</b></td>';
378: } else {
379: $toprow.='<td><i>'.&mt('true').'</i></td>';
380: }
381: } else {
382: $toprow.='<td>'.&mt('false').'</td>';
383: }
384: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
385: }
386: return '<blockquote><table border="1">'.
387: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
388: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
389: $bottomrow.'</tr></table></blockquote>';
390: } elsif ($response eq 'essay') {
391: if (! exists ($env{'form.'.$symb})) {
392: my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
393: $env{'course.'.$env{'request.course.id'}.'.domain'},
394: $env{'course.'.$env{'request.course.id'}.'.num'});
395:
396: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
397: $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
398: $env{'form.kwclr'} = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
399: $env{'form.kwsize'} = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
400: $env{'form.kwstyle'} = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
401: $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
402: }
403: $answer =~ s-\n-<br />-g;
404: return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
405: } elsif ( $response eq 'organic') {
406: my $result='Smile representation: "<tt>'.$answer.'</tt>"';
407: my $jme=$record->{$version."resource.$partid.$respid.molecule"};
408: $result.=&Apache::chemresponse::jme_img($jme,$answer,400);
409: return $result;
410: } elsif ( $response eq 'Task') {
411: if ( $answer eq 'SUBMITTED') {
412: my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
413: my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
414: return $result;
415: } elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
416: my @matches = grep(/^\Q$version\E.*?\.instance$/,
417: keys(%{$record}));
418: return join('<br />',($version,@matches));
419:
420:
421: } else {
422: my $result =
423: '<p>'
424: .&mt('Overall result: [_1]',
425: $record->{$version."resource.$respid.$partid.status"})
426: .'</p>';
427:
428: $result .= '<ul>';
429: my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
430: keys(%{$record}));
431: foreach my $grade (sort(@grade)) {
432: my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
433: $result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
434: $dim, $record->{$grade}).
435: '</li>';
436: }
437: $result.='</ul>';
438: return $result;
439: }
440: } elsif ( $response =~ m/(?:numerical|formula)/) {
441: $answer =
442: &Apache::loncommon::format_previous_attempt_value('submission',
443: $answer);
444: }
445: return $answer;
446: }
447:
448: #-- A couple of common js functions
449: sub commonJSfunctions {
450: my $request = shift;
451: $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
452: function radioSelection(radioButton) {
453: var selection=null;
454: if (radioButton.length > 1) {
455: for (var i=0; i<radioButton.length; i++) {
456: if (radioButton[i].checked) {
457: return radioButton[i].value;
458: }
459: }
460: } else {
461: if (radioButton.checked) return radioButton.value;
462: }
463: return selection;
464: }
465:
466: function pullDownSelection(selectOne) {
467: var selection="";
468: if (selectOne.length > 1) {
469: for (var i=0; i<selectOne.length; i++) {
470: if (selectOne[i].selected) {
471: return selectOne[i].value;
472: }
473: }
474: } else {
475: // only one value it must be the selected one
476: return selectOne.value;
477: }
478: }
479: COMMONJSFUNCTIONS
480: }
481:
482: #--- Dumps the class list with usernames,list of sections,
483: #--- section, ids and fullnames for each user.
484: sub getclasslist {
485: my ($getsec,$filterlist,$getgroup) = @_;
486: my @getsec;
487: my @getgroup;
488: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
489: if (!ref($getsec)) {
490: if ($getsec ne '' && $getsec ne 'all') {
491: @getsec=($getsec);
492: }
493: } else {
494: @getsec=@{$getsec};
495: }
496: if (grep(/^all$/,@getsec)) { undef(@getsec); }
497: if (!ref($getgroup)) {
498: if ($getgroup ne '' && $getgroup ne 'all') {
499: @getgroup=($getgroup);
500: }
501: } else {
502: @getgroup=@{$getgroup};
503: }
504: if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
505:
506: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
507: # Bail out if we were unable to get the classlist
508: return if (! defined($classlist));
509: &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
510: #
511: my %sections;
512: my %fullnames;
513: foreach my $student (keys(%$classlist)) {
514: my $end =
515: $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
516: my $start =
517: $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
518: my $id =
519: $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
520: my $section =
521: $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
522: my $fullname =
523: $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
524: my $status =
525: $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
526: my $group =
527: $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
528: # filter students according to status selected
529: if ($filterlist && (!($stu_status =~ /Any/))) {
530: if (!($stu_status =~ $status)) {
531: delete($classlist->{$student});
532: next;
533: }
534: }
535: # filter students according to groups selected
536: my @stu_groups = split(/,/,$group);
537: if (@getgroup) {
538: my $exclude = 1;
539: foreach my $grp (@getgroup) {
540: foreach my $stu_group (@stu_groups) {
541: if ($stu_group eq $grp) {
542: $exclude = 0;
543: }
544: }
545: if (($grp eq 'none') && !$group) {
546: $exclude = 0;
547: }
548: }
549: if ($exclude) {
550: delete($classlist->{$student});
551: }
552: }
553: $section = ($section ne '' ? $section : 'none');
554: if (&canview($section)) {
555: if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
556: $sections{$section}++;
557: if ($classlist->{$student}) {
558: $fullnames{$student}=$fullname;
559: }
560: } else {
561: delete($classlist->{$student});
562: }
563: } else {
564: delete($classlist->{$student});
565: }
566: }
567: my %seen = ();
568: my @sections = sort(keys(%sections));
569: return ($classlist,\@sections,\%fullnames);
570: }
571:
572: sub canmodify {
573: my ($sec)=@_;
574: if ($perm{'mgr'}) {
575: if (!defined($perm{'mgr_section'})) {
576: # can modify whole class
577: return 1;
578: } else {
579: if ($sec eq $perm{'mgr_section'}) {
580: #can modify the requested section
581: return 1;
582: } else {
583: # can't modify the request section
584: return 0;
585: }
586: }
587: }
588: #can't modify
589: return 0;
590: }
591:
592: sub canview {
593: my ($sec)=@_;
594: if ($perm{'vgr'}) {
595: if (!defined($perm{'vgr_section'})) {
596: # can modify whole class
597: return 1;
598: } else {
599: if ($sec eq $perm{'vgr_section'}) {
600: #can modify the requested section
601: return 1;
602: } else {
603: # can't modify the request section
604: return 0;
605: }
606: }
607: }
608: #can't modify
609: return 0;
610: }
611:
612: #--- Retrieve the grade status of a student for all the parts
613: sub student_gradeStatus {
614: my ($symb,$udom,$uname,$partlist) = @_;
615: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
616: my %partstatus = ();
617: foreach (@$partlist) {
618: my ($status,undef) = split(/_/,$record{"resource.$_.solved"},2);
619: $status = 'nothing' if ($status eq '');
620: $partstatus{$_} = $status;
621: my $subkey = "resource.$_.submitted_by";
622: $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
623: }
624: return %partstatus;
625: }
626:
627: # hidden form and javascript that calls the form
628: # Use by verifyscript and viewgrades
629: # Shows a student's view of problem and submission
630: sub jscriptNform {
631: my ($symb) = @_;
632: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
633: my $jscript= &Apache::lonhtmlcommon::scripttag(
634: ' function viewOneStudent(user,domain) {'."\n".
635: ' document.onestudent.student.value = user;'."\n".
636: ' document.onestudent.userdom.value = domain;'."\n".
637: ' document.onestudent.submit();'."\n".
638: ' }'."\n".
639: "\n");
640: $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
641: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
642: '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
643: '<input type="hidden" name="command" value="submission" />'."\n".
644: '<input type="hidden" name="student" value="" />'."\n".
645: '<input type="hidden" name="userdom" value="" />'."\n".
646: '</form>'."\n";
647: return $jscript;
648: }
649:
650:
651:
652: # Given the score (as a number [0-1] and the weight) what is the final
653: # point value? This function will round to the nearest tenth, third,
654: # or quarter if one of those is within the tolerance of .00001.
655: sub compute_points {
656: my ($score, $weight) = @_;
657:
658: my $tolerance = .00001;
659: my $points = $score * $weight;
660:
661: # Check for nearness to 1/x.
662: my $check_for_nearness = sub {
663: my ($factor) = @_;
664: my $num = ($points * $factor) + $tolerance;
665: my $floored_num = floor($num);
666: if ($num - $floored_num < 2 * $tolerance * $factor) {
667: return $floored_num / $factor;
668: }
669: return $points;
670: };
671:
672: $points = $check_for_nearness->(10);
673: $points = $check_for_nearness->(3);
674: $points = $check_for_nearness->(4);
675:
676: return $points;
677: }
678:
679: #------------------ End of general use routines --------------------
680:
681: #
682: # Find most similar essay
683: #
684:
685: sub most_similar {
686: my ($uname,$udom,$symb,$uessay)=@_;
687:
688: unless ($symb) { return ''; }
689:
690: unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
691:
692: # ignore spaces and punctuation
693:
694: $uessay=~s/\W+/ /gs;
695:
696: # ignore empty submissions (occuring when only files are sent)
697:
698: unless ($uessay=~/\w+/s) { return ''; }
699:
700: # these will be returned. Do not care if not at least 50 percent similar
701: my $limit=0.6;
702: my $sname='';
703: my $sdom='';
704: my $scrsid='';
705: my $sessay='';
706: # go through all essays ...
707: foreach my $tkey (keys(%{$old_essays{$symb}})) {
708: my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
709: # ... except the same student
710: next if (($tname eq $uname) && ($tdom eq $udom));
711: my $tessay=$old_essays{$symb}{$tkey};
712: $tessay=~s/\W+/ /gs;
713: # String similarity gives up if not even limit
714: my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
715: # Found one
716: if ($tsimilar>$limit) {
717: $limit=$tsimilar;
718: $sname=$tname;
719: $sdom=$tdom;
720: $scrsid=$tcrsid;
721: $sessay=$old_essays{$symb}{$tkey};
722: }
723: }
724: if ($limit>0.6) {
725: return ($sname,$sdom,$scrsid,$sessay,$limit);
726: } else {
727: return ('','','','',0);
728: }
729: }
730:
731: #-------------------------------------------------------------------
732:
733: #------------------------------------ Receipt Verification Routines
734: #
735:
736: sub initialverifyreceipt {
737: my ($request,$symb) = @_;
738: &commonJSfunctions($request);
739: return '<form name="gradingMenu"><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
740: &Apache::lonnet::recprefix($env{'request.course.id'}).
741: '-<input type="text" name="receipt" size="4" />'.
742: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
743: '<input type="hidden" name="command" value="verify" />'.
744: "</form>\n";
745: }
746:
747: #--- Check whether a receipt number is valid.---
748: sub verifyreceipt {
749: my ($request,$symb) = @_;
750:
751: my $courseid = $env{'request.course.id'};
752: my $receipt = &Apache::lonnet::recprefix($courseid).'-'.
753: $env{'form.receipt'};
754: $receipt =~ s/[^\-\d]//g;
755:
756: my $title.=
757: '<h3><span class="LC_info">'.
758: &mt('Verifying Receipt Number [_1]',$receipt).
759: '</span></h3>'."\n";
760:
761: my ($string,$contents,$matches) = ('','',0);
762: my (undef,undef,$fullname) = &getclasslist('all','0');
763:
764: my $receiptparts=0;
765: if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
766: $env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
767: my $parts=['0'];
768: if ($receiptparts) {
769: my $res_error;
770: ($parts)=&response_type($symb,\$res_error);
771: if ($res_error) {
772: return &navmap_errormsg();
773: }
774: }
775:
776: my $header =
777: &Apache::loncommon::start_data_table().
778: &Apache::loncommon::start_data_table_header_row().
779: '<th> '.&mt('Fullname').' </th>'."\n".
780: '<th> '.&mt('Username').' </th>'."\n".
781: '<th> '.&mt('Domain').' </th>';
782: if ($receiptparts) {
783: $header.='<th> '.&mt('Problem Part').' </th>';
784: }
785: $header.=
786: &Apache::loncommon::end_data_table_header_row();
787:
788: foreach (sort
789: {
790: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
791: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
792: }
793: return $a cmp $b;
794: } (keys(%$fullname))) {
795: my ($uname,$udom)=split(/\:/);
796: foreach my $part (@$parts) {
797: if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
798: $contents.=
799: &Apache::loncommon::start_data_table_row().
800: '<td> '."\n".
801: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
802: '\');" target="_self">'.$$fullname{$_}.'</a> </td>'."\n".
803: '<td> '.$uname.' </td>'.
804: '<td> '.$udom.' </td>';
805: if ($receiptparts) {
806: $contents.='<td> '.$part.' </td>';
807: }
808: $contents.=
809: &Apache::loncommon::end_data_table_row()."\n";
810:
811: $matches++;
812: }
813: }
814: }
815: if ($matches == 0) {
816: $string = $title
817: .'<p class="LC_warning">'
818: .&mt('No match found for the above receipt number.')
819: .'</p>';
820: } else {
821: $string = &jscriptNform($symb).$title.
822: '<p>'.
823: &mt('The above receipt number matches the following [quant,_1,student].',$matches).
824: '</p>'.
825: $header.
826: $contents.
827: &Apache::loncommon::end_data_table()."\n";
828: }
829: return $string;
830: }
831:
832: #--- This is called by a number of programs.
833: #--- Called from the Grading Menu - View/Grade an individual student
834: #--- Also called directly when one clicks on the subm button
835: # on the problem page.
836: sub listStudents {
837: my ($request,$symb,$submitonly) = @_;
838:
839: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
840: my $cnum = $env{"course.$env{'request.course.id'}.num"};
841: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
842: my $getgroup = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
843: unless ($submitonly) {
844: $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
845: }
846:
847: my $result='';
848: my $res_error;
849: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
850:
851: my %lt = &Apache::lonlocal::texthash (
852: 'multiple' => 'Please select a student or group of students before clicking on the Next button.',
853: 'single' => 'Please select the student before clicking on the Next button.',
854: );
855: $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
856: function checkSelect(checkBox) {
857: var ctr=0;
858: var sense="";
859: if (checkBox.length > 1) {
860: for (var i=0; i<checkBox.length; i++) {
861: if (checkBox[i].checked) {
862: ctr++;
863: }
864: }
865: sense = '$lt{'multiple'}';
866: } else {
867: if (checkBox.checked) {
868: ctr = 1;
869: }
870: sense = '$lt{'single'}';
871: }
872: if (ctr == 0) {
873: alert(sense);
874: return false;
875: }
876: document.gradesub.submit();
877: }
878:
879: function reLoadList(formname) {
880: if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
881: formname.command.value = 'submission';
882: formname.submit();
883: }
884: LISTJAVASCRIPT
885:
886: &commonJSfunctions($request);
887: $request->print($result);
888:
889: my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
890: "\n";
891:
892: $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
893: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
894: .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
895: .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
896: .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
897: .&Apache::lonhtmlcommon::row_closure();
898: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
899: .'<label><input type="radio" name="vAns" value="no" /> '.&mt('no').' </label>'."\n"
900: .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
901: .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
902: .&Apache::lonhtmlcommon::row_closure();
903:
904: my $submission_options;
905: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
906: my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
907: $env{'form.Status'} = $saveStatus;
908: $submission_options.=
909: '<span class="LC_nobreak">'.
910: '<label><input type="radio" name="lastSub" value="lastonly" /> '.
911: &mt('last submission only').' </label></span>'."\n".
912: '<span class="LC_nobreak">'.
913: '<label><input type="radio" name="lastSub" value="last" /> '.
914: &mt('last submission & parts info').' </label></span>'."\n".
915: '<span class="LC_nobreak">'.
916: '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
917: &mt('by dates and submissions').'</label></span>'."\n".
918: '<span class="LC_nobreak">'.
919: '<label><input type="radio" name="lastSub" value="all" /> '.
920: &mt('all details').'</label></span>';
921: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
922: .$submission_options
923: .&Apache::lonhtmlcommon::row_closure();
924:
925: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
926: .'<select name="increment">'
927: .'<option value="1">'.&mt('Whole Points').'</option>'
928: .'<option value=".5">'.&mt('Half Points').'</option>'
929: .'<option value=".25">'.&mt('Quarter Points').'</option>'
930: .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
931: .'</select>'
932: .&Apache::lonhtmlcommon::row_closure();
933:
934: $gradeTable .=
935: &build_section_inputs().
936: '<input type="hidden" name="submitonly" value="'.$submitonly.'" />'."\n".
937: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
938: '<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
939:
940: if (exists($env{'form.Status'})) {
941: $gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
942: } else {
943: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
944: .&Apache::lonhtmlcommon::StatusOptions(
945: $saveStatus,undef,1,'javascript:reLoadList(this.form);')
946: .&Apache::lonhtmlcommon::row_closure();
947: }
948:
949: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
950: .'<input type="checkbox" name="checkPlag" checked="checked" />'
951: .&Apache::lonhtmlcommon::row_closure(1)
952: .&Apache::lonhtmlcommon::end_pick_box();
953:
954: $gradeTable .= '<p>'
955: .&mt("To view/grade/regrade a submission or a group of submissions, click on the check box(es) next to the student's name(s). Then click on the Next button.")."\n"
956: .'<input type="hidden" name="command" value="processGroup" />'
957: .'</p>';
958:
959: # checkall buttons
960: $gradeTable.=&check_script('gradesub', 'stuinfo');
961: $gradeTable.='<input type="button" '."\n".
962: 'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
963: 'value="'.&mt('Next').' →" /> <br />'."\n";
964: $gradeTable.=&check_buttons();
965: my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
966: $gradeTable.= &Apache::loncommon::start_data_table().
967: &Apache::loncommon::start_data_table_header_row();
968: my $loop = 0;
969: while ($loop < 2) {
970: $gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
971: '<th>'.&nameUserString('header').' '.&mt('Section/Group').'</th>';
972: if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
973: foreach my $part (sort(@$partlist)) {
974: my $display_part=
975: &get_display_part((split(/_/,$part))[0],$symb);
976: $gradeTable.=
977: '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
978: }
979: } elsif ($submitonly eq 'queued') {
980: $gradeTable.='<th>'.&mt('Queue Status').' </th>';
981: }
982: $loop++;
983: # $gradeTable.='<td></td>' if ($loop%2 ==1);
984: }
985: $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
986:
987: my $ctr = 0;
988: foreach my $student (sort
989: {
990: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
991: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
992: }
993: return $a cmp $b;
994: }
995: (keys(%$fullname))) {
996: my ($uname,$udom) = split(/:/,$student);
997:
998: my %status = ();
999:
1000: if ($submitonly eq 'queued') {
1001: my %queue_status =
1002: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
1003: $udom,$uname);
1004: next if (!defined($queue_status{'gradingqueue'}));
1005: $status{'gradingqueue'} = $queue_status{'gradingqueue'};
1006: }
1007:
1008: if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1009: (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1010: my $submitted = 0;
1011: my $graded = 0;
1012: my $incorrect = 0;
1013: foreach (keys(%status)) {
1014: $submitted = 1 if ($status{$_} ne 'nothing');
1015: $graded = 1 if ($status{$_} =~ /^ungraded/);
1016: $incorrect = 1 if ($status{$_} =~ /^incorrect/);
1017:
1018: my ($foo,$partid,$foo1) = split(/\./,$_);
1019: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1020: $submitted = 0;
1021: my ($part)=split(/\./,$partid);
1022: $gradeTable.='<input type="hidden" name="'.
1023: $student.':'.$part.':submitted_by" value="'.
1024: $status{'resource.'.$partid.'.submitted_by'}.'" />';
1025: }
1026: }
1027:
1028: next if (!$submitted && ($submitonly eq 'yes' ||
1029: $submitonly eq 'incorrect' ||
1030: $submitonly eq 'graded'));
1031: next if (!$graded && ($submitonly eq 'graded'));
1032: next if (!$incorrect && $submitonly eq 'incorrect');
1033: }
1034:
1035: $ctr++;
1036: my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1037: my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1038: if ( $perm{'vgr'} eq 'F' ) {
1039: if ($ctr%2 ==1) {
1040: $gradeTable.= &Apache::loncommon::start_data_table_row();
1041: }
1042: $gradeTable.='<td align="right">'.$ctr.' </td>'.
1043: '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1044: $student.':'.$$fullname{$student}.':::SECTION'.$section.
1045: ') " /> </label></td>'."\n".'<td>'.
1046: &nameUserString(undef,$$fullname{$student},$uname,$udom).
1047: ' '.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1048:
1049: if ($submitonly ne 'all') {
1050: foreach (sort(keys(%status))) {
1051: next if ($_ =~ /^resource.*?submitted_by$/);
1052: $gradeTable.='<td align="center"> '.&mt($status{$_}).' </td>'."\n";
1053: }
1054: }
1055: # $gradeTable.='<td></td>' if ($ctr%2 ==1);
1056: if ($ctr%2 ==0) {
1057: $gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
1058: }
1059: }
1060: }
1061: if ($ctr%2 ==1) {
1062: $gradeTable.='<td> </td><td> </td><td> </td>';
1063: if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1064: foreach (@$partlist) {
1065: $gradeTable.='<td> </td>';
1066: }
1067: } elsif ($submitonly eq 'queued') {
1068: $gradeTable.='<td> </td>';
1069: }
1070: $gradeTable.=&Apache::loncommon::end_data_table_row();
1071: }
1072:
1073: $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1074: '<input type="button" '.
1075: 'onclick="javascript:checkSelect(this.form.stuinfo);" '.
1076: 'value="'.&mt('Next').' →" /></form>'."\n";
1077: if ($ctr == 0) {
1078: my $num_students=(scalar(keys(%$fullname)));
1079: if ($num_students eq 0) {
1080: $gradeTable='<br /> <span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1081: } else {
1082: my $submissions='submissions';
1083: if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
1084: if ($submitonly eq 'graded' ) { $submissions = 'ungraded submissions'; }
1085: if ($submitonly eq 'queued' ) { $submissions = 'queued submissions'; }
1086: $gradeTable='<br /> <span class="LC_warning">'.
1087: &mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
1088: $num_students).
1089: '</span><br />';
1090: }
1091: } elsif ($ctr == 1) {
1092: $gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1093: }
1094: $request->print($gradeTable);
1095: return '';
1096: }
1097:
1098: #---- Called from the listStudents routine
1099:
1100: sub check_script {
1101: my ($form, $type)=@_;
1102: my $chkallscript= &Apache::lonhtmlcommon::scripttag('
1103: function checkall() {
1104: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1105: ele = document.forms.'.$form.'.elements[i];
1106: if (ele.name == "'.$type.'") {
1107: document.forms.'.$form.'.elements[i].checked=true;
1108: }
1109: }
1110: }
1111:
1112: function checksec() {
1113: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1114: ele = document.forms.'.$form.'.elements[i];
1115: string = document.forms.'.$form.'.chksec.value;
1116: if
1117: (ele.value.indexOf(":::SECTION"+string)>0) {
1118: document.forms.'.$form.'.elements[i].checked=true;
1119: }
1120: }
1121: }
1122:
1123:
1124: function uncheckall() {
1125: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1126: ele = document.forms.'.$form.'.elements[i];
1127: if (ele.name == "'.$type.'") {
1128: document.forms.'.$form.'.elements[i].checked=false;
1129: }
1130: }
1131: }
1132:
1133: '."\n");
1134: return $chkallscript;
1135: }
1136:
1137: sub check_buttons {
1138: my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
1139: $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" /> ';
1140: $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1141: $buttons.='<input type="text" size="5" name="chksec" /> ';
1142: return $buttons;
1143: }
1144:
1145: # Displays the submissions for one student or a group of students
1146: sub processGroup {
1147: my ($request,$symb) = @_;
1148: my $ctr = 0;
1149: my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1150: my $total = scalar(@stuchecked)-1;
1151:
1152: foreach my $student (@stuchecked) {
1153: my ($uname,$udom,$fullname) = split(/:/,$student);
1154: $env{'form.student'} = $uname;
1155: $env{'form.userdom'} = $udom;
1156: $env{'form.fullname'} = $fullname;
1157: &submission($request,$ctr,$total,$symb);
1158: $ctr++;
1159: }
1160: return '';
1161: }
1162:
1163: #------------------------------------------------------------------------------------
1164: #
1165: #-------------------------- Next few routines handles grading by student, essentially
1166: # handles essay response type problem/part
1167: #
1168: #--- Javascript to handle the submission page functionality ---
1169: sub sub_page_js {
1170: my $request = shift;
1171: my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1172: $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1173: function updateRadio(formname,id,weight) {
1174: var gradeBox = formname["GD_BOX"+id];
1175: var radioButton = formname["RADVAL"+id];
1176: var oldpts = formname["oldpts"+id].value;
1177: var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1178: gradeBox.value = pts;
1179: var resetbox = false;
1180: if (isNaN(pts) || pts < 0) {
1181: alert("$alertmsg"+pts);
1182: for (var i=0; i<radioButton.length; i++) {
1183: if (radioButton[i].checked) {
1184: gradeBox.value = i;
1185: resetbox = true;
1186: }
1187: }
1188: if (!resetbox) {
1189: formtextbox.value = "";
1190: }
1191: return;
1192: }
1193:
1194: if (pts > weight) {
1195: var resp = confirm("You entered a value ("+pts+
1196: ") greater than the weight for the part. Accept?");
1197: if (resp == false) {
1198: gradeBox.value = oldpts;
1199: return;
1200: }
1201: }
1202:
1203: for (var i=0; i<radioButton.length; i++) {
1204: radioButton[i].checked=false;
1205: if (pts == i && pts != "") {
1206: radioButton[i].checked=true;
1207: }
1208: }
1209: updateSelect(formname,id);
1210: formname["stores"+id].value = "0";
1211: }
1212:
1213: function writeBox(formname,id,pts) {
1214: var gradeBox = formname["GD_BOX"+id];
1215: if (checkSolved(formname,id) == 'update') {
1216: gradeBox.value = pts;
1217: } else {
1218: var oldpts = formname["oldpts"+id].value;
1219: gradeBox.value = oldpts;
1220: var radioButton = formname["RADVAL"+id];
1221: for (var i=0; i<radioButton.length; i++) {
1222: radioButton[i].checked=false;
1223: if (i == oldpts) {
1224: radioButton[i].checked=true;
1225: }
1226: }
1227: }
1228: formname["stores"+id].value = "0";
1229: updateSelect(formname,id);
1230: return;
1231: }
1232:
1233: function clearRadBox(formname,id) {
1234: if (checkSolved(formname,id) == 'noupdate') {
1235: updateSelect(formname,id);
1236: return;
1237: }
1238: gradeSelect = formname["GD_SEL"+id];
1239: for (var i=0; i<gradeSelect.length; i++) {
1240: if (gradeSelect[i].selected) {
1241: var selectx=i;
1242: }
1243: }
1244: var stores = formname["stores"+id];
1245: if (selectx == stores.value) { return };
1246: var gradeBox = formname["GD_BOX"+id];
1247: gradeBox.value = "";
1248: var radioButton = formname["RADVAL"+id];
1249: for (var i=0; i<radioButton.length; i++) {
1250: radioButton[i].checked=false;
1251: }
1252: stores.value = selectx;
1253: }
1254:
1255: function checkSolved(formname,id) {
1256: if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1257: var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
1258: if (!reply) {return "noupdate";}
1259: formname.overRideScore.value = 'yes';
1260: }
1261: return "update";
1262: }
1263:
1264: function updateSelect(formname,id) {
1265: formname["GD_SEL"+id][0].selected = true;
1266: return;
1267: }
1268:
1269: //=========== Check that a point is assigned for all the parts ============
1270: function checksubmit(formname,val,total,parttot) {
1271: formname.gradeOpt.value = val;
1272: if (val == "Save & Next") {
1273: for (i=0;i<=total;i++) {
1274: for (j=0;j<parttot;j++) {
1275: var partid = formname["partid"+i+"_"+j].value;
1276: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1277: var points = formname["GD_BOX"+i+"_"+partid].value;
1278: if (points == "") {
1279: var name = formname["name"+i].value;
1280: var studentID = (name != '' ? name : formname["unamedom"+i].value);
1281: var resp = confirm("You did not assign a score for "+studentID+
1282: ", part "+partid+". Continue?");
1283: if (resp == false) {
1284: formname["GD_BOX"+i+"_"+partid].focus();
1285: return false;
1286: }
1287: }
1288: }
1289:
1290: }
1291: }
1292:
1293: }
1294: formname.submit();
1295: }
1296:
1297: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
1298: function checkSubmitPage(formname,total) {
1299: noscore = new Array(100);
1300: var ptr = 0;
1301: for (i=1;i<total;i++) {
1302: var partid = formname["q_"+i].value;
1303: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1304: var points = formname["GD_BOX"+i+"_"+partid].value;
1305: var status = formname["solved"+i+"_"+partid].value;
1306: if (points == "" && status != "correct_by_student") {
1307: noscore[ptr] = i;
1308: ptr++;
1309: }
1310: }
1311: }
1312: if (ptr != 0) {
1313: var sense = ptr == 1 ? ": " : "s: ";
1314: var prolist = "";
1315: if (ptr == 1) {
1316: prolist = noscore[0];
1317: } else {
1318: var i = 0;
1319: while (i < ptr-1) {
1320: prolist += noscore[i]+", ";
1321: i++;
1322: }
1323: prolist += "and "+noscore[i];
1324: }
1325: var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
1326: if (resp == false) {
1327: return false;
1328: }
1329: }
1330:
1331: formname.submit();
1332: }
1333: SUBJAVASCRIPT
1334: }
1335:
1336: #--- javascript for essay type problem --
1337: sub sub_page_kw_js {
1338: my $request = shift;
1339: my $iconpath = $request->dir_config('lonIconsURL');
1340: &commonJSfunctions($request);
1341:
1342: my $inner_js_msg_central= (<<INNERJS);
1343: <script type="text/javascript">
1344: function checkInput() {
1345: opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
1346: var nmsg = opener.document.SCORE.savemsgN.value;
1347: var usrctr = document.msgcenter.usrctr.value;
1348: var newval = opener.document.SCORE["newmsg"+usrctr];
1349: newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
1350:
1351: var msgchk = "";
1352: if (document.msgcenter.subchk.checked) {
1353: msgchk = "msgsub,";
1354: }
1355: var includemsg = 0;
1356: for (var i=1; i<=nmsg; i++) {
1357: var opnmsg = opener.document.SCORE["savemsg"+i];
1358: var frmmsg = document.msgcenter["msg"+i];
1359: opnmsg.value = opener.checkEntities(frmmsg.value);
1360: var showflg = opener.document.SCORE["shownOnce"+i];
1361: showflg.value = "1";
1362: var chkbox = document.msgcenter["msgn"+i];
1363: if (chkbox.checked) {
1364: msgchk += "savemsg"+i+",";
1365: includemsg = 1;
1366: }
1367: }
1368: if (document.msgcenter.newmsgchk.checked) {
1369: msgchk += "newmsg"+usrctr;
1370: includemsg = 1;
1371: }
1372: imgformname = opener.document.SCORE["mailicon"+usrctr];
1373: imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
1374: var includemsg = opener.document.SCORE["includemsg"+usrctr];
1375: includemsg.value = msgchk;
1376:
1377: self.close()
1378:
1379: }
1380: </script>
1381: INNERJS
1382:
1383: my $inner_js_highlight_central= (<<INNERJS);
1384: <script type="text/javascript">
1385: function updateChoice(flag) {
1386: opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
1387: opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
1388: opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
1389: opener.document.SCORE.refresh.value = "on";
1390: if (opener.document.SCORE.keywords.value!=""){
1391: opener.document.SCORE.submit();
1392: }
1393: self.close()
1394: }
1395: </script>
1396: INNERJS
1397:
1398: my $start_page_msg_central =
1399: &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
1400: {'js_ready' => 1,
1401: 'only_body' => 1,
1402: 'bgcolor' =>'#FFFFFF',});
1403: my $end_page_msg_central =
1404: &Apache::loncommon::end_page({'js_ready' => 1});
1405:
1406:
1407: my $start_page_highlight_central =
1408: &Apache::loncommon::start_page('Highlight Central',
1409: $inner_js_highlight_central,
1410: {'js_ready' => 1,
1411: 'only_body' => 1,
1412: 'bgcolor' =>'#FFFFFF',});
1413: my $end_page_highlight_central =
1414: &Apache::loncommon::end_page({'js_ready' => 1});
1415:
1416: my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1417: $docopen=~s/^document\.//;
1418: my %lt = &Apache::lonlocal::texthash(
1419: keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
1420: plse => 'Please select a word or group of words from document and then click this link.',
1421: adds => 'Add selection to keyword list? Edit if desired.',
1422: comp => 'Compose Message for: ',
1423: incl => 'Include',
1424: type => 'Type',
1425: subj => 'Subject',
1426: mesa => 'Message',
1427: new => 'New',
1428: save => 'Save',
1429: canc => 'Cancel',
1430: kehi => 'Keyword Highlight Options',
1431: txtc => 'Text Color',
1432: font => 'Font Size',
1433: fnst => 'Font Style',
1434: );
1435: $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1436:
1437: //===================== Show list of keywords ====================
1438: function keywords(formname) {
1439: var nret = prompt("$lt{'keyw'}",formname.keywords.value);
1440: if (nret==null) return;
1441: formname.keywords.value = nret;
1442:
1443: if (formname.keywords.value != "") {
1444: formname.refresh.value = "on";
1445: formname.submit();
1446: }
1447: return;
1448: }
1449:
1450: //===================== Script to view submitted by ==================
1451: function viewSubmitter(submitter) {
1452: document.SCORE.refresh.value = "on";
1453: document.SCORE.NCT.value = "1";
1454: document.SCORE.unamedom0.value = submitter;
1455: document.SCORE.submit();
1456: return;
1457: }
1458:
1459: //===================== Script to add keyword(s) ==================
1460: function getSel() {
1461: if (document.getSelection) txt = document.getSelection();
1462: else if (document.selection) txt = document.selection.createRange().text;
1463: else return;
1464: var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
1465: if (cleantxt=="") {
1466: alert("$lt{'plse'}");
1467: return;
1468: }
1469: var nret = prompt("$lt{'adds'}",cleantxt);
1470: if (nret==null) return;
1471: document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1472: if (document.SCORE.keywords.value != "") {
1473: document.SCORE.refresh.value = "on";
1474: document.SCORE.submit();
1475: }
1476: return;
1477: }
1478:
1479: //====================== Script for composing message ==============
1480: // preload images
1481: img1 = new Image();
1482: img1.src = "$iconpath/mailbkgrd.gif";
1483: img2 = new Image();
1484: img2.src = "$iconpath/mailto.gif";
1485:
1486: function msgCenter(msgform,usrctr,fullname) {
1487: var Nmsg = msgform.savemsgN.value;
1488: savedMsgHeader(Nmsg,usrctr,fullname);
1489: var subject = msgform.msgsub.value;
1490: var msgchk = document.SCORE["includemsg"+usrctr].value;
1491: re = /msgsub/;
1492: var shwsel = "";
1493: if (re.test(msgchk)) { shwsel = "checked" }
1494: subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
1495: displaySubject(checkEntities(subject),shwsel);
1496: for (var i=1; i<=Nmsg; i++) {
1497: var testmsg = "savemsg"+i+",";
1498: re = new RegExp(testmsg,"g");
1499: shwsel = "";
1500: if (re.test(msgchk)) { shwsel = "checked" }
1501: var message = document.SCORE["savemsg"+i].value;
1502: message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1503: displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
1504: //any < is already converted to <, etc. However, only once!!
1505: }
1506: newmsg = document.SCORE["newmsg"+usrctr].value;
1507: shwsel = "";
1508: re = /newmsg/;
1509: if (re.test(msgchk)) { shwsel = "checked" }
1510: newMsg(newmsg,shwsel);
1511: msgTail();
1512: return;
1513: }
1514:
1515: function checkEntities(strx) {
1516: if (strx.length == 0) return strx;
1517: var orgStr = ["&", "<", ">", '"'];
1518: var newStr = ["&", "<", ">", """];
1519: var counter = 0;
1520: while (counter < 4) {
1521: strx = strReplace(strx,orgStr[counter],newStr[counter]);
1522: counter++;
1523: }
1524: return strx;
1525: }
1526:
1527: function strReplace(strx, orgStr, newStr) {
1528: return strx.split(orgStr).join(newStr);
1529: }
1530:
1531: function savedMsgHeader(Nmsg,usrctr,fullname) {
1532: var height = 70*Nmsg+250;
1533: if (height > 600) {
1534: height = 600;
1535: }
1536: var xpos = (screen.width-600)/2;
1537: xpos = (xpos < 0) ? '0' : xpos;
1538: var ypos = (screen.height-height)/2-30;
1539: ypos = (ypos < 0) ? '0' : ypos;
1540:
1541: pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1542: pWin.focus();
1543: pDoc = pWin.document;
1544: pDoc.$docopen;
1545: pDoc.write('$start_page_msg_central');
1546:
1547: pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
1548: pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1549: pDoc.write("<h3><span class=\\"LC_info\\"> $lt{'comp'}\"+fullname+\"<\\/span><\\/h3><br /><br />");
1550:
1551: pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
1552: pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1553: pDoc.write("<td><b>$lt{'type'}<\\/b><\\/td><td><b>$lt{'incl'}<\\/b><\\/td><td><b>$lt{'mesa'}<\\/td><\\/tr>");
1554: }
1555: function displaySubject(msg,shwsel) {
1556: pDoc = pWin.document;
1557: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1558: pDoc.write("<td>$lt{'subj'}<\\/td>");
1559: pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1560: pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1561: }
1562:
1563: function displaySavedMsg(ctr,msg,shwsel) {
1564: pDoc = pWin.document;
1565: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1566: pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
1567: pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1568: pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1569: }
1570:
1571: function newMsg(newmsg,shwsel) {
1572: pDoc = pWin.document;
1573: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1574: pDoc.write("<td align=\\"center\\">$lt{'new'}<\\/td>");
1575: pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1576: pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1577: }
1578:
1579: function msgTail() {
1580: pDoc = pWin.document;
1581: pDoc.write("<\\/table>");
1582: pDoc.write("<\\/td><\\/tr><\\/table> ");
1583: pDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:checkInput()\\"> ");
1584: pDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1585: pDoc.write("<\\/form>");
1586: pDoc.write('$end_page_msg_central');
1587: pDoc.close();
1588: }
1589:
1590: //====================== Script for keyword highlight options ==============
1591: function kwhighlight() {
1592: var kwclr = document.SCORE.kwclr.value;
1593: var kwsize = document.SCORE.kwsize.value;
1594: var kwstyle = document.SCORE.kwstyle.value;
1595: var redsel = "";
1596: var grnsel = "";
1597: var blusel = "";
1598: if (kwclr=="red") {var redsel="checked"};
1599: if (kwclr=="green") {var grnsel="checked"};
1600: if (kwclr=="blue") {var blusel="checked"};
1601: var sznsel = "";
1602: var sz1sel = "";
1603: var sz2sel = "";
1604: if (kwsize=="0") {var sznsel="checked"};
1605: if (kwsize=="+1") {var sz1sel="checked"};
1606: if (kwsize=="+2") {var sz2sel="checked"};
1607: var synsel = "";
1608: var syisel = "";
1609: var sybsel = "";
1610: if (kwstyle=="") {var synsel="checked"};
1611: if (kwstyle=="<i>") {var syisel="checked"};
1612: if (kwstyle=="<b>") {var sybsel="checked"};
1613: highlightCentral();
1614: highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
1615: highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
1616: highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
1617: highlightend();
1618: return;
1619: }
1620:
1621: function highlightCentral() {
1622: // if (window.hwdWin) window.hwdWin.close();
1623: var xpos = (screen.width-400)/2;
1624: xpos = (xpos < 0) ? '0' : xpos;
1625: var ypos = (screen.height-330)/2-30;
1626: ypos = (ypos < 0) ? '0' : ypos;
1627:
1628: hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1629: hwdWin.focus();
1630: var hDoc = hwdWin.document;
1631: hDoc.$docopen;
1632: hDoc.write('$start_page_highlight_central');
1633: hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1634: hDoc.write("<h3><span class=\\"LC_info\\"> $lt{'kehi'}<\\/span><\\/h3><br /><br />");
1635:
1636: hDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
1637: hDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1638: hDoc.write("<td><b>$lt{'txtc'}<\\/b><\\/td><td><b>$lt{'font'}<\\/b><\\/td><td><b>$lt{'fnst'}<\\/td><\\/tr>");
1639: }
1640:
1641: function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) {
1642: var hDoc = hwdWin.document;
1643: hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1644: hDoc.write("<td align=\\"left\\">");
1645: hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+"> "+clrtxt+"<\\/td>");
1646: hDoc.write("<td align=\\"left\\">");
1647: hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+"> "+sztxt+"<\\/td>");
1648: hDoc.write("<td align=\\"left\\">");
1649: hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+"> "+sytxt+"<\\/td>");
1650: hDoc.write("<\\/tr>");
1651: }
1652:
1653: function highlightend() {
1654: var hDoc = hwdWin.document;
1655: hDoc.write("<\\/table>");
1656: hDoc.write("<\\/td><\\/tr><\\/table> ");
1657: hDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\"> ");
1658: hDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1659: hDoc.write("<\\/form>");
1660: hDoc.write('$end_page_highlight_central');
1661: hDoc.close();
1662: }
1663:
1664: SUBJAVASCRIPT
1665: }
1666:
1667: sub get_increment {
1668: my $increment = $env{'form.increment'};
1669: if ($increment != 1 && $increment != .5 && $increment != .25 &&
1670: $increment != .1) {
1671: $increment = 1;
1672: }
1673: return $increment;
1674: }
1675:
1676: sub gradeBox_start {
1677: return (
1678: &Apache::loncommon::start_data_table()
1679: .&Apache::loncommon::start_data_table_header_row()
1680: .'<th>'.&mt('Part').'</th>'
1681: .'<th>'.&mt('Points').'</th>'
1682: .'<th> </th>'
1683: .'<th>'.&mt('Assign Grade').'</th>'
1684: .'<th>'.&mt('Weight').'</th>'
1685: .'<th>'.&mt('Grade Status').'</th>'
1686: .&Apache::loncommon::end_data_table_header_row()
1687: );
1688: }
1689:
1690: sub gradeBox_end {
1691: return (
1692: &Apache::loncommon::end_data_table()
1693: );
1694: }
1695: #--- displays the grading box, used in essay type problem and grading by page/sequence
1696: sub gradeBox {
1697: my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1698: my $checkIcon = '<img alt="'.&mt('Check Mark').
1699: '" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1700: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1701: my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)')
1702: : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1703: $wgt = ($wgt > 0 ? $wgt : '1');
1704: my $score = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1705: '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1706: my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1707: my $display_part= &get_display_part($partid,$symb);
1708: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
1709: [$partid]);
1710: my $aggtries = $$record{'resource.'.$partid.'.tries'};
1711: if ($last_resets{$partid}) {
1712: $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
1713: }
1714: $result.=&Apache::loncommon::start_data_table_row();
1715: my $ctr = 0;
1716: my $thisweight = 0;
1717: my $increment = &get_increment();
1718:
1719: my $radio.='<table border="0"><tr>'."\n"; # display radio buttons in a nice table 10 across
1720: while ($thisweight<=$wgt) {
1721: $radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1722: 'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1723: $thisweight.')" value="'.$thisweight.'" '.
1724: ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1725: $radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1726: $thisweight += $increment;
1727: $ctr++;
1728: }
1729: $radio.='</tr></table>';
1730:
1731: my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1732: ($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1733: 'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1734: $wgt.')" /></td>'."\n";
1735: $line.='<td>/'.$wgt.' '.$wgtmsg.
1736: ($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? ' '.$checkIcon : '').
1737: ' </td>'."\n";
1738: $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1739: 'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1740: if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1741: $line.='<option></option>'.
1742: '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1743: } else {
1744: $line.='<option selected="selected"></option>'.
1745: '<option value="excused" >'.&mt('excused').'</option>';
1746: }
1747: $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
1748:
1749:
1750: $result .=
1751: '<td>'.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
1752: $result.=&Apache::loncommon::end_data_table_row();
1753: $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
1754: '<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
1755: '<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1756: $$record{'resource.'.$partid.'.solved'}.'" />'."\n".
1757: '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
1758: $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
1759: '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
1760: $aggtries.'" />'."\n";
1761: my $res_error;
1762: $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1763: if ($res_error) {
1764: return &navmap_errormsg();
1765: }
1766: return $result;
1767: }
1768:
1769: sub handback_box {
1770: my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
1771: my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
1772: my (@respids);
1773: my @part_response_id = &flatten_responseType($responseType);
1774: foreach my $part_response_id (@part_response_id) {
1775: my ($part,$resp) = @{ $part_response_id };
1776: if ($part eq $partid) {
1777: push(@respids,$resp);
1778: }
1779: }
1780: my $result;
1781: foreach my $respid (@respids) {
1782: my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
1783: my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
1784: next if (!@$files);
1785: my $file_counter = 0;
1786: foreach my $file (@$files) {
1787: if ($file =~ /\/portfolio\//) {
1788: $file_counter++;
1789: my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1790: my ($name,$version,$ext) = &file_name_version_ext($file_disp);
1791: $file_disp = "$name.$ext";
1792: $file = $file_path.$file_disp;
1793: $result.=&mt('Return commented version of [_1] to student.',
1794: '<span class="LC_filename">'.$file_disp.'</span>');
1795: $result.='<input type="file" name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1796: $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1797: }
1798: }
1799: if ($file_counter) {
1800: $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
1801: '<span class="LC_info">'.
1802: '('.&mt('File(s) will be uploaded when you click on Save & Next below.',$file_counter).')</span><br /><br />';
1803: }
1804: }
1805: return $result;
1806: }
1807:
1808: sub show_problem {
1809: my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1810: my $rendered;
1811: my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1812: &Apache::lonxml::remember_problem_counter();
1813: if ($mode eq 'both' or $mode eq 'text') {
1814: $rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1815: $env{'request.course.id'},
1816: undef,\%form);
1817: }
1818: if ($removeform) {
1819: $rendered=~s|<form(.*?)>||g;
1820: $rendered=~s|</form>||g;
1821: $rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1822: }
1823: my $companswer;
1824: if ($mode eq 'both' or $mode eq 'answer') {
1825: &Apache::lonxml::restore_problem_counter();
1826: $companswer=
1827: &Apache::loncommon::get_student_answers($symb,$uname,$udom,
1828: $env{'request.course.id'},
1829: %form);
1830: }
1831: if ($removeform) {
1832: $companswer=~s|<form(.*?)>||g;
1833: $companswer=~s|</form>||g;
1834: $companswer=~s|name="submit"|name="would_have_been_submit"|g;
1835: }
1836: my $renderheading = &mt('View of the problem');
1837: my $answerheading = &mt('Correct answer');
1838: if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1839: my $stu_fullname = $env{'form.fullname'};
1840: if ($stu_fullname eq '') {
1841: $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
1842: }
1843: my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
1844: if ($forwhom ne '') {
1845: $renderheading = &mt('View of the problem for[_1]',$forwhom);
1846: $answerheading = &mt('Correct answer for[_1]',$forwhom);
1847: }
1848: }
1849: $rendered=
1850: '<div class="LC_Box">'
1851: .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1852: .$rendered
1853: .'</div>';
1854: $companswer=
1855: '<div class="LC_Box">'
1856: .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1857: .$companswer
1858: .'</div>';
1859: my $result;
1860: if ($mode eq 'both') {
1861: $result=$rendered.$companswer;
1862: } elsif ($mode eq 'text') {
1863: $result=$rendered;
1864: } elsif ($mode eq 'answer') {
1865: $result=$companswer;
1866: }
1867: return $result;
1868: }
1869:
1870: sub files_exist {
1871: my ($r, $symb) = @_;
1872: my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1873:
1874: foreach my $student (@students) {
1875: my ($uname,$udom,$fullname) = split(/:/,$student);
1876: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
1877: $udom,$uname);
1878: my ($string,$timestamp)= &get_last_submission(\%record);
1879: foreach my $submission (@$string) {
1880: my ($partid,$respid) =
1881: ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1882: my $files=&get_submitted_files($udom,$uname,$partid,$respid,
1883: \%record);
1884: return 1 if (@$files);
1885: }
1886: }
1887: return 0;
1888: }
1889:
1890: sub download_all_link {
1891: my ($r,$symb) = @_;
1892: unless (&files_exist($r, $symb)) {
1893: $r->print(&mt('There are currently no submitted documents.'));
1894: return;
1895: }
1896:
1897: my $all_students =
1898: join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
1899:
1900: my $parts =
1901: join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
1902:
1903: my $identifier = &Apache::loncommon::get_cgi_id();
1904: &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
1905: 'cgi.'.$identifier.'.symb' => $symb,
1906: 'cgi.'.$identifier.'.parts' => $parts,});
1907: $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
1908: &mt('Download All Submitted Documents').'</a>');
1909: return;
1910: }
1911:
1912: sub submit_download_link {
1913: my ($request,$symb) = @_;
1914: if (!$symb) { return ''; }
1915: #FIXME: Figure out which type of problem this is and provide appropriate download
1916: &download_all_link($request,$symb);
1917: }
1918:
1919: sub build_section_inputs {
1920: my $section_inputs;
1921: if ($env{'form.section'} eq '') {
1922: $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
1923: } else {
1924: my @sections = &Apache::loncommon::get_env_multiple('form.section');
1925: foreach my $section (@sections) {
1926: $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
1927: }
1928: }
1929: return $section_inputs;
1930: }
1931:
1932: # --------------------------- show submissions of a student, option to grade
1933: sub submission {
1934: my ($request,$counter,$total,$symb) = @_;
1935: my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
1936: $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
1937: my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
1938: $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1939:
1940: my $probtitle=&Apache::lonnet::gettitle($symb);
1941: if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1942:
1943: if (!&canview($usec)) {
1944: $request->print('<span class="LC_warning">Unable to view requested student.('.
1945: $uname.':'.$udom.' in section '.$usec.' in course id '.
1946: $env{'request.course.id'}.')</span>');
1947: return;
1948: }
1949:
1950: if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
1951: if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
1952: if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
1953: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1954: my $checkIcon = '<img alt="'.&mt('Check Mark').
1955: '" src="'.$request->dir_config('lonIconsURL').
1956: '/check.gif" height="16" border="0" />';
1957:
1958: # header info
1959: if ($counter == 0) {
1960: &sub_page_js($request);
1961: &sub_page_kw_js($request);
1962:
1963: # option to display problem, only once else it cause problems
1964: # with the form later since the problem has a form.
1965: if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1966: my $mode;
1967: if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1968: $mode='both';
1969: } elsif ($env{'form.vProb'} eq 'yes') {
1970: $mode='text';
1971: } elsif ($env{'form.vAns'} eq 'yes') {
1972: $mode='answer';
1973: }
1974: &Apache::lonxml::clear_problem_counter();
1975: $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1976: }
1977:
1978: # kwclr is the only variable that is guaranteed to be non blank
1979: # if this subroutine has been called once.
1980: my %keyhash = ();
1981: # if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1982: if (1) {
1983: %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1984: $env{'course.'.$env{'request.course.id'}.'.domain'},
1985: $env{'course.'.$env{'request.course.id'}.'.num'});
1986:
1987: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1988: $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
1989: $env{'form.kwclr'} = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
1990: $env{'form.kwsize'} = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
1991: $env{'form.kwstyle'} = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
1992: $env{'form.msgsub'} = $keyhash{$symb.'_subject'} ne '' ?
1993: $keyhash{$symb.'_subject'} : $probtitle;
1994: $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1995: }
1996: my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1997: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1998: $request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1999: '<input type="hidden" name="command" value="handgrade" />'."\n".
2000: '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
2001: '<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
2002: '<input type="hidden" name="refresh" value="off" />'."\n".
2003: '<input type="hidden" name="studentNo" value="" />'."\n".
2004: '<input type="hidden" name="gradeOpt" value="" />'."\n".
2005: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
2006: '<input type="hidden" name="vProb" value="'.$env{'form.vProb'}.'" />'."\n".
2007: '<input type="hidden" name="vAns" value="'.$env{'form.vAns'}.'" />'."\n".
2008: '<input type="hidden" name="lastSub" value="'.$env{'form.lastSub'}.'" />'."\n".
2009: &build_section_inputs().
2010: '<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
2011: '<input type="hidden" name="NCT"'.
2012: ' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
2013: # if ($env{'form.handgrade'} eq 'yes') {
2014: if (1) {
2015: $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
2016: '<input type="hidden" name="kwclr" value="'.$env{'form.kwclr'}.'" />'."\n".
2017: '<input type="hidden" name="kwsize" value="'.$env{'form.kwsize'}.'" />'."\n".
2018: '<input type="hidden" name="kwstyle" value="'.$env{'form.kwstyle'}.'" />'."\n".
2019: '<input type="hidden" name="msgsub" value="'.$env{'form.msgsub'}.'" />'."\n".
2020: '<input type="hidden" name="shownSub" value="0" />'."\n".
2021: '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
2022: foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
2023: $request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
2024: }
2025: }
2026:
2027: my ($cts,$prnmsg) = (1,'');
2028: while ($cts <= $env{'form.savemsgN'}) {
2029: $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
2030: (!exists($keyhash{$symb.'_savemsg'.$cts}) ?
2031: &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
2032: &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
2033: '" />'."\n".
2034: '<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
2035: $cts++;
2036: }
2037: $request->print($prnmsg);
2038:
2039: # if ($env{'form.handgrade'} eq 'yes') {
2040: if (1) {
2041:
2042: my %lt = &Apache::lonlocal::texthash(
2043: keyw => 'Keyword Options',
2044: list => 'List',
2045: past => 'Paste Selection to List',
2046: high => 'Highlight Attribute',
2047: );
2048: #
2049: # Print out the keyword options line
2050: #
2051: $request->print(<<KEYWORDS);
2052: <br /><b>$lt{'keyw'}:</b>
2053: <a href="javascript:keywords(document.SCORE);" target="_self">$lt{'list'}</a>
2054: <a href="#" onmousedown="javascript:getSel(); return false"
2055: CLASS="page">$lt{'past'}</a>
2056: <a href="javascript:kwhighlight();" target="_self">$lt{'high'}</a><br /><br />
2057: KEYWORDS
2058: #
2059: # Load the other essays for similarity check
2060: #
2061: my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
2062: my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
2063: $apath=&escape($apath);
2064: $apath=~s/\W/\_/gs;
2065: &init_old_essays($symb,$apath,$adom,$aname);
2066: }
2067: }
2068:
2069: # This is where output for one specific student would start
2070: my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
2071: $request->print(
2072: "\n\n"
2073: .'<div class="LC_grade_show_user'.$add_class.'">'
2074: .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
2075: ."\n"
2076: );
2077:
2078: # Show additional functions if allowed
2079: if ($perm{'vgr'}) {
2080: $request->print(
2081: &Apache::loncommon::track_student_link(
2082: &mt('View recent activity'),
2083: $uname,$udom,'check')
2084: .' '
2085: );
2086: }
2087: if ($perm{'opa'}) {
2088: $request->print(
2089: &Apache::loncommon::pprmlink(
2090: &mt('Set/Change parameters'),
2091: $uname,$udom,$symb,'check'));
2092: }
2093:
2094: # Show Problem
2095: if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
2096: my $mode;
2097: if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
2098: $mode='both';
2099: } elsif ($env{'form.vProb'} eq 'all' ) {
2100: $mode='text';
2101: } elsif ($env{'form.vAns'} eq 'all') {
2102: $mode='answer';
2103: }
2104: &Apache::lonxml::clear_problem_counter();
2105: $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
2106: }
2107:
2108: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
2109: my $res_error;
2110: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
2111: if ($res_error) {
2112: $request->print(&navmap_errormsg());
2113: return;
2114: }
2115:
2116: # Display student info
2117: $request->print(($counter == 0 ? '' : '<br />'));
2118:
2119: my $result='<div class="LC_Box">'
2120: .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
2121: $result.='<input type="hidden" name="name'.$counter.
2122: '" value="'.$env{'form.fullname'}.'" />'."\n";
2123: # if ($env{'form.handgrade'} eq 'no') {
2124: if (1) {
2125: $result.='<p class="LC_info">'
2126: .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
2127: ."</p>\n";
2128: }
2129:
2130: # If any part of the problem is an essay-response (handgraded), then check for collaborators
2131: my $fullname;
2132: my $col_fullnames = [];
2133: # if ($env{'form.handgrade'} eq 'yes') {
2134: if (1) {
2135: (my $sub_result,$fullname,$col_fullnames)=
2136: &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
2137: $counter);
2138: $result.=$sub_result;
2139: }
2140: $request->print($result."\n");
2141:
2142: # print student answer/submission
2143: # Options are (1) Handgraded submission only
2144: # (2) Last submission, includes submission that is not handgraded
2145: # (for multi-response type part)
2146: # (3) Last submission plus the parts info
2147: # (4) The whole record for this student
2148: if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
2149: my ($string,$timestamp)= &get_last_submission(\%record);
2150:
2151: my $lastsubonly;
2152:
2153: if ($$timestamp eq '') {
2154: $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>';
2155: } else {
2156: $lastsubonly =
2157: '<div class="LC_grade_submissions_body">'
2158: .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
2159:
2160: my %seenparts;
2161: my @part_response_id = &flatten_responseType($responseType);
2162: foreach my $part (@part_response_id) {
2163: next if ($env{'form.lastSub'} eq 'hdgrade'
2164: && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
2165:
2166: my ($partid,$respid) = @{ $part };
2167: my $display_part=&get_display_part($partid,$symb);
2168: if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
2169: if (exists($seenparts{$partid})) { next; }
2170: $seenparts{$partid}=1;
2171: my $submitby='<b>Part:</b> '.$display_part.
2172: ' <b>Collaborative submission by:</b> '.
2173: '<a href="javascript:viewSubmitter(\''.
2174: $env{"form.$uname:$udom:$partid:submitted_by"}.
2175: '\');" target="_self">'.
2176: $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
2177: $request->print($submitby);
2178: next;
2179: }
2180: my $responsetype = $responseType->{$partid}->{$respid};
2181: if (!exists($record{"resource.$partid.$respid.submission"})) {
2182: $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
2183: '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
2184: ' <span class="LC_internal_info">'.
2185: '('.&mt('Response ID: [_1]',$respid).')'.
2186: '</span> '.
2187: '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
2188: next;
2189: }
2190: foreach my $submission (@$string) {
2191: my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
2192: if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
2193: my ($ressub,$hide,$subval) = split(/:/,$submission,3);
2194: # Similarity check
2195: my $similar='';
2196: my ($type,$trial,$rndseed);
2197: if ($hide eq 'rand') {
2198: $type = 'randomizetry';
2199: $trial = $record{"resource.$partid.tries"};
2200: $rndseed = $record{"resource.$partid.rndseed"};
2201: }
2202: if($env{'form.checkPlag'}){
2203: my ($oname,$odom,$ocrsid,$oessay,$osim)=
2204: &most_similar($uname,$udom,$symb,$subval);
2205: if ($osim) {
2206: $osim=int($osim*100.0);
2207: my %old_course_desc =
2208: &Apache::lonnet::coursedescription($ocrsid,
2209: {'one_time' => 1});
2210:
2211: if ($hide eq 'anon') {
2212: $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
2213: &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
2214: } else {
2215: $similar="<hr /><h3><span class=\"LC_warning\">".
2216: &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
2217: $osim,
2218: &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
2219: $old_course_desc{'description'},
2220: $old_course_desc{'num'},
2221: $old_course_desc{'domain'}).
2222: '</span></h3><blockquote><i>'.
2223: &keywords_highlight($oessay).
2224: '</i></blockquote><hr />';
2225: }
2226: }
2227: }
2228: my $order=&get_order($partid,$respid,$symb,$uname,$udom,
2229: undef,$type,$trial,$rndseed);
2230: if ($env{'form.lastSub'} eq 'lastonly' ||
2231: ($env{'form.lastSub'} eq 'hdgrade' &&
2232: $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
2233: my $display_part=&get_display_part($partid,$symb);
2234: $lastsubonly.='<div class="LC_grade_submission_part">'.
2235: '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
2236: ' <span class="LC_internal_info">'.
2237: '('.&mt('Response ID: [_1]',$respid).')'.
2238: '</span> ';
2239: my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
2240: if (@$files) {
2241: if ($hide eq 'anon') {
2242: $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
2243: } else {
2244: $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</span><br />';
2245: foreach my $file (@$files) {
2246: &Apache::lonnet::allowuploaded('/adm/grades',$file);
2247: $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" /> '.$file.'</a>';
2248: }
2249: }
2250: $lastsubonly.='<br />';
2251: }
2252: if ($hide eq 'anon') {
2253: $lastsubonly.='<b>'.&mt('Anonymous Survey').'</b>';
2254: } else {
2255: $lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
2256: &cleanRecord($subval,$responsetype,$symb,$partid,
2257: $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
2258: }
2259: if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
2260: $lastsubonly.='</div>';
2261: }
2262: }
2263: }
2264: $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
2265: }
2266: $request->print($lastsubonly);
2267: } elsif ($env{'form.lastSub'} eq 'datesub') {
2268: my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
2269: $request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
2270: } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
2271: $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
2272: $env{'request.course.id'},
2273: $last,'.submission',
2274: 'Apache::grades::keywords_highlight'));
2275: }
2276: $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
2277: .$udom.'" />'."\n");
2278: # return if view submission with no grading option
2279: if (!&canmodify($usec)) {
2280: $request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
2281: return;
2282: } else {
2283: $request->print('</div>'."\n");
2284: }
2285:
2286: # essay grading message center
2287: # if ($env{'form.handgrade'} eq 'yes') {
2288: if (1) {
2289: my $result='<div class="LC_grade_message_center">';
2290:
2291: $result.='<div class="LC_grade_message_center_header">'.
2292: &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
2293: my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
2294: my $msgfor = $givenn.' '.$lastname;
2295: if (scalar(@$col_fullnames) > 0) {
2296: my $lastone = pop(@$col_fullnames);
2297: $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
2298: }
2299: $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
2300: $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
2301: '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
2302: $result.=' <a href="javascript:msgCenter(document.SCORE,'.$counter.
2303: ',\''.$msgfor.'\');" target="_self">'.
2304: &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
2305: &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
2306: '<img src="'.$request->dir_config('lonIconsURL').
2307: '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
2308: '<br /> ('.
2309: &mt('Message will be sent when you click on Save & Next below.').")\n";
2310: $result.='</div></div>';
2311: $request->print($result);
2312: }
2313:
2314: my %seen = ();
2315: my @partlist;
2316: my @gradePartRespid;
2317: my @part_response_id = &flatten_responseType($responseType);
2318: $request->print(
2319: '<div class="LC_Box">'
2320: .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
2321: );
2322: $request->print(&gradeBox_start());
2323: foreach my $part_response_id (@part_response_id) {
2324: my ($partid,$respid) = @{ $part_response_id };
2325: my $part_resp = join('_',@{ $part_response_id });
2326: next if ($seen{$partid} > 0);
2327: $seen{$partid}++;
2328: next if ($$handgrade{$part_resp} ne 'yes'
2329: && $env{'form.lastSub'} eq 'hdgrade');
2330: push(@partlist,$partid);
2331: push(@gradePartRespid,$partid.'.'.$respid);
2332: $request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
2333: }
2334: $request->print(&gradeBox_end()); # </div>
2335: $request->print('</div>');
2336:
2337: $request->print('<div class="LC_grade_info_links">');
2338: $request->print('</div>');
2339:
2340: $result='<input type="hidden" name="partlist'.$counter.
2341: '" value="'.(join ":",@partlist).'" />'."\n";
2342: $result.='<input type="hidden" name="gradePartRespid'.
2343: '" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
2344: my $ctr = 0;
2345: while ($ctr < scalar(@partlist)) {
2346: $result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
2347: $partlist[$ctr].'" />'."\n";
2348: $ctr++;
2349: }
2350: $request->print($result.''."\n");
2351:
2352: # Done with printing info for one student
2353:
2354: $request->print('</div>');#LC_grade_show_user
2355:
2356:
2357: # print end of form
2358: if ($counter == $total) {
2359: my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
2360: $endform.='<input type="button" value="'.&mt('Save & Next').'" '.
2361: 'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
2362: $total.','.scalar(@partlist).');" target="_self" /> '."\n";
2363: my $ntstu ='<select name="NTSTU">'.
2364: '<option>1</option><option>2</option>'.
2365: '<option>3</option><option>5</option>'.
2366: '<option>7</option><option>10</option></select>'."\n";
2367: my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
2368: $ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
2369: $endform.=&mt('[_1]student(s)',$ntstu);
2370: $endform.=' <input type="button" value="'.&mt('Previous').'" '.
2371: 'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> '."\n".
2372: '<input type="button" value="'.&mt('Next').'" '.
2373: 'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> ';
2374: $endform.='<span class="LC_warning">'.
2375: &mt('(Next and Previous (student) do not save the scores.)').
2376: '</span>'."\n" ;
2377: $endform.="<input type='hidden' value='".&get_increment().
2378: "' name='increment' />";
2379: $endform.='</td></tr></table></form>';
2380: $request->print($endform);
2381: }
2382: return '';
2383: }
2384:
2385: sub check_collaborators {
2386: my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
2387: my ($result,@col_fullnames);
2388: my ($classlist,undef,$fullname) = &getclasslist('all','0');
2389: foreach my $part (keys(%$handgrade)) {
2390: my $ncol = &Apache::lonnet::EXT('resource.'.$part.
2391: '.maxcollaborators',
2392: $symb,$udom,$uname);
2393: next if ($ncol <= 0);
2394: $part =~ s/\_/\./g;
2395: next if ($record->{'resource.'.$part.'.collaborators'} eq '');
2396: my (@good_collaborators, @bad_collaborators);
2397: foreach my $possible_collaborator
2398: (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) {
2399: $possible_collaborator =~ s/[\$\^\(\)]//g;
2400: next if ($possible_collaborator eq '');
2401: my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
2402: $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
2403: next if ($co_name eq $uname && $co_dom eq $udom);
2404: # Doing this grep allows 'fuzzy' specification
2405: my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i,
2406: keys(%$classlist));
2407: if (! scalar(@matches)) {
2408: push(@bad_collaborators, $possible_collaborator);
2409: } else {
2410: push(@good_collaborators, @matches);
2411: }
2412: }
2413: if (scalar(@good_collaborators) != 0) {
2414: $result.='<br />'.&mt('Collaborators:').'<ol>';
2415: foreach my $name (@good_collaborators) {
2416: my ($lastname,$givenn) = split(/,/,$$fullname{$name});
2417: push(@col_fullnames, $givenn.' '.$lastname);
2418: $result.='<li>'.$fullname->{$name}.'</li>';
2419: }
2420: $result.='</ol><br />'."\n";
2421: my ($part)=split(/\./,$part);
2422: $result.='<input type="hidden" name="collaborator'.$counter.
2423: '" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
2424: "\n";
2425: }
2426: if (scalar(@bad_collaborators) > 0) {
2427: $result.='<div class="LC_warning">';
2428: $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
2429: $result .= '</div>';
2430: }
2431: if (scalar(@bad_collaborators > $ncol)) {
2432: $result .= '<div class="LC_warning">';
2433: $result .= &mt('This student has submitted too many '.
2434: 'collaborators. Maximum is [_1].',$ncol);
2435: $result .= '</div>';
2436: }
2437: }
2438: return ($result,$fullname,\@col_fullnames);
2439: }
2440:
2441: #--- Retrieve the last submission for all the parts
2442: sub get_last_submission {
2443: my ($returnhash)=@_;
2444: my (@string,$timestamp,%lasthidden);
2445: if ($$returnhash{'version'}) {
2446: my %lasthash=();
2447: my ($version);
2448: for ($version=1;$version<=$$returnhash{'version'};$version++) {
2449: foreach my $key (sort(split(/\:/,
2450: $$returnhash{$version.':keys'}))) {
2451: $lasthash{$key}=$$returnhash{$version.':'.$key};
2452: $timestamp =
2453: &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
2454: }
2455: }
2456: my (%typeparts,%randombytry);
2457: my $showsurv =
2458: &Apache::lonnet::allowed('vas',$env{'request.course.id'});
2459: foreach my $key (sort(keys(%lasthash))) {
2460: if ($key =~ /\.type$/) {
2461: if (($lasthash{$key} eq 'anonsurvey') ||
2462: ($lasthash{$key} eq 'anonsurveycred') ||
2463: ($lasthash{$key} eq 'randomizetry')) {
2464: my ($ign,@parts) = split(/\./,$key);
2465: pop(@parts);
2466: my $id = join('.',@parts);
2467: if ($lasthash{$key} eq 'randomizetry') {
2468: $randombytry{$ign.'.'.$id} = $lasthash{$key};
2469: } else {
2470: unless ($showsurv) {
2471: $typeparts{$ign.'.'.$id} = $lasthash{$key};
2472: }
2473: }
2474: delete($lasthash{$key});
2475: }
2476: }
2477: }
2478: my @hidden = keys(%typeparts);
2479: my @randomize = keys(%randombytry);
2480: foreach my $key (keys(%lasthash)) {
2481: next if ($key !~ /\.submission$/);
2482: my $hide;
2483: if (@hidden) {
2484: foreach my $id (@hidden) {
2485: if ($key =~ /^\Q$id\E/) {
2486: $hide = 'anon';
2487: last;
2488: }
2489: }
2490: }
2491: unless ($hide) {
2492: if (@randomize) {
2493: foreach my $id (@hidden) {
2494: if ($key =~ /^\Q$id\E/) {
2495: $hide = 'rand';
2496: last;
2497: }
2498: }
2499: }
2500: }
2501: my ($partid,$foo) = split(/submission$/,$key);
2502: my $draft = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
2503: '<span class="LC_warning">Draft Copy</span> ' : '';
2504: push(@string, join(':', $key, $hide, $draft.$lasthash{$key}));
2505: }
2506: }
2507: if (!@string) {
2508: $string[0] =
2509: '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
2510: }
2511: return (\@string,\$timestamp);
2512: }
2513:
2514: #--- High light keywords, with style choosen by user.
2515: sub keywords_highlight {
2516: my $string = shift;
2517: my $size = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
2518: my $styleon = $env{'form.kwstyle'} eq '' ? '' : $env{'form.kwstyle'};
2519: (my $styleoff = $styleon) =~ s/\</\<\//;
2520: my @keylist = split(/[,\s+]/,$env{'form.keywords'});
2521: foreach my $keyword (@keylist) {
2522: $string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
2523: }
2524: return $string;
2525: }
2526:
2527: # For Tasks provide a mechanism to display previous version for one specific student
2528:
2529: sub show_previous_task_version {
2530: my ($request,$symb) = @_;
2531: if ($symb eq '') {
2532: $request->print("Unable to handle ambiguous references.");
2533:
2534: return '';
2535: }
2536: my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
2537: my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
2538: if (!&canview($usec)) {
2539: $request->print('<span class="LC_warning">Unable to view previous version for requested student.('.
2540: $uname.':'.$udom.' in section '.$usec.' in course id '.
2541: $env{'request.course.id'}.')</span>');
2542: return;
2543: }
2544: my $mode = 'both';
2545: my $isTask = ($symb =~/\.task$/);
2546: if ($isTask) {
2547: if ($env{'form.previousversion'} =~ /^\d+$/) {
2548: if ($env{'form.fullname'} eq '') {
2549: $env{'form.fullname'} =
2550: &Apache::loncommon::plainname($uname,$udom,'lastname');
2551: }
2552: my $probtitle=&Apache::lonnet::gettitle($symb);
2553: $request->print("\n\n".
2554: '<div class="LC_grade_show_user">'.
2555: '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
2556: '</h2>'."\n");
2557: &Apache::lonxml::clear_problem_counter();
2558: $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
2559: {'previousversion' => $env{'form.previousversion'} }));
2560: $request->print("\n</div>");
2561: }
2562: }
2563: return;
2564: }
2565:
2566: sub choose_task_version_form {
2567: my ($symb,$uname,$udom,$nomenu) = @_;
2568: my $isTask = ($symb =~/\.task$/);
2569: my ($current,$version,$result,$js,$displayed,$rowtitle);
2570: if ($isTask) {
2571: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
2572: $udom,$uname);
2573: if (($record{'resource.0.version'} eq '') ||
2574: ($record{'resource.0.version'} < 2)) {
2575: return ($record{'resource.0.version'},
2576: $record{'resource.0.version'},$result,$js);
2577: } else {
2578: $current = $record{'resource.0.version'};
2579: }
2580: if ($env{'form.previousversion'}) {
2581: $displayed = $env{'form.previousversion'};
2582: $rowtitle = &mt('Choose another version:')
2583: } else {
2584: $displayed = $current;
2585: $rowtitle = &mt('Show earlier version:');
2586: }
2587: $result = '<div class="LC_left_float">';
2588: my $list;
2589: my $numversions = 0;
2590: for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
2591: if ($i == $current) {
2592: if (!$env{'form.previousversion'} || $nomenu) {
2593: next;
2594: } else {
2595: $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
2596: $numversions ++;
2597: }
2598: } elsif (defined($record{'resource.'.$i.'.0.status'})) {
2599: unless ($i == $env{'form.previousversion'}) {
2600: $numversions ++;
2601: }
2602: $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
2603: }
2604: }
2605: if ($numversions) {
2606: $symb = &HTML::Entities::encode($symb,'<>"&');
2607: $result .=
2608: '<form name="getprev" method="post" action=""'.
2609: ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
2610: &Apache::loncommon::start_data_table().
2611: &Apache::loncommon::start_data_table_row().
2612: '<th align="left">'.$rowtitle.'</th>'.
2613: '<td><select name="version">'.
2614: '<option>'.&mt('Select').'</option>'.
2615: $list.
2616: '</select></td>'.
2617: &Apache::loncommon::end_data_table_row();
2618: unless ($nomenu) {
2619: $result .= &Apache::loncommon::start_data_table_row().
2620: '<th align="left">'.&mt('Open in new window').'</th>'.
2621: '<td><span class="LC_nobreak">'.
2622: '<label><input type="radio" name="prevwin" value="1" />'.
2623: &mt('Yes').'</label>'.
2624: '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
2625: '</span></td>'.
2626: &Apache::loncommon::end_data_table_row();
2627: }
2628: $result .=
2629: &Apache::loncommon::start_data_table_row().
2630: '<th align="left"> </th>'.
2631: '<td>'.
2632: '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
2633: '</td>'.
2634: &Apache::loncommon::end_data_table_row().
2635: &Apache::loncommon::end_data_table().
2636: '</form>';
2637: $js = &previous_display_javascript($nomenu,$current);
2638: } elsif ($displayed && $nomenu) {
2639: $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
2640: } else {
2641: $result .= &mt('No previous versions to show for this student');
2642: }
2643: $result .= '</div>';
2644: }
2645: return ($current,$displayed,$result,$js);
2646: }
2647:
2648: sub previous_display_javascript {
2649: my ($nomenu,$current) = @_;
2650: my $js = <<"JSONE";
2651: <script type="text/javascript">
2652: // <![CDATA[
2653: function previousVersion(uname,udom,symb) {
2654: var current = '$current';
2655: var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
2656: var prevstr = new RegExp("^\\\\d+\$");
2657: if (!prevstr.test(version)) {
2658: return false;
2659: }
2660: var url = '';
2661: if (version == current) {
2662: url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
2663: } else {
2664: url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
2665: }
2666: JSONE
2667: if ($nomenu) {
2668: $js .= <<"JSTWO";
2669: document.location.href = url;
2670: JSTWO
2671: } else {
2672: $js .= <<"JSTHREE";
2673: var newwin = 0;
2674: for (var i=0; i<document.getprev.prevwin.length; i++) {
2675: if (document.getprev.prevwin[i].checked == true) {
2676: newwin = document.getprev.prevwin[i].value;
2677: }
2678: }
2679: if (newwin == 1) {
2680: var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
2681: url = url+'&inhibitmenu=yes';
2682: if (typeof(previousWin) == 'undefined' || previousWin.closed) {
2683: previousWin = window.open(url,'',options,1);
2684: } else {
2685: previousWin.location.href = url;
2686: }
2687: previousWin.focus();
2688: return false;
2689: } else {
2690: document.location.href = url;
2691: return false;
2692: }
2693: JSTHREE
2694: }
2695: $js .= <<"ENDJS";
2696: return false;
2697: }
2698: // ]]>
2699: </script>
2700: ENDJS
2701:
2702: }
2703:
2704: #--- Called from submission routine
2705: sub processHandGrade {
2706: my ($request,$symb) = @_;
2707: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
2708: my $button = $env{'form.gradeOpt'};
2709: my $ngrade = $env{'form.NCT'};
2710: my $ntstu = $env{'form.NTSTU'};
2711: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2712: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2713:
2714: if ($button eq 'Save & Next') {
2715: my $ctr = 0;
2716: while ($ctr < $ngrade) {
2717: my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
2718: my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
2719: if ($errorflag eq 'no_score') {
2720: $ctr++;
2721: next;
2722: }
2723: if ($errorflag eq 'not_allowed') {
2724: $request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
2725: $ctr++;
2726: next;
2727: }
2728: my $includemsg = $env{'form.includemsg'.$ctr};
2729: my ($subject,$message,$msgstatus) = ('','','');
2730: my $restitle = &Apache::lonnet::gettitle($symb);
2731: my ($feedurl,$showsymb) =
2732: &get_feedurl_and_symb($symb,$uname,$udom);
2733: my $messagetail;
2734: if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
2735: $subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
2736: unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
2737: $subject.=' ['.$restitle.']';
2738: my (@msgnum) = split(/,/,$includemsg);
2739: foreach (@msgnum) {
2740: $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
2741: }
2742: $message =&Apache::lonfeedback::clear_out_html($message);
2743: if ($env{'form.withgrades'.$ctr}) {
2744: $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
2745: $messagetail = " for <a href=\"".
2746: $feedurl."?symb=$showsymb\">$restitle</a>";
2747: }
2748: $msgstatus =
2749: &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
2750: $message.$messagetail,
2751: undef,$feedurl,undef,
2752: undef,undef,$showsymb,
2753: $restitle);
2754: $request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
2755: $msgstatus.'<br />');
2756: }
2757: if ($env{'form.collaborator'.$ctr}) {
2758: my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
2759: foreach my $collabstr (@collabstrs) {
2760: my ($part,@collaborators) = split(/:/,$collabstr);
2761: foreach my $collaborator (@collaborators) {
2762: my ($errorflag,$pts,$wgt) =
2763: &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
2764: $env{'form.unamedom'.$ctr},$part);
2765: if ($errorflag eq 'not_allowed') {
2766: $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
2767: next;
2768: } elsif ($message ne '') {
2769: my ($baseurl,$showsymb) =
2770: &get_feedurl_and_symb($symb,$collaborator,
2771: $udom);
2772: if ($env{'form.withgrades'.$ctr}) {
2773: $messagetail = " for <a href=\"".
2774: $baseurl."?symb=$showsymb\">$restitle</a>";
2775: }
2776: $msgstatus =
2777: &Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
2778: }
2779: }
2780: }
2781: }
2782: $ctr++;
2783: }
2784: }
2785:
2786: # if ($env{'form.handgrade'} eq 'yes') {
2787: if (1) {
2788: # Keywords sorted in alphabatical order
2789: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
2790: my %keyhash = ();
2791: $env{'form.keywords'} =~ s/,\s{0,}|\s+/ /g;
2792: $env{'form.keywords'} =~ s/^\s+|\s+$//;
2793: my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
2794: $env{'form.keywords'} = join(' ',@keywords);
2795: $keyhash{$symb.'_keywords'} = $env{'form.keywords'};
2796: $keyhash{$symb.'_subject'} = $env{'form.msgsub'};
2797: $keyhash{$loginuser.'_kwclr'} = $env{'form.kwclr'};
2798: $keyhash{$loginuser.'_kwsize'} = $env{'form.kwsize'};
2799: $keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
2800:
2801: # message center - Order of message gets changed. Blank line is eliminated.
2802: # New messages are saved in env for the next student.
2803: # All messages are saved in nohist_handgrade.db
2804: my ($ctr,$idx) = (1,1);
2805: while ($ctr <= $env{'form.savemsgN'}) {
2806: if ($env{'form.savemsg'.$ctr} ne '') {
2807: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
2808: $idx++;
2809: }
2810: $ctr++;
2811: }
2812: $ctr = 0;
2813: while ($ctr < $ngrade) {
2814: if ($env{'form.newmsg'.$ctr} ne '') {
2815: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2816: $env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2817: $idx++;
2818: }
2819: $ctr++;
2820: }
2821: $env{'form.savemsgN'} = --$idx;
2822: $keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
2823: my $putresult = &Apache::lonnet::put
2824: ('nohist_handgrade',\%keyhash,$cdom,$cnum);
2825: }
2826: # Called by Save & Refresh from Highlight Attribute Window
2827: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
2828: if ($env{'form.refresh'} eq 'on') {
2829: my ($ctr,$total) = (0,0);
2830: while ($ctr < $ngrade) {
2831: $total++ if $env{'form.unamedom'.$ctr} ne '';
2832: $ctr++;
2833: }
2834: $env{'form.NTSTU'}=$ngrade;
2835: $ctr = 0;
2836: while ($ctr < $total) {
2837: my $processUser = $env{'form.unamedom'.$ctr};
2838: ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
2839: $env{'form.fullname'} = $$fullname{$processUser};
2840: &submission($request,$ctr,$total-1,$symb);
2841: $ctr++;
2842: }
2843: return '';
2844: }
2845:
2846: # Get the next/previous one or group of students
2847: my $firststu = $env{'form.unamedom0'};
2848: my $laststu = $env{'form.unamedom'.($ngrade-1)};
2849: my $ctr = 2;
2850: while ($laststu eq '') {
2851: $laststu = $env{'form.unamedom'.($ngrade-$ctr)};
2852: $ctr++;
2853: $laststu = $firststu if ($ctr > $ngrade);
2854: }
2855:
2856: my (@parsedlist,@nextlist);
2857: my ($nextflg) = 0;
2858: foreach my $item (sort
2859: {
2860: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
2861: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
2862: }
2863: return $a cmp $b;
2864: } (keys(%$fullname))) {
2865: # FIXME: this is fishy, looks like the button label
2866: if ($nextflg == 1 && $button =~ /Next$/) {
2867: push(@parsedlist,$item);
2868: }
2869: $nextflg = 1 if ($item eq $laststu);
2870: if ($button eq 'Previous') {
2871: last if ($item eq $firststu);
2872: push(@parsedlist,$item);
2873: }
2874: }
2875: $ctr = 0;
2876: # FIXME: this is fishy, looks like the button label
2877: @parsedlist = reverse @parsedlist if ($button eq 'Previous');
2878: my $res_error;
2879: my ($partlist) = &response_type($symb,\$res_error);
2880: if ($res_error) {
2881: $request->print(&navmap_errormsg());
2882: return;
2883: }
2884: foreach my $student (@parsedlist) {
2885: my $submitonly=$env{'form.submitonly'};
2886: my ($uname,$udom) = split(/:/,$student);
2887:
2888: if ($submitonly eq 'queued') {
2889: my %queue_status =
2890: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
2891: $udom,$uname);
2892: next if (!defined($queue_status{'gradingqueue'}));
2893: }
2894:
2895: if ($submitonly =~ /^(yes|graded|incorrect)$/) {
2896: # my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
2897: my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
2898: my $submitted = 0;
2899: my $ungraded = 0;
2900: my $incorrect = 0;
2901: foreach my $item (keys(%status)) {
2902: $submitted = 1 if ($status{$item} ne 'nothing');
2903: $ungraded = 1 if ($status{$item} =~ /^ungraded/);
2904: $incorrect = 1 if ($status{$item} =~ /^incorrect/);
2905: my ($foo,$partid,$foo1) = split(/\./,$item);
2906: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
2907: $submitted = 0;
2908: }
2909: }
2910: next if (!$submitted && ($submitonly eq 'yes' ||
2911: $submitonly eq 'incorrect' ||
2912: $submitonly eq 'graded'));
2913: next if (!$ungraded && ($submitonly eq 'graded'));
2914: next if (!$incorrect && $submitonly eq 'incorrect');
2915: }
2916: push(@nextlist,$student) if ($ctr < $ntstu);
2917: last if ($ctr == $ntstu);
2918: $ctr++;
2919: }
2920:
2921: $ctr = 0;
2922: my $total = scalar(@nextlist)-1;
2923:
2924: foreach (sort(@nextlist)) {
2925: my ($uname,$udom,$submitter) = split(/:/);
2926: $env{'form.student'} = $uname;
2927: $env{'form.userdom'} = $udom;
2928: $env{'form.fullname'} = $$fullname{$_};
2929: &submission($request,$ctr,$total,$symb);
2930: $ctr++;
2931: }
2932: if ($total < 0) {
2933: my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
2934: $request->print($the_end);
2935: }
2936: return '';
2937: }
2938:
2939: #---- Save the score and award for each student, if changed
2940: sub saveHandGrade {
2941: my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
2942: my @version_parts;
2943: my $usec = &Apache::lonnet::getsection($domain,$stuname,
2944: $env{'request.course.id'});
2945: if (!&canmodify($usec)) { return('not_allowed'); }
2946: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
2947: my @parts_graded;
2948: my %newrecord = ();
2949: my ($pts,$wgt) = ('','');
2950: my %aggregate = ();
2951: my $aggregateflag = 0;
2952: my @parts = split(/:/,$env{'form.partlist'.$newflg});
2953: foreach my $new_part (@parts) {
2954: #collaborator ($submi may vary for different parts
2955: if ($submitter && $new_part ne $part) { next; }
2956: my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
2957: if ($dropMenu eq 'excused') {
2958: if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
2959: $newrecord{'resource.'.$new_part.'.solved'} = 'excused';
2960: if (exists($record{'resource.'.$new_part.'.awarded'})) {
2961: $newrecord{'resource.'.$new_part.'.awarded'} = '';
2962: }
2963: $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
2964: }
2965: } elsif ($dropMenu eq 'reset status'
2966: && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
2967: foreach my $key (keys(%record)) {
2968: if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
2969: }
2970: $newrecord{'resource.'.$new_part.'.regrader'}=
2971: "$env{'user.name'}:$env{'user.domain'}";
2972: my $totaltries = $record{'resource.'.$part.'.tries'};
2973:
2974: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
2975: [$new_part]);
2976: my $aggtries =$totaltries;
2977: if ($last_resets{$new_part}) {
2978: $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
2979: $new_part);
2980: }
2981:
2982: my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
2983: if ($aggtries > 0) {
2984: &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
2985: $aggregateflag = 1;
2986: }
2987: } elsif ($dropMenu eq '') {
2988: $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ?
2989: $env{'form.GD_BOX'.$newflg.'_'.$new_part} :
2990: $env{'form.RADVAL'.$newflg.'_'.$new_part});
2991: if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
2992: next;
2993: }
2994: $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 :
2995: $env{'form.WGT'.$newflg.'_'.$new_part};
2996: my $partial= $pts/$wgt;
2997: if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
2998: #do not update score for part if not changed.
2999: &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
3000: next;
3001: } else {
3002: push(@parts_graded,$new_part);
3003: }
3004: if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
3005: $newrecord{'resource.'.$new_part.'.awarded'} = $partial;
3006: }
3007: my $reckey = 'resource.'.$new_part.'.solved';
3008: if ($partial == 0) {
3009: if ($record{$reckey} ne 'incorrect_by_override') {
3010: $newrecord{$reckey} = 'incorrect_by_override';
3011: }
3012: } else {
3013: if ($record{$reckey} ne 'correct_by_override') {
3014: $newrecord{$reckey} = 'correct_by_override';
3015: }
3016: }
3017: if ($submitter &&
3018: ($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
3019: $newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
3020: }
3021: $newrecord{'resource.'.$new_part.'.regrader'}=
3022: "$env{'user.name'}:$env{'user.domain'}";
3023: }
3024: # unless problem has been graded, set flag to version the submitted files
3025: unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/ ||
3026: $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
3027: $dropMenu eq 'reset status')
3028: {
3029: push(@version_parts,$new_part);
3030: }
3031: }
3032: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3033: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3034:
3035: if (%newrecord) {
3036: if (@version_parts) {
3037: my @changed_keys = &version_portfiles(\%record, \@parts_graded,
3038: $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
3039: @newrecord{@changed_keys} = @record{@changed_keys};
3040: foreach my $new_part (@version_parts) {
3041: &handback_files($request,$symb,$stuname,$domain,$newflg,
3042: $new_part,\%newrecord);
3043: }
3044: }
3045: &Apache::lonnet::cstore(\%newrecord,$symb,
3046: $env{'request.course.id'},$domain,$stuname);
3047: &check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
3048: $cdom,$cnum,$domain,$stuname);
3049: }
3050: if ($aggregateflag) {
3051: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
3052: $cdom,$cnum);
3053: }
3054: return ('',$pts,$wgt);
3055: }
3056:
3057: sub check_and_remove_from_queue {
3058: my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
3059: my @ungraded_parts;
3060: foreach my $part (@{$parts}) {
3061: if ( $record->{ 'resource.'.$part.'.awarded'} eq ''
3062: && $record->{ 'resource.'.$part.'.solved' } ne 'excused'
3063: && $newrecord->{'resource.'.$part.'.awarded'} eq ''
3064: && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
3065: ) {
3066: push(@ungraded_parts, $part);
3067: }
3068: }
3069: if ( !@ungraded_parts ) {
3070: &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
3071: $cnum,$domain,$stuname);
3072: }
3073: }
3074:
3075: sub handback_files {
3076: my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
3077: my $portfolio_root = '/userfiles/portfolio';
3078: my $res_error;
3079: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
3080: if ($res_error) {
3081: $request->print('<br />'.&navmap_errormsg().'<br />');
3082: return;
3083: }
3084: my @handedback;
3085: my $file_msg;
3086: my @part_response_id = &flatten_responseType($responseType);
3087: foreach my $part_response_id (@part_response_id) {
3088: my ($part_id,$resp_id) = @{ $part_response_id };
3089: my $part_resp = join('_',@{ $part_response_id });
3090: if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
3091: for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
3092: # if multiple files are uploaded names will be 'returndoc2','returndoc3'
3093: if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
3094: my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
3095: my ($directory,$answer_file) =
3096: ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
3097: my ($answer_name,$answer_ver,$answer_ext) =
3098: &file_name_version_ext($answer_file);
3099: my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
3100: my $getpropath = 1;
3101: my ($dir_list,$listerror) =
3102: &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
3103: $domain,$stuname,$getpropath);
3104: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
3105: # fix file name
3106: my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
3107: my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
3108: $newflg.'_'.$part_resp.'_returndoc'.$counter,
3109: $save_file_name);
3110: if ($result !~ m|^/uploaded/|) {
3111: $request->print('<br /><span class="LC_error">'.
3112: &mt('An error occurred ([_1]) while trying to upload [_2].',
3113: $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
3114: '</span>');
3115: } else {
3116: # mark the file as read only
3117: push(@handedback,$save_file_name);
3118: if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
3119: $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
3120: }
3121: $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
3122: $file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
3123: }
3124: $request->print('<br />'.&mt('[_1] will be the uploaded file name [_2]','<span class="LC_info">'.$fname.'</span>','<span class="LC_filename">'.$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter}.'</span>'));
3125: }
3126: }
3127: }
3128: }
3129: if (@handedback > 0) {
3130: $request->print('<br />');
3131: my @what = ($symb,$env{'request.course.id'},'handback');
3132: &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
3133: my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});
3134: my ($subject,$message);
3135: if (scalar(@handedback) == 1) {
3136: $subject = &mt_user($user_lh,'File Handed Back by Instructor');
3137: $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
3138: } else {
3139: $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
3140: $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
3141: }
3142: $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
3143: $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
3144: &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
3145: my ($feedurl,$showsymb) =
3146: &get_feedurl_and_symb($symb,$domain,$stuname);
3147: my $restitle = &Apache::lonnet::gettitle($symb);
3148: $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
3149: my $msgstatus =
3150: &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
3151: $message,undef,$feedurl,undef,undef,undef,$showsymb,
3152: $restitle);
3153: if ($msgstatus) {
3154: $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
3155: }
3156: }
3157: return;
3158: }
3159:
3160: sub get_feedurl_and_symb {
3161: my ($symb,$uname,$udom) = @_;
3162: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3163: $url = &Apache::lonnet::clutter($url);
3164: my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
3165: $symb,$udom,$uname);
3166: if ($encrypturl =~ /^yes$/i) {
3167: &Apache::lonenc::encrypted(\$url,1);
3168: &Apache::lonenc::encrypted(\$symb,1);
3169: }
3170: return ($url,$symb);
3171: }
3172:
3173: sub get_submitted_files {
3174: my ($udom,$uname,$partid,$respid,$record) = @_;
3175: my @files;
3176: if ($$record{"resource.$partid.$respid.portfiles"}) {
3177: my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
3178: foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
3179: push(@files,$file_url.$file);
3180: }
3181: }
3182: if ($$record{"resource.$partid.$respid.uploadedurl"}) {
3183: push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
3184: }
3185: return (\@files);
3186: }
3187:
3188: # ----------- Provides number of tries since last reset.
3189: sub get_num_tries {
3190: my ($record,$last_reset,$part) = @_;
3191: my $timestamp = '';
3192: my $num_tries = 0;
3193: if ($$record{'version'}) {
3194: for (my $version=$$record{'version'};$version>=1;$version--) {
3195: if (exists($$record{$version.':resource.'.$part.'.solved'})) {
3196: $timestamp = $$record{$version.':timestamp'};
3197: if ($timestamp > $last_reset) {
3198: $num_tries ++;
3199: } else {
3200: last;
3201: }
3202: }
3203: }
3204: }
3205: return $num_tries;
3206: }
3207:
3208: # ----------- Determine decrements required in aggregate totals
3209: sub decrement_aggs {
3210: my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
3211: my %decrement = (
3212: attempts => 0,
3213: users => 0,
3214: correct => 0
3215: );
3216: $decrement{'attempts'} = $aggtries;
3217: if ($solvedstatus =~ /^correct/) {
3218: $decrement{'correct'} = 1;
3219: }
3220: if ($aggtries == $totaltries) {
3221: $decrement{'users'} = 1;
3222: }
3223: foreach my $type (keys(%decrement)) {
3224: $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
3225: }
3226: return;
3227: }
3228:
3229: # ----------- Determine timestamps for last reset of aggregate totals for parts
3230: sub get_last_resets {
3231: my ($symb,$courseid,$partids) =@_;
3232: my %last_resets;
3233: my $cdom = $env{'course.'.$courseid.'.domain'};
3234: my $cname = $env{'course.'.$courseid.'.num'};
3235: my @keys;
3236: foreach my $part (@{$partids}) {
3237: push(@keys,"$symb\0$part\0resettime");
3238: }
3239: my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
3240: $cdom,$cname);
3241: foreach my $part (@{$partids}) {
3242: $last_resets{$part}=$results{"$symb\0$part\0resettime"};
3243: }
3244: return %last_resets;
3245: }
3246:
3247: # ----------- Handles creating versions for portfolio files as answers
3248: sub version_portfiles {
3249: my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
3250: my $version_parts = join('|',@$v_flag);
3251: my @returned_keys;
3252: my $parts = join('|', @$parts_graded);
3253: my $portfolio_root = '/userfiles/portfolio';
3254: foreach my $key (keys(%$record)) {
3255: my $new_portfiles;
3256: if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
3257: my @versioned_portfiles;
3258: my @portfiles = split(/\s*,\s*/,$$record{$key});
3259: foreach my $file (@portfiles) {
3260: &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
3261: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
3262: my ($answer_name,$answer_ver,$answer_ext) =
3263: &file_name_version_ext($answer_file);
3264: my $getpropath = 1;
3265: my ($dir_list,$listerror) =
3266: &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
3267: $stu_name,$getpropath);
3268: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
3269: my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
3270: if ($new_answer ne 'problem getting file') {
3271: push(@versioned_portfiles, $directory.$new_answer);
3272: &Apache::lonnet::mark_as_readonly($domain,$stu_name,
3273: [$directory.$new_answer],
3274: [$symb,$env{'request.course.id'},'graded']);
3275: }
3276: }
3277: $$record{$key} = join(',',@versioned_portfiles);
3278: push(@returned_keys,$key);
3279: }
3280: }
3281: return (@returned_keys);
3282: }
3283:
3284: sub get_next_version {
3285: my ($answer_name, $answer_ext, $dir_list) = @_;
3286: my $version;
3287: if (ref($dir_list) eq 'ARRAY') {
3288: foreach my $row (@{$dir_list}) {
3289: my ($file) = split(/\&/,$row,2);
3290: my ($file_name,$file_version,$file_ext) =
3291: &file_name_version_ext($file);
3292: if (($file_name eq $answer_name) &&
3293: ($file_ext eq $answer_ext)) {
3294: # gets here if filename and extension match,
3295: # regardless of version
3296: if ($file_version ne '') {
3297: # a versioned file is found so save it for later
3298: if ($file_version > $version) {
3299: $version = $file_version;
3300: }
3301: }
3302: }
3303: }
3304: }
3305: $version ++;
3306: return($version);
3307: }
3308:
3309: sub version_selected_portfile {
3310: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
3311: my ($answer_name,$answer_ver,$answer_ext) =
3312: &file_name_version_ext($file_name);
3313: my $new_answer;
3314: $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
3315: if($env{'form.copy'} eq '-1') {
3316: $new_answer = 'problem getting file';
3317: } else {
3318: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
3319: my $copy_result = &Apache::lonnet::finishuserfileupload(
3320: $stu_name,$domain,'copy',
3321: '/portfolio'.$directory.$new_answer);
3322: }
3323: return ($new_answer);
3324: }
3325:
3326: sub file_name_version_ext {
3327: my ($file)=@_;
3328: my @file_parts = split(/\./, $file);
3329: my ($name,$version,$ext);
3330: if (@file_parts > 1) {
3331: $ext=pop(@file_parts);
3332: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
3333: $version=pop(@file_parts);
3334: }
3335: $name=join('.',@file_parts);
3336: } else {
3337: $name=join('.',@file_parts);
3338: }
3339: return($name,$version,$ext);
3340: }
3341:
3342: #--------------------------------------------------------------------------------------
3343: #
3344: #-------------------------- Next few routines handles grading by section or whole class
3345: #
3346: #--- Javascript to handle grading by section or whole class
3347: sub viewgrades_js {
3348: my ($request) = shift;
3349:
3350: my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
3351: $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
3352: function writePoint(partid,weight,point) {
3353: var radioButton = document.classgrade["RADVAL_"+partid];
3354: var textbox = document.classgrade["TEXTVAL_"+partid];
3355: if (point == "textval") {
3356: point = document.classgrade["TEXTVAL_"+partid].value;
3357: if (isNaN(point) || parseFloat(point) < 0) {
3358: alert("$alertmsg"+parseFloat(point));
3359: var resetbox = false;
3360: for (var i=0; i<radioButton.length; i++) {
3361: if (radioButton[i].checked) {
3362: textbox.value = i;
3363: resetbox = true;
3364: }
3365: }
3366: if (!resetbox) {
3367: textbox.value = "";
3368: }
3369: return;
3370: }
3371: if (parseFloat(point) > parseFloat(weight)) {
3372: var resp = confirm("You entered a value ("+parseFloat(point)+
3373: ") greater than the weight for the part. Accept?");
3374: if (resp == false) {
3375: textbox.value = "";
3376: return;
3377: }
3378: }
3379: for (var i=0; i<radioButton.length; i++) {
3380: radioButton[i].checked=false;
3381: if (parseFloat(point) == i) {
3382: radioButton[i].checked=true;
3383: }
3384: }
3385:
3386: } else {
3387: textbox.value = parseFloat(point);
3388: }
3389: for (i=0;i<document.classgrade.total.value;i++) {
3390: var user = document.classgrade["ctr"+i].value;
3391: user = user.replace(new RegExp(':', 'g'),"_");
3392: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3393: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3394: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3395: if (saveval != "correct") {
3396: scorename.value = point;
3397: if (selname[0].selected != true) {
3398: selname[0].selected = true;
3399: }
3400: }
3401: }
3402: document.classgrade["SELVAL_"+partid][0].selected = true;
3403: }
3404:
3405: function writeRadText(partid,weight) {
3406: var selval = document.classgrade["SELVAL_"+partid];
3407: var radioButton = document.classgrade["RADVAL_"+partid];
3408: var override = document.classgrade["FORCE_"+partid].checked;
3409: var textbox = document.classgrade["TEXTVAL_"+partid];
3410: if (selval[1].selected || selval[2].selected) {
3411: for (var i=0; i<radioButton.length; i++) {
3412: radioButton[i].checked=false;
3413:
3414: }
3415: textbox.value = "";
3416:
3417: for (i=0;i<document.classgrade.total.value;i++) {
3418: var user = document.classgrade["ctr"+i].value;
3419: user = user.replace(new RegExp(':', 'g'),"_");
3420: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3421: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3422: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3423: if ((saveval != "correct") || override) {
3424: scorename.value = "";
3425: if (selval[1].selected) {
3426: selname[1].selected = true;
3427: } else {
3428: selname[2].selected = true;
3429: if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value))
3430: {document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
3431: }
3432: }
3433: }
3434: } else {
3435: for (i=0;i<document.classgrade.total.value;i++) {
3436: var user = document.classgrade["ctr"+i].value;
3437: user = user.replace(new RegExp(':', 'g'),"_");
3438: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3439: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3440: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3441: if ((saveval != "correct") || override) {
3442: scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
3443: selname[0].selected = true;
3444: }
3445: }
3446: }
3447: }
3448:
3449: function changeSelect(partid,user) {
3450: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
3451: var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
3452: var point = textbox.value;
3453: var weight = document.classgrade["weight_"+partid].value;
3454:
3455: if (isNaN(point) || parseFloat(point) < 0) {
3456: alert("$alertmsg"+parseFloat(point));
3457: textbox.value = "";
3458: return;
3459: }
3460: if (parseFloat(point) > parseFloat(weight)) {
3461: var resp = confirm("You entered a value ("+parseFloat(point)+
3462: ") greater than the weight of the part. Accept?");
3463: if (resp == false) {
3464: textbox.value = "";
3465: return;
3466: }
3467: }
3468: selval[0].selected = true;
3469: }
3470:
3471: function changeOneScore(partid,user) {
3472: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
3473: if (selval[1].selected || selval[2].selected) {
3474: document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
3475: if (selval[2].selected) {
3476: document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
3477: }
3478: }
3479: }
3480:
3481: function resetEntry(numpart) {
3482: for (ctpart=0;ctpart<numpart;ctpart++) {
3483: var partid = document.classgrade["partid_"+ctpart].value;
3484: var radioButton = document.classgrade["RADVAL_"+partid];
3485: var textbox = document.classgrade["TEXTVAL_"+partid];
3486: var selval = document.classgrade["SELVAL_"+partid];
3487: for (var i=0; i<radioButton.length; i++) {
3488: radioButton[i].checked=false;
3489:
3490: }
3491: textbox.value = "";
3492: selval[0].selected = true;
3493:
3494: for (i=0;i<document.classgrade.total.value;i++) {
3495: var user = document.classgrade["ctr"+i].value;
3496: user = user.replace(new RegExp(':', 'g'),"_");
3497: var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3498: resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
3499: var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
3500: resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
3501: var saveselval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3502: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3503: if (saveselval == "excused") {
3504: if (selname[1].selected == false) { selname[1].selected = true;}
3505: } else {
3506: if (selname[0].selected == false) {selname[0].selected = true};
3507: }
3508: }
3509: }
3510: }
3511:
3512: VIEWJAVASCRIPT
3513: }
3514:
3515: #--- show scores for a section or whole class w/ option to change/update a score
3516: sub viewgrades {
3517: my ($request,$symb) = @_;
3518: &viewgrades_js($request);
3519:
3520: #need to make sure we have the correct data for later EXT calls,
3521: #thus invalidate the cache
3522: &Apache::lonnet::devalidatecourseresdata(
3523: $env{'course.'.$env{'request.course.id'}.'.num'},
3524: $env{'course.'.$env{'request.course.id'}.'.domain'});
3525: &Apache::lonnet::clear_EXT_cache_status();
3526:
3527: my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
3528:
3529: #view individual student submission form - called using Javascript viewOneStudent
3530: $result.=&jscriptNform($symb);
3531:
3532: #beginning of class grading form
3533: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
3534: $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
3535: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
3536: '<input type="hidden" name="command" value="editgrades" />'."\n".
3537: &build_section_inputs().
3538: '<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
3539:
3540: my ($common_header,$specific_header);
3541: if ($env{'form.section'} eq 'all') {
3542: $common_header = &mt('Assign Common Grade to Class');
3543: $specific_header = &mt('Assign Grade to Specific Students in Class');
3544: } elsif ($env{'form.section'} eq 'none') {
3545: $common_header = &mt('Assign Common Grade to Students in no Section');
3546: $specific_header = &mt('Assign Grade to Specific Students in no Section');
3547: } else {
3548: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3549: $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
3550: $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
3551: }
3552: $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
3553: #radio buttons/text box for assigning points for a section or class.
3554: #handles different parts of a problem
3555: my $res_error;
3556: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
3557: if ($res_error) {
3558: return &navmap_errormsg();
3559: }
3560: my %weight = ();
3561: my $ctsparts = 0;
3562: my %seen = ();
3563: my @part_response_id = &flatten_responseType($responseType);
3564: foreach my $part_response_id (@part_response_id) {
3565: my ($partid,$respid) = @{ $part_response_id };
3566: my $part_resp = join('_',@{ $part_response_id });
3567: next if $seen{$partid};
3568: $seen{$partid}++;
3569: my $handgrade=$$handgrade{$part_resp};
3570: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
3571: $weight{$partid} = $wgt eq '' ? '1' : $wgt;
3572:
3573: my $display_part=&get_display_part($partid,$symb);
3574: my $radio.='<table border="0"><tr>';
3575: my $ctr = 0;
3576: while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
3577: $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
3578: 'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
3579: ','.$ctr.')" />'.$ctr."</label></td>\n";
3580: $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
3581: $ctr++;
3582: }
3583: $radio.='</tr></table>';
3584: my $line = '<input type="text" name="TEXTVAL_'.
3585: $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
3586: $partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
3587: $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
3588: $line.= '<td><b>'.&mt('Grade Status').':</b><select name="SELVAL_'.$partid.'"'.
3589: 'onchange="javascript:writeRadText(\''.$partid.'\','.
3590: $weight{$partid}.')"> '.
3591: '<option selected="selected"> </option>'.
3592: '<option value="excused">'.&mt('excused').'</option>'.
3593: '<option value="reset status">'.&mt('reset status').'</option>'.
3594: '</select></td>'.
3595: '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
3596: $line.='<input type="hidden" name="partid_'.
3597: $ctsparts.'" value="'.$partid.'" />'."\n";
3598: $line.='<input type="hidden" name="weight_'.
3599: $partid.'" value="'.$weight{$partid}.'" />'."\n";
3600:
3601: $result.=
3602: &Apache::loncommon::start_data_table_row()."\n".
3603: '<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>'.
3604: &Apache::loncommon::end_data_table_row()."\n";
3605: $ctsparts++;
3606: }
3607: $result.=&Apache::loncommon::end_data_table()."\n".
3608: '<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
3609: $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
3610: 'onclick="javascript:resetEntry('.$ctsparts.');" />';
3611:
3612: #table listing all the students in a section/class
3613: #header of table
3614: $result.= '<h3>'.$specific_header.'</h3>'.
3615: &Apache::loncommon::start_data_table().
3616: &Apache::loncommon::start_data_table_header_row().
3617: '<th>'.&mt('No.').'</th>'.
3618: '<th>'.&nameUserString('header')."</th>\n";
3619: my $partserror;
3620: my (@parts) = sort(&getpartlist($symb,\$partserror));
3621: if ($partserror) {
3622: return &navmap_errormsg();
3623: }
3624: my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
3625: my @partids = ();
3626: foreach my $part (@parts) {
3627: my $display=&Apache::lonnet::metadata($url,$part.'.display');
3628: my $narrowtext = &mt('Tries');
3629: $display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
3630: if (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
3631: my ($partid) = &split_part_type($part);
3632: push(@partids,$partid);
3633: #
3634: # FIXME: Looks like $display looks at English text
3635: #
3636: my $display_part=&get_display_part($partid,$symb);
3637: if ($display =~ /^Partial Credit Factor/) {
3638: $result.='<th>'.
3639: &mt('Score Part: [_1]<br /> (weight = [_2])',
3640: $display_part,$weight{$partid}).'</th>'."\n";
3641: next;
3642:
3643: } else {
3644: if ($display =~ /Problem Status/) {
3645: my $grade_status_mt = &mt('Grade Status');
3646: $display =~ s{Problem Status}{$grade_status_mt<br />};
3647: }
3648: my $part_mt = &mt('Part:');
3649: $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
3650: }
3651:
3652: $result.='<th>'.$display.'</th>'."\n";
3653: }
3654: $result.=&Apache::loncommon::end_data_table_header_row();
3655:
3656: my %last_resets =
3657: &get_last_resets($symb,$env{'request.course.id'},\@partids);
3658:
3659: #get info for each student
3660: #list all the students - with points and grade status
3661: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
3662: my $ctr = 0;
3663: foreach (sort
3664: {
3665: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
3666: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
3667: }
3668: return $a cmp $b;
3669: } (keys(%$fullname))) {
3670: $ctr++;
3671: $result.=&viewstudentgrade($symb,$env{'request.course.id'},
3672: $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
3673: }
3674: $result.=&Apache::loncommon::end_data_table();
3675: $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
3676: $result.='<input type="button" value="'.&mt('Save').'" '.
3677: 'onclick="javascript:submit();" target="_self" /></form>'."\n";
3678: if (scalar(%$fullname) eq 0) {
3679: my $colspan=3+scalar(@parts);
3680: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3681: my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
3682: $result='<span class="LC_warning">'.
3683: &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
3684: $section_display, $stu_status).
3685: '</span>';
3686: }
3687: return $result;
3688: }
3689:
3690: #--- call by previous routine to display each student
3691: sub viewstudentgrade {
3692: my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
3693: my ($uname,$udom) = split(/:/,$student);
3694: my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
3695: my %aggregates = ();
3696: my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
3697: '<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
3698: "\n".$ctr.' </td><td> '.
3699: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
3700: '\');" target="_self">'.$fullname.'</a> '.
3701: '<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
3702: $student=~s/:/_/; # colon doen't work in javascript for names
3703: foreach my $apart (@$parts) {
3704: my ($part,$type) = &split_part_type($apart);
3705: my $score=$record{"resource.$part.$type"};
3706: $result.='<td align="center">';
3707: my ($aggtries,$totaltries);
3708: unless (exists($aggregates{$part})) {
3709: $totaltries = $record{'resource.'.$part.'.tries'};
3710:
3711: $aggtries = $totaltries;
3712: if ($$last_resets{$part}) {
3713: $aggtries = &get_num_tries(\%record,$$last_resets{$part},
3714: $part);
3715: }
3716: $result.='<input type="hidden" name="'.
3717: 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
3718: $result.='<input type="hidden" name="'.
3719: 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
3720: $aggregates{$part} = 1;
3721: }
3722: if ($type eq 'awarded') {
3723: my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
3724: $result.='<input type="hidden" name="'.
3725: 'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
3726: $result.='<input type="text" name="'.
3727: 'GD_'.$student.'_'.$part.'_awarded" '.
3728: 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
3729: '\')" value="'.$pts.'" size="4" /></td>'."\n";
3730: } elsif ($type eq 'solved') {
3731: my ($status,$foo)=split(/_/,$score,2);
3732: $status = 'nothing' if ($status eq '');
3733: $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
3734: $part.'_solved_s" value="'.$status.'" />'."\n";
3735: $result.=' <select name="'.
3736: 'GD_'.$student.'_'.$part.'_solved" '.
3737: 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
3738: $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>'
3739: : '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
3740: $result.='<option value="reset status">'.&mt('reset status').'</option>';
3741: $result.="</select> </td>\n";
3742: } else {
3743: $result.='<input type="hidden" name="'.
3744: 'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
3745: "\n";
3746: $result.='<input type="text" name="'.
3747: 'GD_'.$student.'_'.$part.'_'.$type.'" '.
3748: 'value="'.$score.'" size="4" /></td>'."\n";
3749: }
3750: }
3751: $result.=&Apache::loncommon::end_data_table_row();
3752: return $result;
3753: }
3754:
3755: #--- change scores for all the students in a section/class
3756: # record does not get update if unchanged
3757: sub editgrades {
3758: my ($request,$symb) = @_;
3759:
3760: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3761: my $title='<h2>'.&mt('Current Grade Status').'</h2>';
3762: $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
3763:
3764: my $result= &Apache::loncommon::start_data_table().
3765: &Apache::loncommon::start_data_table_header_row().
3766: '<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
3767: '<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
3768: my %scoreptr = (
3769: 'correct' =>'correct_by_override',
3770: 'incorrect'=>'incorrect_by_override',
3771: 'excused' =>'excused',
3772: 'ungraded' =>'ungraded_attempted',
3773: 'credited' =>'credit_attempted',
3774: 'nothing' => '',
3775: );
3776: my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
3777:
3778: my (@partid);
3779: my %weight = ();
3780: my %columns = ();
3781: my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
3782:
3783: my $partserror;
3784: my (@parts) = sort(&getpartlist($symb,\$partserror));
3785: if ($partserror) {
3786: return &navmap_errormsg();
3787: }
3788: my $header;
3789: while ($ctr < $env{'form.totalparts'}) {
3790: my $partid = $env{'form.partid_'.$ctr};
3791: push(@partid,$partid);
3792: $weight{$partid} = $env{'form.weight_'.$partid};
3793: $ctr++;
3794: }
3795: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3796: foreach my $partid (@partid) {
3797: $header .= '<th align="center">'.&mt('Old Score').'</th>'.
3798: '<th align="center">'.&mt('New Score').'</th>';
3799: $columns{$partid}=2;
3800: foreach my $stores (@parts) {
3801: my ($part,$type) = &split_part_type($stores);
3802: if ($part !~ m/^\Q$partid\E/) { next;}
3803: if ($type eq 'awarded' || $type eq 'solved') { next; }
3804: my $display=&Apache::lonnet::metadata($url,$stores.'.display');
3805: $display =~ s/\[Part: \Q$part\E\]//;
3806: my $narrowtext = &mt('Tries');
3807: $display =~ s/Number of Attempts/$narrowtext/;
3808: $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
3809: '<th align="center">'.&mt('New').' '.$display.'</th>';
3810: $columns{$partid}+=2;
3811: }
3812: }
3813: foreach my $partid (@partid) {
3814: my $display_part=&get_display_part($partid,$symb);
3815: $result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
3816: &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
3817: '</th>';
3818:
3819: }
3820: $result .= &Apache::loncommon::end_data_table_header_row().
3821: &Apache::loncommon::start_data_table_header_row().
3822: $header.
3823: &Apache::loncommon::end_data_table_header_row();
3824: my @noupdate;
3825: my ($updateCtr,$noupdateCtr) = (1,1);
3826: for ($i=0; $i<$env{'form.total'}; $i++) {
3827: my $line;
3828: my $user = $env{'form.ctr'.$i};
3829: my ($uname,$udom)=split(/:/,$user);
3830: my %newrecord;
3831: my $updateflag = 0;
3832: $line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
3833: my $usec=$classlist->{"$uname:$udom"}[5];
3834: if (!&canmodify($usec)) {
3835: my $numcols=scalar(@partid)*4+2;
3836: push(@noupdate,
3837: $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
3838: &mt('Not allowed to modify student')."</span></td></tr>");
3839: next;
3840: }
3841: my %aggregate = ();
3842: my $aggregateflag = 0;
3843: $user=~s/:/_/; # colon doen't work in javascript for names
3844: foreach (@partid) {
3845: my $old_aw = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
3846: my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
3847: my $old_part = $old_aw eq '' ? '' : $old_part_pcr;
3848: my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
3849: my $awarded = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
3850: my $pcr = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
3851: my $partial = $awarded eq '' ? '' : $pcr;
3852: my $score;
3853: if ($partial eq '') {
3854: $score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
3855: } elsif ($partial > 0) {
3856: $score = 'correct_by_override';
3857: } elsif ($partial == 0) {
3858: $score = 'incorrect_by_override';
3859: }
3860: my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
3861: $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
3862:
3863: $newrecord{'resource.'.$_.'.regrader'}=
3864: "$env{'user.name'}:$env{'user.domain'}";
3865: if ($dropMenu eq 'reset status' &&
3866: $old_score ne '') { # ignore if no previous attempts => nothing to reset
3867: $newrecord{'resource.'.$_.'.tries'} = '';
3868: $newrecord{'resource.'.$_.'.solved'} = '';
3869: $newrecord{'resource.'.$_.'.award'} = '';
3870: $newrecord{'resource.'.$_.'.awarded'} = '';
3871: $updateflag = 1;
3872: if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
3873: my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
3874: my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
3875: my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
3876: &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
3877: $aggregateflag = 1;
3878: }
3879: } elsif (!($old_part eq $partial && $old_score eq $score)) {
3880: $updateflag = 1;
3881: $newrecord{'resource.'.$_.'.awarded'} = $partial if $partial ne '';
3882: $newrecord{'resource.'.$_.'.solved'} = $score;
3883: $rec_update++;
3884: }
3885:
3886: $line .= '<td align="center">'.$old_aw.' </td>'.
3887: '<td align="center">'.$awarded.
3888: ($score eq 'excused' ? $score : '').' </td>';
3889:
3890:
3891: my $partid=$_;
3892: foreach my $stores (@parts) {
3893: my ($part,$type) = &split_part_type($stores);
3894: if ($part !~ m/^\Q$partid\E/) { next;}
3895: if ($type eq 'awarded' || $type eq 'solved') { next; }
3896: my $old_aw = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
3897: my $awarded = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
3898: if ($awarded ne '' && $awarded ne $old_aw) {
3899: $newrecord{'resource.'.$part.'.'.$type}= $awarded;
3900: $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
3901: $updateflag=1;
3902: }
3903: $line .= '<td align="center">'.$old_aw.' </td>'.
3904: '<td align="center">'.$awarded.' </td>';
3905: }
3906: }
3907: $line.="\n";
3908:
3909: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3910: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3911:
3912: if ($updateflag) {
3913: $count++;
3914: &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
3915: $udom,$uname);
3916:
3917: if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
3918: $cnum,$udom,$uname)) {
3919: # need to figure out if should be in queue.
3920: my %record =
3921: &Apache::lonnet::restore($symb,$env{'request.course.id'},
3922: $udom,$uname);
3923: my $all_graded = 1;
3924: my $none_graded = 1;
3925: foreach my $part (@parts) {
3926: if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
3927: $all_graded = 0;
3928: } else {
3929: $none_graded = 0;
3930: }
3931: }
3932:
3933: if ($all_graded || $none_graded) {
3934: &Apache::bridgetask::remove_from_queue('gradingqueue',
3935: $symb,$cdom,$cnum,
3936: $udom,$uname);
3937: }
3938: }
3939:
3940: $result.=&Apache::loncommon::start_data_table_row().
3941: '<td align="right"> '.$updateCtr.' </td>'.$line.
3942: &Apache::loncommon::end_data_table_row();
3943: $updateCtr++;
3944: } else {
3945: push(@noupdate,
3946: '<td align="right"> '.$noupdateCtr.' </td>'.$line);
3947: $noupdateCtr++;
3948: }
3949: if ($aggregateflag) {
3950: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
3951: $cdom,$cnum);
3952: }
3953: }
3954: if (@noupdate) {
3955: # my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
3956: my $numcols=scalar(@partid)*4+2;
3957: $result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
3958: '<td align="center" colspan="'.$numcols.'">'.
3959: &mt('No Changes Occurred For the Students Below').
3960: '</td>'.
3961: &Apache::loncommon::end_data_table_row();
3962: foreach my $line (@noupdate) {
3963: $result.=
3964: &Apache::loncommon::start_data_table_row().
3965: $line.
3966: &Apache::loncommon::end_data_table_row();
3967: }
3968: }
3969: $result .= &Apache::loncommon::end_data_table();
3970: my $msg = '<p><b>'.
3971: &mt('Number of records updated = [_1] for [quant,_2,student].',
3972: $rec_update,$count).'</b><br />'.
3973: '<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
3974: '</b></p>';
3975: return $title.$msg.$result;
3976: }
3977:
3978: sub split_part_type {
3979: my ($partstr) = @_;
3980: my ($temp,@allparts)=split(/_/,$partstr);
3981: my $type=pop(@allparts);
3982: my $part=join('_',@allparts);
3983: return ($part,$type);
3984: }
3985:
3986: #------------- end of section for handling grading by section/class ---------
3987: #
3988: #----------------------------------------------------------------------------
3989:
3990:
3991: #----------------------------------------------------------------------------
3992: #
3993: #-------------------------- Next few routines handles grading by csv upload
3994: #
3995: #--- Javascript to handle csv upload
3996: sub csvupload_javascript_reverse_associate {
3997: my $error1=&mt('You need to specify the username or the student/employee ID');
3998: my $error2=&mt('You need to specify at least one grading field');
3999: return(<<ENDPICK);
4000: function verify(vf) {
4001: var foundsomething=0;
4002: var founduname=0;
4003: var foundID=0;
4004: for (i=0;i<=vf.nfields.value;i++) {
4005: tw=eval('vf.f'+i+'.selectedIndex');
4006: if (i==0 && tw!=0) { foundID=1; }
4007: if (i==1 && tw!=0) { founduname=1; }
4008: if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
4009: }
4010: if (founduname==0 && foundID==0) {
4011: alert('$error1');
4012: return;
4013: }
4014: if (foundsomething==0) {
4015: alert('$error2');
4016: return;
4017: }
4018: vf.submit();
4019: }
4020: function flip(vf,tf) {
4021: var nw=eval('vf.f'+tf+'.selectedIndex');
4022: var i;
4023: for (i=0;i<=vf.nfields.value;i++) {
4024: //can not pick the same destination field for both name and domain
4025: if (((i ==0)||(i ==1)) &&
4026: ((tf==0)||(tf==1)) &&
4027: (i!=tf) &&
4028: (eval('vf.f'+i+'.selectedIndex')==nw)) {
4029: eval('vf.f'+i+'.selectedIndex=0;')
4030: }
4031: }
4032: }
4033: ENDPICK
4034: }
4035:
4036: sub csvupload_javascript_forward_associate {
4037: my $error1=&mt('You need to specify the username or the student/employee ID');
4038: my $error2=&mt('You need to specify at least one grading field');
4039: return(<<ENDPICK);
4040: function verify(vf) {
4041: var foundsomething=0;
4042: var founduname=0;
4043: var foundID=0;
4044: for (i=0;i<=vf.nfields.value;i++) {
4045: tw=eval('vf.f'+i+'.selectedIndex');
4046: if (tw==1) { foundID=1; }
4047: if (tw==2) { founduname=1; }
4048: if (tw>3) { foundsomething=1; }
4049: }
4050: if (founduname==0 && foundID==0) {
4051: alert('$error1');
4052: return;
4053: }
4054: if (foundsomething==0) {
4055: alert('$error2');
4056: return;
4057: }
4058: vf.submit();
4059: }
4060: function flip(vf,tf) {
4061: var nw=eval('vf.f'+tf+'.selectedIndex');
4062: var i;
4063: //can not pick the same destination field twice
4064: for (i=0;i<=vf.nfields.value;i++) {
4065: if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
4066: eval('vf.f'+i+'.selectedIndex=0;')
4067: }
4068: }
4069: }
4070: ENDPICK
4071: }
4072:
4073: sub csvuploadmap_header {
4074: my ($request,$symb,$datatoken,$distotal)= @_;
4075: my $javascript;
4076: if ($env{'form.upfile_associate'} eq 'reverse') {
4077: $javascript=&csvupload_javascript_reverse_associate();
4078: } else {
4079: $javascript=&csvupload_javascript_forward_associate();
4080: }
4081:
4082: $symb = &Apache::lonenc::check_encrypt($symb);
4083: $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
4084: &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
4085: &mt('Associate entries from the uploaded file with as many fields as you can.'));
4086: my $reverse=&mt("Reverse Association");
4087: $request->print(<<ENDPICK);
4088: <br />
4089: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
4090: <input type="hidden" name="associate" value="" />
4091: <input type="hidden" name="phase" value="three" />
4092: <input type="hidden" name="datatoken" value="$datatoken" />
4093: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
4094: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
4095: <input type="hidden" name="upfile_associate"
4096: value="$env{'form.upfile_associate'}" />
4097: <input type="hidden" name="symb" value="$symb" />
4098: <input type="hidden" name="command" value="csvuploadoptions" />
4099: <hr />
4100: ENDPICK
4101: $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
4102: return '';
4103:
4104: }
4105:
4106: sub csvupload_fields {
4107: my ($symb,$errorref) = @_;
4108: my (@parts) = &getpartlist($symb,$errorref);
4109: if (ref($errorref)) {
4110: if ($$errorref) {
4111: return;
4112: }
4113: }
4114:
4115: my @fields=(['ID','Student/Employee ID'],
4116: ['username','Student Username'],
4117: ['domain','Student Domain']);
4118: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
4119: foreach my $part (sort(@parts)) {
4120: my @datum;
4121: my $display=&Apache::lonnet::metadata($url,$part.'.display');
4122: my $name=$part;
4123: if (!$display) { $display = $name; }
4124: @datum=($name,$display);
4125: if ($name=~/^stores_(.*)_awarded/) {
4126: push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
4127: }
4128: push(@fields,\@datum);
4129: }
4130: return (@fields);
4131: }
4132:
4133: sub csvuploadmap_footer {
4134: my ($request,$i,$keyfields) =@_;
4135: $request->print(<<ENDPICK);
4136: </table>
4137: <input type="hidden" name="nfields" value="$i" />
4138: <input type="hidden" name="keyfields" value="$keyfields" />
4139: <input type="button" onclick="javascript:verify(this.form)" value="Assign Grades" /><br />
4140: </form>
4141: ENDPICK
4142: }
4143:
4144: sub checkforfile_js {
4145: my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
4146: my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
4147: function checkUpload(formname) {
4148: if (formname.upfile.value == "") {
4149: alert("$alertmsg");
4150: return false;
4151: }
4152: formname.submit();
4153: }
4154: CSVFORMJS
4155: return $result;
4156: }
4157:
4158: sub upcsvScores_form {
4159: my ($request,$symb) = @_;
4160: if (!$symb) {return '';}
4161: my $result=&checkforfile_js();
4162: $result.=&Apache::loncommon::start_data_table().
4163: &Apache::loncommon::start_data_table_header_row().
4164: '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
4165: &Apache::loncommon::end_data_table_header_row().
4166: &Apache::loncommon::start_data_table_row().'<td>';
4167: my $upload=&mt("Upload Scores");
4168: my $upfile_select=&Apache::loncommon::upfile_select_html();
4169: my $ignore=&mt('Ignore First Line');
4170: $symb = &Apache::lonenc::check_encrypt($symb);
4171: $result.=<<ENDUPFORM;
4172: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
4173: <input type="hidden" name="symb" value="$symb" />
4174: <input type="hidden" name="command" value="csvuploadmap" />
4175: $upfile_select
4176: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
4177: </form>
4178: ENDUPFORM
4179: $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
4180: &mt("How do I create a CSV file from a spreadsheet")).
4181: '</td>'.
4182: &Apache::loncommon::end_data_table_row().
4183: &Apache::loncommon::end_data_table();
4184: return $result;
4185: }
4186:
4187:
4188: sub csvuploadmap {
4189: my ($request,$symb)= @_;
4190: if (!$symb) {return '';}
4191:
4192: my $datatoken;
4193: if (!$env{'form.datatoken'}) {
4194: $datatoken=&Apache::loncommon::upfile_store($request);
4195: } else {
4196: $datatoken=$env{'form.datatoken'};
4197: &Apache::loncommon::load_tmp_file($request);
4198: }
4199: my @records=&Apache::loncommon::upfile_record_sep();
4200: &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
4201: my ($i,$keyfields);
4202: if (@records) {
4203: my $fieldserror;
4204: my @fields=&csvupload_fields($symb,\$fieldserror);
4205: if ($fieldserror) {
4206: $request->print(&navmap_errormsg());
4207: return;
4208: }
4209: if ($env{'form.upfile_associate'} eq 'reverse') {
4210: &Apache::loncommon::csv_print_samples($request,\@records);
4211: $i=&Apache::loncommon::csv_print_select_table($request,\@records,
4212: \@fields);
4213: foreach (@fields) { $keyfields.=$_->[0].','; }
4214: chop($keyfields);
4215: } else {
4216: unshift(@fields,['none','']);
4217: $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
4218: \@fields);
4219: foreach my $rec (@records) {
4220: my %temp = &Apache::loncommon::record_sep($rec);
4221: if (%temp) {
4222: $keyfields=join(',',sort(keys(%temp)));
4223: last;
4224: }
4225: }
4226: }
4227: }
4228: &csvuploadmap_footer($request,$i,$keyfields);
4229:
4230: return '';
4231: }
4232:
4233: sub csvuploadoptions {
4234: my ($request,$symb)= @_;
4235: my $overwrite=&mt('Overwrite any existing score');
4236: $request->print(<<ENDPICK);
4237: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
4238: <input type="hidden" name="command" value="csvuploadassign" />
4239: <p>
4240: <label>
4241: <input type="checkbox" name="overwite_scores" checked="checked" />
4242: $overwrite
4243: </label>
4244: </p>
4245: ENDPICK
4246: my %fields=&get_fields();
4247: if (!defined($fields{'domain'})) {
4248: my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
4249: $request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
4250: }
4251: foreach my $key (sort(keys(%env))) {
4252: if ($key !~ /^form\.(.*)$/) { next; }
4253: my $cleankey=$1;
4254: if ($cleankey eq 'command') { next; }
4255: $request->print('<input type="hidden" name="'.$cleankey.
4256: '" value="'.$env{$key}.'" />'."\n");
4257: }
4258: # FIXME do a check for any duplicated user ids...
4259: # FIXME do a check for any invalid user ids?...
4260: $request->print('<input type="submit" value="Assign Grades" /><br />
4261: <hr /></form>'."\n");
4262: return '';
4263: }
4264:
4265: sub get_fields {
4266: my %fields;
4267: my @keyfields = split(/\,/,$env{'form.keyfields'});
4268: for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
4269: if ($env{'form.upfile_associate'} eq 'reverse') {
4270: if ($env{'form.f'.$i} ne 'none') {
4271: $fields{$keyfields[$i]}=$env{'form.f'.$i};
4272: }
4273: } else {
4274: if ($env{'form.f'.$i} ne 'none') {
4275: $fields{$env{'form.f'.$i}}=$keyfields[$i];
4276: }
4277: }
4278: }
4279: return %fields;
4280: }
4281:
4282: sub csvuploadassign {
4283: my ($request,$symb)= @_;
4284: if (!$symb) {return '';}
4285: my $error_msg = '';
4286: &Apache::loncommon::load_tmp_file($request);
4287: my @gradedata = &Apache::loncommon::upfile_record_sep();
4288: my %fields=&get_fields();
4289: my $courseid=$env{'request.course.id'};
4290: my ($classlist) = &getclasslist('all',0);
4291: my @notallowed;
4292: my @skipped;
4293: my @warnings;
4294: my $countdone=0;
4295: foreach my $grade (@gradedata) {
4296: my %entries=&Apache::loncommon::record_sep($grade);
4297: my $domain;
4298: if ($entries{$fields{'domain'}}) {
4299: $domain=$entries{$fields{'domain'}};
4300: } else {
4301: $domain=$env{'form.default_domain'};
4302: }
4303: $domain=~s/\s//g;
4304: my $username=$entries{$fields{'username'}};
4305: $username=~s/\s//g;
4306: if (!$username) {
4307: my $id=$entries{$fields{'ID'}};
4308: $id=~s/\s//g;
4309: my %ids=&Apache::lonnet::idget($domain,$id);
4310: $username=$ids{$id};
4311: }
4312: if (!exists($$classlist{"$username:$domain"})) {
4313: my $id=$entries{$fields{'ID'}};
4314: $id=~s/\s//g;
4315: if ($id) {
4316: push(@skipped,"$id:$domain");
4317: } else {
4318: push(@skipped,"$username:$domain");
4319: }
4320: next;
4321: }
4322: my $usec=$classlist->{"$username:$domain"}[5];
4323: if (!&canmodify($usec)) {
4324: push(@notallowed,"$username:$domain");
4325: next;
4326: }
4327: my %points;
4328: my %grades;
4329: foreach my $dest (keys(%fields)) {
4330: if ($dest eq 'ID' || $dest eq 'username' ||
4331: $dest eq 'domain') { next; }
4332: if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
4333: if ($dest=~/stores_(.*)_points/) {
4334: my $part=$1;
4335: my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
4336: $symb,$domain,$username);
4337: if ($wgt) {
4338: $entries{$fields{$dest}}=~s/\s//g;
4339: my $pcr=$entries{$fields{$dest}} / $wgt;
4340: my $award=($pcr == 0) ? 'incorrect_by_override'
4341: : 'correct_by_override';
4342: if ($pcr>1) {
4343: push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
4344: }
4345: $grades{"resource.$part.awarded"}=$pcr;
4346: $grades{"resource.$part.solved"}=$award;
4347: $points{$part}=1;
4348: } else {
4349: $error_msg = "<br />" .
4350: &mt("Some point values were assigned"
4351: ." for problems with a weight "
4352: ."of zero. These values were "
4353: ."ignored.");
4354: }
4355: } else {
4356: if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
4357: if ($dest=~/stores_(.*)_solved/) { if ($points{$1}) {next;} }
4358: my $store_key=$dest;
4359: $store_key=~s/^stores/resource/;
4360: $store_key=~s/_/\./g;
4361: $grades{$store_key}=$entries{$fields{$dest}};
4362: }
4363: }
4364: if (! %grades) {
4365: push(@skipped,&mt("[_1]: no data to save","$username:$domain"));
4366: } else {
4367: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
4368: my $result=&Apache::lonnet::cstore(\%grades,$symb,
4369: $env{'request.course.id'},
4370: $domain,$username);
4371: if ($result eq 'ok') {
4372: # Successfully stored
4373: $request->print('.');
4374: # Remove from grading queue
4375: &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
4376: $env{'course.'.$env{'request.course.id'}.'.domain'},
4377: $env{'course.'.$env{'request.course.id'}.'.num'},
4378: $domain,$username);
4379: $countdone++;
4380: } else {
4381: $request->print("<p><span class=\"LC_error\">".
4382: &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
4383: "$username:$domain",$result)."</span></p>");
4384: }
4385: $request->rflush();
4386: }
4387: }
4388: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
4389: if (@warnings) {
4390: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
4391: $request->print(join(', ',@warnings));
4392: }
4393: if (@skipped) {
4394: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
4395: $request->print(join(', ',@skipped));
4396: }
4397: if (@notallowed) {
4398: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
4399: $request->print(join(', ',@notallowed));
4400: }
4401: $request->print("<br />\n");
4402: return $error_msg;
4403: }
4404: #------------- end of section for handling csv file upload ---------
4405: #
4406: #-------------------------------------------------------------------
4407: #
4408: #-------------- Next few routines handle grading by page/sequence
4409: #
4410: #--- Select a page/sequence and a student to grade
4411: sub pickStudentPage {
4412: my ($request,$symb) = @_;
4413:
4414: my $alertmsg = &mt('Please select the student you wish to grade.');
4415: $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
4416:
4417: function checkPickOne(formname) {
4418: if (radioSelection(formname.student) == null) {
4419: alert("$alertmsg");
4420: return;
4421: }
4422: ptr = pullDownSelection(formname.selectpage);
4423: formname.page.value = formname["page"+ptr].value;
4424: formname.title.value = formname["title"+ptr].value;
4425: formname.submit();
4426: }
4427:
4428: LISTJAVASCRIPT
4429: &commonJSfunctions($request);
4430:
4431: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4432: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4433: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4434:
4435: my $result='<h3><span class="LC_info"> '.
4436: &mt('Manual Grading by Page or Sequence').'</span></h3>';
4437:
4438: $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
4439: my $map_error;
4440: my ($titles,$symbx) = &getSymbMap($map_error);
4441: if ($map_error) {
4442: $request->print(&navmap_errormsg());
4443: return;
4444: }
4445: my ($curpage) =&Apache::lonnet::decode_symb($symb);
4446: # my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb);
4447: # my $type=($curpage =~ /\.(page|sequence)/);
4448: my $select = '<select name="selectpage">'."\n";
4449: my $ctr=0;
4450: foreach (@$titles) {
4451: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4452: $select.='<option value="'.$ctr.'" '.
4453: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
4454: '>'.$showtitle.'</option>'."\n";
4455: $ctr++;
4456: }
4457: $select.= '</select>';
4458: $result.=' <b>'.&mt('Problems from').':</b> '.$select."<br />\n";
4459:
4460: $ctr=0;
4461: foreach (@$titles) {
4462: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4463: $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
4464: $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
4465: $ctr++;
4466: }
4467: $result.='<input type="hidden" name="page" />'."\n".
4468: '<input type="hidden" name="title" />'."\n";
4469:
4470: my $options =
4471: '<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
4472: '<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
4473: $result.=' <b>'.&mt('View Problem Text').': </b>'.$options;
4474:
4475: $options =
4476: '<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
4477: '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
4478: '<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
4479: $result.=' <b>'.&mt('Submissions').': </b>'.$options;
4480:
4481: $result.=&build_section_inputs();
4482: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
4483: $result.='<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
4484: '<input type="hidden" name="command" value="displayPage" />'."\n".
4485: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."<br />\n";
4486:
4487: $result.=' <b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
4488:
4489: $result.=' <input type="button" '.
4490: 'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' →" /><br />'."\n";
4491:
4492: $request->print($result);
4493:
4494: my $studentTable.=' <b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
4495: &Apache::loncommon::start_data_table().
4496: &Apache::loncommon::start_data_table_header_row().
4497: '<th align="right"> '.&mt('No.').'</th>'.
4498: '<th>'.&nameUserString('header').'</th>'.
4499: '<th align="right"> '.&mt('No.').'</th>'.
4500: '<th>'.&nameUserString('header').'</th>'.
4501: &Apache::loncommon::end_data_table_header_row();
4502:
4503: my (undef,undef,$fullname) = &getclasslist($getsec,'1');
4504: my $ptr = 1;
4505: foreach my $student (sort
4506: {
4507: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
4508: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
4509: }
4510: return $a cmp $b;
4511: } (keys(%$fullname))) {
4512: my ($uname,$udom) = split(/:/,$student);
4513: $studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
4514: : '</td>');
4515: $studentTable.='<td align="right">'.$ptr.' </td>';
4516: $studentTable.='<td> <label><input type="radio" name="student" value="'.$student.'" /> '
4517: .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
4518: $studentTable.=
4519: ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row()
4520: : '');
4521: $ptr++;
4522: }
4523: if ($ptr%2 == 0) {
4524: $studentTable.='</td><td> </td><td> </td>'.
4525: &Apache::loncommon::end_data_table_row();
4526: }
4527: $studentTable.=&Apache::loncommon::end_data_table()."\n";
4528: $studentTable.='<input type="button" '.
4529: 'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' →" /></form>'."\n";
4530:
4531: $request->print($studentTable);
4532:
4533: return '';
4534: }
4535:
4536: sub getSymbMap {
4537: my ($map_error) = @_;
4538: my $navmap = Apache::lonnavmaps::navmap->new();
4539: unless (ref($navmap)) {
4540: if (ref($map_error)) {
4541: $$map_error = 'navmap';
4542: }
4543: return;
4544: }
4545: my %symbx = ();
4546: my @titles = ();
4547: my $minder = 0;
4548:
4549: # Gather every sequence that has problems.
4550: my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
4551: 1,0,1);
4552: for my $sequence ($navmap->getById('0.0'), @sequences) {
4553: if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
4554: my $title = $minder.'.'.
4555: &HTML::Entities::encode($sequence->compTitle(),'"\'&');
4556: push(@titles, $title); # minder in case two titles are identical
4557: $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
4558: $minder++;
4559: }
4560: }
4561: return \@titles,\%symbx;
4562: }
4563:
4564: #
4565: #--- Displays a page/sequence w/wo problems, w/wo submissions
4566: sub displayPage {
4567: my ($request,$symb) = @_;
4568: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4569: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4570: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4571: my $pageTitle = $env{'form.page'};
4572: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
4573: my ($uname,$udom) = split(/:/,$env{'form.student'});
4574: my $usec=$classlist->{$env{'form.student'}}[5];
4575:
4576: #need to make sure we have the correct data for later EXT calls,
4577: #thus invalidate the cache
4578: &Apache::lonnet::devalidatecourseresdata(
4579: $env{'course.'.$env{'request.course.id'}.'.num'},
4580: $env{'course.'.$env{'request.course.id'}.'.domain'});
4581: &Apache::lonnet::clear_EXT_cache_status();
4582:
4583: if (!&canview($usec)) {
4584: $request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
4585: return;
4586: }
4587: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
4588: $result.='<h3> '.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
4589: '</h3>'."\n";
4590: $env{'form.CODE'} = uc($env{'form.CODE'});
4591: if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
4592: $result.='<h3> '.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
4593: } else {
4594: delete($env{'form.CODE'});
4595: }
4596: &sub_page_js($request);
4597: $request->print($result);
4598:
4599: my $navmap = Apache::lonnavmaps::navmap->new();
4600: unless (ref($navmap)) {
4601: $request->print(&navmap_errormsg());
4602: return;
4603: }
4604: my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
4605: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
4606: if (!$map) {
4607: $request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
4608: return;
4609: }
4610: my $iterator = $navmap->getIterator($map->map_start(),
4611: $map->map_finish());
4612:
4613: my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
4614: '<input type="hidden" name="command" value="gradeByPage" />'."\n".
4615: '<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
4616: '<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
4617: '<input type="hidden" name="page" value="'.$pageTitle.'" />'."\n".
4618: '<input type="hidden" name="title" value="'.$env{'form.title'}.'" />'."\n".
4619: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
4620: '<input type="hidden" name="overRideScore" value="no" />'."\n";
4621:
4622: if (defined($env{'form.CODE'})) {
4623: $studentTable.=
4624: '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
4625: }
4626: my $checkIcon = '<img alt="'.&mt('Check Mark').
4627: '" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
4628:
4629: $studentTable.=' <span class="LC_info">'.
4630: &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
4631: '</span>'."\n".
4632: &Apache::loncommon::start_data_table().
4633: &Apache::loncommon::start_data_table_header_row().
4634: '<th align="center"> Prob. </th>'.
4635: '<th> '.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
4636: &Apache::loncommon::end_data_table_header_row();
4637:
4638: &Apache::lonxml::clear_problem_counter();
4639: my ($depth,$question,$prob) = (1,1,1);
4640: $iterator->next(); # skip the first BEGIN_MAP
4641: my $curRes = $iterator->next(); # for "current resource"
4642: while ($depth > 0) {
4643: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
4644: if($curRes == $iterator->END_MAP) { $depth--; }
4645:
4646: if (ref($curRes) && $curRes->is_problem()) {
4647: my $parts = $curRes->parts();
4648: my $title = $curRes->compTitle();
4649: my $symbx = $curRes->symb();
4650: $studentTable.=
4651: &Apache::loncommon::start_data_table_row().
4652: '<td align="center" valign="top" >'.$prob.
4653: (scalar(@{$parts}) == 1 ? ''
4654: : '<br />('.&mt('[_1]parts)',
4655: scalar(@{$parts}).' ')
4656: ).
4657: '</td>';
4658: $studentTable.='<td valign="top">';
4659: my %form = ('CODE' => $env{'form.CODE'},);
4660: if ($env{'form.vProb'} eq 'yes' ) {
4661: $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
4662: undef,'both',\%form);
4663: } else {
4664: my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
4665: $companswer =~ s|<form(.*?)>||g;
4666: $companswer =~ s|</form>||g;
4667: # while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
4668: # $companswer =~ s/$1/ /ms;
4669: # $request->print('match='.$1."<br />\n");
4670: # }
4671: # $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
4672: $studentTable.=' <b>'.$title.'</b> <br /> <b>'.&mt('Correct answer').':</b><br />'.$companswer;
4673: }
4674:
4675: my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
4676:
4677: if ($env{'form.lastSub'} eq 'datesub') {
4678: if ($record{'version'} eq '') {
4679: $studentTable.='<br /> <span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
4680: } else {
4681: my %responseType = ();
4682: foreach my $partid (@{$parts}) {
4683: my @responseIds =$curRes->responseIds($partid);
4684: my @responseType =$curRes->responseType($partid);
4685: my %responseIds;
4686: for (my $i=0;$i<=$#responseIds;$i++) {
4687: $responseIds{$responseIds[$i]}=$responseType[$i];
4688: }
4689: $responseType{$partid} = \%responseIds;
4690: }
4691: $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
4692:
4693: }
4694: } elsif ($env{'form.lastSub'} eq 'all') {
4695: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
4696: $studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
4697: $env{'request.course.id'},
4698: '','.submission');
4699:
4700: }
4701: if (&canmodify($usec)) {
4702: $studentTable.=&gradeBox_start();
4703: foreach my $partid (@{$parts}) {
4704: $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
4705: $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
4706: $question++;
4707: }
4708: $studentTable.=&gradeBox_end();
4709: $prob++;
4710: }
4711: $studentTable.='</td></tr>';
4712:
4713: }
4714: $curRes = $iterator->next();
4715: }
4716:
4717: $studentTable.=
4718: '</table>'."\n".
4719: '<input type="button" value="'.&mt('Save').'" '.
4720: 'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
4721: '</form>'."\n";
4722: $request->print($studentTable);
4723:
4724: return '';
4725: }
4726:
4727: sub displaySubByDates {
4728: my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
4729: my $isCODE=0;
4730: my $isTask = ($symb =~/\.task$/);
4731: if (exists($record->{'resource.CODE'})) { $isCODE=1; }
4732: my $studentTable=&Apache::loncommon::start_data_table().
4733: &Apache::loncommon::start_data_table_header_row().
4734: '<th>'.&mt('Date/Time').'</th>'.
4735: ($isCODE?'<th>'.&mt('CODE').'</th>':'').
4736: ($isTask?'<th>'.&mt('Version').'</th>':'').
4737: '<th>'.&mt('Submission').'</th>'.
4738: '<th>'.&mt('Status').'</th>'.
4739: &Apache::loncommon::end_data_table_header_row();
4740: my ($version);
4741: my %mark;
4742: my %orders;
4743: $mark{'correct_by_student'} = $checkIcon;
4744: if (!exists($$record{'1:timestamp'})) {
4745: return '<br /> <span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
4746: }
4747:
4748: my $interaction;
4749: my $no_increment = 1;
4750: my %lastrndseed;
4751: for ($version=1;$version<=$$record{'version'};$version++) {
4752: my $timestamp =
4753: &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
4754: if (exists($$record{$version.':resource.0.version'})) {
4755: $interaction = $$record{$version.':resource.0.version'};
4756: }
4757: if ($isTask && $env{'form.previousversion'}) {
4758: next unless ($interaction == $env{'form.previousversion'});
4759: }
4760: my $where = ($isTask ? "$version:resource.$interaction"
4761: : "$version:resource");
4762: $studentTable.=&Apache::loncommon::start_data_table_row().
4763: '<td>'.$timestamp.'</td>';
4764: if ($isCODE) {
4765: $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
4766: }
4767: if ($isTask) {
4768: $studentTable.='<td>'.$interaction.'</td>';
4769: }
4770: my @versionKeys = split(/\:/,$$record{$version.':keys'});
4771: my @displaySub = ();
4772: foreach my $partid (@{$parts}) {
4773: my ($hidden,$type);
4774: $type = $$record{$version.':resource.'.$partid.'.type'};
4775: if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
4776: $hidden = 1;
4777: }
4778: my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
4779: : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
4780:
4781: # next if ($$record{"$version:resource.$partid.solved"} eq '');
4782: my $display_part=&get_display_part($partid,$symb);
4783: foreach my $matchKey (@matchKey) {
4784: if (exists($$record{$version.':'.$matchKey}) &&
4785: $$record{$version.':'.$matchKey} ne '') {
4786:
4787: my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
4788: : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
4789: $displaySub[0].='<span class="LC_nobreak">';
4790: $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
4791: .' <span class="LC_internal_info">'
4792: .'('.&mt('Response ID: [_1]',$responseId).')'
4793: .'</span>'
4794: .' <b>';
4795: if ($hidden) {
4796: $displaySub[0].= &mt('Anonymous Survey').'</b>';
4797: } else {
4798: my ($trial,$rndseed,$newvariation);
4799: if ($type eq 'randomizetry') {
4800: $trial = $$record{"$where.$partid.tries"};
4801: $rndseed = $$record{"$where.$partid.rndseed"};
4802: }
4803: if ($$record{"$where.$partid.tries"} eq '') {
4804: $displaySub[0].=&mt('Trial not counted');
4805: } else {
4806: $displaySub[0].=&mt('Trial: [_1]',
4807: $$record{"$where.$partid.tries"});
4808: if ($rndseed || $lastrndseed{$partid}) {
4809: if ($rndseed ne $lastrndseed{$partid}) {
4810: $newvariation = ' ('.&mt('New variation this try').')';
4811: }
4812: }
4813: $lastrndseed{$partid} = $rndseed;
4814: }
4815: my $responseType=($isTask ? 'Task'
4816: : $responseType->{$partid}->{$responseId});
4817: if (!exists($orders{$partid})) { $orders{$partid}={}; }
4818: if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
4819: $orders{$partid}->{$responseId}=
4820: &get_order($partid,$responseId,$symb,$uname,$udom,
4821: $no_increment,$type,$trial,$rndseed);
4822: }
4823: $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
4824: $displaySub[0].=' '.
4825: &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
4826: }
4827: }
4828: }
4829: if (exists($$record{"$where.$partid.checkedin"})) {
4830: $displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
4831: $$record{"$where.$partid.checkedin"},
4832: $$record{"$where.$partid.checkedin.slot"}).
4833: '<br />';
4834: }
4835: if (exists $$record{"$where.$partid.award"}) {
4836: $displaySub[1].='<b>'.&mt('Part:').'</b> '.$display_part.' '.
4837: lc($$record{"$where.$partid.award"}).' '.
4838: $mark{$$record{"$where.$partid.solved"}}.
4839: '<br />';
4840: }
4841: if (exists $$record{"$where.$partid.regrader"}) {
4842: $displaySub[2].=$$record{"$where.$partid.regrader"}.
4843: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
4844: } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
4845: $displaySub[2].=
4846: $$record{"$version:resource.$partid.regrader"}.
4847: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
4848: }
4849: }
4850: # needed because old essay regrader has not parts info
4851: if (exists $$record{"$version:resource.regrader"}) {
4852: $displaySub[2].=$$record{"$version:resource.regrader"};
4853: }
4854: $studentTable.='<td>'.$displaySub[0].' </td><td>'.$displaySub[1];
4855: if ($displaySub[2]) {
4856: $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
4857: }
4858: $studentTable.=' </td>'.
4859: &Apache::loncommon::end_data_table_row();
4860: }
4861: $studentTable.=&Apache::loncommon::end_data_table();
4862: return $studentTable;
4863: }
4864:
4865: sub updateGradeByPage {
4866: my ($request,$symb) = @_;
4867:
4868: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4869: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4870: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4871: my $pageTitle = $env{'form.page'};
4872: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
4873: my ($uname,$udom) = split(/:/,$env{'form.student'});
4874: my $usec=$classlist->{$env{'form.student'}}[5];
4875: if (!&canmodify($usec)) {
4876: $request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
4877: return;
4878: }
4879: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
4880: $result.='<h3> '.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
4881: '</h3>'."\n";
4882:
4883: $request->print($result);
4884:
4885:
4886: my $navmap = Apache::lonnavmaps::navmap->new();
4887: unless (ref($navmap)) {
4888: $request->print(&navmap_errormsg());
4889: return;
4890: }
4891: my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
4892: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
4893: if (!$map) {
4894: $request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
4895: return;
4896: }
4897: my $iterator = $navmap->getIterator($map->map_start(),
4898: $map->map_finish());
4899:
4900: my $studentTable=
4901: &Apache::loncommon::start_data_table().
4902: &Apache::loncommon::start_data_table_header_row().
4903: '<th align="center"> '.&mt('Prob.').' </th>'.
4904: '<th> '.&mt('Title').' </th>'.
4905: '<th> '.&mt('Previous Score').' </th>'.
4906: '<th> '.&mt('New Score').' </th>'.
4907: &Apache::loncommon::end_data_table_header_row();
4908:
4909: $iterator->next(); # skip the first BEGIN_MAP
4910: my $curRes = $iterator->next(); # for "current resource"
4911: my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
4912: while ($depth > 0) {
4913: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
4914: if($curRes == $iterator->END_MAP) { $depth--; }
4915:
4916: if (ref($curRes) && $curRes->is_problem()) {
4917: my $parts = $curRes->parts();
4918: my $title = $curRes->compTitle();
4919: my $symbx = $curRes->symb();
4920: $studentTable.=
4921: &Apache::loncommon::start_data_table_row().
4922: '<td align="center" valign="top" >'.$prob.
4923: (scalar(@{$parts}) == 1 ? ''
4924: : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
4925: .')').'</td>';
4926: $studentTable.='<td valign="top"> <b>'.$title.'</b> </td>';
4927:
4928: my %newrecord=();
4929: my @displayPts=();
4930: my %aggregate = ();
4931: my $aggregateflag = 0;
4932: foreach my $partid (@{$parts}) {
4933: my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
4934: my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
4935:
4936: my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ?
4937: $env{'form.WGT'.$question.'_'.$partid} : 1;
4938: my $partial = $newpts/$wgt;
4939: my $score;
4940: if ($partial > 0) {
4941: $score = 'correct_by_override';
4942: } elsif ($newpts ne '') { #empty is taken as 0
4943: $score = 'incorrect_by_override';
4944: }
4945: my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
4946: if ($dropMenu eq 'excused') {
4947: $partial = '';
4948: $score = 'excused';
4949: } elsif ($dropMenu eq 'reset status'
4950: && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
4951: $newrecord{'resource.'.$partid.'.tries'} = 0;
4952: $newrecord{'resource.'.$partid.'.solved'} = '';
4953: $newrecord{'resource.'.$partid.'.award'} = '';
4954: $newrecord{'resource.'.$partid.'.awarded'} = 0;
4955: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
4956: $changeflag++;
4957: $newpts = '';
4958:
4959: my $aggtries = $env{'form.aggtries'.$question.'_'.$partid};
4960: my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
4961: my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
4962: if ($aggtries > 0) {
4963: &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
4964: $aggregateflag = 1;
4965: }
4966: }
4967: my $display_part=&get_display_part($partid,$curRes->symb());
4968: my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
4969: $displayPts[0].=' <b>'.&mt('Part').':</b> '.$display_part.' = '.
4970: (($oldstatus eq 'excused') ? 'excused' : $oldpts).
4971: ' <br />';
4972: $displayPts[1].=' <b>'.&mt('Part').':</b> '.$display_part.' = '.
4973: (($score eq 'excused') ? 'excused' : $newpts).
4974: ' <br />';
4975: $question++;
4976: next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
4977:
4978: $newrecord{'resource.'.$partid.'.awarded'} = $partial if $partial ne '';
4979: $newrecord{'resource.'.$partid.'.solved'} = $score if $score ne '';
4980: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
4981: if (scalar(keys(%newrecord)) > 0);
4982:
4983: $changeflag++;
4984: }
4985: if (scalar(keys(%newrecord)) > 0) {
4986: my %record =
4987: &Apache::lonnet::restore($symbx,$env{'request.course.id'},
4988: $udom,$uname);
4989:
4990: if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
4991: $newrecord{'resource.CODE'} = $env{'form.CODE'};
4992: } elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
4993: $newrecord{'resource.CODE'} = '';
4994: }
4995: &Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
4996: $udom,$uname);
4997: %record = &Apache::lonnet::restore($symbx,
4998: $env{'request.course.id'},
4999: $udom,$uname);
5000: &check_and_remove_from_queue($parts,\%record,undef,$symbx,
5001: $cdom,$cnum,$udom,$uname);
5002: }
5003:
5004: if ($aggregateflag) {
5005: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
5006: $env{'course.'.$env{'request.course.id'}.'.domain'},
5007: $env{'course.'.$env{'request.course.id'}.'.num'});
5008: }
5009:
5010: $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
5011: '<td valign="top">'.$displayPts[1].'</td>'.
5012: &Apache::loncommon::end_data_table_row();
5013:
5014: $prob++;
5015: }
5016: $curRes = $iterator->next();
5017: }
5018:
5019: $studentTable.=&Apache::loncommon::end_data_table();
5020: my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
5021: &mt('The scores were changed for [quant,_1,problem].',
5022: $changeflag));
5023: $request->print($grademsg.$studentTable);
5024:
5025: return '';
5026: }
5027:
5028: #-------- end of section for handling grading by page/sequence ---------
5029: #
5030: #-------------------------------------------------------------------
5031:
5032: #-------------------- Bubblesheet (Scantron) Grading -------------------
5033: #
5034: #------ start of section for handling grading by page/sequence ---------
5035:
5036: =pod
5037:
5038: =head1 Bubble sheet grading routines
5039:
5040: For this documentation:
5041:
5042: 'scanline' refers to the full line of characters
5043: from the file that we are parsing that represents one entire sheet
5044:
5045: 'bubble line' refers to the data
5046: representing the line of bubbles that are on the physical bubblesheet
5047:
5048:
5049: The overall process is that a scanned in bubblesheet data is uploaded
5050: into a course. When a user wants to grade, they select a
5051: sequence/folder of resources, a file of bubblesheet info, and pick
5052: one of the predefined configurations for what each scanline looks
5053: like.
5054:
5055: Next each scanline is checked for any errors of either 'missing
5056: bubbles' (it's an error because it may have been mis-scanned
5057: because too light bubbling), 'double bubble' (each bubble line should
5058: have no more that one letter picked), invalid or duplicated CODE,
5059: invalid student/employee ID
5060:
5061: If the CODE option is used that determines the randomization of the
5062: homework problems, either way the student/employee ID is looked up into a
5063: username:domain.
5064:
5065: During the validation phase the instructor can choose to skip scanlines.
5066:
5067: After the validation phase, there are now 3 bubblesheet files
5068:
5069: scantron_original_filename (unmodified original file)
5070: scantron_corrected_filename (file where the corrected information has replaced the original information)
5071: scantron_skipped_filename (contains the exact text of scanlines that where skipped)
5072:
5073: Also there is a separate hash nohist_scantrondata that contains extra
5074: correction information that isn't representable in the bubblesheet
5075: file (see &scantron_getfile() for more information)
5076:
5077: After all scanlines are either valid, marked as valid or skipped, then
5078: foreach line foreach problem in the picked sequence, an ssi request is
5079: made that simulates a user submitting their selected letter(s) against
5080: the homework problem.
5081:
5082: =over 4
5083:
5084:
5085:
5086: =item defaultFormData
5087:
5088: Returns html hidden inputs used to hold context/default values.
5089:
5090: Arguments:
5091: $symb - $symb of the current resource
5092:
5093: =cut
5094:
5095: sub defaultFormData {
5096: my ($symb)=@_;
5097: return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
5098: }
5099:
5100:
5101: =pod
5102:
5103: =item getSequenceDropDown
5104:
5105: Return html dropdown of possible sequences to grade
5106:
5107: Arguments:
5108: $symb - $symb of the current resource
5109: $map_error - ref to scalar which will container error if
5110: $navmap object is unavailable in &getSymbMap().
5111:
5112: =cut
5113:
5114: sub getSequenceDropDown {
5115: my ($symb,$map_error)=@_;
5116: my $result='<select name="selectpage">'."\n";
5117: my ($titles,$symbx) = &getSymbMap($map_error);
5118: if (ref($map_error)) {
5119: return if ($$map_error);
5120: }
5121: my ($curpage)=&Apache::lonnet::decode_symb($symb);
5122: my $ctr=0;
5123: foreach (@$titles) {
5124: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
5125: $result.='<option value="'.$$symbx{$_}.'" '.
5126: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
5127: '>'.$showtitle.'</option>'."\n";
5128: $ctr++;
5129: }
5130: $result.= '</select>';
5131: return $result;
5132: }
5133:
5134: my %bubble_lines_per_response; # no. bubble lines for each response.
5135: # key is zero-based index - 0, 1, 2 ...
5136:
5137: my %first_bubble_line; # First bubble line no. for each bubble.
5138:
5139: my %subdivided_bubble_lines; # no. bubble lines for optionresponse,
5140: # matchresponse or rankresponse, where
5141: # an individual response can have multiple
5142: # lines
5143:
5144: my %responsetype_per_response; # responsetype for each response
5145:
5146: # Save and restore the bubble lines array to the form env.
5147:
5148:
5149: sub save_bubble_lines {
5150: foreach my $line (keys(%bubble_lines_per_response)) {
5151: $env{"form.scantron.bubblelines.$line"} = $bubble_lines_per_response{$line};
5152: $env{"form.scantron.first_bubble_line.$line"} =
5153: $first_bubble_line{$line};
5154: $env{"form.scantron.sub_bubblelines.$line"} =
5155: $subdivided_bubble_lines{$line};
5156: $env{"form.scantron.responsetype.$line"} =
5157: $responsetype_per_response{$line};
5158: }
5159: }
5160:
5161:
5162: sub restore_bubble_lines {
5163: my $line = 0;
5164: %bubble_lines_per_response = ();
5165: while ($env{"form.scantron.bubblelines.$line"}) {
5166: my $value = $env{"form.scantron.bubblelines.$line"};
5167: $bubble_lines_per_response{$line} = $value;
5168: $first_bubble_line{$line} =
5169: $env{"form.scantron.first_bubble_line.$line"};
5170: $subdivided_bubble_lines{$line} =
5171: $env{"form.scantron.sub_bubblelines.$line"};
5172: $responsetype_per_response{$line} =
5173: $env{"form.scantron.responsetype.$line"};
5174: $line++;
5175: }
5176: }
5177:
5178: # Given the parsed scanline, get the response for
5179: # 'answer' number n:
5180:
5181: sub get_response_bubbles {
5182: my ($parsed_line, $response) = @_;
5183:
5184: my $bubble_line = $first_bubble_line{$response-1} +1;
5185: my $bubble_lines= $bubble_lines_per_response{$response-1};
5186:
5187: my $selected = "";
5188:
5189: for (my $bline = 0; $bline < $bubble_lines; $bline++) {
5190: $selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
5191: $bubble_line++;
5192: }
5193: return $selected;
5194: }
5195:
5196: =pod
5197:
5198: =item scantron_filenames
5199:
5200: Returns a list of the scantron files in the current course
5201:
5202: =cut
5203:
5204: sub scantron_filenames {
5205: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5206: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5207: my $getpropath = 1;
5208: my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
5209: $cname,$getpropath);
5210: my @possiblenames;
5211: if (ref($dirlist) eq 'ARRAY') {
5212: foreach my $filename (sort(@{$dirlist})) {
5213: ($filename)=split(/&/,$filename);
5214: if ($filename!~/^scantron_orig_/) { next ; }
5215: $filename=~s/^scantron_orig_//;
5216: push(@possiblenames,$filename);
5217: }
5218: }
5219: return @possiblenames;
5220: }
5221:
5222: =pod
5223:
5224: =item scantron_uploads
5225:
5226: Returns html drop-down list of scantron files in current course.
5227:
5228: Arguments:
5229: $file2grade - filename to set as selected in the dropdown
5230:
5231: =cut
5232:
5233: sub scantron_uploads {
5234: my ($file2grade) = @_;
5235: my $result= '<select name="scantron_selectfile">';
5236: $result.="<option></option>";
5237: foreach my $filename (sort(&scantron_filenames())) {
5238: $result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
5239: }
5240: $result.="</select>";
5241: return $result;
5242: }
5243:
5244: =pod
5245:
5246: =item scantron_scantab
5247:
5248: Returns html drop down of the scantron formats in the scantronformat.tab
5249: file.
5250:
5251: =cut
5252:
5253: sub scantron_scantab {
5254: my $result='<select name="scantron_format">'."\n";
5255: $result.='<option></option>'."\n";
5256: my @lines = &get_scantronformat_file();
5257: if (@lines > 0) {
5258: foreach my $line (@lines) {
5259: next if (($line =~ /^\#/) || ($line eq ''));
5260: my ($name,$descrip)=split(/:/,$line);
5261: $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
5262: }
5263: }
5264: $result.='</select>'."\n";
5265: return $result;
5266: }
5267:
5268: =pod
5269:
5270: =item get_scantronformat_file
5271:
5272: Returns an array containing lines from the scantron format file for
5273: the domain of the course.
5274:
5275: If a url for a custom.tab file is listed in domain's configuration.db,
5276: lines are from this file.
5277:
5278: Otherwise, if a default.tab has been published in RES space by the
5279: domainconfig user, lines are from this file.
5280:
5281: Otherwise, fall back to getting lines from the legacy file on the
5282: local server: /home/httpd/lonTabs/default_scantronformat.tab
5283:
5284: =cut
5285:
5286: sub get_scantronformat_file {
5287: my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
5288: my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
5289: my $gottab = 0;
5290: my @lines;
5291: if (ref($domconfig{'scantron'}) eq 'HASH') {
5292: if ($domconfig{'scantron'}{'scantronformat'} ne '') {
5293: my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
5294: if ($formatfile ne '-1') {
5295: @lines = split("\n",$formatfile,-1);
5296: $gottab = 1;
5297: }
5298: }
5299: }
5300: if (!$gottab) {
5301: my $confname = $cdom.'-domainconfig';
5302: my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
5303: my $formatfile = &Apache::lonnet::getfile($default);
5304: if ($formatfile ne '-1') {
5305: @lines = split("\n",$formatfile,-1);
5306: $gottab = 1;
5307: }
5308: }
5309: if (!$gottab) {
5310: my @domains = &Apache::lonnet::current_machine_domains();
5311: if (grep(/^\Q$cdom\E$/,@domains)) {
5312: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
5313: @lines = <$fh>;
5314: close($fh);
5315: } else {
5316: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
5317: @lines = <$fh>;
5318: close($fh);
5319: }
5320: }
5321: return @lines;
5322: }
5323:
5324: =pod
5325:
5326: =item scantron_CODElist
5327:
5328: Returns html drop down of the saved CODE lists from current course,
5329: generated from earlier printings.
5330:
5331: =cut
5332:
5333: sub scantron_CODElist {
5334: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5335: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5336: my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
5337: my $namechoice='<option></option>';
5338: foreach my $name (sort {uc($a) cmp uc($b)} @names) {
5339: if ($name =~ /^error: 2 /) { next; }
5340: if ($name =~ /^type\0/) { next; }
5341: $namechoice.='<option value="'.$name.'">'.$name.'</option>';
5342: }
5343: $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
5344: return $namechoice;
5345: }
5346:
5347: =pod
5348:
5349: =item scantron_CODEunique
5350:
5351: Returns the html for "Each CODE to be used once" radio.
5352:
5353: =cut
5354:
5355: sub scantron_CODEunique {
5356: my $result='<span class="LC_nobreak">
5357: <label><input type="radio" name="scantron_CODEunique"
5358: value="yes" checked="checked" />'.&mt('Yes').' </label>
5359: </span>
5360: <span class="LC_nobreak">
5361: <label><input type="radio" name="scantron_CODEunique"
5362: value="no" />'.&mt('No').' </label>
5363: </span>';
5364: return $result;
5365: }
5366:
5367: =pod
5368:
5369: =item scantron_selectphase
5370:
5371: Generates the initial screen to start the bubblesheet process.
5372: Allows for - starting a grading run.
5373: - downloading existing scan data (original, corrected
5374: or skipped info)
5375:
5376: - uploading new scan data
5377:
5378: Arguments:
5379: $r - The Apache request object
5380: $file2grade - name of the file that contain the scanned data to score
5381:
5382: =cut
5383:
5384: sub scantron_selectphase {
5385: my ($r,$file2grade,$symb) = @_;
5386: if (!$symb) {return '';}
5387: my $map_error;
5388: my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
5389: if ($map_error) {
5390: $r->print('<br />'.&navmap_errormsg().'<br />');
5391: return;
5392: }
5393: my $default_form_data=&defaultFormData($symb);
5394: my $file_selector=&scantron_uploads($file2grade);
5395: my $format_selector=&scantron_scantab();
5396: my $CODE_selector=&scantron_CODElist();
5397: my $CODE_unique=&scantron_CODEunique();
5398: my $result;
5399:
5400: $ssi_error = 0;
5401:
5402: if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
5403: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
5404:
5405: # Chunk of form to prompt for a scantron file upload.
5406:
5407: $r->print('
5408: <br />
5409: '.&Apache::loncommon::start_data_table('LC_scantron_action').'
5410: '.&Apache::loncommon::start_data_table_header_row().'
5411: <th>
5412: '.&mt('Specify a bubblesheet data file to upload.').'
5413: </th>
5414: '.&Apache::loncommon::end_data_table_header_row().'
5415: '.&Apache::loncommon::start_data_table_row().'
5416: <td>
5417: ');
5418: my $default_form_data=&defaultFormData($symb);
5419: my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
5420: my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
5421: $r->print(&Apache::lonhtmlcommon::scripttag('
5422: function checkUpload(formname) {
5423: if (formname.upfile.value == "") {
5424: alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
5425: return false;
5426: }
5427: formname.submit();
5428: }'));
5429: $r->print('
5430: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
5431: '.$default_form_data.'
5432: <input name="courseid" type="hidden" value="'.$cnum.'" />
5433: <input name="domainid" type="hidden" value="'.$cdom.'" />
5434: <input name="command" value="scantronupload_save" type="hidden" />
5435: '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
5436: <br />
5437: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
5438: </form>
5439: ');
5440:
5441: $r->print('
5442: </td>
5443: '.&Apache::loncommon::end_data_table_row().'
5444: '.&Apache::loncommon::end_data_table().'
5445: ');
5446: }
5447:
5448: # Chunk of form to prompt for a file to grade and how:
5449:
5450: $result.= '
5451: <br />
5452: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
5453: <input type="hidden" name="command" value="scantron_warning" />
5454: '.$default_form_data.'
5455: '.&Apache::loncommon::start_data_table('LC_scantron_action').'
5456: '.&Apache::loncommon::start_data_table_header_row().'
5457: <th colspan="2">
5458: '.&mt('Specify file and which Folder/Sequence to grade').'
5459: </th>
5460: '.&Apache::loncommon::end_data_table_header_row().'
5461: '.&Apache::loncommon::start_data_table_row().'
5462: <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
5463: '.&Apache::loncommon::end_data_table_row().'
5464: '.&Apache::loncommon::start_data_table_row().'
5465: <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
5466: '.&Apache::loncommon::end_data_table_row().'
5467: '.&Apache::loncommon::start_data_table_row().'
5468: <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
5469: '.&Apache::loncommon::end_data_table_row().'
5470: '.&Apache::loncommon::start_data_table_row().'
5471: <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
5472: '.&Apache::loncommon::end_data_table_row().'
5473: '.&Apache::loncommon::start_data_table_row().'
5474: <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
5475: '.&Apache::loncommon::end_data_table_row().'
5476: '.&Apache::loncommon::start_data_table_row().'
5477: <td> '.&mt('Options:').' </td>
5478: <td>
5479: <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
5480: <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
5481: <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
5482: </td>
5483: '.&Apache::loncommon::end_data_table_row().'
5484: '.&Apache::loncommon::start_data_table_row().'
5485: <td colspan="2">
5486: <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
5487: </td>
5488: '.&Apache::loncommon::end_data_table_row().'
5489: '.&Apache::loncommon::end_data_table().'
5490: </form>
5491: ';
5492:
5493: $r->print($result);
5494:
5495:
5496:
5497: # Chunk of the form that prompts to view a scoring office file,
5498: # corrected file, skipped records in a file.
5499:
5500: $r->print('
5501: <br />
5502: <form action="/adm/grades" name="scantron_download">
5503: '.$default_form_data.'
5504: <input type="hidden" name="command" value="scantron_download" />
5505: '.&Apache::loncommon::start_data_table('LC_scantron_action').'
5506: '.&Apache::loncommon::start_data_table_header_row().'
5507: <th>
5508: '.&mt('Download a scoring office file').'
5509: </th>
5510: '.&Apache::loncommon::end_data_table_header_row().'
5511: '.&Apache::loncommon::start_data_table_row().'
5512: <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).'
5513: <br />
5514: <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
5515: '.&Apache::loncommon::end_data_table_row().'
5516: '.&Apache::loncommon::end_data_table().'
5517: </form>
5518: <br />
5519: ');
5520:
5521: &Apache::lonpickcode::code_list($r,2);
5522:
5523: $r->print('<br /><form method="post" name="checkscantron">'.
5524: $default_form_data."\n".
5525: &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
5526: &Apache::loncommon::start_data_table_header_row()."\n".
5527: '<th colspan="2">
5528: '.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
5529: '</th>'."\n".
5530: &Apache::loncommon::end_data_table_header_row()."\n".
5531: &Apache::loncommon::start_data_table_row()."\n".
5532: '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
5533: '<td> '.$sequence_selector.' </td>'.
5534: &Apache::loncommon::end_data_table_row()."\n".
5535: &Apache::loncommon::start_data_table_row()."\n".
5536: '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
5537: '<td> '.$file_selector.' </td>'."\n".
5538: &Apache::loncommon::end_data_table_row()."\n".
5539: &Apache::loncommon::start_data_table_row()."\n".
5540: '<td> '.&mt('Format of data file:').' </td>'."\n".
5541: '<td> '.$format_selector.' </td>'."\n".
5542: &Apache::loncommon::end_data_table_row()."\n".
5543: &Apache::loncommon::start_data_table_row()."\n".
5544: '<td> '.&mt('Options').' </td>'."\n".
5545: '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
5546: &Apache::loncommon::end_data_table_row()."\n".
5547: &Apache::loncommon::start_data_table_row()."\n".
5548: '<td colspan="2">'."\n".
5549: '<input type="hidden" name="command" value="checksubmissions" />'."\n".
5550: '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
5551: '</td>'."\n".
5552: &Apache::loncommon::end_data_table_row()."\n".
5553: &Apache::loncommon::end_data_table()."\n".
5554: '</form><br />');
5555: return;
5556: }
5557:
5558: =pod
5559:
5560: =item get_scantron_config
5561:
5562: Parse and return the scantron configuration line selected as a
5563: hash of configuration file fields.
5564:
5565: Arguments:
5566: which - the name of the configuration to parse from the file.
5567:
5568:
5569: Returns:
5570: If the named configuration is not in the file, an empty
5571: hash is returned.
5572: a hash with the fields
5573: name - internal name for the this configuration setup
5574: description - text to display to operator that describes this config
5575: CODElocation - if 0 or the string 'none'
5576: - no CODE exists for this config
5577: if -1 || the string 'letter'
5578: - a CODE exists for this config and is
5579: a string of letters
5580: Unsupported value (but planned for future support)
5581: if a positive integer
5582: - The CODE exists as the first n items from
5583: the question section of the form
5584: if the string 'number'
5585: - The CODE exists for this config and is
5586: a string of numbers
5587: CODEstart - (only matter if a CODE exists) column in the line where
5588: the CODE starts
5589: CODElength - length of the CODE
5590: IDstart - column where the student/employee ID starts
5591: IDlength - length of the student/employee ID info
5592: Qstart - column where the information from the bubbled
5593: 'questions' start
5594: Qlength - number of columns comprising a single bubble line from
5595: the sheet. (usually either 1 or 10)
5596: Qon - either a single character representing the character used
5597: to signal a bubble was chosen in the positional setup, or
5598: the string 'letter' if the letter of the chosen bubble is
5599: in the final, or 'number' if a number representing the
5600: chosen bubble is in the file (1->A 0->J)
5601: Qoff - the character used to represent that a bubble was
5602: left blank
5603: PaperID - if the scanning process generates a unique number for each
5604: sheet scanned the column that this ID number starts in
5605: PaperIDlength - number of columns that comprise the unique ID number
5606: for the sheet of paper
5607: FirstName - column that the first name starts in
5608: FirstNameLength - number of columns that the first name spans
5609:
5610: LastName - column that the last name starts in
5611: LastNameLength - number of columns that the last name spans
5612: BubblesPerRow - number of bubbles available in each row used to
5613: bubble an answer. (If not specified, 10 assumed).
5614:
5615: =cut
5616:
5617: sub get_scantron_config {
5618: my ($which) = @_;
5619: my @lines = &get_scantronformat_file();
5620: my %config;
5621: #FIXME probably should move to XML it has already gotten a bit much now
5622: foreach my $line (@lines) {
5623: my ($name,$descrip)=split(/:/,$line);
5624: if ($name ne $which ) { next; }
5625: chomp($line);
5626: my @config=split(/:/,$line);
5627: $config{'name'}=$config[0];
5628: $config{'description'}=$config[1];
5629: $config{'CODElocation'}=$config[2];
5630: $config{'CODEstart'}=$config[3];
5631: $config{'CODElength'}=$config[4];
5632: $config{'IDstart'}=$config[5];
5633: $config{'IDlength'}=$config[6];
5634: $config{'Qstart'}=$config[7];
5635: $config{'Qlength'}=$config[8];
5636: $config{'Qoff'}=$config[9];
5637: $config{'Qon'}=$config[10];
5638: $config{'PaperID'}=$config[11];
5639: $config{'PaperIDlength'}=$config[12];
5640: $config{'FirstName'}=$config[13];
5641: $config{'FirstNamelength'}=$config[14];
5642: $config{'LastName'}=$config[15];
5643: $config{'LastNamelength'}=$config[16];
5644: $config{'BubblesPerRow'}=$config[17];
5645: last;
5646: }
5647: return %config;
5648: }
5649:
5650: =pod
5651:
5652: =item username_to_idmap
5653:
5654: creates a hash keyed by student/employee ID with values of the corresponding
5655: student username:domain.
5656:
5657: Arguments:
5658:
5659: $classlist - reference to the class list hash. This is a hash
5660: keyed by student name:domain whose elements are references
5661: to arrays containing various chunks of information
5662: about the student. (See loncoursedata for more info).
5663:
5664: Returns
5665: %idmap - the constructed hash
5666:
5667: =cut
5668:
5669: sub username_to_idmap {
5670: my ($classlist)= @_;
5671: my %idmap;
5672: foreach my $student (keys(%$classlist)) {
5673: $idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
5674: $student;
5675: }
5676: return %idmap;
5677: }
5678:
5679: =pod
5680:
5681: =item scantron_fixup_scanline
5682:
5683: Process a requested correction to a scanline.
5684:
5685: Arguments:
5686: $scantron_config - hash from &get_scantron_config()
5687: $scan_data - hash of correction information
5688: (see &scantron_getfile())
5689: $line - existing scanline
5690: $whichline - line number of the passed in scanline
5691: $field - type of change to process
5692: (either
5693: 'ID' -> correct the student/employee ID
5694: 'CODE' -> correct the CODE
5695: 'answer' -> fixup the submitted answers)
5696:
5697: $args - hash of additional info,
5698: - 'ID'
5699: 'newid' -> studentID to use in replacement
5700: of existing one
5701: - 'CODE'
5702: 'CODE_ignore_dup' - set to true if duplicates
5703: should be ignored.
5704: 'CODE' - is new code or 'use_unfound'
5705: if the existing unfound code should
5706: be used as is
5707: - 'answer'
5708: 'response' - new answer or 'none' if blank
5709: 'question' - the bubble line to change
5710: 'questionnum' - the question identifier,
5711: may include subquestion.
5712:
5713: Returns:
5714: $line - the modified scanline
5715:
5716: Side effects:
5717: $scan_data - may be updated
5718:
5719: =cut
5720:
5721:
5722: sub scantron_fixup_scanline {
5723: my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
5724: if ($field eq 'ID') {
5725: if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
5726: return ($line,1,'New value too large');
5727: }
5728: if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
5729: $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
5730: $args->{'newid'});
5731: }
5732: substr($line,$$scantron_config{'IDstart'}-1,
5733: $$scantron_config{'IDlength'})=$args->{'newid'};
5734: if ($args->{'newid'}=~/^\s*$/) {
5735: &scan_data($scan_data,"$whichline.user",
5736: $args->{'username'}.':'.$args->{'domain'});
5737: }
5738: } elsif ($field eq 'CODE') {
5739: if ($args->{'CODE_ignore_dup'}) {
5740: &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
5741: }
5742: &scan_data($scan_data,"$whichline.useCODE",'1');
5743: if ($args->{'CODE'} ne 'use_unfound') {
5744: if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
5745: return ($line,1,'New CODE value too large');
5746: }
5747: if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
5748: $args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
5749: }
5750: substr($line,$$scantron_config{'CODEstart'}-1,
5751: $$scantron_config{'CODElength'})=$args->{'CODE'};
5752: }
5753: } elsif ($field eq 'answer') {
5754: my $length=$scantron_config->{'Qlength'};
5755: my $off=$scantron_config->{'Qoff'};
5756: my $on=$scantron_config->{'Qon'};
5757: my $answer=${off}x$length;
5758: if ($args->{'response'} eq 'none') {
5759: &scan_data($scan_data,
5760: "$whichline.no_bubble.".$args->{'questionnum'},'1');
5761: } else {
5762: if ($on eq 'letter') {
5763: my @alphabet=('A'..'Z');
5764: $answer=$alphabet[$args->{'response'}];
5765: } elsif ($on eq 'number') {
5766: $answer=$args->{'response'}+1;
5767: if ($answer == 10) { $answer = '0'; }
5768: } else {
5769: substr($answer,$args->{'response'},1)=$on;
5770: }
5771: &scan_data($scan_data,
5772: "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
5773: }
5774: my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
5775: substr($line,$where-1,$length)=$answer;
5776: }
5777: return $line;
5778: }
5779:
5780: =pod
5781:
5782: =item scan_data
5783:
5784: Edit or look up an item in the scan_data hash.
5785:
5786: Arguments:
5787: $scan_data - The hash (see scantron_getfile)
5788: $key - shorthand of the key to edit (actual key is
5789: scantronfilename_key).
5790: $data - New value of the hash entry.
5791: $delete - If true, the entry is removed from the hash.
5792:
5793: Returns:
5794: The new value of the hash table field (undefined if deleted).
5795:
5796: =cut
5797:
5798:
5799: sub scan_data {
5800: my ($scan_data,$key,$value,$delete)=@_;
5801: my $filename=$env{'form.scantron_selectfile'};
5802: if (defined($value)) {
5803: $scan_data->{$filename.'_'.$key} = $value;
5804: }
5805: if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
5806: return $scan_data->{$filename.'_'.$key};
5807: }
5808:
5809: # ----- These first few routines are general use routines.----
5810:
5811: # Return the number of occurences of a pattern in a string.
5812:
5813: sub occurence_count {
5814: my ($string, $pattern) = @_;
5815:
5816: my @matches = ($string =~ /$pattern/g);
5817:
5818: return scalar(@matches);
5819: }
5820:
5821:
5822: # Take a string known to have digits and convert all the
5823: # digits into letters in the range J,A..I.
5824:
5825: sub digits_to_letters {
5826: my ($input) = @_;
5827:
5828: my @alphabet = ('J', 'A'..'I');
5829:
5830: my @input = split(//, $input);
5831: my $output ='';
5832: for (my $i = 0; $i < scalar(@input); $i++) {
5833: if ($input[$i] =~ /\d/) {
5834: $output .= $alphabet[$input[$i]];
5835: } else {
5836: $output .= $input[$i];
5837: }
5838: }
5839: return $output;
5840: }
5841:
5842: =pod
5843:
5844: =item scantron_parse_scanline
5845:
5846: Decodes a scanline from the selected scantron file
5847:
5848: Arguments:
5849: line - The text of the scantron file line to process
5850: whichline - Line number
5851: scantron_config - Hash describing the format of the scantron lines.
5852: scan_data - Hash of extra information about the scanline
5853: (see scantron_getfile for more information)
5854: just_header - True if should not process question answers but only
5855: the stuff to the left of the answers.
5856: Returns:
5857: Hash containing the result of parsing the scanline
5858:
5859: Keys are all proceeded by the string 'scantron.'
5860:
5861: CODE - the CODE in use for this scanline
5862: useCODE - 1 if the CODE is invalid but it usage has been forced
5863: by the operator
5864: CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
5865: CODEs were selected, but the usage has been
5866: forced by the operator
5867: ID - student/employee ID
5868: PaperID - if used, the ID number printed on the sheet when the
5869: paper was scanned
5870: FirstName - first name from the sheet
5871: LastName - last name from the sheet
5872:
5873: if just_header was not true these key may also exist
5874:
5875: missingerror - a list of bubble ranges that are considered to be answers
5876: to a single question that don't have any bubbles filled in.
5877: Of the form questionnumber:firstbubblenumber:count.
5878: doubleerror - a list of bubble ranges that are considered to be answers
5879: to a single question that have more than one bubble filled in.
5880: Of the form questionnumber::firstbubblenumber:count
5881:
5882: In the above, count is the number of bubble responses in the
5883: input line needed to represent the possible answers to the question.
5884: e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
5885: per line would have count = 2.
5886:
5887: maxquest - the number of the last bubble line that was parsed
5888:
5889: (<number> starts at 1)
5890: <number>.answer - zero or more letters representing the selected
5891: letters from the scanline for the bubble line
5892: <number>.
5893: if blank there was either no bubble or there where
5894: multiple bubbles, (consult the keys missingerror and
5895: doubleerror if this is an error condition)
5896:
5897: =cut
5898:
5899: sub scantron_parse_scanline {
5900: my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
5901:
5902: my %record;
5903: my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
5904: my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos); # Answers
5905: my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # earlier stuff
5906: if (!($$scantron_config{'CODElocation'} eq 0 ||
5907: $$scantron_config{'CODElocation'} eq 'none')) {
5908: if ($$scantron_config{'CODElocation'} < 0 ||
5909: $$scantron_config{'CODElocation'} eq 'letter' ||
5910: $$scantron_config{'CODElocation'} eq 'number') {
5911: $record{'scantron.CODE'}=substr($data,
5912: $$scantron_config{'CODEstart'}-1,
5913: $$scantron_config{'CODElength'});
5914: if (&scan_data($scan_data,"$whichline.useCODE")) {
5915: $record{'scantron.useCODE'}=1;
5916: }
5917: if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
5918: $record{'scantron.CODE_ignore_dup'}=1;
5919: }
5920: } else {
5921: #FIXME interpret first N questions
5922: }
5923: }
5924: $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
5925: $$scantron_config{'IDlength'});
5926: $record{'scantron.PaperID'}=
5927: substr($data,$$scantron_config{'PaperID'}-1,
5928: $$scantron_config{'PaperIDlength'});
5929: $record{'scantron.FirstName'}=
5930: substr($data,$$scantron_config{'FirstName'}-1,
5931: $$scantron_config{'FirstNamelength'});
5932: $record{'scantron.LastName'}=
5933: substr($data,$$scantron_config{'LastName'}-1,
5934: $$scantron_config{'LastNamelength'});
5935: if ($just_header) { return \%record; }
5936:
5937: my @alphabet=('A'..'Z');
5938: my $questnum=0;
5939: my $ansnum =1; # Multiple 'answer lines'/question.
5940:
5941: chomp($questions); # Get rid of any trailing \n.
5942: $questions =~ s/\r$//; # Get rid of trailing \r too (MAC or Win uploads).
5943: while (length($questions)) {
5944: my $answers_needed = $bubble_lines_per_response{$questnum};
5945: my $answer_length = ($$scantron_config{'Qlength'} * $answers_needed)
5946: || 1;
5947: $questnum++;
5948: my $quest_id = $questnum;
5949: my $currentquest = substr($questions,0,$answer_length);
5950: $questions = substr($questions,$answer_length);
5951: if (length($currentquest) < $answer_length) { next; }
5952:
5953: if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
5954: my $subquestnum = 1;
5955: my $subquestions = $currentquest;
5956: my @subanswers_needed =
5957: split(/,/,$subdivided_bubble_lines{$questnum-1});
5958: foreach my $subans (@subanswers_needed) {
5959: my $subans_length =
5960: ($$scantron_config{'Qlength'} * $subans) || 1;
5961: my $currsubquest = substr($subquestions,0,$subans_length);
5962: $subquestions = substr($subquestions,$subans_length);
5963: $quest_id = "$questnum.$subquestnum";
5964: if (($$scantron_config{'Qon'} eq 'letter') ||
5965: ($$scantron_config{'Qon'} eq 'number')) {
5966: $ansnum = &scantron_validator_lettnum($ansnum,
5967: $questnum,$quest_id,$subans,$currsubquest,$whichline,
5968: \@alphabet,\%record,$scantron_config,$scan_data);
5969: } else {
5970: $ansnum = &scantron_validator_positional($ansnum,
5971: $questnum,$quest_id,$subans,$currsubquest,$whichline, \@alphabet,\%record,$scantron_config,$scan_data);
5972: }
5973: $subquestnum ++;
5974: }
5975: } else {
5976: if (($$scantron_config{'Qon'} eq 'letter') ||
5977: ($$scantron_config{'Qon'} eq 'number')) {
5978: $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
5979: $quest_id,$answers_needed,$currentquest,$whichline,
5980: \@alphabet,\%record,$scantron_config,$scan_data);
5981: } else {
5982: $ansnum = &scantron_validator_positional($ansnum,$questnum,
5983: $quest_id,$answers_needed,$currentquest,$whichline,
5984: \@alphabet,\%record,$scantron_config,$scan_data);
5985: }
5986: }
5987: }
5988: $record{'scantron.maxquest'}=$questnum;
5989: return \%record;
5990: }
5991:
5992: sub scantron_validator_lettnum {
5993: my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
5994: $alphabet,$record,$scantron_config,$scan_data) = @_;
5995:
5996: # Qon 'letter' implies for each slot in currquest we have:
5997: # ? or * for doubles, a letter in A-Z for a bubble, and
5998: # about anything else (esp. a value of Qoff) for missing
5999: # bubbles.
6000: #
6001: # Qon 'number' implies each slot gives a digit that indexes the
6002: # bubbles filled, or Qoff, or a non-number for unbubbled lines,
6003: # and * or ? for double bubbles on a single line.
6004: #
6005:
6006: my $matchon;
6007: if ($$scantron_config{'Qon'} eq 'letter') {
6008: $matchon = '[A-Z]';
6009: } elsif ($$scantron_config{'Qon'} eq 'number') {
6010: $matchon = '\d';
6011: }
6012: my $occurrences = 0;
6013: if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
6014: ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
6015: ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
6016: ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
6017: ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
6018: ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
6019: my @singlelines = split('',$currquest);
6020: foreach my $entry (@singlelines) {
6021: $occurrences = &occurence_count($entry,$matchon);
6022: if ($occurrences > 1) {
6023: last;
6024: }
6025: }
6026: } else {
6027: $occurrences = &occurence_count($currquest,$matchon);
6028: }
6029: if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
6030: push(@{$record->{'scantron.doubleerror'}},$quest_id);
6031: for (my $ans=0; $ans<$answers_needed; $ans++) {
6032: my $bubble = substr($currquest,$ans,1);
6033: if ($bubble =~ /$matchon/ ) {
6034: if ($$scantron_config{'Qon'} eq 'number') {
6035: if ($bubble == 0) {
6036: $bubble = 10;
6037: }
6038: $record->{"scantron.$ansnum.answer"} =
6039: $alphabet->[$bubble-1];
6040: } else {
6041: $record->{"scantron.$ansnum.answer"} = $bubble;
6042: }
6043: } else {
6044: $record->{"scantron.$ansnum.answer"}='';
6045: }
6046: $ansnum++;
6047: }
6048: } elsif (!defined($currquest)
6049: || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
6050: || (&occurence_count($currquest,$matchon) == 0)) {
6051: for (my $ans=0; $ans<$answers_needed; $ans++ ) {
6052: $record->{"scantron.$ansnum.answer"}='';
6053: $ansnum++;
6054: }
6055: if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
6056: push(@{$record->{'scantron.missingerror'}},$quest_id);
6057: }
6058: } else {
6059: if ($$scantron_config{'Qon'} eq 'number') {
6060: $currquest = &digits_to_letters($currquest);
6061: }
6062: for (my $ans=0; $ans<$answers_needed; $ans++) {
6063: my $bubble = substr($currquest,$ans,1);
6064: $record->{"scantron.$ansnum.answer"} = $bubble;
6065: $ansnum++;
6066: }
6067: }
6068: return $ansnum;
6069: }
6070:
6071: sub scantron_validator_positional {
6072: my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
6073: $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
6074:
6075: # Otherwise there's a positional notation;
6076: # each bubble line requires Qlength items, and there are filled in
6077: # bubbles for each case where there 'Qon' characters.
6078: #
6079:
6080: my @array=split($$scantron_config{'Qon'},$currquest,-1);
6081:
6082: # If the split only gives us one element.. the full length of the
6083: # answer string, no bubbles are filled in:
6084:
6085: if ($answers_needed eq '') {
6086: return;
6087: }
6088:
6089: if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
6090: for (my $ans=0; $ans<$answers_needed; $ans++ ) {
6091: $record->{"scantron.$ansnum.answer"}='';
6092: $ansnum++;
6093: }
6094: if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
6095: push(@{$record->{"scantron.missingerror"}},$quest_id);
6096: }
6097: } elsif (scalar(@array) == 2) {
6098: my $location = length($array[0]);
6099: my $line_num = int($location / $$scantron_config{'Qlength'});
6100: my $bubble = $alphabet->[$location % $$scantron_config{'Qlength'}];
6101: for (my $ans=0; $ans<$answers_needed; $ans++) {
6102: if ($ans eq $line_num) {
6103: $record->{"scantron.$ansnum.answer"} = $bubble;
6104: } else {
6105: $record->{"scantron.$ansnum.answer"} = ' ';
6106: }
6107: $ansnum++;
6108: }
6109: } else {
6110: # If there's more than one instance of a bubble character
6111: # That's a double bubble; with positional notation we can
6112: # record all the bubbles filled in as well as the
6113: # fact this response consists of multiple bubbles.
6114: #
6115: if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
6116: ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
6117: ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
6118: ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
6119: ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
6120: ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
6121: my $doubleerror = 0;
6122: while (($currquest >= $$scantron_config{'Qlength'}) &&
6123: (!$doubleerror)) {
6124: my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
6125: $currquest = substr($currquest,$$scantron_config{'Qlength'});
6126: my @currarray = split($$scantron_config{'Qon'},$currline,-1);
6127: if (length(@currarray) > 2) {
6128: $doubleerror = 1;
6129: }
6130: }
6131: if ($doubleerror) {
6132: push(@{$record->{'scantron.doubleerror'}},$quest_id);
6133: }
6134: } else {
6135: push(@{$record->{'scantron.doubleerror'}},$quest_id);
6136: }
6137: my $item = $ansnum;
6138: for (my $ans=0; $ans<$answers_needed; $ans++) {
6139: $record->{"scantron.$item.answer"} = '';
6140: $item ++;
6141: }
6142:
6143: my @ans=@array;
6144: my $i=0;
6145: my $increment = 0;
6146: while ($#ans) {
6147: $i+=length($ans[0]) + $increment;
6148: my $line = int($i/$$scantron_config{'Qlength'} + $ansnum);
6149: my $bubble = $i%$$scantron_config{'Qlength'};
6150: $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
6151: shift(@ans);
6152: $increment = 1;
6153: }
6154: $ansnum += $answers_needed;
6155: }
6156: return $ansnum;
6157: }
6158:
6159: =pod
6160:
6161: =item scantron_add_delay
6162:
6163: Adds an error message that occurred during the grading phase to a
6164: queue of messages to be shown after grading pass is complete
6165:
6166: Arguments:
6167: $delayqueue - arrary ref of hash ref of error messages
6168: $scanline - the scanline that caused the error
6169: $errormesage - the error message
6170: $errorcode - a numeric code for the error
6171:
6172: Side Effects:
6173: updates the $delayqueue to have a new hash ref of the error
6174:
6175: =cut
6176:
6177: sub scantron_add_delay {
6178: my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
6179: push(@$delayqueue,
6180: {'line' => $scanline, 'emsg' => $errormessage,
6181: 'ecode' => $errorcode }
6182: );
6183: }
6184:
6185: =pod
6186:
6187: =item scantron_find_student
6188:
6189: Finds the username for the current scanline
6190:
6191: Arguments:
6192: $scantron_record - hash result from scantron_parse_scanline
6193: $scan_data - hash of correction information
6194: (see &scantron_getfile() form more information)
6195: $idmap - hash from &username_to_idmap()
6196: $line - number of current scanline
6197:
6198: Returns:
6199: Either 'username:domain' or undef if unknown
6200:
6201: =cut
6202:
6203: sub scantron_find_student {
6204: my ($scantron_record,$scan_data,$idmap,$line)=@_;
6205: my $scanID=$$scantron_record{'scantron.ID'};
6206: if ($scanID =~ /^\s*$/) {
6207: return &scan_data($scan_data,"$line.user");
6208: }
6209: foreach my $id (keys(%$idmap)) {
6210: if (lc($id) eq lc($scanID)) {
6211: return $$idmap{$id};
6212: }
6213: }
6214: return undef;
6215: }
6216:
6217: =pod
6218:
6219: =item scantron_filter
6220:
6221: Filter sub for lonnavmaps, filters out hidden resources if ignore
6222: hidden resources was selected
6223:
6224: =cut
6225:
6226: sub scantron_filter {
6227: my ($curres)=@_;
6228:
6229: if (ref($curres) && $curres->is_problem()) {
6230: # if the user has asked to not have either hidden
6231: # or 'randomout' controlled resources to be graded
6232: # don't include them
6233: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
6234: && $curres->randomout) {
6235: return 0;
6236: }
6237: return 1;
6238: }
6239: return 0;
6240: }
6241:
6242: =pod
6243:
6244: =item scantron_process_corrections
6245:
6246: Gets correction information out of submitted form data and corrects
6247: the scanline
6248:
6249: =cut
6250:
6251: sub scantron_process_corrections {
6252: my ($r) = @_;
6253: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6254: my ($scanlines,$scan_data)=&scantron_getfile();
6255: my $classlist=&Apache::loncoursedata::get_classlist();
6256: my $which=$env{'form.scantron_line'};
6257: my $line=&scantron_get_line($scanlines,$scan_data,$which);
6258: my ($skip,$err,$errmsg);
6259: if ($env{'form.scantron_skip_record'}) {
6260: $skip=1;
6261: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
6262: my $newstudent=$env{'form.scantron_username'}.':'.
6263: $env{'form.scantron_domain'};
6264: my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
6265: ($line,$err,$errmsg)=
6266: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
6267: 'ID',{'newid'=>$newid,
6268: 'username'=>$env{'form.scantron_username'},
6269: 'domain'=>$env{'form.scantron_domain'}});
6270: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
6271: my $resolution=$env{'form.scantron_CODE_resolution'};
6272: my $newCODE;
6273: my %args;
6274: if ($resolution eq 'use_unfound') {
6275: $newCODE='use_unfound';
6276: } elsif ($resolution eq 'use_found') {
6277: $newCODE=$env{'form.scantron_CODE_selectedvalue'};
6278: } elsif ($resolution eq 'use_typed') {
6279: $newCODE=$env{'form.scantron_CODE_newvalue'};
6280: } elsif ($resolution =~ /^use_closest_(\d+)/) {
6281: $newCODE=$env{"form.scantron_CODE_closest_$1"};
6282: }
6283: if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
6284: $args{'CODE_ignore_dup'}=1;
6285: }
6286: $args{'CODE'}=$newCODE;
6287: ($line,$err,$errmsg)=
6288: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
6289: 'CODE',\%args);
6290: } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
6291: foreach my $question (split(',',$env{'form.scantron_questions'})) {
6292: ($line,$err,$errmsg)=
6293: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
6294: $which,'answer',
6295: { 'question'=>$question,
6296: 'response'=>$env{"form.scantron_correct_Q_$question"},
6297: 'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
6298: if ($err) { last; }
6299: }
6300: }
6301: if ($err) {
6302: $r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
6303: } else {
6304: &scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
6305: &scantron_putfile($scanlines,$scan_data);
6306: }
6307: }
6308:
6309: =pod
6310:
6311: =item reset_skipping_status
6312:
6313: Forgets the current set of remember skipped scanlines (and thus
6314: reverts back to considering all lines in the
6315: scantron_skipped_<filename> file)
6316:
6317: =cut
6318:
6319: sub reset_skipping_status {
6320: my ($scanlines,$scan_data)=&scantron_getfile();
6321: &scan_data($scan_data,'remember_skipping',undef,1);
6322: &scantron_putfile(undef,$scan_data);
6323: }
6324:
6325: =pod
6326:
6327: =item start_skipping
6328:
6329: Marks a scanline to be skipped.
6330:
6331: =cut
6332:
6333: sub start_skipping {
6334: my ($scan_data,$i)=@_;
6335: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
6336: if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
6337: $remembered{$i}=2;
6338: } else {
6339: $remembered{$i}=1;
6340: }
6341: &scan_data($scan_data,'remember_skipping',join(':',%remembered));
6342: }
6343:
6344: =pod
6345:
6346: =item should_be_skipped
6347:
6348: Checks whether a scanline should be skipped.
6349:
6350: =cut
6351:
6352: sub should_be_skipped {
6353: my ($scanlines,$scan_data,$i)=@_;
6354: if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
6355: # not redoing old skips
6356: if ($scanlines->{'skipped'}[$i]) { return 1; }
6357: return 0;
6358: }
6359: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
6360:
6361: if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
6362: return 0;
6363: }
6364: return 1;
6365: }
6366:
6367: =pod
6368:
6369: =item remember_current_skipped
6370:
6371: Discovers what scanlines are in the scantron_skipped_<filename>
6372: file and remembers them into scan_data for later use.
6373:
6374: =cut
6375:
6376: sub remember_current_skipped {
6377: my ($scanlines,$scan_data)=&scantron_getfile();
6378: my %to_remember;
6379: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6380: if ($scanlines->{'skipped'}[$i]) {
6381: $to_remember{$i}=1;
6382: }
6383: }
6384:
6385: &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
6386: &scantron_putfile(undef,$scan_data);
6387: }
6388:
6389: =pod
6390:
6391: =item check_for_error
6392:
6393: Checks if there was an error when attempting to remove a specific
6394: scantron_.. bubblesheet data file. Prints out an error if
6395: something went wrong.
6396:
6397: =cut
6398:
6399: sub check_for_error {
6400: my ($r,$result)=@_;
6401: if ($result ne 'ok' && $result ne 'not_found' ) {
6402: $r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
6403: }
6404: }
6405:
6406: =pod
6407:
6408: =item scantron_warning_screen
6409:
6410: Interstitial screen to make sure the operator has selected the
6411: correct options before we start the validation phase.
6412:
6413: =cut
6414:
6415: sub scantron_warning_screen {
6416: my ($button_text,$symb)=@_;
6417: my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
6418: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6419: my $CODElist;
6420: if ($scantron_config{'CODElocation'} &&
6421: $scantron_config{'CODEstart'} &&
6422: $scantron_config{'CODElength'}) {
6423: $CODElist=$env{'form.scantron_CODElist'};
6424: if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
6425: $CODElist=
6426: '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
6427: $env{'form.scantron_CODElist'}.'</tt></td></tr>';
6428: }
6429: my $lastbubblepoints;
6430: if ($env{'form.scantron_lastbubblepoints'} ne '') {
6431: $lastbubblepoints =
6432: '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
6433: $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
6434: }
6435: return ('
6436: <p>
6437: <span class="LC_warning">
6438: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
6439: </p>
6440: <table>
6441: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
6442: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
6443: '.$CODElist.$lastbubblepoints.'
6444: </table>
6445: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'<br />
6446: '.&mt('If something is incorrect, please return to [_1]Grade/Manage/Review Bubblesheets[_2] to start over.','<a href="/adm/grades?symb='.$symb.'&command=scantron_selectphase" class="LC_info">','</a>').'</p>
6447:
6448: <br />
6449: ');
6450: }
6451:
6452: =pod
6453:
6454: =item scantron_do_warning
6455:
6456: Check if the operator has picked something for all required
6457: fields. Error out if something is missing.
6458:
6459: =cut
6460:
6461: sub scantron_do_warning {
6462: my ($r,$symb)=@_;
6463: if (!$symb) {return '';}
6464: my $default_form_data=&defaultFormData($symb);
6465: $r->print(&scantron_form_start().$default_form_data);
6466: if ( $env{'form.selectpage'} eq '' ||
6467: $env{'form.scantron_selectfile'} eq '' ||
6468: $env{'form.scantron_format'} eq '' ) {
6469: $r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
6470: if ( $env{'form.selectpage'} eq '') {
6471: $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
6472: }
6473: if ( $env{'form.scantron_selectfile'} eq '') {
6474: $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
6475: }
6476: if ( $env{'form.scantron_format'} eq '') {
6477: $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
6478: }
6479: } else {
6480: my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
6481: my $bubbledbyhand=&hand_bubble_option();
6482: $r->print('
6483: '.$warning.$bubbledbyhand.'
6484: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
6485: <input type="hidden" name="command" value="scantron_validate" />
6486: ');
6487: }
6488: $r->print("</form><br />");
6489: return '';
6490: }
6491:
6492: =pod
6493:
6494: =item scantron_form_start
6495:
6496: html hidden input for remembering all selected grading options
6497:
6498: =cut
6499:
6500: sub scantron_form_start {
6501: my ($max_bubble)=@_;
6502: my $result= <<SCANTRONFORM;
6503: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
6504: <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
6505: <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
6506: <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
6507: <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
6508: <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
6509: <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
6510: <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
6511: <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
6512: <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
6513: SCANTRONFORM
6514:
6515: my $line = 0;
6516: while (defined($env{"form.scantron.bubblelines.$line"})) {
6517: my $chunk =
6518: '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
6519: $chunk .=
6520: '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
6521: $chunk .=
6522: '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
6523: $chunk .=
6524: '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
6525: $result .= $chunk;
6526: $line++;
6527: }
6528: return $result;
6529: }
6530:
6531: =pod
6532:
6533: =item scantron_validate_file
6534:
6535: Dispatch routine for doing validation of a bubblesheet data file.
6536:
6537: Also processes any necessary information resets that need to
6538: occur before validation begins (ignore previous corrections,
6539: restarting the skipped records processing)
6540:
6541: =cut
6542:
6543: sub scantron_validate_file {
6544: my ($r,$symb) = @_;
6545: if (!$symb) {return '';}
6546: my $default_form_data=&defaultFormData($symb);
6547:
6548: # do the detection of only doing skipped records first befroe we delete
6549: # them when doing the corrections reset
6550: if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
6551: &reset_skipping_status();
6552: }
6553: if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
6554: &remember_current_skipped();
6555: $env{'form.scantron_options_redo'}='redo_skipped_ready';
6556: }
6557:
6558: if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
6559: &check_for_error($r,&scantron_remove_file('corrected'));
6560: &check_for_error($r,&scantron_remove_file('skipped'));
6561: &check_for_error($r,&scantron_remove_scan_data());
6562: $env{'form.scantron_options_ignore'}='done';
6563: }
6564:
6565: if ($env{'form.scantron_corrections'}) {
6566: &scantron_process_corrections($r);
6567: }
6568: $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
6569: #get the student pick code ready
6570: $r->print(&Apache::loncommon::studentbrowser_javascript());
6571: my $nav_error;
6572: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6573: my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
6574: if ($nav_error) {
6575: $r->print(&navmap_errormsg());
6576: return '';
6577: }
6578: my $result=&scantron_form_start($max_bubble).$default_form_data;
6579: if ($env{'form.scantron_lastbubblepoints'} ne '') {
6580: $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
6581: }
6582: $r->print($result);
6583:
6584: my @validate_phases=( 'sequence',
6585: 'ID',
6586: 'CODE',
6587: 'doublebubble',
6588: 'missingbubbles');
6589: if (!$env{'form.validatepass'}) {
6590: $env{'form.validatepass'} = 0;
6591: }
6592: my $currentphase=$env{'form.validatepass'};
6593:
6594:
6595: my $stop=0;
6596: while (!$stop && $currentphase < scalar(@validate_phases)) {
6597: $r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
6598: $r->rflush();
6599: my $which="scantron_validate_".$validate_phases[$currentphase];
6600: {
6601: no strict 'refs';
6602: ($stop,$currentphase)=&$which($r,$currentphase);
6603: }
6604: }
6605: if (!$stop) {
6606: my $warning=&scantron_warning_screen('Start Grading',$symb);
6607: $r->print(&mt('Validation process complete.').'<br />'.
6608: $warning.
6609: &mt('Perform verification for each student after storage of submissions?').
6610: ' <span class="LC_nobreak"><label>'.
6611: '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
6612: (' 'x3).'<label>'.
6613: '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
6614: '</label></span><br />'.
6615: &mt('Grading will take longer if you use verification.').'<br />'.
6616: &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','»').'<br /><br />'.
6617: '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
6618: '<input type="hidden" name="command" value="scantron_process" />'."\n");
6619: } else {
6620: $r->print('<input type="hidden" name="command" value="scantron_validate" />');
6621: $r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
6622: }
6623: if ($stop) {
6624: if ($validate_phases[$currentphase] eq 'sequence') {
6625: $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' → " />');
6626: $r->print(' '.&mt('this error').' <br />');
6627:
6628: $r->print('<p>'.&mt('Or return to [_1]Grade/Manage/Review Bubblesheets[_2] to start over.','<a href="/adm/grades?symb='.$symb.'&command=scantron_selectphase" class="LC_info">','</a>').'</p>');
6629: } else {
6630: if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
6631: $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' →" onclick="javascript:verify_bubble_radio(this.form)" />');
6632: } else {
6633: $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' →" />');
6634: }
6635: $r->print(' '.&mt('using corrected info').' <br />');
6636: $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
6637: $r->print(" ".&mt("this scanline saving it for later."));
6638: }
6639: }
6640: $r->print(" </form><br />");
6641: return '';
6642: }
6643:
6644:
6645: =pod
6646:
6647: =item scantron_remove_file
6648:
6649: Removes the requested bubblesheet data file, makes sure that
6650: scantron_original_<filename> is never removed
6651:
6652:
6653: =cut
6654:
6655: sub scantron_remove_file {
6656: my ($which)=@_;
6657: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6658: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6659: my $file='scantron_';
6660: if ($which eq 'corrected' || $which eq 'skipped') {
6661: $file.=$which.'_';
6662: } else {
6663: return 'refused';
6664: }
6665: $file.=$env{'form.scantron_selectfile'};
6666: return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
6667: }
6668:
6669:
6670: =pod
6671:
6672: =item scantron_remove_scan_data
6673:
6674: Removes all scan_data correction for the requested bubblesheet
6675: data file. (In the case that both the are doing skipped records we need
6676: to remember the old skipped lines for the time being so that element
6677: persists for a while.)
6678:
6679: =cut
6680:
6681: sub scantron_remove_scan_data {
6682: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6683: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6684: my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
6685: my @todelete;
6686: my $filename=$env{'form.scantron_selectfile'};
6687: foreach my $key (@keys) {
6688: if ($key=~/^\Q$filename\E_/) {
6689: if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
6690: $key=~/remember_skipping/) {
6691: next;
6692: }
6693: push(@todelete,$key);
6694: }
6695: }
6696: my $result;
6697: if (@todelete) {
6698: $result = &Apache::lonnet::del('nohist_scantrondata',
6699: \@todelete,$cdom,$cname);
6700: } else {
6701: $result = 'ok';
6702: }
6703: return $result;
6704: }
6705:
6706:
6707: =pod
6708:
6709: =item scantron_getfile
6710:
6711: Fetches the requested bubblesheet data file (all 3 versions), and
6712: the scan_data hash
6713:
6714: Arguments:
6715: None
6716:
6717: Returns:
6718: 2 hash references
6719:
6720: - first one has
6721: orig -
6722: corrected -
6723: skipped - each of which points to an array ref of the specified
6724: file broken up into individual lines
6725: count - number of scanlines
6726:
6727: - second is the scan_data hash possible keys are
6728: ($number refers to scanline numbered $number and thus the key affects
6729: only that scanline
6730: $bubline refers to the specific bubble line element and the aspects
6731: refers to that specific bubble line element)
6732:
6733: $number.user - username:domain to use
6734: $number.CODE_ignore_dup
6735: - ignore the duplicate CODE error
6736: $number.useCODE
6737: - use the CODE in the scanline as is
6738: $number.no_bubble.$bubline
6739: - it is valid that there is no bubbled in bubble
6740: at $number $bubline
6741: remember_skipping
6742: - a frozen hash containing keys of $number and values
6743: of either
6744: 1 - we are on a 'do skipped records pass' and plan
6745: on processing this line
6746: 2 - we are on a 'do skipped records pass' and this
6747: scanline has been marked to skip yet again
6748:
6749: =cut
6750:
6751: sub scantron_getfile {
6752: #FIXME really would prefer a scantron directory
6753: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6754: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6755: my $lines;
6756: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
6757: 'scantron_orig_'.$env{'form.scantron_selectfile'});
6758: my %scanlines;
6759: $scanlines{'orig'}=[(split("\n",$lines,-1))];
6760: my $temp=$scanlines{'orig'};
6761: $scanlines{'count'}=$#$temp;
6762:
6763: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
6764: 'scantron_corrected_'.$env{'form.scantron_selectfile'});
6765: if ($lines eq '-1') {
6766: $scanlines{'corrected'}=[];
6767: } else {
6768: $scanlines{'corrected'}=[(split("\n",$lines,-1))];
6769: }
6770: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
6771: 'scantron_skipped_'.$env{'form.scantron_selectfile'});
6772: if ($lines eq '-1') {
6773: $scanlines{'skipped'}=[];
6774: } else {
6775: $scanlines{'skipped'}=[(split("\n",$lines,-1))];
6776: }
6777: my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
6778: if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
6779: my %scan_data = @tmp;
6780: return (\%scanlines,\%scan_data);
6781: }
6782:
6783: =pod
6784:
6785: =item lonnet_putfile
6786:
6787: Wrapper routine to call &Apache::lonnet::finishuserfileupload
6788:
6789: Arguments:
6790: $contents - data to store
6791: $filename - filename to store $contents into
6792:
6793: Returns:
6794: result value from &Apache::lonnet::finishuserfileupload
6795:
6796: =cut
6797:
6798: sub lonnet_putfile {
6799: my ($contents,$filename)=@_;
6800: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
6801: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6802: $env{'form.sillywaytopassafilearound'}=$contents;
6803: &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
6804:
6805: }
6806:
6807: =pod
6808:
6809: =item scantron_putfile
6810:
6811: Stores the current version of the bubblesheet data files, and the
6812: scan_data hash. (Does not modify the original version only the
6813: corrected and skipped versions.
6814:
6815: Arguments:
6816: $scanlines - hash ref that looks like the first return value from
6817: &scantron_getfile()
6818: $scan_data - hash ref that looks like the second return value from
6819: &scantron_getfile()
6820:
6821: =cut
6822:
6823: sub scantron_putfile {
6824: my ($scanlines,$scan_data) = @_;
6825: #FIXME really would prefer a scantron directory
6826: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6827: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6828: if ($scanlines) {
6829: my $prefix='scantron_';
6830: # no need to update orig, shouldn't change
6831: # &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
6832: # $env{'form.scantron_selectfile'});
6833: &lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
6834: $prefix.'corrected_'.
6835: $env{'form.scantron_selectfile'});
6836: &lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
6837: $prefix.'skipped_'.
6838: $env{'form.scantron_selectfile'});
6839: }
6840: &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
6841: }
6842:
6843: =pod
6844:
6845: =item scantron_get_line
6846:
6847: Returns the correct version of the scanline
6848:
6849: Arguments:
6850: $scanlines - hash ref that looks like the first return value from
6851: &scantron_getfile()
6852: $scan_data - hash ref that looks like the second return value from
6853: &scantron_getfile()
6854: $i - number of the requested line (starts at 0)
6855:
6856: Returns:
6857: A scanline, (either the original or the corrected one if it
6858: exists), or undef if the requested scanline should be
6859: skipped. (Either because it's an skipped scanline, or it's an
6860: unskipped scanline and we are not doing a 'do skipped scanlines'
6861: pass.
6862:
6863: =cut
6864:
6865: sub scantron_get_line {
6866: my ($scanlines,$scan_data,$i)=@_;
6867: if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
6868: #if ($scanlines->{'skipped'}[$i]) { return undef; }
6869: if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
6870: return $scanlines->{'orig'}[$i];
6871: }
6872:
6873: =pod
6874:
6875: =item scantron_todo_count
6876:
6877: Counts the number of scanlines that need processing.
6878:
6879: Arguments:
6880: $scanlines - hash ref that looks like the first return value from
6881: &scantron_getfile()
6882: $scan_data - hash ref that looks like the second return value from
6883: &scantron_getfile()
6884:
6885: Returns:
6886: $count - number of scanlines to process
6887:
6888: =cut
6889:
6890: sub get_todo_count {
6891: my ($scanlines,$scan_data)=@_;
6892: my $count=0;
6893: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6894: my $line=&scantron_get_line($scanlines,$scan_data,$i);
6895: if ($line=~/^[\s\cz]*$/) { next; }
6896: $count++;
6897: }
6898: return $count;
6899: }
6900:
6901: =pod
6902:
6903: =item scantron_put_line
6904:
6905: Updates the 'corrected' or 'skipped' versions of the bubblesheet
6906: data file.
6907:
6908: Arguments:
6909: $scanlines - hash ref that looks like the first return value from
6910: &scantron_getfile()
6911: $scan_data - hash ref that looks like the second return value from
6912: &scantron_getfile()
6913: $i - line number to update
6914: $newline - contents of the updated scanline
6915: $skip - if true make the line for skipping and update the
6916: 'skipped' file
6917:
6918: =cut
6919:
6920: sub scantron_put_line {
6921: my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
6922: if ($skip) {
6923: $scanlines->{'skipped'}[$i]=$newline;
6924: &start_skipping($scan_data,$i);
6925: return;
6926: }
6927: $scanlines->{'corrected'}[$i]=$newline;
6928: }
6929:
6930: =pod
6931:
6932: =item scantron_clear_skip
6933:
6934: Remove a line from the 'skipped' file
6935:
6936: Arguments:
6937: $scanlines - hash ref that looks like the first return value from
6938: &scantron_getfile()
6939: $scan_data - hash ref that looks like the second return value from
6940: &scantron_getfile()
6941: $i - line number to update
6942:
6943: =cut
6944:
6945: sub scantron_clear_skip {
6946: my ($scanlines,$scan_data,$i)=@_;
6947: if (exists($scanlines->{'skipped'}[$i])) {
6948: undef($scanlines->{'skipped'}[$i]);
6949: return 1;
6950: }
6951: return 0;
6952: }
6953:
6954: =pod
6955:
6956: =item scantron_filter_not_exam
6957:
6958: Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
6959: filter out resources that are not marked as 'exam' mode
6960:
6961: =cut
6962:
6963: sub scantron_filter_not_exam {
6964: my ($curres)=@_;
6965:
6966: if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
6967: # if the user has asked to not have either hidden
6968: # or 'randomout' controlled resources to be graded
6969: # don't include them
6970: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
6971: && $curres->randomout) {
6972: return 0;
6973: }
6974: return 1;
6975: }
6976: return 0;
6977: }
6978:
6979: =pod
6980:
6981: =item scantron_validate_sequence
6982:
6983: Validates the selected sequence, checking for resource that are
6984: not set to exam mode.
6985:
6986: =cut
6987:
6988: sub scantron_validate_sequence {
6989: my ($r,$currentphase) = @_;
6990:
6991: my $navmap=Apache::lonnavmaps::navmap->new();
6992: unless (ref($navmap)) {
6993: $r->print(&navmap_errormsg());
6994: return (1,$currentphase);
6995: }
6996: my (undef,undef,$sequence)=
6997: &Apache::lonnet::decode_symb($env{'form.selectpage'});
6998:
6999: my $map=$navmap->getResourceByUrl($sequence);
7000:
7001: $r->print('<input type="hidden" name="validate_sequence_exam"
7002: value="ignore" />');
7003: if ($env{'form.validate_sequence_exam'} ne 'ignore') {
7004: my @resources=
7005: $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
7006: if (@resources) {
7007: $r->print(
7008: '<p class="LC_warning">'
7009: .&mt('Some resources in the sequence currently are not set to'
7010: .' exam mode. Grading these resources currently may not'
7011: .' work correctly.')
7012: .'</p>'
7013: );
7014: return (1,$currentphase);
7015: }
7016: }
7017:
7018: return (0,$currentphase+1);
7019: }
7020:
7021:
7022:
7023: sub scantron_validate_ID {
7024: my ($r,$currentphase) = @_;
7025:
7026: #get student info
7027: my $classlist=&Apache::loncoursedata::get_classlist();
7028: my %idmap=&username_to_idmap($classlist);
7029:
7030: #get scantron line setup
7031: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7032: my ($scanlines,$scan_data)=&scantron_getfile();
7033:
7034: my $nav_error;
7035: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
7036: if ($nav_error) {
7037: $r->print(&navmap_errormsg());
7038: return(1,$currentphase);
7039: }
7040:
7041: my %found=('ids'=>{},'usernames'=>{});
7042: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7043: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7044: if ($line=~/^[\s\cz]*$/) { next; }
7045: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7046: $scan_data);
7047: my $id=$$scan_record{'scantron.ID'};
7048: my $found;
7049: foreach my $checkid (keys(%idmap)) {
7050: if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
7051: }
7052: if ($found) {
7053: my $username=$idmap{$found};
7054: if ($found{'ids'}{$found}) {
7055: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
7056: $line,'duplicateID',$found);
7057: return(1,$currentphase);
7058: } elsif ($found{'usernames'}{$username}) {
7059: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
7060: $line,'duplicateID',$username);
7061: return(1,$currentphase);
7062: }
7063: #FIXME store away line we previously saw the ID on to use above
7064: $found{'ids'}{$found}++;
7065: $found{'usernames'}{$username}++;
7066: } else {
7067: if ($id =~ /^\s*$/) {
7068: my $username=&scan_data($scan_data,"$i.user");
7069: if (defined($username) && $found{'usernames'}{$username}) {
7070: &scantron_get_correction($r,$i,$scan_record,
7071: \%scantron_config,
7072: $line,'duplicateID',$username);
7073: return(1,$currentphase);
7074: } elsif (!defined($username)) {
7075: &scantron_get_correction($r,$i,$scan_record,
7076: \%scantron_config,
7077: $line,'incorrectID');
7078: return(1,$currentphase);
7079: }
7080: $found{'usernames'}{$username}++;
7081: } else {
7082: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
7083: $line,'incorrectID');
7084: return(1,$currentphase);
7085: }
7086: }
7087: }
7088:
7089: return (0,$currentphase+1);
7090: }
7091:
7092:
7093: sub scantron_get_correction {
7094: my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
7095: #FIXME in the case of a duplicated ID the previous line, probably need
7096: #to show both the current line and the previous one and allow skipping
7097: #the previous one or the current one
7098:
7099: if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
7100: $r->print(
7101: '<p class="LC_warning">'
7102: .&mt('An error was detected ([_1]) for PaperID [_2]',
7103: "<b>$error</b>",
7104: '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
7105: ."</p> \n");
7106: } else {
7107: $r->print(
7108: '<p class="LC_warning">'
7109: .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
7110: "<b>$error</b>", $i, "<pre>$line</pre>")
7111: ."</p> \n");
7112: }
7113: my $message =
7114: '<p>'
7115: .&mt('The ID on the form is [_1]',
7116: "<tt>$$scan_record{'scantron.ID'}</tt>")
7117: .'<br />'
7118: .&mt('The name on the paper is [_1], [_2]',
7119: $$scan_record{'scantron.LastName'},
7120: $$scan_record{'scantron.FirstName'})
7121: .'</p>';
7122:
7123: $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
7124: $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
7125: # Array populated for doublebubble or
7126: my @lines_to_correct; # missingbubble errors to build javascript
7127: # to validate radio button checking
7128:
7129: if ($error =~ /ID$/) {
7130: if ($error eq 'incorrectID') {
7131: $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
7132: "</p>\n");
7133: } elsif ($error eq 'duplicateID') {
7134: $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
7135: }
7136: $r->print($message);
7137: $r->print("<p>".&mt("How should I handle this?")." <br /> \n");
7138: $r->print("\n<ul><li> ");
7139: #FIXME it would be nice if this sent back the user ID and
7140: #could do partial userID matches
7141: $r->print(&Apache::loncommon::selectstudent_link('scantronupload',
7142: 'scantron_username','scantron_domain'));
7143: $r->print(": <input type='text' name='scantron_username' value='' />");
7144: $r->print("\n@".
7145: &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
7146:
7147: $r->print('</li>');
7148: } elsif ($error =~ /CODE$/) {
7149: if ($error eq 'incorrectCODE') {
7150: $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
7151: } elsif ($error eq 'duplicateCODE') {
7152: $r->print('<p class="LC_warning">'.&mt("The encoded CODE has also been used by a previous paper [_1], and CODEs are supposed to be unique.",join(', ',@{$arg}))."</p>\n");
7153: }
7154: $r->print("<p>".&mt('The CODE on the form is [_1]',
7155: "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
7156: ."</p>\n");
7157: $r->print($message);
7158: $r->print("<p>".&mt("How should I handle this?")."</p>\n");
7159: $r->print("\n<br /> ");
7160: my $i=0;
7161: if ($error eq 'incorrectCODE'
7162: && $$scan_record{'scantron.CODE'}=~/\S/ ) {
7163: my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
7164: if ($closest > 0) {
7165: foreach my $testcode (@{$closest}) {
7166: my $checked='';
7167: if (!$i) { $checked=' checked="checked"'; }
7168: $r->print("
7169: <label>
7170: <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
7171: ".&mt("Use the similar CODE [_1] instead.",
7172: "<b><tt>".$testcode."</tt></b>")."
7173: </label>
7174: <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
7175: $r->print("\n<br />");
7176: $i++;
7177: }
7178: }
7179: }
7180: if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
7181: my $checked; if (!$i) { $checked=' checked="checked"'; }
7182: $r->print("
7183: <label>
7184: <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
7185: ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
7186: "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
7187: </label>");
7188: $r->print("\n<br />");
7189: }
7190:
7191: $r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
7192: function change_radio(field) {
7193: var slct=document.scantronupload.scantron_CODE_resolution;
7194: var i;
7195: for (i=0;i<slct.length;i++) {
7196: if (slct[i].value==field) { slct[i].checked=true; }
7197: }
7198: }
7199: ENDSCRIPT
7200: my $href="/adm/pickcode?".
7201: "form=".&escape("scantronupload").
7202: "&scantron_format=".&escape($env{'form.scantron_format'}).
7203: "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
7204: "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
7205: "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
7206: if ($env{'form.scantron_CODElist'} =~ /\S/) {
7207: $r->print("
7208: <label>
7209: <input type='radio' name='scantron_CODE_resolution' value='use_found' />
7210: ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
7211: "<a target='_blank' href='$href'>","</a>")."
7212: </label>
7213: ".&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\')" />'));
7214: $r->print("\n<br />");
7215: }
7216: $r->print("
7217: <label>
7218: <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
7219: ".&mt("Use [_1] as the CODE.",
7220: "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
7221: $r->print("\n<br /><br />");
7222: } elsif ($error eq 'doublebubble') {
7223: $r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
7224:
7225: # The form field scantron_questions is acutally a list of line numbers.
7226: # represented by this form so:
7227:
7228: my $line_list = &questions_to_line_list($arg);
7229:
7230: $r->print('<input type="hidden" name="scantron_questions" value="'.
7231: $line_list.'" />');
7232: $r->print($message);
7233: $r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
7234: foreach my $question (@{$arg}) {
7235: my @linenums = &prompt_for_corrections($r,$question,$scan_config,
7236: $scan_record, $error);
7237: push(@lines_to_correct,@linenums);
7238: }
7239: $r->print(&verify_bubbles_checked(@lines_to_correct));
7240: } elsif ($error eq 'missingbubble') {
7241: $r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
7242: $r->print($message);
7243: $r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
7244: $r->print(&mt("Some questions have no scanned bubbles.")."\n");
7245:
7246: # The form field scantron_questions is actually a list of line numbers not
7247: # a list of question numbers. Therefore:
7248: #
7249:
7250: my $line_list = &questions_to_line_list($arg);
7251:
7252: $r->print('<input type="hidden" name="scantron_questions" value="'.
7253: $line_list.'" />');
7254: foreach my $question (@{$arg}) {
7255: my @linenums = &prompt_for_corrections($r,$question,$scan_config,
7256: $scan_record, $error);
7257: push(@lines_to_correct,@linenums);
7258: }
7259: $r->print(&verify_bubbles_checked(@lines_to_correct));
7260: } else {
7261: $r->print("\n<ul>");
7262: }
7263: $r->print("\n</li></ul>");
7264: }
7265:
7266: sub verify_bubbles_checked {
7267: my (@ansnums) = @_;
7268: my $ansnumstr = join('","',@ansnums);
7269: my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
7270: my $output = &Apache::lonhtmlcommon::scripttag((<<ENDSCRIPT));
7271: function verify_bubble_radio(form) {
7272: var ansnumArray = new Array ("$ansnumstr");
7273: var need_bubble_count = 0;
7274: for (var i=0; i<ansnumArray.length; i++) {
7275: if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
7276: var bubble_picked = 0;
7277: for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
7278: if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
7279: bubble_picked = 1;
7280: }
7281: }
7282: if (bubble_picked == 0) {
7283: need_bubble_count ++;
7284: }
7285: }
7286: }
7287: if (need_bubble_count) {
7288: alert("$warning");
7289: return;
7290: }
7291: form.submit();
7292: }
7293: ENDSCRIPT
7294: return $output;
7295: }
7296:
7297: =pod
7298:
7299: =item questions_to_line_list
7300:
7301: Converts a list of questions into a string of comma separated
7302: line numbers in the answer sheet used by the questions. This is
7303: used to fill in the scantron_questions form field.
7304:
7305: Arguments:
7306: questions - Reference to an array of questions.
7307:
7308: =cut
7309:
7310:
7311: sub questions_to_line_list {
7312: my ($questions) = @_;
7313: my @lines;
7314:
7315: foreach my $item (@{$questions}) {
7316: my $question = $item;
7317: my ($first,$count,$last);
7318: if ($item =~ /^(\d+)\.(\d+)$/) {
7319: $question = $1;
7320: my $subquestion = $2;
7321: $first = $first_bubble_line{$question-1} + 1;
7322: my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
7323: my $subcount = 1;
7324: while ($subcount<$subquestion) {
7325: $first += $subans[$subcount-1];
7326: $subcount ++;
7327: }
7328: $count = $subans[$subquestion-1];
7329: } else {
7330: $first = $first_bubble_line{$question-1} + 1;
7331: $count = $bubble_lines_per_response{$question-1};
7332: }
7333: $last = $first+$count-1;
7334: push(@lines, ($first..$last));
7335: }
7336: return join(',', @lines);
7337: }
7338:
7339: =pod
7340:
7341: =item prompt_for_corrections
7342:
7343: Prompts for a potentially multiline correction to the
7344: user's bubbling (factors out common code from scantron_get_correction
7345: for multi and missing bubble cases).
7346:
7347: Arguments:
7348: $r - Apache request object.
7349: $question - The question number to prompt for.
7350: $scan_config - The scantron file configuration hash.
7351: $scan_record - Reference to the hash that has the the parsed scanlines.
7352: $error - Type of error
7353:
7354: Implicit inputs:
7355: %bubble_lines_per_response - Starting line numbers for each question.
7356: Numbered from 0 (but question numbers are from
7357: 1.
7358: %first_bubble_line - Starting bubble line for each question.
7359: %subdivided_bubble_lines - optionresponse, matchresponse and rankresponse
7360: type problems render as separate sub-questions,
7361: in exam mode. This hash contains a
7362: comma-separated list of the lines per
7363: sub-question.
7364: %responsetype_per_response - essayresponse, formularesponse,
7365: stringresponse, imageresponse, reactionresponse,
7366: and organicresponse type problem parts can have
7367: multiple lines per response if the weight
7368: assigned exceeds 10. In this case, only
7369: one bubble per line is permitted, but more
7370: than one line might contain bubbles, e.g.
7371: bubbling of: line 1 - J, line 2 - J,
7372: line 3 - B would assign 22 points.
7373:
7374: =cut
7375:
7376: sub prompt_for_corrections {
7377: my ($r, $question, $scan_config, $scan_record, $error) = @_;
7378: my ($current_line,$lines);
7379: my @linenums;
7380: my $questionnum = $question;
7381: if ($question =~ /^(\d+)\.(\d+)$/) {
7382: $question = $1;
7383: $current_line = $first_bubble_line{$question-1} + 1 ;
7384: my $subquestion = $2;
7385: my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
7386: my $subcount = 1;
7387: while ($subcount<$subquestion) {
7388: $current_line += $subans[$subcount-1];
7389: $subcount ++;
7390: }
7391: $lines = $subans[$subquestion-1];
7392: } else {
7393: $current_line = $first_bubble_line{$question-1} + 1 ;
7394: $lines = $bubble_lines_per_response{$question-1};
7395: }
7396: if ($lines > 1) {
7397: $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
7398: if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
7399: ($responsetype_per_response{$question-1} eq 'formularesponse') ||
7400: ($responsetype_per_response{$question-1} eq 'stringresponse') ||
7401: ($responsetype_per_response{$question-1} eq 'imageresponse') ||
7402: ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
7403: ($responsetype_per_response{$question-1} eq 'organicresponse')) {
7404: $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 />');
7405: } else {
7406: $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
7407: }
7408: }
7409: for (my $i =0; $i < $lines; $i++) {
7410: my $selected = $$scan_record{"scantron.$current_line.answer"};
7411: &scantron_bubble_selector($r,$scan_config,$current_line,
7412: $questionnum,$error,split('', $selected));
7413: push(@linenums,$current_line);
7414: $current_line++;
7415: }
7416: if ($lines > 1) {
7417: $r->print("<hr /><br />");
7418: }
7419: return @linenums;
7420: }
7421:
7422: =pod
7423:
7424: =item scantron_bubble_selector
7425:
7426: Generates the html radiobuttons to correct a single bubble line
7427: possibly showing the existing the selected bubbles if known
7428:
7429: Arguments:
7430: $r - Apache request object
7431: $scan_config - hash from &get_scantron_config()
7432: $line - Number of the line being displayed.
7433: $questionnum - Question number (may include subquestion)
7434: $error - Type of error.
7435: @selected - Array of bubbles picked on this line.
7436:
7437: =cut
7438:
7439: sub scantron_bubble_selector {
7440: my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
7441: my $max=$$scan_config{'Qlength'};
7442:
7443: my $scmode=$$scan_config{'Qon'};
7444: if ($scmode eq 'number' || $scmode eq 'letter') {
7445: if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
7446: ($$scan_config{'BubblesPerRow'} > 0)) {
7447: $max=$$scan_config{'BubblesPerRow'};
7448: if (($scmode eq 'number') && ($max > 10)) {
7449: $max = 10;
7450: } elsif (($scmode eq 'letter') && $max > 26) {
7451: $max = 26;
7452: }
7453: } else {
7454: $max = 10;
7455: }
7456: }
7457:
7458: my @alphabet=('A'..'Z');
7459: $r->print(&Apache::loncommon::start_data_table().
7460: &Apache::loncommon::start_data_table_row());
7461: $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
7462: for (my $i=0;$i<$max+1;$i++) {
7463: $r->print("\n".'<td align="center">');
7464: if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
7465: else { $r->print(' '); }
7466: $r->print('</td>');
7467: }
7468: $r->print(&Apache::loncommon::end_data_table_row().
7469: &Apache::loncommon::start_data_table_row());
7470: for (my $i=0;$i<$max;$i++) {
7471: $r->print("\n".
7472: '<td><label><input type="radio" name="scantron_correct_Q_'.
7473: $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
7474: }
7475: my $nobub_checked = ' ';
7476: if ($error eq 'missingbubble') {
7477: $nobub_checked = ' checked = "checked" ';
7478: }
7479: $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
7480: $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
7481: '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
7482: $line.'" value="'.$questionnum.'" /></td>');
7483: $r->print(&Apache::loncommon::end_data_table_row().
7484: &Apache::loncommon::end_data_table());
7485: }
7486:
7487: =pod
7488:
7489: =item num_matches
7490:
7491: Counts the number of characters that are the same between the two arguments.
7492:
7493: Arguments:
7494: $orig - CODE from the scanline
7495: $code - CODE to match against
7496:
7497: Returns:
7498: $count - integer count of the number of same characters between the
7499: two arguments
7500:
7501: =cut
7502:
7503: sub num_matches {
7504: my ($orig,$code) = @_;
7505: my @code=split(//,$code);
7506: my @orig=split(//,$orig);
7507: my $same=0;
7508: for (my $i=0;$i<scalar(@code);$i++) {
7509: if ($code[$i] eq $orig[$i]) { $same++; }
7510: }
7511: return $same;
7512: }
7513:
7514: =pod
7515:
7516: =item scantron_get_closely_matching_CODEs
7517:
7518: Cycles through all CODEs and finds the set that has the greatest
7519: number of same characters as the provided CODE
7520:
7521: Arguments:
7522: $allcodes - hash ref returned by &get_codes()
7523: $CODE - CODE from the current scanline
7524:
7525: Returns:
7526: 2 element list
7527: - first elements is number of how closely matching the best fit is
7528: (5 means best set has 5 matching characters)
7529: - second element is an arrary ref containing the set of valid CODEs
7530: that best fit the passed in CODE
7531:
7532: =cut
7533:
7534: sub scantron_get_closely_matching_CODEs {
7535: my ($allcodes,$CODE)=@_;
7536: my @CODEs;
7537: foreach my $testcode (sort(keys(%{$allcodes}))) {
7538: push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
7539: }
7540:
7541: return ($#CODEs,$CODEs[-1]);
7542: }
7543:
7544: =pod
7545:
7546: =item get_codes
7547:
7548: Builds a hash which has keys of all of the valid CODEs from the selected
7549: set of remembered CODEs.
7550:
7551: Arguments:
7552: $old_name - name of the set of remembered CODEs
7553: $cdom - domain of the course
7554: $cnum - internal course name
7555:
7556: Returns:
7557: %allcodes - keys are the valid CODEs, values are all 1
7558:
7559: =cut
7560:
7561: sub get_codes {
7562: my ($old_name, $cdom, $cnum) = @_;
7563: if (!$old_name) {
7564: $old_name=$env{'form.scantron_CODElist'};
7565: }
7566: if (!$cdom) {
7567: $cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
7568: }
7569: if (!$cnum) {
7570: $cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
7571: }
7572: my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
7573: $cdom,$cnum);
7574: my %allcodes;
7575: if ($result{"type\0$old_name"} eq 'number') {
7576: %allcodes=map {($_,1)} split(',',$result{$old_name});
7577: } else {
7578: %allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
7579: }
7580: return %allcodes;
7581: }
7582:
7583: =pod
7584:
7585: =item scantron_validate_CODE
7586:
7587: Validates all scanlines in the selected file to not have any
7588: invalid or underspecified CODEs and that none of the codes are
7589: duplicated if this was requested.
7590:
7591: =cut
7592:
7593: sub scantron_validate_CODE {
7594: my ($r,$currentphase) = @_;
7595: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7596: if ($scantron_config{'CODElocation'} &&
7597: $scantron_config{'CODEstart'} &&
7598: $scantron_config{'CODElength'}) {
7599: if (!defined($env{'form.scantron_CODElist'})) {
7600: &FIXME_blow_up()
7601: }
7602: } else {
7603: return (0,$currentphase+1);
7604: }
7605:
7606: my %usedCODEs;
7607:
7608: my %allcodes=&get_codes();
7609:
7610: my $nav_error;
7611: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
7612: if ($nav_error) {
7613: $r->print(&navmap_errormsg());
7614: return(1,$currentphase);
7615: }
7616:
7617: my ($scanlines,$scan_data)=&scantron_getfile();
7618: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7619: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7620: if ($line=~/^[\s\cz]*$/) { next; }
7621: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7622: $scan_data);
7623: my $CODE=$$scan_record{'scantron.CODE'};
7624: my $error=0;
7625: if (!&Apache::lonnet::validCODE($CODE)) {
7626: &scantron_get_correction($r,$i,$scan_record,
7627: \%scantron_config,
7628: $line,'incorrectCODE',\%allcodes);
7629: return(1,$currentphase);
7630: }
7631: if (%allcodes && !exists($allcodes{$CODE})
7632: && !$$scan_record{'scantron.useCODE'}) {
7633: &scantron_get_correction($r,$i,$scan_record,
7634: \%scantron_config,
7635: $line,'incorrectCODE',\%allcodes);
7636: return(1,$currentphase);
7637: }
7638: if (exists($usedCODEs{$CODE})
7639: && $env{'form.scantron_CODEunique'} eq 'yes'
7640: && !$$scan_record{'scantron.CODE_ignore_dup'}) {
7641: &scantron_get_correction($r,$i,$scan_record,
7642: \%scantron_config,
7643: $line,'duplicateCODE',$usedCODEs{$CODE});
7644: return(1,$currentphase);
7645: }
7646: push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
7647: }
7648: return (0,$currentphase+1);
7649: }
7650:
7651: =pod
7652:
7653: =item scantron_validate_doublebubble
7654:
7655: Validates all scanlines in the selected file to not have any
7656: bubble lines with multiple bubbles marked.
7657:
7658: =cut
7659:
7660: sub scantron_validate_doublebubble {
7661: my ($r,$currentphase) = @_;
7662: #get student info
7663: my $classlist=&Apache::loncoursedata::get_classlist();
7664: my %idmap=&username_to_idmap($classlist);
7665:
7666: #get scantron line setup
7667: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7668: my ($scanlines,$scan_data)=&scantron_getfile();
7669: my $nav_error;
7670: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
7671: if ($nav_error) {
7672: $r->print(&navmap_errormsg());
7673: return(1,$currentphase);
7674: }
7675:
7676: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7677: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7678: if ($line=~/^[\s\cz]*$/) { next; }
7679: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7680: $scan_data);
7681: if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
7682: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
7683: 'doublebubble',
7684: $$scan_record{'scantron.doubleerror'});
7685: return (1,$currentphase);
7686: }
7687: return (0,$currentphase+1);
7688: }
7689:
7690:
7691: sub scantron_get_maxbubble {
7692: my ($nav_error,$scantron_config) = @_;
7693: if (defined($env{'form.scantron_maxbubble'}) &&
7694: $env{'form.scantron_maxbubble'}) {
7695: &restore_bubble_lines();
7696: return $env{'form.scantron_maxbubble'};
7697: }
7698:
7699: my (undef, undef, $sequence) =
7700: &Apache::lonnet::decode_symb($env{'form.selectpage'});
7701:
7702: my $navmap=Apache::lonnavmaps::navmap->new();
7703: unless (ref($navmap)) {
7704: if (ref($nav_error)) {
7705: $$nav_error = 1;
7706: }
7707: return;
7708: }
7709: my $map=$navmap->getResourceByUrl($sequence);
7710: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
7711: my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
7712:
7713: &Apache::lonxml::clear_problem_counter();
7714:
7715: my $uname = $env{'user.name'};
7716: my $udom = $env{'user.domain'};
7717: my $cid = $env{'request.course.id'};
7718: my $total_lines = 0;
7719: %bubble_lines_per_response = ();
7720: %first_bubble_line = ();
7721: %subdivided_bubble_lines = ();
7722: %responsetype_per_response = ();
7723:
7724: my $response_number = 0;
7725: my $bubble_line = 0;
7726: foreach my $resource (@resources) {
7727: my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
7728: $udom,undef,$bubbles_per_row);
7729: if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
7730: foreach my $part_id (@{$parts}) {
7731: my $lines;
7732:
7733: # TODO - make this a persistent hash not an array.
7734:
7735: # optionresponse, matchresponse and rankresponse type items
7736: # render as separate sub-questions in exam mode.
7737: if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
7738: ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
7739: ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
7740: my ($numbub,$numshown);
7741: if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
7742: if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
7743: $numbub = scalar(@{$analysis->{$part_id.'.options'}});
7744: }
7745: } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
7746: if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
7747: $numbub = scalar(@{$analysis->{$part_id.'.items'}});
7748: }
7749: } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
7750: if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
7751: $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
7752: }
7753: }
7754: if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
7755: $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
7756: }
7757: my $bubbles_per_row =
7758: &bubblesheet_bubbles_per_row($scantron_config);
7759: my $inner_bubble_lines = int($numbub/$bubbles_per_row);
7760: if (($numbub % $bubbles_per_row) != 0) {
7761: $inner_bubble_lines++;
7762: }
7763: for (my $i=0; $i<$numshown; $i++) {
7764: $subdivided_bubble_lines{$response_number} .=
7765: $inner_bubble_lines.',';
7766: }
7767: $subdivided_bubble_lines{$response_number} =~ s/,$//;
7768: $lines = $numshown * $inner_bubble_lines;
7769: } else {
7770: $lines = $analysis->{"$part_id.bubble_lines"};
7771: }
7772:
7773: $first_bubble_line{$response_number} = $bubble_line;
7774: $bubble_lines_per_response{$response_number} = $lines;
7775: $responsetype_per_response{$response_number} =
7776: $analysis->{$part_id.'.type'};
7777: $response_number++;
7778:
7779: $bubble_line += $lines;
7780: $total_lines += $lines;
7781: }
7782: }
7783: }
7784: &Apache::lonnet::delenv('scantron.');
7785:
7786: &save_bubble_lines();
7787: $env{'form.scantron_maxbubble'} =
7788: $total_lines;
7789: return $env{'form.scantron_maxbubble'};
7790: }
7791:
7792: sub bubblesheet_bubbles_per_row {
7793: my ($scantron_config) = @_;
7794: my $bubbles_per_row;
7795: if (ref($scantron_config) eq 'HASH') {
7796: $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
7797: }
7798: if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
7799: $bubbles_per_row = 10;
7800: }
7801: return $bubbles_per_row;
7802: }
7803:
7804: sub scantron_validate_missingbubbles {
7805: my ($r,$currentphase) = @_;
7806: #get student info
7807: my $classlist=&Apache::loncoursedata::get_classlist();
7808: my %idmap=&username_to_idmap($classlist);
7809:
7810: #get scantron line setup
7811: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7812: my ($scanlines,$scan_data)=&scantron_getfile();
7813: my $nav_error;
7814: my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
7815: if ($nav_error) {
7816: return(1,$currentphase);
7817: }
7818: if (!$max_bubble) { $max_bubble=2**31; }
7819: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7820: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7821: if ($line=~/^[\s\cz]*$/) { next; }
7822: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7823: $scan_data);
7824: if (!defined($$scan_record{'scantron.missingerror'})) { next; }
7825: my @to_correct;
7826:
7827: # Probably here's where the error is...
7828:
7829: foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
7830: my $lastbubble;
7831: if ($missing =~ /^(\d+)\.(\d+)$/) {
7832: my $question = $1;
7833: my $subquestion = $2;
7834: if (!defined($first_bubble_line{$question -1})) { next; }
7835: my $first = $first_bubble_line{$question-1};
7836: my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
7837: my $subcount = 1;
7838: while ($subcount<$subquestion) {
7839: $first += $subans[$subcount-1];
7840: $subcount ++;
7841: }
7842: my $count = $subans[$subquestion-1];
7843: $lastbubble = $first + $count;
7844: } else {
7845: if (!defined($first_bubble_line{$missing - 1})) { next; }
7846: $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
7847: }
7848: if ($lastbubble > $max_bubble) { next; }
7849: push(@to_correct,$missing);
7850: }
7851: if (@to_correct) {
7852: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
7853: $line,'missingbubble',\@to_correct);
7854: return (1,$currentphase);
7855: }
7856:
7857: }
7858: return (0,$currentphase+1);
7859: }
7860:
7861: sub hand_bubble_option {
7862: my (undef, undef, $sequence) =
7863: &Apache::lonnet::decode_symb($env{'form.selectpage'});
7864: return if ($sequence eq '');
7865: my $navmap = Apache::lonnavmaps::navmap->new();
7866: unless (ref($navmap)) {
7867: return;
7868: }
7869: my $needs_hand_bubbles;
7870: my $map=$navmap->getResourceByUrl($sequence);
7871: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
7872: foreach my $res (@resources) {
7873: if (ref($res)) {
7874: if ($res->is_problem()) {
7875: my $partlist = $res->parts();
7876: foreach my $part (@{ $partlist }) {
7877: my @types = $res->responseType($part);
7878: if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
7879: $needs_hand_bubbles = 1;
7880: last;
7881: }
7882: }
7883: }
7884: }
7885: }
7886: if ($needs_hand_bubbles) {
7887: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7888: my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
7889: return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
7890: &mt('If you have already graded these by bubbling sheets to indicate points awarded, [_1]what point value is assigned to a filled last bubble in each row?','<br />').
7891: '<label><input type="radio" name="scantron_lastbubblepoints" value="'.$bubbles_per_row.'" checked="checked" />'.&mt('[quant,_1,point]',$bubbles_per_row).'</label> '.&mt('or').' '.
7892: '<label><input type="radio" name="scantron_lastbubblepoints" value="0"/>0 points</label></p>';
7893: }
7894: return;
7895: }
7896:
7897: sub scantron_process_students {
7898: my ($r,$symb) = @_;
7899:
7900: my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
7901: if (!$symb) {
7902: return '';
7903: }
7904: my $default_form_data=&defaultFormData($symb);
7905:
7906: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7907: my $bubbles_per_row =
7908: &bubblesheet_bubbles_per_row(\%scantron_config);
7909: my ($scanlines,$scan_data)=&scantron_getfile();
7910: my $classlist=&Apache::loncoursedata::get_classlist();
7911: my %idmap=&username_to_idmap($classlist);
7912: my $navmap=Apache::lonnavmaps::navmap->new();
7913: unless (ref($navmap)) {
7914: $r->print(&navmap_errormsg());
7915: return '';
7916: }
7917: my $map=$navmap->getResourceByUrl($sequence);
7918: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
7919: my (%grader_partids_by_symb,%grader_randomlists_by_symb);
7920: &graders_resources_pass(\@resources,\%grader_partids_by_symb,
7921: \%grader_randomlists_by_symb,$bubbles_per_row);
7922: my $resource_error;
7923: foreach my $resource (@resources) {
7924: my $ressymb;
7925: if (ref($resource)) {
7926: $ressymb = $resource->symb();
7927: } else {
7928: $resource_error = 1;
7929: last;
7930: }
7931: my ($analysis,$parts) =
7932: &scantron_partids_tograde($resource,$env{'request.course.id'},
7933: $env{'user.name'},$env{'user.domain'},
7934: 1,$bubbles_per_row);
7935: $grader_partids_by_symb{$ressymb} = $parts;
7936: if (ref($analysis) eq 'HASH') {
7937: if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
7938: $grader_randomlists_by_symb{$ressymb} =
7939: $analysis->{'parts_withrandomlist'};
7940: }
7941: }
7942: }
7943: if ($resource_error) {
7944: $r->print(&navmap_errormsg());
7945: return '';
7946: }
7947:
7948: my ($uname,$udom);
7949: my $result= <<SCANTRONFORM;
7950: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
7951: <input type="hidden" name="command" value="scantron_configphase" />
7952: $default_form_data
7953: SCANTRONFORM
7954: $r->print($result);
7955:
7956: my @delayqueue;
7957: my (%completedstudents,%scandata);
7958:
7959: my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
7960: my $count=&get_todo_count($scanlines,$scan_data);
7961: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
7962: &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
7963: $r->print('<br />');
7964: my $start=&Time::HiRes::time();
7965: my $i=-1;
7966: my $started;
7967:
7968: my $nav_error;
7969: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
7970: if ($nav_error) {
7971: $r->print(&navmap_errormsg());
7972: return '';
7973: }
7974:
7975: # If an ssi failed in scantron_get_maxbubble, put an error message out to
7976: # the user and return.
7977:
7978: if ($ssi_error) {
7979: $r->print("</form>");
7980: &ssi_print_error($r);
7981: &Apache::lonnet::remove_lock($lock);
7982: return ''; # Dunno why the other returns return '' rather than just returning.
7983: }
7984:
7985: my %lettdig = &letter_to_digits();
7986: my $numletts = scalar(keys(%lettdig));
7987:
7988: while ($i<$scanlines->{'count'}) {
7989: ($uname,$udom)=('','');
7990: $i++;
7991: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7992: if ($line=~/^[\s\cz]*$/) { next; }
7993: if ($started) {
7994: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
7995: }
7996: $started=1;
7997: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7998: $scan_data);
7999: unless ($uname=&scantron_find_student($scan_record,$scan_data,
8000: \%idmap,$i)) {
8001: &scantron_add_delay(\@delayqueue,$line,
8002: 'Unable to find a student that matches',1);
8003: next;
8004: }
8005: if (exists $completedstudents{$uname}) {
8006: &scantron_add_delay(\@delayqueue,$line,
8007: 'Student '.$uname.' has multiple sheets',2);
8008: next;
8009: }
8010: ($uname,$udom)=split(/:/,$uname);
8011:
8012: my (%partids_by_symb,$res_error);
8013: foreach my $resource (@resources) {
8014: my $ressymb;
8015: if (ref($resource)) {
8016: $ressymb = $resource->symb();
8017: } else {
8018: $res_error = 1;
8019: last;
8020: }
8021: if ((exists($grader_randomlists_by_symb{$ressymb})) ||
8022: (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
8023: my ($analysis,$parts) =
8024: &scantron_partids_tograde($resource,$env{'request.course.id'},
8025: $uname,$udom,undef,$bubbles_per_row);
8026: $partids_by_symb{$ressymb} = $parts;
8027: } else {
8028: $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
8029: }
8030: }
8031:
8032: if ($res_error) {
8033: &scantron_add_delay(\@delayqueue,$line,
8034: 'An error occurred while grading student '.$uname,2);
8035: next;
8036: }
8037:
8038: &Apache::lonxml::clear_problem_counter();
8039: &Apache::lonnet::appenv($scan_record);
8040:
8041: if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
8042: &scantron_putfile($scanlines,$scan_data);
8043: }
8044:
8045: my $scancode;
8046: if ((exists($scan_record->{'scantron.CODE'})) &&
8047: (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
8048: $scancode = $scan_record->{'scantron.CODE'};
8049: } else {
8050: $scancode = '';
8051: }
8052:
8053: if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
8054: \@resources,\%partids_by_symb,
8055: $bubbles_per_row) eq 'ssi_error') {
8056: $ssi_error = 0; # So end of handler error message does not trigger.
8057: $r->print("</form>");
8058: &ssi_print_error($r);
8059: &Apache::lonnet::remove_lock($lock);
8060: return ''; # Why return ''? Beats me.
8061: }
8062:
8063: $completedstudents{$uname}={'line'=>$line};
8064: if ($env{'form.verifyrecord'}) {
8065: my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
8066: my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
8067: chomp($studentdata);
8068: $studentdata =~ s/\r$//;
8069: my $studentrecord = '';
8070: my $counter = -1;
8071: foreach my $resource (@resources) {
8072: my $ressymb = $resource->symb();
8073: ($counter,my $recording) =
8074: &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
8075: $counter,$studentdata,$partids_by_symb{$ressymb},
8076: \%scantron_config,\%lettdig,$numletts);
8077: $studentrecord .= $recording;
8078: }
8079: if ($studentrecord ne $studentdata) {
8080: &Apache::lonxml::clear_problem_counter();
8081: if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
8082: \@resources,\%partids_by_symb,
8083: $bubbles_per_row) eq 'ssi_error') {
8084: $ssi_error = 0; # So end of handler error message does not trigger.
8085: $r->print("</form>");
8086: &ssi_print_error($r);
8087: &Apache::lonnet::remove_lock($lock);
8088: delete($completedstudents{$uname});
8089: return '';
8090: }
8091: $counter = -1;
8092: $studentrecord = '';
8093: foreach my $resource (@resources) {
8094: my $ressymb = $resource->symb();
8095: ($counter,my $recording) =
8096: &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
8097: $counter,$studentdata,$partids_by_symb{$ressymb},
8098: \%scantron_config,\%lettdig,$numletts);
8099: $studentrecord .= $recording;
8100: }
8101: if ($studentrecord ne $studentdata) {
8102: $r->print('<p><span class="LC_warning">');
8103: if ($scancode eq '') {
8104: $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
8105: $uname.':'.$udom,$scan_record->{'scantron.ID'}));
8106: } else {
8107: $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
8108: $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
8109: }
8110: $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
8111: &Apache::loncommon::start_data_table_header_row()."\n".
8112: '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
8113: &Apache::loncommon::end_data_table_header_row()."\n".
8114: &Apache::loncommon::start_data_table_row().
8115: '<td>'.&mt('Bubblesheet').'</td>'.
8116: '<td><span class="LC_nobreak"><tt>'.$studentdata.'</tt></span></td>'.
8117: &Apache::loncommon::end_data_table_row().
8118: &Apache::loncommon::start_data_table_row().
8119: '<td>'.&mt('Stored submissions').'</td>'.
8120: '<td><span class="LC_nobreak"><tt>'.$studentrecord.'</tt></span></td>'."\n".
8121: &Apache::loncommon::end_data_table_row().
8122: &Apache::loncommon::end_data_table().'</p>');
8123: } else {
8124: $r->print('<br /><span class="LC_warning">'.
8125: &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 />'.
8126: &mt("As a consequence, this user's submission history records two tries.").
8127: '</span><br />');
8128: }
8129: }
8130: }
8131: if (&Apache::loncommon::connection_aborted($r)) { last; }
8132: } continue {
8133: &Apache::lonxml::clear_problem_counter();
8134: &Apache::lonnet::delenv('scantron.');
8135: }
8136: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
8137: &Apache::lonnet::remove_lock($lock);
8138: # my $lasttime = &Time::HiRes::time()-$start;
8139: # $r->print("<p>took $lasttime</p>");
8140:
8141: $r->print("</form>");
8142: return '';
8143: }
8144:
8145: sub graders_resources_pass {
8146: my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
8147: $bubbles_per_row) = @_;
8148: if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) &&
8149: (ref($grader_randomlists_by_symb) eq 'HASH')) {
8150: foreach my $resource (@{$resources}) {
8151: my $ressymb = $resource->symb();
8152: my ($analysis,$parts) =
8153: &scantron_partids_tograde($resource,$env{'request.course.id'},
8154: $env{'user.name'},$env{'user.domain'},
8155: 1,$bubbles_per_row);
8156: $grader_partids_by_symb->{$ressymb} = $parts;
8157: if (ref($analysis) eq 'HASH') {
8158: if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
8159: $grader_randomlists_by_symb->{$ressymb} =
8160: $analysis->{'parts_withrandomlist'};
8161: }
8162: }
8163: }
8164: }
8165: return;
8166: }
8167:
8168: sub grade_student_bubbles {
8169: my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row) = @_;
8170: # Walk folder as student here to get resources in order student sees.
8171: if (ref($resources) eq 'ARRAY') {
8172: my $count = 0;
8173: foreach my $resource (@{$resources}) {
8174: my $ressymb = $resource->symb();
8175: my %form = ('submitted' => 'scantron',
8176: 'grade_target' => 'grade',
8177: 'grade_username' => $uname,
8178: 'grade_domain' => $udom,
8179: 'grade_courseid' => $env{'request.course.id'},
8180: 'grade_symb' => $ressymb,
8181: 'CODE' => $scancode
8182: );
8183: if ($bubbles_per_row ne '') {
8184: $form{'bubbles_per_row'} = $bubbles_per_row;
8185: }
8186: if ($env{'form.scantron_lastbubblepoints'} ne '') {
8187: $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
8188: }
8189: if (ref($parts) eq 'HASH') {
8190: if (ref($parts->{$ressymb}) eq 'ARRAY') {
8191: foreach my $part (@{$parts->{$ressymb}}) {
8192: $form{'scantron_questnum_start.'.$part} =
8193: 1+$env{'form.scantron.first_bubble_line.'.$count};
8194: $count++;
8195: }
8196: }
8197: }
8198: my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
8199: return 'ssi_error' if ($ssi_error);
8200: last if (&Apache::loncommon::connection_aborted($r));
8201: }
8202: }
8203: return;
8204: }
8205:
8206: sub scantron_upload_scantron_data {
8207: my ($r,$symb)=@_;
8208: my $dom = $env{'request.role.domain'};
8209: my $domdesc = &Apache::lonnet::domain($dom,'description');
8210: $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
8211: my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
8212: 'domainid',
8213: 'coursename',$dom);
8214: my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
8215: (' 'x2).&mt('(shows course personnel)');
8216: my $default_form_data=&defaultFormData($symb);
8217: my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
8218: 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.");
8219: $r->print(&Apache::lonhtmlcommon::scripttag('
8220: function checkUpload(formname) {
8221: if (formname.upfile.value == "") {
8222: alert("'.$nofile_alert.'");
8223: return false;
8224: }
8225: if (formname.courseid.value == "") {
8226: alert("'.$nocourseid_alert.'");
8227: return false;
8228: }
8229: formname.submit();
8230: }
8231:
8232: function ToSyllabus() {
8233: var cdom = '."'$dom'".';
8234: var cnum = document.rules.courseid.value;
8235: if (cdom == "" || cdom == null) {
8236: return;
8237: }
8238: if (cnum == "" || cnum == null) {
8239: return;
8240: }
8241: syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
8242: "height=350,width=350,scrollbars=yes,menubar=no");
8243: return;
8244: }
8245:
8246: '));
8247: $r->print('
8248: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
8249:
8250: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
8251: '.$default_form_data.
8252: &Apache::lonhtmlcommon::start_pick_box().
8253: &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
8254: '<input name="courseid" type="text" size="30" />'.$select_link.
8255: &Apache::lonhtmlcommon::row_closure().
8256: &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
8257: '<input name="coursename" type="text" size="30" />'.$syllabuslink.
8258: &Apache::lonhtmlcommon::row_closure().
8259: &Apache::lonhtmlcommon::row_title(&mt('Domain')).
8260: '<input name="domainid" type="hidden" />'.$domdesc.
8261: &Apache::lonhtmlcommon::row_closure().
8262: &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
8263: '<input type="file" name="upfile" size="50" />'.
8264: &Apache::lonhtmlcommon::row_closure(1).
8265: &Apache::lonhtmlcommon::end_pick_box().'<br />
8266:
8267: <input name="command" value="scantronupload_save" type="hidden" />
8268: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
8269: </form>
8270: ');
8271: return '';
8272: }
8273:
8274:
8275: sub scantron_upload_scantron_data_save {
8276: my($r,$symb)=@_;
8277: my $doanotherupload=
8278: '<br /><form action="/adm/grades" method="post">'."\n".
8279: '<input type="hidden" name="command" value="scantronupload" />'."\n".
8280: '<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
8281: '</form>'."\n";
8282: if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
8283: !&Apache::lonnet::allowed('usc',
8284: $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
8285: $r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
8286: unless ($symb) {
8287: $r->print($doanotherupload);
8288: }
8289: return '';
8290: }
8291: my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
8292: my $uploadedfile;
8293: $r->print('<h3>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</h3>');
8294: if (length($env{'form.upfile'}) < 2) {
8295: $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>'));
8296: } else {
8297: my $result =
8298: &Apache::lonnet::userfileupload('upfile','','scantron','','','',
8299: $env{'form.courseid'},$env{'form.domainid'});
8300: if ($result =~ m{^/uploaded/}) {
8301: $r->print(&mt('[_1]Success:[_2] Successfully uploaded [_3] bytes of data into location: [_4]',
8302: '<span class="LC_success">','</span>',(length($env{'form.upfile'})-1),
8303: '<span class="LC_filename">'.$result.'</span>'));
8304: ($uploadedfile) = ($result =~ m{/([^/]+)$});
8305: $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
8306: $env{'form.courseid'},$uploadedfile));
8307: } else {
8308: $r->print(&mt('[_1]Error:[_2] An error ([_3]) occurred when attempting to upload the file, [_4]',
8309: '<span class="LC_error">','</span>',$result,
8310: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
8311: }
8312: }
8313: if ($symb) {
8314: $r->print(&scantron_selectphase($r,$uploadedfile,$symb));
8315: } else {
8316: $r->print($doanotherupload);
8317: }
8318: return '';
8319: }
8320:
8321: sub validate_uploaded_scantron_file {
8322: my ($cdom,$cname,$fname) = @_;
8323: my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
8324: my @lines;
8325: if ($scanlines ne '-1') {
8326: @lines=split("\n",$scanlines,-1);
8327: }
8328: my $output;
8329: if (@lines) {
8330: my (%counts,$max_match_format);
8331: my ($max_match_count,$max_match_pct) = (0,0);
8332: my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
8333: my %idmap = &username_to_idmap($classlist);
8334: foreach my $key (keys(%idmap)) {
8335: my $lckey = lc($key);
8336: $idmap{$lckey} = $idmap{$key};
8337: }
8338: my %unique_formats;
8339: my @formatlines = &get_scantronformat_file();
8340: foreach my $line (@formatlines) {
8341: chomp($line);
8342: my @config = split(/:/,$line);
8343: my $idstart = $config[5];
8344: my $idlength = $config[6];
8345: if (($idstart ne '') && ($idlength > 0)) {
8346: if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
8347: push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]);
8348: } else {
8349: $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
8350: }
8351: }
8352: }
8353: foreach my $key (keys(%unique_formats)) {
8354: my ($idstart,$idlength) = split(':',$key);
8355: %{$counts{$key}} = (
8356: 'found' => 0,
8357: 'total' => 0,
8358: );
8359: foreach my $line (@lines) {
8360: next if ($line =~ /^#/);
8361: next if ($line =~ /^[\s\cz]*$/);
8362: my $id = substr($line,$idstart-1,$idlength);
8363: $id = lc($id);
8364: if (exists($idmap{$id})) {
8365: $counts{$key}{'found'} ++;
8366: }
8367: $counts{$key}{'total'} ++;
8368: }
8369: if ($counts{$key}{'total'}) {
8370: my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
8371: if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
8372: $max_match_pct = $percent_match;
8373: $max_match_format = $key;
8374: $max_match_count = $counts{$key}{'total'};
8375: }
8376: }
8377: }
8378: if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
8379: my $format_descs;
8380: my $numwithformat = @{$unique_formats{$max_match_format}};
8381: for (my $i=0; $i<$numwithformat; $i++) {
8382: my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
8383: if ($i<$numwithformat-2) {
8384: $format_descs .= '"<i>'.$desc.'</i>", ';
8385: } elsif ($i==$numwithformat-2) {
8386: $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
8387: } elsif ($i==$numwithformat-1) {
8388: $format_descs .= '"<i>'.$desc.'</i>"';
8389: }
8390: }
8391: my $showpct = sprintf("%.0f",$max_match_pct).'%';
8392: $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).
8393: '<br />'.&mt('A low percentage of matches results from one of the following:').'<ul>'.
8394: '<li>'.&mt('The file was uploaded to the wrong course').'</li>'.
8395: '<li>'.&mt('The data are not in the format expected for the domain: [_1]',
8396: '<i>'.$cdom.'</i>').'</li>'.
8397: '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
8398: '<li>'.&mt('The course roster is not up to date').'</li>'.
8399: '</ul>';
8400: }
8401: } else {
8402: $output = '<span class="LC_warning">'.&mt('Uploaded file contained no data').'</span>';
8403: }
8404: return $output;
8405: }
8406:
8407: sub valid_file {
8408: my ($requested_file)=@_;
8409: foreach my $filename (sort(&scantron_filenames())) {
8410: if ($requested_file eq $filename) { return 1; }
8411: }
8412: return 0;
8413: }
8414:
8415: sub scantron_download_scantron_data {
8416: my ($r,$symb)=@_;
8417: my $default_form_data=&defaultFormData($symb);
8418: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
8419: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
8420: my $file=$env{'form.scantron_selectfile'};
8421: if (! &valid_file($file)) {
8422: $r->print('
8423: <p>
8424: '.&mt('The requested file name was invalid.').'
8425: </p>
8426: ');
8427: return;
8428: }
8429: my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
8430: my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
8431: my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
8432: &Apache::lonnet::allowuploaded('/adm/grades',$orig);
8433: &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
8434: &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
8435: $r->print('
8436: <p>
8437: '.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
8438: '<a href="'.$orig.'">','</a>').'
8439: </p>
8440: <p>
8441: '.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
8442: '<a href="'.$corrected.'">','</a>').'
8443: </p>
8444: <p>
8445: '.&mt('[_1]Skipped[_2], a file of records that were skipped.',
8446: '<a href="'.$skipped.'">','</a>').'
8447: </p>
8448: ');
8449: return '';
8450: }
8451:
8452: sub checkscantron_results {
8453: my ($r,$symb) = @_;
8454: if (!$symb) {return '';}
8455: my $cid = $env{'request.course.id'};
8456: my %lettdig = &letter_to_digits();
8457: my $numletts = scalar(keys(%lettdig));
8458: my $cnum = $env{'course.'.$cid.'.num'};
8459: my $cdom = $env{'course.'.$cid.'.domain'};
8460: my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
8461: my %record;
8462: my %scantron_config =
8463: &Apache::grades::get_scantron_config($env{'form.scantron_format'});
8464: my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
8465: my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
8466: my $classlist=&Apache::loncoursedata::get_classlist();
8467: my %idmap=&Apache::grades::username_to_idmap($classlist);
8468: my $navmap=Apache::lonnavmaps::navmap->new();
8469: unless (ref($navmap)) {
8470: $r->print(&navmap_errormsg());
8471: return '';
8472: }
8473: my $map=$navmap->getResourceByUrl($sequence);
8474: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
8475: my (%grader_partids_by_symb,%grader_randomlists_by_symb);
8476: &graders_resources_pass(\@resources,\%grader_partids_by_symb,
8477: \%grader_randomlists_by_symb,$bubbles_per_row);
8478:
8479: my ($uname,$udom);
8480: my (%scandata,%lastname,%bylast);
8481: $r->print('
8482: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
8483:
8484: my @delayqueue;
8485: my %completedstudents;
8486:
8487: my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
8488: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
8489: my ($username,$domain,$started);
8490: my $nav_error;
8491: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
8492: if ($nav_error) {
8493: $r->print(&navmap_errormsg());
8494: return '';
8495: }
8496:
8497: &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
8498: my $start=&Time::HiRes::time();
8499: my $i=-1;
8500:
8501: while ($i<$scanlines->{'count'}) {
8502: ($username,$domain,$uname)=('','','');
8503: $i++;
8504: my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
8505: if ($line=~/^[\s\cz]*$/) { next; }
8506: if ($started) {
8507: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
8508: }
8509: $started=1;
8510: my $scan_record=
8511: &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
8512: $scan_data);
8513: unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
8514: \%idmap,$i)) {
8515: &Apache::grades::scantron_add_delay(\@delayqueue,$line,
8516: 'Unable to find a student that matches',1);
8517: next;
8518: }
8519: if (exists $completedstudents{$uname}) {
8520: &Apache::grades::scantron_add_delay(\@delayqueue,$line,
8521: 'Student '.$uname.' has multiple sheets',2);
8522: next;
8523: }
8524: my $pid = $scan_record->{'scantron.ID'};
8525: $lastname{$pid} = $scan_record->{'scantron.LastName'};
8526: push(@{$bylast{$lastname{$pid}}},$pid);
8527: my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
8528: $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
8529: chomp($scandata{$pid});
8530: $scandata{$pid} =~ s/\r$//;
8531: ($username,$domain)=split(/:/,$uname);
8532: my $counter = -1;
8533: foreach my $resource (@resources) {
8534: my $parts;
8535: my $ressymb = $resource->symb();
8536: if ((exists($grader_randomlists_by_symb{$ressymb})) ||
8537: (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
8538: (my $analysis,$parts) =
8539: &scantron_partids_tograde($resource,$env{'request.course.id'},
8540: $username,$domain,undef,
8541: $bubbles_per_row);
8542: } else {
8543: $parts = $grader_partids_by_symb{$ressymb};
8544: }
8545: ($counter,my $recording) =
8546: &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
8547: $scandata{$pid},$parts,
8548: \%scantron_config,\%lettdig,$numletts);
8549: $record{$pid} .= $recording;
8550: }
8551: }
8552: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
8553: $r->print('<br />');
8554: my ($okstudents,$badstudents,$numstudents,$passed,$failed);
8555: $passed = 0;
8556: $failed = 0;
8557: $numstudents = 0;
8558: foreach my $last (sort(keys(%bylast))) {
8559: if (ref($bylast{$last}) eq 'ARRAY') {
8560: foreach my $pid (sort(@{$bylast{$last}})) {
8561: my $showscandata = $scandata{$pid};
8562: my $showrecord = $record{$pid};
8563: $showscandata =~ s/\s/ /g;
8564: $showrecord =~ s/\s/ /g;
8565: if ($scandata{$pid} eq $record{$pid}) {
8566: my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
8567: $okstudents .= '<tr class="'.$css_class.'">'.
8568: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
8569: '</tr>'."\n".
8570: '<tr class="'.$css_class.'">'."\n".
8571: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
8572: $passed ++;
8573: } else {
8574: my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
8575: $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".
8576: '</tr>'."\n".
8577: '<tr class="'.$css_class.'">'."\n".
8578: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
8579: '</tr>'."\n";
8580: $failed ++;
8581: }
8582: $numstudents ++;
8583: }
8584: }
8585: }
8586: $r->print(
8587: '<p>'
8588: .&mt('Comparison of bubblesheet data (including corrections) with corresponding submission records (most recent submission) for [_1][quant,_2,student][_3] ([quant,_4,bubblesheet line] per student).',
8589: '<b>',
8590: $numstudents,
8591: '</b>',
8592: $env{'form.scantron_maxbubble'})
8593: .'</p>'
8594: );
8595: $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>');
8596: if ($passed) {
8597: $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
8598: $r->print(&Apache::loncommon::start_data_table()."\n".
8599: &Apache::loncommon::start_data_table_header_row()."\n".
8600: '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
8601: &Apache::loncommon::end_data_table_header_row()."\n".
8602: $okstudents."\n".
8603: &Apache::loncommon::end_data_table().'<br />');
8604: }
8605: if ($failed) {
8606: $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
8607: $r->print(&Apache::loncommon::start_data_table()."\n".
8608: &Apache::loncommon::start_data_table_header_row()."\n".
8609: '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
8610: &Apache::loncommon::end_data_table_header_row()."\n".
8611: $badstudents."\n".
8612: &Apache::loncommon::end_data_table()).'<br />'.
8613: &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.');
8614: }
8615: $r->print('</form><br />');
8616: return;
8617: }
8618:
8619: sub verify_scantron_grading {
8620: my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
8621: $scantron_config,$lettdig,$numletts) = @_;
8622: my ($record,%expected,%startpos);
8623: return ($counter,$record) if (!ref($resource));
8624: return ($counter,$record) if (!$resource->is_problem());
8625: my $symb = $resource->symb();
8626: return ($counter,$record) if (ref($partids) ne 'ARRAY');
8627: foreach my $part_id (@{$partids}) {
8628: $counter ++;
8629: $expected{$part_id} = 0;
8630: if ($env{"form.scantron.sub_bubblelines.$counter"}) {
8631: my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
8632: foreach my $item (@sub_lines) {
8633: $expected{$part_id} += $item;
8634: }
8635: } else {
8636: $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
8637: }
8638: $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
8639: }
8640: if ($symb) {
8641: my %recorded;
8642: my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
8643: if ($returnhash{'version'}) {
8644: my %lasthash=();
8645: my $version;
8646: for ($version=1;$version<=$returnhash{'version'};$version++) {
8647: foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
8648: $lasthash{$key}=$returnhash{$version.':'.$key};
8649: }
8650: }
8651: foreach my $key (keys(%lasthash)) {
8652: if ($key =~ /\.scantron$/) {
8653: my $value = &unescape($lasthash{$key});
8654: my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
8655: if ($value eq '') {
8656: for (my $i=0; $i<$expected{$part_id}; $i++) {
8657: for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
8658: $recorded{$part_id} .= $scantron_config->{'Qoff'};
8659: }
8660: }
8661: } else {
8662: my @tocheck;
8663: my @items = split(//,$value);
8664: if (($scantron_config->{'Qon'} eq 'letter') ||
8665: ($scantron_config->{'Qon'} eq 'number')) {
8666: if (@items < $expected{$part_id}) {
8667: my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
8668: my @singles = split(//,$fragment);
8669: foreach my $pos (@singles) {
8670: if ($pos eq ' ') {
8671: push(@tocheck,$pos);
8672: } else {
8673: my $next = shift(@items);
8674: push(@tocheck,$next);
8675: }
8676: }
8677: } else {
8678: @tocheck = @items;
8679: }
8680: foreach my $letter (@tocheck) {
8681: if ($scantron_config->{'Qon'} eq 'letter') {
8682: if ($letter !~ /^[A-J]$/) {
8683: $letter = $scantron_config->{'Qoff'};
8684: }
8685: $recorded{$part_id} .= $letter;
8686: } elsif ($scantron_config->{'Qon'} eq 'number') {
8687: my $digit;
8688: if ($letter !~ /^[A-J]$/) {
8689: $digit = $scantron_config->{'Qoff'};
8690: } else {
8691: $digit = $lettdig->{$letter};
8692: }
8693: $recorded{$part_id} .= $digit;
8694: }
8695: }
8696: } else {
8697: @tocheck = @items;
8698: for (my $i=0; $i<$expected{$part_id}; $i++) {
8699: my $curr_sub = shift(@tocheck);
8700: my $digit;
8701: if ($curr_sub =~ /^[A-J]$/) {
8702: $digit = $lettdig->{$curr_sub}-1;
8703: }
8704: if ($curr_sub eq 'J') {
8705: $digit += scalar($numletts);
8706: }
8707: for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
8708: if ($j == $digit) {
8709: $recorded{$part_id} .= $scantron_config->{'Qon'};
8710: } else {
8711: $recorded{$part_id} .= $scantron_config->{'Qoff'};
8712: }
8713: }
8714: }
8715: }
8716: }
8717: }
8718: }
8719: }
8720: foreach my $part_id (@{$partids}) {
8721: if ($recorded{$part_id} eq '') {
8722: for (my $i=0; $i<$expected{$part_id}; $i++) {
8723: for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
8724: $recorded{$part_id} .= $scantron_config->{'Qoff'};
8725: }
8726: }
8727: }
8728: $record .= $recorded{$part_id};
8729: }
8730: }
8731: return ($counter,$record);
8732: }
8733:
8734: sub letter_to_digits {
8735: my %lettdig = (
8736: A => 1,
8737: B => 2,
8738: C => 3,
8739: D => 4,
8740: E => 5,
8741: F => 6,
8742: G => 7,
8743: H => 8,
8744: I => 9,
8745: J => 0,
8746: );
8747: return %lettdig;
8748: }
8749:
8750:
8751: #-------- end of section for handling grading scantron forms -------
8752: #
8753: #-------------------------------------------------------------------
8754:
8755: #-------------------------- Menu interface -------------------------
8756: #
8757: #--- Href with symb and command ---
8758:
8759: sub href_symb_cmd {
8760: my ($symb,$cmd)=@_;
8761: return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&command='.$cmd;
8762: }
8763:
8764: sub grading_menu {
8765: my ($request,$symb) = @_;
8766: if (!$symb) {return '';}
8767:
8768: my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
8769: 'command'=>'individual');
8770:
8771: my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
8772:
8773: $fields{'command'}='ungraded';
8774: my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
8775:
8776: $fields{'command'}='table';
8777: my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
8778:
8779: $fields{'command'}='all_for_one';
8780: my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
8781:
8782: $fields{'command'}='downloadfilesselect';
8783: my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
8784:
8785: $fields{'command'} = 'csvform';
8786: my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
8787:
8788: $fields{'command'} = 'processclicker';
8789: my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
8790:
8791: $fields{'command'} = 'scantron_selectphase';
8792: my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
8793:
8794: $fields{'command'} = 'initialverifyreceipt';
8795: my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
8796:
8797: my @menu = ({ categorytitle=>'Hand Grading',
8798: items =>[
8799: { linktext => 'Select individual students to grade',
8800: url => $url1a,
8801: permission => 'F',
8802: icon => 'grade_students.png',
8803: linktitle => 'Grade current resource for a selection of students.'
8804: },
8805: { linktext => 'Grade ungraded submissions.',
8806: url => $url1b,
8807: permission => 'F',
8808: icon => 'ungrade_sub.png',
8809: linktitle => 'Grade all submissions that have not been graded yet.'
8810: },
8811:
8812: { linktext => 'Grading table',
8813: url => $url1c,
8814: permission => 'F',
8815: icon => 'grading_table.png',
8816: linktitle => 'Grade current resource for all students.'
8817: },
8818: { linktext => 'Grade page/folder for one student',
8819: url => $url1d,
8820: permission => 'F',
8821: icon => 'grade_PageFolder.png',
8822: linktitle => 'Grade all resources in current page/sequence/folder for one student.'
8823: },
8824: { linktext => 'Download submissions',
8825: url => $url1e,
8826: permission => 'F',
8827: icon => 'download_sub.png',
8828: linktitle => 'Download all students submissions.'
8829: }]},
8830: { categorytitle=>'Automated Grading',
8831: items =>[
8832:
8833: { linktext => 'Upload Scores',
8834: url => $url2,
8835: permission => 'F',
8836: icon => 'uploadscores.png',
8837: linktitle => 'Specify a file containing the class scores for current resource.'
8838: },
8839: { linktext => 'Process Clicker',
8840: url => $url3,
8841: permission => 'F',
8842: icon => 'addClickerInfoFile.png',
8843: linktitle => 'Specify a file containing the clicker information for this resource.'
8844: },
8845: { linktext => 'Grade/Manage/Review Bubblesheets',
8846: url => $url4,
8847: permission => 'F',
8848: icon => 'bubblesheet.png',
8849: linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
8850: },
8851: { linktext => 'Verify Receipt Number',
8852: url => $url5,
8853: permission => 'F',
8854: icon => 'receipt_number.png',
8855: linktitle => 'Verify a system-generated receipt number for correct problem solution.'
8856: }
8857:
8858: ]
8859: });
8860:
8861: # Create the menu
8862: my $Str;
8863: $Str .= '<form method="post" action="" name="gradingMenu">';
8864: $Str .= '<input type="hidden" name="command" value="" />'.
8865: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
8866:
8867: $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
8868: return $Str;
8869: }
8870:
8871:
8872: sub ungraded {
8873: my ($request)=@_;
8874: &submit_options($request);
8875: }
8876:
8877: sub submit_options_sequence {
8878: my ($request,$symb) = @_;
8879: if (!$symb) {return '';}
8880: &commonJSfunctions($request);
8881: my $result;
8882:
8883: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
8884: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
8885: $result.=&selectfield(0).
8886: '<input type="hidden" name="command" value="pickStudentPage" />
8887: <div>
8888: <input type="submit" value="'.&mt('Next').' →" />
8889: </div>
8890: </div>
8891: </form>';
8892: return $result;
8893: }
8894:
8895: sub submit_options_table {
8896: my ($request,$symb) = @_;
8897: if (!$symb) {return '';}
8898: &commonJSfunctions($request);
8899: my $result;
8900:
8901: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
8902: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
8903:
8904: $result.=&selectfield(0).
8905: '<input type="hidden" name="command" value="viewgrades" />
8906: <div>
8907: <input type="submit" value="'.&mt('Next').' →" />
8908: </div>
8909: </div>
8910: </form>';
8911: return $result;
8912: }
8913:
8914: sub submit_options_download {
8915: my ($request,$symb) = @_;
8916: if (!$symb) {return '';}
8917:
8918: &commonJSfunctions($request);
8919:
8920: my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
8921: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
8922: $result.='
8923: <h2>
8924: '.&mt('Select Students for Which to Download Submissions').'
8925: </h2>'.&selectfield(1).'
8926: <input type="hidden" name="command" value="downloadfileslink" />
8927: <input type="submit" value="'.&mt('Next').' →" />
8928: </div>
8929: </div>
8930:
8931:
8932: </form>';
8933: return $result;
8934: }
8935:
8936: #--- Displays the submissions first page -------
8937: sub submit_options {
8938: my ($request,$symb) = @_;
8939: if (!$symb) {return '';}
8940:
8941: &commonJSfunctions($request);
8942: my $result;
8943:
8944: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
8945: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
8946: $result.=&selectfield(1).'
8947: <input type="hidden" name="command" value="submission" />
8948: <input type="submit" value="'.&mt('Next').' →" />
8949: </div>
8950: </div>
8951:
8952:
8953: </form>';
8954: return $result;
8955: }
8956:
8957: sub selectfield {
8958: my ($full)=@_;
8959: my %options =
8960: (&Apache::lonlocal::texthash(
8961: 'yes' => 'with submissions',
8962: 'queued' => 'in grading queue',
8963: 'graded' => 'with ungraded submissions',
8964: 'incorrect' => 'with incorrect submissions',
8965: 'all' => 'with any status'),
8966: 'select_form_order' => ['yes','queued','graded','incorrect','all']);
8967: my $result='<div class="LC_columnSection">
8968:
8969: <fieldset>
8970: <legend>
8971: '.&mt('Sections').'
8972: </legend>
8973: '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
8974: </fieldset>
8975:
8976: <fieldset>
8977: <legend>
8978: '.&mt('Groups').'
8979: </legend>
8980: '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
8981: </fieldset>
8982:
8983: <fieldset>
8984: <legend>
8985: '.&mt('Access Status').'
8986: </legend>
8987: '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
8988: </fieldset>';
8989: if ($full) {
8990: $result.='
8991: <fieldset>
8992: <legend>
8993: '.&mt('Submission Status').'
8994: </legend>'.
8995: &Apache::loncommon::select_form('all','submitonly',\%options).
8996: '</fieldset>';
8997: }
8998: $result.='</div><br />';
8999: return $result;
9000: }
9001:
9002: sub reset_perm {
9003: undef(%perm);
9004: }
9005:
9006: sub init_perm {
9007: &reset_perm();
9008: foreach my $test_perm ('vgr','mgr','opa') {
9009:
9010: my $scope = $env{'request.course.id'};
9011: if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
9012:
9013: $scope .= '/'.$env{'request.course.sec'};
9014: if ( $perm{$test_perm}=
9015: &Apache::lonnet::allowed($test_perm,$scope)) {
9016: $perm{$test_perm.'_section'}=$env{'request.course.sec'};
9017: } else {
9018: delete($perm{$test_perm});
9019: }
9020: }
9021: }
9022: }
9023:
9024: sub init_old_essays {
9025: my ($symb,$apath,$adom,$aname) = @_;
9026: if ($symb ne '') {
9027: my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
9028: if (keys(%essays) > 0) {
9029: $old_essays{$symb} = \%essays;
9030: }
9031: }
9032: return;
9033: }
9034:
9035: sub reset_old_essays {
9036: undef(%old_essays);
9037: }
9038:
9039: sub gather_clicker_ids {
9040: my %clicker_ids;
9041:
9042: my $classlist = &Apache::loncoursedata::get_classlist();
9043:
9044: # Set up a couple variables.
9045: my $username_idx = &Apache::loncoursedata::CL_SNAME();
9046: my $domain_idx = &Apache::loncoursedata::CL_SDOM();
9047: my $status_idx = &Apache::loncoursedata::CL_STATUS();
9048:
9049: foreach my $student (keys(%$classlist)) {
9050: if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
9051: my $username = $classlist->{$student}->[$username_idx];
9052: my $domain = $classlist->{$student}->[$domain_idx];
9053: my $clickers =
9054: (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
9055: foreach my $id (split(/\,/,$clickers)) {
9056: $id=~s/^[\#0]+//;
9057: $id=~s/[\-\:]//g;
9058: if (exists($clicker_ids{$id})) {
9059: $clicker_ids{$id}.=','.$username.':'.$domain;
9060: } else {
9061: $clicker_ids{$id}=$username.':'.$domain;
9062: }
9063: }
9064: }
9065: return %clicker_ids;
9066: }
9067:
9068: sub gather_adv_clicker_ids {
9069: my %clicker_ids;
9070: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
9071: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
9072: my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
9073: foreach my $element (sort(keys(%coursepersonnel))) {
9074: foreach my $person (split(/\,/,$coursepersonnel{$element})) {
9075: my ($puname,$pudom)=split(/\:/,$person);
9076: my $clickers =
9077: (&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
9078: foreach my $id (split(/\,/,$clickers)) {
9079: $id=~s/^[\#0]+//;
9080: $id=~s/[\-\:]//g;
9081: if (exists($clicker_ids{$id})) {
9082: $clicker_ids{$id}.=','.$puname.':'.$pudom;
9083: } else {
9084: $clicker_ids{$id}=$puname.':'.$pudom;
9085: }
9086: }
9087: }
9088: }
9089: return %clicker_ids;
9090: }
9091:
9092: sub clicker_grading_parameters {
9093: return ('gradingmechanism' => 'scalar',
9094: 'upfiletype' => 'scalar',
9095: 'specificid' => 'scalar',
9096: 'pcorrect' => 'scalar',
9097: 'pincorrect' => 'scalar');
9098: }
9099:
9100: sub process_clicker {
9101: my ($r,$symb)=@_;
9102: if (!$symb) {return '';}
9103: my $result=&checkforfile_js();
9104: $result.=&Apache::loncommon::start_data_table().
9105: &Apache::loncommon::start_data_table_header_row().
9106: '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
9107: &Apache::loncommon::end_data_table_header_row().
9108: &Apache::loncommon::start_data_table_row()."<td>\n";
9109: # Attempt to restore parameters from last session, set defaults if not present
9110: my %Saveable_Parameters=&clicker_grading_parameters();
9111: &Apache::loncommon::restore_course_settings('grades_clicker',
9112: \%Saveable_Parameters);
9113: if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
9114: if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
9115: if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
9116: if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
9117:
9118: my %checked;
9119: foreach my $gradingmechanism ('attendance','personnel','specific','given') {
9120: if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
9121: $checked{$gradingmechanism}=' checked="checked"';
9122: }
9123: }
9124:
9125: my $upload=&mt("Evaluate File");
9126: my $type=&mt("Type");
9127: my $attendance=&mt("Award points just for participation");
9128: my $personnel=&mt("Correctness determined from response by course personnel");
9129: my $specific=&mt("Correctness determined from response with clicker ID(s)");
9130: my $given=&mt("Correctness determined from given list of answers").' '.
9131: '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
9132: my $pcorrect=&mt("Percentage points for correct solution");
9133: my $pincorrect=&mt("Percentage points for incorrect solution");
9134: my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
9135: {'iclicker' => 'i>clicker',
9136: 'interwrite' => 'interwrite PRS',
9137: 'turning' => 'Turning Technologies'});
9138: $symb = &Apache::lonenc::check_encrypt($symb);
9139: $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
9140: function sanitycheck() {
9141: // Accept only integer percentages
9142: document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
9143: document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
9144: // Find out grading choice
9145: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
9146: if (document.forms.gradesupload.gradingmechanism[i].checked) {
9147: gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
9148: }
9149: }
9150: // By default, new choice equals user selection
9151: newgradingchoice=gradingchoice;
9152: // Not good to give more points for false answers than correct ones
9153: if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
9154: document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
9155: }
9156: // If new choice is attendance only, and old choice was correctness-based, restore defaults
9157: if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
9158: document.forms.gradesupload.pcorrect.value=100;
9159: document.forms.gradesupload.pincorrect.value=100;
9160: }
9161: // If the values are different, cannot be attendance only
9162: if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
9163: (gradingchoice=='attendance')) {
9164: newgradingchoice='personnel';
9165: }
9166: // Change grading choice to new one
9167: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
9168: if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
9169: document.forms.gradesupload.gradingmechanism[i].checked=true;
9170: } else {
9171: document.forms.gradesupload.gradingmechanism[i].checked=false;
9172: }
9173: }
9174: // Remember the old state
9175: document.forms.gradesupload.waschecked.value=newgradingchoice;
9176: }
9177: ENDUPFORM
9178: $result.= <<ENDUPFORM;
9179: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
9180: <input type="hidden" name="symb" value="$symb" />
9181: <input type="hidden" name="command" value="processclickerfile" />
9182: <input type="file" name="upfile" size="50" />
9183: <br /><label>$type: $selectform</label>
9184: ENDUPFORM
9185: $result.='</td>'.&Apache::loncommon::end_data_table_row().
9186: &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
9187: <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
9188: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
9189: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
9190: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
9191: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
9192: <br />
9193: <input type="text" name="givenanswer" size="50" />
9194: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
9195: ENDGRADINGFORM
9196: $result.='</td>'.&Apache::loncommon::end_data_table_row().
9197: &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
9198: <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
9199: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
9200: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
9201: </form>'
9202: ENDPERCFORM
9203: $result.='</td>'.
9204: &Apache::loncommon::end_data_table_row().
9205: &Apache::loncommon::end_data_table();
9206: return $result;
9207: }
9208:
9209: sub process_clicker_file {
9210: my ($r,$symb)=@_;
9211: if (!$symb) {return '';}
9212:
9213: my %Saveable_Parameters=&clicker_grading_parameters();
9214: &Apache::loncommon::store_course_settings('grades_clicker',
9215: \%Saveable_Parameters);
9216: my $result='';
9217: if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
9218: $result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
9219: return $result;
9220: }
9221: if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
9222: $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
9223: return $result;
9224: }
9225: my $foundgiven=0;
9226: if ($env{'form.gradingmechanism'} eq 'given') {
9227: $env{'form.givenanswer'}=~s/^\s*//gs;
9228: $env{'form.givenanswer'}=~s/\s*$//gs;
9229: $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
9230: $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
9231: my @answers=split(/\,/,$env{'form.givenanswer'});
9232: $foundgiven=$#answers+1;
9233: }
9234: my %clicker_ids=&gather_clicker_ids();
9235: my %correct_ids;
9236: if ($env{'form.gradingmechanism'} eq 'personnel') {
9237: %correct_ids=&gather_adv_clicker_ids();
9238: }
9239: if ($env{'form.gradingmechanism'} eq 'specific') {
9240: foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
9241: $correct_id=~tr/a-z/A-Z/;
9242: $correct_id=~s/\s//gs;
9243: $correct_id=~s/^[\#0]+//;
9244: $correct_id=~s/[\-\:]//g;
9245: if ($correct_id) {
9246: $correct_ids{$correct_id}='specified';
9247: }
9248: }
9249: }
9250: if ($env{'form.gradingmechanism'} eq 'attendance') {
9251: $result.=&mt('Score based on attendance only');
9252: } elsif ($env{'form.gradingmechanism'} eq 'given') {
9253: $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
9254: } else {
9255: my $number=0;
9256: $result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
9257: foreach my $id (sort(keys(%correct_ids))) {
9258: $result.='<br /><tt>'.$id.'</tt> - ';
9259: if ($correct_ids{$id} eq 'specified') {
9260: $result.=&mt('specified');
9261: } else {
9262: my ($uname,$udom)=split(/\:/,$correct_ids{$id});
9263: $result.=&Apache::loncommon::plainname($uname,$udom);
9264: }
9265: $number++;
9266: }
9267: $result.="</p>\n";
9268: if ($number==0) {
9269: $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
9270: return $result;
9271: }
9272: }
9273: if (length($env{'form.upfile'}) < 2) {
9274: $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
9275: '<span class="LC_error">',
9276: '</span>',
9277: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
9278: return $result;
9279: }
9280:
9281: # Were able to get all the info needed, now analyze the file
9282:
9283: $result.=&Apache::loncommon::studentbrowser_javascript();
9284: $symb = &Apache::lonenc::check_encrypt($symb);
9285: $result.=&Apache::loncommon::start_data_table().
9286: &Apache::loncommon::start_data_table_header_row().
9287: '<th>'.&mt('Evaluate clicker file').'</th>'.
9288: &Apache::loncommon::end_data_table_header_row().
9289: &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
9290: <td>
9291: <form method="post" action="/adm/grades" name="clickeranalysis">
9292: <input type="hidden" name="symb" value="$symb" />
9293: <input type="hidden" name="command" value="assignclickergrades" />
9294: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
9295: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
9296: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
9297: ENDHEADER
9298: if ($env{'form.gradingmechanism'} eq 'given') {
9299: $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
9300: }
9301: my %responses;
9302: my @questiontitles;
9303: my $errormsg='';
9304: my $number=0;
9305: if ($env{'form.upfiletype'} eq 'iclicker') {
9306: ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
9307: }
9308: if ($env{'form.upfiletype'} eq 'interwrite') {
9309: ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
9310: }
9311: if ($env{'form.upfiletype'} eq 'turning') {
9312: ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
9313: }
9314: $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
9315: '<input type="hidden" name="number" value="'.$number.'" />'.
9316: &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
9317: $env{'form.pcorrect'},$env{'form.pincorrect'}).
9318: '<br />';
9319: if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
9320: $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
9321: return $result;
9322: }
9323: # Remember Question Titles
9324: # FIXME: Possibly need delimiter other than ":"
9325: for (my $i=0;$i<$number;$i++) {
9326: $result.='<input type="hidden" name="question:'.$i.'" value="'.
9327: &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
9328: }
9329: my $correct_count=0;
9330: my $student_count=0;
9331: my $unknown_count=0;
9332: # Match answers with usernames
9333: # FIXME: Possibly need delimiter other than ":"
9334: foreach my $id (keys(%responses)) {
9335: if ($correct_ids{$id}) {
9336: $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
9337: $correct_count++;
9338: } elsif ($clicker_ids{$id}) {
9339: if ($clicker_ids{$id}=~/\,/) {
9340: # More than one user with the same clicker!
9341: $result.="</td>".&Apache::loncommon::end_data_table_row().
9342: &Apache::loncommon::start_data_table_row()."<td>".
9343: &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
9344: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
9345: "<select name='multi".$id."'>";
9346: foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
9347: $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
9348: }
9349: $result.='</select>';
9350: $unknown_count++;
9351: } else {
9352: # Good: found one and only one user with the right clicker
9353: $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
9354: $student_count++;
9355: }
9356: } else {
9357: $result.="</td>".&Apache::loncommon::end_data_table_row().
9358: &Apache::loncommon::start_data_table_row()."<td>".
9359: &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
9360: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
9361: "\n".&mt("Username").": <input type='text' name='uname".$id."' /> ".
9362: "\n".&mt("Domain").": ".
9363: &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).' '.
9364: &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
9365: $unknown_count++;
9366: }
9367: }
9368: $result.='<hr />'.
9369: &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
9370: if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
9371: if ($correct_count==0) {
9372: $errormsg.="Found no correct answers answers for grading!";
9373: } elsif ($correct_count>1) {
9374: $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
9375: }
9376: }
9377: if ($number<1) {
9378: $errormsg.="Found no questions.";
9379: }
9380: if ($errormsg) {
9381: $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
9382: } else {
9383: $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
9384: }
9385: $result.='</form></td>'.
9386: &Apache::loncommon::end_data_table_row().
9387: &Apache::loncommon::end_data_table();
9388: return $result;
9389: }
9390:
9391: sub iclicker_eval {
9392: my ($questiontitles,$responses)=@_;
9393: my $number=0;
9394: my $errormsg='';
9395: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
9396: my %components=&Apache::loncommon::record_sep($line);
9397: my @entries=map {$components{$_}} (sort(keys(%components)));
9398: if ($entries[0] eq 'Question') {
9399: for (my $i=3;$i<$#entries;$i+=6) {
9400: $$questiontitles[$number]=$entries[$i];
9401: $number++;
9402: }
9403: }
9404: if ($entries[0]=~/^\#/) {
9405: my $id=$entries[0];
9406: my @idresponses;
9407: $id=~s/^[\#0]+//;
9408: for (my $i=0;$i<$number;$i++) {
9409: my $idx=3+$i*6;
9410: $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
9411: push(@idresponses,$entries[$idx]);
9412: }
9413: $$responses{$id}=join(',',@idresponses);
9414: }
9415: }
9416: return ($errormsg,$number);
9417: }
9418:
9419: sub interwrite_eval {
9420: my ($questiontitles,$responses)=@_;
9421: my $number=0;
9422: my $errormsg='';
9423: my $skipline=1;
9424: my $questionnumber=0;
9425: my %idresponses=();
9426: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
9427: my %components=&Apache::loncommon::record_sep($line);
9428: my @entries=map {$components{$_}} (sort(keys(%components)));
9429: if ($entries[1] eq 'Time') { $skipline=0; next; }
9430: if ($entries[1] eq 'Response') { $skipline=1; }
9431: next if $skipline;
9432: if ($entries[0]!=$questionnumber) {
9433: $questionnumber=$entries[0];
9434: $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
9435: $number++;
9436: }
9437: my $id=$entries[4];
9438: $id=~s/^[\#0]+//;
9439: $id=~s/^v\d*\://i;
9440: $id=~s/[\-\:]//g;
9441: $idresponses{$id}[$number]=$entries[6];
9442: }
9443: foreach my $id (keys(%idresponses)) {
9444: $$responses{$id}=join(',',@{$idresponses{$id}});
9445: $$responses{$id}=~s/^\s*\,//;
9446: }
9447: return ($errormsg,$number);
9448: }
9449:
9450: sub turning_eval {
9451: my ($questiontitles,$responses)=@_;
9452: my $number=0;
9453: my $errormsg='';
9454: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
9455: my %components=&Apache::loncommon::record_sep($line);
9456: my @entries=map {$components{$_}} (sort(keys(%components)));
9457: if ($#entries>$number) { $number=$#entries; }
9458: my $id=$entries[0];
9459: my @idresponses;
9460: $id=~s/^[\#0]+//;
9461: unless ($id) { next; }
9462: for (my $idx=1;$idx<=$#entries;$idx++) {
9463: $entries[$idx]=~s/\,/\;/g;
9464: $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
9465: push(@idresponses,$entries[$idx]);
9466: }
9467: $$responses{$id}=join(',',@idresponses);
9468: }
9469: for (my $i=1; $i<=$number; $i++) {
9470: $$questiontitles[$i]=&mt('Question [_1]',$i);
9471: }
9472: return ($errormsg,$number);
9473: }
9474:
9475:
9476: sub assign_clicker_grades {
9477: my ($r,$symb)=@_;
9478: if (!$symb) {return '';}
9479: # See which part we are saving to
9480: my $res_error;
9481: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
9482: if ($res_error) {
9483: return &navmap_errormsg();
9484: }
9485: # FIXME: This should probably look for the first handgradeable part
9486: my $part=$$partlist[0];
9487: # Start screen output
9488: my $result=&Apache::loncommon::start_data_table().
9489: &Apache::loncommon::start_data_table_header_row().
9490: '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
9491: &Apache::loncommon::end_data_table_header_row().
9492: &Apache::loncommon::start_data_table_row().'<td>';
9493: # Get correct result
9494: # FIXME: Possibly need delimiter other than ":"
9495: my @correct=();
9496: my $gradingmechanism=$env{'form.gradingmechanism'};
9497: my $number=$env{'form.number'};
9498: if ($gradingmechanism ne 'attendance') {
9499: foreach my $key (keys(%env)) {
9500: if ($key=~/^form\.correct\:/) {
9501: my @input=split(/\,/,$env{$key});
9502: for (my $i=0;$i<=$#input;$i++) {
9503: if (($correct[$i]) && ($input[$i]) &&
9504: ($correct[$i] ne $input[$i])) {
9505: $result.='<br /><span class="LC_warning">'.
9506: &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
9507: $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
9508: } elsif (($input[$i]) || ($input[$i] eq '0')) {
9509: $correct[$i]=$input[$i];
9510: }
9511: }
9512: }
9513: }
9514: for (my $i=0;$i<$number;$i++) {
9515: if ((!$correct[$i]) && ($correct[$i] ne '0')) {
9516: $result.='<br /><span class="LC_error">'.
9517: &mt('No correct result given for question "[_1]"!',
9518: $env{'form.question:'.$i}).'</span>';
9519: }
9520: }
9521: $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
9522: }
9523: # Start grading
9524: my $pcorrect=$env{'form.pcorrect'};
9525: my $pincorrect=$env{'form.pincorrect'};
9526: my $storecount=0;
9527: my %users=();
9528: foreach my $key (keys(%env)) {
9529: my $user='';
9530: if ($key=~/^form\.student\:(.*)$/) {
9531: $user=$1;
9532: }
9533: if ($key=~/^form\.unknown\:(.*)$/) {
9534: my $id=$1;
9535: if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
9536: $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
9537: } elsif ($env{'form.multi'.$id}) {
9538: $user=$env{'form.multi'.$id};
9539: }
9540: }
9541: if ($user) {
9542: if ($users{$user}) {
9543: $result.='<br /><span class="LC_warning">'.
9544: &mt("More than one entry found for <tt>[_1]</tt>!",$user).
9545: '</span><br />';
9546: }
9547: $users{$user}=1;
9548: my @answer=split(/\,/,$env{$key});
9549: my $sum=0;
9550: my $realnumber=$number;
9551: for (my $i=0;$i<$number;$i++) {
9552: if ($correct[$i] eq '-') {
9553: $realnumber--;
9554: } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
9555: if ($gradingmechanism eq 'attendance') {
9556: $sum+=$pcorrect;
9557: } elsif ($correct[$i] eq '*') {
9558: $sum+=$pcorrect;
9559: } else {
9560: # We actually grade if correct or not
9561: my $increment=$pincorrect;
9562: # Special case: numerical answer "0"
9563: if ($correct[$i] eq '0') {
9564: if ($answer[$i]=~/^[0\.]+$/) {
9565: $increment=$pcorrect;
9566: }
9567: # General numerical answer, both evaluate to something non-zero
9568: } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
9569: if (1.0*$correct[$i]==1.0*$answer[$i]) {
9570: $increment=$pcorrect;
9571: }
9572: # Must be just alphanumeric
9573: } elsif ($answer[$i] eq $correct[$i]) {
9574: $increment=$pcorrect;
9575: }
9576: $sum+=$increment;
9577: }
9578: }
9579: }
9580: my $ave=$sum/(100*$realnumber);
9581: # Store
9582: my ($username,$domain)=split(/\:/,$user);
9583: my %grades=();
9584: $grades{"resource.$part.solved"}='correct_by_override';
9585: $grades{"resource.$part.awarded"}=$ave;
9586: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
9587: my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
9588: $env{'request.course.id'},
9589: $domain,$username);
9590: if ($returncode ne 'ok') {
9591: $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
9592: } else {
9593: $storecount++;
9594: }
9595: }
9596: }
9597: # We are done
9598: $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
9599: '</td>'.
9600: &Apache::loncommon::end_data_table_row().
9601: &Apache::loncommon::end_data_table();
9602: return $result;
9603: }
9604:
9605: sub navmap_errormsg {
9606: return '<div class="LC_error">'.
9607: &mt('An error occurred retrieving information about resources in the course.').'<br />'.
9608: &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>').
9609: '</div>';
9610: }
9611:
9612: sub startpage {
9613: my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
9614: if ($nomenu) {
9615: $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
9616: } else {
9617: unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
9618: $r->print(&Apache::loncommon::start_page('Grading',$js,
9619: {'bread_crumbs' => $crumbs}));
9620: &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
9621: }
9622: unless ($nodisplayflag) {
9623: $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
9624: }
9625: }
9626:
9627: sub select_problem {
9628: my ($r)=@_;
9629: $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
9630: $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1));
9631: $r->print('<input type="hidden" name="command" value="gradingmenu" />');
9632: $r->print('<input type="submit" value="'.&mt('Next').' →" /></form>');
9633: }
9634:
9635: sub handler {
9636: my $request=$_[0];
9637: &reset_caches();
9638: if ($request->header_only) {
9639: &Apache::loncommon::content_type($request,'text/html');
9640: $request->send_http_header;
9641: return OK;
9642: }
9643: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
9644:
9645: # see what command we need to execute
9646:
9647: my @commands=&Apache::loncommon::get_env_multiple('form.command');
9648: my $command=$commands[0];
9649:
9650: &init_perm();
9651: if (!$env{'request.course.id'}) {
9652: unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
9653: ($command =~ /^scantronupload/)) {
9654: # Not in a course.
9655: $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
9656: return HTTP_NOT_ACCEPTABLE;
9657: }
9658: } elsif (!%perm) {
9659: $request->internal_redirect('/adm/quickgrades');
9660: }
9661: &Apache::loncommon::content_type($request,'text/html');
9662: $request->send_http_header;
9663:
9664: if ($#commands > 0) {
9665: &Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
9666: }
9667:
9668: # see what the symb is
9669:
9670: my $symb=$env{'form.symb'};
9671: unless ($symb) {
9672: (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
9673: $symb=&Apache::lonnet::symbread($url);
9674: }
9675: &Apache::lonenc::check_decrypt(\$symb);
9676:
9677: $ssi_error = 0;
9678: if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
9679: #
9680: # Not called from a resource, but inside a course
9681: #
9682: &startpage($request,undef,[],1,1);
9683: &select_problem($request);
9684: } else {
9685: if ($command eq 'submission' && $perm{'vgr'}) {
9686: my ($stuvcurrent,$stuvdisp,$versionform,$js);
9687: if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
9688: ($stuvcurrent,$stuvdisp,$versionform,$js) =
9689: &choose_task_version_form($symb,$env{'form.student'},
9690: $env{'form.userdom'});
9691: }
9692: &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
9693: if ($versionform) {
9694: $request->print($versionform);
9695: }
9696: $request->print('<br clear="all" />');
9697: ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
9698: } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
9699: my ($stuvcurrent,$stuvdisp,$versionform,$js) =
9700: &choose_task_version_form($symb,$env{'form.student'},
9701: $env{'form.userdom'},
9702: $env{'form.inhibitmenu'});
9703: &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
9704: if ($versionform) {
9705: $request->print($versionform);
9706: }
9707: $request->print('<br clear="all" />');
9708: $request->print(&show_previous_task_version($request,$symb));
9709: } elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
9710: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
9711: {href=>'',text=>'Select student'}],1,1);
9712: &pickStudentPage($request,$symb);
9713: } elsif ($command eq 'displayPage' && $perm{'vgr'}) {
9714: &startpage($request,$symb,
9715: [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
9716: {href=>'',text=>'Select student'},
9717: {href=>'',text=>'Grade student'}],1,1);
9718: &displayPage($request,$symb);
9719: } elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
9720: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
9721: {href=>'',text=>'Select student'},
9722: {href=>'',text=>'Grade student'},
9723: {href=>'',text=>'Store grades'}],1,1);
9724: &updateGradeByPage($request,$symb);
9725: } elsif ($command eq 'processGroup' && $perm{'vgr'}) {
9726: &startpage($request,$symb,[{href=>'',text=>'...'},
9727: {href=>'',text=>'Modify grades'}]);
9728: &processGroup($request,$symb);
9729: } elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
9730: &startpage($request,$symb);
9731: $request->print(&grading_menu($request,$symb));
9732: } elsif ($command eq 'individual' && $perm{'vgr'}) {
9733: &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
9734: $request->print(&submit_options($request,$symb));
9735: } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
9736: &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
9737: $request->print(&listStudents($request,$symb,'graded'));
9738: } elsif ($command eq 'table' && $perm{'vgr'}) {
9739: &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
9740: $request->print(&submit_options_table($request,$symb));
9741: } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
9742: &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
9743: $request->print(&submit_options_sequence($request,$symb));
9744: } elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
9745: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
9746: $request->print(&viewgrades($request,$symb));
9747: } elsif ($command eq 'handgrade' && $perm{'mgr'}) {
9748: &startpage($request,$symb,[{href=>'',text=>'...'},
9749: {href=>'',text=>'Store grades'}]);
9750: $request->print(&processHandGrade($request,$symb));
9751: } elsif ($command eq 'editgrades' && $perm{'mgr'}) {
9752: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
9753: {href=>&href_symb_cmd($symb,'viewgrades').'&group=all§ion=all&Status=Active',
9754: text=>"Modify grades"},
9755: {href=>'', text=>"Store grades"}]);
9756: $request->print(&editgrades($request,$symb));
9757: } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
9758: &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
9759: $request->print(&initialverifyreceipt($request,$symb));
9760: } elsif ($command eq 'verify' && $perm{'vgr'}) {
9761: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
9762: {href=>'',text=>'Verification Result'}]);
9763: $request->print(&verifyreceipt($request,$symb));
9764: } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
9765: &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
9766: $request->print(&process_clicker($request,$symb));
9767: } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
9768: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
9769: {href=>'', text=>'Process clicker file'}]);
9770: $request->print(&process_clicker_file($request,$symb));
9771: } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
9772: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
9773: {href=>'', text=>'Process clicker file'},
9774: {href=>'', text=>'Store grades'}]);
9775: $request->print(&assign_clicker_grades($request,$symb));
9776: } elsif ($command eq 'csvform' && $perm{'mgr'}) {
9777: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
9778: $request->print(&upcsvScores_form($request,$symb));
9779: } elsif ($command eq 'csvupload' && $perm{'mgr'}) {
9780: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
9781: $request->print(&csvupload($request,$symb));
9782: } elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
9783: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
9784: $request->print(&csvuploadmap($request,$symb));
9785: } elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
9786: if ($env{'form.associate'} ne 'Reverse Association') {
9787: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
9788: $request->print(&csvuploadoptions($request,$symb));
9789: } else {
9790: if ( $env{'form.upfile_associate'} ne 'reverse' ) {
9791: $env{'form.upfile_associate'} = 'reverse';
9792: } else {
9793: $env{'form.upfile_associate'} = 'forward';
9794: }
9795: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
9796: $request->print(&csvuploadmap($request,$symb));
9797: }
9798: } elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
9799: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
9800: $request->print(&csvuploadassign($request,$symb));
9801: } elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
9802: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9803: $request->print(&scantron_selectphase($request,undef,$symb));
9804: } elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
9805: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9806: $request->print(&scantron_do_warning($request,$symb));
9807: } elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
9808: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9809: $request->print(&scantron_validate_file($request,$symb));
9810: } elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
9811: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9812: $request->print(&scantron_process_students($request,$symb));
9813: } elsif ($command eq 'scantronupload' &&
9814: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
9815: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
9816: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9817: $request->print(&scantron_upload_scantron_data($request,$symb));
9818: } elsif ($command eq 'scantronupload_save' &&
9819: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
9820: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
9821: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9822: $request->print(&scantron_upload_scantron_data_save($request,$symb));
9823: } elsif ($command eq 'scantron_download' &&
9824: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
9825: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9826: $request->print(&scantron_download_scantron_data($request,$symb));
9827: } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
9828: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
9829: $request->print(&checkscantron_results($request,$symb));
9830: } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
9831: &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
9832: $request->print(&submit_options_download($request,$symb));
9833: } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
9834: &startpage($request,$symb,
9835: [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
9836: {href=>'', text=>'Download submissions'}]);
9837: &submit_download_link($request,$symb);
9838: } elsif ($command) {
9839: &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
9840: $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
9841: }
9842: }
9843: if ($ssi_error) {
9844: &ssi_print_error($request);
9845: }
9846: if ($env{'form.inhibitmenu'}) {
9847: $request->print(&Apache::loncommon::end_page());
9848: } else {
9849: &Apache::lonquickgrades::endGradeScreen($request);
9850: }
9851: &reset_caches();
9852: return OK;
9853: }
9854:
9855: 1;
9856:
9857: __END__;
9858:
9859:
9860: =head1 NAME
9861:
9862: Apache::grades
9863:
9864: =head1 SYNOPSIS
9865:
9866: Handles the viewing of grades.
9867:
9868: This is part of the LearningOnline Network with CAPA project
9869: described at http://www.lon-capa.org.
9870:
9871: =head1 OVERVIEW
9872:
9873: Do an ssi with retries:
9874: While I'd love to factor out this with the vesrion in lonprintout,
9875: 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
9876: I'm not quite ready to invent (e.g. an ssi_with_retry object).
9877:
9878: At least the logic that drives this has been pulled out into loncommon.
9879:
9880:
9881:
9882: ssi_with_retries - Does the server side include of a resource.
9883: if the ssi call returns an error we'll retry it up to
9884: the number of times requested by the caller.
9885: If we still have a proble, no text is appended to the
9886: output and we set some global variables.
9887: to indicate to the caller an SSI error occurred.
9888: All of this is supposed to deal with the issues described
9889: in LonCAPA BZ 5631 see:
9890: http://bugs.lon-capa.org/show_bug.cgi?id=5631
9891: by informing the user that this happened.
9892:
9893: Parameters:
9894: resource - The resource to include. This is passed directly, without
9895: interpretation to lonnet::ssi.
9896: form - The form hash parameters that guide the interpretation of the resource
9897:
9898: retries - Number of retries allowed before giving up completely.
9899: Returns:
9900: On success, returns the rendered resource identified by the resource parameter.
9901: Side Effects:
9902: The following global variables can be set:
9903: ssi_error - If an unrecoverable error occurred this becomes true.
9904: It is up to the caller to initialize this to false
9905: if desired.
9906: ssi_error_resource - If an unrecoverable error occurred, this is the value
9907: of the resource that could not be rendered by the ssi
9908: call.
9909: ssi_error_message - The error string fetched from the ssi response
9910: in the event of an error.
9911:
9912:
9913: =head1 HANDLER SUBROUTINE
9914:
9915: ssi_with_retries()
9916:
9917: =head1 SUBROUTINES
9918:
9919: =over
9920:
9921: =head1 Routines to display previous version of a Task for a specific student
9922:
9923: Tasks are graded pass/fail. Students who have yet to pass a particular Task
9924: can receive another opportunity. Access to tasks is slot-based. If a slot
9925: requires a proctor to check-in the student, a new version of the Task will
9926: be created when the student is checked in to the new opportunity.
9927:
9928: If a particular student has tried two or more versions of a particular task,
9929: the submission screen provides a user with vgr privileges (e.g., a Course
9930: Coordinator) the ability to display a previous version worked on by the
9931: student. By default, the current version is displayed. If a previous version
9932: has been selected for display, submission data are only shown that pertain
9933: to that particular version, and the interface to submit grades is not shown.
9934:
9935: =over 4
9936:
9937: =item show_previous_task_version()
9938:
9939: Displays a specified version of a student's Task, as the student sees it.
9940:
9941: Inputs: 2
9942: request - request object
9943: symb - unique symb for current instance of resource
9944:
9945: Output: None.
9946:
9947: Side Effects: calls &show_problem() to print version of Task, with
9948: version contained in form item: $env{'form.previousversion'}
9949:
9950: =item choose_task_version_form()
9951:
9952: Displays a web form used to select which version of a student's view of a
9953: Task should be displayed. Either launches a pop-up window, or replaces
9954: content in existing pop-up, or replaces page in main window.
9955:
9956: Inputs: 4
9957: symb - unique symb for current instance of resource
9958: uname - username of student
9959: udom - domain of student
9960: nomenu - 1 if display is in a pop-up window, and hence no menu
9961: breadcrumbs etc., are displayed
9962:
9963: Output: 4
9964: current - student's current version
9965: displayed - student's version being displayed
9966: result - scalar containing HTML for web form used to switch to
9967: a different version (or a link to close window, if pop-up).
9968: js - javascript for processing selection in versions web form
9969:
9970: Side Effects: None.
9971:
9972: =item previous_display_javascript()
9973:
9974: Inputs: 2
9975: nomenu - 1 if display is in a pop-up window, and hence no menu
9976: breadcrumbs etc., are displayed.
9977: current - student's current version number.
9978:
9979: Output: 1
9980: js - javascript for processing selection in versions web form.
9981:
9982: Side Effects: None.
9983:
9984: =back
9985:
9986: =head1 Routines to process bubblesheet data.
9987:
9988: =over 4
9989:
9990: =item scantron_get_correction() :
9991:
9992: Builds the interface screen to interact with the operator to fix a
9993: specific error condition in a specific scanline
9994:
9995: Arguments:
9996: $r - Apache request object
9997: $i - number of the current scanline
9998: $scan_record - hash ref as returned from &scantron_parse_scanline()
9999: $scan_config - hash ref as returned from &get_scantron_config()
10000: $line - full contents of the current scanline
10001: $error - error condition, valid values are
10002: 'incorrectCODE', 'duplicateCODE',
10003: 'doublebubble', 'missingbubble',
10004: 'duplicateID', 'incorrectID'
10005: $arg - extra information needed
10006: For errors:
10007: - duplicateID - paper number that this studentID was seen before on
10008: - duplicateCODE - array ref of the paper numbers this CODE was
10009: seen on before
10010: - incorrectCODE - current incorrect CODE
10011: - doublebubble - array ref of the bubble lines that have double
10012: bubble errors
10013: - missingbubble - array ref of the bubble lines that have missing
10014: bubble errors
10015:
10016: =item scantron_get_maxbubble() :
10017:
10018: Arguments:
10019: $nav_error - Reference to scalar which is a flag to indicate a
10020: failure to retrieve a navmap object.
10021: if $nav_error is set to 1 by scantron_get_maxbubble(), the
10022: calling routine should trap the error condition and display the warning
10023: found in &navmap_errormsg().
10024:
10025: $scantron_config - Reference to bubblesheet format configuration hash.
10026:
10027: Returns the maximum number of bubble lines that are expected to
10028: occur. Does this by walking the selected sequence rendering the
10029: resource and then checking &Apache::lonxml::get_problem_counter()
10030: for what the current value of the problem counter is.
10031:
10032: Caches the results to $env{'form.scantron_maxbubble'},
10033: $env{'form.scantron.bubble_lines.n'},
10034: $env{'form.scantron.first_bubble_line.n'} and
10035: $env{"form.scantron.sub_bubblelines.n"}
10036: which are the total number of bubble, lines, the number of bubble
10037: lines for response n and number of the first bubble line for response n,
10038: and a comma separated list of numbers of bubble lines for sub-questions
10039: (for optionresponse, matchresponse, and rankresponse items), for response n.
10040:
10041:
10042: =item scantron_validate_missingbubbles() :
10043:
10044: Validates all scanlines in the selected file to not have any
10045: answers that don't have bubbles that have not been verified
10046: to be bubble free.
10047:
10048: =item scantron_process_students() :
10049:
10050: Routine that does the actual grading of the bubblesheet information.
10051:
10052: The parsed scanline hash is added to %env
10053:
10054: Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
10055: foreach resource , with the form data of
10056:
10057: 'submitted' =>'scantron'
10058: 'grade_target' =>'grade',
10059: 'grade_username'=> username of student
10060: 'grade_domain' => domain of student
10061: 'grade_courseid'=> of course
10062: 'grade_symb' => symb of resource to grade
10063:
10064: This triggers a grading pass. The problem grading code takes care
10065: of converting the bubbled letter information (now in %env) into a
10066: valid submission.
10067:
10068: =item scantron_upload_scantron_data() :
10069:
10070: Creates the screen for adding a new bubblesheet data file to a course.
10071:
10072: =item scantron_upload_scantron_data_save() :
10073:
10074: Adds a provided bubble information data file to the course if user
10075: has the correct privileges to do so.
10076:
10077: =item valid_file() :
10078:
10079: Validates that the requested bubble data file exists in the course.
10080:
10081: =item scantron_download_scantron_data() :
10082:
10083: Shows a list of the three internal files (original, corrected,
10084: skipped) for a specific bubblesheet data file that exists in the
10085: course.
10086:
10087: =item scantron_validate_ID() :
10088:
10089: Validates all scanlines in the selected file to not have any
10090: invalid or underspecified student/employee IDs
10091:
10092: =item navmap_errormsg() :
10093:
10094: Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
10095: Should be called whenever the request to instantiate a navmap object fails.
10096:
10097: =back
10098:
10099: =back
10100:
10101: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>