1: # The LearningOnline Network with CAPA
2: # The LON-CAPA Grading handler
3: #
4: # $Id: grades.pm,v 1.769 2020/05/08 15:12:34 raeburn Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28:
29:
30:
31: package Apache::grades;
32: use strict;
33: use Apache::style;
34: use Apache::lonxml;
35: use Apache::lonnet;
36: use Apache::loncommon;
37: use Apache::lonhtmlcommon;
38: use Apache::lonnavmaps;
39: use Apache::lonhomework;
40: use Apache::lonpickcode;
41: use Apache::loncoursedata;
42: use Apache::lonmsg();
43: use Apache::Constants qw(:common :http);
44: use Apache::lonlocal;
45: use Apache::lonenc;
46: use Apache::lonstathelpers;
47: use Apache::lonquickgrades;
48: use Apache::bridgetask();
49: use Apache::lontexconvert();
50: use String::Similarity;
51: use HTML::Parser();
52: use File::MMagic;
53: use LONCAPA;
54:
55: use POSIX qw(floor);
56:
57:
58:
59: my %perm=();
60: my %old_essays=();
61:
62: # These variables are used to recover from ssi errors
63:
64: my $ssi_retries = 5;
65: my $ssi_error;
66: my $ssi_error_resource;
67: my $ssi_error_message;
68:
69:
70: sub ssi_with_retries {
71: my ($resource, $retries, %form) = @_;
72: my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
73: if ($response->is_error) {
74: $ssi_error = 1;
75: $ssi_error_resource = $resource;
76: $ssi_error_message = $response->code . " " . $response->message;
77: }
78:
79: return $content;
80:
81: }
82: #
83: # Prodcuces an ssi retry failure error message to the user:
84: #
85:
86: sub ssi_print_error {
87: my ($r) = @_;
88: my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
89: $r->print('
90: <br />
91: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
92: <p>
93: '.&mt('Unable to retrieve a resource from a server:').'<br />
94: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
95: '.&mt('Error:').' '.$ssi_error_message.'
96: </p>
97: <p>'.
98: &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 />'.
99: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
100: '</p>');
101: return;
102: }
103:
104: #
105: # --- Retrieve the parts from the metadata file.---
106: # Returns an array of everything that the resources stores away
107: #
108:
109: sub getpartlist {
110: my ($symb,$errorref) = @_;
111:
112: my $navmap = Apache::lonnavmaps::navmap->new();
113: unless (ref($navmap)) {
114: if (ref($errorref)) {
115: $$errorref = 'navmap';
116: return;
117: }
118: }
119: my $res = $navmap->getBySymb($symb);
120: my $partlist = $res->parts();
121: my $url = $res->src();
122: my $toolsymb;
123: if ($url =~ /ext\.tool$/) {
124: $toolsymb = $symb;
125: }
126: my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys',$toolsymb));
127:
128: my @stores;
129: foreach my $part (@{ $partlist }) {
130: foreach my $key (@metakeys) {
131: if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
132: }
133: }
134: return @stores;
135: }
136:
137: #--- Format fullname, username:domain if different for display
138: #--- Use anywhere where the student names are listed
139: sub nameUserString {
140: my ($type,$fullname,$uname,$udom) = @_;
141: if ($type eq 'header') {
142: return '<b> '.&mt('Fullname').' </b><span class="LC_internal_info">('.&mt('Username').')</span>';
143: } else {
144: return ' '.$fullname.'<span class="LC_internal_info"> ('.$uname.
145: ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
146: }
147: }
148:
149: #--- Get the partlist and the response type for a given problem. ---
150: #--- Indicate if a response type is coded handgraded or not. ---
151: #--- Sets response_error pointer to "1" if navmaps object broken ---
152: sub response_type {
153: my ($symb,$response_error) = @_;
154:
155: my $navmap = Apache::lonnavmaps::navmap->new();
156: unless (ref($navmap)) {
157: if (ref($response_error)) {
158: $$response_error = 1;
159: }
160: return;
161: }
162: my $res = $navmap->getBySymb($symb);
163: unless (ref($res)) {
164: $$response_error = 1;
165: return;
166: }
167: my $partlist = $res->parts();
168: my %vPart =
169: map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
170: my (%response_types,%handgrade);
171: foreach my $part (@{ $partlist }) {
172: next if (%vPart && !exists($vPart{$part}));
173:
174: my @types = $res->responseType($part);
175: my @ids = $res->responseIds($part);
176: for (my $i=0; $i < scalar(@ids); $i++) {
177: $response_types{$part}{$ids[$i]} = $types[$i];
178: $handgrade{$part.'_'.$ids[$i]} =
179: &Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
180: '.handgrade',$symb);
181: }
182: }
183: return ($partlist,\%handgrade,\%response_types);
184: }
185:
186: sub flatten_responseType {
187: my ($responseType) = @_;
188: my @part_response_id =
189: map {
190: my $part = $_;
191: map {
192: [$part,$_]
193: } sort(keys(%{ $responseType->{$part} }));
194: } sort(keys(%$responseType));
195: return @part_response_id;
196: }
197:
198: sub get_display_part {
199: my ($partID,$symb)=@_;
200: my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
201: if (defined($display) and $display ne '') {
202: $display.= ' (<span class="LC_internal_info">'
203: .&mt('Part ID: [_1]',$partID).'</span>)';
204: } else {
205: $display=$partID;
206: }
207: return $display;
208: }
209:
210: sub reset_caches {
211: &reset_analyze_cache();
212: &reset_perm();
213: &reset_old_essays();
214: }
215:
216: {
217: my %analyze_cache;
218: my %analyze_cache_formkeys;
219:
220: sub reset_analyze_cache {
221: undef(%analyze_cache);
222: undef(%analyze_cache_formkeys);
223: }
224:
225: sub get_analyze {
226: my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
227: my $key = "$symb\0$uname\0$udom";
228: if ($type eq 'randomizetry') {
229: if ($trial ne '') {
230: $key .= "\0".$trial;
231: }
232: }
233: if (exists($analyze_cache{$key})) {
234: my $getupdate = 0;
235: if (ref($add_to_hash) eq 'HASH') {
236: foreach my $item (keys(%{$add_to_hash})) {
237: if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
238: if (!exists($analyze_cache_formkeys{$key}{$item})) {
239: $getupdate = 1;
240: last;
241: }
242: } else {
243: $getupdate = 1;
244: }
245: }
246: }
247: if (!$getupdate) {
248: return $analyze_cache{$key};
249: }
250: }
251:
252: my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
253: $url=&Apache::lonnet::clutter($url);
254: my %form = ('grade_target' => 'analyze',
255: 'grade_domain' => $udom,
256: 'grade_symb' => $symb,
257: 'grade_courseid' => $env{'request.course.id'},
258: 'grade_username' => $uname,
259: 'grade_noincrement' => $no_increment);
260: if ($bubbles_per_row ne '') {
261: $form{'bubbles_per_row'} = $bubbles_per_row;
262: }
263: if ($type eq 'randomizetry') {
264: $form{'grade_questiontype'} = $type;
265: if ($rndseed ne '') {
266: $form{'grade_rndseed'} = $rndseed;
267: }
268: }
269: if (ref($add_to_hash)) {
270: %form = (%form,%{$add_to_hash});
271: }
272: my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
273: (undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
274: my %analyze=&Apache::lonnet::str2hash($subresult);
275: if (ref($add_to_hash) eq 'HASH') {
276: $analyze_cache_formkeys{$key} = $add_to_hash;
277: } else {
278: $analyze_cache_formkeys{$key} = {};
279: }
280: return $analyze_cache{$key} = \%analyze;
281: }
282:
283: sub get_order {
284: my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
285: my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
286: return $analyze->{"$partid.$respid.shown"};
287: }
288:
289: sub get_radiobutton_correct_foil {
290: my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
291: my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
292: my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
293: if (ref($foils) eq 'ARRAY') {
294: foreach my $foil (@{$foils}) {
295: if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
296: return $foil;
297: }
298: }
299: }
300: }
301:
302: sub scantron_partids_tograde {
303: my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row,$scancode) = @_;
304: my (%analysis,@parts);
305: if (ref($resource)) {
306: my $symb = $resource->symb();
307: my $add_to_form;
308: if ($check_for_randomlist) {
309: $add_to_form = { 'check_parts_withrandomlist' => 1,};
310: }
311: if ($scancode) {
312: if (ref($add_to_form) eq 'HASH') {
313: $add_to_form->{'code_for_randomlist'} = $scancode;
314: } else {
315: $add_to_form = { 'code_for_randomlist' => $scancode,};
316: }
317: }
318: my $analyze =
319: &get_analyze($symb,$uname,$udom,undef,$add_to_form,
320: undef,undef,undef,$bubbles_per_row);
321: if (ref($analyze) eq 'HASH') {
322: %analysis = %{$analyze};
323: }
324: if (ref($analysis{'parts'}) eq 'ARRAY') {
325: foreach my $part (@{$analysis{'parts'}}) {
326: my ($id,$respid) = split(/\./,$part);
327: if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
328: push(@parts,$part);
329: }
330: }
331: }
332: }
333: return (\%analysis,\@parts);
334: }
335:
336: }
337:
338: #--- Clean response type for display
339: #--- Currently filters option/rank/radiobutton/match/essay/Task
340: # response types only.
341: sub cleanRecord {
342: my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
343: $uname,$udom,$type,$trial,$rndseed) = @_;
344: my $grayFont = '<span class="LC_internal_info">';
345: if ($response =~ /^(option|rank)$/) {
346: my %answer=&Apache::lonnet::str2hash($answer);
347: my @answer = %answer;
348: %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
349: my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
350: my ($toprow,$bottomrow);
351: foreach my $foil (@$order) {
352: if ($grading{$foil} == 1) {
353: $toprow.='<td><b>'.$answer{$foil}.' </b></td>';
354: } else {
355: $toprow.='<td><i>'.$answer{$foil}.' </i></td>';
356: }
357: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
358: }
359: return '<blockquote><table border="1">'.
360: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
361: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
362: $bottomrow.'</tr></table></blockquote>';
363: } elsif ($response eq 'match') {
364: my %answer=&Apache::lonnet::str2hash($answer);
365: my @answer = %answer;
366: %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
367: my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
368: my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
369: my ($toprow,$middlerow,$bottomrow);
370: foreach my $foil (@$order) {
371: my $item=shift(@items);
372: if ($grading{$foil} == 1) {
373: $toprow.='<td><b>'.$item.' </b></td>';
374: $middlerow.='<td><b>'.$grayFont.$answer{$foil}.' </span></b></td>';
375: } else {
376: $toprow.='<td><i>'.$item.' </i></td>';
377: $middlerow.='<td><i>'.$grayFont.$answer{$foil}.' </span></i></td>';
378: }
379: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
380: }
381: return '<blockquote><table border="1">'.
382: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
383: '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
384: $middlerow.'</tr>'.
385: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
386: $bottomrow.'</tr></table></blockquote>';
387: } elsif ($response eq 'radiobutton') {
388: my %answer=&Apache::lonnet::str2hash($answer);
389: my @answer = %answer;
390: %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
391: my ($toprow,$bottomrow);
392: my $correct =
393: &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
394: foreach my $foil (@$order) {
395: if (exists($answer{$foil})) {
396: if ($foil eq $correct) {
397: $toprow.='<td><b>'.&mt('true').'</b></td>';
398: } else {
399: $toprow.='<td><i>'.&mt('true').'</i></td>';
400: }
401: } else {
402: $toprow.='<td>'.&mt('false').'</td>';
403: }
404: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
405: }
406: return '<blockquote><table border="1">'.
407: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
408: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
409: $bottomrow.'</tr></table></blockquote>';
410: } elsif ($response eq 'essay') {
411: if (! exists ($env{'form.'.$symb})) {
412: my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
413: $env{'course.'.$env{'request.course.id'}.'.domain'},
414: $env{'course.'.$env{'request.course.id'}.'.num'});
415:
416: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
417: $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
418: $env{'form.kwclr'} = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
419: $env{'form.kwsize'} = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
420: $env{'form.kwstyle'} = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
421: $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
422: }
423: $answer = &Apache::lontexconvert::msgtexconverted($answer);
424: return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
425: } elsif ( $response eq 'organic') {
426: my $result=&mt('Smile representation: [_1]',
427: '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
428: my $jme=$record->{$version."resource.$partid.$respid.molecule"};
429: $result.=&Apache::chemresponse::jme_img($jme,$answer,400);
430: return $result;
431: } elsif ( $response eq 'Task') {
432: if ( $answer eq 'SUBMITTED') {
433: my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
434: my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
435: return $result;
436: } elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
437: my @matches = grep(/^\Q$version\E.*?\.instance$/,
438: keys(%{$record}));
439: return join('<br />',($version,@matches));
440:
441:
442: } else {
443: my $result =
444: '<p>'
445: .&mt('Overall result: [_1]',
446: $record->{$version."resource.$respid.$partid.status"})
447: .'</p>';
448:
449: $result .= '<ul>';
450: my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
451: keys(%{$record}));
452: foreach my $grade (sort(@grade)) {
453: my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
454: $result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
455: $dim, $record->{$grade}).
456: '</li>';
457: }
458: $result.='</ul>';
459: return $result;
460: }
461: } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
462: # Respect multiple input fields, see Bug #5409
463: $answer =
464: &Apache::loncommon::format_previous_attempt_value('submission',
465: $answer);
466: return $answer;
467: }
468: return &HTML::Entities::encode($answer, '"<>&');
469: }
470:
471: #-- A couple of common js functions
472: sub commonJSfunctions {
473: my $request = shift;
474: $request->print(&Apache::lonhtmlcommon::scripttag(<<COMMONJSFUNCTIONS));
475: function radioSelection(radioButton) {
476: var selection=null;
477: if (radioButton.length > 1) {
478: for (var i=0; i<radioButton.length; i++) {
479: if (radioButton[i].checked) {
480: return radioButton[i].value;
481: }
482: }
483: } else {
484: if (radioButton.checked) return radioButton.value;
485: }
486: return selection;
487: }
488:
489: function pullDownSelection(selectOne) {
490: var selection="";
491: if (selectOne.length > 1) {
492: for (var i=0; i<selectOne.length; i++) {
493: if (selectOne[i].selected) {
494: return selectOne[i].value;
495: }
496: }
497: } else {
498: // only one value it must be the selected one
499: return selectOne.value;
500: }
501: }
502: COMMONJSFUNCTIONS
503: }
504:
505: #--- Dumps the class list with usernames,list of sections,
506: #--- section, ids and fullnames for each user.
507: sub getclasslist {
508: my ($getsec,$filterbyaccstatus,$getgroup,$symb,$submitonly,$filterbysubmstatus) = @_;
509: my @getsec;
510: my @getgroup;
511: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
512: if (!ref($getsec)) {
513: if ($getsec ne '' && $getsec ne 'all') {
514: @getsec=($getsec);
515: }
516: } else {
517: @getsec=@{$getsec};
518: }
519: if (grep(/^all$/,@getsec)) { undef(@getsec); }
520: if (!ref($getgroup)) {
521: if ($getgroup ne '' && $getgroup ne 'all') {
522: @getgroup=($getgroup);
523: }
524: } else {
525: @getgroup=@{$getgroup};
526: }
527: if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
528:
529: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
530: # Bail out if we were unable to get the classlist
531: return if (! defined($classlist));
532: &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
533: #
534: my %sections;
535: my %fullnames;
536: my ($cdom,$cnum,$partlist);
537: if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
538: $cdom = $env{"course.$env{'request.course.id'}.domain"};
539: $cnum = $env{"course.$env{'request.course.id'}.num"};
540: my $res_error;
541: ($partlist,my $handgrade,my $responseType) = &response_type($symb,\$res_error);
542: }
543: foreach my $student (keys(%$classlist)) {
544: my $end =
545: $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
546: my $start =
547: $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
548: my $id =
549: $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
550: my $section =
551: $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
552: my $fullname =
553: $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
554: my $status =
555: $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
556: my $group =
557: $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
558: # filter students according to status selected
559: if ($filterbyaccstatus && (!($stu_status =~ /Any/))) {
560: if (!($stu_status =~ $status)) {
561: delete($classlist->{$student});
562: next;
563: }
564: }
565: # filter students according to groups selected
566: my @stu_groups = split(/,/,$group);
567: if (@getgroup) {
568: my $exclude = 1;
569: foreach my $grp (@getgroup) {
570: foreach my $stu_group (@stu_groups) {
571: if ($stu_group eq $grp) {
572: $exclude = 0;
573: }
574: }
575: if (($grp eq 'none') && !$group) {
576: $exclude = 0;
577: }
578: }
579: if ($exclude) {
580: delete($classlist->{$student});
581: next;
582: }
583: }
584: if (($filterbysubmstatus) && ($submitonly ne 'all') && ($symb ne '')) {
585: my $udom =
586: $classlist->{$student}->[&Apache::loncoursedata::CL_SDOM()];
587: my $uname =
588: $classlist->{$student}->[&Apache::loncoursedata::CL_SNAME()];
589: if (($symb ne '') && ($udom ne '') && ($uname ne '')) {
590: if ($submitonly eq 'queued') {
591: my %queue_status =
592: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
593: $udom,$uname);
594: if (!defined($queue_status{'gradingqueue'})) {
595: delete($classlist->{$student});
596: next;
597: }
598: } else {
599: my (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
600: my $submitted = 0;
601: my $graded = 0;
602: my $incorrect = 0;
603: foreach (keys(%status)) {
604: $submitted = 1 if ($status{$_} ne 'nothing');
605: $graded = 1 if ($status{$_} =~ /^ungraded/);
606: $incorrect = 1 if ($status{$_} =~ /^incorrect/);
607:
608: my ($foo,$partid,$foo1) = split(/\./,$_);
609: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
610: $submitted = 0;
611: }
612: }
613: if (!$submitted && ($submitonly eq 'yes' ||
614: $submitonly eq 'incorrect' ||
615: $submitonly eq 'graded')) {
616: delete($classlist->{$student});
617: next;
618: } elsif (!$graded && ($submitonly eq 'graded')) {
619: delete($classlist->{$student});
620: next;
621: } elsif (!$incorrect && $submitonly eq 'incorrect') {
622: delete($classlist->{$student});
623: next;
624: }
625: }
626: }
627: }
628: $section = ($section ne '' ? $section : 'none');
629: if (&canview($section)) {
630: if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
631: $sections{$section}++;
632: if ($classlist->{$student}) {
633: $fullnames{$student}=$fullname;
634: }
635: } else {
636: delete($classlist->{$student});
637: }
638: } else {
639: delete($classlist->{$student});
640: }
641: }
642: my @sections = sort(keys(%sections));
643: return ($classlist,\@sections,\%fullnames);
644: }
645:
646: sub canmodify {
647: my ($sec)=@_;
648: if ($perm{'mgr'}) {
649: if (!defined($perm{'mgr_section'})) {
650: # can modify whole class
651: return 1;
652: } else {
653: if ($sec eq $perm{'mgr_section'}) {
654: #can modify the requested section
655: return 1;
656: } else {
657: # can't modify the requested section
658: return 0;
659: }
660: }
661: }
662: #can't modify
663: return 0;
664: }
665:
666: sub canview {
667: my ($sec)=@_;
668: if ($perm{'vgr'}) {
669: if (!defined($perm{'vgr_section'})) {
670: # can view whole class
671: return 1;
672: } else {
673: if ($sec eq $perm{'vgr_section'}) {
674: #can view the requested section
675: return 1;
676: } else {
677: # can't view the requested section
678: return 0;
679: }
680: }
681: }
682: #can't view
683: return 0;
684: }
685:
686: #--- Retrieve the grade status of a student for all the parts
687: sub student_gradeStatus {
688: my ($symb,$udom,$uname,$partlist) = @_;
689: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
690: my %partstatus = ();
691: foreach (@$partlist) {
692: my ($status,undef) = split(/_/,$record{"resource.$_.solved"},2);
693: $status = 'nothing' if ($status eq '');
694: $partstatus{$_} = $status;
695: my $subkey = "resource.$_.submitted_by";
696: $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
697: }
698: return %partstatus;
699: }
700:
701: # hidden form and javascript that calls the form
702: # Use by verifyscript and viewgrades
703: # Shows a student's view of problem and submission
704: sub jscriptNform {
705: my ($symb) = @_;
706: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
707: my $jscript= &Apache::lonhtmlcommon::scripttag(
708: ' function viewOneStudent(user,domain) {'."\n".
709: ' document.onestudent.student.value = user;'."\n".
710: ' document.onestudent.userdom.value = domain;'."\n".
711: ' document.onestudent.submit();'."\n".
712: ' }'."\n".
713: "\n");
714: $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
715: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
716: '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
717: '<input type="hidden" name="command" value="submission" />'."\n".
718: '<input type="hidden" name="student" value="" />'."\n".
719: '<input type="hidden" name="userdom" value="" />'."\n".
720: '</form>'."\n";
721: return $jscript;
722: }
723:
724:
725:
726: # Given the score (as a number [0-1] and the weight) what is the final
727: # point value? This function will round to the nearest tenth, third,
728: # or quarter if one of those is within the tolerance of .00001.
729: sub compute_points {
730: my ($score, $weight) = @_;
731:
732: my $tolerance = .00001;
733: my $points = $score * $weight;
734:
735: # Check for nearness to 1/x.
736: my $check_for_nearness = sub {
737: my ($factor) = @_;
738: my $num = ($points * $factor) + $tolerance;
739: my $floored_num = floor($num);
740: if ($num - $floored_num < 2 * $tolerance * $factor) {
741: return $floored_num / $factor;
742: }
743: return $points;
744: };
745:
746: $points = $check_for_nearness->(10);
747: $points = $check_for_nearness->(3);
748: $points = $check_for_nearness->(4);
749:
750: return $points;
751: }
752:
753: #------------------ End of general use routines --------------------
754:
755: #
756: # Find most similar essay
757: #
758:
759: sub most_similar {
760: my ($uname,$udom,$symb,$uessay)=@_;
761:
762: unless ($symb) { return ''; }
763:
764: unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
765:
766: # ignore spaces and punctuation
767:
768: $uessay=~s/\W+/ /gs;
769:
770: # ignore empty submissions (occuring when only files are sent)
771:
772: unless ($uessay=~/\w+/s) { return ''; }
773:
774: # these will be returned. Do not care if not at least 50 percent similar
775: my $limit=0.6;
776: my $sname='';
777: my $sdom='';
778: my $scrsid='';
779: my $sessay='';
780: # go through all essays ...
781: foreach my $tkey (keys(%{$old_essays{$symb}})) {
782: my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
783: # ... except the same student
784: next if (($tname eq $uname) && ($tdom eq $udom));
785: my $tessay=$old_essays{$symb}{$tkey};
786: $tessay=~s/\W+/ /gs;
787: # String similarity gives up if not even limit
788: my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
789: # Found one
790: if ($tsimilar>$limit) {
791: $limit=$tsimilar;
792: $sname=$tname;
793: $sdom=$tdom;
794: $scrsid=$tcrsid;
795: $sessay=$old_essays{$symb}{$tkey};
796: }
797: }
798: if ($limit>0.6) {
799: return ($sname,$sdom,$scrsid,$sessay,$limit);
800: } else {
801: return ('','','','',0);
802: }
803: }
804:
805: #-------------------------------------------------------------------
806:
807: #------------------------------------ Receipt Verification Routines
808: #
809:
810: sub initialverifyreceipt {
811: my ($request,$symb) = @_;
812: &commonJSfunctions($request);
813: return '<form name="gradingMenu" action=""><input type="submit" value="'.&mt('Verify Receipt Number.').'" />'.
814: &Apache::lonnet::recprefix($env{'request.course.id'}).
815: '-<input type="text" name="receipt" size="4" />'.
816: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
817: '<input type="hidden" name="command" value="verify" />'.
818: "</form>\n";
819: }
820:
821: #--- Check whether a receipt number is valid.---
822: sub verifyreceipt {
823: my ($request,$symb) = @_;
824:
825: my $courseid = $env{'request.course.id'};
826: my $receipt = &Apache::lonnet::recprefix($courseid).'-'.
827: $env{'form.receipt'};
828: $receipt =~ s/[^\-\d]//g;
829:
830: my $title =
831: '<h3><span class="LC_info">'.
832: &mt('Verifying Receipt Number [_1]',$receipt).
833: '</span></h3>'."\n";
834:
835: my ($string,$contents,$matches) = ('','',0);
836: my (undef,undef,$fullname) = &getclasslist('all','0');
837:
838: my $receiptparts=0;
839: if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
840: $env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
841: my $parts=['0'];
842: if ($receiptparts) {
843: my $res_error;
844: ($parts)=&response_type($symb,\$res_error);
845: if ($res_error) {
846: return &navmap_errormsg();
847: }
848: }
849:
850: my $header =
851: &Apache::loncommon::start_data_table().
852: &Apache::loncommon::start_data_table_header_row().
853: '<th> '.&mt('Fullname').' </th>'."\n".
854: '<th> '.&mt('Username').' </th>'."\n".
855: '<th> '.&mt('Domain').' </th>';
856: if ($receiptparts) {
857: $header.='<th> '.&mt('Problem Part').' </th>';
858: }
859: $header.=
860: &Apache::loncommon::end_data_table_header_row();
861:
862: foreach (sort
863: {
864: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
865: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
866: }
867: return $a cmp $b;
868: } (keys(%$fullname))) {
869: my ($uname,$udom)=split(/\:/);
870: foreach my $part (@$parts) {
871: if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
872: $contents.=
873: &Apache::loncommon::start_data_table_row().
874: '<td> '."\n".
875: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
876: '\');" target="_self">'.$$fullname{$_}.'</a> </td>'."\n".
877: '<td> '.$uname.' </td>'.
878: '<td> '.$udom.' </td>';
879: if ($receiptparts) {
880: $contents.='<td> '.$part.' </td>';
881: }
882: $contents.=
883: &Apache::loncommon::end_data_table_row()."\n";
884:
885: $matches++;
886: }
887: }
888: }
889: if ($matches == 0) {
890: $string = $title
891: .'<p class="LC_warning">'
892: .&mt('No match found for the above receipt number.')
893: .'</p>';
894: } else {
895: $string = &jscriptNform($symb).$title.
896: '<p>'.
897: &mt('The above receipt number matches the following [quant,_1,student].',$matches).
898: '</p>'.
899: $header.
900: $contents.
901: &Apache::loncommon::end_data_table()."\n";
902: }
903: return $string;
904: }
905:
906: #--- This is called by a number of programs.
907: #--- Called from the Grading Menu - View/Grade an individual student
908: #--- Also called directly when one clicks on the subm button
909: # on the problem page.
910: sub listStudents {
911: my ($request,$symb,$submitonly) = @_;
912:
913: my $is_tool = ($symb =~ /ext\.tool$/);
914: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
915: my $cnum = $env{"course.$env{'request.course.id'}.num"};
916: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
917: my $getgroup = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
918: unless ($submitonly) {
919: $submitonly = $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
920: }
921:
922: my $result='';
923: my $res_error;
924: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
925:
926: my %js_lt = &Apache::lonlocal::texthash (
927: 'multiple' => 'Please select a student or group of students before clicking on the Next button.',
928: 'single' => 'Please select the student before clicking on the Next button.',
929: );
930: &js_escape(\%js_lt);
931: $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
932: function checkSelect(checkBox) {
933: var ctr=0;
934: var sense="";
935: if (checkBox.length > 1) {
936: for (var i=0; i<checkBox.length; i++) {
937: if (checkBox[i].checked) {
938: ctr++;
939: }
940: }
941: sense = '$js_lt{'multiple'}';
942: } else {
943: if (checkBox.checked) {
944: ctr = 1;
945: }
946: sense = '$js_lt{'single'}';
947: }
948: if (ctr == 0) {
949: alert(sense);
950: return false;
951: }
952: document.gradesub.submit();
953: }
954:
955: function reLoadList(formname) {
956: if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
957: formname.command.value = 'submission';
958: formname.submit();
959: }
960: LISTJAVASCRIPT
961:
962: &commonJSfunctions($request);
963: $request->print($result);
964:
965: my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
966: "\n";
967:
968: $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
969: unless ($is_tool) {
970: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
971: .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
972: .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
973: .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
974: .&Apache::lonhtmlcommon::row_closure();
975: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
976: .'<label><input type="radio" name="vAns" value="no" /> '.&mt('no').' </label>'."\n"
977: .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
978: .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
979: .&Apache::lonhtmlcommon::row_closure();
980: }
981:
982: my $submission_options;
983: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
984: my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
985: $env{'form.Status'} = $saveStatus;
986: my %optiontext;
987: if ($is_tool) {
988: %optiontext = &Apache::lonlocal::texthash (
989: lastonly => 'last transaction',
990: last => 'last transaction with details',
991: datesub => 'all transactions',
992: all => 'all transactions with details',
993: );
994: } else {
995: %optiontext = &Apache::lonlocal::texthash (
996: lastonly => 'last submission',
997: last => 'last submission with details',
998: datesub => 'all submissions',
999: all => 'all submissions with details',
1000: );
1001: }
1002: $submission_options.=
1003: '<span class="LC_nobreak">'.
1004: '<label><input type="radio" name="lastSub" value="lastonly" /> '.
1005: $optiontext{'lastonly'}.' </label></span>'."\n".
1006: '<span class="LC_nobreak">'.
1007: '<label><input type="radio" name="lastSub" value="last" /> '.
1008: $optiontext{'last'}.' </label></span>'."\n".
1009: '<span class="LC_nobreak">'.
1010: '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.
1011: $optiontext{'datesub'}.'</label></span>'."\n".
1012: '<span class="LC_nobreak">'.
1013: '<label><input type="radio" name="lastSub" value="all" /> '.
1014: $optiontext{'all'}.'</label></span>';
1015: my $viewtitle;
1016: if ($is_tool) {
1017: $viewtitle = &mt('View Transactions');
1018: } else {
1019: $viewtitle = &mt('View Submissions');
1020: }
1021: $gradeTable .= &Apache::lonhtmlcommon::row_title($viewtitle)
1022: .$submission_options
1023: .&Apache::lonhtmlcommon::row_closure();
1024:
1025: my $closure;
1026: if (($is_tool) && (exists($env{'form.Status'}))) {
1027: $closure = 1;
1028: }
1029: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
1030: .'<select name="increment">'
1031: .'<option value="1">'.&mt('Whole Points').'</option>'
1032: .'<option value=".5">'.&mt('Half Points').'</option>'
1033: .'<option value=".25">'.&mt('Quarter Points').'</option>'
1034: .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
1035: .'</select>'
1036: .&Apache::lonhtmlcommon::row_closure($closure);
1037:
1038: $gradeTable .=
1039: &build_section_inputs().
1040: '<input type="hidden" name="submitonly" value="'.$submitonly.'" />'."\n".
1041: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1042: '<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
1043:
1044: if (exists($env{'form.Status'})) {
1045: $gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1046: } else {
1047: if ($is_tool) {
1048: $closure = 1;
1049: }
1050: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
1051: .&Apache::lonhtmlcommon::StatusOptions(
1052: $saveStatus,undef,1,'javascript:reLoadList(this.form);')
1053: .&Apache::lonhtmlcommon::row_closure($closure);
1054: }
1055:
1056: unless ($is_tool) {
1057: $closure = 1;
1058: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
1059: .'<input type="checkbox" name="checkPlag" checked="checked" />'
1060: .&Apache::lonhtmlcommon::row_closure($closure);
1061: }
1062: $gradeTable .= &Apache::lonhtmlcommon::end_pick_box();
1063: my $regrademsg;
1064: if ($is_tool) {
1065: $regrademsg =&mt("To view/grade/regrade, click on the check box(es) next to the student's name(s). Then click on the Next button.");
1066: } else {
1067: $regrademsg = &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.");
1068: }
1069: $gradeTable .= '<p>'
1070: .$regrademsg."\n"
1071: .'<input type="hidden" name="command" value="processGroup" />'
1072: .'</p>';
1073:
1074: # checkall buttons
1075: $gradeTable.=&check_script('gradesub', 'stuinfo');
1076: $gradeTable.='<input type="button" '."\n".
1077: 'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
1078: 'value="'.&mt('Next').' →" /> <br />'."\n";
1079: $gradeTable.=&check_buttons();
1080: my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1081: $gradeTable.= &Apache::loncommon::start_data_table().
1082: &Apache::loncommon::start_data_table_header_row();
1083: my $loop = 0;
1084: while ($loop < 2) {
1085: $gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
1086: '<th>'.&nameUserString('header').' '.&mt('Section/Group').'</th>';
1087: if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1088: foreach my $part (sort(@$partlist)) {
1089: my $display_part=
1090: &get_display_part((split(/_/,$part))[0],$symb);
1091: $gradeTable.=
1092: '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1093: }
1094: } elsif ($submitonly eq 'queued') {
1095: $gradeTable.='<th>'.&mt('Queue Status').' </th>';
1096: }
1097: $loop++;
1098: # $gradeTable.='<td></td>' if ($loop%2 ==1);
1099: }
1100: $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1101:
1102: my $ctr = 0;
1103: foreach my $student (sort
1104: {
1105: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
1106: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
1107: }
1108: return $a cmp $b;
1109: }
1110: (keys(%$fullname))) {
1111: my ($uname,$udom) = split(/:/,$student);
1112:
1113: my %status = ();
1114:
1115: if ($submitonly eq 'queued') {
1116: my %queue_status =
1117: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
1118: $udom,$uname);
1119: next if (!defined($queue_status{'gradingqueue'}));
1120: $status{'gradingqueue'} = $queue_status{'gradingqueue'};
1121: }
1122:
1123: if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1124: (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1125: my $submitted = 0;
1126: my $graded = 0;
1127: my $incorrect = 0;
1128: foreach (keys(%status)) {
1129: $submitted = 1 if ($status{$_} ne 'nothing');
1130: $graded = 1 if ($status{$_} =~ /^ungraded/);
1131: $incorrect = 1 if ($status{$_} =~ /^incorrect/);
1132:
1133: my ($foo,$partid,$foo1) = split(/\./,$_);
1134: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1135: $submitted = 0;
1136: my ($part)=split(/\./,$partid);
1137: $gradeTable.='<input type="hidden" name="'.
1138: $student.':'.$part.':submitted_by" value="'.
1139: $status{'resource.'.$partid.'.submitted_by'}.'" />';
1140: }
1141: }
1142:
1143: next if (!$submitted && ($submitonly eq 'yes' ||
1144: $submitonly eq 'incorrect' ||
1145: $submitonly eq 'graded'));
1146: next if (!$graded && ($submitonly eq 'graded'));
1147: next if (!$incorrect && $submitonly eq 'incorrect');
1148: }
1149:
1150: $ctr++;
1151: my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1152: my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1153: if ( $perm{'vgr'} eq 'F' ) {
1154: if ($ctr%2 ==1) {
1155: $gradeTable.= &Apache::loncommon::start_data_table_row();
1156: }
1157: $gradeTable.='<td align="right">'.$ctr.' </td>'.
1158: '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1159: $student.':'.$$fullname{$student}.':::SECTION'.$section.
1160: ') " /> </label></td>'."\n".'<td>'.
1161: &nameUserString(undef,$$fullname{$student},$uname,$udom).
1162: ' '.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1163:
1164: if ($submitonly ne 'all') {
1165: foreach (sort(keys(%status))) {
1166: next if ($_ =~ /^resource.*?submitted_by$/);
1167: $gradeTable.='<td align="center"> '.&mt($status{$_}).' </td>'."\n";
1168: }
1169: }
1170: # $gradeTable.='<td></td>' if ($ctr%2 ==1);
1171: if ($ctr%2 ==0) {
1172: $gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
1173: }
1174: }
1175: }
1176: if ($ctr%2 ==1) {
1177: $gradeTable.='<td> </td><td> </td><td> </td>';
1178: if (($submitonly ne 'queued') && ($submitonly ne 'all')) {
1179: foreach (@$partlist) {
1180: $gradeTable.='<td> </td>';
1181: }
1182: } elsif ($submitonly eq 'queued') {
1183: $gradeTable.='<td> </td>';
1184: }
1185: $gradeTable.=&Apache::loncommon::end_data_table_row();
1186: }
1187:
1188: $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1189: '<input type="button" '.
1190: 'onclick="javascript:checkSelect(this.form.stuinfo);" '.
1191: 'value="'.&mt('Next').' →" /></form>'."\n";
1192: if ($ctr == 0) {
1193: my $num_students=(scalar(keys(%$fullname)));
1194: if ($num_students eq 0) {
1195: $gradeTable='<br /> <span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1196: } else {
1197: my $submissions='submissions';
1198: if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
1199: if ($submitonly eq 'graded' ) { $submissions = 'ungraded submissions'; }
1200: if ($submitonly eq 'queued' ) { $submissions = 'queued submissions'; }
1201: $gradeTable='<br /> <span class="LC_warning">'.
1202: &mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
1203: $num_students).
1204: '</span><br />';
1205: }
1206: } elsif ($ctr == 1) {
1207: $gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1208: }
1209: $request->print($gradeTable);
1210: return '';
1211: }
1212:
1213: #---- Called from the listStudents routine
1214:
1215: sub check_script {
1216: my ($form,$type) = @_;
1217: my $chkallscript = &Apache::lonhtmlcommon::scripttag('
1218: function checkall() {
1219: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1220: ele = document.forms.'.$form.'.elements[i];
1221: if (ele.name == "'.$type.'") {
1222: document.forms.'.$form.'.elements[i].checked=true;
1223: }
1224: }
1225: }
1226:
1227: function checksec() {
1228: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1229: ele = document.forms.'.$form.'.elements[i];
1230: string = document.forms.'.$form.'.chksec.value;
1231: if
1232: (ele.value.indexOf(":::SECTION"+string)>0) {
1233: document.forms.'.$form.'.elements[i].checked=true;
1234: }
1235: }
1236: }
1237:
1238:
1239: function uncheckall() {
1240: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1241: ele = document.forms.'.$form.'.elements[i];
1242: if (ele.name == "'.$type.'") {
1243: document.forms.'.$form.'.elements[i].checked=false;
1244: }
1245: }
1246: }
1247:
1248: '."\n");
1249: return $chkallscript;
1250: }
1251:
1252: sub check_buttons {
1253: my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
1254: $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" /> ';
1255: $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1256: $buttons.='<input type="text" size="5" name="chksec" /> ';
1257: return $buttons;
1258: }
1259:
1260: # Displays the submissions for one student or a group of students
1261: sub processGroup {
1262: my ($request,$symb) = @_;
1263: my $ctr = 0;
1264: my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1265: my $total = scalar(@stuchecked)-1;
1266:
1267: foreach my $student (@stuchecked) {
1268: my ($uname,$udom,$fullname) = split(/:/,$student);
1269: $env{'form.student'} = $uname;
1270: $env{'form.userdom'} = $udom;
1271: $env{'form.fullname'} = $fullname;
1272: &submission($request,$ctr,$total,$symb);
1273: $ctr++;
1274: }
1275: return '';
1276: }
1277:
1278: #------------------------------------------------------------------------------------
1279: #
1280: #-------------------------- Next few routines handles grading by student, essentially
1281: # handles essay response type problem/part
1282: #
1283: #--- Javascript to handle the submission page functionality ---
1284: sub sub_page_js {
1285: my $request = shift;
1286: my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1287: &js_escape(\$alertmsg);
1288: $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1289: function updateRadio(formname,id,weight) {
1290: var gradeBox = formname["GD_BOX"+id];
1291: var radioButton = formname["RADVAL"+id];
1292: var oldpts = formname["oldpts"+id].value;
1293: var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1294: gradeBox.value = pts;
1295: var resetbox = false;
1296: if (isNaN(pts) || pts < 0) {
1297: alert("$alertmsg"+pts);
1298: for (var i=0; i<radioButton.length; i++) {
1299: if (radioButton[i].checked) {
1300: gradeBox.value = i;
1301: resetbox = true;
1302: }
1303: }
1304: if (!resetbox) {
1305: formtextbox.value = "";
1306: }
1307: return;
1308: }
1309:
1310: if (pts > weight) {
1311: var resp = confirm("You entered a value ("+pts+
1312: ") greater than the weight for the part. Accept?");
1313: if (resp == false) {
1314: gradeBox.value = oldpts;
1315: return;
1316: }
1317: }
1318:
1319: for (var i=0; i<radioButton.length; i++) {
1320: radioButton[i].checked=false;
1321: if (pts == i && pts != "") {
1322: radioButton[i].checked=true;
1323: }
1324: }
1325: updateSelect(formname,id);
1326: formname["stores"+id].value = "0";
1327: }
1328:
1329: function writeBox(formname,id,pts) {
1330: var gradeBox = formname["GD_BOX"+id];
1331: if (checkSolved(formname,id) == 'update') {
1332: gradeBox.value = pts;
1333: } else {
1334: var oldpts = formname["oldpts"+id].value;
1335: gradeBox.value = oldpts;
1336: var radioButton = formname["RADVAL"+id];
1337: for (var i=0; i<radioButton.length; i++) {
1338: radioButton[i].checked=false;
1339: if (i == oldpts) {
1340: radioButton[i].checked=true;
1341: }
1342: }
1343: }
1344: formname["stores"+id].value = "0";
1345: updateSelect(formname,id);
1346: return;
1347: }
1348:
1349: function clearRadBox(formname,id) {
1350: if (checkSolved(formname,id) == 'noupdate') {
1351: updateSelect(formname,id);
1352: return;
1353: }
1354: gradeSelect = formname["GD_SEL"+id];
1355: for (var i=0; i<gradeSelect.length; i++) {
1356: if (gradeSelect[i].selected) {
1357: var selectx=i;
1358: }
1359: }
1360: var stores = formname["stores"+id];
1361: if (selectx == stores.value) { return };
1362: var gradeBox = formname["GD_BOX"+id];
1363: gradeBox.value = "";
1364: var radioButton = formname["RADVAL"+id];
1365: for (var i=0; i<radioButton.length; i++) {
1366: radioButton[i].checked=false;
1367: }
1368: stores.value = selectx;
1369: }
1370:
1371: function checkSolved(formname,id) {
1372: if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1373: var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
1374: if (!reply) {return "noupdate";}
1375: formname.overRideScore.value = 'yes';
1376: }
1377: return "update";
1378: }
1379:
1380: function updateSelect(formname,id) {
1381: formname["GD_SEL"+id][0].selected = true;
1382: return;
1383: }
1384:
1385: //=========== Check that a point is assigned for all the parts ============
1386: function checksubmit(formname,val,total,parttot) {
1387: formname.gradeOpt.value = val;
1388: if (val == "Save & Next") {
1389: for (i=0;i<=total;i++) {
1390: for (j=0;j<parttot;j++) {
1391: var partid = formname["partid"+i+"_"+j].value;
1392: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1393: var points = formname["GD_BOX"+i+"_"+partid].value;
1394: if (points == "") {
1395: var name = formname["name"+i].value;
1396: var studentID = (name != '' ? name : formname["unamedom"+i].value);
1397: var resp = confirm("You did not assign a score for "+studentID+
1398: ", part "+partid+". Continue?");
1399: if (resp == false) {
1400: formname["GD_BOX"+i+"_"+partid].focus();
1401: return false;
1402: }
1403: }
1404: }
1405: }
1406: }
1407: }
1408: formname.submit();
1409: }
1410:
1411: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
1412: function checkSubmitPage(formname,total) {
1413: noscore = new Array(100);
1414: var ptr = 0;
1415: for (i=1;i<total;i++) {
1416: var partid = formname["q_"+i].value;
1417: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1418: var points = formname["GD_BOX"+i+"_"+partid].value;
1419: var status = formname["solved"+i+"_"+partid].value;
1420: if (points == "" && status != "correct_by_student") {
1421: noscore[ptr] = i;
1422: ptr++;
1423: }
1424: }
1425: }
1426: if (ptr != 0) {
1427: var sense = ptr == 1 ? ": " : "s: ";
1428: var prolist = "";
1429: if (ptr == 1) {
1430: prolist = noscore[0];
1431: } else {
1432: var i = 0;
1433: while (i < ptr-1) {
1434: prolist += noscore[i]+", ";
1435: i++;
1436: }
1437: prolist += "and "+noscore[i];
1438: }
1439: var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
1440: if (resp == false) {
1441: return false;
1442: }
1443: }
1444:
1445: formname.submit();
1446: }
1447: SUBJAVASCRIPT
1448: }
1449:
1450: #--- javascript for essay type problem --
1451: sub sub_page_kw_js {
1452: my $request = shift;
1453: my $iconpath = $request->dir_config('lonIconsURL');
1454: &commonJSfunctions($request);
1455:
1456: my $inner_js_msg_central= (<<INNERJS);
1457: <script type="text/javascript">
1458: function checkInput() {
1459: opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
1460: var nmsg = opener.document.SCORE.savemsgN.value;
1461: var usrctr = document.msgcenter.usrctr.value;
1462: var newval = opener.document.SCORE["newmsg"+usrctr];
1463: newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
1464:
1465: var msgchk = "";
1466: if (document.msgcenter.subchk.checked) {
1467: msgchk = "msgsub,";
1468: }
1469: var includemsg = 0;
1470: for (var i=1; i<=nmsg; i++) {
1471: var opnmsg = opener.document.SCORE["savemsg"+i];
1472: var frmmsg = document.msgcenter["msg"+i];
1473: opnmsg.value = opener.checkEntities(frmmsg.value);
1474: var showflg = opener.document.SCORE["shownOnce"+i];
1475: showflg.value = "1";
1476: var chkbox = document.msgcenter["msgn"+i];
1477: if (chkbox.checked) {
1478: msgchk += "savemsg"+i+",";
1479: includemsg = 1;
1480: }
1481: }
1482: if (document.msgcenter.newmsgchk.checked) {
1483: msgchk += "newmsg"+usrctr;
1484: includemsg = 1;
1485: }
1486: imgformname = opener.document.SCORE["mailicon"+usrctr];
1487: imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
1488: var includemsg = opener.document.SCORE["includemsg"+usrctr];
1489: includemsg.value = msgchk;
1490:
1491: self.close()
1492:
1493: }
1494: </script>
1495: INNERJS
1496:
1497: my $inner_js_highlight_central= (<<INNERJS);
1498: <script type="text/javascript">
1499: function updateChoice(flag) {
1500: opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
1501: opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
1502: opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
1503: opener.document.SCORE.refresh.value = "on";
1504: if (opener.document.SCORE.keywords.value!=""){
1505: opener.document.SCORE.submit();
1506: }
1507: self.close()
1508: }
1509: </script>
1510: INNERJS
1511:
1512: my $start_page_msg_central =
1513: &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
1514: {'js_ready' => 1,
1515: 'only_body' => 1,
1516: 'bgcolor' =>'#FFFFFF',});
1517: my $end_page_msg_central =
1518: &Apache::loncommon::end_page({'js_ready' => 1});
1519:
1520:
1521: my $start_page_highlight_central =
1522: &Apache::loncommon::start_page('Highlight Central',
1523: $inner_js_highlight_central,
1524: {'js_ready' => 1,
1525: 'only_body' => 1,
1526: 'bgcolor' =>'#FFFFFF',});
1527: my $end_page_highlight_central =
1528: &Apache::loncommon::end_page({'js_ready' => 1});
1529:
1530: my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1531: $docopen=~s/^document\.//;
1532: my %js_lt = &Apache::lonlocal::texthash(
1533: keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
1534: plse => 'Please select a word or group of words from document and then click this link.',
1535: adds => 'Add selection to keyword list? Edit if desired.',
1536: col1 => 'red',
1537: col2 => 'green',
1538: col3 => 'blue',
1539: siz1 => 'normal',
1540: siz2 => '+1',
1541: siz3 => '+2',
1542: sty1 => 'normal',
1543: sty2 => 'italic',
1544: sty3 => 'bold',
1545: );
1546: my %html_js_lt = &Apache::lonlocal::texthash(
1547: comp => 'Compose Message for: ',
1548: incl => 'Include',
1549: type => 'Type',
1550: subj => 'Subject',
1551: mesa => 'Message',
1552: new => 'New',
1553: save => 'Save',
1554: canc => 'Cancel',
1555: kehi => 'Keyword Highlight Options',
1556: txtc => 'Text Color',
1557: font => 'Font Size',
1558: fnst => 'Font Style',
1559: );
1560: &js_escape(\%js_lt);
1561: &html_escape(\%html_js_lt);
1562: &js_escape(\%html_js_lt);
1563: $request->print(&Apache::lonhtmlcommon::scripttag(<<SUBJAVASCRIPT));
1564:
1565: //===================== Show list of keywords ====================
1566: function keywords(formname) {
1567: var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
1568: if (nret==null) return;
1569: formname.keywords.value = nret;
1570:
1571: if (formname.keywords.value != "") {
1572: formname.refresh.value = "on";
1573: formname.submit();
1574: }
1575: return;
1576: }
1577:
1578: //===================== Script to view submitted by ==================
1579: function viewSubmitter(submitter) {
1580: document.SCORE.refresh.value = "on";
1581: document.SCORE.NCT.value = "1";
1582: document.SCORE.unamedom0.value = submitter;
1583: document.SCORE.submit();
1584: return;
1585: }
1586:
1587: //===================== Script to add keyword(s) ==================
1588: function getSel() {
1589: if (document.getSelection) txt = document.getSelection();
1590: else if (document.selection) txt = document.selection.createRange().text;
1591: else return;
1592: var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
1593: if (cleantxt=="") {
1594: alert("$js_lt{'plse'}");
1595: return;
1596: }
1597: var nret = prompt("$js_lt{'adds'}",cleantxt);
1598: if (nret==null) return;
1599: document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1600: if (document.SCORE.keywords.value != "") {
1601: document.SCORE.refresh.value = "on";
1602: document.SCORE.submit();
1603: }
1604: return;
1605: }
1606:
1607: //====================== Script for composing message ==============
1608: // preload images
1609: img1 = new Image();
1610: img1.src = "$iconpath/mailbkgrd.gif";
1611: img2 = new Image();
1612: img2.src = "$iconpath/mailto.gif";
1613:
1614: function msgCenter(msgform,usrctr,fullname) {
1615: var Nmsg = msgform.savemsgN.value;
1616: savedMsgHeader(Nmsg,usrctr,fullname);
1617: var subject = msgform.msgsub.value;
1618: var msgchk = document.SCORE["includemsg"+usrctr].value;
1619: re = /msgsub/;
1620: var shwsel = "";
1621: if (re.test(msgchk)) { shwsel = "checked" }
1622: subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
1623: displaySubject(checkEntities(subject),shwsel);
1624: for (var i=1; i<=Nmsg; i++) {
1625: var testmsg = "savemsg"+i+",";
1626: re = new RegExp(testmsg,"g");
1627: shwsel = "";
1628: if (re.test(msgchk)) { shwsel = "checked" }
1629: var message = document.SCORE["savemsg"+i].value;
1630: message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1631: displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
1632: //any < is already converted to <, etc. However, only once!!
1633: }
1634: newmsg = document.SCORE["newmsg"+usrctr].value;
1635: shwsel = "";
1636: re = /newmsg/;
1637: if (re.test(msgchk)) { shwsel = "checked" }
1638: newMsg(newmsg,shwsel);
1639: msgTail();
1640: return;
1641: }
1642:
1643: function checkEntities(strx) {
1644: if (strx.length == 0) return strx;
1645: var orgStr = ["&", "<", ">", '"'];
1646: var newStr = ["&", "<", ">", """];
1647: var counter = 0;
1648: while (counter < 4) {
1649: strx = strReplace(strx,orgStr[counter],newStr[counter]);
1650: counter++;
1651: }
1652: return strx;
1653: }
1654:
1655: function strReplace(strx, orgStr, newStr) {
1656: return strx.split(orgStr).join(newStr);
1657: }
1658:
1659: function savedMsgHeader(Nmsg,usrctr,fullname) {
1660: var height = 70*Nmsg+250;
1661: if (height > 600) {
1662: height = 600;
1663: }
1664: var xpos = (screen.width-600)/2;
1665: xpos = (xpos < 0) ? '0' : xpos;
1666: var ypos = (screen.height-height)/2-30;
1667: ypos = (ypos < 0) ? '0' : ypos;
1668:
1669: pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1670: pWin.focus();
1671: pDoc = pWin.document;
1672: pDoc.$docopen;
1673: pDoc.write('$start_page_msg_central');
1674:
1675: pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
1676: pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1677: pDoc.write("<h1> $html_js_lt{'comp'}\"+fullname+\"<\\/h1>");
1678:
1679: pDoc.write('<table style="border:1px solid black;"><tr>');
1680: pDoc.write("<td><b>$html_js_lt{'incl'}<\\/b><\\/td><td><b>$html_js_lt{'type'}<\\/b><\\/td><td><b>$html_js_lt{'mesa'}<\\/td><\\/tr>");
1681: }
1682: function displaySubject(msg,shwsel) {
1683: pDoc = pWin.document;
1684: pDoc.write("<tr>");
1685: pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1686: pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
1687: pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"40\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1688: }
1689:
1690: function displaySavedMsg(ctr,msg,shwsel) {
1691: pDoc = pWin.document;
1692: pDoc.write("<tr>");
1693: pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1694: pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
1695: pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1696: }
1697:
1698: function newMsg(newmsg,shwsel) {
1699: pDoc = pWin.document;
1700: pDoc.write("<tr>");
1701: pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1702: pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
1703: pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1704: }
1705:
1706: function msgTail() {
1707: pDoc = pWin.document;
1708: //pDoc.write("<\\/table>");
1709: pDoc.write("<\\/td><\\/tr><\\/table> ");
1710: pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\"> ");
1711: pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1712: pDoc.write("<\\/form>");
1713: pDoc.write('$end_page_msg_central');
1714: pDoc.close();
1715: }
1716:
1717: //====================== Script for keyword highlight options ==============
1718: function kwhighlight() {
1719: var kwclr = document.SCORE.kwclr.value;
1720: var kwsize = document.SCORE.kwsize.value;
1721: var kwstyle = document.SCORE.kwstyle.value;
1722: var redsel = "";
1723: var grnsel = "";
1724: var blusel = "";
1725: var txtcol1 = "$js_lt{'col1'}";
1726: var txtcol2 = "$js_lt{'col2'}";
1727: var txtcol3 = "$js_lt{'col3'}";
1728: var txtsiz1 = "$js_lt{'siz1'}";
1729: var txtsiz2 = "$js_lt{'siz2'}";
1730: var txtsiz3 = "$js_lt{'siz3'}";
1731: var txtsty1 = "$js_lt{'sty1'}";
1732: var txtsty2 = "$js_lt{'sty2'}";
1733: var txtsty3 = "$js_lt{'sty3'}";
1734: if (kwclr=="red") {var redsel="checked='checked'"};
1735: if (kwclr=="green") {var grnsel="checked='checked'"};
1736: if (kwclr=="blue") {var blusel="checked='checked'"};
1737: var sznsel = "";
1738: var sz1sel = "";
1739: var sz2sel = "";
1740: if (kwsize=="0") {var sznsel="checked='checked'"};
1741: if (kwsize=="+1") {var sz1sel="checked='checked'"};
1742: if (kwsize=="+2") {var sz2sel="checked='checked'"};
1743: var synsel = "";
1744: var syisel = "";
1745: var sybsel = "";
1746: if (kwstyle=="") {var synsel="checked='checked'"};
1747: if (kwstyle=="<i>") {var syisel="checked='checked'"};
1748: if (kwstyle=="<b>") {var sybsel="checked='checked'"};
1749: highlightCentral();
1750: highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
1751: highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
1752: highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
1753: highlightend();
1754: return;
1755: }
1756:
1757: function highlightCentral() {
1758: // if (window.hwdWin) window.hwdWin.close();
1759: var xpos = (screen.width-400)/2;
1760: xpos = (xpos < 0) ? '0' : xpos;
1761: var ypos = (screen.height-330)/2-30;
1762: ypos = (ypos < 0) ? '0' : ypos;
1763:
1764: hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1765: hwdWin.focus();
1766: var hDoc = hwdWin.document;
1767: hDoc.$docopen;
1768: hDoc.write('$start_page_highlight_central');
1769: hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1770: hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
1771:
1772: hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
1773: hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
1774: }
1775:
1776: function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) {
1777: var hDoc = hwdWin.document;
1778: hDoc.write("<tr>");
1779: hDoc.write("<td align=\\"left\\">");
1780: hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/> "+clrtxt+"<\\/td>");
1781: hDoc.write("<td align=\\"left\\">");
1782: hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/> "+sztxt+"<\\/td>");
1783: hDoc.write("<td align=\\"left\\">");
1784: hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/> "+sytxt+"<\\/td>");
1785: hDoc.write("<\\/tr>");
1786: }
1787:
1788: function highlightend() {
1789: var hDoc = hwdWin.document;
1790: hDoc.write("<\\/table><br \\/>");
1791: hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/> ");
1792: hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
1793: hDoc.write("<\\/form>");
1794: hDoc.write('$end_page_highlight_central');
1795: hDoc.close();
1796: }
1797:
1798: SUBJAVASCRIPT
1799: }
1800:
1801: sub get_increment {
1802: my $increment = $env{'form.increment'};
1803: if ($increment != 1 && $increment != .5 && $increment != .25 &&
1804: $increment != .1) {
1805: $increment = 1;
1806: }
1807: return $increment;
1808: }
1809:
1810: sub gradeBox_start {
1811: return (
1812: &Apache::loncommon::start_data_table()
1813: .&Apache::loncommon::start_data_table_header_row()
1814: .'<th>'.&mt('Part').'</th>'
1815: .'<th>'.&mt('Points').'</th>'
1816: .'<th> </th>'
1817: .'<th>'.&mt('Assign Grade').'</th>'
1818: .'<th>'.&mt('Weight').'</th>'
1819: .'<th>'.&mt('Grade Status').'</th>'
1820: .&Apache::loncommon::end_data_table_header_row()
1821: );
1822: }
1823:
1824: sub gradeBox_end {
1825: return (
1826: &Apache::loncommon::end_data_table()
1827: );
1828: }
1829: #--- displays the grading box, used in essay type problem and grading by page/sequence
1830: sub gradeBox {
1831: my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1832: my $checkIcon = '<img alt="'.&mt('Check Mark').
1833: '" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1834: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1835: my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)')
1836: : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1837: $wgt = ($wgt > 0 ? $wgt : '1');
1838: my $score = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1839: '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1840: my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1841: my $display_part= &get_display_part($partid,$symb);
1842: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
1843: [$partid]);
1844: my $aggtries = $$record{'resource.'.$partid.'.tries'};
1845: if ($last_resets{$partid}) {
1846: $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
1847: }
1848: my $result=&Apache::loncommon::start_data_table_row();
1849: my $ctr = 0;
1850: my $thisweight = 0;
1851: my $increment = &get_increment();
1852:
1853: my $radio.='<table border="0"><tr>'."\n"; # display radio buttons in a nice table 10 across
1854: while ($thisweight<=$wgt) {
1855: $radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1856: 'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1857: $thisweight.')" value="'.$thisweight.'" '.
1858: ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1859: $radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1860: $thisweight += $increment;
1861: $ctr++;
1862: }
1863: $radio.='</tr></table>';
1864:
1865: my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1866: ($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1867: 'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1868: $wgt.')" /></td>'."\n";
1869: $line.='<td>/'.$wgt.' '.$wgtmsg.
1870: ($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? ' '.$checkIcon : '').
1871: ' </td>'."\n";
1872: $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1873: 'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1874: if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1875: $line.='<option></option>'.
1876: '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1877: } else {
1878: $line.='<option selected="selected"></option>'.
1879: '<option value="excused" >'.&mt('excused').'</option>';
1880: }
1881: $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
1882:
1883:
1884: $result .=
1885: '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
1886: $result.=&Apache::loncommon::end_data_table_row();
1887: $result.=&Apache::loncommon::start_data_table_row().'<td colspan="6">';
1888: $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
1889: '<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
1890: '<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1891: $$record{'resource.'.$partid.'.solved'}.'" />'."\n".
1892: '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
1893: $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
1894: '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
1895: $aggtries.'" />'."\n";
1896: my $res_error;
1897: $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1898: $result.='</td>'.&Apache::loncommon::end_data_table_row();
1899: if ($res_error) {
1900: return &navmap_errormsg();
1901: }
1902: return $result;
1903: }
1904:
1905: sub handback_box {
1906: my ($symb,$uname,$udom,$counter,$partid,$record,$res_error_pointer) = @_;
1907: my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error_pointer);
1908: my (@respids);
1909: my @part_response_id = &flatten_responseType($responseType);
1910: foreach my $part_response_id (@part_response_id) {
1911: my ($part,$resp) = @{ $part_response_id };
1912: if ($part eq $partid) {
1913: push(@respids,$resp);
1914: }
1915: }
1916: my $result;
1917: foreach my $respid (@respids) {
1918: my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
1919: my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
1920: next if (!@$files);
1921: my $file_counter = 0;
1922: foreach my $file (@$files) {
1923: if ($file =~ /\/portfolio\//) {
1924: $file_counter++;
1925: my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1926: my ($name,$version,$ext) = &Apache::lonnet::file_name_version_ext($file_disp);
1927: $file_disp = "$name.$ext";
1928: $file = $file_path.$file_disp;
1929: $result.=&mt('Return commented version of [_1] to student.',
1930: '<span class="LC_filename">'.$file_disp.'</span>');
1931: $result.='<input type="file" name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1932: $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1933: }
1934: }
1935: if ($file_counter) {
1936: $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
1937: '<span class="LC_info">'.
1938: '('.&mt('File(s) will be uploaded when you click on Save & Next below.',$file_counter).')</span><br /><br />';
1939: }
1940: }
1941: return $result;
1942: }
1943:
1944: sub show_problem {
1945: my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1946: my $rendered;
1947: my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1948: &Apache::lonxml::remember_problem_counter();
1949: if ($mode eq 'both' or $mode eq 'text') {
1950: $rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1951: $env{'request.course.id'},
1952: undef,\%form);
1953: }
1954: if ($removeform) {
1955: $rendered=~s|<form(.*?)>||g;
1956: $rendered=~s|</form>||g;
1957: $rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1958: }
1959: my $companswer;
1960: if ($mode eq 'both' or $mode eq 'answer') {
1961: &Apache::lonxml::restore_problem_counter();
1962: $companswer=
1963: &Apache::loncommon::get_student_answers($symb,$uname,$udom,
1964: $env{'request.course.id'},
1965: %form);
1966: }
1967: if ($removeform) {
1968: $companswer=~s|<form(.*?)>||g;
1969: $companswer=~s|</form>||g;
1970: $companswer=~s|name="submit"|name="would_have_been_submit"|g;
1971: }
1972: my $renderheading = &mt('View of the problem');
1973: my $answerheading = &mt('Correct answer');
1974: if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1975: my $stu_fullname = $env{'form.fullname'};
1976: if ($stu_fullname eq '') {
1977: $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
1978: }
1979: my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
1980: if ($forwhom ne '') {
1981: $renderheading = &mt('View of the problem for[_1]',$forwhom);
1982: $answerheading = &mt('Correct answer for[_1]',$forwhom);
1983: }
1984: }
1985: $rendered=
1986: '<div class="LC_Box">'
1987: .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1988: .$rendered
1989: .'</div>';
1990: $companswer=
1991: '<div class="LC_Box">'
1992: .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1993: .$companswer
1994: .'</div>';
1995: my $result;
1996: if ($mode eq 'both') {
1997: $result=$rendered.$companswer;
1998: } elsif ($mode eq 'text') {
1999: $result=$rendered;
2000: } elsif ($mode eq 'answer') {
2001: $result=$companswer;
2002: }
2003: return $result;
2004: }
2005:
2006: sub files_exist {
2007: my ($r, $symb) = @_;
2008: my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
2009: foreach my $student (@students) {
2010: my ($uname,$udom,$fullname) = split(/:/,$student);
2011: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
2012: $udom,$uname);
2013: my ($string,$timestamp)= &get_last_submission(\%record);
2014: foreach my $submission (@$string) {
2015: my ($partid,$respid) =
2016: ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
2017: my $files=&get_submitted_files($udom,$uname,$partid,$respid,
2018: \%record);
2019: return 1 if (@$files);
2020: }
2021: }
2022: return 0;
2023: }
2024:
2025: sub download_all_link {
2026: my ($r,$symb) = @_;
2027: unless (&files_exist($r, $symb)) {
2028: $r->print(&mt('There are currently no submitted documents.'));
2029: return;
2030: }
2031: my $all_students =
2032: join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
2033:
2034: my $parts =
2035: join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
2036:
2037: my $identifier = &Apache::loncommon::get_cgi_id();
2038: &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
2039: 'cgi.'.$identifier.'.symb' => $symb,
2040: 'cgi.'.$identifier.'.parts' => $parts,});
2041: $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
2042: &mt('Download All Submitted Documents').'</a>');
2043: return;
2044: }
2045:
2046: sub submit_download_link {
2047: my ($request,$symb) = @_;
2048: if (!$symb) { return ''; }
2049: #FIXME: Figure out which type of problem this is and provide appropriate download
2050: my $res_error;
2051: my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
2052: if (ref($res_error)) {
2053: if ($$res_error) {
2054: $request->print(&mt('An error occurred retrieving response types'));
2055: return;
2056: }
2057: }
2058: my ($numupload,$numessay) = (0,0);
2059: if (ref($responseType) eq 'HASH') {
2060: foreach my $part (sort(keys(%$responseType))) {
2061: foreach my $id (sort(keys(%{ $responseType->{$part} }))) {
2062: my $responsetype = $responseType->{$part}->{$id};
2063: if ($responsetype eq 'essay') {
2064: my $uploadedfiletypes =
2065: &Apache::lonnet::EXT("resource.$part".'_'."$id.uploadedfiletypes",$symb);
2066: if ($uploadedfiletypes) {
2067: $numupload++;
2068: } else {
2069: $numessay++;
2070: }
2071: }
2072: }
2073: }
2074: }
2075: if (($numupload) || ($numessay)) {
2076: my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
2077: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
2078: my $getgroup = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
2079: (undef,undef,my $fullname) = &getclasslist($getsec,1,$getgroup,$symb,$submitonly,1);
2080: if (ref($fullname) eq 'HASH') {
2081: my @students = map { $_.':'.$fullname->{$_} } (keys(%{$fullname}));
2082: if (@students) {
2083: @{$env{'form.stuinfo'}} = @students;
2084: if ($numupload) {
2085: &download_all_link($request,$symb);
2086: }
2087: # FIXME Need to provide a mechanism to download essays, i.e., if $numessay > 0
2088: # Needs to omit user's identity if resource instance is for an anonymous survey.
2089: } else {
2090: $request->print(&mt('No students match the criteria you selected'));
2091: }
2092: } else {
2093: $request->print(&mt('Could not retrieve student information'));
2094: }
2095: } else {
2096: $request->print(&mt('No essayresponse items found'));
2097: }
2098: return;
2099: }
2100:
2101: sub build_section_inputs {
2102: my $section_inputs;
2103: if ($env{'form.section'} eq '') {
2104: $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
2105: } else {
2106: my @sections = &Apache::loncommon::get_env_multiple('form.section');
2107: foreach my $section (@sections) {
2108: $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
2109: }
2110: }
2111: return $section_inputs;
2112: }
2113:
2114: # --------------------------- show submissions of a student, option to grade
2115: sub submission {
2116: my ($request,$counter,$total,$symb) = @_;
2117: my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
2118: $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
2119: my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
2120: $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
2121:
2122: my $probtitle=&Apache::lonnet::gettitle($symb);
2123: if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
2124: my $is_tool = ($symb =~ /ext\.tool$/);
2125: my ($essayurl,%coursedesc_by_cid);
2126:
2127: if (!&canview($usec)) {
2128: $request->print(
2129: '<span class="LC_warning">'.
2130: &mt('Unable to view requested student.').
2131: ' '.&mt('([_1] in section [_2] in course id [_3])',
2132: $uname.':'.$udom,$usec,$env{'request.course.id'}).
2133: '</span>');
2134: return;
2135: }
2136:
2137: if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
2138: unless ($is_tool) {
2139: if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
2140: if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
2141: }
2142: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
2143: my $checkIcon = '<img alt="'.&mt('Check Mark').
2144: '" src="'.$request->dir_config('lonIconsURL').
2145: '/check.gif" height="16" border="0" />';
2146:
2147: # header info
2148: if ($counter == 0) {
2149: &sub_page_js($request);
2150: &sub_page_kw_js($request);
2151:
2152: # option to display problem, only once else it cause problems
2153: # with the form later since the problem has a form.
2154: if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
2155: my $mode;
2156: if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
2157: $mode='both';
2158: } elsif ($env{'form.vProb'} eq 'yes') {
2159: $mode='text';
2160: } elsif ($env{'form.vAns'} eq 'yes') {
2161: $mode='answer';
2162: }
2163: &Apache::lonxml::clear_problem_counter();
2164: $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
2165: }
2166:
2167: # kwclr is the only variable that is guaranteed not to be blank
2168: # if this subroutine has been called once.
2169: my %keyhash = ();
2170: # if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
2171: if (1) {
2172: %keyhash = &Apache::lonnet::dump('nohist_handgrade',
2173: $env{'course.'.$env{'request.course.id'}.'.domain'},
2174: $env{'course.'.$env{'request.course.id'}.'.num'});
2175:
2176: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
2177: $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
2178: $env{'form.kwclr'} = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
2179: $env{'form.kwsize'} = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
2180: $env{'form.kwstyle'} = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
2181: $env{'form.msgsub'} = $keyhash{$symb.'_subject'} ne '' ?
2182: $keyhash{$symb.'_subject'} : $probtitle;
2183: $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
2184: }
2185: my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
2186: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
2187: $request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
2188: '<input type="hidden" name="command" value="handgrade" />'."\n".
2189: '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
2190: '<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
2191: '<input type="hidden" name="refresh" value="off" />'."\n".
2192: '<input type="hidden" name="studentNo" value="" />'."\n".
2193: '<input type="hidden" name="gradeOpt" value="" />'."\n".
2194: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
2195: '<input type="hidden" name="vProb" value="'.$env{'form.vProb'}.'" />'."\n".
2196: '<input type="hidden" name="vAns" value="'.$env{'form.vAns'}.'" />'."\n".
2197: '<input type="hidden" name="lastSub" value="'.$env{'form.lastSub'}.'" />'."\n".
2198: &build_section_inputs().
2199: '<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
2200: '<input type="hidden" name="NCT"'.
2201: ' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
2202: # if ($env{'form.handgrade'} eq 'yes') {
2203: if (1) {
2204: $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
2205: '<input type="hidden" name="kwclr" value="'.$env{'form.kwclr'}.'" />'."\n".
2206: '<input type="hidden" name="kwsize" value="'.$env{'form.kwsize'}.'" />'."\n".
2207: '<input type="hidden" name="kwstyle" value="'.$env{'form.kwstyle'}.'" />'."\n".
2208: '<input type="hidden" name="msgsub" value="'.$env{'form.msgsub'}.'" />'."\n".
2209: '<input type="hidden" name="shownSub" value="0" />'."\n".
2210: '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
2211: foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
2212: $request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
2213: }
2214: }
2215:
2216: my ($cts,$prnmsg) = (1,'');
2217: while ($cts <= $env{'form.savemsgN'}) {
2218: $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
2219: (!exists($keyhash{$symb.'_savemsg'.$cts}) ?
2220: &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
2221: &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
2222: '" />'."\n".
2223: '<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
2224: $cts++;
2225: }
2226: $request->print($prnmsg);
2227:
2228: # if ($env{'form.handgrade'} eq 'yes') {
2229: unless ($is_tool) {
2230:
2231: my %lt = &Apache::lonlocal::texthash(
2232: keyh => 'Keyword Highlighting for Essays',
2233: keyw => 'Keyword Options',
2234: list => 'List',
2235: past => 'Paste Selection to List',
2236: high => 'Highlight Attribute',
2237: );
2238: #
2239: # Print out the keyword options line
2240: #
2241: $request->print(
2242: '<div class="LC_columnSection">'
2243: .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
2244: .&Apache::lonhtmlcommon::funclist_from_array(
2245: ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
2246: '<a href="#" onmousedown="javascript:getSel(); return false"
2247: class="page">'.$lt{'past'}.'</a>',
2248: '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
2249: {legend => $lt{'keyw'}})
2250: .'</fieldset></div>'
2251: );
2252:
2253: #
2254: # Load the other essays for similarity check
2255: #
2256: (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
2257: if ($essayurl eq 'lib/templates/simpleproblem.problem') {
2258: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2259: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2260: if ($cdom ne '' && $cnum ne '') {
2261: my ($map,$id,$res) = &Apache::lonnet::decode_symb($symb);
2262: if ($map =~ m{^\Quploaded/$cdom/$cnum/\E(default(?:|_\d+)\.(?:sequence|page))$}) {
2263: my $apath = $1.'_'.$id;
2264: $apath=~s/\W/\_/gs;
2265: &init_old_essays($symb,$apath,$cdom,$cnum);
2266: }
2267: }
2268: } else {
2269: my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
2270: $apath=&escape($apath);
2271: $apath=~s/\W/\_/gs;
2272: &init_old_essays($symb,$apath,$adom,$aname);
2273: }
2274: }
2275: }
2276:
2277: # This is where output for one specific student would start
2278: my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
2279: $request->print(
2280: "\n\n"
2281: .'<div class="LC_grade_show_user'.$add_class.'">'
2282: .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
2283: ."\n"
2284: );
2285:
2286: # Show additional functions if allowed
2287: if ($perm{'vgr'}) {
2288: $request->print(
2289: &Apache::loncommon::track_student_link(
2290: 'View recent activity',
2291: $uname,$udom,'check')
2292: .' '
2293: );
2294: }
2295: if ($perm{'opa'}) {
2296: $request->print(
2297: &Apache::loncommon::pprmlink(
2298: &mt('Set/Change parameters'),
2299: $uname,$udom,$symb,'check'));
2300: }
2301:
2302: # Show Problem
2303: if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
2304: my $mode;
2305: if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
2306: $mode='both';
2307: } elsif ($env{'form.vProb'} eq 'all' ) {
2308: $mode='text';
2309: } elsif ($env{'form.vAns'} eq 'all') {
2310: $mode='answer';
2311: }
2312: &Apache::lonxml::clear_problem_counter();
2313: $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
2314: }
2315:
2316: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
2317: my $res_error;
2318: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
2319: if ($res_error) {
2320: $request->print(&navmap_errormsg());
2321: return;
2322: }
2323:
2324: # Display student info
2325: $request->print(($counter == 0 ? '' : '<br />'));
2326:
2327: my $boxtitle = &mt('Submissions');
2328: if ($is_tool) {
2329: $boxtitle = &mt('Transactions')
2330: }
2331: my $result='<div class="LC_Box">'
2332: .'<h3 class="LC_hcell">'.$boxtitle.'</h3>';
2333: $result.='<input type="hidden" name="name'.$counter.
2334: '" value="'.$env{'form.fullname'}.'" />'."\n";
2335: # if ($env{'form.handgrade'} eq 'no') {
2336: unless ($is_tool) {
2337: $result.='<p class="LC_info">'
2338: .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
2339: ."</p>\n";
2340: }
2341:
2342: # If any part of the problem is an essay-response (handgraded), then check for collaborators
2343: my $fullname;
2344: my $col_fullnames = [];
2345: # if ($env{'form.handgrade'} eq 'yes') {
2346: unless ($is_tool) {
2347: (my $sub_result,$fullname,$col_fullnames)=
2348: &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
2349: $counter);
2350: $result.=$sub_result;
2351: }
2352: $request->print($result."\n");
2353:
2354: # print student answer/submission
2355: # Options are (1) Handgraded submission only
2356: # (2) Last submission, includes submission that is not handgraded
2357: # (for multi-response type part)
2358: # (3) Last submission plus the parts info
2359: # (4) The whole record for this student
2360:
2361: my ($string,$timestamp)= &get_last_submission(\%record,$is_tool);
2362:
2363: my $lastsubonly;
2364:
2365: if ($$timestamp eq '') {
2366: $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>';
2367: } elsif ($is_tool) {
2368: $lastsubonly =
2369: '<div class="LC_grade_submissions_body">'
2370: .'<b>'.&mt('Date Grade Passed Back:').'</b> '.$$timestamp."</div>\n";
2371: } else {
2372: $lastsubonly =
2373: '<div class="LC_grade_submissions_body">'
2374: .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
2375:
2376: my %seenparts;
2377: my @part_response_id = &flatten_responseType($responseType);
2378: foreach my $part (@part_response_id) {
2379: next if ($env{'form.lastSub'} eq 'hdgrade'
2380: && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
2381:
2382: my ($partid,$respid) = @{ $part };
2383: my $display_part=&get_display_part($partid,$symb);
2384: if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
2385: if (exists($seenparts{$partid})) { next; }
2386: $seenparts{$partid}=1;
2387: $request->print(
2388: '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
2389: ' <b>'.&mt('Collaborative submission by: [_1]',
2390: '<a href="javascript:viewSubmitter(\''.
2391: $env{"form.$uname:$udom:$partid:submitted_by"}.
2392: '\');" target="_self">'.
2393: $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
2394: '<br />');
2395: next;
2396: }
2397: my $responsetype = $responseType->{$partid}->{$respid};
2398: if (!exists($record{"resource.$partid.$respid.submission"})) {
2399: $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
2400: '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
2401: ' <span class="LC_internal_info">'.
2402: '('.&mt('Response ID: [_1]',$respid).')'.
2403: '</span> '.
2404: '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
2405: next;
2406: }
2407: foreach my $submission (@$string) {
2408: my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
2409: if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
2410: my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
2411: # Similarity check
2412: my $similar='';
2413: my ($type,$trial,$rndseed);
2414: if ($hide eq 'rand') {
2415: $type = 'randomizetry';
2416: $trial = $record{"resource.$partid.tries"};
2417: $rndseed = $record{"resource.$partid.rndseed"};
2418: }
2419: if ($env{'form.checkPlag'}) {
2420: my ($oname,$odom,$ocrsid,$oessay,$osim)=
2421: &most_similar($uname,$udom,$symb,$subval);
2422: if ($osim) {
2423: $osim=int($osim*100.0);
2424: if ($hide eq 'anon') {
2425: $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
2426: &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
2427: } else {
2428: $similar='<hr />';
2429: if ($essayurl eq 'lib/templates/simpleproblem.problem') {
2430: $similar .= '<h3><span class="LC_warning">'.
2431: &mt('Essay is [_1]% similar to an essay by [_2]',
2432: $osim,
2433: &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
2434: '</span></h3>';
2435: } else {
2436: my %old_course_desc;
2437: if ($ocrsid ne '') {
2438: if (ref($coursedesc_by_cid{$ocrsid}) eq 'HASH') {
2439: %old_course_desc = %{$coursedesc_by_cid{$ocrsid}};
2440: } else {
2441: my $args;
2442: if ($ocrsid ne $env{'request.course.id'}) {
2443: $args = {'one_time' => 1};
2444: }
2445: %old_course_desc =
2446: &Apache::lonnet::coursedescription($ocrsid,$args);
2447: $coursedesc_by_cid{$ocrsid} = \%old_course_desc;
2448: }
2449: $similar .=
2450: '<h3><span class="LC_warning">'.
2451: &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
2452: $osim,
2453: &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
2454: $old_course_desc{'description'},
2455: $old_course_desc{'num'},
2456: $old_course_desc{'domain'}).
2457: '</span></h3>';
2458: } else {
2459: $similar .=
2460: '<h3><span class="LC_warning">'.
2461: &mt('Essay is [_1]% similar to an essay by [_2] in an unknown course',
2462: $osim,
2463: &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
2464: '</span></h3>';
2465: }
2466: }
2467: $similar .= '<blockquote><i>'.
2468: &keywords_highlight($oessay).
2469: '</i></blockquote><hr />';
2470: }
2471: }
2472: }
2473: my $order=&get_order($partid,$respid,$symb,$uname,$udom,
2474: undef,$type,$trial,$rndseed);
2475: if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' &&
2476: $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
2477: my $display_part=&get_display_part($partid,$symb);
2478: $lastsubonly.='<div class="LC_grade_submission_part">'.
2479: '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
2480: ' <span class="LC_internal_info">'.
2481: '('.&mt('Response ID: [_1]',$respid).')'.
2482: '</span> ';
2483: my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
2484:
2485: if (@$files) {
2486: if ($hide eq 'anon') {
2487: $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
2488: } else {
2489: $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
2490: .'<br /><span class="LC_warning">';
2491: if(@$files == 1) {
2492: $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
2493: } else {
2494: $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
2495: }
2496: $lastsubonly .= '</span>';
2497: foreach my $file (@$files) {
2498: &Apache::lonnet::allowuploaded('/adm/grades',$file);
2499: $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
2500: }
2501: }
2502: $lastsubonly.='<br />';
2503: }
2504: if ($hide eq 'anon') {
2505: $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>';
2506: } else {
2507: $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
2508: if ($draft) {
2509: $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
2510: }
2511: $subval =
2512: &cleanRecord($subval,$responsetype,$symb,$partid,
2513: $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
2514: if ($responsetype eq 'essay') {
2515: $subval =~ s{\n}{<br />}g;
2516: }
2517: $lastsubonly.=$subval."\n";
2518: }
2519: if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
2520: $lastsubonly.='</div>';
2521: }
2522: }
2523: }
2524: $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
2525: }
2526: $request->print($lastsubonly);
2527: if ($env{'form.lastSub'} eq 'datesub') {
2528: my ($parts,$handgrade,$responseType) = &response_type($symb,\$res_error);
2529: $request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
2530:
2531: }
2532: if ($env{'form.lastSub'} =~ /^(last|all)$/) {
2533: my $identifier = (&canmodify($usec)? $counter : '');
2534: $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
2535: $env{'request.course.id'},
2536: $last,'.submission',
2537: 'Apache::grades::keywords_highlight',
2538: $usec,$identifier));
2539: }
2540: $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
2541: .$udom.'" />'."\n");
2542: # return if view submission with no grading option
2543: if (!&canmodify($usec)) {
2544: $request->print('<p><span class="LC_warning">'.&mt('No grading privileges').'</span></p></div>');
2545: return;
2546: } else {
2547: $request->print('</div>'."\n");
2548: }
2549:
2550: # essay grading message center
2551: # if ($env{'form.handgrade'} eq 'yes') {
2552: if (1) {
2553: my $result='<div class="LC_grade_message_center">';
2554:
2555: $result.='<div class="LC_grade_message_center_header">'.
2556: &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
2557: my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
2558: my $msgfor = $givenn.' '.$lastname;
2559: if (scalar(@$col_fullnames) > 0) {
2560: my $lastone = pop(@$col_fullnames);
2561: $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
2562: }
2563: $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
2564: $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
2565: '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
2566: $result.=' <a href="javascript:msgCenter(document.SCORE,'.$counter.
2567: ',\''.$msgfor.'\');" target="_self">'.
2568: &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
2569: &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
2570: ' <img src="'.$request->dir_config('lonIconsURL').
2571: '/mailbkgrd.gif" width="14" height="10" alt="" name="mailicon'.$counter.'" />'."\n".
2572: '<br /> ('.
2573: &mt('Message will be sent when you click on Save & Next below.').")\n";
2574: $result.='</div></div>';
2575: $request->print($result);
2576: }
2577:
2578: my %seen = ();
2579: my @partlist;
2580: my @gradePartRespid;
2581: my @part_response_id;
2582: if ($is_tool) {
2583: @part_response_id = ([0,'']);
2584: } else {
2585: @part_response_id = &flatten_responseType($responseType);
2586: }
2587: $request->print(
2588: '<div class="LC_Box">'
2589: .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
2590: );
2591: $request->print(&gradeBox_start());
2592: foreach my $part_response_id (@part_response_id) {
2593: my ($partid,$respid) = @{ $part_response_id };
2594: my $part_resp = join('_',@{ $part_response_id });
2595: next if ($seen{$partid} > 0);
2596: $seen{$partid}++;
2597: next if ($$handgrade{$part_resp} ne 'yes'
2598: && $env{'form.lastSub'} eq 'hdgrade');
2599: push(@partlist,$partid);
2600: push(@gradePartRespid,$partid.'.'.$respid);
2601: $request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
2602: }
2603: $request->print(&gradeBox_end()); # </div>
2604: $request->print('</div>');
2605:
2606: $request->print('<div class="LC_grade_info_links">');
2607: $request->print('</div>');
2608:
2609: $result='<input type="hidden" name="partlist'.$counter.
2610: '" value="'.(join ":",@partlist).'" />'."\n";
2611: $result.='<input type="hidden" name="gradePartRespid'.
2612: '" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
2613: my $ctr = 0;
2614: while ($ctr < scalar(@partlist)) {
2615: $result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
2616: $partlist[$ctr].'" />'."\n";
2617: $ctr++;
2618: }
2619: $request->print($result.''."\n");
2620:
2621: # Done with printing info for one student
2622:
2623: $request->print('</div>');#LC_grade_show_user
2624:
2625:
2626: # print end of form
2627: if ($counter == $total) {
2628: my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
2629: $endform.='<input type="button" value="'.&mt('Save & Next').'" '.
2630: 'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
2631: $total.','.scalar(@partlist).');" target="_self" /> '."\n";
2632: my $ntstu ='<select name="NTSTU">'.
2633: '<option>1</option><option>2</option>'.
2634: '<option>3</option><option>5</option>'.
2635: '<option>7</option><option>10</option></select>'."\n";
2636: my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
2637: $ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
2638: $endform.=&mt('[_1]student(s)',$ntstu);
2639: $endform.=' <input type="button" value="'.&mt('Previous').'" '.
2640: 'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> '."\n".
2641: '<input type="button" value="'.&mt('Next').'" '.
2642: 'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> ';
2643: $endform.='<span class="LC_warning">'.
2644: &mt('(Next and Previous (student) do not save the scores.)').
2645: '</span>'."\n" ;
2646: $endform.="<input type='hidden' value='".&get_increment().
2647: "' name='increment' />";
2648: $endform.='</td></tr></table></form>';
2649: $request->print($endform);
2650: }
2651: return '';
2652: }
2653:
2654: sub check_collaborators {
2655: my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
2656: my ($result,@col_fullnames);
2657: my ($classlist,undef,$fullname) = &getclasslist('all','0');
2658: foreach my $part (keys(%$handgrade)) {
2659: my $ncol = &Apache::lonnet::EXT('resource.'.$part.
2660: '.maxcollaborators',
2661: $symb,$udom,$uname);
2662: next if ($ncol <= 0);
2663: $part =~ s/\_/\./g;
2664: next if ($record->{'resource.'.$part.'.collaborators'} eq '');
2665: my (@good_collaborators, @bad_collaborators);
2666: foreach my $possible_collaborator
2667: (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) {
2668: $possible_collaborator =~ s/[\$\^\(\)]//g;
2669: next if ($possible_collaborator eq '');
2670: my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
2671: $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
2672: next if ($co_name eq $uname && $co_dom eq $udom);
2673: # Doing this grep allows 'fuzzy' specification
2674: my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i,
2675: keys(%$classlist));
2676: if (! scalar(@matches)) {
2677: push(@bad_collaborators, $possible_collaborator);
2678: } else {
2679: push(@good_collaborators, @matches);
2680: }
2681: }
2682: if (scalar(@good_collaborators) != 0) {
2683: $result.='<br />'.&mt('Collaborators:').'<ol>';
2684: foreach my $name (@good_collaborators) {
2685: my ($lastname,$givenn) = split(/,/,$$fullname{$name});
2686: push(@col_fullnames, $givenn.' '.$lastname);
2687: $result.='<li>'.$fullname->{$name}.'</li>';
2688: }
2689: $result.='</ol><br />'."\n";
2690: my ($part)=split(/\./,$part);
2691: $result.='<input type="hidden" name="collaborator'.$counter.
2692: '" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
2693: "\n";
2694: }
2695: if (scalar(@bad_collaborators) > 0) {
2696: $result.='<div class="LC_warning">';
2697: $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
2698: $result .= '</div>';
2699: }
2700: if (scalar(@bad_collaborators > $ncol)) {
2701: $result .= '<div class="LC_warning">';
2702: $result .= &mt('This student has submitted too many '.
2703: 'collaborators. Maximum is [_1].',$ncol);
2704: $result .= '</div>';
2705: }
2706: }
2707: return ($result,$fullname,\@col_fullnames);
2708: }
2709:
2710: #--- Retrieve the last submission for all the parts
2711: sub get_last_submission {
2712: my ($returnhash,$is_tool)=@_;
2713: my (@string,$timestamp,%lasthidden);
2714: if ($$returnhash{'version'}) {
2715: my %lasthash=();
2716: my ($version);
2717: for ($version=1;$version<=$$returnhash{'version'};$version++) {
2718: foreach my $key (sort(split(/\:/,
2719: $$returnhash{$version.':keys'}))) {
2720: $lasthash{$key}=$$returnhash{$version.':'.$key};
2721: $timestamp =
2722: &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
2723: }
2724: }
2725: my (%typeparts,%randombytry);
2726: my $showsurv =
2727: &Apache::lonnet::allowed('vas',$env{'request.course.id'});
2728: foreach my $key (sort(keys(%lasthash))) {
2729: if ($key =~ /\.type$/) {
2730: if (($lasthash{$key} eq 'anonsurvey') ||
2731: ($lasthash{$key} eq 'anonsurveycred') ||
2732: ($lasthash{$key} eq 'randomizetry')) {
2733: my ($ign,@parts) = split(/\./,$key);
2734: pop(@parts);
2735: my $id = join('.',@parts);
2736: if ($lasthash{$key} eq 'randomizetry') {
2737: $randombytry{$ign.'.'.$id} = $lasthash{$key};
2738: } else {
2739: unless ($showsurv) {
2740: $typeparts{$ign.'.'.$id} = $lasthash{$key};
2741: }
2742: }
2743: delete($lasthash{$key});
2744: }
2745: }
2746: }
2747: my @hidden = keys(%typeparts);
2748: my @randomize = keys(%randombytry);
2749: foreach my $key (keys(%lasthash)) {
2750: next if ($key !~ /\.submission$/);
2751: my $hide;
2752: if (@hidden) {
2753: foreach my $id (@hidden) {
2754: if ($key =~ /^\Q$id\E/) {
2755: $hide = 'anon';
2756: last;
2757: }
2758: }
2759: }
2760: unless ($hide) {
2761: if (@randomize) {
2762: foreach my $id (@randomize) {
2763: if ($key =~ /^\Q$id\E/) {
2764: $hide = 'rand';
2765: last;
2766: }
2767: }
2768: }
2769: }
2770: my ($partid,$foo) = split(/submission$/,$key);
2771: my $draft = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1 : 0;
2772: push(@string, join(':', $key, $hide, $draft, (
2773: ref($lasthash{$key}) eq 'ARRAY' ?
2774: join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
2775: }
2776: }
2777: if (!@string) {
2778: my $msg;
2779: if ($is_tool) {
2780: $msg = &mt('No grade passed back.');
2781: } else {
2782: $msg = &mt('Nothing submitted - no attempts.');
2783: }
2784: $string[0] =
2785: '<span class="LC_warning">'.$msg.'</span>';
2786: }
2787: return (\@string,\$timestamp);
2788: }
2789:
2790: #--- High light keywords, with style choosen by user.
2791: sub keywords_highlight {
2792: my $string = shift;
2793: my $size = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
2794: my $styleon = $env{'form.kwstyle'} eq '' ? '' : $env{'form.kwstyle'};
2795: (my $styleoff = $styleon) =~ s/\</\<\//;
2796: my @keylist = split(/[,\s+]/,$env{'form.keywords'});
2797: foreach my $keyword (@keylist) {
2798: $string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
2799: }
2800: return $string;
2801: }
2802:
2803: # For Tasks provide a mechanism to display previous version for one specific student
2804:
2805: sub show_previous_task_version {
2806: my ($request,$symb) = @_;
2807: if ($symb eq '') {
2808: $request->print(
2809: '<span class="LC_error">'.
2810: &mt('Unable to handle ambiguous references.').
2811: '</span>');
2812: return '';
2813: }
2814: my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
2815: my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
2816: if (!&canview($usec)) {
2817: $request->print(
2818: '<span class="LC_warning">'.
2819: &mt('Unable to view previous version for requested student.').
2820: ' '.&mt('([_1] in section [_2] in course id [_3])',
2821: $uname.':'.$udom,$usec,$env{'request.course.id'}).
2822: '</span>');
2823: return;
2824: }
2825: my $mode = 'both';
2826: my $isTask = ($symb =~/\.task$/);
2827: if ($isTask) {
2828: if ($env{'form.previousversion'} =~ /^\d+$/) {
2829: if ($env{'form.fullname'} eq '') {
2830: $env{'form.fullname'} =
2831: &Apache::loncommon::plainname($uname,$udom,'lastname');
2832: }
2833: my $probtitle=&Apache::lonnet::gettitle($symb);
2834: $request->print("\n\n".
2835: '<div class="LC_grade_show_user">'.
2836: '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
2837: '</h2>'."\n");
2838: &Apache::lonxml::clear_problem_counter();
2839: $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
2840: {'previousversion' => $env{'form.previousversion'} }));
2841: $request->print("\n</div>");
2842: }
2843: }
2844: return;
2845: }
2846:
2847: sub choose_task_version_form {
2848: my ($symb,$uname,$udom,$nomenu) = @_;
2849: my $isTask = ($symb =~/\.task$/);
2850: my ($current,$version,$result,$js,$displayed,$rowtitle);
2851: if ($isTask) {
2852: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
2853: $udom,$uname);
2854: if (($record{'resource.0.version'} eq '') ||
2855: ($record{'resource.0.version'} < 2)) {
2856: return ($record{'resource.0.version'},
2857: $record{'resource.0.version'},$result,$js);
2858: } else {
2859: $current = $record{'resource.0.version'};
2860: }
2861: if ($env{'form.previousversion'}) {
2862: $displayed = $env{'form.previousversion'};
2863: $rowtitle = &mt('Choose another version:')
2864: } else {
2865: $displayed = $current;
2866: $rowtitle = &mt('Show earlier version:');
2867: }
2868: $result = '<div class="LC_left_float">';
2869: my $list;
2870: my $numversions = 0;
2871: for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
2872: if ($i == $current) {
2873: if (!$env{'form.previousversion'} || $nomenu) {
2874: next;
2875: } else {
2876: $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
2877: $numversions ++;
2878: }
2879: } elsif (defined($record{'resource.'.$i.'.0.status'})) {
2880: unless ($i == $env{'form.previousversion'}) {
2881: $numversions ++;
2882: }
2883: $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
2884: }
2885: }
2886: if ($numversions) {
2887: $symb = &HTML::Entities::encode($symb,'<>"&');
2888: $result .=
2889: '<form name="getprev" method="post" action=""'.
2890: ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
2891: &Apache::loncommon::start_data_table().
2892: &Apache::loncommon::start_data_table_row().
2893: '<th align="left">'.$rowtitle.'</th>'.
2894: '<td><select name="version">'.
2895: '<option>'.&mt('Select').'</option>'.
2896: $list.
2897: '</select></td>'.
2898: &Apache::loncommon::end_data_table_row();
2899: unless ($nomenu) {
2900: $result .= &Apache::loncommon::start_data_table_row().
2901: '<th align="left">'.&mt('Open in new window').'</th>'.
2902: '<td><span class="LC_nobreak">'.
2903: '<label><input type="radio" name="prevwin" value="1" />'.
2904: &mt('Yes').'</label>'.
2905: '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
2906: '</span></td>'.
2907: &Apache::loncommon::end_data_table_row();
2908: }
2909: $result .=
2910: &Apache::loncommon::start_data_table_row().
2911: '<th align="left"> </th>'.
2912: '<td>'.
2913: '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
2914: '</td>'.
2915: &Apache::loncommon::end_data_table_row().
2916: &Apache::loncommon::end_data_table().
2917: '</form>';
2918: $js = &previous_display_javascript($nomenu,$current);
2919: } elsif ($displayed && $nomenu) {
2920: $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
2921: } else {
2922: $result .= &mt('No previous versions to show for this student');
2923: }
2924: $result .= '</div>';
2925: }
2926: return ($current,$displayed,$result,$js);
2927: }
2928:
2929: sub previous_display_javascript {
2930: my ($nomenu,$current) = @_;
2931: my $js = <<"JSONE";
2932: <script type="text/javascript">
2933: // <![CDATA[
2934: function previousVersion(uname,udom,symb) {
2935: var current = '$current';
2936: var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
2937: var prevstr = new RegExp("^\\\\d+\$");
2938: if (!prevstr.test(version)) {
2939: return false;
2940: }
2941: var url = '';
2942: if (version == current) {
2943: url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
2944: } else {
2945: url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
2946: }
2947: JSONE
2948: if ($nomenu) {
2949: $js .= <<"JSTWO";
2950: document.location.href = url;
2951: JSTWO
2952: } else {
2953: $js .= <<"JSTHREE";
2954: var newwin = 0;
2955: for (var i=0; i<document.getprev.prevwin.length; i++) {
2956: if (document.getprev.prevwin[i].checked == true) {
2957: newwin = document.getprev.prevwin[i].value;
2958: }
2959: }
2960: if (newwin == 1) {
2961: var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
2962: url = url+'&inhibitmenu=yes';
2963: if (typeof(previousWin) == 'undefined' || previousWin.closed) {
2964: previousWin = window.open(url,'',options,1);
2965: } else {
2966: previousWin.location.href = url;
2967: }
2968: previousWin.focus();
2969: return false;
2970: } else {
2971: document.location.href = url;
2972: return false;
2973: }
2974: JSTHREE
2975: }
2976: $js .= <<"ENDJS";
2977: return false;
2978: }
2979: // ]]>
2980: </script>
2981: ENDJS
2982:
2983: }
2984:
2985: #--- Called from submission routine
2986: sub processHandGrade {
2987: my ($request,$symb) = @_;
2988: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
2989: my $button = $env{'form.gradeOpt'};
2990: my $ngrade = $env{'form.NCT'};
2991: my $ntstu = $env{'form.NTSTU'};
2992: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2993: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2994:
2995: if ($button eq 'Save & Next') {
2996: my $ctr = 0;
2997: while ($ctr < $ngrade) {
2998: my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
2999: my ($errorflag,$pts,$wgt,$numhidden) =
3000: &saveHandGrade($request,$symb,$uname,$udom,$ctr);
3001: if ($errorflag eq 'no_score') {
3002: $ctr++;
3003: next;
3004: }
3005: if ($errorflag eq 'not_allowed') {
3006: $request->print(
3007: '<span class="LC_error">'
3008: .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
3009: .'</span>');
3010: $ctr++;
3011: next;
3012: }
3013: if ($numhidden) {
3014: $request->print(
3015: '<span class="LC_info">'
3016: .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
3017: .'</span><br />');
3018: }
3019: my $includemsg = $env{'form.includemsg'.$ctr};
3020: my ($subject,$message,$msgstatus) = ('','','');
3021: my $restitle = &Apache::lonnet::gettitle($symb);
3022: my ($feedurl,$showsymb) =
3023: &get_feedurl_and_symb($symb,$uname,$udom);
3024: my $messagetail;
3025: if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
3026: $subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
3027: unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
3028: $subject.=' ['.$restitle.']';
3029: my (@msgnum) = split(/,/,$includemsg);
3030: foreach (@msgnum) {
3031: $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
3032: }
3033: $message =&Apache::lonfeedback::clear_out_html($message);
3034: if ($env{'form.withgrades'.$ctr}) {
3035: $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
3036: $messagetail = " for <a href=\"".
3037: $feedurl."?symb=$showsymb\">$restitle</a>";
3038: }
3039: $msgstatus =
3040: &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
3041: $message.$messagetail,
3042: undef,$feedurl,undef,
3043: undef,undef,$showsymb,
3044: $restitle);
3045: $request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
3046: $msgstatus.'<br />');
3047: }
3048: if ($env{'form.collaborator'.$ctr}) {
3049: my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
3050: foreach my $collabstr (@collabstrs) {
3051: my ($part,@collaborators) = split(/:/,$collabstr);
3052: foreach my $collaborator (@collaborators) {
3053: my ($errorflag,$pts,$wgt) =
3054: &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
3055: $env{'form.unamedom'.$ctr},$part);
3056: if ($errorflag eq 'not_allowed') {
3057: $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
3058: next;
3059: } elsif ($message ne '') {
3060: my ($baseurl,$showsymb) =
3061: &get_feedurl_and_symb($symb,$collaborator,
3062: $udom);
3063: if ($env{'form.withgrades'.$ctr}) {
3064: $messagetail = " for <a href=\"".
3065: $baseurl."?symb=$showsymb\">$restitle</a>";
3066: }
3067: $msgstatus =
3068: &Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
3069: }
3070: }
3071: }
3072: }
3073: $ctr++;
3074: }
3075: }
3076:
3077: # if ($env{'form.handgrade'} eq 'yes') {
3078: if (1) {
3079: # Keywords sorted in alphabatical order
3080: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
3081: my %keyhash = ();
3082: $env{'form.keywords'} =~ s/,\s{0,}|\s+/ /g;
3083: $env{'form.keywords'} =~ s/^\s+|\s+$//;
3084: my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
3085: $env{'form.keywords'} = join(' ',@keywords);
3086: $keyhash{$symb.'_keywords'} = $env{'form.keywords'};
3087: $keyhash{$symb.'_subject'} = $env{'form.msgsub'};
3088: $keyhash{$loginuser.'_kwclr'} = $env{'form.kwclr'};
3089: $keyhash{$loginuser.'_kwsize'} = $env{'form.kwsize'};
3090: $keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
3091:
3092: # message center - Order of message gets changed. Blank line is eliminated.
3093: # New messages are saved in env for the next student.
3094: # All messages are saved in nohist_handgrade.db
3095: my ($ctr,$idx) = (1,1);
3096: while ($ctr <= $env{'form.savemsgN'}) {
3097: if ($env{'form.savemsg'.$ctr} ne '') {
3098: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
3099: $idx++;
3100: }
3101: $ctr++;
3102: }
3103: $ctr = 0;
3104: while ($ctr < $ngrade) {
3105: if ($env{'form.newmsg'.$ctr} ne '') {
3106: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
3107: $env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
3108: $idx++;
3109: }
3110: $ctr++;
3111: }
3112: $env{'form.savemsgN'} = --$idx;
3113: $keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
3114: my $putresult = &Apache::lonnet::put
3115: ('nohist_handgrade',\%keyhash,$cdom,$cnum);
3116: }
3117: # Called by Save & Refresh from Highlight Attribute Window
3118: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
3119: if ($env{'form.refresh'} eq 'on') {
3120: my ($ctr,$total) = (0,0);
3121: while ($ctr < $ngrade) {
3122: $total++ if $env{'form.unamedom'.$ctr} ne '';
3123: $ctr++;
3124: }
3125: $env{'form.NTSTU'}=$ngrade;
3126: $ctr = 0;
3127: while ($ctr < $total) {
3128: my $processUser = $env{'form.unamedom'.$ctr};
3129: ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
3130: $env{'form.fullname'} = $$fullname{$processUser};
3131: &submission($request,$ctr,$total-1,$symb);
3132: $ctr++;
3133: }
3134: return '';
3135: }
3136:
3137: # Get the next/previous one or group of students
3138: my $firststu = $env{'form.unamedom0'};
3139: my $laststu = $env{'form.unamedom'.($ngrade-1)};
3140: my $ctr = 2;
3141: while ($laststu eq '') {
3142: $laststu = $env{'form.unamedom'.($ngrade-$ctr)};
3143: $ctr++;
3144: $laststu = $firststu if ($ctr > $ngrade);
3145: }
3146:
3147: my (@parsedlist,@nextlist);
3148: my ($nextflg) = 0;
3149: foreach my $item (sort
3150: {
3151: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
3152: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
3153: }
3154: return $a cmp $b;
3155: } (keys(%$fullname))) {
3156: # FIXME: this is fishy, looks like the button label
3157: if ($nextflg == 1 && $button =~ /Next$/) {
3158: push(@parsedlist,$item);
3159: }
3160: $nextflg = 1 if ($item eq $laststu);
3161: if ($button eq 'Previous') {
3162: last if ($item eq $firststu);
3163: push(@parsedlist,$item);
3164: }
3165: }
3166: $ctr = 0;
3167: # FIXME: this is fishy, looks like the button label
3168: @parsedlist = reverse @parsedlist if ($button eq 'Previous');
3169: my $res_error;
3170: my ($partlist) = &response_type($symb,\$res_error);
3171: if ($res_error) {
3172: $request->print(&navmap_errormsg());
3173: return;
3174: }
3175: foreach my $student (@parsedlist) {
3176: my $submitonly=$env{'form.submitonly'};
3177: my ($uname,$udom) = split(/:/,$student);
3178:
3179: if ($submitonly eq 'queued') {
3180: my %queue_status =
3181: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
3182: $udom,$uname);
3183: next if (!defined($queue_status{'gradingqueue'}));
3184: }
3185:
3186: if ($submitonly =~ /^(yes|graded|incorrect)$/) {
3187: # my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
3188: my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
3189: my $submitted = 0;
3190: my $ungraded = 0;
3191: my $incorrect = 0;
3192: foreach my $item (keys(%status)) {
3193: $submitted = 1 if ($status{$item} ne 'nothing');
3194: $ungraded = 1 if ($status{$item} =~ /^ungraded/);
3195: $incorrect = 1 if ($status{$item} =~ /^incorrect/);
3196: my ($foo,$partid,$foo1) = split(/\./,$item);
3197: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
3198: $submitted = 0;
3199: }
3200: }
3201: next if (!$submitted && ($submitonly eq 'yes' ||
3202: $submitonly eq 'incorrect' ||
3203: $submitonly eq 'graded'));
3204: next if (!$ungraded && ($submitonly eq 'graded'));
3205: next if (!$incorrect && $submitonly eq 'incorrect');
3206: }
3207: push(@nextlist,$student) if ($ctr < $ntstu);
3208: last if ($ctr == $ntstu);
3209: $ctr++;
3210: }
3211:
3212: $ctr = 0;
3213: my $total = scalar(@nextlist)-1;
3214:
3215: foreach (sort(@nextlist)) {
3216: my ($uname,$udom,$submitter) = split(/:/);
3217: $env{'form.student'} = $uname;
3218: $env{'form.userdom'} = $udom;
3219: $env{'form.fullname'} = $$fullname{$_};
3220: &submission($request,$ctr,$total,$symb);
3221: $ctr++;
3222: }
3223: if ($total < 0) {
3224: my $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
3225: $request->print($the_end);
3226: }
3227: return '';
3228: }
3229:
3230: #---- Save the score and award for each student, if changed
3231: sub saveHandGrade {
3232: my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
3233: my @version_parts;
3234: my $usec = &Apache::lonnet::getsection($domain,$stuname,
3235: $env{'request.course.id'});
3236: if (!&canmodify($usec)) { return('not_allowed'); }
3237: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
3238: my @parts_graded;
3239: my %newrecord = ();
3240: my ($pts,$wgt,$totchg) = ('','',0);
3241: my %aggregate = ();
3242: my $aggregateflag = 0;
3243: if ($env{'form.HIDE'.$newflg}) {
3244: my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
3245: my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
3246: $totchg += $numchgs;
3247: }
3248: my @parts = split(/:/,$env{'form.partlist'.$newflg});
3249: foreach my $new_part (@parts) {
3250: #collaborator ($submi may vary for different parts
3251: if ($submitter && $new_part ne $part) { next; }
3252: my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
3253: if ($dropMenu eq 'excused') {
3254: if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
3255: $newrecord{'resource.'.$new_part.'.solved'} = 'excused';
3256: if (exists($record{'resource.'.$new_part.'.awarded'})) {
3257: $newrecord{'resource.'.$new_part.'.awarded'} = '';
3258: }
3259: $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
3260: }
3261: } elsif ($dropMenu eq 'reset status'
3262: && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
3263: foreach my $key (keys(%record)) {
3264: if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
3265: }
3266: $newrecord{'resource.'.$new_part.'.regrader'}=
3267: "$env{'user.name'}:$env{'user.domain'}";
3268: my $totaltries = $record{'resource.'.$part.'.tries'};
3269:
3270: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
3271: [$new_part]);
3272: my $aggtries =$totaltries;
3273: if ($last_resets{$new_part}) {
3274: $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
3275: $new_part);
3276: }
3277:
3278: my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
3279: if ($aggtries > 0) {
3280: &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
3281: $aggregateflag = 1;
3282: }
3283: } elsif ($dropMenu eq '') {
3284: $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ?
3285: $env{'form.GD_BOX'.$newflg.'_'.$new_part} :
3286: $env{'form.RADVAL'.$newflg.'_'.$new_part});
3287: if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
3288: next;
3289: }
3290: $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 :
3291: $env{'form.WGT'.$newflg.'_'.$new_part};
3292: my $partial= $pts/$wgt;
3293: if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
3294: #do not update score for part if not changed.
3295: &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
3296: next;
3297: } else {
3298: push(@parts_graded,$new_part);
3299: }
3300: if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
3301: $newrecord{'resource.'.$new_part.'.awarded'} = $partial;
3302: }
3303: my $reckey = 'resource.'.$new_part.'.solved';
3304: if ($partial == 0) {
3305: if ($record{$reckey} ne 'incorrect_by_override') {
3306: $newrecord{$reckey} = 'incorrect_by_override';
3307: }
3308: } else {
3309: if ($record{$reckey} ne 'correct_by_override') {
3310: $newrecord{$reckey} = 'correct_by_override';
3311: }
3312: }
3313: if ($submitter &&
3314: ($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
3315: $newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
3316: }
3317: $newrecord{'resource.'.$new_part.'.regrader'}=
3318: "$env{'user.name'}:$env{'user.domain'}";
3319: }
3320: # unless problem has been graded, set flag to version the submitted files
3321: unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/ ||
3322: $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
3323: $dropMenu eq 'reset status')
3324: {
3325: push(@version_parts,$new_part);
3326: }
3327: }
3328: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3329: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3330:
3331: if (%newrecord) {
3332: if (@version_parts) {
3333: my @changed_keys = &version_portfiles(\%record, \@parts_graded,
3334: $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
3335: @newrecord{@changed_keys} = @record{@changed_keys};
3336: foreach my $new_part (@version_parts) {
3337: &handback_files($request,$symb,$stuname,$domain,$newflg,
3338: $new_part,\%newrecord);
3339: }
3340: }
3341: &Apache::lonnet::cstore(\%newrecord,$symb,
3342: $env{'request.course.id'},$domain,$stuname);
3343: &check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
3344: $cdom,$cnum,$domain,$stuname);
3345: }
3346: if ($aggregateflag) {
3347: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
3348: $cdom,$cnum);
3349: }
3350: return ('',$pts,$wgt,$totchg);
3351: }
3352:
3353: sub makehidden {
3354: my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
3355: return unless (ref($record) eq 'HASH');
3356: my %modified;
3357: my $numchanged = 0;
3358: if (exists($record->{$version.':keys'})) {
3359: my $partsregexp = $parts;
3360: $partsregexp =~ s/,/|/g;
3361: foreach my $key (split(/\:/,$record->{$version.':keys'})) {
3362: if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
3363: my $item = $1;
3364: unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
3365: $modified{$key} = $record->{$version.':'.$key};
3366: }
3367: } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
3368: $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
3369: } elsif ($key =~ /^(ip|timestamp|host)$/) {
3370: $modified{$key} = $record->{$version.':'.$key};
3371: }
3372: }
3373: if (keys(%modified)) {
3374: if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
3375: $domain,$stuname,$tolog) eq 'ok') {
3376: $numchanged ++;
3377: }
3378: }
3379: }
3380: return $numchanged;
3381: }
3382:
3383: sub check_and_remove_from_queue {
3384: my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
3385: my @ungraded_parts;
3386: foreach my $part (@{$parts}) {
3387: if ( $record->{ 'resource.'.$part.'.awarded'} eq ''
3388: && $record->{ 'resource.'.$part.'.solved' } ne 'excused'
3389: && $newrecord->{'resource.'.$part.'.awarded'} eq ''
3390: && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
3391: ) {
3392: push(@ungraded_parts, $part);
3393: }
3394: }
3395: if ( !@ungraded_parts ) {
3396: &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
3397: $cnum,$domain,$stuname);
3398: }
3399: }
3400:
3401: sub handback_files {
3402: my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
3403: my $portfolio_root = '/userfiles/portfolio';
3404: my $res_error;
3405: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
3406: if ($res_error) {
3407: $request->print('<br />'.&navmap_errormsg().'<br />');
3408: return;
3409: }
3410: my @handedback;
3411: my $file_msg;
3412: my @part_response_id = &flatten_responseType($responseType);
3413: foreach my $part_response_id (@part_response_id) {
3414: my ($part_id,$resp_id) = @{ $part_response_id };
3415: my $part_resp = join('_',@{ $part_response_id });
3416: if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
3417: for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
3418: # if multiple files are uploaded names will be 'returndoc2','returndoc3'
3419: if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
3420: my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
3421: my ($directory,$answer_file) =
3422: ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
3423: my ($answer_name,$answer_ver,$answer_ext) =
3424: &Apache::lonnet::file_name_version_ext($answer_file);
3425: my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
3426: my $getpropath = 1;
3427: my ($dir_list,$listerror) =
3428: &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
3429: $domain,$stuname,$getpropath);
3430: my $version = &Apache::lonnet::get_next_version($answer_name,$answer_ext,$dir_list);
3431: # fix filename
3432: my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
3433: my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
3434: $newflg.'_'.$part_resp.'_returndoc'.$counter,
3435: $save_file_name);
3436: if ($result !~ m|^/uploaded/|) {
3437: $request->print('<br /><span class="LC_error">'.
3438: &mt('An error occurred ([_1]) while trying to upload [_2].',
3439: $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
3440: '</span>');
3441: } else {
3442: # mark the file as read only
3443: push(@handedback,$save_file_name);
3444: if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
3445: $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
3446: }
3447: $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
3448: $file_msg.= '<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
3449: }
3450: $request->print('<br />'.&mt('[_1] will be the uploaded filename [_2]','<span class="LC_info">'.$fname.'</span>','<span class="LC_filename">'.$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter}.'</span>'));
3451: }
3452: }
3453: }
3454: }
3455: if (@handedback > 0) {
3456: $request->print('<br />');
3457: my @what = ($symb,$env{'request.course.id'},'handback');
3458: &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
3459: my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});
3460: my ($subject,$message);
3461: if (scalar(@handedback) == 1) {
3462: $subject = &mt_user($user_lh,'File Handed Back by Instructor');
3463: $message = &mt_user($user_lh,'A file has been returned that was originally submitted in response to: ');
3464: } else {
3465: $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
3466: $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
3467: }
3468: $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
3469: $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
3470: &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
3471: my ($feedurl,$showsymb) =
3472: &get_feedurl_and_symb($symb,$domain,$stuname);
3473: my $restitle = &Apache::lonnet::gettitle($symb);
3474: $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
3475: my $msgstatus =
3476: &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
3477: $message,undef,$feedurl,undef,undef,undef,$showsymb,
3478: $restitle);
3479: if ($msgstatus) {
3480: $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
3481: }
3482: }
3483: return;
3484: }
3485:
3486: sub get_feedurl_and_symb {
3487: my ($symb,$uname,$udom) = @_;
3488: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3489: $url = &Apache::lonnet::clutter($url);
3490: my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
3491: $symb,$udom,$uname);
3492: if ($encrypturl =~ /^yes$/i) {
3493: &Apache::lonenc::encrypted(\$url,1);
3494: &Apache::lonenc::encrypted(\$symb,1);
3495: }
3496: return ($url,$symb);
3497: }
3498:
3499: sub get_submitted_files {
3500: my ($udom,$uname,$partid,$respid,$record) = @_;
3501: my @files;
3502: if ($$record{"resource.$partid.$respid.portfiles"}) {
3503: my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
3504: foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
3505: push(@files,$file_url.$file);
3506: }
3507: }
3508: if ($$record{"resource.$partid.$respid.uploadedurl"}) {
3509: push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
3510: }
3511: return (\@files);
3512: }
3513:
3514: # ----------- Provides number of tries since last reset.
3515: sub get_num_tries {
3516: my ($record,$last_reset,$part) = @_;
3517: my $timestamp = '';
3518: my $num_tries = 0;
3519: if ($$record{'version'}) {
3520: for (my $version=$$record{'version'};$version>=1;$version--) {
3521: if (exists($$record{$version.':resource.'.$part.'.solved'})) {
3522: $timestamp = $$record{$version.':timestamp'};
3523: if ($timestamp > $last_reset) {
3524: $num_tries ++;
3525: } else {
3526: last;
3527: }
3528: }
3529: }
3530: }
3531: return $num_tries;
3532: }
3533:
3534: # ----------- Determine decrements required in aggregate totals
3535: sub decrement_aggs {
3536: my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
3537: my %decrement = (
3538: attempts => 0,
3539: users => 0,
3540: correct => 0
3541: );
3542: $decrement{'attempts'} = $aggtries;
3543: if ($solvedstatus =~ /^correct/) {
3544: $decrement{'correct'} = 1;
3545: }
3546: if ($aggtries == $totaltries) {
3547: $decrement{'users'} = 1;
3548: }
3549: foreach my $type (keys(%decrement)) {
3550: $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
3551: }
3552: return;
3553: }
3554:
3555: # ----------- Determine timestamps for last reset of aggregate totals for parts
3556: sub get_last_resets {
3557: my ($symb,$courseid,$partids) =@_;
3558: my %last_resets;
3559: my $cdom = $env{'course.'.$courseid.'.domain'};
3560: my $cname = $env{'course.'.$courseid.'.num'};
3561: my @keys;
3562: foreach my $part (@{$partids}) {
3563: push(@keys,"$symb\0$part\0resettime");
3564: }
3565: my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
3566: $cdom,$cname);
3567: foreach my $part (@{$partids}) {
3568: $last_resets{$part}=$results{"$symb\0$part\0resettime"};
3569: }
3570: return %last_resets;
3571: }
3572:
3573: # ----------- Handles creating versions for portfolio files as answers
3574: sub version_portfiles {
3575: my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
3576: my $version_parts = join('|',@$v_flag);
3577: my @returned_keys;
3578: my $parts = join('|', @$parts_graded);
3579: foreach my $key (keys(%$record)) {
3580: my $new_portfiles;
3581: if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
3582: my @versioned_portfiles;
3583: my @portfiles = split(/\s*,\s*/,$$record{$key});
3584: if (@portfiles) {
3585: &Apache::lonnet::portfiles_versioning($symb,$domain,$stu_name,\@portfiles,
3586: \@versioned_portfiles);
3587: }
3588: $$record{$key} = join(',',@versioned_portfiles);
3589: push(@returned_keys,$key);
3590: }
3591: }
3592: return (@returned_keys);
3593: }
3594:
3595: #--------------------------------------------------------------------------------------
3596: #
3597: #-------------------------- Next few routines handles grading by section or whole class
3598: #
3599: #--- Javascript to handle grading by section or whole class
3600: sub viewgrades_js {
3601: my ($request) = shift;
3602:
3603: my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
3604: &js_escape(\$alertmsg);
3605: $request->print(&Apache::lonhtmlcommon::scripttag(<<VIEWJAVASCRIPT));
3606: function writePoint(partid,weight,point) {
3607: var radioButton = document.classgrade["RADVAL_"+partid];
3608: var textbox = document.classgrade["TEXTVAL_"+partid];
3609: if (point == "textval") {
3610: point = document.classgrade["TEXTVAL_"+partid].value;
3611: if (isNaN(point) || parseFloat(point) < 0) {
3612: alert("$alertmsg"+parseFloat(point));
3613: var resetbox = false;
3614: for (var i=0; i<radioButton.length; i++) {
3615: if (radioButton[i].checked) {
3616: textbox.value = i;
3617: resetbox = true;
3618: }
3619: }
3620: if (!resetbox) {
3621: textbox.value = "";
3622: }
3623: return;
3624: }
3625: if (parseFloat(point) > parseFloat(weight)) {
3626: var resp = confirm("You entered a value ("+parseFloat(point)+
3627: ") greater than the weight for the part. Accept?");
3628: if (resp == false) {
3629: textbox.value = "";
3630: return;
3631: }
3632: }
3633: for (var i=0; i<radioButton.length; i++) {
3634: radioButton[i].checked=false;
3635: if (parseFloat(point) == i) {
3636: radioButton[i].checked=true;
3637: }
3638: }
3639:
3640: } else {
3641: textbox.value = parseFloat(point);
3642: }
3643: for (i=0;i<document.classgrade.total.value;i++) {
3644: var user = document.classgrade["ctr"+i].value;
3645: user = user.replace(new RegExp(':', 'g'),"_");
3646: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3647: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3648: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3649: if (saveval != "correct") {
3650: scorename.value = point;
3651: if (selname[0].selected != true) {
3652: selname[0].selected = true;
3653: }
3654: }
3655: }
3656: document.classgrade["SELVAL_"+partid][0].selected = true;
3657: }
3658:
3659: function writeRadText(partid,weight) {
3660: var selval = document.classgrade["SELVAL_"+partid];
3661: var radioButton = document.classgrade["RADVAL_"+partid];
3662: var override = document.classgrade["FORCE_"+partid].checked;
3663: var textbox = document.classgrade["TEXTVAL_"+partid];
3664: if (selval[1].selected || selval[2].selected) {
3665: for (var i=0; i<radioButton.length; i++) {
3666: radioButton[i].checked=false;
3667:
3668: }
3669: textbox.value = "";
3670:
3671: for (i=0;i<document.classgrade.total.value;i++) {
3672: var user = document.classgrade["ctr"+i].value;
3673: user = user.replace(new RegExp(':', 'g'),"_");
3674: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3675: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3676: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3677: if ((saveval != "correct") || override) {
3678: scorename.value = "";
3679: if (selval[1].selected) {
3680: selname[1].selected = true;
3681: } else {
3682: selname[2].selected = true;
3683: if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value))
3684: {document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
3685: }
3686: }
3687: }
3688: } else {
3689: for (i=0;i<document.classgrade.total.value;i++) {
3690: var user = document.classgrade["ctr"+i].value;
3691: user = user.replace(new RegExp(':', 'g'),"_");
3692: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3693: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3694: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3695: if ((saveval != "correct") || override) {
3696: scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
3697: selname[0].selected = true;
3698: }
3699: }
3700: }
3701: }
3702:
3703: function changeSelect(partid,user) {
3704: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
3705: var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
3706: var point = textbox.value;
3707: var weight = document.classgrade["weight_"+partid].value;
3708:
3709: if (isNaN(point) || parseFloat(point) < 0) {
3710: alert("$alertmsg"+parseFloat(point));
3711: textbox.value = "";
3712: return;
3713: }
3714: if (parseFloat(point) > parseFloat(weight)) {
3715: var resp = confirm("You entered a value ("+parseFloat(point)+
3716: ") greater than the weight of the part. Accept?");
3717: if (resp == false) {
3718: textbox.value = "";
3719: return;
3720: }
3721: }
3722: selval[0].selected = true;
3723: }
3724:
3725: function changeOneScore(partid,user) {
3726: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
3727: if (selval[1].selected || selval[2].selected) {
3728: document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
3729: if (selval[2].selected) {
3730: document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
3731: }
3732: }
3733: }
3734:
3735: function resetEntry(numpart) {
3736: for (ctpart=0;ctpart<numpart;ctpart++) {
3737: var partid = document.classgrade["partid_"+ctpart].value;
3738: var radioButton = document.classgrade["RADVAL_"+partid];
3739: var textbox = document.classgrade["TEXTVAL_"+partid];
3740: var selval = document.classgrade["SELVAL_"+partid];
3741: for (var i=0; i<radioButton.length; i++) {
3742: radioButton[i].checked=false;
3743:
3744: }
3745: textbox.value = "";
3746: selval[0].selected = true;
3747:
3748: for (i=0;i<document.classgrade.total.value;i++) {
3749: var user = document.classgrade["ctr"+i].value;
3750: user = user.replace(new RegExp(':', 'g'),"_");
3751: var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3752: resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
3753: var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
3754: resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
3755: var saveselval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3756: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3757: if (saveselval == "excused") {
3758: if (selname[1].selected == false) { selname[1].selected = true;}
3759: } else {
3760: if (selname[0].selected == false) {selname[0].selected = true};
3761: }
3762: }
3763: }
3764: }
3765:
3766: VIEWJAVASCRIPT
3767: }
3768:
3769: #--- show scores for a section or whole class w/ option to change/update a score
3770: sub viewgrades {
3771: my ($request,$symb) = @_;
3772: my ($is_tool,$toolsymb);
3773: if ($symb =~ /ext\.tool$/) {
3774: $is_tool = 1;
3775: $toolsymb = $symb;
3776: }
3777: &viewgrades_js($request);
3778:
3779: #need to make sure we have the correct data for later EXT calls,
3780: #thus invalidate the cache
3781: &Apache::lonnet::devalidatecourseresdata(
3782: $env{'course.'.$env{'request.course.id'}.'.num'},
3783: $env{'course.'.$env{'request.course.id'}.'.domain'});
3784: &Apache::lonnet::clear_EXT_cache_status();
3785:
3786: my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
3787:
3788: #view individual student submission form - called using Javascript viewOneStudent
3789: $result.=&jscriptNform($symb);
3790:
3791: #beginning of class grading form
3792: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
3793: $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
3794: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
3795: '<input type="hidden" name="command" value="editgrades" />'."\n".
3796: &build_section_inputs().
3797: '<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
3798:
3799: #retrieve selected groups
3800: my (@groups,$group_display);
3801: @groups = &Apache::loncommon::get_env_multiple('form.group');
3802: if (grep(/^all$/,@groups)) {
3803: @groups = ('all');
3804: } elsif (grep(/^none$/,@groups)) {
3805: @groups = ('none');
3806: } elsif (@groups > 0) {
3807: $group_display = join(', ',@groups);
3808: }
3809:
3810: my ($common_header,$specific_header,@sections,$section_display);
3811: @sections = &Apache::loncommon::get_env_multiple('form.section');
3812: if (grep(/^all$/,@sections)) {
3813: @sections = ('all');
3814: if ($group_display) {
3815: $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
3816: $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
3817: } elsif (grep(/^none$/,@groups)) {
3818: $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
3819: $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
3820: } else {
3821: $common_header = &mt('Assign Common Grade to Class');
3822: $specific_header = &mt('Assign Grade to Specific Students in Class');
3823: }
3824: } elsif (grep(/^none$/,@sections)) {
3825: @sections = ('none');
3826: if ($group_display) {
3827: $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
3828: $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
3829: } elsif (grep(/^none$/,@groups)) {
3830: $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
3831: $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
3832: } else {
3833: $common_header = &mt('Assign Common Grade to Students in no Section');
3834: $specific_header = &mt('Assign Grade to Specific Students in no Section');
3835: }
3836: } else {
3837: $section_display = join (", ",@sections);
3838: if ($group_display) {
3839: $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
3840: $section_display,$group_display);
3841: $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
3842: $section_display,$group_display);
3843: } elsif (grep(/^none$/,@groups)) {
3844: $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
3845: $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
3846: } else {
3847: $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
3848: $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
3849: }
3850: }
3851: my %submit_types = &substatus_options();
3852: my $submission_status = $submit_types{$env{'form.submitonly'}};
3853:
3854: if ($env{'form.submitonly'} eq 'all') {
3855: $result.= '<h3>'.$common_header.'</h3>';
3856: } else {
3857: my $text;
3858: if ($is_tool) {
3859: $text = &mt('(transaction status: "[_1]")',$submission_status);
3860: } else {
3861: $text = &mt('(submission status: "[_1]")',$submission_status);
3862: }
3863: $result.= '<h3>'.$common_header.' '.$text.'</h3>';
3864: }
3865: $result .= &Apache::loncommon::start_data_table();
3866: #radio buttons/text box for assigning points for a section or class.
3867: #handles different parts of a problem
3868: my $res_error;
3869: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
3870: if ($res_error) {
3871: return &navmap_errormsg();
3872: }
3873: my %weight = ();
3874: my $ctsparts = 0;
3875: my %seen = ();
3876: my @part_response_id;
3877: if ($is_tool) {
3878: @part_response_id = ([0,'']);
3879: } else {
3880: @part_response_id = &flatten_responseType($responseType);
3881: }
3882: foreach my $part_response_id (@part_response_id) {
3883: my ($partid,$respid) = @{ $part_response_id };
3884: my $part_resp = join('_',@{ $part_response_id });
3885: next if $seen{$partid};
3886: $seen{$partid}++;
3887: # my $handgrade=$$handgrade{$part_resp};
3888: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
3889: $weight{$partid} = $wgt eq '' ? '1' : $wgt;
3890:
3891: my $display_part=&get_display_part($partid,$symb);
3892: my $radio.='<table border="0"><tr>';
3893: my $ctr = 0;
3894: while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
3895: $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
3896: 'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
3897: ','.$ctr.')" />'.$ctr."</label></td>\n";
3898: $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
3899: $ctr++;
3900: }
3901: $radio.='</tr></table>';
3902: my $line = '<input type="text" name="TEXTVAL_'.
3903: $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
3904: $partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
3905: $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
3906: $line.= '<td><b>'.&mt('Grade Status').':</b>'.
3907: '<select name="SELVAL_'.$partid.'" '.
3908: 'onchange="javascript:writeRadText(\''.$partid.'\','.
3909: $weight{$partid}.')"> '.
3910: '<option selected="selected"> </option>'.
3911: '<option value="excused">'.&mt('excused').'</option>'.
3912: '<option value="reset status">'.&mt('reset status').'</option>'.
3913: '</select></td>'.
3914: '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
3915: $line.='<input type="hidden" name="partid_'.
3916: $ctsparts.'" value="'.$partid.'" />'."\n";
3917: $line.='<input type="hidden" name="weight_'.
3918: $partid.'" value="'.$weight{$partid}.'" />'."\n";
3919:
3920: $result.=
3921: &Apache::loncommon::start_data_table_row()."\n".
3922: '<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>'.
3923: &Apache::loncommon::end_data_table_row()."\n";
3924: $ctsparts++;
3925: }
3926: $result.=&Apache::loncommon::end_data_table()."\n".
3927: '<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
3928: $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
3929: 'onclick="javascript:resetEntry('.$ctsparts.');" />';
3930:
3931: #table listing all the students in a section/class
3932: #header of table
3933: if ($env{'form.submitonly'} eq 'all') {
3934: $result.= '<h3>'.$specific_header.'</h3>';
3935: } else {
3936: my $text;
3937: if ($is_tool) {
3938: $text = &mt('(transaction status: "[_1]")',$submission_status);
3939: } else {
3940: $text = &mt('(submission status: "[_1]")',$submission_status);
3941: }
3942: $result.= '<h3>'.$specific_header.' '.$text.'</h3>';
3943: }
3944: $result.= &Apache::loncommon::start_data_table().
3945: &Apache::loncommon::start_data_table_header_row().
3946: '<th>'.&mt('No.').'</th>'.
3947: '<th>'.&nameUserString('header')."</th>\n";
3948: my $partserror;
3949: my (@parts) = sort(&getpartlist($symb,\$partserror));
3950: if ($partserror) {
3951: return &navmap_errormsg();
3952: }
3953: my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
3954: my @partids = ();
3955: foreach my $part (@parts) {
3956: my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
3957: my $narrowtext = &mt('Tries');
3958: $display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
3959: if (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name',$toolsymb); }
3960: my ($partid) = &split_part_type($part);
3961: push(@partids,$partid);
3962: #
3963: # FIXME: Looks like $display looks at English text
3964: #
3965: my $display_part=&get_display_part($partid,$symb);
3966: if ($display =~ /^Partial Credit Factor/) {
3967: $result.='<th>'.
3968: &mt('Score Part: [_1][_2](weight = [_3])',
3969: $display_part,'<br />',$weight{$partid}).'</th>'."\n";
3970: next;
3971:
3972: } else {
3973: if ($display =~ /Problem Status/) {
3974: my $grade_status_mt = &mt('Grade Status');
3975: $display =~ s{Problem Status}{$grade_status_mt<br />};
3976: }
3977: my $part_mt = &mt('Part:');
3978: $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
3979: }
3980:
3981: $result.='<th>'.$display.'</th>'."\n";
3982: }
3983: $result.=&Apache::loncommon::end_data_table_header_row();
3984:
3985: my %last_resets =
3986: &get_last_resets($symb,$env{'request.course.id'},\@partids);
3987:
3988: #get info for each student
3989: #list all the students - with points and grade status
3990: my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
3991: my $ctr = 0;
3992: foreach (sort
3993: {
3994: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
3995: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
3996: }
3997: return $a cmp $b;
3998: } (keys(%$fullname))) {
3999: $result.=&viewstudentgrade($symb,$env{'request.course.id'},
4000: $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets,$is_tool);
4001: }
4002: $result.=&Apache::loncommon::end_data_table();
4003: $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
4004: $result.='<input type="button" value="'.&mt('Save').'" '.
4005: 'onclick="javascript:submit();" target="_self" /></form>'."\n";
4006: if ($ctr == 0) {
4007: my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
4008: $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
4009: '<span class="LC_warning">';
4010: if ($env{'form.submitonly'} eq 'all') {
4011: if (grep(/^all$/,@sections)) {
4012: if (grep(/^all$/,@groups)) {
4013: $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
4014: $stu_status);
4015: } elsif (grep(/^none$/,@groups)) {
4016: $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
4017: $stu_status);
4018: } else {
4019: $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
4020: $group_display,$stu_status);
4021: }
4022: } elsif (grep(/^none$/,@sections)) {
4023: if (grep(/^all$/,@groups)) {
4024: $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
4025: $stu_status);
4026: } elsif (grep(/^none$/,@groups)) {
4027: $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
4028: $stu_status);
4029: } else {
4030: $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
4031: $group_display,$stu_status);
4032: }
4033: } else {
4034: if (grep(/^all$/,@groups)) {
4035: $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
4036: $section_display,$stu_status);
4037: } elsif (grep(/^none$/,@groups)) {
4038: $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
4039: $section_display,$stu_status);
4040: } else {
4041: $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
4042: $section_display,$group_display,$stu_status);
4043: }
4044: }
4045: } else {
4046: if (grep(/^all$/,@sections)) {
4047: if (grep(/^all$/,@groups)) {
4048: $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
4049: $stu_status,$submission_status);
4050: } elsif (grep(/^none$/,@groups)) {
4051: $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
4052: $stu_status,$submission_status);
4053: } else {
4054: $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
4055: $group_display,$stu_status,$submission_status);
4056: }
4057: } elsif (grep(/^none$/,@sections)) {
4058: if (grep(/^all$/,@groups)) {
4059: $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
4060: $stu_status,$submission_status);
4061: } elsif (grep(/^none$/,@groups)) {
4062: $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
4063: $stu_status,$submission_status);
4064: } else {
4065: $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
4066: $group_display,$stu_status,$submission_status);
4067: }
4068: } else {
4069: if (grep(/^all$/,@groups)) {
4070: $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
4071: $section_display,$stu_status,$submission_status);
4072: } elsif (grep(/^none$/,@groups)) {
4073: $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] and submission status "[_3]" to modify or grade.',
4074: $section_display,$stu_status,$submission_status);
4075: } else {
4076: $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] and submission status "[_4]" to modify or grade.',
4077: $section_display,$group_display,$stu_status,$submission_status);
4078: }
4079: }
4080: }
4081: $result .= '</span><br />';
4082: }
4083: return $result;
4084: }
4085:
4086: #--- call by previous routine to display each student who satisfies submission filter.
4087: sub viewstudentgrade {
4088: my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets,$is_tool) = @_;
4089: my ($uname,$udom) = split(/:/,$student);
4090: my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
4091: my $submitonly = $env{'form.submitonly'};
4092: unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
4093: my %partstatus = ();
4094: if (ref($parts) eq 'ARRAY') {
4095: foreach my $apart (@{$parts}) {
4096: my ($part,$type) = &split_part_type($apart);
4097: my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
4098: $status = 'nothing' if ($status eq '');
4099: $partstatus{$part} = $status;
4100: my $subkey = "resource.$part.submitted_by";
4101: $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
4102: }
4103: my $submitted = 0;
4104: my $graded = 0;
4105: my $incorrect = 0;
4106: foreach my $key (keys(%partstatus)) {
4107: $submitted = 1 if ($partstatus{$key} ne 'nothing');
4108: $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
4109: $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
4110:
4111: my $partid = (split(/\./,$key))[1];
4112: if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
4113: $submitted = 0;
4114: }
4115: }
4116: return if (!$submitted && ($submitonly eq 'yes' ||
4117: $submitonly eq 'incorrect' ||
4118: $submitonly eq 'graded'));
4119: return if (!$graded && ($submitonly eq 'graded'));
4120: return if (!$incorrect && $submitonly eq 'incorrect');
4121: }
4122: }
4123: if ($submitonly eq 'queued') {
4124: my ($cdom,$cnum) = split(/_/,$courseid);
4125: my %queue_status =
4126: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
4127: $udom,$uname);
4128: return if (!defined($queue_status{'gradingqueue'}));
4129: }
4130: $$ctr++;
4131: my %aggregates = ();
4132: my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
4133: '<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
4134: "\n".$$ctr.' </td><td> '.
4135: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
4136: '\');" target="_self">'.$fullname.'</a> '.
4137: '<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
4138: $student=~s/:/_/; # colon doen't work in javascript for names
4139: foreach my $apart (@$parts) {
4140: my ($part,$type) = &split_part_type($apart);
4141: my $score=$record{"resource.$part.$type"};
4142: $result.='<td align="center">';
4143: my ($aggtries,$totaltries);
4144: unless (exists($aggregates{$part})) {
4145: $totaltries = $record{'resource.'.$part.'.tries'};
4146: $aggtries = $totaltries;
4147: if ($$last_resets{$part}) {
4148: $aggtries = &get_num_tries(\%record,$$last_resets{$part},
4149: $part);
4150: }
4151: $result.='<input type="hidden" name="'.
4152: 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
4153: $result.='<input type="hidden" name="'.
4154: 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
4155: $aggregates{$part} = 1;
4156: }
4157: if ($type eq 'awarded') {
4158: my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
4159: $result.='<input type="hidden" name="'.
4160: 'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
4161: $result.='<input type="text" name="'.
4162: 'GD_'.$student.'_'.$part.'_awarded" '.
4163: 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
4164: '\')" value="'.$pts.'" size="4" /></td>'."\n";
4165: } elsif ($type eq 'solved') {
4166: my ($status,$foo)=split(/_/,$score,2);
4167: $status = 'nothing' if ($status eq '');
4168: $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
4169: $part.'_solved_s" value="'.$status.'" />'."\n";
4170: $result.=' <select name="'.
4171: 'GD_'.$student.'_'.$part.'_solved" '.
4172: 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
4173: $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>'
4174: : '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
4175: $result.='<option value="reset status">'.&mt('reset status').'</option>';
4176: $result.="</select> </td>\n";
4177: } else {
4178: $result.='<input type="hidden" name="'.
4179: 'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
4180: "\n";
4181: $result.='<input type="text" name="'.
4182: 'GD_'.$student.'_'.$part.'_'.$type.'" '.
4183: 'value="'.$score.'" size="4" /></td>'."\n";
4184: }
4185: }
4186: $result.=&Apache::loncommon::end_data_table_row();
4187: return $result;
4188: }
4189:
4190: #--- change scores for all the students in a section/class
4191: # record does not get update if unchanged
4192: sub editgrades {
4193: my ($request,$symb) = @_;
4194: my $toolsymb;
4195: if ($symb =~ /ext\.tool$/) {
4196: $toolsymb = $symb;
4197: }
4198:
4199: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
4200: my $title='<h2>'.&mt('Current Grade Status').'</h2>';
4201: $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
4202:
4203: my $result= &Apache::loncommon::start_data_table().
4204: &Apache::loncommon::start_data_table_header_row().
4205: '<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
4206: '<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
4207: my %scoreptr = (
4208: 'correct' =>'correct_by_override',
4209: 'incorrect'=>'incorrect_by_override',
4210: 'excused' =>'excused',
4211: 'ungraded' =>'ungraded_attempted',
4212: 'credited' =>'credit_attempted',
4213: 'nothing' => '',
4214: );
4215: my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
4216:
4217: my (@partid);
4218: my %weight = ();
4219: my %columns = ();
4220: my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
4221:
4222: my $partserror;
4223: my (@parts) = sort(&getpartlist($symb,\$partserror));
4224: if ($partserror) {
4225: return &navmap_errormsg();
4226: }
4227: my $header;
4228: while ($ctr < $env{'form.totalparts'}) {
4229: my $partid = $env{'form.partid_'.$ctr};
4230: push(@partid,$partid);
4231: $weight{$partid} = $env{'form.weight_'.$partid};
4232: $ctr++;
4233: }
4234: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
4235: my $totcolspan = 0;
4236: foreach my $partid (@partid) {
4237: $header .= '<th align="center">'.&mt('Old Score').'</th>'.
4238: '<th align="center">'.&mt('New Score').'</th>';
4239: $columns{$partid}=2;
4240: foreach my $stores (@parts) {
4241: my ($part,$type) = &split_part_type($stores);
4242: if ($part !~ m/^\Q$partid\E/) { next;}
4243: if ($type eq 'awarded' || $type eq 'solved') { next; }
4244: my $display=&Apache::lonnet::metadata($url,$stores.'.display',$toolsymb);
4245: $display =~ s/\[Part: \Q$part\E\]//;
4246: my $narrowtext = &mt('Tries');
4247: $display =~ s/Number of Attempts/$narrowtext/;
4248: $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
4249: '<th align="center">'.&mt('New').' '.$display.'</th>';
4250: $columns{$partid}+=2;
4251: }
4252: $totcolspan += $columns{$partid};
4253: }
4254: foreach my $partid (@partid) {
4255: my $display_part=&get_display_part($partid,$symb);
4256: $result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
4257: &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
4258: '</th>';
4259:
4260: }
4261: $result .= &Apache::loncommon::end_data_table_header_row().
4262: &Apache::loncommon::start_data_table_header_row().
4263: $header.
4264: &Apache::loncommon::end_data_table_header_row();
4265: my @noupdate;
4266: my ($updateCtr,$noupdateCtr) = (1,1);
4267: for ($i=0; $i<$env{'form.total'}; $i++) {
4268: my $user = $env{'form.ctr'.$i};
4269: my ($uname,$udom)=split(/:/,$user);
4270: my %newrecord;
4271: my $updateflag = 0;
4272: my $usec=$classlist->{"$uname:$udom"}[5];
4273: my $canmodify = &canmodify($usec);
4274: my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
4275: &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
4276: if (!$canmodify) {
4277: push(@noupdate,
4278: $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
4279: &mt('Not allowed to modify student')."</span></td>");
4280: next;
4281: }
4282: my %aggregate = ();
4283: my $aggregateflag = 0;
4284: $user=~s/:/_/; # colon doen't work in javascript for names
4285: foreach (@partid) {
4286: my $old_aw = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
4287: my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
4288: my $old_part = $old_aw eq '' ? '' : $old_part_pcr;
4289: my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
4290: my $awarded = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
4291: my $pcr = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
4292: my $partial = $awarded eq '' ? '' : $pcr;
4293: my $score;
4294: if ($partial eq '') {
4295: $score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
4296: } elsif ($partial > 0) {
4297: $score = 'correct_by_override';
4298: } elsif ($partial == 0) {
4299: $score = 'incorrect_by_override';
4300: }
4301: my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
4302: $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
4303:
4304: $newrecord{'resource.'.$_.'.regrader'}=
4305: "$env{'user.name'}:$env{'user.domain'}";
4306: if ($dropMenu eq 'reset status' &&
4307: $old_score ne '') { # ignore if no previous attempts => nothing to reset
4308: $newrecord{'resource.'.$_.'.tries'} = '';
4309: $newrecord{'resource.'.$_.'.solved'} = '';
4310: $newrecord{'resource.'.$_.'.award'} = '';
4311: $newrecord{'resource.'.$_.'.awarded'} = '';
4312: $updateflag = 1;
4313: if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
4314: my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
4315: my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
4316: my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
4317: &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
4318: $aggregateflag = 1;
4319: }
4320: } elsif (!($old_part eq $partial && $old_score eq $score)) {
4321: $updateflag = 1;
4322: $newrecord{'resource.'.$_.'.awarded'} = $partial if $partial ne '';
4323: $newrecord{'resource.'.$_.'.solved'} = $score;
4324: $rec_update++;
4325: }
4326:
4327: $line .= '<td align="center">'.$old_aw.' </td>'.
4328: '<td align="center">'.$awarded.
4329: ($score eq 'excused' ? $score : '').' </td>';
4330:
4331:
4332: my $partid=$_;
4333: foreach my $stores (@parts) {
4334: my ($part,$type) = &split_part_type($stores);
4335: if ($part !~ m/^\Q$partid\E/) { next;}
4336: if ($type eq 'awarded' || $type eq 'solved') { next; }
4337: my $old_aw = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
4338: my $awarded = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
4339: if ($awarded ne '' && $awarded ne $old_aw) {
4340: $newrecord{'resource.'.$part.'.'.$type}= $awarded;
4341: $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
4342: $updateflag=1;
4343: }
4344: $line .= '<td align="center">'.$old_aw.' </td>'.
4345: '<td align="center">'.$awarded.' </td>';
4346: }
4347: }
4348: $line.="\n";
4349:
4350: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4351: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4352:
4353: if ($updateflag) {
4354: $count++;
4355: &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
4356: $udom,$uname);
4357:
4358: if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
4359: $cnum,$udom,$uname)) {
4360: # need to figure out if should be in queue.
4361: my %record =
4362: &Apache::lonnet::restore($symb,$env{'request.course.id'},
4363: $udom,$uname);
4364: my $all_graded = 1;
4365: my $none_graded = 1;
4366: foreach my $part (@parts) {
4367: if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
4368: $all_graded = 0;
4369: } else {
4370: $none_graded = 0;
4371: }
4372: }
4373:
4374: if ($all_graded || $none_graded) {
4375: &Apache::bridgetask::remove_from_queue('gradingqueue',
4376: $symb,$cdom,$cnum,
4377: $udom,$uname);
4378: }
4379: }
4380:
4381: $result.=&Apache::loncommon::start_data_table_row().
4382: '<td align="right"> '.$updateCtr.' </td>'.$line.
4383: &Apache::loncommon::end_data_table_row();
4384: $updateCtr++;
4385: } else {
4386: push(@noupdate,
4387: '<td align="right"> '.$noupdateCtr.' </td>'.$line);
4388: $noupdateCtr++;
4389: }
4390: if ($aggregateflag) {
4391: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
4392: $cdom,$cnum);
4393: }
4394: }
4395: if (@noupdate) {
4396: my $numcols=$totcolspan+2;
4397: $result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
4398: '<td align="center" colspan="'.$numcols.'">'.
4399: &mt('No Changes Occurred For the Students Below').
4400: '</td>'.
4401: &Apache::loncommon::end_data_table_row();
4402: foreach my $line (@noupdate) {
4403: $result.=
4404: &Apache::loncommon::start_data_table_row().
4405: $line.
4406: &Apache::loncommon::end_data_table_row();
4407: }
4408: }
4409: $result .= &Apache::loncommon::end_data_table();
4410: my $msg = '<p><b>'.
4411: &mt('Number of records updated = [_1] for [quant,_2,student].',
4412: $rec_update,$count).'</b><br />'.
4413: '<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
4414: '</b></p>';
4415: return $title.$msg.$result;
4416: }
4417:
4418: sub split_part_type {
4419: my ($partstr) = @_;
4420: my ($temp,@allparts)=split(/_/,$partstr);
4421: my $type=pop(@allparts);
4422: my $part=join('_',@allparts);
4423: return ($part,$type);
4424: }
4425:
4426: #------------- end of section for handling grading by section/class ---------
4427: #
4428: #----------------------------------------------------------------------------
4429:
4430:
4431: #----------------------------------------------------------------------------
4432: #
4433: #-------------------------- Next few routines handles grading by csv upload
4434: #
4435: #--- Javascript to handle csv upload
4436: sub csvupload_javascript_reverse_associate {
4437: my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
4438: my $error2=&mt('You need to specify at least one grading field');
4439: &js_escape(\$error1);
4440: &js_escape(\$error2);
4441: return(<<ENDPICK);
4442: function verify(vf) {
4443: var foundsomething=0;
4444: var founduname=0;
4445: var foundID=0;
4446: var foundclicker=0;
4447: for (i=0;i<=vf.nfields.value;i++) {
4448: tw=eval('vf.f'+i+'.selectedIndex');
4449: if (i==0 && tw!=0) { foundID=1; }
4450: if (i==1 && tw!=0) { founduname=1; }
4451: if (i==2 && tw!=0) { foundclicker=1; }
4452: if (i!=0 && i!=1 && i!=2 && i!=3 && tw!=0) { foundsomething=1; }
4453: }
4454: if (founduname==0 && foundID==0 && foundclicker==0) {
4455: alert('$error1');
4456: return;
4457: }
4458: if (foundsomething==0) {
4459: alert('$error2');
4460: return;
4461: }
4462: vf.submit();
4463: }
4464: function flip(vf,tf) {
4465: var nw=eval('vf.f'+tf+'.selectedIndex');
4466: var i;
4467: for (i=0;i<=vf.nfields.value;i++) {
4468: //can not pick the same destination field for both name and domain
4469: if (((i ==0)||(i ==1)) &&
4470: ((tf==0)||(tf==1)) &&
4471: (i!=tf) &&
4472: (eval('vf.f'+i+'.selectedIndex')==nw)) {
4473: eval('vf.f'+i+'.selectedIndex=0;')
4474: }
4475: }
4476: }
4477: ENDPICK
4478: }
4479:
4480: sub csvupload_javascript_forward_associate {
4481: my $error1=&mt('You need to specify the username, the student/employee ID, or the clicker ID');
4482: my $error2=&mt('You need to specify at least one grading field');
4483: &js_escape(\$error1);
4484: &js_escape(\$error2);
4485: return(<<ENDPICK);
4486: function verify(vf) {
4487: var foundsomething=0;
4488: var founduname=0;
4489: var foundID=0;
4490: var foundclicker=0;
4491: for (i=0;i<=vf.nfields.value;i++) {
4492: tw=eval('vf.f'+i+'.selectedIndex');
4493: if (tw==1) { foundID=1; }
4494: if (tw==2) { founduname=1; }
4495: if (tw==3) { foundclicker=1; }
4496: if (tw>4) { foundsomething=1; }
4497: }
4498: if (founduname==0 && foundID==0 && Æ’oundclicker==0) {
4499: alert('$error1');
4500: return;
4501: }
4502: if (foundsomething==0) {
4503: alert('$error2');
4504: return;
4505: }
4506: vf.submit();
4507: }
4508: function flip(vf,tf) {
4509: var nw=eval('vf.f'+tf+'.selectedIndex');
4510: var i;
4511: //can not pick the same destination field twice
4512: for (i=0;i<=vf.nfields.value;i++) {
4513: if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
4514: eval('vf.f'+i+'.selectedIndex=0;')
4515: }
4516: }
4517: }
4518: ENDPICK
4519: }
4520:
4521: sub csvuploadmap_header {
4522: my ($request,$symb,$datatoken,$distotal)= @_;
4523: my $javascript;
4524: if ($env{'form.upfile_associate'} eq 'reverse') {
4525: $javascript=&csvupload_javascript_reverse_associate();
4526: } else {
4527: $javascript=&csvupload_javascript_forward_associate();
4528: }
4529:
4530: $symb = &Apache::lonenc::check_encrypt($symb);
4531: $request->print('<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">'.
4532: &mt('Total number of records found in file: [_1]',$distotal).'<hr />'.
4533: &mt('Associate entries from the uploaded file with as many fields as you can.'));
4534: my $reverse=&mt("Reverse Association");
4535: $request->print(<<ENDPICK);
4536: <br />
4537: <input type="button" value="$reverse" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
4538: <input type="hidden" name="associate" value="" />
4539: <input type="hidden" name="phase" value="three" />
4540: <input type="hidden" name="datatoken" value="$datatoken" />
4541: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
4542: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
4543: <input type="hidden" name="upfile_associate"
4544: value="$env{'form.upfile_associate'}" />
4545: <input type="hidden" name="symb" value="$symb" />
4546: <input type="hidden" name="command" value="csvuploadoptions" />
4547: <hr />
4548: ENDPICK
4549: $request->print(&Apache::lonhtmlcommon::scripttag($javascript));
4550: return '';
4551:
4552: }
4553:
4554: sub csvupload_fields {
4555: my ($symb,$errorref) = @_;
4556: my $toolsymb;
4557: if ($symb =~ /ext\.tool$/) {
4558: $toolsymb = $symb;
4559: }
4560: my (@parts) = &getpartlist($symb,$errorref);
4561: if (ref($errorref)) {
4562: if ($$errorref) {
4563: return;
4564: }
4565: }
4566:
4567: my @fields=(['ID','Student/Employee ID'],
4568: ['username','Student Username'],
4569: ['clicker','Clicker ID'],
4570: ['domain','Student Domain']);
4571: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
4572: foreach my $part (sort(@parts)) {
4573: my @datum;
4574: my $display=&Apache::lonnet::metadata($url,$part.'.display',$toolsymb);
4575: my $name=$part;
4576: if (!$display) { $display = $name; }
4577: @datum=($name,$display);
4578: if ($name=~/^stores_(.*)_awarded/) {
4579: push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
4580: }
4581: push(@fields,\@datum);
4582: }
4583: return (@fields);
4584: }
4585:
4586: sub csvuploadmap_footer {
4587: my ($request,$i,$keyfields) =@_;
4588: my $buttontext = &mt('Assign Grades');
4589: $request->print(<<ENDPICK);
4590: </table>
4591: <input type="hidden" name="nfields" value="$i" />
4592: <input type="hidden" name="keyfields" value="$keyfields" />
4593: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
4594: </form>
4595: ENDPICK
4596: }
4597:
4598: sub checkforfile_js {
4599: my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
4600: &js_escape(\$alertmsg);
4601: my $result = &Apache::lonhtmlcommon::scripttag(<<CSVFORMJS);
4602: function checkUpload(formname) {
4603: if (formname.upfile.value == "") {
4604: alert("$alertmsg");
4605: return false;
4606: }
4607: formname.submit();
4608: }
4609: CSVFORMJS
4610: return $result;
4611: }
4612:
4613: sub upcsvScores_form {
4614: my ($request,$symb) = @_;
4615: if (!$symb) {return '';}
4616: my $result=&checkforfile_js();
4617: $result.=&Apache::loncommon::start_data_table().
4618: &Apache::loncommon::start_data_table_header_row().
4619: '<th>'.&mt('Specify a file containing the class scores for current resource.').'</th>'.
4620: &Apache::loncommon::end_data_table_header_row().
4621: &Apache::loncommon::start_data_table_row().'<td>';
4622: my $upload=&mt("Upload Scores");
4623: my $upfile_select=&Apache::loncommon::upfile_select_html();
4624: my $ignore=&mt('Ignore First Line');
4625: $symb = &Apache::lonenc::check_encrypt($symb);
4626: $result.=<<ENDUPFORM;
4627: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
4628: <input type="hidden" name="symb" value="$symb" />
4629: <input type="hidden" name="command" value="csvuploadmap" />
4630: $upfile_select
4631: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
4632: </form>
4633: ENDUPFORM
4634: $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
4635: &mt("How do I create a CSV file from a spreadsheet")).
4636: '</td>'.
4637: &Apache::loncommon::end_data_table_row().
4638: &Apache::loncommon::end_data_table();
4639: return $result;
4640: }
4641:
4642:
4643: sub csvuploadmap {
4644: my ($request,$symb) = @_;
4645: if (!$symb) {return '';}
4646:
4647: my $datatoken;
4648: if (!$env{'form.datatoken'}) {
4649: $datatoken=&Apache::loncommon::upfile_store($request);
4650: } else {
4651: $datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
4652: if ($datatoken ne '') {
4653: &Apache::loncommon::load_tmp_file($request,$datatoken);
4654: }
4655: }
4656: my @records=&Apache::loncommon::upfile_record_sep();
4657: &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
4658: my ($i,$keyfields);
4659: if (@records) {
4660: my $fieldserror;
4661: my @fields=&csvupload_fields($symb,\$fieldserror);
4662: if ($fieldserror) {
4663: $request->print(&navmap_errormsg());
4664: return;
4665: }
4666: if ($env{'form.upfile_associate'} eq 'reverse') {
4667: &Apache::loncommon::csv_print_samples($request,\@records);
4668: $i=&Apache::loncommon::csv_print_select_table($request,\@records,
4669: \@fields);
4670: foreach (@fields) { $keyfields.=$_->[0].','; }
4671: chop($keyfields);
4672: } else {
4673: unshift(@fields,['none','']);
4674: $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
4675: \@fields);
4676: foreach my $rec (@records) {
4677: my %temp = &Apache::loncommon::record_sep($rec);
4678: if (%temp) {
4679: $keyfields=join(',',sort(keys(%temp)));
4680: last;
4681: }
4682: }
4683: }
4684: }
4685: &csvuploadmap_footer($request,$i,$keyfields);
4686:
4687: return '';
4688: }
4689:
4690: sub csvuploadoptions {
4691: my ($request,$symb)= @_;
4692: my $overwrite=&mt('Overwrite any existing score');
4693: $request->print(<<ENDPICK);
4694: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
4695: <input type="hidden" name="command" value="csvuploadassign" />
4696: <p>
4697: <label>
4698: <input type="checkbox" name="overwite_scores" checked="checked" />
4699: $overwrite
4700: </label>
4701: </p>
4702: ENDPICK
4703: my %fields=&get_fields();
4704: if (!defined($fields{'domain'})) {
4705: my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
4706: $request->print("\n<p>".&mt('Users are in domain: [_1]',$domform)."</p>\n");
4707: }
4708: foreach my $key (sort(keys(%env))) {
4709: if ($key !~ /^form\.(.*)$/) { next; }
4710: my $cleankey=$1;
4711: if ($cleankey eq 'command') { next; }
4712: $request->print('<input type="hidden" name="'.$cleankey.
4713: '" value="'.$env{$key}.'" />'."\n");
4714: }
4715: # FIXME do a check for any duplicated user ids...
4716: # FIXME do a check for any invalid user ids?...
4717: $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
4718: <hr /></form>'."\n");
4719: return '';
4720: }
4721:
4722: sub get_fields {
4723: my %fields;
4724: my @keyfields = split(/\,/,$env{'form.keyfields'});
4725: for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
4726: if ($env{'form.upfile_associate'} eq 'reverse') {
4727: if ($env{'form.f'.$i} ne 'none') {
4728: $fields{$keyfields[$i]}=$env{'form.f'.$i};
4729: }
4730: } else {
4731: if ($env{'form.f'.$i} ne 'none') {
4732: $fields{$env{'form.f'.$i}}=$keyfields[$i];
4733: }
4734: }
4735: }
4736: return %fields;
4737: }
4738:
4739: sub csvuploadassign {
4740: my ($request,$symb) = @_;
4741: if (!$symb) {return '';}
4742: my $error_msg = '';
4743: my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
4744: if ($datatoken ne '') {
4745: &Apache::loncommon::load_tmp_file($request,$datatoken);
4746: }
4747: my @gradedata = &Apache::loncommon::upfile_record_sep();
4748: my %fields=&get_fields();
4749: my $courseid=$env{'request.course.id'};
4750: my ($classlist) = &getclasslist('all',0);
4751: my @notallowed;
4752: my @skipped;
4753: my @warnings;
4754: my $countdone=0;
4755: foreach my $grade (@gradedata) {
4756: my %entries=&Apache::loncommon::record_sep($grade);
4757: my $domain;
4758: if ($entries{$fields{'domain'}}) {
4759: $domain=$entries{$fields{'domain'}};
4760: } else {
4761: $domain=$env{'form.default_domain'};
4762: }
4763: $domain=~s/\s//g;
4764: my $username=$entries{$fields{'username'}};
4765: $username=~s/\s//g;
4766: if (!$username) {
4767: my $id=$entries{$fields{'ID'}};
4768: $id=~s/\s//g;
4769: if ($id ne '') {
4770: my %ids=&Apache::lonnet::idget($domain,[$id]);
4771: $username=$ids{$id};
4772: } else {
4773: if ($entries{$fields{'clicker'}}) {
4774: my $clicker = $entries{$fields{'clicker'}};
4775: $clicker=~s/\s//g;
4776: if ($clicker ne '') {
4777: my %clickers = &Apache::lonnet::idget($domain,[$clicker],'clickers');
4778: if ($clickers{$clicker} ne '') {
4779: my $match = 0;
4780: my @inclass;
4781: foreach my $poss (split(/,/,$clickers{$clicker})) {
4782: if (exists($$classlist{"$poss:$domain"})) {
4783: $username = $poss;
4784: push(@inclass,$poss);
4785: $match ++;
4786:
4787: }
4788: }
4789: if ($match > 1) {
4790: undef($username);
4791: $request->print('<p class="LC_warning">'.
4792: &mt('Score not saved for clicker: [_1] (matched multiple usernames: [_2])',
4793: $clicker,join(', ',@inclass)).'</p>');
4794: }
4795: }
4796: }
4797: }
4798: }
4799: }
4800: if (!exists($$classlist{"$username:$domain"})) {
4801: my $id=$entries{$fields{'ID'}};
4802: $id=~s/\s//g;
4803: my $clicker = $entries{$fields{'clicker'}};
4804: $clicker=~s/\s//g;
4805: if ($clicker) {
4806: push(@skipped,"$clicker:$domain");
4807: } elsif ($id) {
4808: push(@skipped,"$id:$domain");
4809: } else {
4810: push(@skipped,"$username:$domain");
4811: }
4812: next;
4813: }
4814: my $usec=$classlist->{"$username:$domain"}[5];
4815: if (!&canmodify($usec)) {
4816: push(@notallowed,"$username:$domain");
4817: next;
4818: }
4819: my %points;
4820: my %grades;
4821: foreach my $dest (keys(%fields)) {
4822: if ($dest eq 'ID' || $dest eq 'username' ||
4823: $dest eq 'domain') { next; }
4824: if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
4825: if ($dest=~/stores_(.*)_points/) {
4826: my $part=$1;
4827: my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
4828: $symb,$domain,$username);
4829: if ($wgt) {
4830: $entries{$fields{$dest}}=~s/\s//g;
4831: my $pcr=$entries{$fields{$dest}} / $wgt;
4832: my $award=($pcr == 0) ? 'incorrect_by_override'
4833: : 'correct_by_override';
4834: if ($pcr>1) {
4835: push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
4836: }
4837: $grades{"resource.$part.awarded"}=$pcr;
4838: $grades{"resource.$part.solved"}=$award;
4839: $points{$part}=1;
4840: } else {
4841: $error_msg = "<br />" .
4842: &mt("Some point values were assigned"
4843: ." for problems with a weight "
4844: ."of zero. These values were "
4845: ."ignored.");
4846: }
4847: } else {
4848: if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
4849: if ($dest=~/stores_(.*)_solved/) { if ($points{$1}) {next;} }
4850: my $store_key=$dest;
4851: $store_key=~s/^stores/resource/;
4852: $store_key=~s/_/\./g;
4853: $grades{$store_key}=$entries{$fields{$dest}};
4854: }
4855: }
4856: if (! %grades) {
4857: push(@skipped,&mt("[_1]: no data to save","$username:$domain"));
4858: } else {
4859: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
4860: my $result=&Apache::lonnet::cstore(\%grades,$symb,
4861: $env{'request.course.id'},
4862: $domain,$username);
4863: if ($result eq 'ok') {
4864: # Successfully stored
4865: $request->print('.');
4866: # Remove from grading queue
4867: &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
4868: $env{'course.'.$env{'request.course.id'}.'.domain'},
4869: $env{'course.'.$env{'request.course.id'}.'.num'},
4870: $domain,$username);
4871: $countdone++;
4872: } else {
4873: $request->print("<p><span class=\"LC_error\">".
4874: &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
4875: "$username:$domain",$result)."</span></p>");
4876: }
4877: $request->rflush();
4878: }
4879: }
4880: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
4881: if (@warnings) {
4882: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
4883: $request->print(join(', ',@warnings));
4884: }
4885: if (@skipped) {
4886: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
4887: $request->print(join(', ',@skipped));
4888: }
4889: if (@notallowed) {
4890: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
4891: $request->print(join(', ',@notallowed));
4892: }
4893: $request->print("<br />\n");
4894: return $error_msg;
4895: }
4896: #------------- end of section for handling csv file upload ---------
4897: #
4898: #-------------------------------------------------------------------
4899: #
4900: #-------------- Next few routines handle grading by page/sequence
4901: #
4902: #--- Select a page/sequence and a student to grade
4903: sub pickStudentPage {
4904: my ($request,$symb) = @_;
4905:
4906: my $alertmsg = &mt('Please select the student you wish to grade.');
4907: &js_escape(\$alertmsg);
4908: $request->print(&Apache::lonhtmlcommon::scripttag(<<LISTJAVASCRIPT));
4909:
4910: function checkPickOne(formname) {
4911: if (radioSelection(formname.student) == null) {
4912: alert("$alertmsg");
4913: return;
4914: }
4915: ptr = pullDownSelection(formname.selectpage);
4916: formname.page.value = formname["page"+ptr].value;
4917: formname.title.value = formname["title"+ptr].value;
4918: formname.submit();
4919: }
4920:
4921: LISTJAVASCRIPT
4922: &commonJSfunctions($request);
4923:
4924: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4925: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4926: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4927: my $getgroup = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
4928:
4929: my $result='<h3><span class="LC_info"> '.
4930: &mt('Manual Grading by Page or Sequence').'</span></h3>';
4931:
4932: $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
4933: my $map_error;
4934: my ($titles,$symbx) = &getSymbMap($map_error);
4935: if ($map_error) {
4936: $request->print(&navmap_errormsg());
4937: return;
4938: }
4939: my ($curpage) =&Apache::lonnet::decode_symb($symb);
4940: # my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb);
4941: # my $type=($curpage =~ /\.(page|sequence)/);
4942:
4943: # Collection of hidden fields
4944: my $ctr=0;
4945: foreach (@$titles) {
4946: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4947: $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
4948: $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
4949: $ctr++;
4950: }
4951: $result.='<input type="hidden" name="page" />'."\n".
4952: '<input type="hidden" name="title" />'."\n";
4953:
4954: $result.=&build_section_inputs();
4955: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
4956: $result.='<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
4957: '<input type="hidden" name="command" value="displayPage" />'."\n".
4958: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
4959:
4960: # Show grading options
4961: $result.=&Apache::lonhtmlcommon::start_pick_box();
4962: my $select = '<select name="selectpage">'."\n";
4963: $ctr=0;
4964: foreach (@$titles) {
4965: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4966: $select.='<option value="'.$ctr.'"'.
4967: ($$symbx{$_} =~ /$curpage$/ ? ' selected="selected"' : '').
4968: '>'.$showtitle.'</option>'."\n";
4969: $ctr++;
4970: }
4971: $select.= '</select>';
4972:
4973: $result.=
4974: &Apache::lonhtmlcommon::row_title(&mt('Problems from'))
4975: .$select
4976: .&Apache::lonhtmlcommon::row_closure();
4977:
4978: $result.=
4979: &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
4980: .'<label><input type="radio" name="vProb" value="no"'
4981: .' checked="checked" /> '.&mt('no').' </label>'."\n"
4982: .'<label><input type="radio" name="vProb" value="yes" />'
4983: .&mt('yes').'</label>'."\n"
4984: .&Apache::lonhtmlcommon::row_closure();
4985:
4986: $result.=
4987: &Apache::lonhtmlcommon::row_title(&mt('View Submissions'))
4988: .'<label><input type="radio" name="lastSub" value="none" /> '
4989: .&mt('none').' </label>'."\n"
4990: .'<label><input type="radio" name="lastSub" value="datesub"'
4991: .' checked="checked" /> '.&mt('all submissions').'</label>'."\n"
4992: .'<label><input type="radio" name="lastSub" value="all" /> '
4993: .&mt('all submissions with details').' </label>'
4994: .&Apache::lonhtmlcommon::row_closure();
4995:
4996: $result.=
4997: &Apache::lonhtmlcommon::row_title(&mt('Use CODE'))
4998: .'<input type="text" name="CODE" value="" />'
4999: .&Apache::lonhtmlcommon::row_closure(1)
5000: .&Apache::lonhtmlcommon::end_pick_box();
5001:
5002: # Show list of students to select for grading
5003: $result.='<br /><input type="button" '.
5004: 'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' →" /><br />'."\n";
5005:
5006: $request->print($result);
5007:
5008: my $studentTable.=' <b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
5009: &Apache::loncommon::start_data_table().
5010: &Apache::loncommon::start_data_table_header_row().
5011: '<th align="right"> '.&mt('No.').'</th>'.
5012: '<th>'.&nameUserString('header').'</th>'.
5013: '<th align="right"> '.&mt('No.').'</th>'.
5014: '<th>'.&nameUserString('header').'</th>'.
5015: &Apache::loncommon::end_data_table_header_row();
5016:
5017: my (undef,undef,$fullname) = &getclasslist($getsec,'1',$getgroup);
5018: my $ptr = 1;
5019: foreach my $student (sort
5020: {
5021: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
5022: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
5023: }
5024: return $a cmp $b;
5025: } (keys(%$fullname))) {
5026: my ($uname,$udom) = split(/:/,$student);
5027: $studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
5028: : '</td>');
5029: $studentTable.='<td align="right">'.$ptr.' </td>';
5030: $studentTable.='<td> <label><input type="radio" name="student" value="'.$student.'" /> '
5031: .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
5032: $studentTable.=
5033: ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row()
5034: : '');
5035: $ptr++;
5036: }
5037: if ($ptr%2 == 0) {
5038: $studentTable.='</td><td> </td><td> </td>'.
5039: &Apache::loncommon::end_data_table_row();
5040: }
5041: $studentTable.=&Apache::loncommon::end_data_table()."\n";
5042: $studentTable.='<input type="button" '.
5043: 'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' →" /></form>'."\n";
5044:
5045: $request->print($studentTable);
5046:
5047: return '';
5048: }
5049:
5050: sub getSymbMap {
5051: my ($map_error) = @_;
5052: my $navmap = Apache::lonnavmaps::navmap->new();
5053: unless (ref($navmap)) {
5054: if (ref($map_error)) {
5055: $$map_error = 'navmap';
5056: }
5057: return;
5058: }
5059: my %symbx = ();
5060: my @titles = ();
5061: my $minder = 0;
5062:
5063: # Gather every sequence that has problems.
5064: my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
5065: 1,0,1);
5066: for my $sequence ($navmap->getById('0.0'), @sequences) {
5067: if ($navmap->hasResource($sequence, sub { shift->is_gradable(); }, 0) ) {
5068: my $title = $minder.'.'.
5069: &HTML::Entities::encode($sequence->compTitle(),'"\'&');
5070: push(@titles, $title); # minder in case two titles are identical
5071: $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
5072: $minder++;
5073: }
5074: }
5075: return \@titles,\%symbx;
5076: }
5077:
5078: #
5079: #--- Displays a page/sequence w/wo problems, w/wo submissions
5080: sub displayPage {
5081: my ($request,$symb) = @_;
5082: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
5083: my $cnum = $env{"course.$env{'request.course.id'}.num"};
5084: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
5085: my $pageTitle = $env{'form.page'};
5086: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
5087: my ($uname,$udom) = split(/:/,$env{'form.student'});
5088: my $usec=$classlist->{$env{'form.student'}}[5];
5089:
5090: #need to make sure we have the correct data for later EXT calls,
5091: #thus invalidate the cache
5092: &Apache::lonnet::devalidatecourseresdata(
5093: $env{'course.'.$env{'request.course.id'}.'.num'},
5094: $env{'course.'.$env{'request.course.id'}.'.domain'});
5095: &Apache::lonnet::clear_EXT_cache_status();
5096:
5097: if (!&canview($usec)) {
5098: $request->print(
5099: '<span class="LC_warning">'.
5100: &mt('Unable to view requested student. ([_1])',
5101: $env{'form.student'}).
5102: '</span>');
5103: return;
5104: }
5105: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
5106: $result.='<h3> '.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
5107: '</h3>'."\n";
5108: $env{'form.CODE'} = uc($env{'form.CODE'});
5109: if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
5110: $result.='<h3> '.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
5111: } else {
5112: delete($env{'form.CODE'});
5113: }
5114: &sub_page_js($request);
5115: $request->print($result);
5116:
5117: my $navmap = Apache::lonnavmaps::navmap->new();
5118: unless (ref($navmap)) {
5119: $request->print(&navmap_errormsg());
5120: return;
5121: }
5122: my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
5123: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
5124: if (!$map) {
5125: $request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
5126: return;
5127: }
5128: my $iterator = $navmap->getIterator($map->map_start(),
5129: $map->map_finish());
5130:
5131: my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
5132: '<input type="hidden" name="command" value="gradeByPage" />'."\n".
5133: '<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
5134: '<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
5135: '<input type="hidden" name="page" value="'.$pageTitle.'" />'."\n".
5136: '<input type="hidden" name="title" value="'.$env{'form.title'}.'" />'."\n".
5137: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
5138: '<input type="hidden" name="overRideScore" value="no" />'."\n";
5139:
5140: if (defined($env{'form.CODE'})) {
5141: $studentTable.=
5142: '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
5143: }
5144: my $checkIcon = '<img alt="'.&mt('Check Mark').
5145: '" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
5146:
5147: $studentTable.=' <span class="LC_info">'.
5148: &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
5149: '</span>'."\n".
5150: &Apache::loncommon::start_data_table().
5151: &Apache::loncommon::start_data_table_header_row().
5152: '<th>'.&mt('Prob.').'</th>'.
5153: '<th> '.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
5154: &Apache::loncommon::end_data_table_header_row();
5155:
5156: &Apache::lonxml::clear_problem_counter();
5157: my ($depth,$question,$prob) = (1,1,1);
5158: $iterator->next(); # skip the first BEGIN_MAP
5159: my $curRes = $iterator->next(); # for "current resource"
5160: while ($depth > 0) {
5161: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
5162: if($curRes == $iterator->END_MAP) { $depth--; }
5163:
5164: if (ref($curRes) && $curRes->is_gradable()) {
5165: my $parts = $curRes->parts();
5166: my $title = $curRes->compTitle();
5167: my $symbx = $curRes->symb();
5168: my $is_tool = ($symbx =~ /ext\.tool$/);
5169: $studentTable.=
5170: &Apache::loncommon::start_data_table_row().
5171: '<td align="center" valign="top" >'.$prob.
5172: (scalar(@{$parts}) == 1 ? ''
5173: : '<br />('.&mt('[_1]parts',
5174: scalar(@{$parts}).' ').')'
5175: ).
5176: '</td>';
5177: $studentTable.='<td valign="top">';
5178: my %form = ('CODE' => $env{'form.CODE'},);
5179: if ($is_tool) {
5180: $studentTable.=' <b>'.$title.'</b><br />';
5181: } else {
5182: if ($env{'form.vProb'} eq 'yes' ) {
5183: $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
5184: undef,'both',\%form);
5185: } else {
5186: my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
5187: $companswer =~ s|<form(.*?)>||g;
5188: $companswer =~ s|</form>||g;
5189: # while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
5190: # $companswer =~ s/$1/ /ms;
5191: # $request->print('match='.$1."<br />\n");
5192: # }
5193: # $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
5194: $studentTable.=' <b>'.$title.'</b> <br /> <b>'.&mt('Correct answer').':</b><br />'.$companswer;
5195: }
5196: }
5197:
5198: my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
5199:
5200: if ($env{'form.lastSub'} eq 'datesub') {
5201: if ($record{'version'} eq '') {
5202: my $msg = &mt('No recorded submission for this problem.');
5203: if ($is_tool) {
5204: $msg = &mt('No recorded transactions for this external tool');
5205: }
5206: $studentTable.='<br /> <span class="LC_warning">'.$msg.'</span><br />';
5207: } else {
5208: my %responseType = ();
5209: foreach my $partid (@{$parts}) {
5210: my @responseIds =$curRes->responseIds($partid);
5211: my @responseType =$curRes->responseType($partid);
5212: my %responseIds;
5213: for (my $i=0;$i<=$#responseIds;$i++) {
5214: $responseIds{$responseIds[$i]}=$responseType[$i];
5215: }
5216: $responseType{$partid} = \%responseIds;
5217: }
5218: $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
5219: }
5220: } elsif ($env{'form.lastSub'} eq 'all') {
5221: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
5222: my $identifier = (&canmodify($usec)? $prob : '');
5223: $studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
5224: $env{'request.course.id'},
5225: '','.submission',undef,
5226: $usec,$identifier);
5227:
5228: }
5229: if (&canmodify($usec)) {
5230: $studentTable.=&gradeBox_start();
5231: foreach my $partid (@{$parts}) {
5232: $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
5233: $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
5234: $question++;
5235: }
5236: $studentTable.=&gradeBox_end();
5237: $prob++;
5238: }
5239: $studentTable.='</td></tr>';
5240:
5241: }
5242: $curRes = $iterator->next();
5243: }
5244:
5245: $studentTable.=
5246: '</table>'."\n".
5247: '<input type="button" value="'.&mt('Save').'" '.
5248: 'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
5249: '</form>'."\n";
5250: $request->print($studentTable);
5251:
5252: return '';
5253: }
5254:
5255: sub displaySubByDates {
5256: my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
5257: my $isCODE=0;
5258: my $isTask = ($symb =~/\.task$/);
5259: my $is_tool = ($symb =~/\.tool$/);
5260: if (exists($record->{'resource.CODE'})) { $isCODE=1; }
5261: my $studentTable=&Apache::loncommon::start_data_table().
5262: &Apache::loncommon::start_data_table_header_row().
5263: '<th>'.&mt('Date/Time').'</th>'.
5264: ($isCODE?'<th>'.&mt('CODE').'</th>':'').
5265: ($isTask?'<th>'.&mt('Version').'</th>':'').
5266: '<th>'.($is_tool?&mt('Grade'):&mt('Submission')).'</th>'.
5267: '<th>'.&mt('Status').'</th>'.
5268: &Apache::loncommon::end_data_table_header_row();
5269: my ($version);
5270: my %mark;
5271: my %orders;
5272: $mark{'correct_by_student'} = $checkIcon;
5273: if (!exists($$record{'1:timestamp'})) {
5274: if ($is_tool) {
5275: return '<br /> <span class="LC_warning">'.&mt('No grade passed back.').'</span><br />';
5276: } else {
5277: return '<br /> <span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
5278: }
5279: }
5280:
5281: my $interaction;
5282: my $no_increment = 1;
5283: my (%lastrndseed,%lasttype);
5284: for ($version=1;$version<=$$record{'version'};$version++) {
5285: my $timestamp =
5286: &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
5287: if (exists($$record{$version.':resource.0.version'})) {
5288: $interaction = $$record{$version.':resource.0.version'};
5289: }
5290: if ($isTask && $env{'form.previousversion'}) {
5291: next unless ($interaction == $env{'form.previousversion'});
5292: }
5293: my $where = ($isTask ? "$version:resource.$interaction"
5294: : "$version:resource");
5295: $studentTable.=&Apache::loncommon::start_data_table_row().
5296: '<td>'.$timestamp.'</td>';
5297: if ($isCODE) {
5298: $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
5299: }
5300: if ($isTask) {
5301: $studentTable.='<td>'.$interaction.'</td>';
5302: }
5303: my @versionKeys = split(/\:/,$$record{$version.':keys'});
5304: my @displaySub = ();
5305: foreach my $partid (@{$parts}) {
5306: my ($hidden,$type);
5307: $type = $$record{$version.':resource.'.$partid.'.type'};
5308: if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
5309: $hidden = 1;
5310: }
5311: my @matchKey;
5312: if ($isTask) {
5313: @matchKey = sort(grep(/^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys));
5314: } elsif ($is_tool) {
5315: @matchKey = sort(grep(/^resource\.\Q$partid\E\.awarded$/,@versionKeys));
5316: } else {
5317: @matchKey = sort(grep(/^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
5318: }
5319: # next if ($$record{"$version:resource.$partid.solved"} eq '');
5320: my $display_part=&get_display_part($partid,$symb);
5321: foreach my $matchKey (@matchKey) {
5322: if (exists($$record{$version.':'.$matchKey}) &&
5323: $$record{$version.':'.$matchKey} ne '') {
5324: if ($is_tool) {
5325: $displaySub[0].=$$record{"$version:resource.$partid.awarded"};
5326: } else {
5327: my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
5328: : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
5329: $displaySub[0].='<span class="LC_nobreak">';
5330: $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
5331: .' <span class="LC_internal_info">'
5332: .'('.&mt('Response ID: [_1]',$responseId).')'
5333: .'</span>'
5334: .' <b>';
5335: if ($hidden) {
5336: $displaySub[0].= &mt('Anonymous Survey').'</b>';
5337: } else {
5338: my ($trial,$rndseed,$newvariation);
5339: if ($type eq 'randomizetry') {
5340: $trial = $$record{"$where.$partid.tries"};
5341: $rndseed = $$record{"$where.$partid.rndseed"};
5342: }
5343: if ($$record{"$where.$partid.tries"} eq '') {
5344: $displaySub[0].=&mt('Trial not counted');
5345: } else {
5346: $displaySub[0].=&mt('Trial: [_1]',
5347: $$record{"$where.$partid.tries"});
5348: if (($rndseed ne '') && ($lastrndseed{$partid} ne '')) {
5349: if (($rndseed ne $lastrndseed{$partid}) &&
5350: (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
5351: $newvariation = ' ('.&mt('New variation this try').')';
5352: }
5353: }
5354: $lastrndseed{$partid} = $rndseed;
5355: $lasttype{$partid} = $type;
5356: }
5357: my $responseType=($isTask ? 'Task'
5358: : $responseType->{$partid}->{$responseId});
5359: if (!exists($orders{$partid})) { $orders{$partid}={}; }
5360: if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
5361: $orders{$partid}->{$responseId}=
5362: &get_order($partid,$responseId,$symb,$uname,$udom,
5363: $no_increment,$type,$trial,$rndseed);
5364: }
5365: $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
5366: $displaySub[0].=' '.
5367: &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
5368: }
5369: }
5370: }
5371: }
5372: if (exists($$record{"$where.$partid.checkedin"})) {
5373: $displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
5374: $$record{"$where.$partid.checkedin"},
5375: $$record{"$where.$partid.checkedin.slot"}).
5376: '<br />';
5377: }
5378: if (exists $$record{"$where.$partid.award"}) {
5379: $displaySub[1].='<b>'.&mt('Part:').'</b> '.$display_part.' '.
5380: lc($$record{"$where.$partid.award"}).' '.
5381: $mark{$$record{"$where.$partid.solved"}}.
5382: '<br />';
5383: } elsif (($is_tool) && (exists($$record{"$version:resource.$partid.solved"}))) {
5384: if ($$record{"$version:resource.$partid.solved"} =~ /^(in|)correct_by_passback$/) {
5385: $displaySub[1].=&mt('Grade passed back by external tool');
5386: }
5387: }
5388: if (exists $$record{"$where.$partid.regrader"}) {
5389: $displaySub[2].=$$record{"$where.$partid.regrader"};
5390: unless ($is_tool) {
5391: $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
5392: }
5393: } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
5394: $displaySub[2].=
5395: $$record{"$version:resource.$partid.regrader"};
5396: unless ($is_tool) {
5397: $displaySub[2].=' (<b>'.&mt('Part').':</b> '.$display_part.')';
5398: }
5399: }
5400: }
5401: # needed because old essay regrader has not parts info
5402: if (exists $$record{"$version:resource.regrader"}) {
5403: $displaySub[2].=$$record{"$version:resource.regrader"};
5404: }
5405: $studentTable.='<td>'.$displaySub[0].' </td><td>'.$displaySub[1];
5406: if ($displaySub[2]) {
5407: $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
5408: }
5409: $studentTable.=' </td>'.
5410: &Apache::loncommon::end_data_table_row();
5411: }
5412: $studentTable.=&Apache::loncommon::end_data_table();
5413: return $studentTable;
5414: }
5415:
5416: sub updateGradeByPage {
5417: my ($request,$symb) = @_;
5418:
5419: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
5420: my $cnum = $env{"course.$env{'request.course.id'}.num"};
5421: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
5422: my $pageTitle = $env{'form.page'};
5423: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
5424: my ($uname,$udom) = split(/:/,$env{'form.student'});
5425: my $usec=$classlist->{$env{'form.student'}}[5];
5426: if (!&canmodify($usec)) {
5427: $request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
5428: return;
5429: }
5430: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
5431: $result.='<h3> '.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
5432: '</h3>'."\n";
5433:
5434: $request->print($result);
5435:
5436:
5437: my $navmap = Apache::lonnavmaps::navmap->new();
5438: unless (ref($navmap)) {
5439: $request->print(&navmap_errormsg());
5440: return;
5441: }
5442: my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
5443: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
5444: if (!$map) {
5445: $request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
5446: return;
5447: }
5448: my $iterator = $navmap->getIterator($map->map_start(),
5449: $map->map_finish());
5450:
5451: my $studentTable=
5452: &Apache::loncommon::start_data_table().
5453: &Apache::loncommon::start_data_table_header_row().
5454: '<th align="center"> '.&mt('Prob.').' </th>'.
5455: '<th> '.&mt('Title').' </th>'.
5456: '<th> '.&mt('Previous Score').' </th>'.
5457: '<th> '.&mt('New Score').' </th>'.
5458: &Apache::loncommon::end_data_table_header_row();
5459:
5460: $iterator->next(); # skip the first BEGIN_MAP
5461: my $curRes = $iterator->next(); # for "current resource"
5462: my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
5463: while ($depth > 0) {
5464: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
5465: if($curRes == $iterator->END_MAP) { $depth--; }
5466:
5467: if (ref($curRes) && $curRes->is_problem()) {
5468: my $parts = $curRes->parts();
5469: my $title = $curRes->compTitle();
5470: my $symbx = $curRes->symb();
5471: $studentTable.=
5472: &Apache::loncommon::start_data_table_row().
5473: '<td align="center" valign="top" >'.$prob.
5474: (scalar(@{$parts}) == 1 ? ''
5475: : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
5476: .')').'</td>';
5477: $studentTable.='<td valign="top"> <b>'.$title.'</b> </td>';
5478:
5479: my %newrecord=();
5480: my @displayPts=();
5481: my %aggregate = ();
5482: my $aggregateflag = 0;
5483: if ($env{'form.HIDE'.$prob}) {
5484: my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
5485: my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
5486: my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
5487: $hideflag += $numchgs;
5488: }
5489: foreach my $partid (@{$parts}) {
5490: my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
5491: my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
5492:
5493: my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ?
5494: $env{'form.WGT'.$question.'_'.$partid} : 1;
5495: my $partial = $newpts/$wgt;
5496: my $score;
5497: if ($partial > 0) {
5498: $score = 'correct_by_override';
5499: } elsif ($newpts ne '') { #empty is taken as 0
5500: $score = 'incorrect_by_override';
5501: }
5502: my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
5503: if ($dropMenu eq 'excused') {
5504: $partial = '';
5505: $score = 'excused';
5506: } elsif ($dropMenu eq 'reset status'
5507: && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
5508: $newrecord{'resource.'.$partid.'.tries'} = 0;
5509: $newrecord{'resource.'.$partid.'.solved'} = '';
5510: $newrecord{'resource.'.$partid.'.award'} = '';
5511: $newrecord{'resource.'.$partid.'.awarded'} = 0;
5512: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
5513: $changeflag++;
5514: $newpts = '';
5515:
5516: my $aggtries = $env{'form.aggtries'.$question.'_'.$partid};
5517: my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
5518: my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
5519: if ($aggtries > 0) {
5520: &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
5521: $aggregateflag = 1;
5522: }
5523: }
5524: my $display_part=&get_display_part($partid,$curRes->symb());
5525: my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
5526: $displayPts[0].=' <b>'.&mt('Part').':</b> '.$display_part.' = '.
5527: (($oldstatus eq 'excused') ? 'excused' : $oldpts).
5528: ' <br />';
5529: $displayPts[1].=' <b>'.&mt('Part').':</b> '.$display_part.' = '.
5530: (($score eq 'excused') ? 'excused' : $newpts).
5531: ' <br />';
5532: $question++;
5533: next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
5534:
5535: $newrecord{'resource.'.$partid.'.awarded'} = $partial if $partial ne '';
5536: $newrecord{'resource.'.$partid.'.solved'} = $score if $score ne '';
5537: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
5538: if (scalar(keys(%newrecord)) > 0);
5539:
5540: $changeflag++;
5541: }
5542: if (scalar(keys(%newrecord)) > 0) {
5543: my %record =
5544: &Apache::lonnet::restore($symbx,$env{'request.course.id'},
5545: $udom,$uname);
5546:
5547: if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
5548: $newrecord{'resource.CODE'} = $env{'form.CODE'};
5549: } elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
5550: $newrecord{'resource.CODE'} = '';
5551: }
5552: &Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
5553: $udom,$uname);
5554: %record = &Apache::lonnet::restore($symbx,
5555: $env{'request.course.id'},
5556: $udom,$uname);
5557: &check_and_remove_from_queue($parts,\%record,undef,$symbx,
5558: $cdom,$cnum,$udom,$uname);
5559: }
5560:
5561: if ($aggregateflag) {
5562: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
5563: $env{'course.'.$env{'request.course.id'}.'.domain'},
5564: $env{'course.'.$env{'request.course.id'}.'.num'});
5565: }
5566:
5567: $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
5568: '<td valign="top">'.$displayPts[1].'</td>'.
5569: &Apache::loncommon::end_data_table_row();
5570:
5571: $prob++;
5572: }
5573: $curRes = $iterator->next();
5574: }
5575:
5576: $studentTable.=&Apache::loncommon::end_data_table();
5577: my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
5578: &mt('The scores were changed for [quant,_1,problem].',
5579: $changeflag).'<br />');
5580: my $hidemsg=($hideflag == 0 ? '' :
5581: &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
5582: $hideflag).'<br />');
5583: $request->print($hidemsg.$grademsg.$studentTable);
5584:
5585: return '';
5586: }
5587:
5588: #-------- end of section for handling grading by page/sequence ---------
5589: #
5590: #-------------------------------------------------------------------
5591:
5592: #-------------------- Bubblesheet (Scantron) Grading -------------------
5593: #
5594: #------ start of section for handling grading by page/sequence ---------
5595:
5596: =pod
5597:
5598: =head1 Bubble sheet grading routines
5599:
5600: For this documentation:
5601:
5602: 'scanline' refers to the full line of characters
5603: from the file that we are parsing that represents one entire sheet
5604:
5605: 'bubble line' refers to the data
5606: representing the line of bubbles that are on the physical bubblesheet
5607:
5608:
5609: The overall process is that a scanned in bubblesheet data is uploaded
5610: into a course. When a user wants to grade, they select a
5611: sequence/folder of resources, a file of bubblesheet info, and pick
5612: one of the predefined configurations for what each scanline looks
5613: like.
5614:
5615: Next each scanline is checked for any errors of either 'missing
5616: bubbles' (it's an error because it may have been mis-scanned
5617: because too light bubbling), 'double bubble' (each bubble line should
5618: have no more than one letter picked), invalid or duplicated CODE,
5619: invalid student/employee ID
5620:
5621: If the CODE option is used that determines the randomization of the
5622: homework problems, either way the student/employee ID is looked up into a
5623: username:domain.
5624:
5625: During the validation phase the instructor can choose to skip scanlines.
5626:
5627: After the validation phase, there are now 3 bubblesheet files
5628:
5629: scantron_original_filename (unmodified original file)
5630: scantron_corrected_filename (file where the corrected information has replaced the original information)
5631: scantron_skipped_filename (contains the exact text of scanlines that where skipped)
5632:
5633: Also there is a separate hash nohist_scantrondata that contains extra
5634: correction information that isn't representable in the bubblesheet
5635: file (see &scantron_getfile() for more information)
5636:
5637: After all scanlines are either valid, marked as valid or skipped, then
5638: foreach line foreach problem in the picked sequence, an ssi request is
5639: made that simulates a user submitting their selected letter(s) against
5640: the homework problem.
5641:
5642: =over 4
5643:
5644:
5645:
5646: =item defaultFormData
5647:
5648: Returns html hidden inputs used to hold context/default values.
5649:
5650: Arguments:
5651: $symb - $symb of the current resource
5652:
5653: =cut
5654:
5655: sub defaultFormData {
5656: my ($symb)=@_;
5657: return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />';
5658: }
5659:
5660:
5661: =pod
5662:
5663: =item getSequenceDropDown
5664:
5665: Return html dropdown of possible sequences to grade
5666:
5667: Arguments:
5668: $symb - $symb of the current resource
5669: $map_error - ref to scalar which will container error if
5670: $navmap object is unavailable in &getSymbMap().
5671:
5672: =cut
5673:
5674: sub getSequenceDropDown {
5675: my ($symb,$map_error)=@_;
5676: my $result='<select name="selectpage">'."\n";
5677: my ($titles,$symbx) = &getSymbMap($map_error);
5678: if (ref($map_error)) {
5679: return if ($$map_error);
5680: }
5681: my ($curpage)=&Apache::lonnet::decode_symb($symb);
5682: my $ctr=0;
5683: foreach (@$titles) {
5684: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
5685: $result.='<option value="'.$$symbx{$_}.'" '.
5686: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
5687: '>'.$showtitle.'</option>'."\n";
5688: $ctr++;
5689: }
5690: $result.= '</select>';
5691: return $result;
5692: }
5693:
5694: my %bubble_lines_per_response; # no. bubble lines for each response.
5695: # key is zero-based index - 0, 1, 2 ...
5696:
5697: my %first_bubble_line; # First bubble line no. for each bubble.
5698:
5699: my %subdivided_bubble_lines; # no. bubble lines for optionresponse,
5700: # matchresponse or rankresponse, where
5701: # an individual response can have multiple
5702: # lines
5703:
5704: my %responsetype_per_response; # responsetype for each response
5705:
5706: my %masterseq_id_responsenum; # src_id (e.g., 12.3_0.11 etc.) for each
5707: # numbered response. Needed when randomorder
5708: # or randompick are in use. Key is ID, value
5709: # is response number.
5710:
5711: # Save and restore the bubble lines array to the form env.
5712:
5713:
5714: sub save_bubble_lines {
5715: foreach my $line (keys(%bubble_lines_per_response)) {
5716: $env{"form.scantron.bubblelines.$line"} = $bubble_lines_per_response{$line};
5717: $env{"form.scantron.first_bubble_line.$line"} =
5718: $first_bubble_line{$line};
5719: $env{"form.scantron.sub_bubblelines.$line"} =
5720: $subdivided_bubble_lines{$line};
5721: $env{"form.scantron.responsetype.$line"} =
5722: $responsetype_per_response{$line};
5723: }
5724: foreach my $resid (keys(%masterseq_id_responsenum)) {
5725: my $line = $masterseq_id_responsenum{$resid};
5726: $env{"form.scantron.residpart.$line"} = $resid;
5727: }
5728: }
5729:
5730:
5731: sub restore_bubble_lines {
5732: my $line = 0;
5733: %bubble_lines_per_response = ();
5734: %masterseq_id_responsenum = ();
5735: while ($env{"form.scantron.bubblelines.$line"}) {
5736: my $value = $env{"form.scantron.bubblelines.$line"};
5737: $bubble_lines_per_response{$line} = $value;
5738: $first_bubble_line{$line} =
5739: $env{"form.scantron.first_bubble_line.$line"};
5740: $subdivided_bubble_lines{$line} =
5741: $env{"form.scantron.sub_bubblelines.$line"};
5742: $responsetype_per_response{$line} =
5743: $env{"form.scantron.responsetype.$line"};
5744: my $id = $env{"form.scantron.residpart.$line"};
5745: $masterseq_id_responsenum{$id} = $line;
5746: $line++;
5747: }
5748: }
5749:
5750: =pod
5751:
5752: =item scantron_filenames
5753:
5754: Returns a list of the scantron files in the current course
5755:
5756: =cut
5757:
5758: sub scantron_filenames {
5759: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5760: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5761: my $getpropath = 1;
5762: my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
5763: $cname,$getpropath);
5764: my @possiblenames;
5765: if (ref($dirlist) eq 'ARRAY') {
5766: foreach my $filename (sort(@{$dirlist})) {
5767: ($filename)=split(/&/,$filename);
5768: if ($filename!~/^scantron_orig_/) { next ; }
5769: $filename=~s/^scantron_orig_//;
5770: push(@possiblenames,$filename);
5771: }
5772: }
5773: return @possiblenames;
5774: }
5775:
5776: =pod
5777:
5778: =item scantron_uploads
5779:
5780: Returns html drop-down list of scantron files in current course.
5781:
5782: Arguments:
5783: $file2grade - filename to set as selected in the dropdown
5784:
5785: =cut
5786:
5787: sub scantron_uploads {
5788: my ($file2grade) = @_;
5789: my $result= '<select name="scantron_selectfile">';
5790: $result.="<option></option>";
5791: foreach my $filename (sort(&scantron_filenames())) {
5792: $result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
5793: }
5794: $result.="</select>";
5795: return $result;
5796: }
5797:
5798: =pod
5799:
5800: =item scantron_scantab
5801:
5802: Returns html drop down of the scantron formats in the scantronformat.tab
5803: file.
5804:
5805: =cut
5806:
5807: sub scantron_scantab {
5808: my $result='<select name="scantron_format">'."\n";
5809: $result.='<option></option>'."\n";
5810: my @lines = &Apache::lonnet::get_scantronformat_file();
5811: if (@lines > 0) {
5812: foreach my $line (@lines) {
5813: next if (($line =~ /^\#/) || ($line eq ''));
5814: my ($name,$descrip)=split(/:/,$line);
5815: $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
5816: }
5817: }
5818: $result.='</select>'."\n";
5819: return $result;
5820: }
5821:
5822: =pod
5823:
5824: =item scantron_CODElist
5825:
5826: Returns html drop down of the saved CODE lists from current course,
5827: generated from earlier printings.
5828:
5829: =cut
5830:
5831: sub scantron_CODElist {
5832: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5833: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5834: my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
5835: my $namechoice='<option></option>';
5836: foreach my $name (sort {uc($a) cmp uc($b)} @names) {
5837: if ($name =~ /^error: 2 /) { next; }
5838: if ($name =~ /^type\0/) { next; }
5839: $namechoice.='<option value="'.$name.'">'.$name.'</option>';
5840: }
5841: $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
5842: return $namechoice;
5843: }
5844:
5845: =pod
5846:
5847: =item scantron_CODEunique
5848:
5849: Returns the html for "Each CODE to be used once" radio.
5850:
5851: =cut
5852:
5853: sub scantron_CODEunique {
5854: my $result='<span class="LC_nobreak">
5855: <label><input type="radio" name="scantron_CODEunique"
5856: value="yes" checked="checked" />'.&mt('Yes').' </label>
5857: </span>
5858: <span class="LC_nobreak">
5859: <label><input type="radio" name="scantron_CODEunique"
5860: value="no" />'.&mt('No').' </label>
5861: </span>';
5862: return $result;
5863: }
5864:
5865: =pod
5866:
5867: =item scantron_selectphase
5868:
5869: Generates the initial screen to start the bubblesheet process.
5870: Allows for - starting a grading run.
5871: - downloading existing scan data (original, corrected
5872: or skipped info)
5873:
5874: - uploading new scan data
5875:
5876: Arguments:
5877: $r - The Apache request object
5878: $file2grade - name of the file that contain the scanned data to score
5879:
5880: =cut
5881:
5882: sub scantron_selectphase {
5883: my ($r,$file2grade,$symb) = @_;
5884: if (!$symb) {return '';}
5885: my $map_error;
5886: my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
5887: if ($map_error) {
5888: $r->print('<br />'.&navmap_errormsg().'<br />');
5889: return;
5890: }
5891: my $default_form_data=&defaultFormData($symb);
5892: my $file_selector=&scantron_uploads($file2grade);
5893: my $format_selector=&scantron_scantab();
5894: my $CODE_selector=&scantron_CODElist();
5895: my $CODE_unique=&scantron_CODEunique();
5896: my $result;
5897:
5898: $ssi_error = 0;
5899:
5900: if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
5901: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
5902:
5903: # Chunk of form to prompt for a scantron file upload.
5904:
5905: $r->print('
5906: <br />');
5907: my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
5908: my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
5909: my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
5910: &js_escape(\$alertmsg);
5911: my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($cdom);
5912: $r->print(&Apache::lonhtmlcommon::scripttag('
5913: function checkUpload(formname) {
5914: if (formname.upfile.value == "") {
5915: alert("'.$alertmsg.'");
5916: return false;
5917: }
5918: formname.submit();
5919: }'."\n".$formatjs));
5920: $r->print('
5921: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
5922: '.$default_form_data.'
5923: <input name="courseid" type="hidden" value="'.$cnum.'" />
5924: <input name="domainid" type="hidden" value="'.$cdom.'" />
5925: <input name="command" value="scantronupload_save" type="hidden" />
5926: '.&Apache::loncommon::start_data_table('LC_scantron_action').'
5927: '.&Apache::loncommon::start_data_table_header_row().'
5928: <th>
5929: '.&mt('Specify a bubblesheet data file to upload.').'
5930: </th>
5931: '.&Apache::loncommon::end_data_table_header_row().'
5932: '.&Apache::loncommon::start_data_table_row().'
5933: <td>
5934: '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'<br />'."\n");
5935: if ($formatoptions) {
5936: $r->print('</td>
5937: '.&Apache::loncommon::end_data_table_row().'
5938: '.&Apache::loncommon::start_data_table_row().'
5939: <td>'.$formattitle.(' 'x2).$formatoptions.'
5940: </td>
5941: '.&Apache::loncommon::end_data_table_row().'
5942: '.&Apache::loncommon::start_data_table_row().'
5943: <td>'
5944: );
5945: } else {
5946: $r->print(' <br />');
5947: }
5948: $r->print('<input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
5949: </td>
5950: '.&Apache::loncommon::end_data_table_row().'
5951: '.&Apache::loncommon::end_data_table().'
5952: </form>'
5953: );
5954:
5955: }
5956:
5957: # Chunk of form to prompt for a file to grade and how:
5958:
5959: $result.= '
5960: <br />
5961: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
5962: <input type="hidden" name="command" value="scantron_warning" />
5963: '.$default_form_data.'
5964: '.&Apache::loncommon::start_data_table('LC_scantron_action').'
5965: '.&Apache::loncommon::start_data_table_header_row().'
5966: <th colspan="2">
5967: '.&mt('Specify file and which Folder/Sequence to grade').'
5968: </th>
5969: '.&Apache::loncommon::end_data_table_header_row().'
5970: '.&Apache::loncommon::start_data_table_row().'
5971: <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
5972: '.&Apache::loncommon::end_data_table_row().'
5973: '.&Apache::loncommon::start_data_table_row().'
5974: <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
5975: '.&Apache::loncommon::end_data_table_row().'
5976: '.&Apache::loncommon::start_data_table_row().'
5977: <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
5978: '.&Apache::loncommon::end_data_table_row().'
5979: '.&Apache::loncommon::start_data_table_row().'
5980: <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
5981: '.&Apache::loncommon::end_data_table_row().'
5982: '.&Apache::loncommon::start_data_table_row().'
5983: <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
5984: '.&Apache::loncommon::end_data_table_row().'
5985: '.&Apache::loncommon::start_data_table_row().'
5986: <td> '.&mt('Options:').' </td>
5987: <td>
5988: <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
5989: <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
5990: <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
5991: </td>
5992: '.&Apache::loncommon::end_data_table_row().'
5993: '.&Apache::loncommon::start_data_table_row().'
5994: <td colspan="2">
5995: <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
5996: </td>
5997: '.&Apache::loncommon::end_data_table_row().'
5998: '.&Apache::loncommon::end_data_table().'
5999: </form>
6000: ';
6001:
6002: $r->print($result);
6003:
6004: # Chunk of the form that prompts to view a scoring office file,
6005: # corrected file, skipped records in a file.
6006:
6007: $r->print('
6008: <br />
6009: <form action="/adm/grades" name="scantron_download">
6010: '.$default_form_data.'
6011: <input type="hidden" name="command" value="scantron_download" />
6012: '.&Apache::loncommon::start_data_table('LC_scantron_action').'
6013: '.&Apache::loncommon::start_data_table_header_row().'
6014: <th>
6015: '.&mt('Download a scoring office file').'
6016: </th>
6017: '.&Apache::loncommon::end_data_table_header_row().'
6018: '.&Apache::loncommon::start_data_table_row().'
6019: <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).'
6020: <br />
6021: <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
6022: '.&Apache::loncommon::end_data_table_row().'
6023: '.&Apache::loncommon::end_data_table().'
6024: </form>
6025: <br />
6026: ');
6027:
6028: &Apache::lonpickcode::code_list($r,2);
6029:
6030: $r->print('<br /><form method="post" name="checkscantron" action="">'.
6031: $default_form_data."\n".
6032: &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
6033: &Apache::loncommon::start_data_table_header_row()."\n".
6034: '<th colspan="2">
6035: '.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
6036: '</th>'."\n".
6037: &Apache::loncommon::end_data_table_header_row()."\n".
6038: &Apache::loncommon::start_data_table_row()."\n".
6039: '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
6040: '<td> '.$sequence_selector.' </td>'.
6041: &Apache::loncommon::end_data_table_row()."\n".
6042: &Apache::loncommon::start_data_table_row()."\n".
6043: '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
6044: '<td> '.$file_selector.' </td>'."\n".
6045: &Apache::loncommon::end_data_table_row()."\n".
6046: &Apache::loncommon::start_data_table_row()."\n".
6047: '<td> '.&mt('Format of data file:').' </td>'."\n".
6048: '<td> '.$format_selector.' </td>'."\n".
6049: &Apache::loncommon::end_data_table_row()."\n".
6050: &Apache::loncommon::start_data_table_row()."\n".
6051: '<td> '.&mt('Options').' </td>'."\n".
6052: '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
6053: &Apache::loncommon::end_data_table_row()."\n".
6054: &Apache::loncommon::start_data_table_row()."\n".
6055: '<td colspan="2">'."\n".
6056: '<input type="hidden" name="command" value="checksubmissions" />'."\n".
6057: '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
6058: '</td>'."\n".
6059: &Apache::loncommon::end_data_table_row()."\n".
6060: &Apache::loncommon::end_data_table()."\n".
6061: '</form><br />');
6062: return;
6063: }
6064:
6065: =pod
6066:
6067: =item username_to_idmap
6068:
6069: creates a hash keyed by student/employee ID with values of the corresponding
6070: student username:domain. If a single ID occurs for more than one student,
6071: the status of the student is checked, and if Active, the value in the hash
6072: will be set to the Active student.
6073:
6074: Arguments:
6075:
6076: $classlist - reference to the class list hash. This is a hash
6077: keyed by student name:domain whose elements are references
6078: to arrays containing various chunks of information
6079: about the student. (See loncoursedata for more info).
6080:
6081: Returns
6082: %idmap - the constructed hash
6083:
6084: =cut
6085:
6086: sub username_to_idmap {
6087: my ($classlist)= @_;
6088: my %idmap;
6089: foreach my $student (keys(%$classlist)) {
6090: my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
6091: unless ($id eq '') {
6092: if (!exists($idmap{$id})) {
6093: $idmap{$id} = $student;
6094: } else {
6095: my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
6096: if ($status eq 'Active') {
6097: $idmap{$id} = $student;
6098: }
6099: }
6100: }
6101: }
6102: return %idmap;
6103: }
6104:
6105: =pod
6106:
6107: =item scantron_fixup_scanline
6108:
6109: Process a requested correction to a scanline.
6110:
6111: Arguments:
6112: $scantron_config - hash from &Apache::lonnet::get_scantron_config()
6113: $scan_data - hash of correction information
6114: (see &scantron_getfile())
6115: $line - existing scanline
6116: $whichline - line number of the passed in scanline
6117: $field - type of change to process
6118: (either
6119: 'ID' -> correct the student/employee ID
6120: 'CODE' -> correct the CODE
6121: 'answer' -> fixup the submitted answers)
6122:
6123: $args - hash of additional info,
6124: - 'ID'
6125: 'newid' -> studentID to use in replacement
6126: of existing one
6127: - 'CODE'
6128: 'CODE_ignore_dup' - set to true if duplicates
6129: should be ignored.
6130: 'CODE' - is new code or 'use_unfound'
6131: if the existing unfound code should
6132: be used as is
6133: - 'answer'
6134: 'response' - new answer or 'none' if blank
6135: 'question' - the bubble line to change
6136: 'questionnum' - the question identifier,
6137: may include subquestion.
6138:
6139: Returns:
6140: $line - the modified scanline
6141:
6142: Side effects:
6143: $scan_data - may be updated
6144:
6145: =cut
6146:
6147:
6148: sub scantron_fixup_scanline {
6149: my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
6150: if ($field eq 'ID') {
6151: if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
6152: return ($line,1,'New value too large');
6153: }
6154: if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
6155: $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
6156: $args->{'newid'});
6157: }
6158: substr($line,$$scantron_config{'IDstart'}-1,
6159: $$scantron_config{'IDlength'})=$args->{'newid'};
6160: if ($args->{'newid'}=~/^\s*$/) {
6161: &scan_data($scan_data,"$whichline.user",
6162: $args->{'username'}.':'.$args->{'domain'});
6163: }
6164: } elsif ($field eq 'CODE') {
6165: if ($args->{'CODE_ignore_dup'}) {
6166: &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
6167: }
6168: &scan_data($scan_data,"$whichline.useCODE",'1');
6169: if ($args->{'CODE'} ne 'use_unfound') {
6170: if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
6171: return ($line,1,'New CODE value too large');
6172: }
6173: if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
6174: $args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
6175: }
6176: substr($line,$$scantron_config{'CODEstart'}-1,
6177: $$scantron_config{'CODElength'})=$args->{'CODE'};
6178: }
6179: } elsif ($field eq 'answer') {
6180: my $length=$scantron_config->{'Qlength'};
6181: my $off=$scantron_config->{'Qoff'};
6182: my $on=$scantron_config->{'Qon'};
6183: my $answer=${off}x$length;
6184: if ($args->{'response'} eq 'none') {
6185: &scan_data($scan_data,
6186: "$whichline.no_bubble.".$args->{'questionnum'},'1');
6187: } else {
6188: if ($on eq 'letter') {
6189: my @alphabet=('A'..'Z');
6190: $answer=$alphabet[$args->{'response'}];
6191: } elsif ($on eq 'number') {
6192: $answer=$args->{'response'}+1;
6193: if ($answer == 10) { $answer = '0'; }
6194: } else {
6195: substr($answer,$args->{'response'},1)=$on;
6196: }
6197: &scan_data($scan_data,
6198: "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
6199: }
6200: my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
6201: substr($line,$where-1,$length)=$answer;
6202: }
6203: return $line;
6204: }
6205:
6206: =pod
6207:
6208: =item scan_data
6209:
6210: Edit or look up an item in the scan_data hash.
6211:
6212: Arguments:
6213: $scan_data - The hash (see scantron_getfile)
6214: $key - shorthand of the key to edit (actual key is
6215: scantronfilename_key).
6216: $data - New value of the hash entry.
6217: $delete - If true, the entry is removed from the hash.
6218:
6219: Returns:
6220: The new value of the hash table field (undefined if deleted).
6221:
6222: =cut
6223:
6224:
6225: sub scan_data {
6226: my ($scan_data,$key,$value,$delete)=@_;
6227: my $filename=$env{'form.scantron_selectfile'};
6228: if (defined($value)) {
6229: $scan_data->{$filename.'_'.$key} = $value;
6230: }
6231: if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
6232: return $scan_data->{$filename.'_'.$key};
6233: }
6234:
6235: # ----- These first few routines are general use routines.----
6236:
6237: # Return the number of occurences of a pattern in a string.
6238:
6239: sub occurence_count {
6240: my ($string, $pattern) = @_;
6241:
6242: my @matches = ($string =~ /$pattern/g);
6243:
6244: return scalar(@matches);
6245: }
6246:
6247:
6248: # Take a string known to have digits and convert all the
6249: # digits into letters in the range J,A..I.
6250:
6251: sub digits_to_letters {
6252: my ($input) = @_;
6253:
6254: my @alphabet = ('J', 'A'..'I');
6255:
6256: my @input = split(//, $input);
6257: my $output ='';
6258: for (my $i = 0; $i < scalar(@input); $i++) {
6259: if ($input[$i] =~ /\d/) {
6260: $output .= $alphabet[$input[$i]];
6261: } else {
6262: $output .= $input[$i];
6263: }
6264: }
6265: return $output;
6266: }
6267:
6268: =pod
6269:
6270: =item scantron_parse_scanline
6271:
6272: Decodes a scanline from the selected bubblesheet file
6273:
6274: Arguments:
6275: line - The text of the bubblesheet file line to process
6276: whichline - Line number
6277: scantron_config - Hash describing the format of the bubblesheet lines.
6278: scan_data - Hash of extra information about the scanline
6279: (see scantron_getfile for more information)
6280: just_header - True if should not process question answers but only
6281: the stuff to the left of the answers.
6282: randomorder - True if randomorder in use
6283: randompick - True if randompick in use
6284: sequence - Exam folder URL
6285: master_seq - Ref to array containing symbs in exam folder
6286: symb_to_resource - Ref to hash of symbs for resources in exam folder
6287: (corresponding values are resource objects)
6288: partids_by_symb - Ref to hash of symb -> array ref of partIDs
6289: orderedforcode - Ref to hash of arrays. keys are CODEs and values
6290: are refs to an array of resource objects, ordered
6291: according to order used for CODE, when randomorder
6292: and or randompick are in use.
6293: respnumlookup - Ref to hash mapping question numbers in bubble lines
6294: for current line to question number used for same question
6295: in "Master Sequence" (as seen by Course Coordinator).
6296: startline - Ref to hash where key is question number (0 is first)
6297: and value is number of first bubble line for current
6298: student or code-based randompick and/or randomorder.
6299: totalref - Ref of scalar used to score total number of bubble
6300: lines needed for responses in a scan line (used when
6301: randompick in use.
6302:
6303: Returns:
6304: Hash containing the result of parsing the scanline
6305:
6306: Keys are all proceeded by the string 'scantron.'
6307:
6308: CODE - the CODE in use for this scanline
6309: useCODE - 1 if the CODE is invalid but it usage has been forced
6310: by the operator
6311: CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
6312: CODEs were selected, but the usage has been
6313: forced by the operator
6314: ID - student/employee ID
6315: PaperID - if used, the ID number printed on the sheet when the
6316: paper was scanned
6317: FirstName - first name from the sheet
6318: LastName - last name from the sheet
6319:
6320: if just_header was not true these key may also exist
6321:
6322: missingerror - a list of bubble ranges that are considered to be answers
6323: to a single question that don't have any bubbles filled in.
6324: Of the form questionnumber:firstbubblenumber:count.
6325: doubleerror - a list of bubble ranges that are considered to be answers
6326: to a single question that have more than one bubble filled in.
6327: Of the form questionnumber::firstbubblenumber:count
6328:
6329: In the above, count is the number of bubble responses in the
6330: input line needed to represent the possible answers to the question.
6331: e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
6332: per line would have count = 2.
6333:
6334: maxquest - the number of the last bubble line that was parsed
6335:
6336: (<number> starts at 1)
6337: <number>.answer - zero or more letters representing the selected
6338: letters from the scanline for the bubble line
6339: <number>.
6340: if blank there was either no bubble or there where
6341: multiple bubbles, (consult the keys missingerror and
6342: doubleerror if this is an error condition)
6343:
6344: =cut
6345:
6346: sub scantron_parse_scanline {
6347: my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
6348: $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
6349: $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
6350:
6351: my %record;
6352: my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
6353: if (!($$scantron_config{'CODElocation'} eq 0 ||
6354: $$scantron_config{'CODElocation'} eq 'none')) {
6355: if ($$scantron_config{'CODElocation'} < 0 ||
6356: $$scantron_config{'CODElocation'} eq 'letter' ||
6357: $$scantron_config{'CODElocation'} eq 'number') {
6358: $record{'scantron.CODE'}=substr($data,
6359: $$scantron_config{'CODEstart'}-1,
6360: $$scantron_config{'CODElength'});
6361: if (&scan_data($scan_data,"$whichline.useCODE")) {
6362: $record{'scantron.useCODE'}=1;
6363: }
6364: if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
6365: $record{'scantron.CODE_ignore_dup'}=1;
6366: }
6367: } else {
6368: #FIXME interpret first N questions
6369: }
6370: }
6371: $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
6372: $$scantron_config{'IDlength'});
6373: $record{'scantron.PaperID'}=
6374: substr($data,$$scantron_config{'PaperID'}-1,
6375: $$scantron_config{'PaperIDlength'});
6376: $record{'scantron.FirstName'}=
6377: substr($data,$$scantron_config{'FirstName'}-1,
6378: $$scantron_config{'FirstNamelength'});
6379: $record{'scantron.LastName'}=
6380: substr($data,$$scantron_config{'LastName'}-1,
6381: $$scantron_config{'LastNamelength'});
6382: if ($just_header) { return \%record; }
6383:
6384: my @alphabet=('A'..'Z');
6385: my $questnum=0;
6386: my $ansnum =1; # Multiple 'answer lines'/question.
6387:
6388: my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
6389: if ($randompick || $randomorder) {
6390: my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
6391: $master_seq,$symb_to_resource,
6392: $partids_by_symb,$orderedforcode,
6393: $respnumlookup,$startline);
6394: if ($total) {
6395: $lastpos = $total*$$scantron_config{'Qlength'};
6396: }
6397: if (ref($totalref)) {
6398: $$totalref = $total;
6399: }
6400: }
6401: my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos); # Answers
6402: chomp($questions); # Get rid of any trailing \n.
6403: $questions =~ s/\r$//; # Get rid of trailing \r too (MAC or Win uploads).
6404: while (length($questions)) {
6405: my $answers_needed;
6406: if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
6407: $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
6408: } else {
6409: $answers_needed = $bubble_lines_per_response{$questnum};
6410: }
6411: my $answer_length = ($$scantron_config{'Qlength'} * $answers_needed)
6412: || 1;
6413: $questnum++;
6414: my $quest_id = $questnum;
6415: my $currentquest = substr($questions,0,$answer_length);
6416: $questions = substr($questions,$answer_length);
6417: if (length($currentquest) < $answer_length) { next; }
6418:
6419: my $subdivided;
6420: if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
6421: $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
6422: } else {
6423: $subdivided = $subdivided_bubble_lines{$questnum-1};
6424: }
6425: if ($subdivided =~ /,/) {
6426: my $subquestnum = 1;
6427: my $subquestions = $currentquest;
6428: my @subanswers_needed = split(/,/,$subdivided);
6429: foreach my $subans (@subanswers_needed) {
6430: my $subans_length =
6431: ($$scantron_config{'Qlength'} * $subans) || 1;
6432: my $currsubquest = substr($subquestions,0,$subans_length);
6433: $subquestions = substr($subquestions,$subans_length);
6434: $quest_id = "$questnum.$subquestnum";
6435: if (($$scantron_config{'Qon'} eq 'letter') ||
6436: ($$scantron_config{'Qon'} eq 'number')) {
6437: $ansnum = &scantron_validator_lettnum($ansnum,
6438: $questnum,$quest_id,$subans,$currsubquest,$whichline,
6439: \@alphabet,\%record,$scantron_config,$scan_data,
6440: $randomorder,$randompick,$respnumlookup);
6441: } else {
6442: $ansnum = &scantron_validator_positional($ansnum,
6443: $questnum,$quest_id,$subans,$currsubquest,$whichline,
6444: \@alphabet,\%record,$scantron_config,$scan_data,
6445: $randomorder,$randompick,$respnumlookup);
6446: }
6447: $subquestnum ++;
6448: }
6449: } else {
6450: if (($$scantron_config{'Qon'} eq 'letter') ||
6451: ($$scantron_config{'Qon'} eq 'number')) {
6452: $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
6453: $quest_id,$answers_needed,$currentquest,$whichline,
6454: \@alphabet,\%record,$scantron_config,$scan_data,
6455: $randomorder,$randompick,$respnumlookup);
6456: } else {
6457: $ansnum = &scantron_validator_positional($ansnum,$questnum,
6458: $quest_id,$answers_needed,$currentquest,$whichline,
6459: \@alphabet,\%record,$scantron_config,$scan_data,
6460: $randomorder,$randompick,$respnumlookup);
6461: }
6462: }
6463: }
6464: $record{'scantron.maxquest'}=$questnum;
6465: return \%record;
6466: }
6467:
6468: sub get_master_seq {
6469: my ($resources,$master_seq,$symb_to_resource) = @_;
6470: return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') &&
6471: (ref($symb_to_resource) eq 'HASH'));
6472: my $resource_error;
6473: foreach my $resource (@{$resources}) {
6474: my $ressymb;
6475: if (ref($resource)) {
6476: $ressymb = $resource->symb();
6477: push(@{$master_seq},$ressymb);
6478: $symb_to_resource->{$ressymb} = $resource;
6479: } else {
6480: $resource_error = 1;
6481: last;
6482: }
6483: }
6484: return $resource_error;
6485: }
6486:
6487: sub get_respnum_lookups {
6488: my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
6489: $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
6490: return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
6491: (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
6492: (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
6493: (ref($startline) eq 'HASH'));
6494: my ($user,$scancode);
6495: if ((exists($record->{'scantron.CODE'})) &&
6496: (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
6497: $scancode = $record->{'scantron.CODE'};
6498: } else {
6499: $user = &scantron_find_student($record,$scan_data,$idmap,$line);
6500: }
6501: my @mapresources =
6502: &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
6503: $orderedforcode);
6504: my $total = 0;
6505: my $count = 0;
6506: foreach my $resource (@mapresources) {
6507: my $id = $resource->id();
6508: my $symb = $resource->symb();
6509: if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
6510: foreach my $partid (@{$partids_by_symb->{$symb}}) {
6511: my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
6512: if ($respnum ne '') {
6513: $respnumlookup->{$count} = $respnum;
6514: $startline->{$count} = $total;
6515: $total += $bubble_lines_per_response{$respnum};
6516: $count ++;
6517: }
6518: }
6519: }
6520: }
6521: return $total;
6522: }
6523:
6524: sub scantron_validator_lettnum {
6525: my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
6526: $alphabet,$record,$scantron_config,$scan_data,$randomorder,
6527: $randompick,$respnumlookup) = @_;
6528:
6529: # Qon 'letter' implies for each slot in currquest we have:
6530: # ? or * for doubles, a letter in A-Z for a bubble, and
6531: # about anything else (esp. a value of Qoff) for missing
6532: # bubbles.
6533: #
6534: # Qon 'number' implies each slot gives a digit that indexes the
6535: # bubbles filled, or Qoff, or a non-number for unbubbled lines,
6536: # and * or ? for double bubbles on a single line.
6537: #
6538:
6539: my $matchon;
6540: if ($$scantron_config{'Qon'} eq 'letter') {
6541: $matchon = '[A-Z]';
6542: } elsif ($$scantron_config{'Qon'} eq 'number') {
6543: $matchon = '\d';
6544: }
6545: my $occurrences = 0;
6546: my $responsenum = $questnum-1;
6547: if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
6548: $responsenum = $respnumlookup->{$questnum-1}
6549: }
6550: if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
6551: ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
6552: ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
6553: ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
6554: ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
6555: ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
6556: my @singlelines = split('',$currquest);
6557: foreach my $entry (@singlelines) {
6558: $occurrences = &occurence_count($entry,$matchon);
6559: if ($occurrences > 1) {
6560: last;
6561: }
6562: }
6563: } else {
6564: $occurrences = &occurence_count($currquest,$matchon);
6565: }
6566: if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
6567: push(@{$record->{'scantron.doubleerror'}},$quest_id);
6568: for (my $ans=0; $ans<$answers_needed; $ans++) {
6569: my $bubble = substr($currquest,$ans,1);
6570: if ($bubble =~ /$matchon/ ) {
6571: if ($$scantron_config{'Qon'} eq 'number') {
6572: if ($bubble == 0) {
6573: $bubble = 10;
6574: }
6575: $record->{"scantron.$ansnum.answer"} =
6576: $alphabet->[$bubble-1];
6577: } else {
6578: $record->{"scantron.$ansnum.answer"} = $bubble;
6579: }
6580: } else {
6581: $record->{"scantron.$ansnum.answer"}='';
6582: }
6583: $ansnum++;
6584: }
6585: } elsif (!defined($currquest)
6586: || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
6587: || (&occurence_count($currquest,$matchon) == 0)) {
6588: for (my $ans=0; $ans<$answers_needed; $ans++ ) {
6589: $record->{"scantron.$ansnum.answer"}='';
6590: $ansnum++;
6591: }
6592: if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
6593: push(@{$record->{'scantron.missingerror'}},$quest_id);
6594: }
6595: } else {
6596: if ($$scantron_config{'Qon'} eq 'number') {
6597: $currquest = &digits_to_letters($currquest);
6598: }
6599: for (my $ans=0; $ans<$answers_needed; $ans++) {
6600: my $bubble = substr($currquest,$ans,1);
6601: $record->{"scantron.$ansnum.answer"} = $bubble;
6602: $ansnum++;
6603: }
6604: }
6605: return $ansnum;
6606: }
6607:
6608: sub scantron_validator_positional {
6609: my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
6610: $whichline,$alphabet,$record,$scantron_config,$scan_data,
6611: $randomorder,$randompick,$respnumlookup) = @_;
6612:
6613: # Otherwise there's a positional notation;
6614: # each bubble line requires Qlength items, and there are filled in
6615: # bubbles for each case where there 'Qon' characters.
6616: #
6617:
6618: my @array=split($$scantron_config{'Qon'},$currquest,-1);
6619:
6620: # If the split only gives us one element.. the full length of the
6621: # answer string, no bubbles are filled in:
6622:
6623: if ($answers_needed eq '') {
6624: return;
6625: }
6626:
6627: if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
6628: for (my $ans=0; $ans<$answers_needed; $ans++ ) {
6629: $record->{"scantron.$ansnum.answer"}='';
6630: $ansnum++;
6631: }
6632: if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
6633: push(@{$record->{"scantron.missingerror"}},$quest_id);
6634: }
6635: } elsif (scalar(@array) == 2) {
6636: my $location = length($array[0]);
6637: my $line_num = int($location / $$scantron_config{'Qlength'});
6638: my $bubble = $alphabet->[$location % $$scantron_config{'Qlength'}];
6639: for (my $ans=0; $ans<$answers_needed; $ans++) {
6640: if ($ans eq $line_num) {
6641: $record->{"scantron.$ansnum.answer"} = $bubble;
6642: } else {
6643: $record->{"scantron.$ansnum.answer"} = ' ';
6644: }
6645: $ansnum++;
6646: }
6647: } else {
6648: # If there's more than one instance of a bubble character
6649: # That's a double bubble; with positional notation we can
6650: # record all the bubbles filled in as well as the
6651: # fact this response consists of multiple bubbles.
6652: #
6653: my $responsenum = $questnum-1;
6654: if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
6655: $responsenum = $respnumlookup->{$questnum-1}
6656: }
6657: if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
6658: ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
6659: ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
6660: ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
6661: ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
6662: ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
6663: my $doubleerror = 0;
6664: while (($currquest >= $$scantron_config{'Qlength'}) &&
6665: (!$doubleerror)) {
6666: my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
6667: $currquest = substr($currquest,$$scantron_config{'Qlength'});
6668: my @currarray = split($$scantron_config{'Qon'},$currline,-1);
6669: if (length(@currarray) > 2) {
6670: $doubleerror = 1;
6671: }
6672: }
6673: if ($doubleerror) {
6674: push(@{$record->{'scantron.doubleerror'}},$quest_id);
6675: }
6676: } else {
6677: push(@{$record->{'scantron.doubleerror'}},$quest_id);
6678: }
6679: my $item = $ansnum;
6680: for (my $ans=0; $ans<$answers_needed; $ans++) {
6681: $record->{"scantron.$item.answer"} = '';
6682: $item ++;
6683: }
6684:
6685: my @ans=@array;
6686: my $i=0;
6687: my $increment = 0;
6688: while ($#ans) {
6689: $i+=length($ans[0]) + $increment;
6690: my $line = int($i/$$scantron_config{'Qlength'} + $ansnum);
6691: my $bubble = $i%$$scantron_config{'Qlength'};
6692: $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
6693: shift(@ans);
6694: $increment = 1;
6695: }
6696: $ansnum += $answers_needed;
6697: }
6698: return $ansnum;
6699: }
6700:
6701: =pod
6702:
6703: =item scantron_add_delay
6704:
6705: Adds an error message that occurred during the grading phase to a
6706: queue of messages to be shown after grading pass is complete
6707:
6708: Arguments:
6709: $delayqueue - arrary ref of hash ref of error messages
6710: $scanline - the scanline that caused the error
6711: $errormesage - the error message
6712: $errorcode - a numeric code for the error
6713:
6714: Side Effects:
6715: updates the $delayqueue to have a new hash ref of the error
6716:
6717: =cut
6718:
6719: sub scantron_add_delay {
6720: my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
6721: push(@$delayqueue,
6722: {'line' => $scanline, 'emsg' => $errormessage,
6723: 'ecode' => $errorcode }
6724: );
6725: }
6726:
6727: =pod
6728:
6729: =item scantron_find_student
6730:
6731: Finds the username for the current scanline
6732:
6733: Arguments:
6734: $scantron_record - hash result from scantron_parse_scanline
6735: $scan_data - hash of correction information
6736: (see &scantron_getfile() form more information)
6737: $idmap - hash from &username_to_idmap()
6738: $line - number of current scanline
6739:
6740: Returns:
6741: Either 'username:domain' or undef if unknown
6742:
6743: =cut
6744:
6745: sub scantron_find_student {
6746: my ($scantron_record,$scan_data,$idmap,$line)=@_;
6747: my $scanID=$$scantron_record{'scantron.ID'};
6748: if ($scanID =~ /^\s*$/) {
6749: return &scan_data($scan_data,"$line.user");
6750: }
6751: foreach my $id (keys(%$idmap)) {
6752: if (lc($id) eq lc($scanID)) {
6753: return $$idmap{$id};
6754: }
6755: }
6756: return undef;
6757: }
6758:
6759: =pod
6760:
6761: =item scantron_filter
6762:
6763: Filter sub for lonnavmaps, filters out hidden resources if ignore
6764: hidden resources was selected
6765:
6766: =cut
6767:
6768: sub scantron_filter {
6769: my ($curres)=@_;
6770:
6771: if (ref($curres) && $curres->is_problem()) {
6772: # if the user has asked to not have either hidden
6773: # or 'randomout' controlled resources to be graded
6774: # don't include them
6775: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
6776: && $curres->randomout) {
6777: return 0;
6778: }
6779: return 1;
6780: }
6781: return 0;
6782: }
6783:
6784: =pod
6785:
6786: =item scantron_process_corrections
6787:
6788: Gets correction information out of submitted form data and corrects
6789: the scanline
6790:
6791: =cut
6792:
6793: sub scantron_process_corrections {
6794: my ($r) = @_;
6795: my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
6796: my ($scanlines,$scan_data)=&scantron_getfile();
6797: my $classlist=&Apache::loncoursedata::get_classlist();
6798: my $which=$env{'form.scantron_line'};
6799: my $line=&scantron_get_line($scanlines,$scan_data,$which);
6800: my ($skip,$err,$errmsg);
6801: if ($env{'form.scantron_skip_record'}) {
6802: $skip=1;
6803: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
6804: my $newstudent=$env{'form.scantron_username'}.':'.
6805: $env{'form.scantron_domain'};
6806: my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
6807: ($line,$err,$errmsg)=
6808: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
6809: 'ID',{'newid'=>$newid,
6810: 'username'=>$env{'form.scantron_username'},
6811: 'domain'=>$env{'form.scantron_domain'}});
6812: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
6813: my $resolution=$env{'form.scantron_CODE_resolution'};
6814: my $newCODE;
6815: my %args;
6816: if ($resolution eq 'use_unfound') {
6817: $newCODE='use_unfound';
6818: } elsif ($resolution eq 'use_found') {
6819: $newCODE=$env{'form.scantron_CODE_selectedvalue'};
6820: } elsif ($resolution eq 'use_typed') {
6821: $newCODE=$env{'form.scantron_CODE_newvalue'};
6822: } elsif ($resolution =~ /^use_closest_(\d+)/) {
6823: $newCODE=$env{"form.scantron_CODE_closest_$1"};
6824: }
6825: if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
6826: $args{'CODE_ignore_dup'}=1;
6827: }
6828: $args{'CODE'}=$newCODE;
6829: ($line,$err,$errmsg)=
6830: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
6831: 'CODE',\%args);
6832: } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
6833: foreach my $question (split(',',$env{'form.scantron_questions'})) {
6834: ($line,$err,$errmsg)=
6835: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
6836: $which,'answer',
6837: { 'question'=>$question,
6838: 'response'=>$env{"form.scantron_correct_Q_$question"},
6839: 'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
6840: if ($err) { last; }
6841: }
6842: }
6843: if ($err) {
6844: $r->print(
6845: '<p class="LC_error">'
6846: .&mt('Unable to accept last correction, an error occurred: [_1]',
6847: $errmsg)
6848: .'</p>');
6849: } else {
6850: &scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
6851: &scantron_putfile($scanlines,$scan_data);
6852: }
6853: }
6854:
6855: =pod
6856:
6857: =item reset_skipping_status
6858:
6859: Forgets the current set of remember skipped scanlines (and thus
6860: reverts back to considering all lines in the
6861: scantron_skipped_<filename> file)
6862:
6863: =cut
6864:
6865: sub reset_skipping_status {
6866: my ($scanlines,$scan_data)=&scantron_getfile();
6867: &scan_data($scan_data,'remember_skipping',undef,1);
6868: &scantron_putfile(undef,$scan_data);
6869: }
6870:
6871: =pod
6872:
6873: =item start_skipping
6874:
6875: Marks a scanline to be skipped.
6876:
6877: =cut
6878:
6879: sub start_skipping {
6880: my ($scan_data,$i)=@_;
6881: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
6882: if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
6883: $remembered{$i}=2;
6884: } else {
6885: $remembered{$i}=1;
6886: }
6887: &scan_data($scan_data,'remember_skipping',join(':',%remembered));
6888: }
6889:
6890: =pod
6891:
6892: =item should_be_skipped
6893:
6894: Checks whether a scanline should be skipped.
6895:
6896: =cut
6897:
6898: sub should_be_skipped {
6899: my ($scanlines,$scan_data,$i)=@_;
6900: if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
6901: # not redoing old skips
6902: if ($scanlines->{'skipped'}[$i]) { return 1; }
6903: return 0;
6904: }
6905: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
6906:
6907: if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
6908: return 0;
6909: }
6910: return 1;
6911: }
6912:
6913: =pod
6914:
6915: =item remember_current_skipped
6916:
6917: Discovers what scanlines are in the scantron_skipped_<filename>
6918: file and remembers them into scan_data for later use.
6919:
6920: =cut
6921:
6922: sub remember_current_skipped {
6923: my ($scanlines,$scan_data)=&scantron_getfile();
6924: my %to_remember;
6925: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6926: if ($scanlines->{'skipped'}[$i]) {
6927: $to_remember{$i}=1;
6928: }
6929: }
6930:
6931: &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
6932: &scantron_putfile(undef,$scan_data);
6933: }
6934:
6935: =pod
6936:
6937: =item check_for_error
6938:
6939: Checks if there was an error when attempting to remove a specific
6940: scantron_.. bubblesheet data file. Prints out an error if
6941: something went wrong.
6942:
6943: =cut
6944:
6945: sub check_for_error {
6946: my ($r,$result)=@_;
6947: if ($result ne 'ok' && $result ne 'not_found' ) {
6948: $r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
6949: }
6950: }
6951:
6952: =pod
6953:
6954: =item scantron_warning_screen
6955:
6956: Interstitial screen to make sure the operator has selected the
6957: correct options before we start the validation phase.
6958:
6959: =cut
6960:
6961: sub scantron_warning_screen {
6962: my ($button_text,$symb)=@_;
6963: my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
6964: my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
6965: my $CODElist;
6966: if ($scantron_config{'CODElocation'} &&
6967: $scantron_config{'CODEstart'} &&
6968: $scantron_config{'CODElength'}) {
6969: $CODElist=$env{'form.scantron_CODElist'};
6970: if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
6971: $CODElist=
6972: '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
6973: $env{'form.scantron_CODElist'}.'</tt></td></tr>';
6974: }
6975: my $lastbubblepoints;
6976: if ($env{'form.scantron_lastbubblepoints'} ne '') {
6977: $lastbubblepoints =
6978: '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
6979: $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
6980: }
6981: return ('
6982: <p>
6983: <span class="LC_warning">
6984: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
6985: </p>
6986: <table>
6987: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
6988: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
6989: '.$CODElist.$lastbubblepoints.'
6990: </table>
6991: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'<br />
6992: '.&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>
6993:
6994: <br />
6995: ');
6996: }
6997:
6998: =pod
6999:
7000: =item scantron_do_warning
7001:
7002: Check if the operator has picked something for all required
7003: fields. Error out if something is missing.
7004:
7005: =cut
7006:
7007: sub scantron_do_warning {
7008: my ($r,$symb)=@_;
7009: if (!$symb) {return '';}
7010: my $default_form_data=&defaultFormData($symb);
7011: $r->print(&scantron_form_start().$default_form_data);
7012: if ( $env{'form.selectpage'} eq '' ||
7013: $env{'form.scantron_selectfile'} eq '' ||
7014: $env{'form.scantron_format'} eq '' ) {
7015: $r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
7016: if ( $env{'form.selectpage'} eq '') {
7017: $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
7018: }
7019: if ( $env{'form.scantron_selectfile'} eq '') {
7020: $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
7021: }
7022: if ( $env{'form.scantron_format'} eq '') {
7023: $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
7024: }
7025: } else {
7026: my $warning=&scantron_warning_screen('Grading: Validate Records',$symb);
7027: my $bubbledbyhand=&hand_bubble_option();
7028: $r->print('
7029: '.$warning.$bubbledbyhand.'
7030: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
7031: <input type="hidden" name="command" value="scantron_validate" />
7032: ');
7033: }
7034: $r->print("</form><br />");
7035: return '';
7036: }
7037:
7038: =pod
7039:
7040: =item scantron_form_start
7041:
7042: html hidden input for remembering all selected grading options
7043:
7044: =cut
7045:
7046: sub scantron_form_start {
7047: my ($max_bubble)=@_;
7048: my $result= <<SCANTRONFORM;
7049: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
7050: <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
7051: <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
7052: <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
7053: <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
7054: <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
7055: <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
7056: <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
7057: <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
7058: <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
7059: SCANTRONFORM
7060:
7061: my $line = 0;
7062: while (defined($env{"form.scantron.bubblelines.$line"})) {
7063: my $chunk =
7064: '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
7065: $chunk .=
7066: '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
7067: $chunk .=
7068: '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
7069: $chunk .=
7070: '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
7071: $chunk .=
7072: '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
7073: $result .= $chunk;
7074: $line++;
7075: }
7076: return $result;
7077: }
7078:
7079: =pod
7080:
7081: =item scantron_validate_file
7082:
7083: Dispatch routine for doing validation of a bubblesheet data file.
7084:
7085: Also processes any necessary information resets that need to
7086: occur before validation begins (ignore previous corrections,
7087: restarting the skipped records processing)
7088:
7089: =cut
7090:
7091: sub scantron_validate_file {
7092: my ($r,$symb) = @_;
7093: if (!$symb) {return '';}
7094: my $default_form_data=&defaultFormData($symb);
7095:
7096: # do the detection of only doing skipped records first before we delete
7097: # them when doing the corrections reset
7098: if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
7099: &reset_skipping_status();
7100: }
7101: if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
7102: &remember_current_skipped();
7103: $env{'form.scantron_options_redo'}='redo_skipped_ready';
7104: }
7105:
7106: if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
7107: &check_for_error($r,&scantron_remove_file('corrected'));
7108: &check_for_error($r,&scantron_remove_file('skipped'));
7109: &check_for_error($r,&scantron_remove_scan_data());
7110: $env{'form.scantron_options_ignore'}='done';
7111: }
7112:
7113: if ($env{'form.scantron_corrections'}) {
7114: &scantron_process_corrections($r);
7115: }
7116: $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
7117: #get the student pick code ready
7118: $r->print(&Apache::loncommon::studentbrowser_javascript());
7119: my $nav_error;
7120: my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
7121: my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
7122: if ($nav_error) {
7123: $r->print(&navmap_errormsg());
7124: return '';
7125: }
7126: my $result=&scantron_form_start($max_bubble).$default_form_data;
7127: if ($env{'form.scantron_lastbubblepoints'} ne '') {
7128: $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
7129: }
7130: $r->print($result);
7131:
7132: my @validate_phases=( 'sequence',
7133: 'ID',
7134: 'CODE',
7135: 'doublebubble',
7136: 'missingbubbles');
7137: if (!$env{'form.validatepass'}) {
7138: $env{'form.validatepass'} = 0;
7139: }
7140: my $currentphase=$env{'form.validatepass'};
7141:
7142:
7143: my $stop=0;
7144: while (!$stop && $currentphase < scalar(@validate_phases)) {
7145: $r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
7146: $r->rflush();
7147:
7148: my $which="scantron_validate_".$validate_phases[$currentphase];
7149: {
7150: no strict 'refs';
7151: ($stop,$currentphase)=&$which($r,$currentphase);
7152: }
7153: }
7154: if (!$stop) {
7155: my $warning=&scantron_warning_screen('Start Grading',$symb);
7156: $r->print(&mt('Validation process complete.').'<br />'.
7157: $warning.
7158: &mt('Perform verification for each student after storage of submissions?').
7159: ' <span class="LC_nobreak"><label>'.
7160: '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
7161: (' 'x3).'<label>'.
7162: '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
7163: '</label></span><br />'.
7164: &mt('Grading will take longer if you use verification.').'<br />'.
7165: &mt('Otherwise, Grade/Manage/Review Bubblesheets [_1] Review bubblesheet data can be used once grading is complete.','»').'<br /><br />'.
7166: '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
7167: '<input type="hidden" name="command" value="scantron_process" />'."\n");
7168: } else {
7169: $r->print('<input type="hidden" name="command" value="scantron_validate" />');
7170: $r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
7171: }
7172: if ($stop) {
7173: if ($validate_phases[$currentphase] eq 'sequence') {
7174: $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' → " />');
7175: $r->print(' '.&mt('this error').' <br />');
7176:
7177: $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>');
7178: } else {
7179: if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
7180: $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' →" onclick="javascript:verify_bubble_radio(this.form)" />');
7181: } else {
7182: $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' →" />');
7183: }
7184: $r->print(' '.&mt('using corrected info').' <br />');
7185: $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
7186: $r->print(" ".&mt("this scanline saving it for later."));
7187: }
7188: }
7189: $r->print(" </form><br />");
7190: return '';
7191: }
7192:
7193:
7194: =pod
7195:
7196: =item scantron_remove_file
7197:
7198: Removes the requested bubblesheet data file, makes sure that
7199: scantron_original_<filename> is never removed
7200:
7201:
7202: =cut
7203:
7204: sub scantron_remove_file {
7205: my ($which)=@_;
7206: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7207: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7208: my $file='scantron_';
7209: if ($which eq 'corrected' || $which eq 'skipped') {
7210: $file.=$which.'_';
7211: } else {
7212: return 'refused';
7213: }
7214: $file.=$env{'form.scantron_selectfile'};
7215: return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
7216: }
7217:
7218:
7219: =pod
7220:
7221: =item scantron_remove_scan_data
7222:
7223: Removes all scan_data correction for the requested bubblesheet
7224: data file. (In the case that both the are doing skipped records we need
7225: to remember the old skipped lines for the time being so that element
7226: persists for a while.)
7227:
7228: =cut
7229:
7230: sub scantron_remove_scan_data {
7231: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7232: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7233: my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
7234: my @todelete;
7235: my $filename=$env{'form.scantron_selectfile'};
7236: foreach my $key (@keys) {
7237: if ($key=~/^\Q$filename\E_/) {
7238: if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
7239: $key=~/remember_skipping/) {
7240: next;
7241: }
7242: push(@todelete,$key);
7243: }
7244: }
7245: my $result;
7246: if (@todelete) {
7247: $result = &Apache::lonnet::del('nohist_scantrondata',
7248: \@todelete,$cdom,$cname);
7249: } else {
7250: $result = 'ok';
7251: }
7252: return $result;
7253: }
7254:
7255:
7256: =pod
7257:
7258: =item scantron_getfile
7259:
7260: Fetches the requested bubblesheet data file (all 3 versions), and
7261: the scan_data hash
7262:
7263: Arguments:
7264: None
7265:
7266: Returns:
7267: 2 hash references
7268:
7269: - first one has
7270: orig -
7271: corrected -
7272: skipped - each of which points to an array ref of the specified
7273: file broken up into individual lines
7274: count - number of scanlines
7275:
7276: - second is the scan_data hash possible keys are
7277: ($number refers to scanline numbered $number and thus the key affects
7278: only that scanline
7279: $bubline refers to the specific bubble line element and the aspects
7280: refers to that specific bubble line element)
7281:
7282: $number.user - username:domain to use
7283: $number.CODE_ignore_dup
7284: - ignore the duplicate CODE error
7285: $number.useCODE
7286: - use the CODE in the scanline as is
7287: $number.no_bubble.$bubline
7288: - it is valid that there is no bubbled in bubble
7289: at $number $bubline
7290: remember_skipping
7291: - a frozen hash containing keys of $number and values
7292: of either
7293: 1 - we are on a 'do skipped records pass' and plan
7294: on processing this line
7295: 2 - we are on a 'do skipped records pass' and this
7296: scanline has been marked to skip yet again
7297:
7298: =cut
7299:
7300: sub scantron_getfile {
7301: #FIXME really would prefer a scantron directory
7302: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7303: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7304: my $lines;
7305: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
7306: 'scantron_orig_'.$env{'form.scantron_selectfile'});
7307: my %scanlines;
7308: $scanlines{'orig'}=[(split("\n",$lines,-1))];
7309: my $temp=$scanlines{'orig'};
7310: $scanlines{'count'}=$#$temp;
7311:
7312: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
7313: 'scantron_corrected_'.$env{'form.scantron_selectfile'});
7314: if ($lines eq '-1') {
7315: $scanlines{'corrected'}=[];
7316: } else {
7317: $scanlines{'corrected'}=[(split("\n",$lines,-1))];
7318: }
7319: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
7320: 'scantron_skipped_'.$env{'form.scantron_selectfile'});
7321: if ($lines eq '-1') {
7322: $scanlines{'skipped'}=[];
7323: } else {
7324: $scanlines{'skipped'}=[(split("\n",$lines,-1))];
7325: }
7326: my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
7327: if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
7328: my %scan_data = @tmp;
7329: return (\%scanlines,\%scan_data);
7330: }
7331:
7332: =pod
7333:
7334: =item lonnet_putfile
7335:
7336: Wrapper routine to call &Apache::lonnet::finishuserfileupload
7337:
7338: Arguments:
7339: $contents - data to store
7340: $filename - filename to store $contents into
7341:
7342: Returns:
7343: result value from &Apache::lonnet::finishuserfileupload
7344:
7345: =cut
7346:
7347: sub lonnet_putfile {
7348: my ($contents,$filename)=@_;
7349: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
7350: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7351: $env{'form.sillywaytopassafilearound'}=$contents;
7352: &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
7353:
7354: }
7355:
7356: =pod
7357:
7358: =item scantron_putfile
7359:
7360: Stores the current version of the bubblesheet data files, and the
7361: scan_data hash. (Does not modify the original version only the
7362: corrected and skipped versions.
7363:
7364: Arguments:
7365: $scanlines - hash ref that looks like the first return value from
7366: &scantron_getfile()
7367: $scan_data - hash ref that looks like the second return value from
7368: &scantron_getfile()
7369:
7370: =cut
7371:
7372: sub scantron_putfile {
7373: my ($scanlines,$scan_data) = @_;
7374: #FIXME really would prefer a scantron directory
7375: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7376: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7377: if ($scanlines) {
7378: my $prefix='scantron_';
7379: # no need to update orig, shouldn't change
7380: # &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
7381: # $env{'form.scantron_selectfile'});
7382: &lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
7383: $prefix.'corrected_'.
7384: $env{'form.scantron_selectfile'});
7385: &lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
7386: $prefix.'skipped_'.
7387: $env{'form.scantron_selectfile'});
7388: }
7389: &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
7390: }
7391:
7392: =pod
7393:
7394: =item scantron_get_line
7395:
7396: Returns the correct version of the scanline
7397:
7398: Arguments:
7399: $scanlines - hash ref that looks like the first return value from
7400: &scantron_getfile()
7401: $scan_data - hash ref that looks like the second return value from
7402: &scantron_getfile()
7403: $i - number of the requested line (starts at 0)
7404:
7405: Returns:
7406: A scanline, (either the original or the corrected one if it
7407: exists), or undef if the requested scanline should be
7408: skipped. (Either because it's an skipped scanline, or it's an
7409: unskipped scanline and we are not doing a 'do skipped scanlines'
7410: pass.
7411:
7412: =cut
7413:
7414: sub scantron_get_line {
7415: my ($scanlines,$scan_data,$i)=@_;
7416: if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
7417: #if ($scanlines->{'skipped'}[$i]) { return undef; }
7418: if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
7419: return $scanlines->{'orig'}[$i];
7420: }
7421:
7422: =pod
7423:
7424: =item scantron_todo_count
7425:
7426: Counts the number of scanlines that need processing.
7427:
7428: Arguments:
7429: $scanlines - hash ref that looks like the first return value from
7430: &scantron_getfile()
7431: $scan_data - hash ref that looks like the second return value from
7432: &scantron_getfile()
7433:
7434: Returns:
7435: $count - number of scanlines to process
7436:
7437: =cut
7438:
7439: sub get_todo_count {
7440: my ($scanlines,$scan_data)=@_;
7441: my $count=0;
7442: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7443: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7444: if ($line=~/^[\s\cz]*$/) { next; }
7445: $count++;
7446: }
7447: return $count;
7448: }
7449:
7450: =pod
7451:
7452: =item scantron_put_line
7453:
7454: Updates the 'corrected' or 'skipped' versions of the bubblesheet
7455: data file.
7456:
7457: Arguments:
7458: $scanlines - hash ref that looks like the first return value from
7459: &scantron_getfile()
7460: $scan_data - hash ref that looks like the second return value from
7461: &scantron_getfile()
7462: $i - line number to update
7463: $newline - contents of the updated scanline
7464: $skip - if true make the line for skipping and update the
7465: 'skipped' file
7466:
7467: =cut
7468:
7469: sub scantron_put_line {
7470: my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
7471: if ($skip) {
7472: $scanlines->{'skipped'}[$i]=$newline;
7473: &start_skipping($scan_data,$i);
7474: return;
7475: }
7476: $scanlines->{'corrected'}[$i]=$newline;
7477: }
7478:
7479: =pod
7480:
7481: =item scantron_clear_skip
7482:
7483: Remove a line from the 'skipped' file
7484:
7485: Arguments:
7486: $scanlines - hash ref that looks like the first return value from
7487: &scantron_getfile()
7488: $scan_data - hash ref that looks like the second return value from
7489: &scantron_getfile()
7490: $i - line number to update
7491:
7492: =cut
7493:
7494: sub scantron_clear_skip {
7495: my ($scanlines,$scan_data,$i)=@_;
7496: if (exists($scanlines->{'skipped'}[$i])) {
7497: undef($scanlines->{'skipped'}[$i]);
7498: return 1;
7499: }
7500: return 0;
7501: }
7502:
7503: =pod
7504:
7505: =item scantron_filter_not_exam
7506:
7507: Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
7508: filter out resources that are not marked as 'exam' mode
7509:
7510: =cut
7511:
7512: sub scantron_filter_not_exam {
7513: my ($curres)=@_;
7514:
7515: if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
7516: # if the user has asked to not have either hidden
7517: # or 'randomout' controlled resources to be graded
7518: # don't include them
7519: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
7520: && $curres->randomout) {
7521: return 0;
7522: }
7523: return 1;
7524: }
7525: return 0;
7526: }
7527:
7528: =pod
7529:
7530: =item scantron_validate_sequence
7531:
7532: Validates the selected sequence, checking for resource that are
7533: not set to exam mode.
7534:
7535: =cut
7536:
7537: sub scantron_validate_sequence {
7538: my ($r,$currentphase) = @_;
7539:
7540: my $navmap=Apache::lonnavmaps::navmap->new();
7541: unless (ref($navmap)) {
7542: $r->print(&navmap_errormsg());
7543: return (1,$currentphase);
7544: }
7545: my (undef,undef,$sequence)=
7546: &Apache::lonnet::decode_symb($env{'form.selectpage'});
7547:
7548: my $map=$navmap->getResourceByUrl($sequence);
7549:
7550: $r->print('<input type="hidden" name="validate_sequence_exam"
7551: value="ignore" />');
7552: if ($env{'form.validate_sequence_exam'} ne 'ignore') {
7553: my @resources=
7554: $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
7555: if (@resources) {
7556: $r->print(
7557: '<p class="LC_warning">'
7558: .&mt('Some resources in the sequence currently are not set to'
7559: .' bubblesheet exam mode. Grading these resources currently may not'
7560: .' work correctly.')
7561: .'</p>'
7562: );
7563: return (1,$currentphase);
7564: }
7565: }
7566:
7567: return (0,$currentphase+1);
7568: }
7569:
7570:
7571:
7572: sub scantron_validate_ID {
7573: my ($r,$currentphase) = @_;
7574:
7575: #get student info
7576: my $classlist=&Apache::loncoursedata::get_classlist();
7577: my %idmap=&username_to_idmap($classlist);
7578:
7579: #get scantron line setup
7580: my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
7581: my ($scanlines,$scan_data)=&scantron_getfile();
7582:
7583: my $nav_error;
7584: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
7585: if ($nav_error) {
7586: $r->print(&navmap_errormsg());
7587: return(1,$currentphase);
7588: }
7589:
7590: my %found=('ids'=>{},'usernames'=>{});
7591: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7592: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7593: if ($line=~/^[\s\cz]*$/) { next; }
7594: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7595: $scan_data);
7596: my $id=$$scan_record{'scantron.ID'};
7597: my $found;
7598: foreach my $checkid (keys(%idmap)) {
7599: if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
7600: }
7601: if ($found) {
7602: my $username=$idmap{$found};
7603: if ($found{'ids'}{$found}) {
7604: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
7605: $line,'duplicateID',$found);
7606: return(1,$currentphase);
7607: } elsif ($found{'usernames'}{$username}) {
7608: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
7609: $line,'duplicateID',$username);
7610: return(1,$currentphase);
7611: }
7612: #FIXME store away line we previously saw the ID on to use above
7613: $found{'ids'}{$found}++;
7614: $found{'usernames'}{$username}++;
7615: } else {
7616: if ($id =~ /^\s*$/) {
7617: my $username=&scan_data($scan_data,"$i.user");
7618: if (defined($username) && $found{'usernames'}{$username}) {
7619: &scantron_get_correction($r,$i,$scan_record,
7620: \%scantron_config,
7621: $line,'duplicateID',$username);
7622: return(1,$currentphase);
7623: } elsif (!defined($username)) {
7624: &scantron_get_correction($r,$i,$scan_record,
7625: \%scantron_config,
7626: $line,'incorrectID');
7627: return(1,$currentphase);
7628: }
7629: $found{'usernames'}{$username}++;
7630: } else {
7631: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
7632: $line,'incorrectID');
7633: return(1,$currentphase);
7634: }
7635: }
7636: }
7637:
7638: return (0,$currentphase+1);
7639: }
7640:
7641:
7642: sub scantron_get_correction {
7643: my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
7644: $randomorder,$randompick,$respnumlookup,$startline)=@_;
7645: #FIXME in the case of a duplicated ID the previous line, probably need
7646: #to show both the current line and the previous one and allow skipping
7647: #the previous one or the current one
7648:
7649: if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
7650: $r->print(
7651: '<p class="LC_warning">'
7652: .&mt('An error was detected ([_1]) for PaperID [_2]',
7653: "<b>$error</b>",
7654: '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
7655: ."</p> \n");
7656: } else {
7657: $r->print(
7658: '<p class="LC_warning">'
7659: .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
7660: "<b>$error</b>", $i, "<pre>$line</pre>")
7661: ."</p> \n");
7662: }
7663: my $message =
7664: '<p>'
7665: .&mt('The ID on the form is [_1]',
7666: "<tt>$$scan_record{'scantron.ID'}</tt>")
7667: .'<br />'
7668: .&mt('The name on the paper is [_1], [_2]',
7669: $$scan_record{'scantron.LastName'},
7670: $$scan_record{'scantron.FirstName'})
7671: .'</p>';
7672:
7673: $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
7674: $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
7675: # Array populated for doublebubble or
7676: my @lines_to_correct; # missingbubble errors to build javascript
7677: # to validate radio button checking
7678:
7679: if ($error =~ /ID$/) {
7680: if ($error eq 'incorrectID') {
7681: $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
7682: "</p>\n");
7683: } elsif ($error eq 'duplicateID') {
7684: $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
7685: }
7686: $r->print($message);
7687: $r->print("<p>".&mt("How should I handle this?")." <br /> \n");
7688: $r->print("\n<ul><li> ");
7689: #FIXME it would be nice if this sent back the user ID and
7690: #could do partial userID matches
7691: $r->print(&Apache::loncommon::selectstudent_link('scantronupload',
7692: 'scantron_username','scantron_domain'));
7693: $r->print(": <input type='text' name='scantron_username' value='' />");
7694: $r->print("\n:\n".
7695: &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
7696:
7697: $r->print('</li>');
7698: } elsif ($error =~ /CODE$/) {
7699: if ($error eq 'incorrectCODE') {
7700: $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
7701: } elsif ($error eq 'duplicateCODE') {
7702: $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");
7703: }
7704: $r->print("<p>".&mt('The CODE on the form is [_1]',
7705: "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
7706: ."</p>\n");
7707: $r->print($message);
7708: $r->print("<p>".&mt("How should I handle this?")."</p>\n");
7709: $r->print("\n<br /> ");
7710: my $i=0;
7711: if ($error eq 'incorrectCODE'
7712: && $$scan_record{'scantron.CODE'}=~/\S/ ) {
7713: my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
7714: if ($closest > 0) {
7715: foreach my $testcode (@{$closest}) {
7716: my $checked='';
7717: if (!$i) { $checked=' checked="checked"'; }
7718: $r->print("
7719: <label>
7720: <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
7721: ".&mt("Use the similar CODE [_1] instead.",
7722: "<b><tt>".$testcode."</tt></b>")."
7723: </label>
7724: <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
7725: $r->print("\n<br />");
7726: $i++;
7727: }
7728: }
7729: }
7730: if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
7731: my $checked; if (!$i) { $checked=' checked="checked"'; }
7732: $r->print("
7733: <label>
7734: <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
7735: ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
7736: "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
7737: </label>");
7738: $r->print("\n<br />");
7739: }
7740:
7741: $r->print(&Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT));
7742: function change_radio(field) {
7743: var slct=document.scantronupload.scantron_CODE_resolution;
7744: var i;
7745: for (i=0;i<slct.length;i++) {
7746: if (slct[i].value==field) { slct[i].checked=true; }
7747: }
7748: }
7749: ENDSCRIPT
7750: my $href="/adm/pickcode?".
7751: "form=".&escape("scantronupload").
7752: "&scantron_format=".&escape($env{'form.scantron_format'}).
7753: "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
7754: "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
7755: "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
7756: if ($env{'form.scantron_CODElist'} =~ /\S/) {
7757: $r->print("
7758: <label>
7759: <input type='radio' name='scantron_CODE_resolution' value='use_found' />
7760: ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
7761: "<a target='_blank' href='$href'>","</a>")."
7762: </label>
7763: ".&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\')" />'));
7764: $r->print("\n<br />");
7765: }
7766: $r->print("
7767: <label>
7768: <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
7769: ".&mt("Use [_1] as the CODE.",
7770: "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
7771: $r->print("\n<br /><br />");
7772: } elsif ($error eq 'doublebubble') {
7773: $r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
7774:
7775: # The form field scantron_questions is acutally a list of line numbers.
7776: # represented by this form so:
7777:
7778: my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
7779: $respnumlookup,$startline);
7780:
7781: $r->print('<input type="hidden" name="scantron_questions" value="'.
7782: $line_list.'" />');
7783: $r->print($message);
7784: $r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
7785: foreach my $question (@{$arg}) {
7786: my @linenums = &prompt_for_corrections($r,$question,$scan_config,
7787: $scan_record, $error,
7788: $randomorder,$randompick,
7789: $respnumlookup,$startline);
7790: push(@lines_to_correct,@linenums);
7791: }
7792: $r->print(&verify_bubbles_checked(@lines_to_correct));
7793: } elsif ($error eq 'missingbubble') {
7794: $r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
7795: $r->print($message);
7796: $r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
7797: $r->print(&mt("Some questions have no scanned bubbles.")."\n");
7798:
7799: # The form field scantron_questions is actually a list of line numbers not
7800: # a list of question numbers. Therefore:
7801: #
7802:
7803: my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
7804: $respnumlookup,$startline);
7805:
7806: $r->print('<input type="hidden" name="scantron_questions" value="'.
7807: $line_list.'" />');
7808: foreach my $question (@{$arg}) {
7809: my @linenums = &prompt_for_corrections($r,$question,$scan_config,
7810: $scan_record, $error,
7811: $randomorder,$randompick,
7812: $respnumlookup,$startline);
7813: push(@lines_to_correct,@linenums);
7814: }
7815: $r->print(&verify_bubbles_checked(@lines_to_correct));
7816: } else {
7817: $r->print("\n<ul>");
7818: }
7819: $r->print("\n</li></ul>");
7820: }
7821:
7822: sub verify_bubbles_checked {
7823: my (@ansnums) = @_;
7824: my $ansnumstr = join('","',@ansnums);
7825: my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
7826: &js_escape(\$warning);
7827: my $output = &Apache::lonhtmlcommon::scripttag(<<ENDSCRIPT);
7828: function verify_bubble_radio(form) {
7829: var ansnumArray = new Array ("$ansnumstr");
7830: var need_bubble_count = 0;
7831: for (var i=0; i<ansnumArray.length; i++) {
7832: if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
7833: var bubble_picked = 0;
7834: for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
7835: if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
7836: bubble_picked = 1;
7837: }
7838: }
7839: if (bubble_picked == 0) {
7840: need_bubble_count ++;
7841: }
7842: }
7843: }
7844: if (need_bubble_count) {
7845: alert("$warning");
7846: return;
7847: }
7848: form.submit();
7849: }
7850: ENDSCRIPT
7851: return $output;
7852: }
7853:
7854: =pod
7855:
7856: =item questions_to_line_list
7857:
7858: Converts a list of questions into a string of comma separated
7859: line numbers in the answer sheet used by the questions. This is
7860: used to fill in the scantron_questions form field.
7861:
7862: Arguments:
7863: questions - Reference to an array of questions.
7864: randomorder - True if randomorder in use.
7865: randompick - True if randompick in use.
7866: respnumlookup - Reference to HASH mapping question numbers in bubble lines
7867: for current line to question number used for same question
7868: in "Master Seqence" (as seen by Course Coordinator).
7869: startline - Reference to hash where key is question number (0 is first)
7870: and key is number of first bubble line for current student
7871: or code-based randompick and/or randomorder.
7872:
7873: =cut
7874:
7875:
7876: sub questions_to_line_list {
7877: my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
7878: my @lines;
7879:
7880: foreach my $item (@{$questions}) {
7881: my $question = $item;
7882: my ($first,$count,$last);
7883: if ($item =~ /^(\d+)\.(\d+)$/) {
7884: $question = $1;
7885: my $subquestion = $2;
7886: my $responsenum = $question-1;
7887: if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
7888: $responsenum = $respnumlookup->{$question-1};
7889: if (ref($startline) eq 'HASH') {
7890: $first = $startline->{$question-1} + 1;
7891: }
7892: } else {
7893: $first = $first_bubble_line{$responsenum} + 1;
7894: }
7895: my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
7896: my $subcount = 1;
7897: while ($subcount<$subquestion) {
7898: $first += $subans[$subcount-1];
7899: $subcount ++;
7900: }
7901: $count = $subans[$subquestion-1];
7902: } else {
7903: my $responsenum = $question-1;
7904: if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
7905: $responsenum = $respnumlookup->{$question-1};
7906: if (ref($startline) eq 'HASH') {
7907: $first = $startline->{$question-1} + 1;
7908: }
7909: } else {
7910: $first = $first_bubble_line{$responsenum} + 1;
7911: }
7912: $count = $bubble_lines_per_response{$responsenum};
7913: }
7914: $last = $first+$count-1;
7915: push(@lines, ($first..$last));
7916: }
7917: return join(',', @lines);
7918: }
7919:
7920: =pod
7921:
7922: =item prompt_for_corrections
7923:
7924: Prompts for a potentially multiline correction to the
7925: user's bubbling (factors out common code from scantron_get_correction
7926: for multi and missing bubble cases).
7927:
7928: Arguments:
7929: $r - Apache request object.
7930: $question - The question number to prompt for.
7931: $scan_config - The scantron file configuration hash.
7932: $scan_record - Reference to the hash that has the the parsed scanlines.
7933: $error - Type of error
7934: $randomorder - True if randomorder in use.
7935: $randompick - True if randompick in use.
7936: $respnumlookup - Reference to HASH mapping question numbers in bubble lines
7937: for current line to question number used for same question
7938: in "Master Seqence" (as seen by Course Coordinator).
7939: $startline - Reference to hash where key is question number (0 is first)
7940: and value is number of first bubble line for current student
7941: or code-based randompick and/or randomorder.
7942:
7943:
7944: Implicit inputs:
7945: %bubble_lines_per_response - Starting line numbers for each question.
7946: Numbered from 0 (but question numbers are from
7947: 1.
7948: %first_bubble_line - Starting bubble line for each question.
7949: %subdivided_bubble_lines - optionresponse, matchresponse and rankresponse
7950: type problems render as separate sub-questions,
7951: in exam mode. This hash contains a
7952: comma-separated list of the lines per
7953: sub-question.
7954: %responsetype_per_response - essayresponse, formularesponse,
7955: stringresponse, imageresponse, reactionresponse,
7956: and organicresponse type problem parts can have
7957: multiple lines per response if the weight
7958: assigned exceeds 10. In this case, only
7959: one bubble per line is permitted, but more
7960: than one line might contain bubbles, e.g.
7961: bubbling of: line 1 - J, line 2 - J,
7962: line 3 - B would assign 22 points.
7963:
7964: =cut
7965:
7966: sub prompt_for_corrections {
7967: my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
7968: $randompick, $respnumlookup, $startline) = @_;
7969: my ($current_line,$lines);
7970: my @linenums;
7971: my $questionnum = $question;
7972: my ($first,$responsenum);
7973: if ($question =~ /^(\d+)\.(\d+)$/) {
7974: $question = $1;
7975: my $subquestion = $2;
7976: if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
7977: $responsenum = $respnumlookup->{$question-1};
7978: if (ref($startline) eq 'HASH') {
7979: $first = $startline->{$question-1};
7980: }
7981: } else {
7982: $responsenum = $question-1;
7983: $first = $first_bubble_line{$responsenum};
7984: }
7985: $current_line = $first + 1 ;
7986: my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
7987: my $subcount = 1;
7988: while ($subcount<$subquestion) {
7989: $current_line += $subans[$subcount-1];
7990: $subcount ++;
7991: }
7992: $lines = $subans[$subquestion-1];
7993: } else {
7994: if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
7995: $responsenum = $respnumlookup->{$question-1};
7996: if (ref($startline) eq 'HASH') {
7997: $first = $startline->{$question-1};
7998: }
7999: } else {
8000: $responsenum = $question-1;
8001: $first = $first_bubble_line{$responsenum};
8002: }
8003: $current_line = $first + 1;
8004: $lines = $bubble_lines_per_response{$responsenum};
8005: }
8006: if ($lines > 1) {
8007: $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
8008: if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
8009: ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
8010: ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
8011: ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
8012: ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
8013: ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
8014: $r->print(
8015: &mt("Although this particular question type requires handgrading, the instructions for this question in the bubblesheet exam directed students to leave [quant,_1,line] blank on their bubblesheets.",$lines)
8016: .'<br /><br />'
8017: .&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.')
8018: .'<br />'
8019: .&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.')
8020: .'<br />'
8021: .&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.")
8022: .'<br /><br />'
8023: );
8024: } else {
8025: $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
8026: }
8027: }
8028: for (my $i =0; $i < $lines; $i++) {
8029: my $selected = $$scan_record{"scantron.$current_line.answer"};
8030: &scantron_bubble_selector($r,$scan_config,$current_line,
8031: $questionnum,$error,split('', $selected));
8032: push(@linenums,$current_line);
8033: $current_line++;
8034: }
8035: if ($lines > 1) {
8036: $r->print("<hr /><br />");
8037: }
8038: return @linenums;
8039: }
8040:
8041: =pod
8042:
8043: =item scantron_bubble_selector
8044:
8045: Generates the html radiobuttons to correct a single bubble line
8046: possibly showing the existing the selected bubbles if known
8047:
8048: Arguments:
8049: $r - Apache request object
8050: $scan_config - hash from &Apache::lonnet::get_scantron_config()
8051: $line - Number of the line being displayed.
8052: $questionnum - Question number (may include subquestion)
8053: $error - Type of error.
8054: @selected - Array of bubbles picked on this line.
8055:
8056: =cut
8057:
8058: sub scantron_bubble_selector {
8059: my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
8060: my $max=$$scan_config{'Qlength'};
8061:
8062: my $scmode=$$scan_config{'Qon'};
8063: if ($scmode eq 'number' || $scmode eq 'letter') {
8064: if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
8065: ($$scan_config{'BubblesPerRow'} > 0)) {
8066: $max=$$scan_config{'BubblesPerRow'};
8067: if (($scmode eq 'number') && ($max > 10)) {
8068: $max = 10;
8069: } elsif (($scmode eq 'letter') && $max > 26) {
8070: $max = 26;
8071: }
8072: } else {
8073: $max = 10;
8074: }
8075: }
8076:
8077: my @alphabet=('A'..'Z');
8078: $r->print(&Apache::loncommon::start_data_table().
8079: &Apache::loncommon::start_data_table_row());
8080: $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
8081: for (my $i=0;$i<$max+1;$i++) {
8082: $r->print("\n".'<td align="center">');
8083: if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
8084: else { $r->print(' '); }
8085: $r->print('</td>');
8086: }
8087: $r->print(&Apache::loncommon::end_data_table_row().
8088: &Apache::loncommon::start_data_table_row());
8089: for (my $i=0;$i<$max;$i++) {
8090: $r->print("\n".
8091: '<td><label><input type="radio" name="scantron_correct_Q_'.
8092: $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
8093: }
8094: my $nobub_checked = ' ';
8095: if ($error eq 'missingbubble') {
8096: $nobub_checked = ' checked = "checked" ';
8097: }
8098: $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
8099: $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
8100: '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
8101: $line.'" value="'.$questionnum.'" /></td>');
8102: $r->print(&Apache::loncommon::end_data_table_row().
8103: &Apache::loncommon::end_data_table());
8104: }
8105:
8106: =pod
8107:
8108: =item num_matches
8109:
8110: Counts the number of characters that are the same between the two arguments.
8111:
8112: Arguments:
8113: $orig - CODE from the scanline
8114: $code - CODE to match against
8115:
8116: Returns:
8117: $count - integer count of the number of same characters between the
8118: two arguments
8119:
8120: =cut
8121:
8122: sub num_matches {
8123: my ($orig,$code) = @_;
8124: my @code=split(//,$code);
8125: my @orig=split(//,$orig);
8126: my $same=0;
8127: for (my $i=0;$i<scalar(@code);$i++) {
8128: if ($code[$i] eq $orig[$i]) { $same++; }
8129: }
8130: return $same;
8131: }
8132:
8133: =pod
8134:
8135: =item scantron_get_closely_matching_CODEs
8136:
8137: Cycles through all CODEs and finds the set that has the greatest
8138: number of same characters as the provided CODE
8139:
8140: Arguments:
8141: $allcodes - hash ref returned by &get_codes()
8142: $CODE - CODE from the current scanline
8143:
8144: Returns:
8145: 2 element list
8146: - first elements is number of how closely matching the best fit is
8147: (5 means best set has 5 matching characters)
8148: - second element is an arrary ref containing the set of valid CODEs
8149: that best fit the passed in CODE
8150:
8151: =cut
8152:
8153: sub scantron_get_closely_matching_CODEs {
8154: my ($allcodes,$CODE)=@_;
8155: my @CODEs;
8156: foreach my $testcode (sort(keys(%{$allcodes}))) {
8157: push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
8158: }
8159:
8160: return ($#CODEs,$CODEs[-1]);
8161: }
8162:
8163: =pod
8164:
8165: =item get_codes
8166:
8167: Builds a hash which has keys of all of the valid CODEs from the selected
8168: set of remembered CODEs.
8169:
8170: Arguments:
8171: $old_name - name of the set of remembered CODEs
8172: $cdom - domain of the course
8173: $cnum - internal course name
8174:
8175: Returns:
8176: %allcodes - keys are the valid CODEs, values are all 1
8177:
8178: =cut
8179:
8180: sub get_codes {
8181: my ($old_name, $cdom, $cnum) = @_;
8182: if (!$old_name) {
8183: $old_name=$env{'form.scantron_CODElist'};
8184: }
8185: if (!$cdom) {
8186: $cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
8187: }
8188: if (!$cnum) {
8189: $cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
8190: }
8191: my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
8192: $cdom,$cnum);
8193: my %allcodes;
8194: if ($result{"type\0$old_name"} eq 'number') {
8195: %allcodes=map {($_,1)} split(',',$result{$old_name});
8196: } else {
8197: %allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
8198: }
8199: return %allcodes;
8200: }
8201:
8202: =pod
8203:
8204: =item scantron_validate_CODE
8205:
8206: Validates all scanlines in the selected file to not have any
8207: invalid or underspecified CODEs and that none of the codes are
8208: duplicated if this was requested.
8209:
8210: =cut
8211:
8212: sub scantron_validate_CODE {
8213: my ($r,$currentphase) = @_;
8214: my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
8215: if ($scantron_config{'CODElocation'} &&
8216: $scantron_config{'CODEstart'} &&
8217: $scantron_config{'CODElength'}) {
8218: if (!defined($env{'form.scantron_CODElist'})) {
8219: &FIXME_blow_up()
8220: }
8221: } else {
8222: return (0,$currentphase+1);
8223: }
8224:
8225: my %usedCODEs;
8226:
8227: my %allcodes=&get_codes();
8228:
8229: my $nav_error;
8230: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
8231: if ($nav_error) {
8232: $r->print(&navmap_errormsg());
8233: return(1,$currentphase);
8234: }
8235:
8236: my ($scanlines,$scan_data)=&scantron_getfile();
8237: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
8238: my $line=&scantron_get_line($scanlines,$scan_data,$i);
8239: if ($line=~/^[\s\cz]*$/) { next; }
8240: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
8241: $scan_data);
8242: my $CODE=$$scan_record{'scantron.CODE'};
8243: my $error=0;
8244: if (!&Apache::lonnet::validCODE($CODE)) {
8245: &scantron_get_correction($r,$i,$scan_record,
8246: \%scantron_config,
8247: $line,'incorrectCODE',\%allcodes);
8248: return(1,$currentphase);
8249: }
8250: if (%allcodes && !exists($allcodes{$CODE})
8251: && !$$scan_record{'scantron.useCODE'}) {
8252: &scantron_get_correction($r,$i,$scan_record,
8253: \%scantron_config,
8254: $line,'incorrectCODE',\%allcodes);
8255: return(1,$currentphase);
8256: }
8257: if (exists($usedCODEs{$CODE})
8258: && $env{'form.scantron_CODEunique'} eq 'yes'
8259: && !$$scan_record{'scantron.CODE_ignore_dup'}) {
8260: &scantron_get_correction($r,$i,$scan_record,
8261: \%scantron_config,
8262: $line,'duplicateCODE',$usedCODEs{$CODE});
8263: return(1,$currentphase);
8264: }
8265: push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
8266: }
8267: return (0,$currentphase+1);
8268: }
8269:
8270: =pod
8271:
8272: =item scantron_validate_doublebubble
8273:
8274: Validates all scanlines in the selected file to not have any
8275: bubble lines with multiple bubbles marked.
8276:
8277: =cut
8278:
8279: sub scantron_validate_doublebubble {
8280: my ($r,$currentphase) = @_;
8281: #get student info
8282: my $classlist=&Apache::loncoursedata::get_classlist();
8283: my %idmap=&username_to_idmap($classlist);
8284: my (undef,undef,$sequence)=
8285: &Apache::lonnet::decode_symb($env{'form.selectpage'});
8286:
8287: #get scantron line setup
8288: my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
8289: my ($scanlines,$scan_data)=&scantron_getfile();
8290:
8291: my $navmap = Apache::lonnavmaps::navmap->new();
8292: unless (ref($navmap)) {
8293: $r->print(&navmap_errormsg());
8294: return(1,$currentphase);
8295: }
8296: my $map=$navmap->getResourceByUrl($sequence);
8297: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
8298: my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
8299: %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
8300: my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
8301:
8302: my $nav_error;
8303: if (ref($map)) {
8304: $randomorder = $map->randomorder();
8305: $randompick = $map->randompick();
8306: if ($randomorder || $randompick) {
8307: $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
8308: if ($nav_error) {
8309: $r->print(&navmap_errormsg());
8310: return(1,$currentphase);
8311: }
8312: &graders_resources_pass(\@resources,\%grader_partids_by_symb,
8313: \%grader_randomlists_by_symb,$bubbles_per_row);
8314: }
8315: } else {
8316: $r->print(&navmap_errormsg());
8317: return(1,$currentphase);
8318: }
8319:
8320: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
8321: if ($nav_error) {
8322: $r->print(&navmap_errormsg());
8323: return(1,$currentphase);
8324: }
8325:
8326: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
8327: my $line=&scantron_get_line($scanlines,$scan_data,$i);
8328: if ($line=~/^[\s\cz]*$/) { next; }
8329: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
8330: $scan_data,undef,\%idmap,$randomorder,
8331: $randompick,$sequence,\@master_seq,
8332: \%symb_to_resource,\%grader_partids_by_symb,
8333: \%orderedforcode,\%respnumlookup,\%startline);
8334: if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
8335: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
8336: 'doublebubble',
8337: $$scan_record{'scantron.doubleerror'},
8338: $randomorder,$randompick,\%respnumlookup,\%startline);
8339: return (1,$currentphase);
8340: }
8341: return (0,$currentphase+1);
8342: }
8343:
8344:
8345: sub scantron_get_maxbubble {
8346: my ($nav_error,$scantron_config) = @_;
8347: if (defined($env{'form.scantron_maxbubble'}) &&
8348: $env{'form.scantron_maxbubble'}) {
8349: &restore_bubble_lines();
8350: return $env{'form.scantron_maxbubble'};
8351: }
8352:
8353: my (undef, undef, $sequence) =
8354: &Apache::lonnet::decode_symb($env{'form.selectpage'});
8355:
8356: my $navmap=Apache::lonnavmaps::navmap->new();
8357: unless (ref($navmap)) {
8358: if (ref($nav_error)) {
8359: $$nav_error = 1;
8360: }
8361: return;
8362: }
8363: my $map=$navmap->getResourceByUrl($sequence);
8364: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
8365: my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
8366:
8367: &Apache::lonxml::clear_problem_counter();
8368:
8369: my $uname = $env{'user.name'};
8370: my $udom = $env{'user.domain'};
8371: my $cid = $env{'request.course.id'};
8372: my $total_lines = 0;
8373: %bubble_lines_per_response = ();
8374: %first_bubble_line = ();
8375: %subdivided_bubble_lines = ();
8376: %responsetype_per_response = ();
8377: %masterseq_id_responsenum = ();
8378:
8379: my $response_number = 0;
8380: my $bubble_line = 0;
8381: foreach my $resource (@resources) {
8382: my $resid = $resource->id();
8383: my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
8384: $udom,undef,$bubbles_per_row);
8385: if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
8386: foreach my $part_id (@{$parts}) {
8387: my $lines;
8388:
8389: # TODO - make this a persistent hash not an array.
8390:
8391: # optionresponse, matchresponse and rankresponse type items
8392: # render as separate sub-questions in exam mode.
8393: if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
8394: ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
8395: ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
8396: my ($numbub,$numshown);
8397: if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
8398: if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
8399: $numbub = scalar(@{$analysis->{$part_id.'.options'}});
8400: }
8401: } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
8402: if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
8403: $numbub = scalar(@{$analysis->{$part_id.'.items'}});
8404: }
8405: } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
8406: if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
8407: $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
8408: }
8409: }
8410: if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
8411: $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
8412: }
8413: my $bubbles_per_row =
8414: &bubblesheet_bubbles_per_row($scantron_config);
8415: my $inner_bubble_lines = int($numbub/$bubbles_per_row);
8416: if (($numbub % $bubbles_per_row) != 0) {
8417: $inner_bubble_lines++;
8418: }
8419: for (my $i=0; $i<$numshown; $i++) {
8420: $subdivided_bubble_lines{$response_number} .=
8421: $inner_bubble_lines.',';
8422: }
8423: $subdivided_bubble_lines{$response_number} =~ s/,$//;
8424: $lines = $numshown * $inner_bubble_lines;
8425: } else {
8426: $lines = $analysis->{"$part_id.bubble_lines"};
8427: }
8428:
8429: $first_bubble_line{$response_number} = $bubble_line;
8430: $bubble_lines_per_response{$response_number} = $lines;
8431: $responsetype_per_response{$response_number} =
8432: $analysis->{$part_id.'.type'};
8433: $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;
8434: $response_number++;
8435:
8436: $bubble_line += $lines;
8437: $total_lines += $lines;
8438: }
8439: }
8440: }
8441: &Apache::lonnet::delenv('scantron.');
8442:
8443: &save_bubble_lines();
8444: $env{'form.scantron_maxbubble'} =
8445: $total_lines;
8446: return $env{'form.scantron_maxbubble'};
8447: }
8448:
8449: sub bubblesheet_bubbles_per_row {
8450: my ($scantron_config) = @_;
8451: my $bubbles_per_row;
8452: if (ref($scantron_config) eq 'HASH') {
8453: $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
8454: }
8455: if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
8456: $bubbles_per_row = 10;
8457: }
8458: return $bubbles_per_row;
8459: }
8460:
8461: sub scantron_validate_missingbubbles {
8462: my ($r,$currentphase) = @_;
8463: #get student info
8464: my $classlist=&Apache::loncoursedata::get_classlist();
8465: my %idmap=&username_to_idmap($classlist);
8466: my (undef,undef,$sequence)=
8467: &Apache::lonnet::decode_symb($env{'form.selectpage'});
8468:
8469: #get scantron line setup
8470: my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
8471: my ($scanlines,$scan_data)=&scantron_getfile();
8472:
8473: my $navmap = Apache::lonnavmaps::navmap->new();
8474: unless (ref($navmap)) {
8475: $r->print(&navmap_errormsg());
8476: return(1,$currentphase);
8477: }
8478:
8479: my $map=$navmap->getResourceByUrl($sequence);
8480: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
8481: my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
8482: %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
8483: my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
8484:
8485: my $nav_error;
8486: if (ref($map)) {
8487: $randomorder = $map->randomorder();
8488: $randompick = $map->randompick();
8489: if ($randomorder || $randompick) {
8490: $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
8491: if ($nav_error) {
8492: $r->print(&navmap_errormsg());
8493: return(1,$currentphase);
8494: }
8495: &graders_resources_pass(\@resources,\%grader_partids_by_symb,
8496: \%grader_randomlists_by_symb,$bubbles_per_row);
8497: }
8498: } else {
8499: $r->print(&navmap_errormsg());
8500: return(1,$currentphase);
8501: }
8502:
8503:
8504: my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
8505: if ($nav_error) {
8506: $r->print(&navmap_errormsg());
8507: return(1,$currentphase);
8508: }
8509:
8510: if (!$max_bubble) { $max_bubble=2**31; }
8511: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
8512: my $line=&scantron_get_line($scanlines,$scan_data,$i);
8513: if ($line=~/^[\s\cz]*$/) { next; }
8514: my $scan_record =
8515: &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
8516: $randomorder,$randompick,$sequence,\@master_seq,
8517: \%symb_to_resource,\%grader_partids_by_symb,
8518: \%orderedforcode,\%respnumlookup,\%startline);
8519: if (!defined($$scan_record{'scantron.missingerror'})) { next; }
8520: my @to_correct;
8521:
8522: # Probably here's where the error is...
8523:
8524: foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
8525: my $lastbubble;
8526: if ($missing =~ /^(\d+)\.(\d+)$/) {
8527: my $question = $1;
8528: my $subquestion = $2;
8529: my ($first,$responsenum);
8530: if ($randomorder || $randompick) {
8531: $responsenum = $respnumlookup{$question-1};
8532: $first = $startline{$question-1};
8533: } else {
8534: $responsenum = $question-1;
8535: $first = $first_bubble_line{$responsenum};
8536: }
8537: if (!defined($first)) { next; }
8538: my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
8539: my $subcount = 1;
8540: while ($subcount<$subquestion) {
8541: $first += $subans[$subcount-1];
8542: $subcount ++;
8543: }
8544: my $count = $subans[$subquestion-1];
8545: $lastbubble = $first + $count;
8546: } else {
8547: my ($first,$responsenum);
8548: if ($randomorder || $randompick) {
8549: $responsenum = $respnumlookup{$missing-1};
8550: $first = $startline{$missing-1};
8551: } else {
8552: $responsenum = $missing-1;
8553: $first = $first_bubble_line{$responsenum};
8554: }
8555: if (!defined($first)) { next; }
8556: $lastbubble = $first + $bubble_lines_per_response{$responsenum};
8557: }
8558: if ($lastbubble > $max_bubble) { next; }
8559: push(@to_correct,$missing);
8560: }
8561: if (@to_correct) {
8562: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
8563: $line,'missingbubble',\@to_correct,
8564: $randomorder,$randompick,\%respnumlookup,
8565: \%startline);
8566: return (1,$currentphase);
8567: }
8568:
8569: }
8570: return (0,$currentphase+1);
8571: }
8572:
8573: sub hand_bubble_option {
8574: my (undef, undef, $sequence) =
8575: &Apache::lonnet::decode_symb($env{'form.selectpage'});
8576: return if ($sequence eq '');
8577: my $navmap = Apache::lonnavmaps::navmap->new();
8578: unless (ref($navmap)) {
8579: return;
8580: }
8581: my $needs_hand_bubbles;
8582: my $map=$navmap->getResourceByUrl($sequence);
8583: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
8584: foreach my $res (@resources) {
8585: if (ref($res)) {
8586: if ($res->is_problem()) {
8587: my $partlist = $res->parts();
8588: foreach my $part (@{ $partlist }) {
8589: my @types = $res->responseType($part);
8590: if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
8591: $needs_hand_bubbles = 1;
8592: last;
8593: }
8594: }
8595: }
8596: }
8597: }
8598: if ($needs_hand_bubbles) {
8599: my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
8600: my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
8601: return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
8602: &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 />').
8603: '<label><input type="radio" name="scantron_lastbubblepoints" value="'.$bubbles_per_row.'" checked="checked" />'.&mt('[quant,_1,point]',$bubbles_per_row).'</label> '.&mt('or').' '.
8604: '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
8605: }
8606: return;
8607: }
8608:
8609: sub scantron_process_students {
8610: my ($r,$symb) = @_;
8611:
8612: my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
8613: if (!$symb) {
8614: return '';
8615: }
8616: my $default_form_data=&defaultFormData($symb);
8617:
8618: my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
8619: my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
8620: my ($scanlines,$scan_data)=&scantron_getfile();
8621: my $classlist=&Apache::loncoursedata::get_classlist();
8622: my %idmap=&username_to_idmap($classlist);
8623: my $navmap=Apache::lonnavmaps::navmap->new();
8624: unless (ref($navmap)) {
8625: $r->print(&navmap_errormsg());
8626: return '';
8627: }
8628: my $map=$navmap->getResourceByUrl($sequence);
8629: my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
8630: %grader_randomlists_by_symb);
8631: if (ref($map)) {
8632: $randomorder = $map->randomorder();
8633: $randompick = $map->randompick();
8634: } else {
8635: $r->print(&navmap_errormsg());
8636: return '';
8637: }
8638: my $nav_error;
8639: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
8640: if ($randomorder || $randompick) {
8641: $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
8642: if ($nav_error) {
8643: $r->print(&navmap_errormsg());
8644: return '';
8645: }
8646: }
8647: &graders_resources_pass(\@resources,\%grader_partids_by_symb,
8648: \%grader_randomlists_by_symb,$bubbles_per_row);
8649:
8650: my ($uname,$udom);
8651: my $result= <<SCANTRONFORM;
8652: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
8653: <input type="hidden" name="command" value="scantron_configphase" />
8654: $default_form_data
8655: SCANTRONFORM
8656: $r->print($result);
8657:
8658: my @delayqueue;
8659: my (%completedstudents,%scandata);
8660:
8661: my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
8662: my $count=&get_todo_count($scanlines,$scan_data);
8663: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
8664: &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
8665: $r->print('<br />');
8666: my $start=&Time::HiRes::time();
8667: my $i=-1;
8668: my $started;
8669:
8670: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
8671: if ($nav_error) {
8672: $r->print(&navmap_errormsg());
8673: return '';
8674: }
8675:
8676: # If an ssi failed in scantron_get_maxbubble, put an error message out to
8677: # the user and return.
8678:
8679: if ($ssi_error) {
8680: $r->print("</form>");
8681: &ssi_print_error($r);
8682: &Apache::lonnet::remove_lock($lock);
8683: return ''; # Dunno why the other returns return '' rather than just returning.
8684: }
8685:
8686: my %lettdig = &Apache::lonnet::letter_to_digits();
8687: my $numletts = scalar(keys(%lettdig));
8688: my %orderedforcode;
8689:
8690: while ($i<$scanlines->{'count'}) {
8691: ($uname,$udom)=('','');
8692: $i++;
8693: my $line=&scantron_get_line($scanlines,$scan_data,$i);
8694: if ($line=~/^[\s\cz]*$/) { next; }
8695: if ($started) {
8696: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
8697: }
8698: $started=1;
8699: my %respnumlookup = ();
8700: my %startline = ();
8701: my $total;
8702: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
8703: $scan_data,undef,\%idmap,$randomorder,
8704: $randompick,$sequence,\@master_seq,
8705: \%symb_to_resource,\%grader_partids_by_symb,
8706: \%orderedforcode,\%respnumlookup,\%startline,
8707: \$total);
8708: unless ($uname=&scantron_find_student($scan_record,$scan_data,
8709: \%idmap,$i)) {
8710: &scantron_add_delay(\@delayqueue,$line,
8711: 'Unable to find a student that matches',1);
8712: next;
8713: }
8714: if (exists $completedstudents{$uname}) {
8715: &scantron_add_delay(\@delayqueue,$line,
8716: 'Student '.$uname.' has multiple sheets',2);
8717: next;
8718: }
8719: my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
8720: my $user = $uname.':'.$usec;
8721: ($uname,$udom)=split(/:/,$uname);
8722:
8723: my $scancode;
8724: if ((exists($scan_record->{'scantron.CODE'})) &&
8725: (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
8726: $scancode = $scan_record->{'scantron.CODE'};
8727: } else {
8728: $scancode = '';
8729: }
8730:
8731: my @mapresources = @resources;
8732: if ($randomorder || $randompick) {
8733: @mapresources =
8734: &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
8735: \%orderedforcode);
8736: }
8737: my (%partids_by_symb,$res_error);
8738: foreach my $resource (@mapresources) {
8739: my $ressymb;
8740: if (ref($resource)) {
8741: $ressymb = $resource->symb();
8742: } else {
8743: $res_error = 1;
8744: last;
8745: }
8746: if ((exists($grader_randomlists_by_symb{$ressymb})) ||
8747: (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
8748: my $currcode;
8749: if (exists($grader_randomlists_by_symb{$ressymb})) {
8750: $currcode = $scancode;
8751: }
8752: my ($analysis,$parts) =
8753: &scantron_partids_tograde($resource,$env{'request.course.id'},
8754: $uname,$udom,undef,$bubbles_per_row,
8755: $currcode);
8756: $partids_by_symb{$ressymb} = $parts;
8757: } else {
8758: $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
8759: }
8760: }
8761:
8762: if ($res_error) {
8763: &scantron_add_delay(\@delayqueue,$line,
8764: 'An error occurred while grading student '.$uname,2);
8765: next;
8766: }
8767:
8768: &Apache::lonxml::clear_problem_counter();
8769: &Apache::lonnet::appenv($scan_record);
8770:
8771: if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
8772: &scantron_putfile($scanlines,$scan_data);
8773: }
8774:
8775: if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
8776: \@mapresources,\%partids_by_symb,
8777: $bubbles_per_row,$randomorder,$randompick,
8778: \%respnumlookup,\%startline)
8779: eq 'ssi_error') {
8780: $ssi_error = 0; # So end of handler error message does not trigger.
8781: $r->print("</form>");
8782: &ssi_print_error($r);
8783: &Apache::lonnet::remove_lock($lock);
8784: return ''; # Why return ''? Beats me.
8785: }
8786:
8787: if (($scancode) && ($randomorder || $randompick)) {
8788: my $parmresult =
8789: &Apache::lonparmset::storeparm_by_symb($symb,
8790: '0_examcode',2,$scancode,
8791: 'string_examcode',$uname,
8792: $udom);
8793: }
8794: $completedstudents{$uname}={'line'=>$line};
8795: if ($env{'form.verifyrecord'}) {
8796: my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
8797: if ($randompick) {
8798: if ($total) {
8799: $lastpos = $total*$scantron_config{'Qlength'};
8800: }
8801: }
8802:
8803: my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
8804: chomp($studentdata);
8805: $studentdata =~ s/\r$//;
8806: my $studentrecord = '';
8807: my $counter = -1;
8808: foreach my $resource (@mapresources) {
8809: my $ressymb = $resource->symb();
8810: ($counter,my $recording) =
8811: &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
8812: $counter,$studentdata,$partids_by_symb{$ressymb},
8813: \%scantron_config,\%lettdig,$numletts,$randomorder,
8814: $randompick,\%respnumlookup,\%startline);
8815: $studentrecord .= $recording;
8816: }
8817: if ($studentrecord ne $studentdata) {
8818: &Apache::lonxml::clear_problem_counter();
8819: if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
8820: \@mapresources,\%partids_by_symb,
8821: $bubbles_per_row,$randomorder,$randompick,
8822: \%respnumlookup,\%startline)
8823: eq 'ssi_error') {
8824: $ssi_error = 0; # So end of handler error message does not trigger.
8825: $r->print("</form>");
8826: &ssi_print_error($r);
8827: &Apache::lonnet::remove_lock($lock);
8828: delete($completedstudents{$uname});
8829: return '';
8830: }
8831: $counter = -1;
8832: $studentrecord = '';
8833: foreach my $resource (@mapresources) {
8834: my $ressymb = $resource->symb();
8835: ($counter,my $recording) =
8836: &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
8837: $counter,$studentdata,$partids_by_symb{$ressymb},
8838: \%scantron_config,\%lettdig,$numletts,
8839: $randomorder,$randompick,\%respnumlookup,
8840: \%startline);
8841: $studentrecord .= $recording;
8842: }
8843: if ($studentrecord ne $studentdata) {
8844: $r->print('<p><span class="LC_warning">');
8845: if ($scancode eq '') {
8846: $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
8847: $uname.':'.$udom,$scan_record->{'scantron.ID'}));
8848: } else {
8849: $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
8850: $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
8851: }
8852: $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
8853: &Apache::loncommon::start_data_table_header_row()."\n".
8854: '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
8855: &Apache::loncommon::end_data_table_header_row()."\n".
8856: &Apache::loncommon::start_data_table_row().
8857: '<td>'.&mt('Bubblesheet').'</td>'.
8858: '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
8859: &Apache::loncommon::end_data_table_row().
8860: &Apache::loncommon::start_data_table_row().
8861: '<td>'.&mt('Stored submissions').'</td>'.
8862: '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
8863: &Apache::loncommon::end_data_table_row().
8864: &Apache::loncommon::end_data_table().'</p>');
8865: } else {
8866: $r->print('<br /><span class="LC_warning">'.
8867: &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 />'.
8868: &mt("As a consequence, this user's submission history records two tries.").
8869: '</span><br />');
8870: }
8871: }
8872: }
8873: if (&Apache::loncommon::connection_aborted($r)) { last; }
8874: } continue {
8875: &Apache::lonxml::clear_problem_counter();
8876: &Apache::lonnet::delenv('scantron.');
8877: }
8878: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
8879: &Apache::lonnet::remove_lock($lock);
8880: # my $lasttime = &Time::HiRes::time()-$start;
8881: # $r->print("<p>took $lasttime</p>");
8882:
8883: $r->print("</form>");
8884: return '';
8885: }
8886:
8887: sub graders_resources_pass {
8888: my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
8889: $bubbles_per_row) = @_;
8890: if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) &&
8891: (ref($grader_randomlists_by_symb) eq 'HASH')) {
8892: foreach my $resource (@{$resources}) {
8893: my $ressymb = $resource->symb();
8894: my ($analysis,$parts) =
8895: &scantron_partids_tograde($resource,$env{'request.course.id'},
8896: $env{'user.name'},$env{'user.domain'},
8897: 1,$bubbles_per_row);
8898: $grader_partids_by_symb->{$ressymb} = $parts;
8899: if (ref($analysis) eq 'HASH') {
8900: if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
8901: $grader_randomlists_by_symb->{$ressymb} =
8902: $analysis->{'parts_withrandomlist'};
8903: }
8904: }
8905: }
8906: }
8907: return;
8908: }
8909:
8910: =pod
8911:
8912: =item users_order
8913:
8914: Returns array of resources in current map, ordered based on either CODE,
8915: if this is a CODEd exam, or based on student's identity if this is a
8916: "NAMEd" exam.
8917:
8918: Should be used when randomorder and/or randompick applied when the
8919: corresponding exam was printed, prior to students completing bubblesheets
8920: for the version of the exam the student received.
8921:
8922: =cut
8923:
8924: sub users_order {
8925: my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
8926: my @mapresources;
8927: unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
8928: return @mapresources;
8929: }
8930: if ($scancode) {
8931: if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
8932: @mapresources = @{$orderedforcode->{$scancode}};
8933: } else {
8934: $env{'form.CODE'} = $scancode;
8935: my $actual_seq =
8936: &Apache::lonprintout::master_seq_to_person_seq($mapurl,
8937: $master_seq,
8938: $user,$scancode,1);
8939: if (ref($actual_seq) eq 'ARRAY') {
8940: @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
8941: if (ref($orderedforcode) eq 'HASH') {
8942: if (@mapresources > 0) {
8943: $orderedforcode->{$scancode} = \@mapresources;
8944: }
8945: }
8946: }
8947: delete($env{'form.CODE'});
8948: }
8949: } else {
8950: my $actual_seq =
8951: &Apache::lonprintout::master_seq_to_person_seq($mapurl,
8952: $master_seq,
8953: $user,undef,1);
8954: if (ref($actual_seq) eq 'ARRAY') {
8955: @mapresources =
8956: map { $symb_to_resource->{$_}; } @{$actual_seq};
8957: }
8958: }
8959: return @mapresources;
8960: }
8961:
8962: sub grade_student_bubbles {
8963: my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
8964: $randomorder,$randompick,$respnumlookup,$startline) = @_;
8965: my $uselookup = 0;
8966: if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
8967: (ref($startline) eq 'HASH')) {
8968: $uselookup = 1;
8969: }
8970:
8971: if (ref($resources) eq 'ARRAY') {
8972: my $count = 0;
8973: foreach my $resource (@{$resources}) {
8974: my $ressymb = $resource->symb();
8975: my %form = ('submitted' => 'scantron',
8976: 'grade_target' => 'grade',
8977: 'grade_username' => $uname,
8978: 'grade_domain' => $udom,
8979: 'grade_courseid' => $env{'request.course.id'},
8980: 'grade_symb' => $ressymb,
8981: 'CODE' => $scancode
8982: );
8983: if ($bubbles_per_row ne '') {
8984: $form{'bubbles_per_row'} = $bubbles_per_row;
8985: }
8986: if ($env{'form.scantron_lastbubblepoints'} ne '') {
8987: $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
8988: }
8989: if (ref($parts) eq 'HASH') {
8990: if (ref($parts->{$ressymb}) eq 'ARRAY') {
8991: foreach my $part (@{$parts->{$ressymb}}) {
8992: if ($uselookup) {
8993: $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
8994: } else {
8995: $form{'scantron_questnum_start.'.$part} =
8996: 1+$env{'form.scantron.first_bubble_line.'.$count};
8997: }
8998: $count++;
8999: }
9000: }
9001: }
9002: my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
9003: return 'ssi_error' if ($ssi_error);
9004: last if (&Apache::loncommon::connection_aborted($r));
9005: }
9006: }
9007: return;
9008: }
9009:
9010: sub scantron_upload_scantron_data {
9011: my ($r,$symb) = @_;
9012: my $dom = $env{'request.role.domain'};
9013: my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($dom);
9014: my $domdesc = &Apache::lonnet::domain($dom,'description');
9015: $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
9016: my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
9017: 'domainid',
9018: 'coursename',$dom);
9019: my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
9020: (' 'x2).&mt('(shows course personnel)');
9021: my $default_form_data=&defaultFormData($symb);
9022: my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
9023: &js_escape(\$nofile_alert);
9024: 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.");
9025: &js_escape(\$nocourseid_alert);
9026: $r->print(&Apache::lonhtmlcommon::scripttag('
9027: function checkUpload(formname) {
9028: if (formname.upfile.value == "") {
9029: alert("'.$nofile_alert.'");
9030: return false;
9031: }
9032: if (formname.courseid.value == "") {
9033: alert("'.$nocourseid_alert.'");
9034: return false;
9035: }
9036: formname.submit();
9037: }
9038:
9039: function ToSyllabus() {
9040: var cdom = '."'$dom'".';
9041: var cnum = document.rules.courseid.value;
9042: if (cdom == "" || cdom == null) {
9043: return;
9044: }
9045: if (cnum == "" || cnum == null) {
9046: return;
9047: }
9048: syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
9049: "height=350,width=350,scrollbars=yes,menubar=no");
9050: return;
9051: }
9052:
9053: '.$formatjs.'
9054: '));
9055: $r->print('
9056: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
9057:
9058: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
9059: '.$default_form_data.
9060: &Apache::lonhtmlcommon::start_pick_box().
9061: &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
9062: '<input name="courseid" type="text" size="30" />'.$select_link.
9063: &Apache::lonhtmlcommon::row_closure().
9064: &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
9065: '<input name="coursename" type="text" size="30" />'.$syllabuslink.
9066: &Apache::lonhtmlcommon::row_closure().
9067: &Apache::lonhtmlcommon::row_title(&mt('Domain')).
9068: '<input name="domainid" type="hidden" />'.$domdesc.
9069: &Apache::lonhtmlcommon::row_closure());
9070: if ($formatoptions) {
9071: $r->print(&Apache::lonhtmlcommon::row_title($formattitle).$formatoptions.
9072: &Apache::lonhtmlcommon::row_closure());
9073: }
9074: $r->print(
9075: &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
9076: '<input type="file" name="upfile" size="50" />'.
9077: &Apache::lonhtmlcommon::row_closure(1).
9078: &Apache::lonhtmlcommon::end_pick_box().'<br />
9079:
9080: <input name="command" value="scantronupload_save" type="hidden" />
9081: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
9082: </form>
9083: ');
9084: return '';
9085: }
9086:
9087: sub scantron_upload_dataformat {
9088: my ($dom) = @_;
9089: my ($formatoptions,$formattitle,$formatjs);
9090: $formatjs = <<'END';
9091: function toggleScantab(form) {
9092: return;
9093: }
9094: END
9095: my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$dom);
9096: if (ref($domconfig{'scantron'}) eq 'HASH') {
9097: if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
9098: if (keys(%{$domconfig{'scantron'}{'config'}}) > 1) {
9099: if (($domconfig{'scantron'}{'config'}{'dat'}) &&
9100: (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH')) {
9101: if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
9102: if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
9103: my ($onclick,$formatextra,$singleline);
9104: my @lines = &Apache::lonnet::get_scantronformat_file();
9105: my $count = 0;
9106: foreach my $line (@lines) {
9107: next if ($line =~ /^#/);
9108: $singleline = $line;
9109: $count ++;
9110: }
9111: if ($count > 1) {
9112: $formatextra = '<div style="display:none" id="bubbletype">'.
9113: '<span class="LC_nobreak">'.
9114: &mt('Bubblesheet type:').' '.
9115: &scantron_scantab().'</span></div>';
9116: $onclick = ' onclick="toggleScantab(this.form);"';
9117: $formatjs = <<"END";
9118: function toggleScantab(form) {
9119: var divid = 'bubbletype';
9120: if (document.getElementById(divid)) {
9121: var radioname = 'fileformat';
9122: var num = form.elements[radioname].length;
9123: if (num) {
9124: for (var i=0; i<num; i++) {
9125: if (form.elements[radioname][i].checked) {
9126: var chosen = form.elements[radioname][i].value;
9127: if (chosen == 'dat') {
9128: document.getElementById(divid).style.display = 'none';
9129: } else if (chosen == 'csv') {
9130: document.getElementById(divid).style.display = 'block';
9131: }
9132: }
9133: }
9134: }
9135: }
9136: return;
9137: }
9138:
9139: END
9140: } elsif ($count == 1) {
9141: my $formatname = (split(/:/,$singleline,2))[0];
9142: $formatextra = '<input type="hidden" name="scantron_format" value="'.$formatname.'" />';
9143: }
9144: $formattitle = &mt('File format');
9145: $formatoptions = '<label><input name="fileformat" type="radio" value="dat" checked="checked"'.$onclick.' />'.
9146: &mt('Plain Text (no delimiters)').
9147: '</label>'.(' 'x2).
9148: '<label><input name="fileformat" type="radio" value="csv"'.$onclick.' />'.
9149: &mt('Comma separated values').'</label>'.$formatextra;
9150: }
9151: }
9152: }
9153: } elsif (keys(%{$domconfig{'scantron'}{'config'}}) == 1) {
9154: if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
9155: if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
9156: $formattitle = &mt('Bubblesheet type');
9157: $formatoptions = &scantron_scantab();
9158: }
9159: }
9160: }
9161: }
9162: }
9163: return ($formatoptions,$formattitle,$formatjs);
9164: }
9165:
9166: sub scantron_upload_scantron_data_save {
9167: my ($r,$symb) = @_;
9168: my $doanotherupload=
9169: '<br /><form action="/adm/grades" method="post">'."\n".
9170: '<input type="hidden" name="command" value="scantronupload" />'."\n".
9171: '<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
9172: '</form>'."\n";
9173: if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
9174: !&Apache::lonnet::allowed('usc',
9175: $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
9176: $r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
9177: unless ($symb) {
9178: $r->print($doanotherupload);
9179: }
9180: return '';
9181: }
9182: my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
9183: my $uploadedfile;
9184: $r->print('<p>'.&mt('Uploading file to [_1]','"'.$coursedata{'description'}.'"').'</p>');
9185: if (length($env{'form.upfile'}) < 2) {
9186: $r->print(
9187: &Apache::lonhtmlcommon::confirm_success(
9188: &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
9189: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
9190: } else {
9191: my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$env{'form.domainid'});
9192: my $parser;
9193: if (ref($domconfig{'scantron'}) eq 'HASH') {
9194: if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
9195: my $is_csv;
9196: my @possibles = keys(%{$domconfig{'scantron'}{'config'}});
9197: if (@possibles > 1) {
9198: if ($env{'form.fileformat'} eq 'csv') {
9199: if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
9200: if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
9201: if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
9202: $is_csv = 1;
9203: }
9204: }
9205: }
9206: }
9207: } elsif (@possibles == 1) {
9208: if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
9209: if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
9210: if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
9211: $is_csv = 1;
9212: }
9213: }
9214: }
9215: }
9216: if ($is_csv) {
9217: $parser = $domconfig{'scantron'}{'config'}{'csv'};
9218: }
9219: }
9220: }
9221: my $result =
9222: &Apache::lonnet::userfileupload('upfile','scantron','scantron',$parser,'','',
9223: $env{'form.courseid'},$env{'form.domainid'});
9224: if ($result =~ m{^/uploaded/}) {
9225: $r->print(
9226: &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
9227: &mt('Uploaded [_1] bytes of data into location: [_2]',
9228: (length($env{'form.upfile'})-1),
9229: '<span class="LC_filename">'.$result.'</span>'));
9230: ($uploadedfile) = ($result =~ m{/([^/]+)$});
9231: $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
9232: $env{'form.courseid'},$uploadedfile));
9233: } else {
9234: $r->print(
9235: &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
9236: &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
9237: $result,
9238: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
9239: }
9240: }
9241: if ($symb) {
9242: $r->print(&scantron_selectphase($r,$uploadedfile,$symb));
9243: } else {
9244: $r->print($doanotherupload);
9245: }
9246: return '';
9247: }
9248:
9249: sub validate_uploaded_scantron_file {
9250: my ($cdom,$cname,$fname) = @_;
9251: my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
9252: my @lines;
9253: if ($scanlines ne '-1') {
9254: @lines=split("\n",$scanlines,-1);
9255: }
9256: my $output;
9257: if (@lines) {
9258: my (%counts,$max_match_format);
9259: my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
9260: my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
9261: my %idmap = &username_to_idmap($classlist);
9262: foreach my $key (keys(%idmap)) {
9263: my $lckey = lc($key);
9264: $idmap{$lckey} = $idmap{$key};
9265: }
9266: my %unique_formats;
9267: my @formatlines = &Apache::lonnet::get_scantronformat_file();
9268: foreach my $line (@formatlines) {
9269: chomp($line);
9270: my @config = split(/:/,$line);
9271: my $idstart = $config[5];
9272: my $idlength = $config[6];
9273: if (($idstart ne '') && ($idlength > 0)) {
9274: if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
9275: push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]);
9276: } else {
9277: $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
9278: }
9279: }
9280: }
9281: foreach my $key (keys(%unique_formats)) {
9282: my ($idstart,$idlength) = split(':',$key);
9283: %{$counts{$key}} = (
9284: 'found' => 0,
9285: 'total' => 0,
9286: );
9287: foreach my $line (@lines) {
9288: next if ($line =~ /^#/);
9289: next if ($line =~ /^[\s\cz]*$/);
9290: my $id = substr($line,$idstart-1,$idlength);
9291: $id = lc($id);
9292: if (exists($idmap{$id})) {
9293: $counts{$key}{'found'} ++;
9294: }
9295: $counts{$key}{'total'} ++;
9296: }
9297: if ($counts{$key}{'total'}) {
9298: my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
9299: if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
9300: $max_match_pct = $percent_match;
9301: $max_match_format = $key;
9302: $found_match_count = $counts{$key}{'found'};
9303: $max_match_count = $counts{$key}{'total'};
9304: }
9305: }
9306: }
9307: if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
9308: my $format_descs;
9309: my $numwithformat = @{$unique_formats{$max_match_format}};
9310: for (my $i=0; $i<$numwithformat; $i++) {
9311: my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
9312: if ($i<$numwithformat-2) {
9313: $format_descs .= '"<i>'.$desc.'</i>", ';
9314: } elsif ($i==$numwithformat-2) {
9315: $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
9316: } elsif ($i==$numwithformat-1) {
9317: $format_descs .= '"<i>'.$desc.'</i>"';
9318: }
9319: }
9320: my $showpct = sprintf("%.0f",$max_match_pct).'%';
9321: $output .= '<br />';
9322: if ($found_match_count == $max_match_count) {
9323: # 100% matching entries
9324: $output .= &Apache::lonhtmlcommon::confirm_success(
9325: &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
9326: '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
9327: &mt('Comparison of student IDs in the uploaded file with'.
9328: ' the course roster found matches for [_1] of the [_2] entries'.
9329: ' in the file (for the format defined for [_3]).',
9330: '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
9331: } else {
9332: # Not all entries matching? -> Show warning and additional info
9333: $output .=
9334: &Apache::lonhtmlcommon::confirm_success(
9335: &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
9336: '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
9337: &mt('Not all entries could be matched!'),1).'<br />'.
9338: &mt('Comparison of student IDs in the uploaded file with'.
9339: ' the course roster found matches for [_1] of the [_2] entries'.
9340: ' in the file (for the format defined for [_3]).',
9341: '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
9342: '<p class="LC_info">'.
9343: &mt('A low percentage of matches results from one of the following:').
9344: '</p><ul>'.
9345: '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
9346: '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
9347: '<i>'.$cdom.'</i>').'</li>'.
9348: '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
9349: '<li>'.&mt('The course roster is not up to date.').'</li>'.
9350: '</ul>';
9351: }
9352: }
9353: } else {
9354: $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
9355: }
9356: return $output;
9357: }
9358:
9359: sub valid_file {
9360: my ($requested_file)=@_;
9361: foreach my $filename (sort(&scantron_filenames())) {
9362: if ($requested_file eq $filename) { return 1; }
9363: }
9364: return 0;
9365: }
9366:
9367: sub scantron_download_scantron_data {
9368: my ($r,$symb) = @_;
9369: my $default_form_data=&defaultFormData($symb);
9370: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
9371: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
9372: my $file=$env{'form.scantron_selectfile'};
9373: if (! &valid_file($file)) {
9374: $r->print('
9375: <p>
9376: '.&mt('The requested filename was invalid.').'
9377: </p>
9378: ');
9379: return;
9380: }
9381: my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
9382: my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
9383: my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
9384: &Apache::lonnet::allowuploaded('/adm/grades',$orig);
9385: &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
9386: &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
9387: $r->print('
9388: <p>
9389: '.&mt('[_1]Original[_2] file as uploaded by the bubblesheet scanning office.',
9390: '<a href="'.$orig.'">','</a>').'
9391: </p>
9392: <p>
9393: '.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
9394: '<a href="'.$corrected.'">','</a>').'
9395: </p>
9396: <p>
9397: '.&mt('[_1]Skipped[_2], a file of records that were skipped.',
9398: '<a href="'.$skipped.'">','</a>').'
9399: </p>
9400: ');
9401: return '';
9402: }
9403:
9404: sub checkscantron_results {
9405: my ($r,$symb) = @_;
9406: if (!$symb) {return '';}
9407: my $cid = $env{'request.course.id'};
9408: my %lettdig = &Apache::lonnet::letter_to_digits();
9409: my $numletts = scalar(keys(%lettdig));
9410: my $cnum = $env{'course.'.$cid.'.num'};
9411: my $cdom = $env{'course.'.$cid.'.domain'};
9412: my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
9413: my %record;
9414: my %scantron_config =
9415: &Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
9416: my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
9417: my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
9418: my $classlist=&Apache::loncoursedata::get_classlist();
9419: my %idmap=&Apache::grades::username_to_idmap($classlist);
9420: my $navmap=Apache::lonnavmaps::navmap->new();
9421: unless (ref($navmap)) {
9422: $r->print(&navmap_errormsg());
9423: return '';
9424: }
9425: my $map=$navmap->getResourceByUrl($sequence);
9426: my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
9427: %grader_randomlists_by_symb,%orderedforcode);
9428: if (ref($map)) {
9429: $randomorder=$map->randomorder();
9430: $randompick=$map->randompick();
9431: }
9432: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
9433: my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
9434: if ($nav_error) {
9435: $r->print(&navmap_errormsg());
9436: return '';
9437: }
9438: &graders_resources_pass(\@resources,\%grader_partids_by_symb,
9439: \%grader_randomlists_by_symb,$bubbles_per_row);
9440: my ($uname,$udom);
9441: my (%scandata,%lastname,%bylast);
9442: $r->print('
9443: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
9444:
9445: my @delayqueue;
9446: my %completedstudents;
9447:
9448: my $count=&get_todo_count($scanlines,$scan_data);
9449: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
9450: my ($username,$domain,$started);
9451: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
9452: if ($nav_error) {
9453: $r->print(&navmap_errormsg());
9454: return '';
9455: }
9456:
9457: &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,'Processing first student');
9458: my $start=&Time::HiRes::time();
9459: my $i=-1;
9460:
9461: while ($i<$scanlines->{'count'}) {
9462: ($username,$domain,$uname)=('','','');
9463: $i++;
9464: my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
9465: if ($line=~/^[\s\cz]*$/) { next; }
9466: if ($started) {
9467: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
9468: }
9469: $started=1;
9470: my $scan_record=
9471: &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
9472: $scan_data);
9473: unless ($uname=&scantron_find_student($scan_record,$scan_data,
9474: \%idmap,$i)) {
9475: &Apache::grades::scantron_add_delay(\@delayqueue,$line,
9476: 'Unable to find a student that matches',1);
9477: next;
9478: }
9479: if (exists $completedstudents{$uname}) {
9480: &Apache::grades::scantron_add_delay(\@delayqueue,$line,
9481: 'Student '.$uname.' has multiple sheets',2);
9482: next;
9483: }
9484: my $pid = $scan_record->{'scantron.ID'};
9485: $lastname{$pid} = $scan_record->{'scantron.LastName'};
9486: push(@{$bylast{$lastname{$pid}}},$pid);
9487: my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
9488: my $user = $uname.':'.$usec;
9489: ($username,$domain)=split(/:/,$uname);
9490:
9491: my $scancode;
9492: if ((exists($scan_record->{'scantron.CODE'})) &&
9493: (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
9494: $scancode = $scan_record->{'scantron.CODE'};
9495: } else {
9496: $scancode = '';
9497: }
9498:
9499: my @mapresources = @resources;
9500: my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
9501: my %respnumlookup=();
9502: my %startline=();
9503: if ($randomorder || $randompick) {
9504: @mapresources =
9505: &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
9506: \%orderedforcode);
9507: my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
9508: $scan_record,\@master_seq,\%symb_to_resource,
9509: \%grader_partids_by_symb,\%orderedforcode,
9510: \%respnumlookup,\%startline);
9511: if ($randompick && $total) {
9512: $lastpos = $total*$scantron_config{'Qlength'};
9513: }
9514: }
9515: $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
9516: chomp($scandata{$pid});
9517: $scandata{$pid} =~ s/\r$//;
9518:
9519: my $counter = -1;
9520: foreach my $resource (@mapresources) {
9521: my $parts;
9522: my $ressymb = $resource->symb();
9523: if ((exists($grader_randomlists_by_symb{$ressymb})) ||
9524: (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
9525: my $currcode;
9526: if (exists($grader_randomlists_by_symb{$ressymb})) {
9527: $currcode = $scancode;
9528: }
9529: (my $analysis,$parts) =
9530: &scantron_partids_tograde($resource,$env{'request.course.id'},
9531: $username,$domain,undef,
9532: $bubbles_per_row,$currcode);
9533: } else {
9534: $parts = $grader_partids_by_symb{$ressymb};
9535: }
9536: ($counter,my $recording) =
9537: &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
9538: $scandata{$pid},$parts,
9539: \%scantron_config,\%lettdig,$numletts,
9540: $randomorder,$randompick,
9541: \%respnumlookup,\%startline);
9542: $record{$pid} .= $recording;
9543: }
9544: }
9545: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
9546: $r->print('<br />');
9547: my ($okstudents,$badstudents,$numstudents,$passed,$failed);
9548: $passed = 0;
9549: $failed = 0;
9550: $numstudents = 0;
9551: foreach my $last (sort(keys(%bylast))) {
9552: if (ref($bylast{$last}) eq 'ARRAY') {
9553: foreach my $pid (sort(@{$bylast{$last}})) {
9554: my $showscandata = $scandata{$pid};
9555: my $showrecord = $record{$pid};
9556: $showscandata =~ s/\s/ /g;
9557: $showrecord =~ s/\s/ /g;
9558: if ($scandata{$pid} eq $record{$pid}) {
9559: my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
9560: $okstudents .= '<tr class="'.$css_class.'">'.
9561: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
9562: '</tr>'."\n".
9563: '<tr class="'.$css_class.'">'."\n".
9564: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
9565: $passed ++;
9566: } else {
9567: my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
9568: $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".
9569: '</tr>'."\n".
9570: '<tr class="'.$css_class.'">'."\n".
9571: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
9572: '</tr>'."\n";
9573: $failed ++;
9574: }
9575: $numstudents ++;
9576: }
9577: }
9578: }
9579: $r->print(
9580: '<p>'
9581: .&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).',
9582: '<b>',
9583: $numstudents,
9584: '</b>',
9585: $env{'form.scantron_maxbubble'})
9586: .'</p>'
9587: );
9588: $r->print('<p>'
9589: .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
9590: .'<br />'
9591: .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
9592: .'</p>'
9593: );
9594: if ($passed) {
9595: $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
9596: $r->print(&Apache::loncommon::start_data_table()."\n".
9597: &Apache::loncommon::start_data_table_header_row()."\n".
9598: '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
9599: &Apache::loncommon::end_data_table_header_row()."\n".
9600: $okstudents."\n".
9601: &Apache::loncommon::end_data_table().'<br />');
9602: }
9603: if ($failed) {
9604: $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
9605: $r->print(&Apache::loncommon::start_data_table()."\n".
9606: &Apache::loncommon::start_data_table_header_row()."\n".
9607: '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
9608: &Apache::loncommon::end_data_table_header_row()."\n".
9609: $badstudents."\n".
9610: &Apache::loncommon::end_data_table()).'<br />'.
9611: &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.');
9612: }
9613: $r->print('</form><br />');
9614: return;
9615: }
9616:
9617: sub verify_scantron_grading {
9618: my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
9619: $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
9620: $respnumlookup,$startline) = @_;
9621: my ($record,%expected,%startpos);
9622: return ($counter,$record) if (!ref($resource));
9623: return ($counter,$record) if (!$resource->is_problem());
9624: my $symb = $resource->symb();
9625: return ($counter,$record) if (ref($partids) ne 'ARRAY');
9626: foreach my $part_id (@{$partids}) {
9627: $counter ++;
9628: $expected{$part_id} = 0;
9629: my $respnum = $counter;
9630: if ($randomorder || $randompick) {
9631: $respnum = $respnumlookup->{$counter};
9632: $startpos{$part_id} = $startline->{$counter} + 1;
9633: } else {
9634: $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
9635: }
9636: if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
9637: my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
9638: foreach my $item (@sub_lines) {
9639: $expected{$part_id} += $item;
9640: }
9641: } else {
9642: $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
9643: }
9644: }
9645: if ($symb) {
9646: my %recorded;
9647: my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
9648: if ($returnhash{'version'}) {
9649: my %lasthash=();
9650: my $version;
9651: for ($version=1;$version<=$returnhash{'version'};$version++) {
9652: foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
9653: $lasthash{$key}=$returnhash{$version.':'.$key};
9654: }
9655: }
9656: foreach my $key (keys(%lasthash)) {
9657: if ($key =~ /\.scantron$/) {
9658: my $value = &unescape($lasthash{$key});
9659: my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
9660: if ($value eq '') {
9661: for (my $i=0; $i<$expected{$part_id}; $i++) {
9662: for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
9663: $recorded{$part_id} .= $scantron_config->{'Qoff'};
9664: }
9665: }
9666: } else {
9667: my @tocheck;
9668: my @items = split(//,$value);
9669: if (($scantron_config->{'Qon'} eq 'letter') ||
9670: ($scantron_config->{'Qon'} eq 'number')) {
9671: if (@items < $expected{$part_id}) {
9672: my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
9673: my @singles = split(//,$fragment);
9674: foreach my $pos (@singles) {
9675: if ($pos eq ' ') {
9676: push(@tocheck,$pos);
9677: } else {
9678: my $next = shift(@items);
9679: push(@tocheck,$next);
9680: }
9681: }
9682: } else {
9683: @tocheck = @items;
9684: }
9685: foreach my $letter (@tocheck) {
9686: if ($scantron_config->{'Qon'} eq 'letter') {
9687: if ($letter !~ /^[A-J]$/) {
9688: $letter = $scantron_config->{'Qoff'};
9689: }
9690: $recorded{$part_id} .= $letter;
9691: } elsif ($scantron_config->{'Qon'} eq 'number') {
9692: my $digit;
9693: if ($letter !~ /^[A-J]$/) {
9694: $digit = $scantron_config->{'Qoff'};
9695: } else {
9696: $digit = $lettdig->{$letter};
9697: }
9698: $recorded{$part_id} .= $digit;
9699: }
9700: }
9701: } else {
9702: @tocheck = @items;
9703: for (my $i=0; $i<$expected{$part_id}; $i++) {
9704: my $curr_sub = shift(@tocheck);
9705: my $digit;
9706: if ($curr_sub =~ /^[A-J]$/) {
9707: $digit = $lettdig->{$curr_sub}-1;
9708: }
9709: if ($curr_sub eq 'J') {
9710: $digit += scalar($numletts);
9711: }
9712: for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
9713: if ($j == $digit) {
9714: $recorded{$part_id} .= $scantron_config->{'Qon'};
9715: } else {
9716: $recorded{$part_id} .= $scantron_config->{'Qoff'};
9717: }
9718: }
9719: }
9720: }
9721: }
9722: }
9723: }
9724: }
9725: foreach my $part_id (@{$partids}) {
9726: if ($recorded{$part_id} eq '') {
9727: for (my $i=0; $i<$expected{$part_id}; $i++) {
9728: for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
9729: $recorded{$part_id} .= $scantron_config->{'Qoff'};
9730: }
9731: }
9732: }
9733: $record .= $recorded{$part_id};
9734: }
9735: }
9736: return ($counter,$record);
9737: }
9738:
9739: #-------- end of section for handling grading scantron forms -------
9740: #
9741: #-------------------------------------------------------------------
9742:
9743: #-------------------------- Menu interface -------------------------
9744: #
9745: #--- Href with symb and command ---
9746:
9747: sub href_symb_cmd {
9748: my ($symb,$cmd)=@_;
9749: return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&command='.$cmd;
9750: }
9751:
9752: sub grading_menu {
9753: my ($request,$symb) = @_;
9754: if (!$symb) {return '';}
9755:
9756: my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
9757: 'command'=>'individual');
9758:
9759: my $url1a = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
9760:
9761: $fields{'command'}='ungraded';
9762: my $url1b=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
9763:
9764: $fields{'command'}='table';
9765: my $url1c=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
9766:
9767: $fields{'command'}='all_for_one';
9768: my $url1d=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
9769:
9770: $fields{'command'}='downloadfilesselect';
9771: my $url1e=&Apache::lonhtmlcommon::build_url('grades/',\%fields);
9772:
9773: $fields{'command'} = 'csvform';
9774: my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
9775:
9776: $fields{'command'} = 'processclicker';
9777: my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
9778:
9779: $fields{'command'} = 'scantron_selectphase';
9780: my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
9781:
9782: $fields{'command'} = 'initialverifyreceipt';
9783: my $url5 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
9784:
9785: my @menu = ({ categorytitle=>'Hand Grading',
9786: items =>[
9787: { linktext => 'Select individual students to grade',
9788: url => $url1a,
9789: permission => 'F',
9790: icon => 'grade_students.png',
9791: linktitle => 'Grade current resource for a selection of students.'
9792: },
9793: { linktext => 'Grade ungraded submissions',
9794: url => $url1b,
9795: permission => 'F',
9796: icon => 'ungrade_sub.png',
9797: linktitle => 'Grade all submissions that have not been graded yet.'
9798: },
9799:
9800: { linktext => 'Grading table',
9801: url => $url1c,
9802: permission => 'F',
9803: icon => 'grading_table.png',
9804: linktitle => 'Grade current resource for all students.'
9805: },
9806: { linktext => 'Grade page/folder for one student',
9807: url => $url1d,
9808: permission => 'F',
9809: icon => 'grade_PageFolder.png',
9810: linktitle => 'Grade all resources in current page/sequence/folder for one student.'
9811: },
9812: { linktext => 'Download submissions',
9813: url => $url1e,
9814: permission => 'F',
9815: icon => 'download_sub.png',
9816: linktitle => 'Download all students submissions.'
9817: }]},
9818: { categorytitle=>'Automated Grading',
9819: items =>[
9820:
9821: { linktext => 'Upload Scores',
9822: url => $url2,
9823: permission => 'F',
9824: icon => 'uploadscores.png',
9825: linktitle => 'Specify a file containing the class scores for current resource.'
9826: },
9827: { linktext => 'Process Clicker',
9828: url => $url3,
9829: permission => 'F',
9830: icon => 'addClickerInfoFile.png',
9831: linktitle => 'Specify a file containing the clicker information for this resource.'
9832: },
9833: { linktext => 'Grade/Manage/Review Bubblesheets',
9834: url => $url4,
9835: permission => 'F',
9836: icon => 'bubblesheet.png',
9837: linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
9838: },
9839: { linktext => 'Verify Receipt Number',
9840: url => $url5,
9841: permission => 'F',
9842: icon => 'receipt_number.png',
9843: linktitle => 'Verify a system-generated receipt number for correct problem solution.'
9844: }
9845:
9846: ]
9847: });
9848:
9849: # Create the menu
9850: my $Str;
9851: $Str .= '<form method="post" action="" name="gradingMenu">';
9852: $Str .= '<input type="hidden" name="command" value="" />'.
9853: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
9854:
9855: $Str .= &Apache::lonhtmlcommon::generate_menu(@menu);
9856: return $Str;
9857: }
9858:
9859: sub ungraded {
9860: my ($request)=@_;
9861: &submit_options($request);
9862: }
9863:
9864: sub submit_options_sequence {
9865: my ($request,$symb) = @_;
9866: if (!$symb) {return '';}
9867: &commonJSfunctions($request);
9868: my $result;
9869:
9870: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
9871: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
9872: $result.=&selectfield(0).
9873: '<input type="hidden" name="command" value="pickStudentPage" />
9874: <div>
9875: <input type="submit" value="'.&mt('Next').' →" />
9876: </div>
9877: </div>
9878: </form>';
9879: return $result;
9880: }
9881:
9882: sub submit_options_table {
9883: my ($request,$symb) = @_;
9884: if (!$symb) {return '';}
9885: &commonJSfunctions($request);
9886: my $is_tool = ($symb =~ /ext\.tool$/);
9887: my $result;
9888:
9889: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
9890: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
9891:
9892: $result.=&selectfield(1,$is_tool).
9893: '<input type="hidden" name="command" value="viewgrades" />
9894: <div>
9895: <input type="submit" value="'.&mt('Next').' →" />
9896: </div>
9897: </div>
9898: </form>';
9899: return $result;
9900: }
9901:
9902: sub submit_options_download {
9903: my ($request,$symb) = @_;
9904: if (!$symb) {return '';}
9905:
9906: my $is_tool = ($symb =~ /ext\.tool$/);
9907: &commonJSfunctions($request);
9908:
9909: my $result='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
9910: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
9911: $result.='
9912: <h2>
9913: '.&mt('Select Students for whom to Download Submissions').'
9914: </h2>'.&selectfield(1,$is_tool).'
9915: <input type="hidden" name="command" value="downloadfileslink" />
9916: <input type="submit" value="'.&mt('Next').' →" />
9917: </div>
9918: </div>
9919:
9920:
9921: </form>';
9922: return $result;
9923: }
9924:
9925: #--- Displays the submissions first page -------
9926: sub submit_options {
9927: my ($request,$symb) = @_;
9928: if (!$symb) {return '';}
9929:
9930: my $is_tool = ($symb =~ /ext\.tool$/);
9931: &commonJSfunctions($request);
9932: my $result;
9933:
9934: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
9935: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n";
9936: $result.=&selectfield(1,$is_tool).'
9937: <input type="hidden" name="command" value="submission" />
9938: <input type="submit" value="'.&mt('Next').' →" />
9939: </div>
9940: </div>
9941: </form>';
9942: return $result;
9943: }
9944:
9945: sub selectfield {
9946: my ($full,$is_tool)=@_;
9947: my %options;
9948: if ($is_tool) {
9949: %options =
9950: (&transtatus_options,
9951: 'select_form_order' => ['yes','incorrect','all']);
9952: } else {
9953: %options =
9954: (&substatus_options,
9955: 'select_form_order' => ['yes','queued','graded','incorrect','all']);
9956: }
9957: my $result='<div class="LC_columnSection">
9958:
9959: <fieldset>
9960: <legend>
9961: '.&mt('Sections').'
9962: </legend>
9963: '.&Apache::lonstatistics::SectionSelect('section','multiple',5).'
9964: </fieldset>
9965:
9966: <fieldset>
9967: <legend>
9968: '.&mt('Groups').'
9969: </legend>
9970: '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
9971: </fieldset>
9972:
9973: <fieldset>
9974: <legend>
9975: '.&mt('Access Status').'
9976: </legend>
9977: '.&Apache::lonhtmlcommon::StatusOptions(undef,undef,5,undef,'mult').'
9978: </fieldset>';
9979: if ($full) {
9980: my $heading = &mt('Submission Status');
9981: if ($is_tool) {
9982: $heading = &mt('Transaction Status');
9983: }
9984: $result.='
9985: <fieldset>
9986: <legend>
9987: '.$heading.'
9988: </legend>'.
9989: &Apache::loncommon::select_form('all','submitonly',\%options).
9990: '</fieldset>';
9991: }
9992: $result.='</div><br />';
9993: return $result;
9994: }
9995:
9996: sub substatus_options {
9997: return &Apache::lonlocal::texthash(
9998: 'yes' => 'with submissions',
9999: 'queued' => 'in grading queue',
10000: 'graded' => 'with ungraded submissions',
10001: 'incorrect' => 'with incorrect submissions',
10002: 'all' => 'with any status',
10003: );
10004: }
10005:
10006: sub transtatus_options {
10007: return &Apache::lonlocal::texthash(
10008: 'yes' => 'with score transactions',
10009: 'incorrect' => 'with less than full credit',
10010: 'all' => 'with any status',
10011: );
10012: }
10013:
10014: sub reset_perm {
10015: undef(%perm);
10016: }
10017:
10018: sub init_perm {
10019: &reset_perm();
10020: foreach my $test_perm ('vgr','mgr','opa') {
10021:
10022: my $scope = $env{'request.course.id'};
10023: if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
10024:
10025: $scope .= '/'.$env{'request.course.sec'};
10026: if ( $perm{$test_perm}=
10027: &Apache::lonnet::allowed($test_perm,$scope)) {
10028: $perm{$test_perm.'_section'}=$env{'request.course.sec'};
10029: } else {
10030: delete($perm{$test_perm});
10031: }
10032: }
10033: }
10034: }
10035:
10036: sub init_old_essays {
10037: my ($symb,$apath,$adom,$aname) = @_;
10038: if ($symb ne '') {
10039: my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
10040: if (keys(%essays) > 0) {
10041: $old_essays{$symb} = \%essays;
10042: }
10043: }
10044: return;
10045: }
10046:
10047: sub reset_old_essays {
10048: undef(%old_essays);
10049: }
10050:
10051: sub gather_clicker_ids {
10052: my %clicker_ids;
10053:
10054: my $classlist = &Apache::loncoursedata::get_classlist();
10055:
10056: # Set up a couple variables.
10057: my $username_idx = &Apache::loncoursedata::CL_SNAME();
10058: my $domain_idx = &Apache::loncoursedata::CL_SDOM();
10059: my $status_idx = &Apache::loncoursedata::CL_STATUS();
10060:
10061: foreach my $student (keys(%$classlist)) {
10062: if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
10063: my $username = $classlist->{$student}->[$username_idx];
10064: my $domain = $classlist->{$student}->[$domain_idx];
10065: my $clickers =
10066: (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
10067: foreach my $id (split(/\,/,$clickers)) {
10068: $id=~s/^[\#0]+//;
10069: $id=~s/[\-\:]//g;
10070: if (exists($clicker_ids{$id})) {
10071: $clicker_ids{$id}.=','.$username.':'.$domain;
10072: } else {
10073: $clicker_ids{$id}=$username.':'.$domain;
10074: }
10075: }
10076: }
10077: return %clicker_ids;
10078: }
10079:
10080: sub gather_adv_clicker_ids {
10081: my %clicker_ids;
10082: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
10083: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
10084: my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
10085: foreach my $element (sort(keys(%coursepersonnel))) {
10086: foreach my $person (split(/\,/,$coursepersonnel{$element})) {
10087: my ($puname,$pudom)=split(/\:/,$person);
10088: my $clickers =
10089: (&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
10090: foreach my $id (split(/\,/,$clickers)) {
10091: $id=~s/^[\#0]+//;
10092: $id=~s/[\-\:]//g;
10093: if (exists($clicker_ids{$id})) {
10094: $clicker_ids{$id}.=','.$puname.':'.$pudom;
10095: } else {
10096: $clicker_ids{$id}=$puname.':'.$pudom;
10097: }
10098: }
10099: }
10100: }
10101: return %clicker_ids;
10102: }
10103:
10104: sub clicker_grading_parameters {
10105: return ('gradingmechanism' => 'scalar',
10106: 'upfiletype' => 'scalar',
10107: 'specificid' => 'scalar',
10108: 'pcorrect' => 'scalar',
10109: 'pincorrect' => 'scalar');
10110: }
10111:
10112: sub process_clicker {
10113: my ($r,$symb)=@_;
10114: if (!$symb) {return '';}
10115: my $result=&checkforfile_js();
10116: $result.=&Apache::loncommon::start_data_table().
10117: &Apache::loncommon::start_data_table_header_row().
10118: '<th>'.&mt('Specify a file containing clicker information and set grading options.').'</th>'.
10119: &Apache::loncommon::end_data_table_header_row().
10120: &Apache::loncommon::start_data_table_row()."<td>\n";
10121: # Attempt to restore parameters from last session, set defaults if not present
10122: my %Saveable_Parameters=&clicker_grading_parameters();
10123: &Apache::loncommon::restore_course_settings('grades_clicker',
10124: \%Saveable_Parameters);
10125: if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
10126: if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
10127: if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
10128: if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
10129:
10130: my %checked;
10131: foreach my $gradingmechanism ('attendance','personnel','specific','given') {
10132: if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
10133: $checked{$gradingmechanism}=' checked="checked"';
10134: }
10135: }
10136:
10137: my $upload=&mt("Evaluate File");
10138: my $type=&mt("Type");
10139: my $attendance=&mt("Award points just for participation");
10140: my $personnel=&mt("Correctness determined from response by course personnel");
10141: my $specific=&mt("Correctness determined from response with clicker ID(s)");
10142: my $given=&mt("Correctness determined from given list of answers").' '.
10143: '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
10144: my $pcorrect=&mt("Percentage points for correct solution");
10145: my $pincorrect=&mt("Percentage points for incorrect solution");
10146: my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
10147: {'iclicker' => 'i>clicker',
10148: 'interwrite' => 'interwrite PRS',
10149: 'turning' => 'Turning Technologies'});
10150: $symb = &Apache::lonenc::check_encrypt($symb);
10151: $result.= &Apache::lonhtmlcommon::scripttag(<<ENDUPFORM);
10152: function sanitycheck() {
10153: // Accept only integer percentages
10154: document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
10155: document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
10156: // Find out grading choice
10157: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10158: if (document.forms.gradesupload.gradingmechanism[i].checked) {
10159: gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
10160: }
10161: }
10162: // By default, new choice equals user selection
10163: newgradingchoice=gradingchoice;
10164: // Not good to give more points for false answers than correct ones
10165: if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
10166: document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
10167: }
10168: // If new choice is attendance only, and old choice was correctness-based, restore defaults
10169: if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
10170: document.forms.gradesupload.pcorrect.value=100;
10171: document.forms.gradesupload.pincorrect.value=100;
10172: }
10173: // If the values are different, cannot be attendance only
10174: if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
10175: (gradingchoice=='attendance')) {
10176: newgradingchoice='personnel';
10177: }
10178: // Change grading choice to new one
10179: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10180: if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
10181: document.forms.gradesupload.gradingmechanism[i].checked=true;
10182: } else {
10183: document.forms.gradesupload.gradingmechanism[i].checked=false;
10184: }
10185: }
10186: // Remember the old state
10187: document.forms.gradesupload.waschecked.value=newgradingchoice;
10188: }
10189: ENDUPFORM
10190: $result.= <<ENDUPFORM;
10191: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
10192: <input type="hidden" name="symb" value="$symb" />
10193: <input type="hidden" name="command" value="processclickerfile" />
10194: <input type="file" name="upfile" size="50" />
10195: <br /><label>$type: $selectform</label>
10196: ENDUPFORM
10197: $result.='</td>'.&Apache::loncommon::end_data_table_row().
10198: &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDGRADINGFORM);
10199: <label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
10200: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
10201: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
10202: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
10203: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
10204: <br />
10205: <input type="text" name="givenanswer" size="50" />
10206: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
10207: ENDGRADINGFORM
10208: $result.='</td>'.&Apache::loncommon::end_data_table_row().
10209: &Apache::loncommon::start_data_table_row().'<td>'.(<<ENDPERCFORM);
10210: <label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
10211: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
10212: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
10213: </form>
10214: ENDPERCFORM
10215: $result.='</td>'.
10216: &Apache::loncommon::end_data_table_row().
10217: &Apache::loncommon::end_data_table();
10218: return $result;
10219: }
10220:
10221: sub process_clicker_file {
10222: my ($r,$symb) = @_;
10223: if (!$symb) {return '';}
10224:
10225: my %Saveable_Parameters=&clicker_grading_parameters();
10226: &Apache::loncommon::store_course_settings('grades_clicker',
10227: \%Saveable_Parameters);
10228: my $result='';
10229: if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
10230: $result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
10231: return $result;
10232: }
10233: if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
10234: $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
10235: return $result;
10236: }
10237: my $foundgiven=0;
10238: if ($env{'form.gradingmechanism'} eq 'given') {
10239: $env{'form.givenanswer'}=~s/^\s*//gs;
10240: $env{'form.givenanswer'}=~s/\s*$//gs;
10241: $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
10242: $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
10243: my @answers=split(/\,/,$env{'form.givenanswer'});
10244: $foundgiven=$#answers+1;
10245: }
10246: my %clicker_ids=&gather_clicker_ids();
10247: my %correct_ids;
10248: if ($env{'form.gradingmechanism'} eq 'personnel') {
10249: %correct_ids=&gather_adv_clicker_ids();
10250: }
10251: if ($env{'form.gradingmechanism'} eq 'specific') {
10252: foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
10253: $correct_id=~tr/a-z/A-Z/;
10254: $correct_id=~s/\s//gs;
10255: $correct_id=~s/^[\#0]+//;
10256: $correct_id=~s/[\-\:]//g;
10257: if ($correct_id) {
10258: $correct_ids{$correct_id}='specified';
10259: }
10260: }
10261: }
10262: if ($env{'form.gradingmechanism'} eq 'attendance') {
10263: $result.=&mt('Score based on attendance only');
10264: } elsif ($env{'form.gradingmechanism'} eq 'given') {
10265: $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
10266: } else {
10267: my $number=0;
10268: $result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
10269: foreach my $id (sort(keys(%correct_ids))) {
10270: $result.='<br /><tt>'.$id.'</tt> - ';
10271: if ($correct_ids{$id} eq 'specified') {
10272: $result.=&mt('specified');
10273: } else {
10274: my ($uname,$udom)=split(/\:/,$correct_ids{$id});
10275: $result.=&Apache::loncommon::plainname($uname,$udom);
10276: }
10277: $number++;
10278: }
10279: $result.="</p>\n";
10280: if ($number==0) {
10281: $result .=
10282: &Apache::lonhtmlcommon::confirm_success(
10283: &mt('No IDs found to determine correct answer'),1);
10284: return $result;
10285: }
10286: }
10287: if (length($env{'form.upfile'}) < 2) {
10288: $result .=
10289: &Apache::lonhtmlcommon::confirm_success(
10290: &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
10291: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
10292: return $result;
10293: }
10294: my $mimetype;
10295: if ($env{'form.upfiletype'} eq 'iclicker') {
10296: my $mm = new File::MMagic;
10297: $mimetype = $mm->checktype_contents($env{'form.upfile'});
10298: unless (($mimetype eq 'text/plain') || ($mimetype eq 'text/html')) {
10299: $result.= '<p>'.
10300: &Apache::lonhtmlcommon::confirm_success(
10301: &mt('File format is neither csv (iclicker 6) nor xml (iclicker 7)'),1).'</p>';
10302: return $result;
10303: }
10304: } elsif (($env{'form.upfiletype'} ne 'interwrite') && ($env{'form.upfiletype'} ne 'turning')) {
10305: $result .= '<p>'.
10306: &Apache::lonhtmlcommon::confirm_success(
10307: &mt('Invalid clicker type: choose one of: i>clicker, Interwrite PRS, or Turning Technologies.'),1).'</p>';
10308: return $result;
10309: }
10310:
10311: # Were able to get all the info needed, now analyze the file
10312:
10313: $result.=&Apache::loncommon::studentbrowser_javascript();
10314: $symb = &Apache::lonenc::check_encrypt($symb);
10315: $result.=&Apache::loncommon::start_data_table().
10316: &Apache::loncommon::start_data_table_header_row().
10317: '<th>'.&mt('Evaluate clicker file').'</th>'.
10318: &Apache::loncommon::end_data_table_header_row().
10319: &Apache::loncommon::start_data_table_row().(<<ENDHEADER);
10320: <td>
10321: <form method="post" action="/adm/grades" name="clickeranalysis">
10322: <input type="hidden" name="symb" value="$symb" />
10323: <input type="hidden" name="command" value="assignclickergrades" />
10324: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
10325: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
10326: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
10327: ENDHEADER
10328: if ($env{'form.gradingmechanism'} eq 'given') {
10329: $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
10330: }
10331: my %responses;
10332: my @questiontitles;
10333: my $errormsg='';
10334: my $number=0;
10335: if ($env{'form.upfiletype'} eq 'iclicker') {
10336: if ($mimetype eq 'text/plain') {
10337: ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
10338: } elsif ($mimetype eq 'text/html') {
10339: ($errormsg,$number)=&iclickerxml_eval(\@questiontitles,\%responses);
10340: }
10341: } elsif ($env{'form.upfiletype'} eq 'interwrite') {
10342: ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
10343: } elsif ($env{'form.upfiletype'} eq 'turning') {
10344: ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
10345: }
10346: $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
10347: '<input type="hidden" name="number" value="'.$number.'" />'.
10348: &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
10349: $env{'form.pcorrect'},$env{'form.pincorrect'}).
10350: '<br />';
10351: if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
10352: $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
10353: return $result;
10354: }
10355: # Remember Question Titles
10356: # FIXME: Possibly need delimiter other than ":"
10357: for (my $i=0;$i<$number;$i++) {
10358: $result.='<input type="hidden" name="question:'.$i.'" value="'.
10359: &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
10360: }
10361: my $correct_count=0;
10362: my $student_count=0;
10363: my $unknown_count=0;
10364: # Match answers with usernames
10365: # FIXME: Possibly need delimiter other than ":"
10366: foreach my $id (keys(%responses)) {
10367: if ($correct_ids{$id}) {
10368: $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
10369: $correct_count++;
10370: } elsif ($clicker_ids{$id}) {
10371: if ($clicker_ids{$id}=~/\,/) {
10372: # More than one user with the same clicker!
10373: $result.="</td>".&Apache::loncommon::end_data_table_row().
10374: &Apache::loncommon::start_data_table_row()."<td>".
10375: &mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
10376: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10377: "<select name='multi".$id."'>";
10378: foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
10379: $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
10380: }
10381: $result.='</select>';
10382: $unknown_count++;
10383: } else {
10384: # Good: found one and only one user with the right clicker
10385: $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
10386: $student_count++;
10387: }
10388: } else {
10389: $result.="</td>".&Apache::loncommon::end_data_table_row().
10390: &Apache::loncommon::start_data_table_row()."<td>".
10391: &mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
10392: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10393: "\n".&mt("Username").": <input type='text' name='uname".$id."' /> ".
10394: "\n".&mt("Domain").": ".
10395: &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).' '.
10396: &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,'',$id);
10397: $unknown_count++;
10398: }
10399: }
10400: $result.='<hr />'.
10401: &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
10402: if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
10403: if ($correct_count==0) {
10404: $errormsg.="Found no correct answers for grading!";
10405: } elsif ($correct_count>1) {
10406: $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
10407: }
10408: }
10409: if ($number<1) {
10410: $errormsg.="Found no questions.";
10411: }
10412: if ($errormsg) {
10413: $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
10414: } else {
10415: $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
10416: }
10417: $result.='</form></td>'.
10418: &Apache::loncommon::end_data_table_row().
10419: &Apache::loncommon::end_data_table();
10420: return $result;
10421: }
10422:
10423: sub iclicker_eval {
10424: my ($questiontitles,$responses)=@_;
10425: my $number=0;
10426: my $errormsg='';
10427: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10428: my %components=&Apache::loncommon::record_sep($line);
10429: my @entries=map {$components{$_}} (sort(keys(%components)));
10430: if ($entries[0] eq 'Question') {
10431: for (my $i=3;$i<$#entries;$i+=6) {
10432: $$questiontitles[$number]=$entries[$i];
10433: $number++;
10434: }
10435: }
10436: if ($entries[0]=~/^\#/) {
10437: my $id=$entries[0];
10438: my @idresponses;
10439: $id=~s/^[\#0]+//;
10440: for (my $i=0;$i<$number;$i++) {
10441: my $idx=3+$i*6;
10442: $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
10443: push(@idresponses,$entries[$idx]);
10444: }
10445: $$responses{$id}=join(',',@idresponses);
10446: }
10447: }
10448: return ($errormsg,$number);
10449: }
10450:
10451: sub iclickerxml_eval {
10452: my ($questiontitles,$responses)=@_;
10453: my $number=0;
10454: my $errormsg='';
10455: my @state;
10456: my %respbyid;
10457: my $p = HTML::Parser->new
10458: (
10459: xml_mode => 1,
10460: start_h =>
10461: [sub {
10462: my ($tagname,$attr) = @_;
10463: push(@state,$tagname);
10464: if ("@state" eq "ssn p") {
10465: my $title = $attr->{qn};
10466: $title =~ s/(^\s+|\s+$)//g;
10467: $questiontitles->[$number]=$title;
10468: } elsif ("@state" eq "ssn p v") {
10469: my $id = $attr->{id};
10470: my $entry = $attr->{ans};
10471: $id=~s/^[\#0]+//;
10472: $entry =~s/[^a-zA-Z0-9\.\*\-\+]+//g;
10473: $respbyid{$id}[$number] = $entry;
10474: }
10475: }, "tagname, attr"],
10476: end_h =>
10477: [sub {
10478: my ($tagname) = @_;
10479: if ("@state" eq "ssn p") {
10480: $number++;
10481: }
10482: pop(@state);
10483: }, "tagname"],
10484: );
10485:
10486: $p->parse($env{'form.upfile'});
10487: $p->eof;
10488: foreach my $id (keys(%respbyid)) {
10489: $responses->{$id}=join(',',@{$respbyid{$id}});
10490: }
10491: return ($errormsg,$number);
10492: }
10493:
10494: sub interwrite_eval {
10495: my ($questiontitles,$responses)=@_;
10496: my $number=0;
10497: my $errormsg='';
10498: my $skipline=1;
10499: my $questionnumber=0;
10500: my %idresponses=();
10501: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10502: my %components=&Apache::loncommon::record_sep($line);
10503: my @entries=map {$components{$_}} (sort(keys(%components)));
10504: if ($entries[1] eq 'Time') { $skipline=0; next; }
10505: if ($entries[1] eq 'Response') { $skipline=1; }
10506: next if $skipline;
10507: if ($entries[0]!=$questionnumber) {
10508: $questionnumber=$entries[0];
10509: $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
10510: $number++;
10511: }
10512: my $id=$entries[4];
10513: $id=~s/^[\#0]+//;
10514: $id=~s/^v\d*\://i;
10515: $id=~s/[\-\:]//g;
10516: $idresponses{$id}[$number]=$entries[6];
10517: }
10518: foreach my $id (keys(%idresponses)) {
10519: $$responses{$id}=join(',',@{$idresponses{$id}});
10520: $$responses{$id}=~s/^\s*\,//;
10521: }
10522: return ($errormsg,$number);
10523: }
10524:
10525: sub turning_eval {
10526: my ($questiontitles,$responses)=@_;
10527: my $number=0;
10528: my $errormsg='';
10529: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10530: my %components=&Apache::loncommon::record_sep($line);
10531: my @entries=map {$components{$_}} (sort(keys(%components)));
10532: if ($#entries>$number) { $number=$#entries; }
10533: my $id=$entries[0];
10534: my @idresponses;
10535: $id=~s/^[\#0]+//;
10536: unless ($id) { next; }
10537: for (my $idx=1;$idx<=$#entries;$idx++) {
10538: $entries[$idx]=~s/\,/\;/g;
10539: $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
10540: push(@idresponses,$entries[$idx]);
10541: }
10542: $$responses{$id}=join(',',@idresponses);
10543: }
10544: for (my $i=1; $i<=$number; $i++) {
10545: $$questiontitles[$i]=&mt('Question [_1]',$i);
10546: }
10547: return ($errormsg,$number);
10548: }
10549:
10550:
10551: sub assign_clicker_grades {
10552: my ($r,$symb) = @_;
10553: if (!$symb) {return '';}
10554: # See which part we are saving to
10555: my $res_error;
10556: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
10557: if ($res_error) {
10558: return &navmap_errormsg();
10559: }
10560: # FIXME: This should probably look for the first handgradeable part
10561: my $part=$$partlist[0];
10562: # Start screen output
10563: my $result = &Apache::loncommon::start_data_table().
10564: &Apache::loncommon::start_data_table_header_row().
10565: '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
10566: &Apache::loncommon::end_data_table_header_row().
10567: &Apache::loncommon::start_data_table_row().'<td>';
10568: # Get correct result
10569: # FIXME: Possibly need delimiter other than ":"
10570: my @correct=();
10571: my $gradingmechanism=$env{'form.gradingmechanism'};
10572: my $number=$env{'form.number'};
10573: if ($gradingmechanism ne 'attendance') {
10574: foreach my $key (keys(%env)) {
10575: if ($key=~/^form\.correct\:/) {
10576: my @input=split(/\,/,$env{$key});
10577: for (my $i=0;$i<=$#input;$i++) {
10578: if (($correct[$i]) && ($input[$i]) &&
10579: ($correct[$i] ne $input[$i])) {
10580: $result.='<br /><span class="LC_warning">'.
10581: &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
10582: $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
10583: } elsif (($input[$i]) || ($input[$i] eq '0')) {
10584: $correct[$i]=$input[$i];
10585: }
10586: }
10587: }
10588: }
10589: for (my $i=0;$i<$number;$i++) {
10590: if ((!$correct[$i]) && ($correct[$i] ne '0')) {
10591: $result.='<br /><span class="LC_error">'.
10592: &mt('No correct result given for question "[_1]"!',
10593: $env{'form.question:'.$i}).'</span>';
10594: }
10595: }
10596: $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
10597: }
10598: # Start grading
10599: my $pcorrect=$env{'form.pcorrect'};
10600: my $pincorrect=$env{'form.pincorrect'};
10601: my $storecount=0;
10602: my %users=();
10603: foreach my $key (keys(%env)) {
10604: my $user='';
10605: if ($key=~/^form\.student\:(.*)$/) {
10606: $user=$1;
10607: }
10608: if ($key=~/^form\.unknown\:(.*)$/) {
10609: my $id=$1;
10610: if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
10611: $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
10612: } elsif ($env{'form.multi'.$id}) {
10613: $user=$env{'form.multi'.$id};
10614: }
10615: }
10616: if ($user) {
10617: if ($users{$user}) {
10618: $result.='<br /><span class="LC_warning">'.
10619: &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
10620: '</span><br />';
10621: }
10622: $users{$user}=1;
10623: my @answer=split(/\,/,$env{$key});
10624: my $sum=0;
10625: my $realnumber=$number;
10626: for (my $i=0;$i<$number;$i++) {
10627: if ($correct[$i] eq '-') {
10628: $realnumber--;
10629: } elsif (($answer[$i]) || ($answer[$i]=~/^[0\.]+$/)) {
10630: if ($gradingmechanism eq 'attendance') {
10631: $sum+=$pcorrect;
10632: } elsif ($correct[$i] eq '*') {
10633: $sum+=$pcorrect;
10634: } else {
10635: # We actually grade if correct or not
10636: my $increment=$pincorrect;
10637: # Special case: numerical answer "0"
10638: if ($correct[$i] eq '0') {
10639: if ($answer[$i]=~/^[0\.]+$/) {
10640: $increment=$pcorrect;
10641: }
10642: # General numerical answer, both evaluate to something non-zero
10643: } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
10644: if (1.0*$correct[$i]==1.0*$answer[$i]) {
10645: $increment=$pcorrect;
10646: }
10647: # Must be just alphanumeric
10648: } elsif ($answer[$i] eq $correct[$i]) {
10649: $increment=$pcorrect;
10650: }
10651: $sum+=$increment;
10652: }
10653: }
10654: }
10655: my $ave=$sum/(100*$realnumber);
10656: # Store
10657: my ($username,$domain)=split(/\:/,$user);
10658: my %grades=();
10659: $grades{"resource.$part.solved"}='correct_by_override';
10660: $grades{"resource.$part.awarded"}=$ave;
10661: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
10662: my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
10663: $env{'request.course.id'},
10664: $domain,$username);
10665: if ($returncode ne 'ok') {
10666: $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
10667: } else {
10668: $storecount++;
10669: }
10670: }
10671: }
10672: # We are done
10673: $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
10674: '</td>'.
10675: &Apache::loncommon::end_data_table_row().
10676: &Apache::loncommon::end_data_table();
10677: return $result;
10678: }
10679:
10680: sub navmap_errormsg {
10681: return '<div class="LC_error">'.
10682: &mt('An error occurred retrieving information about resources in the course.').'<br />'.
10683: &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>').
10684: '</div>';
10685: }
10686:
10687: sub startpage {
10688: my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js,$onload) = @_;
10689: my %args;
10690: if ($onload) {
10691: my %loaditems = (
10692: 'onload' => $onload,
10693: );
10694: $args{'add_entries'} = \%loaditems;
10695: }
10696: if ($nomenu) {
10697: $args{'only_body'} = 1;
10698: $r->print(&Apache::loncommon::start_page("Student's Version",$js,\%args));
10699: } else {
10700: unshift(@$crumbs,{href=>&href_symb_cmd($symb,'gradingmenu'),text=>"Grading"});
10701: $args{'bread_crumbs'} = $crumbs;
10702: $r->print(&Apache::loncommon::start_page('Grading',$js,\%args));
10703: if ($env{'request.course.id'}) {
10704: &Apache::lonquickgrades::startGradeScreen($r,($env{'form.symb'}?'probgrading':'grading'));
10705: }
10706: }
10707: unless ($nodisplayflag) {
10708: $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
10709: }
10710: }
10711:
10712: sub select_problem {
10713: my ($r)=@_;
10714: $r->print('<h3>'.&mt('Select the problem or one of the problems you want to grade').'</h3><form action="/adm/grades">');
10715: $r->print(&Apache::lonstathelpers::problem_selector('.',undef,1,undef,undef,undef,undef,1));
10716: $r->print('<input type="hidden" name="command" value="gradingmenu" />');
10717: $r->print('<input type="submit" value="'.&mt('Next').' →" /></form>');
10718: }
10719:
10720: sub handler {
10721: my $request=$_[0];
10722: &reset_caches();
10723: if ($request->header_only) {
10724: &Apache::loncommon::content_type($request,'text/html');
10725: $request->send_http_header;
10726: return OK;
10727: }
10728: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
10729:
10730: # see what command we need to execute
10731:
10732: my @commands=&Apache::loncommon::get_env_multiple('form.command');
10733: my $command=$commands[0];
10734:
10735: &init_perm();
10736: if (!$env{'request.course.id'}) {
10737: unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
10738: ($command =~ /^scantronupload/)) {
10739: # Not in a course.
10740: $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
10741: return HTTP_NOT_ACCEPTABLE;
10742: }
10743: } elsif (!%perm) {
10744: $request->internal_redirect('/adm/quickgrades');
10745: return OK;
10746: }
10747: &Apache::loncommon::content_type($request,'text/html');
10748: $request->send_http_header;
10749:
10750: if ($#commands > 0) {
10751: &Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
10752: }
10753:
10754: # see what the symb is
10755:
10756: my $symb=$env{'form.symb'};
10757: unless ($symb) {
10758: (my $url=$env{'form.url'}) =~ s-^https*://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
10759: $symb=&Apache::lonnet::symbread($url);
10760: }
10761: &Apache::lonenc::check_decrypt(\$symb);
10762:
10763: $ssi_error = 0;
10764: if (($symb eq '' || $command eq '') && ($env{'request.course.id'})) {
10765: #
10766: # Not called from a resource, but inside a course
10767: #
10768: &startpage($request,undef,[],1,1);
10769: &select_problem($request);
10770: } else {
10771: if ($command eq 'submission' && $perm{'vgr'}) {
10772: my ($stuvcurrent,$stuvdisp,$versionform,$js);
10773: if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
10774: ($stuvcurrent,$stuvdisp,$versionform,$js) =
10775: &choose_task_version_form($symb,$env{'form.student'},
10776: $env{'form.userdom'});
10777: }
10778: &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
10779: if ($versionform) {
10780: $request->print($versionform);
10781: }
10782: $request->print('<br clear="all" />');
10783: ($env{'form.student'} eq '' ? &listStudents($request,$symb) : &submission($request,0,0,$symb));
10784: } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
10785: my ($stuvcurrent,$stuvdisp,$versionform,$js) =
10786: &choose_task_version_form($symb,$env{'form.student'},
10787: $env{'form.userdom'},
10788: $env{'form.inhibitmenu'});
10789: &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
10790: if ($versionform) {
10791: $request->print($versionform);
10792: }
10793: $request->print('<br clear="all" />');
10794: $request->print(&show_previous_task_version($request,$symb));
10795: } elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
10796: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10797: {href=>'',text=>'Select student'}],1,1);
10798: &pickStudentPage($request,$symb);
10799: } elsif ($command eq 'displayPage' && $perm{'vgr'}) {
10800: &startpage($request,$symb,
10801: [{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10802: {href=>'',text=>'Select student'},
10803: {href=>'',text=>'Grade student'}],1,1);
10804: &displayPage($request,$symb);
10805: } elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
10806: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'all_for_one'),text=>'Grade page/folder for one student'},
10807: {href=>'',text=>'Select student'},
10808: {href=>'',text=>'Grade student'},
10809: {href=>'',text=>'Store grades'}],1,1);
10810: &updateGradeByPage($request,$symb);
10811: } elsif ($command eq 'processGroup' && $perm{'vgr'}) {
10812: &startpage($request,$symb,[{href=>'',text=>'...'},
10813: {href=>'',text=>'Modify grades'}]);
10814: &processGroup($request,$symb);
10815: } elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
10816: &startpage($request,$symb);
10817: $request->print(&grading_menu($request,$symb));
10818: } elsif ($command eq 'individual' && $perm{'vgr'}) {
10819: &startpage($request,$symb,[{href=>'',text=>'Select individual students to grade'}]);
10820: $request->print(&submit_options($request,$symb));
10821: } elsif ($command eq 'ungraded' && $perm{'vgr'}) {
10822: &startpage($request,$symb,[{href=>'',text=>'Grade ungraded submissions'}]);
10823: $request->print(&listStudents($request,$symb,'graded'));
10824: } elsif ($command eq 'table' && $perm{'vgr'}) {
10825: &startpage($request,$symb,[{href=>"", text=>"Grading table"}]);
10826: $request->print(&submit_options_table($request,$symb));
10827: } elsif ($command eq 'all_for_one' && $perm{'vgr'}) {
10828: &startpage($request,$symb,[{href=>'',text=>'Grade page/folder for one student'}],1,1);
10829: $request->print(&submit_options_sequence($request,$symb));
10830: } elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
10831: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},{href=>'', text=>"Modify grades"}]);
10832: $request->print(&viewgrades($request,$symb));
10833: } elsif ($command eq 'handgrade' && $perm{'mgr'}) {
10834: &startpage($request,$symb,[{href=>'',text=>'...'},
10835: {href=>'',text=>'Store grades'}]);
10836: $request->print(&processHandGrade($request,$symb));
10837: } elsif ($command eq 'editgrades' && $perm{'mgr'}) {
10838: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"table"), text=>"Grading table"},
10839: {href=>&href_symb_cmd($symb,'viewgrades').'&group=all§ion=all&Status=Active',
10840: text=>"Modify grades"},
10841: {href=>'', text=>"Store grades"}]);
10842: $request->print(&editgrades($request,$symb));
10843: } elsif ($command eq 'initialverifyreceipt' && $perm{'vgr'}) {
10844: &startpage($request,$symb,[{href=>'',text=>'Verify Receipt Number'}]);
10845: $request->print(&initialverifyreceipt($request,$symb));
10846: } elsif ($command eq 'verify' && $perm{'vgr'}) {
10847: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,"initialverifyreceipt"),text=>'Verify Receipt Number'},
10848: {href=>'',text=>'Verification Result'}]);
10849: $request->print(&verifyreceipt($request,$symb));
10850: } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
10851: &startpage($request,$symb,[{href=>'', text=>'Process clicker'}]);
10852: $request->print(&process_clicker($request,$symb));
10853: } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
10854: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
10855: {href=>'', text=>'Process clicker file'}]);
10856: $request->print(&process_clicker_file($request,$symb));
10857: } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
10858: &startpage($request,$symb,[{href=>&href_symb_cmd($symb,'processclicker'), text=>'Process clicker'},
10859: {href=>'', text=>'Process clicker file'},
10860: {href=>'', text=>'Store grades'}]);
10861: $request->print(&assign_clicker_grades($request,$symb));
10862: } elsif ($command eq 'csvform' && $perm{'mgr'}) {
10863: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10864: $request->print(&upcsvScores_form($request,$symb));
10865: } elsif ($command eq 'csvupload' && $perm{'mgr'}) {
10866: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10867: $request->print(&csvupload($request,$symb));
10868: } elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
10869: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10870: $request->print(&csvuploadmap($request,$symb));
10871: } elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
10872: if ($env{'form.associate'} ne 'Reverse Association') {
10873: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10874: $request->print(&csvuploadoptions($request,$symb));
10875: } else {
10876: if ( $env{'form.upfile_associate'} ne 'reverse' ) {
10877: $env{'form.upfile_associate'} = 'reverse';
10878: } else {
10879: $env{'form.upfile_associate'} = 'forward';
10880: }
10881: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10882: $request->print(&csvuploadmap($request,$symb));
10883: }
10884: } elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
10885: &startpage($request,$symb,[{href=>'', text=>'Upload Scores'}],1,1);
10886: $request->print(&csvuploadassign($request,$symb));
10887: } elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
10888: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
10889: undef,undef,undef,undef,'toggleScantab(document.rules);');
10890: $request->print(&scantron_selectphase($request,undef,$symb));
10891: } elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
10892: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10893: $request->print(&scantron_do_warning($request,$symb));
10894: } elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
10895: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10896: $request->print(&scantron_validate_file($request,$symb));
10897: } elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
10898: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10899: $request->print(&scantron_process_students($request,$symb));
10900: } elsif ($command eq 'scantronupload' &&
10901: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10902: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10903: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1,
10904: undef,undef,undef,undef,'toggleScantab(document.rules);');
10905: $request->print(&scantron_upload_scantron_data($request,$symb));
10906: } elsif ($command eq 'scantronupload_save' &&
10907: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10908: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10909: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10910: $request->print(&scantron_upload_scantron_data_save($request,$symb));
10911: } elsif ($command eq 'scantron_download' &&
10912: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
10913: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10914: $request->print(&scantron_download_scantron_data($request,$symb));
10915: } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
10916: &startpage($request,$symb,[{href=>'', text=>'Grade/Manage/Review Bubblesheets'}],1,1);
10917: $request->print(&checkscantron_results($request,$symb));
10918: } elsif ($command eq 'downloadfilesselect' && $perm{'vgr'}) {
10919: &startpage($request,$symb,[{href=>'', text=>'Select which submissions to download'}]);
10920: $request->print(&submit_options_download($request,$symb));
10921: } elsif ($command eq 'downloadfileslink' && $perm{'vgr'}) {
10922: &startpage($request,$symb,
10923: [{href=>&href_symb_cmd($symb,'downloadfilesselect'), text=>'Select which submissions to download'},
10924: {href=>'', text=>'Download submitted files'}]);
10925: &submit_download_link($request,$symb);
10926: } elsif ($command) {
10927: &startpage($request,$symb,[{href=>'', text=>'Access denied'}]);
10928: $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
10929: }
10930: }
10931: if ($ssi_error) {
10932: &ssi_print_error($request);
10933: }
10934: if ($env{'form.inhibitmenu'}) {
10935: $request->print(&Apache::loncommon::end_page());
10936: } elsif ($env{'request.course.id'}) {
10937: &Apache::lonquickgrades::endGradeScreen($request);
10938: }
10939: &reset_caches();
10940: return OK;
10941: }
10942:
10943: 1;
10944:
10945: __END__;
10946:
10947:
10948: =head1 NAME
10949:
10950: Apache::grades
10951:
10952: =head1 SYNOPSIS
10953:
10954: Handles the viewing of grades.
10955:
10956: This is part of the LearningOnline Network with CAPA project
10957: described at http://www.lon-capa.org.
10958:
10959: =head1 OVERVIEW
10960:
10961: Do an ssi with retries:
10962: While I'd love to factor out this with the version in lonprintout,
10963: 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
10964: I'm not quite ready to invent (e.g. an ssi_with_retry object).
10965:
10966: At least the logic that drives this has been pulled out into loncommon.
10967:
10968:
10969:
10970: ssi_with_retries - Does the server side include of a resource.
10971: if the ssi call returns an error we'll retry it up to
10972: the number of times requested by the caller.
10973: If we still have a problem, no text is appended to the
10974: output and we set some global variables.
10975: to indicate to the caller an SSI error occurred.
10976: All of this is supposed to deal with the issues described
10977: in LON-CAPA BZ 5631 see:
10978: http://bugs.lon-capa.org/show_bug.cgi?id=5631
10979: by informing the user that this happened.
10980:
10981: Parameters:
10982: resource - The resource to include. This is passed directly, without
10983: interpretation to lonnet::ssi.
10984: form - The form hash parameters that guide the interpretation of the resource
10985:
10986: retries - Number of retries allowed before giving up completely.
10987: Returns:
10988: On success, returns the rendered resource identified by the resource parameter.
10989: Side Effects:
10990: The following global variables can be set:
10991: ssi_error - If an unrecoverable error occurred this becomes true.
10992: It is up to the caller to initialize this to false
10993: if desired.
10994: ssi_error_resource - If an unrecoverable error occurred, this is the value
10995: of the resource that could not be rendered by the ssi
10996: call.
10997: ssi_error_message - The error string fetched from the ssi response
10998: in the event of an error.
10999:
11000:
11001: =head1 HANDLER SUBROUTINE
11002:
11003: ssi_with_retries()
11004:
11005: =head1 SUBROUTINES
11006:
11007: =over
11008:
11009: =head1 Routines to display previous version of a Task for a specific student
11010:
11011: Tasks are graded pass/fail. Students who have yet to pass a particular Task
11012: can receive another opportunity. Access to tasks is slot-based. If a slot
11013: requires a proctor to check-in the student, a new version of the Task will
11014: be created when the student is checked in to the new opportunity.
11015:
11016: If a particular student has tried two or more versions of a particular task,
11017: the submission screen provides a user with vgr privileges (e.g., a Course
11018: Coordinator) the ability to display a previous version worked on by the
11019: student. By default, the current version is displayed. If a previous version
11020: has been selected for display, submission data are only shown that pertain
11021: to that particular version, and the interface to submit grades is not shown.
11022:
11023: =over 4
11024:
11025: =item show_previous_task_version()
11026:
11027: Displays a specified version of a student's Task, as the student sees it.
11028:
11029: Inputs: 2
11030: request - request object
11031: symb - unique symb for current instance of resource
11032:
11033: Output: None.
11034:
11035: Side Effects: calls &show_problem() to print version of Task, with
11036: version contained in form item: $env{'form.previousversion'}
11037:
11038: =item choose_task_version_form()
11039:
11040: Displays a web form used to select which version of a student's view of a
11041: Task should be displayed. Either launches a pop-up window, or replaces
11042: content in existing pop-up, or replaces page in main window.
11043:
11044: Inputs: 4
11045: symb - unique symb for current instance of resource
11046: uname - username of student
11047: udom - domain of student
11048: nomenu - 1 if display is in a pop-up window, and hence no menu
11049: breadcrumbs etc., are displayed
11050:
11051: Output: 4
11052: current - student's current version
11053: displayed - student's version being displayed
11054: result - scalar containing HTML for web form used to switch to
11055: a different version (or a link to close window, if pop-up).
11056: js - javascript for processing selection in versions web form
11057:
11058: Side Effects: None.
11059:
11060: =item previous_display_javascript()
11061:
11062: Inputs: 2
11063: nomenu - 1 if display is in a pop-up window, and hence no menu
11064: breadcrumbs etc., are displayed.
11065: current - student's current version number.
11066:
11067: Output: 1
11068: js - javascript for processing selection in versions web form.
11069:
11070: Side Effects: None.
11071:
11072: =back
11073:
11074: =head1 Routines to process bubblesheet data.
11075:
11076: =over 4
11077:
11078: =item scantron_get_correction() :
11079:
11080: Builds the interface screen to interact with the operator to fix a
11081: specific error condition in a specific scanline
11082:
11083: Arguments:
11084: $r - Apache request object
11085: $i - number of the current scanline
11086: $scan_record - hash ref as returned from &scantron_parse_scanline()
11087: $scan_config - hash ref as returned from &Apache::lonnet::get_scantron_config()
11088: $line - full contents of the current scanline
11089: $error - error condition, valid values are
11090: 'incorrectCODE', 'duplicateCODE',
11091: 'doublebubble', 'missingbubble',
11092: 'duplicateID', 'incorrectID'
11093: $arg - extra information needed
11094: For errors:
11095: - duplicateID - paper number that this studentID was seen before on
11096: - duplicateCODE - array ref of the paper numbers this CODE was
11097: seen on before
11098: - incorrectCODE - current incorrect CODE
11099: - doublebubble - array ref of the bubble lines that have double
11100: bubble errors
11101: - missingbubble - array ref of the bubble lines that have missing
11102: bubble errors
11103:
11104: $randomorder - True if exam folder has randomorder set
11105: $randompick - True if exam folder has randompick set
11106: $respnumlookup - Reference to HASH mapping question numbers in bubble lines
11107: for current line to question number used for same question
11108: in "Master Seqence" (as seen by Course Coordinator).
11109: $startline - Reference to hash where key is question number (0 is first)
11110: and value is number of first bubble line for current student
11111: or code-based randompick and/or randomorder.
11112:
11113:
11114:
11115: =item scantron_get_maxbubble() :
11116:
11117: Arguments:
11118: $nav_error - Reference to scalar which is a flag to indicate a
11119: failure to retrieve a navmap object.
11120: if $nav_error is set to 1 by scantron_get_maxbubble(), the
11121: calling routine should trap the error condition and display the warning
11122: found in &navmap_errormsg().
11123:
11124: $scantron_config - Reference to bubblesheet format configuration hash.
11125:
11126: Returns the maximum number of bubble lines that are expected to
11127: occur. Does this by walking the selected sequence rendering the
11128: resource and then checking &Apache::lonxml::get_problem_counter()
11129: for what the current value of the problem counter is.
11130:
11131: Caches the results to $env{'form.scantron_maxbubble'},
11132: $env{'form.scantron.bubble_lines.n'},
11133: $env{'form.scantron.first_bubble_line.n'} and
11134: $env{"form.scantron.sub_bubblelines.n"}
11135: which are the total number of bubble lines, the number of bubble
11136: lines for response n and number of the first bubble line for response n,
11137: and a comma separated list of numbers of bubble lines for sub-questions
11138: (for optionresponse, matchresponse, and rankresponse items), for response n.
11139:
11140:
11141: =item scantron_validate_missingbubbles() :
11142:
11143: Validates all scanlines in the selected file to not have any
11144: answers that don't have bubbles that have not been verified
11145: to be bubble free.
11146:
11147: =item scantron_process_students() :
11148:
11149: Routine that does the actual grading of the bubblesheet information.
11150:
11151: The parsed scanline hash is added to %env
11152:
11153: Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
11154: foreach resource , with the form data of
11155:
11156: 'submitted' =>'scantron'
11157: 'grade_target' =>'grade',
11158: 'grade_username'=> username of student
11159: 'grade_domain' => domain of student
11160: 'grade_courseid'=> of course
11161: 'grade_symb' => symb of resource to grade
11162:
11163: This triggers a grading pass. The problem grading code takes care
11164: of converting the bubbled letter information (now in %env) into a
11165: valid submission.
11166:
11167: =item scantron_upload_scantron_data() :
11168:
11169: Creates the screen for adding a new bubblesheet data file to a course.
11170:
11171: =item scantron_upload_scantron_data_save() :
11172:
11173: Adds a provided bubble information data file to the course if user
11174: has the correct privileges to do so.
11175:
11176: =item valid_file() :
11177:
11178: Validates that the requested bubble data file exists in the course.
11179:
11180: =item scantron_download_scantron_data() :
11181:
11182: Shows a list of the three internal files (original, corrected,
11183: skipped) for a specific bubblesheet data file that exists in the
11184: course.
11185:
11186: =item scantron_validate_ID() :
11187:
11188: Validates all scanlines in the selected file to not have any
11189: invalid or underspecified student/employee IDs
11190:
11191: =item navmap_errormsg() :
11192:
11193: Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
11194: Should be called whenever the request to instantiate a navmap object fails.
11195:
11196: =back
11197:
11198: =back
11199:
11200: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>