1: # The LearningOnline Network with CAPA
2: # The LON-CAPA Grading handler
3: #
4: # $Id: grades.pm,v 1.596.2.12.2.50 2020/02/12 17:33:53 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::bridgetask();
47: use Apache::lontexconvert();
48: use HTML::Parser();
49: use File::MMagic;
50: use String::Similarity;
51: use LONCAPA;
52:
53: use POSIX qw(floor);
54:
55:
56:
57: my %perm=();
58: my %old_essays=();
59:
60: # These variables are used to recover from ssi errors
61:
62: my $ssi_retries = 5;
63: my $ssi_error;
64: my $ssi_error_resource;
65: my $ssi_error_message;
66:
67:
68: sub ssi_with_retries {
69: my ($resource, $retries, %form) = @_;
70: my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
71: if ($response->is_error) {
72: $ssi_error = 1;
73: $ssi_error_resource = $resource;
74: $ssi_error_message = $response->code . " " . $response->message;
75: }
76:
77: return $content;
78:
79: }
80: #
81: # Prodcuces an ssi retry failure error message to the user:
82: #
83:
84: sub ssi_print_error {
85: my ($r) = @_;
86: my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
87: $r->print('
88: <br />
89: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
90: <p>
91: '.&mt('Unable to retrieve a resource from a server:').'<br />
92: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
93: '.&mt('Error:').' '.$ssi_error_message.'
94: </p>
95: <p>'.
96: &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 />'.
97: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
98: '</p>');
99: return;
100: }
101:
102: #
103: # --- Retrieve the parts from the metadata file.---
104: sub getpartlist {
105: my ($symb,$errorref) = @_;
106:
107: my $navmap = Apache::lonnavmaps::navmap->new();
108: unless (ref($navmap)) {
109: if (ref($errorref)) {
110: $$errorref = 'navmap';
111: return;
112: }
113: }
114: my $res = $navmap->getBySymb($symb);
115: my $partlist = $res->parts();
116: my $url = $res->src();
117: my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
118:
119: my @stores;
120: foreach my $part (@{ $partlist }) {
121: foreach my $key (@metakeys) {
122: if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
123: }
124: }
125: return @stores;
126: }
127:
128: # --- Get the symbolic name of a problem and the url
129: sub get_symb {
130: my ($request,$silent) = @_;
131: my $symb=$env{'form.symb'};
132: unless ($symb) {
133: (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
134: $symb = &Apache::lonnet::symbread($url);
135: if ($symb eq '') {
136: if (!$silent) {
137: $request->print(&mt("Unable to handle ambiguous references: [_1].",$url));
138: return ();
139: }
140: }
141: }
142: &Apache::lonenc::check_decrypt(\$symb);
143: return ($symb);
144: }
145:
146: #--- Format fullname, username:domain if different for display
147: #--- Use anywhere where the student names are listed
148: sub nameUserString {
149: my ($type,$fullname,$uname,$udom) = @_;
150: if ($type eq 'header') {
151: return '<b> '.&mt('Fullname').' </b><span class="LC_internal_info">('.&mt('Username').')</span>';
152: } else {
153: return ' '.$fullname.'<span class="LC_internal_info"> ('.$uname.
154: ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
155: }
156: }
157:
158: #--- Get the partlist and the response type for a given problem. ---
159: #--- Indicate if a response type is coded handgraded or not. ---
160: sub response_type {
161: my ($symb,$response_error) = @_;
162:
163: my $navmap = Apache::lonnavmaps::navmap->new();
164: unless (ref($navmap)) {
165: if (ref($response_error)) {
166: $$response_error = 1;
167: }
168: return;
169: }
170: my $res = $navmap->getBySymb($symb);
171: unless (ref($res)) {
172: $$response_error = 1;
173: return;
174: }
175: my $partlist = $res->parts();
176: my %vPart =
177: map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
178: my (%response_types,%handgrade);
179: foreach my $part (@{ $partlist }) {
180: next if (%vPart && !exists($vPart{$part}));
181:
182: my @types = $res->responseType($part);
183: my @ids = $res->responseIds($part);
184: for (my $i=0; $i < scalar(@ids); $i++) {
185: $response_types{$part}{$ids[$i]} = $types[$i];
186: $handgrade{$part.'_'.$ids[$i]} =
187: &Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
188: '.handgrade',$symb);
189: }
190: }
191: return ($partlist,\%handgrade,\%response_types);
192: }
193:
194: sub flatten_responseType {
195: my ($responseType) = @_;
196: my @part_response_id =
197: map {
198: my $part = $_;
199: map {
200: [$part,$_]
201: } sort(keys(%{ $responseType->{$part} }));
202: } sort(keys(%$responseType));
203: return @part_response_id;
204: }
205:
206: sub get_display_part {
207: my ($partID,$symb)=@_;
208: my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
209: if (defined($display) and $display ne '') {
210: $display.= ' (<span class="LC_internal_info">'
211: .&mt('Part ID: [_1]',$partID).'</span>)';
212: } else {
213: $display=$partID;
214: }
215: return $display;
216: }
217:
218: #--- Show resource title
219: #--- and parts and response type
220: sub showResourceInfo {
221: my ($symb,$probTitle,$checkboxes,$res_error) = @_;
222: my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
223: my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
224: if (ref($res_error)) {
225: if ($$res_error) {
226: return;
227: }
228: }
229: $result.=&Apache::loncommon::start_data_table()
230: .&Apache::loncommon::start_data_table_header_row();
231: if ($checkboxes) {
232: $result.='<th> </th>';
233: }
234: $result.='<th>'.&mt('Problem Part').'</th>'
235: .'<th>'.&mt('Res. ID').'</th>'
236: .'<th>'.&mt('Type').'</th>'
237: .&Apache::loncommon::end_data_table_header_row();
238: my %resptype = ();
239: my $hdgrade='no';
240: my %partsseen;
241: foreach my $partID (sort(keys(%$responseType))) {
242: foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
243: my $handgrade=$$handgrade{$partID.'_'.$resID};
244: my $responsetype = $responseType->{$partID}->{$resID};
245: $hdgrade = $handgrade if ($handgrade eq 'yes');
246: $result.=&Apache::loncommon::start_data_table_row();
247: if ($checkboxes) {
248: if (exists($partsseen{$partID})) {
249: $result.="<td> </td>";
250: } else {
251: $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
252: }
253: $partsseen{$partID}=1;
254: }
255: my $display_part=&get_display_part($partID,$symb);
256: $result.='<td>'.$display_part.'</td>'
257: .'<td>'.'<span class="LC_internal_info">'.$resID.'</span></td>'
258: .'<td>'.&mt($responsetype).'</td>'
259: # .'<td><b>'.&mt('Handgrade: [_1]',$handgrade).'</b></td>'
260: .&Apache::loncommon::end_data_table_row();
261: }
262: }
263: $result.=&Apache::loncommon::end_data_table();
264: return $result,$responseType,$hdgrade,$partlist,$handgrade;
265: }
266:
267: sub reset_caches {
268: &reset_analyze_cache();
269: &reset_perm();
270: &reset_old_essays();
271: }
272:
273: {
274: my %analyze_cache;
275: my %analyze_cache_formkeys;
276:
277: sub reset_analyze_cache {
278: undef(%analyze_cache);
279: undef(%analyze_cache_formkeys);
280: }
281:
282: sub get_analyze {
283: my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
284: my $key = "$symb\0$uname\0$udom";
285: if ($type eq 'randomizetry') {
286: if ($trial ne '') {
287: $key .= "\0".$trial;
288: }
289: }
290: if (exists($analyze_cache{$key})) {
291: my $getupdate = 0;
292: if (ref($add_to_hash) eq 'HASH') {
293: foreach my $item (keys(%{$add_to_hash})) {
294: if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
295: if (!exists($analyze_cache_formkeys{$key}{$item})) {
296: $getupdate = 1;
297: last;
298: }
299: } else {
300: $getupdate = 1;
301: }
302: }
303: }
304: if (!$getupdate) {
305: return $analyze_cache{$key};
306: }
307: }
308:
309: my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
310: $url=&Apache::lonnet::clutter($url);
311: my %form = ('grade_target' => 'analyze',
312: 'grade_domain' => $udom,
313: 'grade_symb' => $symb,
314: 'grade_courseid' => $env{'request.course.id'},
315: 'grade_username' => $uname,
316: 'grade_noincrement' => $no_increment);
317: if ($bubbles_per_row ne '') {
318: $form{'bubbles_per_row'} = $bubbles_per_row;
319: }
320: if ($type eq 'randomizetry') {
321: $form{'grade_questiontype'} = $type;
322: if ($rndseed ne '') {
323: $form{'grade_rndseed'} = $rndseed;
324: }
325: }
326: if (ref($add_to_hash)) {
327: %form = (%form,%{$add_to_hash});
328: }
329: my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
330: (undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
331: my %analyze=&Apache::lonnet::str2hash($subresult);
332: if (ref($add_to_hash) eq 'HASH') {
333: $analyze_cache_formkeys{$key} = $add_to_hash;
334: } else {
335: $analyze_cache_formkeys{$key} = {};
336: }
337: return $analyze_cache{$key} = \%analyze;
338: }
339:
340: sub get_order {
341: my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
342: my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
343: return $analyze->{"$partid.$respid.shown"};
344: }
345:
346: sub get_radiobutton_correct_foil {
347: my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
348: my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
349: my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
350: if (ref($foils) eq 'ARRAY') {
351: foreach my $foil (@{$foils}) {
352: if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
353: return $foil;
354: }
355: }
356: }
357: }
358:
359: sub scantron_partids_tograde {
360: my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row,$scancode) = @_;
361: my (%analysis,@parts);
362: if (ref($resource)) {
363: my $symb = $resource->symb();
364: my $add_to_form;
365: if ($check_for_randomlist) {
366: $add_to_form = { 'check_parts_withrandomlist' => 1,};
367: }
368: if ($scancode) {
369: if (ref($add_to_form) eq 'HASH') {
370: $add_to_form->{'code_for_randomlist'} = $scancode;
371: } else {
372: $add_to_form = { 'code_for_randomlist' => $scancode,};
373: }
374: }
375: my $analyze =
376: &get_analyze($symb,$uname,$udom,undef,$add_to_form,
377: undef,undef,undef,$bubbles_per_row);
378: if (ref($analyze) eq 'HASH') {
379: %analysis = %{$analyze};
380: }
381: if (ref($analysis{'parts'}) eq 'ARRAY') {
382: foreach my $part (@{$analysis{'parts'}}) {
383: my ($id,$respid) = split(/\./,$part);
384: if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
385: push(@parts,$part);
386: }
387: }
388: }
389: }
390: return (\%analysis,\@parts);
391: }
392:
393: }
394:
395: #--- Clean response type for display
396: #--- Currently filters option/rank/radiobutton/match/essay/Task
397: # response types only.
398: sub cleanRecord {
399: my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
400: $uname,$udom,$type,$trial,$rndseed) = @_;
401: my $grayFont = '<span class="LC_internal_info">';
402: if ($response =~ /^(option|rank)$/) {
403: my %answer=&Apache::lonnet::str2hash($answer);
404: my @answer = %answer;
405: %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
406: my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
407: my ($toprow,$bottomrow);
408: foreach my $foil (@$order) {
409: if ($grading{$foil} == 1) {
410: $toprow.='<td><b>'.$answer{$foil}.' </b></td>';
411: } else {
412: $toprow.='<td><i>'.$answer{$foil}.' </i></td>';
413: }
414: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
415: }
416: return '<blockquote><table border="1">'.
417: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
418: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
419: $bottomrow.'</tr></table></blockquote>';
420: } elsif ($response eq 'match') {
421: my %answer=&Apache::lonnet::str2hash($answer);
422: my @answer = %answer;
423: %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
424: my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
425: my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
426: my ($toprow,$middlerow,$bottomrow);
427: foreach my $foil (@$order) {
428: my $item=shift(@items);
429: if ($grading{$foil} == 1) {
430: $toprow.='<td><b>'.$item.' </b></td>';
431: $middlerow.='<td><b>'.$grayFont.$answer{$foil}.' </span></b></td>';
432: } else {
433: $toprow.='<td><i>'.$item.' </i></td>';
434: $middlerow.='<td><i>'.$grayFont.$answer{$foil}.' </span></i></td>';
435: }
436: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
437: }
438: return '<blockquote><table border="1">'.
439: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
440: '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
441: $middlerow.'</tr>'.
442: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
443: $bottomrow.'</tr></table></blockquote>';
444: } elsif ($response eq 'radiobutton') {
445: my %answer=&Apache::lonnet::str2hash($answer);
446: my ($toprow,$bottomrow);
447: my $correct =
448: &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
449: foreach my $foil (@$order) {
450: if (exists($answer{$foil})) {
451: if ($foil eq $correct) {
452: $toprow.='<td><b>'.&mt('true').'</b></td>';
453: } else {
454: $toprow.='<td><i>'.&mt('true').'</i></td>';
455: }
456: } else {
457: $toprow.='<td>'.&mt('false').'</td>';
458: }
459: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
460: }
461: return '<blockquote><table border="1">'.
462: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
463: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
464: $bottomrow.'</tr></table></blockquote>';
465: } elsif ($response eq 'essay') {
466: if (! exists ($env{'form.'.$symb})) {
467: my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
468: $env{'course.'.$env{'request.course.id'}.'.domain'},
469: $env{'course.'.$env{'request.course.id'}.'.num'});
470:
471: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
472: $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
473: $env{'form.kwclr'} = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
474: $env{'form.kwsize'} = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
475: $env{'form.kwstyle'} = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
476: $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
477: }
478: $answer = &Apache::lontexconvert::msgtexconverted($answer);
479: return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
480: } elsif ( $response eq 'organic') {
481: my $result=&mt('Smile representation: [_1]',
482: '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
483: my $jme=$record->{$version."resource.$partid.$respid.molecule"};
484: $result.=&Apache::chemresponse::jme_img($jme,$answer,400);
485: return $result;
486: } elsif ( $response eq 'Task') {
487: if ( $answer eq 'SUBMITTED') {
488: my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
489: my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
490: return $result;
491: } elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
492: my @matches = grep(/^\Q$version\E.*?\.instance$/,
493: keys(%{$record}));
494: return join('<br />',($version,@matches));
495:
496:
497: } else {
498: my $result =
499: '<p>'
500: .&mt('Overall result: [_1]',
501: $record->{$version."resource.$respid.$partid.status"})
502: .'</p>';
503:
504: $result .= '<ul>';
505: my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
506: keys(%{$record}));
507: foreach my $grade (sort(@grade)) {
508: my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
509: $result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
510: $dim, $record->{$grade}).
511: '</li>';
512: }
513: $result.='</ul>';
514: return $result;
515: }
516: } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
517: # Respect multiple input fields, see Bug #5409
518: $answer =
519: &Apache::loncommon::format_previous_attempt_value('submission',
520: $answer);
521: return $answer;
522: }
523: return &HTML::Entities::encode($answer, '"<>&');
524: }
525:
526: #-- A couple of common js functions
527: sub commonJSfunctions {
528: my $request = shift;
529: $request->print(<<COMMONJSFUNCTIONS);
530: <script type="text/javascript" language="javascript">
531: function radioSelection(radioButton) {
532: var selection=null;
533: if (radioButton.length > 1) {
534: for (var i=0; i<radioButton.length; i++) {
535: if (radioButton[i].checked) {
536: return radioButton[i].value;
537: }
538: }
539: } else {
540: if (radioButton.checked) return radioButton.value;
541: }
542: return selection;
543: }
544:
545: function pullDownSelection(selectOne) {
546: var selection="";
547: if (selectOne.length > 1) {
548: for (var i=0; i<selectOne.length; i++) {
549: if (selectOne[i].selected) {
550: return selectOne[i].value;
551: }
552: }
553: } else {
554: // only one value it must be the selected one
555: return selectOne.value;
556: }
557: }
558: </script>
559: COMMONJSFUNCTIONS
560: }
561:
562: #--- Dumps the class list with usernames,list of sections,
563: #--- section, ids and fullnames for each user.
564: sub getclasslist {
565: my ($getsec,$filterlist,$getgroup) = @_;
566: my @getsec;
567: my @getgroup;
568: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
569: if (!ref($getsec)) {
570: if ($getsec ne '' && $getsec ne 'all') {
571: @getsec=($getsec);
572: }
573: } else {
574: @getsec=@{$getsec};
575: }
576: if (grep(/^all$/,@getsec)) { undef(@getsec); }
577: if (!ref($getgroup)) {
578: if ($getgroup ne '' && $getgroup ne 'all') {
579: @getgroup=($getgroup);
580: }
581: } else {
582: @getgroup=@{$getgroup};
583: }
584: if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
585:
586: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
587: # Bail out if we were unable to get the classlist
588: return if (! defined($classlist));
589: &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
590: #
591: my %sections;
592: my %fullnames;
593: foreach my $student (keys(%$classlist)) {
594: my $end =
595: $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
596: my $start =
597: $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
598: my $id =
599: $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
600: my $section =
601: $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
602: my $fullname =
603: $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
604: my $status =
605: $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
606: my $group =
607: $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
608: # filter students according to status selected
609: if ($filterlist && (!($stu_status =~ /Any/))) {
610: if (!($stu_status =~ $status)) {
611: delete($classlist->{$student});
612: next;
613: }
614: }
615: # filter students according to groups selected
616: my @stu_groups = split(/,/,$group);
617: if (@getgroup) {
618: my $exclude = 1;
619: foreach my $grp (@getgroup) {
620: foreach my $stu_group (@stu_groups) {
621: if ($stu_group eq $grp) {
622: $exclude = 0;
623: }
624: }
625: if (($grp eq 'none') && !$group) {
626: $exclude = 0;
627: }
628: }
629: if ($exclude) {
630: delete($classlist->{$student});
631: }
632: }
633: $section = ($section ne '' ? $section : 'none');
634: if (&canview($section)) {
635: if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
636: $sections{$section}++;
637: if ($classlist->{$student}) {
638: $fullnames{$student}=$fullname;
639: }
640: } else {
641: delete($classlist->{$student});
642: }
643: } else {
644: delete($classlist->{$student});
645: }
646: }
647: my %seen = ();
648: my @sections = sort(keys(%sections));
649: return ($classlist,\@sections,\%fullnames);
650: }
651:
652: sub canmodify {
653: my ($sec)=@_;
654: if ($perm{'mgr'}) {
655: if (!defined($perm{'mgr_section'})) {
656: # can modify whole class
657: return 1;
658: } else {
659: if ($sec eq $perm{'mgr_section'}) {
660: #can modify the requested section
661: return 1;
662: } else {
663: # can't modify the request section
664: return 0;
665: }
666: }
667: }
668: #can't modify
669: return 0;
670: }
671:
672: sub canview {
673: my ($sec)=@_;
674: if ($perm{'vgr'}) {
675: if (!defined($perm{'vgr_section'})) {
676: # can modify whole class
677: return 1;
678: } else {
679: if ($sec eq $perm{'vgr_section'}) {
680: #can modify the requested section
681: return 1;
682: } else {
683: # can't modify the request section
684: return 0;
685: }
686: }
687: }
688: #can't modify
689: return 0;
690: }
691:
692: #--- Retrieve the grade status of a student for all the parts
693: sub student_gradeStatus {
694: my ($symb,$udom,$uname,$partlist) = @_;
695: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
696: my %partstatus = ();
697: foreach (@$partlist) {
698: my ($status,undef) = split(/_/,$record{"resource.$_.solved"},2);
699: $status = 'nothing' if ($status eq '');
700: $partstatus{$_} = $status;
701: my $subkey = "resource.$_.submitted_by";
702: $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
703: }
704: return %partstatus;
705: }
706:
707: # hidden form and javascript that calls the form
708: # Use by verifyscript and viewgrades
709: # Shows a student's view of problem and submission
710: sub jscriptNform {
711: my ($symb) = @_;
712: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
713: my $jscript='<script type="text/javascript" language="javascript">'."\n".
714: ' function viewOneStudent(user,domain) {'."\n".
715: ' document.onestudent.student.value = user;'."\n".
716: ' document.onestudent.userdom.value = domain;'."\n".
717: ' document.onestudent.submit();'."\n".
718: ' }'."\n".
719: '</script>'."\n";
720: $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
721: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
722: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
723: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
724: '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
725: '<input type="hidden" name="command" value="submission" />'."\n".
726: '<input type="hidden" name="student" value="" />'."\n".
727: '<input type="hidden" name="userdom" value="" />'."\n".
728: '</form>'."\n";
729: return $jscript;
730: }
731:
732:
733:
734: # Given the score (as a number [0-1] and the weight) what is the final
735: # point value? This function will round to the nearest tenth, third,
736: # or quarter if one of those is within the tolerance of .00001.
737: sub compute_points {
738: my ($score, $weight) = @_;
739:
740: my $tolerance = .00001;
741: my $points = $score * $weight;
742:
743: # Check for nearness to 1/x.
744: my $check_for_nearness = sub {
745: my ($factor) = @_;
746: my $num = ($points * $factor) + $tolerance;
747: my $floored_num = floor($num);
748: if ($num - $floored_num < 2 * $tolerance * $factor) {
749: return $floored_num / $factor;
750: }
751: return $points;
752: };
753:
754: $points = $check_for_nearness->(10);
755: $points = $check_for_nearness->(3);
756: $points = $check_for_nearness->(4);
757:
758: return $points;
759: }
760:
761: #------------------ End of general use routines --------------------
762:
763: #
764: # Find most similar essay
765: #
766:
767: sub most_similar {
768: my ($uname,$udom,$symb,$uessay)=@_;
769:
770: unless ($symb) { return ''; }
771:
772: unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
773:
774: # ignore spaces and punctuation
775:
776: $uessay=~s/\W+/ /gs;
777:
778: # ignore empty submissions (occuring when only files are sent)
779:
780: unless ($uessay=~/\w+/s) { return ''; }
781:
782: # these will be returned. Do not care if not at least 50 percent similar
783: my $limit=0.6;
784: my $sname='';
785: my $sdom='';
786: my $scrsid='';
787: my $sessay='';
788: # go through all essays ...
789: foreach my $tkey (keys(%{$old_essays{$symb}})) {
790: my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
791: # ... except the same student
792: next if (($tname eq $uname) && ($tdom eq $udom));
793: my $tessay=$old_essays{$symb}{$tkey};
794: $tessay=~s/\W+/ /gs;
795: # String similarity gives up if not even limit
796: my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
797: # Found one
798: if ($tsimilar>$limit) {
799: $limit=$tsimilar;
800: $sname=$tname;
801: $sdom=$tdom;
802: $scrsid=$tcrsid;
803: $sessay=$old_essays{$symb}{$tkey};
804: }
805: }
806: if ($limit>0.6) {
807: return ($sname,$sdom,$scrsid,$sessay,$limit);
808: } else {
809: return ('','','','',0);
810: }
811: }
812:
813: #-------------------------------------------------------------------
814:
815: #------------------------------------ Receipt Verification Routines
816: #
817: #--- Check whether a receipt number is valid.---
818: sub verifyreceipt {
819: my $request = shift;
820:
821: my $courseid = $env{'request.course.id'};
822: my $receipt = &Apache::lonnet::recprefix($courseid).'-'.
823: $env{'form.receipt'};
824: $receipt =~ s/[^\-\d]//g;
825: my ($symb) = &get_symb($request);
826:
827: my $title.=
828: '<h3><span class="LC_info">'.
829: &mt('Verifying Receipt No. [_1]',$receipt).
830: '</span></h3>'."\n".
831: '<h4>'.&mt('[_1]Resource: [_2]','<b>','</b>'.$env{'form.probTitle'}).
832: '</h4>'."\n";
833:
834: my ($string,$contents,$matches) = ('','',0);
835: my (undef,undef,$fullname) = &getclasslist('all','0');
836:
837: my $receiptparts=0;
838: if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
839: $env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
840: my $parts=['0'];
841: if ($receiptparts) {
842: my $res_error;
843: ($parts)=&response_type($symb,\$res_error);
844: if ($res_error) {
845: return &navmap_errormsg();
846: }
847: }
848:
849: my $header =
850: &Apache::loncommon::start_data_table().
851: &Apache::loncommon::start_data_table_header_row().
852: '<th> '.&mt('Fullname').' </th>'."\n".
853: '<th> '.&mt('Username').' </th>'."\n".
854: '<th> '.&mt('Domain').' </th>';
855: if ($receiptparts) {
856: $header.='<th> '.&mt('Problem Part').' </th>';
857: }
858: $header.=
859: &Apache::loncommon::end_data_table_header_row();
860:
861: foreach (sort
862: {
863: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
864: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
865: }
866: return $a cmp $b;
867: } (keys(%$fullname))) {
868: my ($uname,$udom)=split(/\:/);
869: foreach my $part (@$parts) {
870: if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
871: $contents.=
872: &Apache::loncommon::start_data_table_row().
873: '<td> '."\n".
874: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
875: '\');" target="_self">'.$$fullname{$_}.'</a> </td>'."\n".
876: '<td> '.$uname.' </td>'.
877: '<td> '.$udom.' </td>';
878: if ($receiptparts) {
879: $contents.='<td> '.$part.' </td>';
880: }
881: $contents.=
882: &Apache::loncommon::end_data_table_row()."\n";
883:
884: $matches++;
885: }
886: }
887: }
888: if ($matches == 0) {
889: $string = $title
890: .'<p class="LC_warning">'
891: .&mt('No match found for the above receipt number.')
892: .'</p>';
893: } else {
894: $string = &jscriptNform($symb).$title.
895: '<p>'.
896: &mt('The above receipt number matches the following [quant,_1,student].',$matches).
897: '</p>'.
898: $header.
899: $contents.
900: &Apache::loncommon::end_data_table()."\n";
901: }
902: return $string.&show_grading_menu_form($symb);
903: }
904:
905: #--- This is called by a number of programs.
906: #--- Called from the Grading Menu - View/Grade an individual student
907: #--- Also called directly when one clicks on the subm button
908: # on the problem page.
909: sub listStudents {
910: my ($request) = shift;
911:
912: my ($symb) = &get_symb($request);
913: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
914: my $cnum = $env{"course.$env{'request.course.id'}.num"};
915: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
916: my $getgroup = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
917: my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
918: my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
919: $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ?
920: &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
921:
922: my $result='<h3><span class="LC_info"> '
923: .&mt("$viewgrade Submissions for a Student or a Group of Students")
924: .'</span></h3>';
925:
926: my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
927:
928: my %js_lt = &Apache::lonlocal::texthash (
929: 'multiple' => 'Please select a student or group of students before clicking on the Next button.',
930: 'single' => 'Please select the student before clicking on the Next button.',
931: );
932: &js_escape(\%js_lt);
933: $request->print(<<LISTJAVASCRIPT);
934: <script type="text/javascript" language="javascript">
935: function checkSelect(checkBox) {
936: var ctr=0;
937: var sense="";
938: if (checkBox.length > 1) {
939: for (var i=0; i<checkBox.length; i++) {
940: if (checkBox[i].checked) {
941: ctr++;
942: }
943: }
944: sense = '$js_lt{'multiple'}';
945: } else {
946: if (checkBox.checked) {
947: ctr = 1;
948: }
949: sense = '$js_lt{'single'}';
950: }
951: if (ctr == 0) {
952: alert(sense);
953: return false;
954: }
955: document.gradesub.submit();
956: }
957:
958: function reLoadList(formname) {
959: if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
960: formname.command.value = 'submission';
961: formname.submit();
962: }
963: </script>
964: LISTJAVASCRIPT
965:
966: &commonJSfunctions($request);
967: $request->print($result);
968:
969: my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
970: my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
971: my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
972: "\n".$table;
973:
974: $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
975: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
976: .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
977: .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
978: .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
979: .&Apache::lonhtmlcommon::row_closure();
980: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
981: .'<label><input type="radio" name="vAns" value="no" /> '.&mt('no').' </label>'."\n"
982: .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
983: .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
984: .&Apache::lonhtmlcommon::row_closure();
985:
986: my $submission_options;
987: if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
988: $submission_options.=
989: '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
990: }
991: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
992: my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
993: $env{'form.Status'} = $saveStatus;
994: $submission_options.=
995: '<span class="LC_nobreak">'.
996: '<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.
997: &mt('last submission only').' </label></span>'."\n".
998: '<span class="LC_nobreak">'.
999: '<label><input type="radio" name="lastSub" value="last" /> '.
1000: &mt('last submission & parts info').' </label></span>'."\n".
1001: '<span class="LC_nobreak">'.
1002: '<label><input type="radio" name="lastSub" value="datesub" /> '.
1003: &mt('by dates and submissions').'</label></span>'."\n".
1004: '<span class="LC_nobreak">'.
1005: '<label><input type="radio" name="lastSub" value="all" /> '.
1006: &mt('all details').'</label></span>';
1007: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
1008: .$submission_options
1009: .&Apache::lonhtmlcommon::row_closure();
1010:
1011: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
1012: .'<select name="increment">'
1013: .'<option value="1">'.&mt('Whole Points').'</option>'
1014: .'<option value=".5">'.&mt('Half Points').'</option>'
1015: .'<option value=".25">'.&mt('Quarter Points').'</option>'
1016: .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
1017: .'</select>'
1018: .&Apache::lonhtmlcommon::row_closure();
1019:
1020: $gradeTable .=
1021: &build_section_inputs().
1022: '<input type="hidden" name="submitonly" value="'.$submitonly.'" />'."\n".
1023: '<input type="hidden" name="handgrade" value="'.$env{'form.handgrade'}.'" /><br />'."\n".
1024: '<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
1025: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1026: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
1027: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1028: '<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
1029:
1030: if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
1031: $gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1032: } else {
1033: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
1034: .&Apache::lonhtmlcommon::StatusOptions(
1035: $saveStatus,undef,1,'javascript:reLoadList(this.form);')
1036: .&Apache::lonhtmlcommon::row_closure();
1037: }
1038:
1039: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
1040: .'<input type="checkbox" name="checkPlag" checked="checked" />'
1041: .&Apache::lonhtmlcommon::row_closure(1)
1042: .&Apache::lonhtmlcommon::end_pick_box();
1043:
1044: $gradeTable .= '<p>'
1045: .&mt('To '.lc($viewgrade)." a submission or a group of submissions, click on the check box(es) next to the student's name(s). Then click on the Next button.")."\n"
1046: .'<input type="hidden" name="command" value="processGroup" />'
1047: .'</p>';
1048:
1049: # checkall buttons
1050: $gradeTable.=&check_script('gradesub', 'stuinfo');
1051: $gradeTable.='<input type="button" '."\n".
1052: 'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
1053: 'value="'.&mt('Next').' →" /> <br />'."\n";
1054: $gradeTable.=&check_buttons();
1055: my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1056: $gradeTable.= &Apache::loncommon::start_data_table().
1057: &Apache::loncommon::start_data_table_header_row();
1058: my $loop = 0;
1059: while ($loop < 2) {
1060: $gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
1061: '<th>'.&nameUserString('header').' '.&mt('Section/Group').'</th>';
1062: if ($env{'form.showgrading'} eq 'yes'
1063: && $submitonly ne 'queued'
1064: && $submitonly ne 'all') {
1065: foreach my $part (sort(@$partlist)) {
1066: my $display_part=
1067: &get_display_part((split(/_/,$part))[0],$symb);
1068: $gradeTable.=
1069: '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1070: }
1071: } elsif ($submitonly eq 'queued') {
1072: $gradeTable.='<th>'.&mt('Queue Status').' </th>';
1073: }
1074: $loop++;
1075: # $gradeTable.='<td></td>' if ($loop%2 ==1);
1076: }
1077: $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1078:
1079: my $ctr = 0;
1080: foreach my $student (sort
1081: {
1082: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
1083: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
1084: }
1085: return $a cmp $b;
1086: }
1087: (keys(%$fullname))) {
1088: my ($uname,$udom) = split(/:/,$student);
1089:
1090: my %status = ();
1091:
1092: if ($submitonly eq 'queued') {
1093: my %queue_status =
1094: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
1095: $udom,$uname);
1096: next if (!defined($queue_status{'gradingqueue'}));
1097: $status{'gradingqueue'} = $queue_status{'gradingqueue'};
1098: }
1099:
1100: if ($env{'form.showgrading'} eq 'yes'
1101: && $submitonly ne 'queued'
1102: && $submitonly ne 'all') {
1103: (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1104: my $submitted = 0;
1105: my $graded = 0;
1106: my $incorrect = 0;
1107: foreach (keys(%status)) {
1108: $submitted = 1 if ($status{$_} ne 'nothing');
1109: $graded = 1 if ($status{$_} =~ /^ungraded/);
1110: $incorrect = 1 if ($status{$_} =~ /^incorrect/);
1111:
1112: my ($foo,$partid,$foo1) = split(/\./,$_);
1113: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1114: $submitted = 0;
1115: my ($part)=split(/\./,$partid);
1116: $gradeTable.='<input type="hidden" name="'.
1117: $student.':'.$part.':submitted_by" value="'.
1118: $status{'resource.'.$partid.'.submitted_by'}.'" />';
1119: }
1120: }
1121:
1122: next if (!$submitted && ($submitonly eq 'yes' ||
1123: $submitonly eq 'incorrect' ||
1124: $submitonly eq 'graded'));
1125: next if (!$graded && ($submitonly eq 'graded'));
1126: next if (!$incorrect && $submitonly eq 'incorrect');
1127: }
1128:
1129: $ctr++;
1130: my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1131: my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1132: if ( $perm{'vgr'} eq 'F' ) {
1133: if ($ctr%2 ==1) {
1134: $gradeTable.= &Apache::loncommon::start_data_table_row();
1135: }
1136: $gradeTable.='<td align="right">'.$ctr.' </td>'.
1137: '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1138: $student.':'.$$fullname{$student}.':::SECTION'.$section.
1139: ') " /> </label></td>'."\n".'<td>'.
1140: &nameUserString(undef,$$fullname{$student},$uname,$udom).
1141: ' '.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1142:
1143: if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1144: foreach (sort(keys(%status))) {
1145: next if ($_ =~ /^resource.*?submitted_by$/);
1146: $gradeTable.='<td align="center"> '.&mt($status{$_}).' </td>'."\n";
1147: }
1148: }
1149: # $gradeTable.='<td></td>' if ($ctr%2 ==1);
1150: if ($ctr%2 ==0) {
1151: $gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
1152: }
1153: }
1154: }
1155: if ($ctr%2 ==1) {
1156: $gradeTable.='<td> </td><td> </td><td> </td>';
1157: if ($env{'form.showgrading'} eq 'yes'
1158: && $submitonly ne 'queued'
1159: && $submitonly ne 'all') {
1160: foreach (@$partlist) {
1161: $gradeTable.='<td> </td>';
1162: }
1163: } elsif ($submitonly eq 'queued') {
1164: $gradeTable.='<td> </td>';
1165: }
1166: $gradeTable.=&Apache::loncommon::end_data_table_row();
1167: }
1168:
1169: $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1170: '<input type="button" '.
1171: 'onclick="javascript:checkSelect(this.form.stuinfo);" '.
1172: 'value="'.&mt('Next').' →" /></form>'."\n";
1173: if ($ctr == 0) {
1174: my $num_students=(scalar(keys(%$fullname)));
1175: if ($num_students eq 0) {
1176: $gradeTable='<br /> <span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1177: } else {
1178: my $submissions='submissions';
1179: if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
1180: if ($submitonly eq 'graded' ) { $submissions = 'ungraded submissions'; }
1181: if ($submitonly eq 'queued' ) { $submissions = 'queued submissions'; }
1182: $gradeTable='<br /> <span class="LC_warning">'.
1183: &mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
1184: $num_students).
1185: '</span><br />';
1186: }
1187: } elsif ($ctr == 1) {
1188: $gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1189: }
1190: $gradeTable.=&show_grading_menu_form($symb);
1191: $request->print($gradeTable);
1192: return '';
1193: }
1194:
1195: #---- Called from the listStudents routine
1196:
1197: sub check_script {
1198: my ($form, $type)=@_;
1199: my $chkallscript='<script type="text/javascript">
1200: function checkall() {
1201: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1202: ele = document.forms.'.$form.'.elements[i];
1203: if (ele.name == "'.$type.'") {
1204: document.forms.'.$form.'.elements[i].checked=true;
1205: }
1206: }
1207: }
1208:
1209: function checksec() {
1210: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1211: ele = document.forms.'.$form.'.elements[i];
1212: string = document.forms.'.$form.'.chksec.value;
1213: if
1214: (ele.value.indexOf(":::SECTION"+string)>0) {
1215: document.forms.'.$form.'.elements[i].checked=true;
1216: }
1217: }
1218: }
1219:
1220:
1221: function uncheckall() {
1222: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1223: ele = document.forms.'.$form.'.elements[i];
1224: if (ele.name == "'.$type.'") {
1225: document.forms.'.$form.'.elements[i].checked=false;
1226: }
1227: }
1228: }
1229:
1230: </script>'."\n";
1231: return $chkallscript;
1232: }
1233:
1234: sub check_buttons {
1235: my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
1236: $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" /> ';
1237: $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1238: $buttons.='<input type="text" size="5" name="chksec" /> ';
1239: return $buttons;
1240: }
1241:
1242: # Displays the submissions for one student or a group of students
1243: sub processGroup {
1244: my ($request) = shift;
1245: my $ctr = 0;
1246: my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1247: my $total = scalar(@stuchecked)-1;
1248:
1249: foreach my $student (@stuchecked) {
1250: my ($uname,$udom,$fullname) = split(/:/,$student);
1251: $env{'form.student'} = $uname;
1252: $env{'form.userdom'} = $udom;
1253: $env{'form.fullname'} = $fullname;
1254: &submission($request,$ctr,$total);
1255: $ctr++;
1256: }
1257: return '';
1258: }
1259:
1260: #------------------------------------------------------------------------------------
1261: #
1262: #-------------------------- Next few routines handles grading by student, essentially
1263: # handles essay response type problem/part
1264: #
1265: #--- Javascript to handle the submission page functionality ---
1266: sub sub_page_js {
1267: my $request = shift;
1268: my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1269: &js_escape(\$alertmsg);
1270: $request->print(<<SUBJAVASCRIPT);
1271: <script type="text/javascript" language="javascript">
1272: function updateRadio(formname,id,weight) {
1273: var gradeBox = formname["GD_BOX"+id];
1274: var radioButton = formname["RADVAL"+id];
1275: var oldpts = formname["oldpts"+id].value;
1276: var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1277: gradeBox.value = pts;
1278: var resetbox = false;
1279: if (isNaN(pts) || pts < 0) {
1280: alert("$alertmsg"+pts);
1281: for (var i=0; i<radioButton.length; i++) {
1282: if (radioButton[i].checked) {
1283: gradeBox.value = i;
1284: resetbox = true;
1285: }
1286: }
1287: if (!resetbox) {
1288: formtextbox.value = "";
1289: }
1290: return;
1291: }
1292:
1293: if (pts > weight) {
1294: var resp = confirm("You entered a value ("+pts+
1295: ") greater than the weight for the part. Accept?");
1296: if (resp == false) {
1297: gradeBox.value = oldpts;
1298: return;
1299: }
1300: }
1301:
1302: for (var i=0; i<radioButton.length; i++) {
1303: radioButton[i].checked=false;
1304: if (pts == i && pts != "") {
1305: radioButton[i].checked=true;
1306: }
1307: }
1308: updateSelect(formname,id);
1309: formname["stores"+id].value = "0";
1310: }
1311:
1312: function writeBox(formname,id,pts) {
1313: var gradeBox = formname["GD_BOX"+id];
1314: if (checkSolved(formname,id) == 'update') {
1315: gradeBox.value = pts;
1316: } else {
1317: var oldpts = formname["oldpts"+id].value;
1318: gradeBox.value = oldpts;
1319: var radioButton = formname["RADVAL"+id];
1320: for (var i=0; i<radioButton.length; i++) {
1321: radioButton[i].checked=false;
1322: if (i == oldpts) {
1323: radioButton[i].checked=true;
1324: }
1325: }
1326: }
1327: formname["stores"+id].value = "0";
1328: updateSelect(formname,id);
1329: return;
1330: }
1331:
1332: function clearRadBox(formname,id) {
1333: if (checkSolved(formname,id) == 'noupdate') {
1334: updateSelect(formname,id);
1335: return;
1336: }
1337: gradeSelect = formname["GD_SEL"+id];
1338: for (var i=0; i<gradeSelect.length; i++) {
1339: if (gradeSelect[i].selected) {
1340: var selectx=i;
1341: }
1342: }
1343: var stores = formname["stores"+id];
1344: if (selectx == stores.value) { return };
1345: var gradeBox = formname["GD_BOX"+id];
1346: gradeBox.value = "";
1347: var radioButton = formname["RADVAL"+id];
1348: for (var i=0; i<radioButton.length; i++) {
1349: radioButton[i].checked=false;
1350: }
1351: stores.value = selectx;
1352: }
1353:
1354: function checkSolved(formname,id) {
1355: if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1356: var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
1357: if (!reply) {return "noupdate";}
1358: formname.overRideScore.value = 'yes';
1359: }
1360: return "update";
1361: }
1362:
1363: function updateSelect(formname,id) {
1364: formname["GD_SEL"+id][0].selected = true;
1365: return;
1366: }
1367:
1368: //=========== Check that a point is assigned for all the parts ============
1369: function checksubmit(formname,val,total,parttot) {
1370: formname.gradeOpt.value = val;
1371: if (val == "Save & Next") {
1372: for (i=0;i<=total;i++) {
1373: for (j=0;j<parttot;j++) {
1374: var partid = formname["partid"+i+"_"+j].value;
1375: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1376: var points = formname["GD_BOX"+i+"_"+partid].value;
1377: if (points == "") {
1378: var name = formname["name"+i].value;
1379: var studentID = (name != '' ? name : formname["unamedom"+i].value);
1380: var resp = confirm("You did not assign a score for "+studentID+
1381: ", part "+partid+". Continue?");
1382: if (resp == false) {
1383: formname["GD_BOX"+i+"_"+partid].focus();
1384: return false;
1385: }
1386: }
1387: }
1388: }
1389: }
1390: }
1391: if (val == "Grade Student") {
1392: formname.showgrading.value = "yes";
1393: if (formname.Status.value == "") {
1394: formname.Status.value = "Active";
1395: }
1396: formname.studentNo.value = total;
1397: }
1398: formname.submit();
1399: }
1400:
1401: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
1402: function checkSubmitPage(formname,total) {
1403: noscore = new Array(100);
1404: var ptr = 0;
1405: for (i=1;i<total;i++) {
1406: var partid = formname["q_"+i].value;
1407: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1408: var points = formname["GD_BOX"+i+"_"+partid].value;
1409: var status = formname["solved"+i+"_"+partid].value;
1410: if (points == "" && status != "correct_by_student") {
1411: noscore[ptr] = i;
1412: ptr++;
1413: }
1414: }
1415: }
1416: if (ptr != 0) {
1417: var sense = ptr == 1 ? ": " : "s: ";
1418: var prolist = "";
1419: if (ptr == 1) {
1420: prolist = noscore[0];
1421: } else {
1422: var i = 0;
1423: while (i < ptr-1) {
1424: prolist += noscore[i]+", ";
1425: i++;
1426: }
1427: prolist += "and "+noscore[i];
1428: }
1429: var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
1430: if (resp == false) {
1431: return false;
1432: }
1433: }
1434:
1435: formname.submit();
1436: }
1437: </script>
1438: SUBJAVASCRIPT
1439: }
1440:
1441: #--- javascript for essay type problem --
1442: sub sub_page_kw_js {
1443: my $request = shift;
1444: my $iconpath = $request->dir_config('lonIconsURL');
1445: &commonJSfunctions($request);
1446:
1447: my $inner_js_msg_central=<<INNERJS;
1448: <script text="text/javascript">
1449: function checkInput() {
1450: opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
1451: var nmsg = opener.document.SCORE.savemsgN.value;
1452: var usrctr = document.msgcenter.usrctr.value;
1453: var newval = opener.document.SCORE["newmsg"+usrctr];
1454: newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
1455:
1456: var msgchk = "";
1457: if (document.msgcenter.subchk.checked) {
1458: msgchk = "msgsub,";
1459: }
1460: var includemsg = 0;
1461: for (var i=1; i<=nmsg; i++) {
1462: var opnmsg = opener.document.SCORE["savemsg"+i];
1463: var frmmsg = document.msgcenter["msg"+i];
1464: opnmsg.value = opener.checkEntities(frmmsg.value);
1465: var showflg = opener.document.SCORE["shownOnce"+i];
1466: showflg.value = "1";
1467: var chkbox = document.msgcenter["msgn"+i];
1468: if (chkbox.checked) {
1469: msgchk += "savemsg"+i+",";
1470: includemsg = 1;
1471: }
1472: }
1473: if (document.msgcenter.newmsgchk.checked) {
1474: msgchk += "newmsg"+usrctr;
1475: includemsg = 1;
1476: }
1477: imgformname = opener.document.SCORE["mailicon"+usrctr];
1478: imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
1479: var includemsg = opener.document.SCORE["includemsg"+usrctr];
1480: includemsg.value = msgchk;
1481:
1482: self.close()
1483:
1484: }
1485: </script>
1486: INNERJS
1487:
1488: my $inner_js_highlight_central=<<INNERJS;
1489: <script type="text/javascript">
1490: function updateChoice(flag) {
1491: opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
1492: opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
1493: opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
1494: opener.document.SCORE.refresh.value = "on";
1495: if (opener.document.SCORE.keywords.value!=""){
1496: opener.document.SCORE.submit();
1497: }
1498: self.close()
1499: }
1500: </script>
1501: INNERJS
1502:
1503: my $start_page_msg_central =
1504: &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
1505: {'js_ready' => 1,
1506: 'only_body' => 1,
1507: 'bgcolor' =>'#FFFFFF',});
1508: my $end_page_msg_central =
1509: &Apache::loncommon::end_page({'js_ready' => 1});
1510:
1511:
1512: my $start_page_highlight_central =
1513: &Apache::loncommon::start_page('Highlight Central',
1514: $inner_js_highlight_central,
1515: {'js_ready' => 1,
1516: 'only_body' => 1,
1517: 'bgcolor' =>'#FFFFFF',});
1518: my $end_page_highlight_central =
1519: &Apache::loncommon::end_page({'js_ready' => 1});
1520:
1521: my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1522: $docopen=~s/^document\.//;
1523: my %js_lt = &Apache::lonlocal::texthash(
1524: keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
1525: plse => 'Please select a word or group of words from document and then click this link.',
1526: adds => 'Add selection to keyword list? Edit if desired.',
1527: col1 => 'red',
1528: col2 => 'green',
1529: col3 => 'blue',
1530: siz1 => 'normal',
1531: siz2 => '+1',
1532: siz3 => '+2',
1533: sty1 => 'normal',
1534: sty2 => 'italic',
1535: sty3 => 'bold',
1536: );
1537: my %html_js_lt = &Apache::lonlocal::texthash(
1538: comp => 'Compose Message for: ',
1539: incl => 'Include',
1540: type => 'Type',
1541: subj => 'Subject',
1542: mesa => 'Message',
1543: new => 'New',
1544: save => 'Save',
1545: canc => 'Cancel',
1546: kehi => 'Keyword Highlight Options',
1547: txtc => 'Text Color',
1548: font => 'Font Size',
1549: fnst => 'Font Style',
1550: );
1551: &js_escape(\%js_lt);
1552: &html_escape(\%html_js_lt);
1553: &js_escape(\%html_js_lt);
1554: $request->print(<<SUBJAVASCRIPT);
1555: <script type="text/javascript" language="javascript">
1556:
1557: //===================== Show list of keywords ====================
1558: function keywords(formname) {
1559: var nret = prompt("$js_lt{'keyw'}",formname.keywords.value);
1560: if (nret==null) return;
1561: formname.keywords.value = nret;
1562:
1563: if (formname.keywords.value != "") {
1564: formname.refresh.value = "on";
1565: formname.submit();
1566: }
1567: return;
1568: }
1569:
1570: //===================== Script to view submitted by ==================
1571: function viewSubmitter(submitter) {
1572: document.SCORE.refresh.value = "on";
1573: document.SCORE.NCT.value = "1";
1574: document.SCORE.unamedom0.value = submitter;
1575: document.SCORE.submit();
1576: return;
1577: }
1578:
1579: //===================== Script to add keyword(s) ==================
1580: function getSel() {
1581: if (document.getSelection) txt = document.getSelection();
1582: else if (document.selection) txt = document.selection.createRange().text;
1583: else return;
1584: var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
1585: if (cleantxt=="") {
1586: alert("$js_lt{'plse'}");
1587: return;
1588: }
1589: var nret = prompt("$js_lt{'adds'}",cleantxt);
1590: if (nret==null) return;
1591: document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1592: if (document.SCORE.keywords.value != "") {
1593: document.SCORE.refresh.value = "on";
1594: document.SCORE.submit();
1595: }
1596: return;
1597: }
1598:
1599: //====================== Script for composing message ==============
1600: // preload images
1601: img1 = new Image();
1602: img1.src = "$iconpath/mailbkgrd.gif";
1603: img2 = new Image();
1604: img2.src = "$iconpath/mailto.gif";
1605:
1606: function msgCenter(msgform,usrctr,fullname) {
1607: var Nmsg = msgform.savemsgN.value;
1608: savedMsgHeader(Nmsg,usrctr,fullname);
1609: var subject = msgform.msgsub.value;
1610: var msgchk = document.SCORE["includemsg"+usrctr].value;
1611: re = /msgsub/;
1612: var shwsel = "";
1613: if (re.test(msgchk)) { shwsel = "checked" }
1614: subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
1615: displaySubject(checkEntities(subject),shwsel);
1616: for (var i=1; i<=Nmsg; i++) {
1617: var testmsg = "savemsg"+i+",";
1618: re = new RegExp(testmsg,"g");
1619: shwsel = "";
1620: if (re.test(msgchk)) { shwsel = "checked" }
1621: var message = document.SCORE["savemsg"+i].value;
1622: message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1623: displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
1624: //any < is already converted to <, etc. However, only once!!
1625: }
1626: newmsg = document.SCORE["newmsg"+usrctr].value;
1627: shwsel = "";
1628: re = /newmsg/;
1629: if (re.test(msgchk)) { shwsel = "checked" }
1630: newMsg(newmsg,shwsel);
1631: msgTail();
1632: return;
1633: }
1634:
1635: function checkEntities(strx) {
1636: if (strx.length == 0) return strx;
1637: var orgStr = ["&", "<", ">", '"'];
1638: var newStr = ["&", "<", ">", """];
1639: var counter = 0;
1640: while (counter < 4) {
1641: strx = strReplace(strx,orgStr[counter],newStr[counter]);
1642: counter++;
1643: }
1644: return strx;
1645: }
1646:
1647: function strReplace(strx, orgStr, newStr) {
1648: return strx.split(orgStr).join(newStr);
1649: }
1650:
1651: function savedMsgHeader(Nmsg,usrctr,fullname) {
1652: var height = 70*Nmsg+250;
1653: if (height > 600) {
1654: height = 600;
1655: }
1656: var xpos = (screen.width-600)/2;
1657: xpos = (xpos < 0) ? '0' : xpos;
1658: var ypos = (screen.height-height)/2-30;
1659: ypos = (ypos < 0) ? '0' : ypos;
1660:
1661: pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1662: pWin.focus();
1663: pDoc = pWin.document;
1664: pDoc.$docopen;
1665: pDoc.write('$start_page_msg_central');
1666:
1667: pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
1668: pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1669: pDoc.write("<h3><span class=\\"LC_info\\"> $html_js_lt{'comp'}\"+fullname+\"<\\/span><\\/h3><br /><br />");
1670:
1671: pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
1672: pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1673: pDoc.write("<td><b>$html_js_lt{'type'}<\\/b><\\/td><td><b>$html_js_lt{'incl'}<\\/b><\\/td><td><b>$html_js_lt{'mesa'}<\\/td><\\/tr>");
1674: }
1675: function displaySubject(msg,shwsel) {
1676: pDoc = pWin.document;
1677: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1678: pDoc.write("<td>$html_js_lt{'subj'}<\\/td>");
1679: pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1680: pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1681: }
1682:
1683: function displaySavedMsg(ctr,msg,shwsel) {
1684: pDoc = pWin.document;
1685: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1686: pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
1687: pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1688: pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1689: }
1690:
1691: function newMsg(newmsg,shwsel) {
1692: pDoc = pWin.document;
1693: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1694: pDoc.write("<td align=\\"center\\">$html_js_lt{'new'}<\\/td>");
1695: pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1696: pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1697: }
1698:
1699: function msgTail() {
1700: pDoc = pWin.document;
1701: pDoc.write("<\\/table>");
1702: pDoc.write("<\\/td><\\/tr><\\/table> ");
1703: pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:checkInput()\\"> ");
1704: pDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1705: pDoc.write("<\\/form>");
1706: pDoc.write('$end_page_msg_central');
1707: pDoc.close();
1708: }
1709:
1710: //====================== Script for keyword highlight options ==============
1711: function kwhighlight() {
1712: var kwclr = document.SCORE.kwclr.value;
1713: var kwsize = document.SCORE.kwsize.value;
1714: var kwstyle = document.SCORE.kwstyle.value;
1715: var redsel = "";
1716: var grnsel = "";
1717: var blusel = "";
1718: var txtcol1 = "$js_lt{'col1'}";
1719: var txtcol2 = "$js_lt{'col2'}";
1720: var txtcol3 = "$js_lt{'col3'}";
1721: var txtsiz1 = "$js_lt{'siz1'}";
1722: var txtsiz2 = "$js_lt{'siz2'}";
1723: var txtsiz3 = "$js_lt{'siz3'}";
1724: var txtsty1 = "$js_lt{'sty1'}";
1725: var txtsty2 = "$js_lt{'sty2'}";
1726: var txtsty3 = "$js_lt{'sty3'}";
1727: if (kwclr=="red") {var redsel="checked='checked'"};
1728: if (kwclr=="green") {var grnsel="checked='checked'"};
1729: if (kwclr=="blue") {var blusel="checked='checked'"};
1730: var sznsel = "";
1731: var sz1sel = "";
1732: var sz2sel = "";
1733: if (kwsize=="0") {var sznsel="checked='checked'"};
1734: if (kwsize=="+1") {var sz1sel="checked='checked'"};
1735: if (kwsize=="+2") {var sz2sel="checked='checked'"};
1736: var synsel = "";
1737: var syisel = "";
1738: var sybsel = "";
1739: if (kwstyle=="") {var synsel="checked='checked'"};
1740: if (kwstyle=="<i>") {var syisel="checked='checked'"};
1741: if (kwstyle=="<b>") {var sybsel="checked='checked'"};
1742: highlightCentral();
1743: highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
1744: highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
1745: highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
1746: highlightend();
1747: return;
1748: }
1749:
1750: function highlightCentral() {
1751: // if (window.hwdWin) window.hwdWin.close();
1752: var xpos = (screen.width-400)/2;
1753: xpos = (xpos < 0) ? '0' : xpos;
1754: var ypos = (screen.height-330)/2-30;
1755: ypos = (ypos < 0) ? '0' : ypos;
1756:
1757: hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1758: hwdWin.focus();
1759: var hDoc = hwdWin.document;
1760: hDoc.$docopen;
1761: hDoc.write('$start_page_highlight_central');
1762: hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1763: hDoc.write("<h1>$html_js_lt{'kehi'}<\\/h1>");
1764:
1765: hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
1766: hDoc.write("<th>$html_js_lt{'txtc'}<\\/th><th>$html_js_lt{'font'}<\\/th><th>$html_js_lt{'fnst'}<\\/th><\\/tr>");
1767: }
1768:
1769: function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) {
1770: var hDoc = hwdWin.document;
1771: hDoc.write("<tr>");
1772: hDoc.write("<td align=\\"left\\">");
1773: hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/> "+clrtxt+"<\\/td>");
1774: hDoc.write("<td align=\\"left\\">");
1775: hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/> "+sztxt+"<\\/td>");
1776: hDoc.write("<td align=\\"left\\">");
1777: hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/> "+sytxt+"<\\/td>");
1778: hDoc.write("<\\/tr>");
1779: }
1780:
1781: function highlightend() {
1782: var hDoc = hwdWin.document;
1783: hDoc.write("<\\/table><br \\/>");
1784: hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/> ");
1785: hDoc.write("<input type=\\"button\\" value=\\"$html_js_lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
1786: hDoc.write("<\\/form>");
1787: hDoc.write('$end_page_highlight_central');
1788: hDoc.close();
1789: }
1790:
1791: </script>
1792: SUBJAVASCRIPT
1793: }
1794:
1795: sub get_increment {
1796: my $increment = $env{'form.increment'};
1797: if ($increment != 1 && $increment != .5 && $increment != .25 &&
1798: $increment != .1) {
1799: $increment = 1;
1800: }
1801: return $increment;
1802: }
1803:
1804: sub gradeBox_start {
1805: return (
1806: &Apache::loncommon::start_data_table()
1807: .&Apache::loncommon::start_data_table_header_row()
1808: .'<th>'.&mt('Part').'</th>'
1809: .'<th>'.&mt('Points').'</th>'
1810: .'<th> </th>'
1811: .'<th>'.&mt('Assign Grade').'</th>'
1812: .'<th>'.&mt('Weight').'</th>'
1813: .'<th>'.&mt('Grade Status').'</th>'
1814: .&Apache::loncommon::end_data_table_header_row()
1815: );
1816: }
1817:
1818: sub gradeBox_end {
1819: return (
1820: &Apache::loncommon::end_data_table()
1821: );
1822: }
1823: #--- displays the grading box, used in essay type problem and grading by page/sequence
1824: sub gradeBox {
1825: my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1826: my $checkIcon = '<img alt="'.&mt('Check Mark').
1827: '" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1828: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1829: my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)')
1830: : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1831: $wgt = ($wgt > 0 ? $wgt : '1');
1832: my $score = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1833: '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1834: my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1835: my $display_part= &get_display_part($partid,$symb);
1836: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
1837: [$partid]);
1838: my $aggtries = $$record{'resource.'.$partid.'.tries'};
1839: if ($last_resets{$partid}) {
1840: $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
1841: }
1842: my $result=&Apache::loncommon::start_data_table_row();
1843: my $ctr = 0;
1844: my $thisweight = 0;
1845: my $increment = &get_increment();
1846:
1847: my $radio.='<table border="0"><tr>'."\n"; # display radio buttons in a nice table 10 across
1848: while ($thisweight<=$wgt) {
1849: $radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1850: 'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1851: $thisweight.')" value="'.$thisweight.'" '.
1852: ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1853: $radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1854: $thisweight += $increment;
1855: $ctr++;
1856: }
1857: $radio.='</tr></table>';
1858:
1859: my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1860: ($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1861: 'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1862: $wgt.')" /></td>'."\n";
1863: $line.='<td>/'.$wgt.' '.$wgtmsg.
1864: ($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? ' '.$checkIcon : '').
1865: ' </td>'."\n";
1866: $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1867: 'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1868: if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1869: $line.='<option></option>'.
1870: '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1871: } else {
1872: $line.='<option selected="selected"></option>'.
1873: '<option value="excused" >'.&mt('excused').'</option>';
1874: }
1875: $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
1876:
1877:
1878: $result .=
1879: '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
1880: $result.=&Apache::loncommon::end_data_table_row().'<td colspan="6">';
1881: $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
1882: '<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
1883: '<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1884: $$record{'resource.'.$partid.'.solved'}.'" />'."\n".
1885: '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
1886: $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
1887: '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
1888: $aggtries.'" />'."\n";
1889: my $res_error;
1890: $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1891: $result.='</td>'.&Apache::loncommon::end_data_table_row();
1892: if ($res_error) {
1893: return &navmap_errormsg();
1894: }
1895: return $result;
1896: }
1897:
1898: sub handback_box {
1899: my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
1900: my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
1901: my (@respids);
1902: my @part_response_id = &flatten_responseType($responseType);
1903: foreach my $part_response_id (@part_response_id) {
1904: my ($part,$resp) = @{ $part_response_id };
1905: if ($part eq $partid) {
1906: push(@respids,$resp);
1907: }
1908: }
1909: my $result;
1910: foreach my $respid (@respids) {
1911: my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
1912: my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
1913: next if (!@$files);
1914: my $file_counter = 0;
1915: foreach my $file (@$files) {
1916: if ($file =~ /\/portfolio\//) {
1917: $file_counter++;
1918: my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1919: my ($name,$version,$ext) = &file_name_version_ext($file_disp);
1920: $file_disp = "$name.$ext";
1921: $file = $file_path.$file_disp;
1922: $result.=&mt('Return commented version of [_1] to student.',
1923: '<span class="LC_filename">'.$file_disp.'</span>');
1924: $result.='<input type="file" name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1925: $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1926: }
1927: }
1928: if ($file_counter) {
1929: $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
1930: '<span class="LC_info">'.
1931: '('.&mt('File(s) will be uploaded when you click on Save & Next below.',$file_counter).')</span><br /><br />';
1932: }
1933: }
1934: return $result;
1935: }
1936:
1937: sub show_problem {
1938: my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1939: my $rendered;
1940: my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1941: &Apache::lonxml::remember_problem_counter();
1942: if ($mode eq 'both' or $mode eq 'text') {
1943: $rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1944: $env{'request.course.id'},
1945: undef,\%form);
1946: }
1947: if ($removeform) {
1948: $rendered=~s|<form(.*?)>||g;
1949: $rendered=~s|</form>||g;
1950: $rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1951: }
1952: my $companswer;
1953: if ($mode eq 'both' or $mode eq 'answer') {
1954: &Apache::lonxml::restore_problem_counter();
1955: $companswer=
1956: &Apache::loncommon::get_student_answers($symb,$uname,$udom,
1957: $env{'request.course.id'},
1958: %form);
1959: }
1960: if ($removeform) {
1961: $companswer=~s|<form(.*?)>||g;
1962: $companswer=~s|</form>||g;
1963: $companswer=~s|name="submit"|name="would_have_been_submit"|g;
1964: }
1965: my $renderheading = &mt('View of the problem');
1966: my $answerheading = &mt('Correct answer');
1967: if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1968: my $stu_fullname = $env{'form.fullname'};
1969: if ($stu_fullname eq '') {
1970: $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
1971: }
1972: my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
1973: if ($forwhom ne '') {
1974: $renderheading = &mt('View of the problem for[_1]',$forwhom);
1975: $answerheading = &mt('Correct answer for[_1]',$forwhom);
1976: }
1977: }
1978: $rendered=
1979: '<div class="LC_Box">'
1980: .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1981: .$rendered
1982: .'</div>';
1983: $companswer=
1984: '<div class="LC_Box">'
1985: .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1986: .$companswer
1987: .'</div>';
1988: my $result;
1989: if ($mode eq 'both') {
1990: $result=$rendered.$companswer;
1991: } elsif ($mode eq 'text') {
1992: $result=$rendered;
1993: } elsif ($mode eq 'answer') {
1994: $result=$companswer;
1995: }
1996: return $result;
1997: }
1998:
1999: sub files_exist {
2000: my ($r, $symb) = @_;
2001: my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
2002:
2003: foreach my $student (@students) {
2004: my ($uname,$udom,$fullname) = split(/:/,$student);
2005: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
2006: $udom,$uname);
2007: my ($string,$timestamp)= &get_last_submission(\%record);
2008: foreach my $submission (@$string) {
2009: my ($partid,$respid) =
2010: ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
2011: my $files=&get_submitted_files($udom,$uname,$partid,$respid,
2012: \%record);
2013: return 1 if (@$files);
2014: }
2015: }
2016: return 0;
2017: }
2018:
2019: sub download_all_link {
2020: my ($r,$symb) = @_;
2021: my $all_students =
2022: join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
2023:
2024: my $parts =
2025: join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
2026:
2027: my $identifier = &Apache::loncommon::get_cgi_id();
2028: &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
2029: 'cgi.'.$identifier.'.symb' => $symb,
2030: 'cgi.'.$identifier.'.parts' => $parts,});
2031: $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
2032: &mt('Download All Submitted Documents').'</a>');
2033: return
2034: }
2035:
2036: sub build_section_inputs {
2037: my $section_inputs;
2038: if ($env{'form.section'} eq '') {
2039: $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
2040: } else {
2041: my @sections = &Apache::loncommon::get_env_multiple('form.section');
2042: foreach my $section (@sections) {
2043: $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
2044: }
2045: }
2046: return $section_inputs;
2047: }
2048:
2049: # --------------------------- show submissions of a student, option to grade
2050: sub submission {
2051: my ($request,$counter,$total) = @_;
2052: my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
2053: $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
2054: my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
2055: $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
2056: my ($symb) = &get_symb($request);
2057: if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
2058: my ($essayurl,%coursedesc_by_cid);
2059:
2060: if (!&canview($usec)) {
2061: $request->print(
2062: '<span class="LC_warning">'.
2063: &mt('Unable to view requested student.').
2064: ' '.&mt('([_1] in section [_2] in course id [_3])',
2065: $uname.':'.$udom,$usec,$env{'request.course.id'}).
2066: '</span>');
2067: $request->print(&show_grading_menu_form($symb));
2068: return;
2069: }
2070:
2071: if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
2072: if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
2073: if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
2074: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
2075: my $checkIcon = '<img alt="'.&mt('Check Mark').
2076: '" src="'.$request->dir_config('lonIconsURL').
2077: '/check.gif" height="16" border="0" />';
2078:
2079: # header info
2080: if ($counter == 0) {
2081: &sub_page_js($request);
2082: &sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
2083: $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ?
2084: &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
2085: if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
2086: &download_all_link($request, $symb);
2087: }
2088: $request->print('<h3> <span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
2089: '<h4> '.&mt('[_1]Resource: [_2]','<b>','</b>'.$env{'form.probTitle'}).'</h4>'."\n");
2090:
2091: # option to display problem, only once else it cause problems
2092: # with the form later since the problem has a form.
2093: if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
2094: my $mode;
2095: if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
2096: $mode='both';
2097: } elsif ($env{'form.vProb'} eq 'yes') {
2098: $mode='text';
2099: } elsif ($env{'form.vAns'} eq 'yes') {
2100: $mode='answer';
2101: }
2102: &Apache::lonxml::clear_problem_counter();
2103: $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
2104: }
2105:
2106: # kwclr is the only variable that is guaranteed not to be blank
2107: # if this subroutine has been called once.
2108: my %keyhash = ();
2109: if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
2110: %keyhash = &Apache::lonnet::dump('nohist_handgrade',
2111: $env{'course.'.$env{'request.course.id'}.'.domain'},
2112: $env{'course.'.$env{'request.course.id'}.'.num'});
2113:
2114: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
2115: $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
2116: $env{'form.kwclr'} = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
2117: $env{'form.kwsize'} = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
2118: $env{'form.kwstyle'} = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
2119: $env{'form.msgsub'} = $keyhash{$symb.'_subject'} ne '' ?
2120: $keyhash{$symb.'_subject'} : $env{'form.probTitle'};
2121: $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
2122: }
2123: my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
2124: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
2125: $request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
2126: '<input type="hidden" name="command" value="handgrade" />'."\n".
2127: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
2128: '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
2129: '<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
2130: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
2131: '<input type="hidden" name="refresh" value="off" />'."\n".
2132: '<input type="hidden" name="studentNo" value="" />'."\n".
2133: '<input type="hidden" name="gradeOpt" value="" />'."\n".
2134: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
2135: '<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
2136: '<input type="hidden" name="vProb" value="'.$env{'form.vProb'}.'" />'."\n".
2137: '<input type="hidden" name="vAns" value="'.$env{'form.vAns'}.'" />'."\n".
2138: '<input type="hidden" name="lastSub" value="'.$env{'form.lastSub'}.'" />'."\n".
2139: &build_section_inputs().
2140: '<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
2141: '<input type="hidden" name="handgrade" value="'.$env{'form.handgrade'}.'" />'."\n".
2142: '<input type="hidden" name="NCT"'.
2143: ' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
2144: if ($env{'form.handgrade'} eq 'yes') {
2145: $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
2146: '<input type="hidden" name="kwclr" value="'.$env{'form.kwclr'}.'" />'."\n".
2147: '<input type="hidden" name="kwsize" value="'.$env{'form.kwsize'}.'" />'."\n".
2148: '<input type="hidden" name="kwstyle" value="'.$env{'form.kwstyle'}.'" />'."\n".
2149: '<input type="hidden" name="msgsub" value="'.$env{'form.msgsub'}.'" />'."\n".
2150: '<input type="hidden" name="shownSub" value="0" />'."\n".
2151: '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
2152: foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
2153: $request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
2154: }
2155: }
2156:
2157: my ($cts,$prnmsg) = (1,'');
2158: while ($cts <= $env{'form.savemsgN'}) {
2159: $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
2160: (!exists($keyhash{$symb.'_savemsg'.$cts}) ?
2161: &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
2162: &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
2163: '" />'."\n".
2164: '<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
2165: $cts++;
2166: }
2167: $request->print($prnmsg);
2168:
2169: if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
2170:
2171: my %lt = &Apache::lonlocal::texthash(
2172: keyh => 'Keyword Highlighting for Essays',
2173: keyw => 'Keyword Options',
2174: list => 'List',
2175: past => 'Paste Selection to List',
2176: high => 'Highlight Attribute',
2177: );
2178: #
2179: # Print out the keyword options line
2180: #
2181: $request->print(
2182: '<div class="LC_columnSection">'
2183: .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
2184: .&Apache::lonhtmlcommon::funclist_from_array(
2185: ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
2186: '<a href="#" onmousedown="javascript:getSel(); return false"
2187: class="page">'.$lt{'past'}.'</a>',
2188: '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
2189: {legend => $lt{'keyw'}})
2190: .'</fieldset></div>'
2191: );
2192:
2193: #
2194: # Load the other essays for similarity check
2195: #
2196: (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
2197: if ($essayurl eq 'lib/templates/simpleproblem.problem') {
2198: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2199: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2200: if ($cdom ne '' && $cnum ne '') {
2201: my ($map,$id,$res) = &Apache::lonnet::decode_symb($symb);
2202: if ($map =~ m{^\Quploaded/$cdom/$cnum/\E(default(?:|_\d+)\.(?:sequence|page))$}) {
2203: my $apath = $1.'_'.$id;
2204: $apath=~s/\W/\_/gs;
2205: &init_old_essays($symb,$apath,$cdom,$cnum);
2206: }
2207: }
2208: } else {
2209: my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
2210: $apath=&escape($apath);
2211: $apath=~s/\W/\_/gs;
2212: &init_old_essays($symb,$apath,$adom,$aname);
2213: }
2214: }
2215: }
2216:
2217: # This is where output for one specific student would start
2218: my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
2219: $request->print(
2220: "\n\n"
2221: .'<div class="LC_grade_show_user'.$add_class.'">'
2222: .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
2223: ."\n"
2224: );
2225:
2226: # Show additional functions if allowed
2227: if ($perm{'vgr'}) {
2228: $request->print(
2229: &Apache::loncommon::track_student_link(
2230: 'View recent activity',
2231: $uname,$udom,'check')
2232: .' '
2233: );
2234: }
2235: if ($perm{'opa'}) {
2236: $request->print(
2237: &Apache::loncommon::pprmlink(
2238: &mt('Set/Change parameters'),
2239: $uname,$udom,$symb,'check'));
2240: }
2241:
2242: # Show Problem
2243: if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
2244: my $mode;
2245: if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
2246: $mode='both';
2247: } elsif ($env{'form.vProb'} eq 'all' ) {
2248: $mode='text';
2249: } elsif ($env{'form.vAns'} eq 'all') {
2250: $mode='answer';
2251: }
2252: &Apache::lonxml::clear_problem_counter();
2253: $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
2254: }
2255:
2256: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
2257: my $res_error;
2258: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
2259: if ($res_error) {
2260: $request->print(&navmap_errormsg());
2261: return;
2262: }
2263:
2264: # Display student info
2265: $request->print(($counter == 0 ? '' : '<br />'));
2266:
2267: my $result='<div class="LC_Box">'
2268: .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
2269: $result.='<input type="hidden" name="name'.$counter.
2270: '" value="'.$env{'form.fullname'}.'" />'."\n";
2271: if ($env{'form.handgrade'} eq 'no') {
2272: $result.='<p class="LC_info">'
2273: .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
2274: ."</p>\n";
2275: }
2276:
2277: # If any part of the problem is an essay-response (handgraded), then check for collaborators
2278: my $fullname;
2279: my $col_fullnames = [];
2280: if ($env{'form.handgrade'} eq 'yes') {
2281: (my $sub_result,$fullname,$col_fullnames)=
2282: &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
2283: $counter);
2284: $result.=$sub_result;
2285: }
2286: $request->print($result."\n");
2287:
2288: # print student answer/submission
2289: # Options are (1) Handgraded submission only
2290: # (2) Last submission, includes submission that is not handgraded
2291: # (for multi-response type part)
2292: # (3) Last submission plus the parts info
2293: # (4) The whole record for this student
2294:
2295: my ($string,$timestamp)= &get_last_submission(\%record);
2296:
2297: my $lastsubonly;
2298:
2299: if ($$timestamp eq '') {
2300: $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>';
2301: } else {
2302: $lastsubonly =
2303: '<div class="LC_grade_submissions_body">'
2304: .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
2305:
2306: my %seenparts;
2307: my @part_response_id = &flatten_responseType($responseType);
2308: foreach my $part (@part_response_id) {
2309: next if ($env{'form.lastSub'} eq 'hdgrade'
2310: && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
2311:
2312: my ($partid,$respid) = @{ $part };
2313: my $display_part=&get_display_part($partid,$symb);
2314: if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
2315: if (exists($seenparts{$partid})) { next; }
2316: $seenparts{$partid}=1;
2317: $request->print(
2318: '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
2319: ' <b>'.&mt('Collaborative submission by: [_1]',
2320: '<a href="javascript:viewSubmitter(\''.
2321: $env{"form.$uname:$udom:$partid:submitted_by"}.
2322: '\');" target="_self">'.
2323: $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
2324: '<br />');
2325: next;
2326: }
2327: my $responsetype = $responseType->{$partid}->{$respid};
2328: if (!exists($record{"resource.$partid.$respid.submission"})) {
2329: $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
2330: '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
2331: ' <span class="LC_internal_info">'.
2332: '('.&mt('Response ID: [_1]',$respid).')'.
2333: '</span> '.
2334: '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
2335: next;
2336: }
2337: foreach my $submission (@$string) {
2338: my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
2339: if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
2340: my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
2341: # Similarity check
2342: my $similar='';
2343: my ($type,$trial,$rndseed);
2344: if ($hide eq 'rand') {
2345: $type = 'randomizetry';
2346: $trial = $record{"resource.$partid.tries"};
2347: $rndseed = $record{"resource.$partid.rndseed"};
2348: }
2349: if ($env{'form.checkPlag'}) {
2350: my ($oname,$odom,$ocrsid,$oessay,$osim)=
2351: &most_similar($uname,$udom,$symb,$subval);
2352: if ($osim) {
2353: $osim=int($osim*100.0);
2354: if ($hide eq 'anon') {
2355: $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
2356: &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
2357: } else {
2358: $similar='<hr />';
2359: if ($essayurl eq 'lib/templates/simpleproblem.problem') {
2360: $similar .= '<h3><span class="LC_warning">'.
2361: &mt('Essay is [_1]% similar to an essay by [_2]',
2362: $osim,
2363: &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
2364: '</span></h3>';
2365: } elsif ($ocrsid ne '') {
2366: my %old_course_desc;
2367: if (ref($coursedesc_by_cid{$ocrsid}) eq 'HASH') {
2368: %old_course_desc = %{$coursedesc_by_cid{$ocrsid}};
2369: } else {
2370: my $args;
2371: if ($ocrsid ne $env{'request.course.id'}) {
2372: $args = {'one_time' => 1};
2373: }
2374: %old_course_desc =
2375: &Apache::lonnet::coursedescription($ocrsid,$args);
2376: $coursedesc_by_cid{$ocrsid} = \%old_course_desc;
2377: }
2378: $similar .=
2379: &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
2380: $osim,
2381: &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
2382: $old_course_desc{'description'},
2383: $old_course_desc{'num'},
2384: $old_course_desc{'domain'}).
2385: '</span></h3>';
2386: } else {
2387: $similar .=
2388: '<h3><span class="LC_warning">'.
2389: &mt('Essay is [_1]% similar to an essay by [_2] in an unknown course',
2390: $osim,
2391: &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')').
2392: '</span></h3>';
2393: }
2394: $similar .= '<blockquote><i>'.
2395: &keywords_highlight($oessay).
2396: '</i></blockquote><hr />';
2397: }
2398: }
2399: }
2400: my $order=&get_order($partid,$respid,$symb,$uname,$udom,
2401: undef,$type,$trial,$rndseed);
2402: if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' &&
2403: $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
2404: my $display_part=&get_display_part($partid,$symb);
2405: $lastsubonly.='<div class="LC_grade_submission_part">'.
2406: '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
2407: ' <span class="LC_internal_info">'.
2408: '('.&mt('Response ID: [_1]',$respid).')'.
2409: '</span> ';
2410: my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
2411: if (@$files) {
2412: if ($hide eq 'anon') {
2413: $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
2414: } else {
2415: $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
2416: .'<br /><span class="LC_warning">';
2417: if(@$files == 1) {
2418: $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
2419: } else {
2420: $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
2421: }
2422: $lastsubonly .= '</span>';
2423:
2424: foreach my $file (@$files) {
2425: &Apache::lonnet::allowuploaded('/adm/grades',$file);
2426: $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
2427: }
2428: }
2429: $lastsubonly.='<br />';
2430: }
2431: if ($hide eq 'anon') {
2432: $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>';
2433: } else {
2434: $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
2435: if ($draft) {
2436: $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
2437: }
2438: $subval =
2439: &cleanRecord($subval,$responsetype,$symb,$partid,
2440: $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
2441: if ($responsetype eq 'essay') {
2442: $subval =~ s{\n}{<br />}g;
2443: }
2444: $lastsubonly.=$subval."\n";
2445: }
2446: if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
2447: $lastsubonly.='</div>';
2448: }
2449: }
2450: }
2451: $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
2452: }
2453: $request->print($lastsubonly);
2454: if ($env{'form.lastSub'} eq 'datesub') {
2455: my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
2456: $request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
2457: }
2458: if ($env{'form.lastSub'} =~ /^(last|all)$/) {
2459: my $identifier = (&canmodify($usec)? $counter : '');
2460: $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
2461: $env{'request.course.id'},
2462: $last,'.submission',
2463: 'Apache::grades::keywords_highlight',
2464: $usec,$identifier));
2465: }
2466:
2467: $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
2468: .$udom.'" />'."\n");
2469: # return if view submission with no grading option
2470: if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
2471: my $toGrade.='<input type="button" value="Grade Student" '.
2472: 'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
2473: .$counter.'\');" target="_self" /> '."\n" if (&canmodify($usec));
2474: $toGrade.='</div>'."\n";
2475: if (($env{'form.command'} eq 'submission') ||
2476: ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
2477: $toGrade.='</form>'.&show_grading_menu_form($symb);
2478: }
2479: $request->print($toGrade);
2480: return;
2481: } else {
2482: $request->print('</div>'."\n");
2483: }
2484:
2485: # essay grading message center
2486: if ($env{'form.handgrade'} eq 'yes') {
2487: my $result='<div class="LC_grade_message_center">';
2488:
2489: $result.='<div class="LC_grade_message_center_header">'.
2490: &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
2491: my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
2492: my $msgfor = $givenn.' '.$lastname;
2493: if (scalar(@$col_fullnames) > 0) {
2494: my $lastone = pop(@$col_fullnames);
2495: $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
2496: }
2497: $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
2498: $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
2499: '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
2500: $result.=' <a href="javascript:msgCenter(document.SCORE,'.$counter.
2501: ',\''.$msgfor.'\');" target="_self">'.
2502: &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
2503: &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
2504: ' <img src="'.$request->dir_config('lonIconsURL').
2505: '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
2506: '<br /> ('.
2507: &mt('Message will be sent when you click on Save & Next below.').")\n";
2508: $result.='</div></div>';
2509: $request->print($result);
2510: }
2511:
2512: my %seen = ();
2513: my @partlist;
2514: my @gradePartRespid;
2515: my @part_response_id = &flatten_responseType($responseType);
2516: $request->print(
2517: '<div class="LC_Box">'
2518: .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
2519: );
2520: $request->print(&gradeBox_start());
2521: foreach my $part_response_id (@part_response_id) {
2522: my ($partid,$respid) = @{ $part_response_id };
2523: my $part_resp = join('_',@{ $part_response_id });
2524: next if ($seen{$partid} > 0);
2525: $seen{$partid}++;
2526: next if ($$handgrade{$part_resp} ne 'yes'
2527: && $env{'form.lastSub'} eq 'hdgrade');
2528: push(@partlist,$partid);
2529: push(@gradePartRespid,$partid.'.'.$respid);
2530: $request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
2531: }
2532: $request->print(&gradeBox_end()); # </div>
2533: $request->print('</div>');
2534:
2535: $request->print('<div class="LC_grade_info_links">');
2536: $request->print('</div>');
2537:
2538: $result='<input type="hidden" name="partlist'.$counter.
2539: '" value="'.(join ":",@partlist).'" />'."\n";
2540: $result.='<input type="hidden" name="gradePartRespid'.
2541: '" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
2542: my $ctr = 0;
2543: while ($ctr < scalar(@partlist)) {
2544: $result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
2545: $partlist[$ctr].'" />'."\n";
2546: $ctr++;
2547: }
2548: $request->print($result.''."\n");
2549:
2550: # Done with printing info for one student
2551:
2552: $request->print('</div>');#LC_grade_show_user
2553:
2554:
2555: # print end of form
2556: if ($counter == $total) {
2557: my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
2558: $endform.='<input type="button" value="'.&mt('Save & Next').'" '.
2559: 'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
2560: $total.','.scalar(@partlist).');" target="_self" /> '."\n";
2561: my $ntstu ='<select name="NTSTU">'.
2562: '<option>1</option><option>2</option>'.
2563: '<option>3</option><option>5</option>'.
2564: '<option>7</option><option>10</option></select>'."\n";
2565: my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
2566: $ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
2567: $endform.=&mt('[_1]student(s)',$ntstu);
2568: $endform.=' <input type="button" value="'.&mt('Previous').'" '.
2569: 'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> '."\n".
2570: '<input type="button" value="'.&mt('Next').'" '.
2571: 'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> ';
2572: $endform.='<span class="LC_warning">'.
2573: &mt('(Next and Previous (student) do not save the scores.)').
2574: '</span>'."\n" ;
2575: $endform.="<input type='hidden' value='".&get_increment().
2576: "' name='increment' />";
2577: $endform.='</td></tr></table></form>';
2578: $endform.=&show_grading_menu_form($symb);
2579: $request->print($endform);
2580: }
2581: return '';
2582: }
2583:
2584: sub check_collaborators {
2585: my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
2586: my ($result,@col_fullnames);
2587: my ($classlist,undef,$fullname) = &getclasslist('all','0');
2588: foreach my $part (keys(%$handgrade)) {
2589: my $ncol = &Apache::lonnet::EXT('resource.'.$part.
2590: '.maxcollaborators',
2591: $symb,$udom,$uname);
2592: next if ($ncol <= 0);
2593: $part =~ s/\_/\./g;
2594: next if ($record->{'resource.'.$part.'.collaborators'} eq '');
2595: my (@good_collaborators, @bad_collaborators);
2596: foreach my $possible_collaborator
2597: (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) {
2598: $possible_collaborator =~ s/[\$\^\(\)]//g;
2599: next if ($possible_collaborator eq '');
2600: my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
2601: $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
2602: next if ($co_name eq $uname && $co_dom eq $udom);
2603: # Doing this grep allows 'fuzzy' specification
2604: my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i,
2605: keys(%$classlist));
2606: if (! scalar(@matches)) {
2607: push(@bad_collaborators, $possible_collaborator);
2608: } else {
2609: push(@good_collaborators, @matches);
2610: }
2611: }
2612: if (scalar(@good_collaborators) != 0) {
2613: $result.='<br />'.&mt('Collaborators:').'<ol>';
2614: foreach my $name (@good_collaborators) {
2615: my ($lastname,$givenn) = split(/,/,$$fullname{$name});
2616: push(@col_fullnames, $givenn.' '.$lastname);
2617: $result.='<li>'.$fullname->{$name}.'</li>';
2618: }
2619: $result.='</ol><br />'."\n";
2620: my ($part)=split(/\./,$part);
2621: $result.='<input type="hidden" name="collaborator'.$counter.
2622: '" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
2623: "\n";
2624: }
2625: if (scalar(@bad_collaborators) > 0) {
2626: $result.='<div class="LC_warning">';
2627: $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
2628: $result .= '</div>';
2629: }
2630: if (scalar(@bad_collaborators > $ncol)) {
2631: $result .= '<div class="LC_warning">';
2632: $result .= &mt('This student has submitted too many '.
2633: 'collaborators. Maximum is [_1].',$ncol);
2634: $result .= '</div>';
2635: }
2636: }
2637: return ($result,$fullname,\@col_fullnames);
2638: }
2639:
2640: #--- Retrieve the last submission for all the parts
2641: sub get_last_submission {
2642: my ($returnhash)=@_;
2643: my (@string,$timestamp,%lasthidden);
2644: if ($$returnhash{'version'}) {
2645: my %lasthash=();
2646: my ($version);
2647: for ($version=1;$version<=$$returnhash{'version'};$version++) {
2648: foreach my $key (sort(split(/\:/,
2649: $$returnhash{$version.':keys'}))) {
2650: $lasthash{$key}=$$returnhash{$version.':'.$key};
2651: $timestamp =
2652: &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
2653: }
2654: }
2655: my (%typeparts,%randombytry);
2656: my $showsurv =
2657: &Apache::lonnet::allowed('vas',$env{'request.course.id'});
2658: foreach my $key (sort(keys(%lasthash))) {
2659: if ($key =~ /\.type$/) {
2660: if (($lasthash{$key} eq 'anonsurvey') ||
2661: ($lasthash{$key} eq 'anonsurveycred') ||
2662: ($lasthash{$key} eq 'randomizetry')) {
2663: my ($ign,@parts) = split(/\./,$key);
2664: pop(@parts);
2665: my $id = join('.',@parts);
2666: if ($lasthash{$key} eq 'randomizetry') {
2667: $randombytry{$ign.'.'.$id} = $lasthash{$key};
2668: } else {
2669: unless ($showsurv) {
2670: $typeparts{$ign.'.'.$id} = $lasthash{$key};
2671: }
2672: }
2673: delete($lasthash{$key});
2674: }
2675: }
2676: }
2677: my @hidden = keys(%typeparts);
2678: my @randomize = keys(%randombytry);
2679: foreach my $key (keys(%lasthash)) {
2680: next if ($key !~ /\.submission$/);
2681: my $hide;
2682: if (@hidden) {
2683: foreach my $id (@hidden) {
2684: if ($key =~ /^\Q$id\E/) {
2685: $hide = 'anon';
2686: last;
2687: }
2688: }
2689: }
2690: unless ($hide) {
2691: if (@randomize) {
2692: foreach my $id (@randomize) {
2693: if ($key =~ /^\Q$id\E/) {
2694: $hide = 'rand';
2695: last;
2696: }
2697: }
2698: }
2699: }
2700: my ($partid,$foo) = split(/submission$/,$key);
2701: my $draft = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1: 0;
2702: push(@string, join(':', $key, $hide, $draft, (
2703: ref($lasthash{$key}) eq 'ARRAY' ?
2704: join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
2705: }
2706: }
2707: if (!@string) {
2708: $string[0] =
2709: '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
2710: }
2711: return (\@string,\$timestamp);
2712: }
2713:
2714: #--- High light keywords, with style choosen by user.
2715: sub keywords_highlight {
2716: my $string = shift;
2717: my $size = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
2718: my $styleon = $env{'form.kwstyle'} eq '' ? '' : $env{'form.kwstyle'};
2719: (my $styleoff = $styleon) =~ s/\</\<\//;
2720: my @keylist = split(/[,\s+]/,$env{'form.keywords'});
2721: foreach my $keyword (@keylist) {
2722: $string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
2723: }
2724: return $string;
2725: }
2726:
2727: # For Tasks provide a mechanism to display previous version for one specific student
2728:
2729: sub show_previous_task_version {
2730: my ($request,$symb) = @_;
2731: if ($symb eq '') {
2732: $request->print(
2733: '<span class="LC_error">'.
2734: &mt('Unable to handle ambiguous references.').
2735: '</span>');
2736: return '';
2737: }
2738: my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
2739: my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
2740: if (!&canview($usec)) {
2741: $request->print('<span class="LC_warning">'.
2742: &mt('Unable to view previous version for requested student.').
2743: ' '.&mt('([_1] in section [_2] in course id [_3])',
2744: $uname.':'.$udom,$usec,$env{'request.course.id'}).
2745: '</span>');
2746: return;
2747: }
2748: my $mode = 'both';
2749: my $isTask = ($symb =~/\.task$/);
2750: if ($isTask) {
2751: if ($env{'form.previousversion'} =~ /^\d+$/) {
2752: if ($env{'form.fullname'} eq '') {
2753: $env{'form.fullname'} =
2754: &Apache::loncommon::plainname($uname,$udom,'lastname');
2755: }
2756: my $probtitle=&Apache::lonnet::gettitle($symb);
2757: $request->print("\n\n".
2758: '<div class="LC_grade_show_user">'.
2759: '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
2760: '</h2>'."\n");
2761: &Apache::lonxml::clear_problem_counter();
2762: $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
2763: {'previousversion' => $env{'form.previousversion'} }));
2764: $request->print("\n</div>");
2765: }
2766: }
2767: return;
2768: }
2769:
2770: sub choose_task_version_form {
2771: my ($symb,$uname,$udom,$nomenu) = @_;
2772: my $isTask = ($symb =~/\.task$/);
2773: my ($current,$version,$result,$js,$displayed,$rowtitle);
2774: if ($isTask) {
2775: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
2776: $udom,$uname);
2777: if (($record{'resource.0.version'} eq '') ||
2778: ($record{'resource.0.version'} < 2)) {
2779: return ($record{'resource.0.version'},
2780: $record{'resource.0.version'},$result,$js);
2781: } else {
2782: $current = $record{'resource.0.version'};
2783: }
2784: if ($env{'form.previousversion'}) {
2785: $displayed = $env{'form.previousversion'};
2786: $rowtitle = &mt('Choose another version:')
2787: } else {
2788: $displayed = $current;
2789: $rowtitle = &mt('Show earlier version:');
2790: }
2791: $result = '<div class="LC_left_float">';
2792: my $list;
2793: my $numversions = 0;
2794: for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
2795: if ($i == $current) {
2796: if (!$env{'form.previousversion'} || $nomenu) {
2797: next;
2798: } else {
2799: $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
2800: $numversions ++;
2801: }
2802: } elsif (defined($record{'resource.'.$i.'.0.status'})) {
2803: unless ($i == $env{'form.previousversion'}) {
2804: $numversions ++;
2805: }
2806: $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
2807: }
2808: }
2809: if ($numversions) {
2810: $symb = &HTML::Entities::encode($symb,'<>"&');
2811: $result .=
2812: '<form name="getprev" method="post" action=""'.
2813: ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
2814: &Apache::loncommon::start_data_table().
2815: &Apache::loncommon::start_data_table_row().
2816: '<th align="left">'.$rowtitle.'</th>'.
2817: '<td><select name="version">'.
2818: '<option>'.&mt('Select').'</option>'.
2819: $list.
2820: '</select></td>'.
2821: &Apache::loncommon::end_data_table_row();
2822: unless ($nomenu) {
2823: $result .= &Apache::loncommon::start_data_table_row().
2824: '<th align="left">'.&mt('Open in new window').'</th>'.
2825: '<td><span class="LC_nobreak">'.
2826: '<label><input type="radio" name="prevwin" value="1" />'.
2827: &mt('Yes').'</label>'.
2828: '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
2829: '</span></td>'.
2830: &Apache::loncommon::end_data_table_row();
2831: }
2832: $result .=
2833: &Apache::loncommon::start_data_table_row().
2834: '<th align="left"> </th>'.
2835: '<td>'.
2836: '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
2837: '</td>'.
2838: &Apache::loncommon::end_data_table_row().
2839: &Apache::loncommon::end_data_table().
2840: '</form>';
2841: $js = &previous_display_javascript($nomenu,$current);
2842: } elsif ($displayed && $nomenu) {
2843: $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
2844: } else {
2845: $result .= &mt('No previous versions to show for this student');
2846: }
2847: $result .= '</div>';
2848: }
2849: return ($current,$displayed,$result,$js);
2850: }
2851:
2852: sub previous_display_javascript {
2853: my ($nomenu,$current) = @_;
2854: my $js = <<"JSONE";
2855: <script type="text/javascript">
2856: // <![CDATA[
2857: function previousVersion(uname,udom,symb) {
2858: var current = '$current';
2859: var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
2860: var prevstr = new RegExp("^\\\\d+\$");
2861: if (!prevstr.test(version)) {
2862: return false;
2863: }
2864: var url = '';
2865: if (version == current) {
2866: url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
2867: } else {
2868: url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
2869: }
2870: JSONE
2871: if ($nomenu) {
2872: $js .= <<"JSTWO";
2873: document.location.href = url;
2874: JSTWO
2875: } else {
2876: $js .= <<"JSTHREE";
2877: var newwin = 0;
2878: for (var i=0; i<document.getprev.prevwin.length; i++) {
2879: if (document.getprev.prevwin[i].checked == true) {
2880: newwin = document.getprev.prevwin[i].value;
2881: }
2882: }
2883: if (newwin == 1) {
2884: var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
2885: url = url+'&inhibitmenu=yes';
2886: if (typeof(previousWin) == 'undefined' || previousWin.closed) {
2887: previousWin = window.open(url,'',options,1);
2888: } else {
2889: previousWin.location.href = url;
2890: }
2891: previousWin.focus();
2892: return false;
2893: } else {
2894: document.location.href = url;
2895: return false;
2896: }
2897: JSTHREE
2898: }
2899: $js .= <<"ENDJS";
2900: return false;
2901: }
2902: // ]]>
2903: </script>
2904: ENDJS
2905:
2906: }
2907:
2908: #--- Called from submission routine
2909: sub processHandGrade {
2910: my ($request) = shift;
2911: my ($symb) = &get_symb($request);
2912: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
2913: my $button = $env{'form.gradeOpt'};
2914: my $ngrade = $env{'form.NCT'};
2915: my $ntstu = $env{'form.NTSTU'};
2916: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2917: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2918:
2919: if ($button eq 'Save & Next') {
2920: my $ctr = 0;
2921: while ($ctr < $ngrade) {
2922: my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
2923: my ($errorflag,$pts,$wgt,$numhidden) =
2924: &saveHandGrade($request,$symb,$uname,$udom,$ctr);
2925: if ($errorflag eq 'no_score') {
2926: $ctr++;
2927: next;
2928: }
2929: if ($errorflag eq 'not_allowed') {
2930: $request->print(
2931: '<span class="LC_error">'
2932: .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
2933: .'</span>');
2934: $ctr++;
2935: next;
2936: }
2937: if ($numhidden) {
2938: $request->print(
2939: '<span class="LC_info">'
2940: .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
2941: .'</span><br />');
2942: }
2943: my $includemsg = $env{'form.includemsg'.$ctr};
2944: my ($subject,$message,$msgstatus) = ('','','');
2945: my $restitle = &Apache::lonnet::gettitle($symb);
2946: my ($feedurl,$showsymb) =
2947: &get_feedurl_and_symb($symb,$uname,$udom);
2948: my $messagetail;
2949: if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
2950: $subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
2951: unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
2952: $subject.=' ['.$restitle.']';
2953: my (@msgnum) = split(/,/,$includemsg);
2954: foreach (@msgnum) {
2955: $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
2956: }
2957: $message =&Apache::lonfeedback::clear_out_html($message);
2958: if ($env{'form.withgrades'.$ctr}) {
2959: $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
2960: $messagetail = " for <a href=\"".
2961: $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
2962: }
2963: $msgstatus =
2964: &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
2965: $message.$messagetail,
2966: undef,$feedurl,undef,
2967: undef,undef,$showsymb,
2968: $restitle);
2969: $request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
2970: $msgstatus.'<br />');
2971: }
2972: if ($env{'form.collaborator'.$ctr}) {
2973: my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
2974: foreach my $collabstr (@collabstrs) {
2975: my ($part,@collaborators) = split(/:/,$collabstr);
2976: foreach my $collaborator (@collaborators) {
2977: my ($errorflag,$pts,$wgt) =
2978: &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
2979: $env{'form.unamedom'.$ctr},$part);
2980: if ($errorflag eq 'not_allowed') {
2981: $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
2982: next;
2983: } elsif ($message ne '') {
2984: my ($baseurl,$showsymb) =
2985: &get_feedurl_and_symb($symb,$collaborator,
2986: $udom);
2987: if ($env{'form.withgrades'.$ctr}) {
2988: $messagetail = " for <a href=\"".
2989: $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
2990: }
2991: $msgstatus =
2992: &Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
2993: }
2994: }
2995: }
2996: }
2997: $ctr++;
2998: }
2999: }
3000:
3001: if ($env{'form.handgrade'} eq 'yes') {
3002: # Keywords sorted in alphabatical order
3003: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
3004: my %keyhash = ();
3005: $env{'form.keywords'} =~ s/,\s{0,}|\s+/ /g;
3006: $env{'form.keywords'} =~ s/^\s+|\s+$//;
3007: my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
3008: $env{'form.keywords'} = join(' ',@keywords);
3009: $keyhash{$symb.'_keywords'} = $env{'form.keywords'};
3010: $keyhash{$symb.'_subject'} = $env{'form.msgsub'};
3011: $keyhash{$loginuser.'_kwclr'} = $env{'form.kwclr'};
3012: $keyhash{$loginuser.'_kwsize'} = $env{'form.kwsize'};
3013: $keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
3014:
3015: # message center - Order of message gets changed. Blank line is eliminated.
3016: # New messages are saved in env for the next student.
3017: # All messages are saved in nohist_handgrade.db
3018: my ($ctr,$idx) = (1,1);
3019: while ($ctr <= $env{'form.savemsgN'}) {
3020: if ($env{'form.savemsg'.$ctr} ne '') {
3021: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
3022: $idx++;
3023: }
3024: $ctr++;
3025: }
3026: $ctr = 0;
3027: while ($ctr < $ngrade) {
3028: if ($env{'form.newmsg'.$ctr} ne '') {
3029: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
3030: $env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
3031: $idx++;
3032: }
3033: $ctr++;
3034: }
3035: $env{'form.savemsgN'} = --$idx;
3036: $keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
3037: my $putresult = &Apache::lonnet::put
3038: ('nohist_handgrade',\%keyhash,$cdom,$cnum);
3039: }
3040: # Called by Save & Refresh from Highlight Attribute Window
3041: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
3042: if ($env{'form.refresh'} eq 'on') {
3043: my ($ctr,$total) = (0,0);
3044: while ($ctr < $ngrade) {
3045: $total++ if $env{'form.unamedom'.$ctr} ne '';
3046: $ctr++;
3047: }
3048: $env{'form.NTSTU'}=$ngrade;
3049: $ctr = 0;
3050: while ($ctr < $total) {
3051: my $processUser = $env{'form.unamedom'.$ctr};
3052: ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
3053: $env{'form.fullname'} = $$fullname{$processUser};
3054: &submission($request,$ctr,$total-1);
3055: $ctr++;
3056: }
3057: return '';
3058: }
3059:
3060: # Go directly to grade student - from submission or link from chart page
3061: if ($button eq 'Grade Student') {
3062: (undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
3063: my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
3064: ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
3065: $env{'form.fullname'} = $$fullname{$processUser};
3066: &submission($request,0,0);
3067: return '';
3068: }
3069:
3070: # Get the next/previous one or group of students
3071: my $firststu = $env{'form.unamedom0'};
3072: my $laststu = $env{'form.unamedom'.($ngrade-1)};
3073: my $ctr = 2;
3074: while ($laststu eq '') {
3075: $laststu = $env{'form.unamedom'.($ngrade-$ctr)};
3076: $ctr++;
3077: $laststu = $firststu if ($ctr > $ngrade);
3078: }
3079:
3080: my (@parsedlist,@nextlist);
3081: my ($nextflg) = 0;
3082: foreach my $item (sort
3083: {
3084: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
3085: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
3086: }
3087: return $a cmp $b;
3088: } (keys(%$fullname))) {
3089: if ($nextflg == 1 && $button =~ /Next$/) {
3090: push(@parsedlist,$item);
3091: }
3092: $nextflg = 1 if ($item eq $laststu);
3093: if ($button eq 'Previous') {
3094: last if ($item eq $firststu);
3095: push(@parsedlist,$item);
3096: }
3097: }
3098: $ctr = 0;
3099: @parsedlist = reverse @parsedlist if ($button eq 'Previous');
3100: my $res_error;
3101: my ($partlist) = &response_type($symb,\$res_error);
3102: if ($res_error) {
3103: $request->print(&navmap_errormsg());
3104: return;
3105: }
3106: foreach my $student (@parsedlist) {
3107: my $submitonly=$env{'form.submitonly'};
3108: my ($uname,$udom) = split(/:/,$student);
3109:
3110: if ($submitonly eq 'queued') {
3111: my %queue_status =
3112: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
3113: $udom,$uname);
3114: next if (!defined($queue_status{'gradingqueue'}));
3115: }
3116:
3117: if ($submitonly =~ /^(yes|graded|incorrect)$/) {
3118: # my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
3119: my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
3120: my $submitted = 0;
3121: my $ungraded = 0;
3122: my $incorrect = 0;
3123: foreach my $item (keys(%status)) {
3124: $submitted = 1 if ($status{$item} ne 'nothing');
3125: $ungraded = 1 if ($status{$item} =~ /^ungraded/);
3126: $incorrect = 1 if ($status{$item} =~ /^incorrect/);
3127: my ($foo,$partid,$foo1) = split(/\./,$item);
3128: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
3129: $submitted = 0;
3130: }
3131: }
3132: next if (!$submitted && ($submitonly eq 'yes' ||
3133: $submitonly eq 'incorrect' ||
3134: $submitonly eq 'graded'));
3135: next if (!$ungraded && ($submitonly eq 'graded'));
3136: next if (!$incorrect && $submitonly eq 'incorrect');
3137: }
3138: push(@nextlist,$student) if ($ctr < $ntstu);
3139: last if ($ctr == $ntstu);
3140: $ctr++;
3141: }
3142:
3143: $ctr = 0;
3144: my $total = scalar(@nextlist)-1;
3145:
3146: foreach (sort(@nextlist)) {
3147: my ($uname,$udom,$submitter) = split(/:/);
3148: $env{'form.student'} = $uname;
3149: $env{'form.userdom'} = $udom;
3150: $env{'form.fullname'} = $$fullname{$_};
3151: &submission($request,$ctr,$total);
3152: $ctr++;
3153: }
3154: if ($total < 0) {
3155: my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
3156: $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
3157: $the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
3158: $the_end.=&show_grading_menu_form($symb);
3159: $request->print($the_end);
3160: }
3161: return '';
3162: }
3163:
3164: #---- Save the score and award for each student, if changed
3165: sub saveHandGrade {
3166: my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
3167: my @version_parts;
3168: my $usec = &Apache::lonnet::getsection($domain,$stuname,
3169: $env{'request.course.id'});
3170: if (!&canmodify($usec)) { return('not_allowed'); }
3171: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
3172: my @parts_graded;
3173: my %newrecord = ();
3174: my ($pts,$wgt,$totchg) = ('','',0);
3175: my %aggregate = ();
3176: my $aggregateflag = 0;
3177: if ($env{'form.HIDE'.$newflg}) {
3178: my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
3179: my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
3180: $totchg += $numchgs;
3181: }
3182: my @parts = split(/:/,$env{'form.partlist'.$newflg});
3183: foreach my $new_part (@parts) {
3184: #collaborator ($submi may vary for different parts
3185: if ($submitter && $new_part ne $part) { next; }
3186: my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
3187: if ($dropMenu eq 'excused') {
3188: if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
3189: $newrecord{'resource.'.$new_part.'.solved'} = 'excused';
3190: if (exists($record{'resource.'.$new_part.'.awarded'})) {
3191: $newrecord{'resource.'.$new_part.'.awarded'} = '';
3192: }
3193: $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
3194: }
3195: } elsif ($dropMenu eq 'reset status'
3196: && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
3197: foreach my $key (keys(%record)) {
3198: if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
3199: }
3200: $newrecord{'resource.'.$new_part.'.regrader'}=
3201: "$env{'user.name'}:$env{'user.domain'}";
3202: my $totaltries = $record{'resource.'.$part.'.tries'};
3203:
3204: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
3205: [$new_part]);
3206: my $aggtries =$totaltries;
3207: if ($last_resets{$new_part}) {
3208: $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
3209: $new_part);
3210: }
3211:
3212: my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
3213: if ($aggtries > 0) {
3214: &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
3215: $aggregateflag = 1;
3216: }
3217: } elsif ($dropMenu eq '') {
3218: $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ?
3219: $env{'form.GD_BOX'.$newflg.'_'.$new_part} :
3220: $env{'form.RADVAL'.$newflg.'_'.$new_part});
3221: if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
3222: next;
3223: }
3224: $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 :
3225: $env{'form.WGT'.$newflg.'_'.$new_part};
3226: my $partial= $pts/$wgt;
3227: if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
3228: #do not update score for part if not changed.
3229: &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
3230: next;
3231: } else {
3232: push(@parts_graded,$new_part);
3233: }
3234: if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
3235: $newrecord{'resource.'.$new_part.'.awarded'} = $partial;
3236: }
3237: my $reckey = 'resource.'.$new_part.'.solved';
3238: if ($partial == 0) {
3239: if ($record{$reckey} ne 'incorrect_by_override') {
3240: $newrecord{$reckey} = 'incorrect_by_override';
3241: }
3242: } else {
3243: if ($record{$reckey} ne 'correct_by_override') {
3244: $newrecord{$reckey} = 'correct_by_override';
3245: }
3246: }
3247: if ($submitter &&
3248: ($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
3249: $newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
3250: }
3251: $newrecord{'resource.'.$new_part.'.regrader'}=
3252: "$env{'user.name'}:$env{'user.domain'}";
3253: }
3254: # unless problem has been graded, set flag to version the submitted files
3255: unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/ ||
3256: $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
3257: $dropMenu eq 'reset status')
3258: {
3259: push(@version_parts,$new_part);
3260: }
3261: }
3262: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3263: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3264:
3265: if (%newrecord) {
3266: if (@version_parts) {
3267: my @changed_keys = &version_portfiles(\%record, \@parts_graded,
3268: $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
3269: @newrecord{@changed_keys} = @record{@changed_keys};
3270: foreach my $new_part (@version_parts) {
3271: &handback_files($request,$symb,$stuname,$domain,$newflg,
3272: $new_part,\%newrecord);
3273: }
3274: }
3275: &Apache::lonnet::cstore(\%newrecord,$symb,
3276: $env{'request.course.id'},$domain,$stuname);
3277: &check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
3278: $cdom,$cnum,$domain,$stuname);
3279: }
3280: if ($aggregateflag) {
3281: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
3282: $cdom,$cnum);
3283: }
3284: return ('',$pts,$wgt,$totchg);
3285: }
3286:
3287: sub makehidden {
3288: my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
3289: return unless (ref($record) eq 'HASH');
3290: my %modified;
3291: my $numchanged = 0;
3292: if (exists($record->{$version.':keys'})) {
3293: my $partsregexp = $parts;
3294: $partsregexp =~ s/,/|/g;
3295: foreach my $key (split(/\:/,$record->{$version.':keys'})) {
3296: if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
3297: my $item = $1;
3298: unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
3299: $modified{$key} = $record->{$version.':'.$key};
3300: }
3301: } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
3302: $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
3303: } elsif ($key =~ /^(ip|timestamp|host)$/) {
3304: $modified{$key} = $record->{$version.':'.$key};
3305: }
3306: }
3307: if (keys(%modified)) {
3308: if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
3309: $domain,$stuname,$tolog) eq 'ok') {
3310: $numchanged ++;
3311: }
3312: }
3313: }
3314: return $numchanged;
3315: }
3316:
3317: sub check_and_remove_from_queue {
3318: my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
3319: my @ungraded_parts;
3320: foreach my $part (@{$parts}) {
3321: if ( $record->{ 'resource.'.$part.'.awarded'} eq ''
3322: && $record->{ 'resource.'.$part.'.solved' } ne 'excused'
3323: && $newrecord->{'resource.'.$part.'.awarded'} eq ''
3324: && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
3325: ) {
3326: push(@ungraded_parts, $part);
3327: }
3328: }
3329: if ( !@ungraded_parts ) {
3330: &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
3331: $cnum,$domain,$stuname);
3332: }
3333: }
3334:
3335: sub handback_files {
3336: my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
3337: my $portfolio_root = '/userfiles/portfolio';
3338: my $res_error;
3339: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
3340: if ($res_error) {
3341: $request->print('<br />'.&navmap_errormsg().'<br />');
3342: return;
3343: }
3344: my @handedback;
3345: my $file_msg;
3346: my @part_response_id = &flatten_responseType($responseType);
3347: foreach my $part_response_id (@part_response_id) {
3348: my ($part_id,$resp_id) = @{ $part_response_id };
3349: my $part_resp = join('_',@{ $part_response_id });
3350: if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
3351: for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
3352: # if multiple files are uploaded names will be 'returndoc2','returndoc3'
3353: if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
3354: my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
3355: my ($directory,$answer_file) =
3356: ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
3357: my ($answer_name,$answer_ver,$answer_ext) =
3358: &file_name_version_ext($answer_file);
3359: my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
3360: my $getpropath = 1;
3361: my ($dir_list,$listerror) =
3362: &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
3363: $domain,$stuname,$getpropath);
3364: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
3365: # fix filename
3366: my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
3367: my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
3368: $newflg.'_'.$part_resp.'_returndoc'.$counter,
3369: $save_file_name);
3370: if ($result !~ m|^/uploaded/|) {
3371: $request->print('<br /><span class="LC_error">'.
3372: &mt('An error occurred ([_1]) while trying to upload [_2].',
3373: $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
3374: '</span>');
3375: } else {
3376: # mark the file as read only
3377: push(@handedback,$save_file_name);
3378: if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
3379: $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
3380: }
3381: $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
3382: $file_msg.='<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
3383:
3384: }
3385: $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>'));
3386: }
3387: }
3388: }
3389: }
3390: if (@handedback > 0) {
3391: $request->print('<br />');
3392: my @what = ($symb,$env{'request.course.id'},'handback');
3393: &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
3394: my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});
3395: my ($subject,$message);
3396: if (scalar(@handedback) == 1) {
3397: $subject = &mt_user($user_lh,'File Handed Back by Instructor');
3398: } else {
3399: $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
3400: $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
3401: }
3402: $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
3403: $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
3404: &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
3405: my ($feedurl,$showsymb) =
3406: &get_feedurl_and_symb($symb,$domain,$stuname);
3407: my $restitle = &Apache::lonnet::gettitle($symb);
3408: $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
3409: my $msgstatus =
3410: &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
3411: $message,undef,$feedurl,undef,undef,undef,$showsymb,
3412: $restitle);
3413: if ($msgstatus) {
3414: $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
3415: }
3416: }
3417: return;
3418: }
3419:
3420: sub get_feedurl_and_symb {
3421: my ($symb,$uname,$udom) = @_;
3422: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3423: $url = &Apache::lonnet::clutter($url);
3424: my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
3425: $symb,$udom,$uname);
3426: if ($encrypturl =~ /^yes$/i) {
3427: &Apache::lonenc::encrypted(\$url,1);
3428: &Apache::lonenc::encrypted(\$symb,1);
3429: }
3430: return ($url,$symb);
3431: }
3432:
3433: sub get_submitted_files {
3434: my ($udom,$uname,$partid,$respid,$record) = @_;
3435: my @files;
3436: if ($$record{"resource.$partid.$respid.portfiles"}) {
3437: my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
3438: foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
3439: push(@files,$file_url.$file);
3440: }
3441: }
3442: if ($$record{"resource.$partid.$respid.uploadedurl"}) {
3443: push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
3444: }
3445: return (\@files);
3446: }
3447:
3448: # ----------- Provides number of tries since last reset.
3449: sub get_num_tries {
3450: my ($record,$last_reset,$part) = @_;
3451: my $timestamp = '';
3452: my $num_tries = 0;
3453: if ($$record{'version'}) {
3454: for (my $version=$$record{'version'};$version>=1;$version--) {
3455: if (exists($$record{$version.':resource.'.$part.'.solved'})) {
3456: $timestamp = $$record{$version.':timestamp'};
3457: if ($timestamp > $last_reset) {
3458: $num_tries ++;
3459: } else {
3460: last;
3461: }
3462: }
3463: }
3464: }
3465: return $num_tries;
3466: }
3467:
3468: # ----------- Determine decrements required in aggregate totals
3469: sub decrement_aggs {
3470: my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
3471: my %decrement = (
3472: attempts => 0,
3473: users => 0,
3474: correct => 0
3475: );
3476: $decrement{'attempts'} = $aggtries;
3477: if ($solvedstatus =~ /^correct/) {
3478: $decrement{'correct'} = 1;
3479: }
3480: if ($aggtries == $totaltries) {
3481: $decrement{'users'} = 1;
3482: }
3483: foreach my $type (keys(%decrement)) {
3484: $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
3485: }
3486: return;
3487: }
3488:
3489: # ----------- Determine timestamps for last reset of aggregate totals for parts
3490: sub get_last_resets {
3491: my ($symb,$courseid,$partids) =@_;
3492: my %last_resets;
3493: my $cdom = $env{'course.'.$courseid.'.domain'};
3494: my $cname = $env{'course.'.$courseid.'.num'};
3495: my @keys;
3496: foreach my $part (@{$partids}) {
3497: push(@keys,"$symb\0$part\0resettime");
3498: }
3499: my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
3500: $cdom,$cname);
3501: foreach my $part (@{$partids}) {
3502: $last_resets{$part}=$results{"$symb\0$part\0resettime"};
3503: }
3504: return %last_resets;
3505: }
3506:
3507: # ----------- Handles creating versions for portfolio files as answers
3508: sub version_portfiles {
3509: my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
3510: my $version_parts = join('|',@$v_flag);
3511: my @returned_keys;
3512: my $parts = join('|', @$parts_graded);
3513: my $portfolio_root = '/userfiles/portfolio';
3514: foreach my $key (keys(%$record)) {
3515: my $new_portfiles;
3516: if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
3517: my @versioned_portfiles;
3518: my @portfiles = split(/\s*,\s*/,$$record{$key});
3519: foreach my $file (@portfiles) {
3520: &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
3521: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
3522: my ($answer_name,$answer_ver,$answer_ext) =
3523: &file_name_version_ext($answer_file);
3524: my $getpropath = 1;
3525: my ($dir_list,$listerror) =
3526: &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
3527: $stu_name,$getpropath);
3528: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
3529: my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
3530: if ($new_answer ne 'problem getting file') {
3531: push(@versioned_portfiles, $directory.$new_answer);
3532: &Apache::lonnet::mark_as_readonly($domain,$stu_name,
3533: [$directory.$new_answer],
3534: [$symb,$env{'request.course.id'},'graded']);
3535: }
3536: }
3537: $$record{$key} = join(',',@versioned_portfiles);
3538: push(@returned_keys,$key);
3539: }
3540: }
3541: return (@returned_keys);
3542: }
3543:
3544: sub get_next_version {
3545: my ($answer_name, $answer_ext, $dir_list) = @_;
3546: my $version;
3547: if (ref($dir_list) eq 'ARRAY') {
3548: foreach my $row (@{$dir_list}) {
3549: my ($file) = split(/\&/,$row,2);
3550: my ($file_name,$file_version,$file_ext) =
3551: &file_name_version_ext($file);
3552: if (($file_name eq $answer_name) &&
3553: ($file_ext eq $answer_ext)) {
3554: # gets here if filename and extension match,
3555: # regardless of version
3556: if ($file_version ne '') {
3557: # a versioned file is found so save it for later
3558: if ($file_version > $version) {
3559: $version = $file_version;
3560: }
3561: }
3562: }
3563: }
3564: }
3565: $version ++;
3566: return($version);
3567: }
3568:
3569: sub version_selected_portfile {
3570: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
3571: my ($answer_name,$answer_ver,$answer_ext) =
3572: &file_name_version_ext($file_name);
3573: my $new_answer;
3574: $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
3575: if($env{'form.copy'} eq '-1') {
3576: $new_answer = 'problem getting file';
3577: } else {
3578: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
3579: my $copy_result = &Apache::lonnet::finishuserfileupload(
3580: $stu_name,$domain,'copy',
3581: '/portfolio'.$directory.$new_answer);
3582: }
3583: return ($new_answer);
3584: }
3585:
3586: sub file_name_version_ext {
3587: my ($file)=@_;
3588: my @file_parts = split(/\./, $file);
3589: my ($name,$version,$ext);
3590: if (@file_parts > 1) {
3591: $ext=pop(@file_parts);
3592: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
3593: $version=pop(@file_parts);
3594: }
3595: $name=join('.',@file_parts);
3596: } else {
3597: $name=join('.',@file_parts);
3598: }
3599: return($name,$version,$ext);
3600: }
3601:
3602: #--------------------------------------------------------------------------------------
3603: #
3604: #-------------------------- Next few routines handles grading by section or whole class
3605: #
3606: #--- Javascript to handle grading by section or whole class
3607: sub viewgrades_js {
3608: my ($request) = shift;
3609:
3610: my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
3611: &js_escape(\$alertmsg);
3612: $request->print(<<VIEWJAVASCRIPT);
3613: <script type="text/javascript" language="javascript">
3614: function writePoint(partid,weight,point) {
3615: var radioButton = document.classgrade["RADVAL_"+partid];
3616: var textbox = document.classgrade["TEXTVAL_"+partid];
3617: if (point == "textval") {
3618: point = document.classgrade["TEXTVAL_"+partid].value;
3619: if (isNaN(point) || parseFloat(point) < 0) {
3620: alert("$alertmsg"+parseFloat(point));
3621: var resetbox = false;
3622: for (var i=0; i<radioButton.length; i++) {
3623: if (radioButton[i].checked) {
3624: textbox.value = i;
3625: resetbox = true;
3626: }
3627: }
3628: if (!resetbox) {
3629: textbox.value = "";
3630: }
3631: return;
3632: }
3633: if (parseFloat(point) > parseFloat(weight)) {
3634: var resp = confirm("You entered a value ("+parseFloat(point)+
3635: ") greater than the weight for the part. Accept?");
3636: if (resp == false) {
3637: textbox.value = "";
3638: return;
3639: }
3640: }
3641: for (var i=0; i<radioButton.length; i++) {
3642: radioButton[i].checked=false;
3643: if (parseFloat(point) == i) {
3644: radioButton[i].checked=true;
3645: }
3646: }
3647:
3648: } else {
3649: textbox.value = parseFloat(point);
3650: }
3651: for (i=0;i<document.classgrade.total.value;i++) {
3652: var user = document.classgrade["ctr"+i].value;
3653: user = user.replace(new RegExp(':', 'g'),"_");
3654: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3655: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3656: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3657: if (saveval != "correct") {
3658: scorename.value = point;
3659: if (selname[0].selected != true) {
3660: selname[0].selected = true;
3661: }
3662: }
3663: }
3664: document.classgrade["SELVAL_"+partid][0].selected = true;
3665: }
3666:
3667: function writeRadText(partid,weight) {
3668: var selval = document.classgrade["SELVAL_"+partid];
3669: var radioButton = document.classgrade["RADVAL_"+partid];
3670: var override = document.classgrade["FORCE_"+partid].checked;
3671: var textbox = document.classgrade["TEXTVAL_"+partid];
3672: if (selval[1].selected || selval[2].selected) {
3673: for (var i=0; i<radioButton.length; i++) {
3674: radioButton[i].checked=false;
3675:
3676: }
3677: textbox.value = "";
3678:
3679: for (i=0;i<document.classgrade.total.value;i++) {
3680: var user = document.classgrade["ctr"+i].value;
3681: user = user.replace(new RegExp(':', 'g'),"_");
3682: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3683: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3684: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3685: if ((saveval != "correct") || override) {
3686: scorename.value = "";
3687: if (selval[1].selected) {
3688: selname[1].selected = true;
3689: } else {
3690: selname[2].selected = true;
3691: if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value))
3692: {document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
3693: }
3694: }
3695: }
3696: } else {
3697: for (i=0;i<document.classgrade.total.value;i++) {
3698: var user = document.classgrade["ctr"+i].value;
3699: user = user.replace(new RegExp(':', 'g'),"_");
3700: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3701: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3702: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3703: if ((saveval != "correct") || override) {
3704: scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
3705: selname[0].selected = true;
3706: }
3707: }
3708: }
3709: }
3710:
3711: function changeSelect(partid,user) {
3712: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
3713: var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
3714: var point = textbox.value;
3715: var weight = document.classgrade["weight_"+partid].value;
3716:
3717: if (isNaN(point) || parseFloat(point) < 0) {
3718: alert("$alertmsg"+parseFloat(point));
3719: textbox.value = "";
3720: return;
3721: }
3722: if (parseFloat(point) > parseFloat(weight)) {
3723: var resp = confirm("You entered a value ("+parseFloat(point)+
3724: ") greater than the weight of the part. Accept?");
3725: if (resp == false) {
3726: textbox.value = "";
3727: return;
3728: }
3729: }
3730: selval[0].selected = true;
3731: }
3732:
3733: function changeOneScore(partid,user) {
3734: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
3735: if (selval[1].selected || selval[2].selected) {
3736: document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
3737: if (selval[2].selected) {
3738: document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
3739: }
3740: }
3741: }
3742:
3743: function resetEntry(numpart) {
3744: for (ctpart=0;ctpart<numpart;ctpart++) {
3745: var partid = document.classgrade["partid_"+ctpart].value;
3746: var radioButton = document.classgrade["RADVAL_"+partid];
3747: var textbox = document.classgrade["TEXTVAL_"+partid];
3748: var selval = document.classgrade["SELVAL_"+partid];
3749: for (var i=0; i<radioButton.length; i++) {
3750: radioButton[i].checked=false;
3751:
3752: }
3753: textbox.value = "";
3754: selval[0].selected = true;
3755:
3756: for (i=0;i<document.classgrade.total.value;i++) {
3757: var user = document.classgrade["ctr"+i].value;
3758: user = user.replace(new RegExp(':', 'g'),"_");
3759: var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3760: resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
3761: var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
3762: resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
3763: var saveselval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3764: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3765: if (saveselval == "excused") {
3766: if (selname[1].selected == false) { selname[1].selected = true;}
3767: } else {
3768: if (selname[0].selected == false) {selname[0].selected = true};
3769: }
3770: }
3771: }
3772: }
3773:
3774: </script>
3775: VIEWJAVASCRIPT
3776: }
3777:
3778: #--- show scores for a section or whole class w/ option to change/update a score
3779: sub viewgrades {
3780: my ($request) = shift;
3781: &viewgrades_js($request);
3782:
3783: my ($symb) = &get_symb($request);
3784: #need to make sure we have the correct data for later EXT calls,
3785: #thus invalidate the cache
3786: &Apache::lonnet::devalidatecourseresdata(
3787: $env{'course.'.$env{'request.course.id'}.'.num'},
3788: $env{'course.'.$env{'request.course.id'}.'.domain'});
3789: &Apache::lonnet::clear_EXT_cache_status();
3790:
3791: my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
3792: $result.='<h4><b>'.&mt('Current Resource').':</b> '.$env{'form.probTitle'}.'</h4>'."\n";
3793:
3794: #view individual student submission form - called using Javascript viewOneStudent
3795: $result.=&jscriptNform($symb);
3796:
3797: #beginning of class grading form
3798: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
3799: $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
3800: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
3801: '<input type="hidden" name="command" value="editgrades" />'."\n".
3802: &build_section_inputs().
3803: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
3804: '<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
3805: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
3806:
3807: #retrieve selected groups
3808: my (@groups,$group_display);
3809: @groups = &Apache::loncommon::get_env_multiple('form.group');
3810: if (grep(/^all$/,@groups)) {
3811: @groups = ('all');
3812: } elsif (grep(/^none$/,@groups)) {
3813: @groups = ('none');
3814: } elsif (@groups > 0) {
3815: $group_display = join(', ',@groups);
3816: }
3817:
3818: my ($common_header,$specific_header,@sections,$section_display);
3819: @sections = &Apache::loncommon::get_env_multiple('form.section');
3820: if (grep(/^all$/,@sections)) {
3821: @sections = ('all');
3822: if ($group_display) {
3823: $common_header = &mt('Assign Common Grade to Students in Group(s) [_1]',$group_display);
3824: $specific_header = &mt('Assign Grade to Specific Students in Group(s) [_1]',$group_display);
3825: } elsif (grep(/^none$/,@groups)) {
3826: $common_header = &mt('Assign Common Grade to Students not assigned to any groups');
3827: $specific_header = &mt('Assign Grade to Specific Students not assigned to any groups');
3828: } else {
3829: $common_header = &mt('Assign Common Grade to Class');
3830: $specific_header = &mt('Assign Grade to Specific Students in Class');
3831: }
3832: } elsif (grep(/^none$/,@sections)) {
3833: @sections = ('none');
3834: if ($group_display) {
3835: $common_header = &mt('Assign Common Grade to Students in no Section and in Group(s) [_1]',$group_display);
3836: $specific_header = &mt('Assign Grade to Specific Students in no Section and in Group(s)',$group_display);
3837: } elsif (grep(/^none$/,@groups)) {
3838: $common_header = &mt('Assign Common Grade to Students in no Section and in no Group');
3839: $specific_header = &mt('Assign Grade to Specific Students in no Section and in no Group');
3840: } else {
3841: $common_header = &mt('Assign Common Grade to Students in no Section');
3842: $specific_header = &mt('Assign Grade to Specific Students in no Section');
3843: }
3844: } else {
3845: $section_display = join (", ",@sections);
3846: if ($group_display) {
3847: $common_header = &mt('Assign Common Grade to Students in Section(s) [_1], and in Group(s) [_2]',
3848: $section_display,$group_display);
3849: $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1], and in Group(s) [_2]',
3850: $section_display,$group_display);
3851: } elsif (grep(/^none$/,@groups)) {
3852: $common_header = &mt('Assign Common Grade to Students in Section(s) [_1] and no Group',$section_display);
3853: $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1] and no Group',$section_display);
3854: } else {
3855: $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
3856: $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
3857: }
3858: }
3859: my %submit_types = &substatus_options();
3860: my $submission_status = $submit_types{$env{'form.submitonly'}};
3861:
3862: if ($env{'form.submitonly'} eq 'all') {
3863: $result.= '<h3>'.$common_header.'</h3>';
3864: } else {
3865: $result.= '<h3>'.$common_header.' '.&mt('(submission status: "[_1]")',$submission_status).'</h3>';
3866: }
3867: $result .= &Apache::loncommon::start_data_table();
3868: #radio buttons/text box for assigning points for a section or class.
3869: #handles different parts of a problem
3870: my $res_error;
3871: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
3872: if ($res_error) {
3873: return &navmap_errormsg();
3874: }
3875: my %weight = ();
3876: my $ctsparts = 0;
3877: my %seen = ();
3878: my @part_response_id = &flatten_responseType($responseType);
3879: foreach my $part_response_id (@part_response_id) {
3880: my ($partid,$respid) = @{ $part_response_id };
3881: my $part_resp = join('_',@{ $part_response_id });
3882: next if $seen{$partid};
3883: $seen{$partid}++;
3884: my $handgrade=$$handgrade{$part_resp};
3885: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
3886: $weight{$partid} = $wgt eq '' ? '1' : $wgt;
3887:
3888: my $display_part=&get_display_part($partid,$symb);
3889: my $radio.='<table border="0"><tr>';
3890: my $ctr = 0;
3891: while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
3892: $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
3893: 'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
3894: ','.$ctr.')" />'.$ctr."</label></td>\n";
3895: $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
3896: $ctr++;
3897: }
3898: $radio.='</tr></table>';
3899: my $line = '<input type="text" name="TEXTVAL_'.
3900: $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
3901: $partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
3902: $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
3903: $line.= '<td><b>'.&mt('Grade Status').':</b>'.
3904: '<select name="SELVAL_'.$partid.'" '.
3905: 'onchange="javascript:writeRadText(\''.$partid.'\','.
3906: $weight{$partid}.')"> '.
3907: '<option selected="selected"> </option>'.
3908: '<option value="excused">'.&mt('excused').'</option>'.
3909: '<option value="reset status">'.&mt('reset status').'</option>'.
3910: '</select></td>'.
3911: '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
3912: $line.='<input type="hidden" name="partid_'.
3913: $ctsparts.'" value="'.$partid.'" />'."\n";
3914: $line.='<input type="hidden" name="weight_'.
3915: $partid.'" value="'.$weight{$partid}.'" />'."\n";
3916:
3917: $result.=
3918: &Apache::loncommon::start_data_table_row()."\n".
3919: '<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>'.
3920: &Apache::loncommon::end_data_table_row()."\n";
3921: $ctsparts++;
3922: }
3923: $result.=&Apache::loncommon::end_data_table()."\n".
3924: '<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
3925: $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
3926: 'onclick="javascript:resetEntry('.$ctsparts.');" />';
3927:
3928: #table listing all the students in a section/class
3929: #header of table
3930: if ($env{'form.submitonly'} eq 'all') {
3931: $result.= '<h3>'.$specific_header.'</h3>';
3932: } else {
3933: $result.= '<h3>'.$specific_header.' '.&mt('(submission status: "[_1]")',$submission_status).'</h3>';
3934: }
3935: $result.= &Apache::loncommon::start_data_table().
3936: &Apache::loncommon::start_data_table_header_row().
3937: '<th>'.&mt('No.').'</th>'.
3938: '<th>'.&nameUserString('header')."</th>\n";
3939: my $partserror;
3940: my (@parts) = sort(&getpartlist($symb,\$partserror));
3941: if ($partserror) {
3942: return &navmap_errormsg();
3943: }
3944: my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
3945: my @partids = ();
3946: foreach my $part (@parts) {
3947: my $display=&Apache::lonnet::metadata($url,$part.'.display');
3948: my $narrowtext = &mt('Tries');
3949: $display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
3950: if (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
3951: my ($partid) = &split_part_type($part);
3952: push(@partids,$partid);
3953: my $display_part=&get_display_part($partid,$symb);
3954: if ($display =~ /^Partial Credit Factor/) {
3955: $result.='<th>'.
3956: &mt('Score Part: [_1][_2](weight = [_3])',
3957: $display_part,'<br />',$weight{$partid}).'</th>'."\n";
3958: next;
3959:
3960: } else {
3961: if ($display =~ /Problem Status/) {
3962: my $grade_status_mt = &mt('Grade Status');
3963: $display =~ s{Problem Status}{$grade_status_mt<br />};
3964: }
3965: my $part_mt = &mt('Part:');
3966: $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
3967: }
3968:
3969: $result.='<th>'.$display.'</th>'."\n";
3970: }
3971: $result.=&Apache::loncommon::end_data_table_header_row();
3972:
3973: my %last_resets =
3974: &get_last_resets($symb,$env{'request.course.id'},\@partids);
3975:
3976: #get info for each student
3977: #list all the students - with points and grade status
3978: my (undef,undef,$fullname) = &getclasslist(\@sections,'1',\@groups);
3979: my $ctr = 0;
3980: foreach (sort
3981: {
3982: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
3983: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
3984: }
3985: return $a cmp $b;
3986: } (keys(%$fullname))) {
3987: $result.=&viewstudentgrade($symb,$env{'request.course.id'},
3988: $_,$$fullname{$_},\@parts,\%weight,\$ctr,\%last_resets);
3989: }
3990: $result.=&Apache::loncommon::end_data_table();
3991: $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
3992: $result.='<input type="button" value="'.&mt('Save').'" '.
3993: 'onclick="javascript:submit();" target="_self" /></form>'."\n";
3994: if ($ctr == 0) {
3995: my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
3996: $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>'.
3997: '<span class="LC_warning">';
3998: if ($env{'form.submitonly'} eq 'all') {
3999: if (grep(/^all$/,@sections)) {
4000: if (grep(/^all$/,@groups)) {
4001: $result .= &mt('There are no students with enrollment status [_1] to modify or grade.',
4002: $stu_status);
4003: } elsif (grep(/^none$/,@groups)) {
4004: $result .= &mt('There are no students with no group assigned and with enrollment status [_1] to modify or grade.',
4005: $stu_status);
4006: } else {
4007: $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] to modify or grade.',
4008: $group_display,$stu_status);
4009: }
4010: } elsif (grep(/^none$/,@sections)) {
4011: if (grep(/^all$/,@groups)) {
4012: $result .= &mt('There are no students in no section with enrollment status [_1] to modify or grade.',
4013: $stu_status);
4014: } elsif (grep(/^none$/,@groups)) {
4015: $result .= &mt('There are no students in no section and no group with enrollment status [_1] to modify or grade.',
4016: $stu_status);
4017: } else {
4018: $result .= &mt('There are no students in no section in group(s) [_1] with enrollment status [_2] to modify or grade.',
4019: $group_display,$stu_status);
4020: }
4021: } else {
4022: if (grep(/^all$/,@groups)) {
4023: $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
4024: $section_display,$stu_status);
4025: } elsif (grep(/^none$/,@groups)) {
4026: $result .= &mt('There are no students in section(s) [_1] and no group with enrollment status [_2] to modify or grade.',
4027: $section_display,$stu_status);
4028: } else {
4029: $result .= &mt('There are no students in section(s) [_1] and group(s) [_2] with enrollment status [_3] to modify or grade.',
4030: $section_display,$group_display,$stu_status);
4031: }
4032: }
4033: } else {
4034: if (grep(/^all$/,@sections)) {
4035: if (grep(/^all$/,@groups)) {
4036: $result .= &mt('There are no students with enrollment status [_1] and submission status "[_2]" to modify or grade.',
4037: $stu_status,$submission_status);
4038: } elsif (grep(/^none$/,@groups)) {
4039: $result .= &mt('There are no students with no group assigned with enrollment status [_1] and submission status "[_2]" to modify or grade.',
4040: $stu_status,$submission_status);
4041: } else {
4042: $result .= &mt('There are no students in group(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
4043: $group_display,$stu_status,$submission_status);
4044: }
4045: } elsif (grep(/^none$/,@sections)) {
4046: if (grep(/^all$/,@groups)) {
4047: $result .= &mt('There are no students in no section with enrollment status [_1] and submission status "[_2]" to modify or grade.',
4048: $stu_status,$submission_status);
4049: } elsif (grep(/^none$/,@groups)) {
4050: $result .= &mt('There are no students in no section and no group with enrollment status [_1] and submission status "[_2]" to modify or grade.',
4051: $stu_status,$submission_status);
4052: } else {
4053: $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.',
4054: $group_display,$stu_status,$submission_status);
4055: }
4056: } else {
4057: if (grep(/^all$/,@groups)) {
4058: $result .= &mt('There are no students in section(s) [_1] with enrollment status [_2] and submission status "[_3]" to modify or grade.',
4059: $section_display,$stu_status,$submission_status);
4060: } elsif (grep(/^none$/,@groups)) {
4061: $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.',
4062: $section_display,$stu_status,$submission_status);
4063: } else {
4064: $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.',
4065: $section_display,$group_display,$stu_status,$submission_status);
4066: }
4067: }
4068: }
4069: $result .= '</span><br />';
4070: }
4071: $result.=&show_grading_menu_form($symb);
4072: return $result;
4073: }
4074:
4075: #--- call by previous routine to display each student who satisfies submission filter.
4076: sub viewstudentgrade {
4077: my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
4078: my ($uname,$udom) = split(/:/,$student);
4079: my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
4080: my $submitonly = $env{'form.submitonly'};
4081: unless (($submitonly eq 'all') || ($submitonly eq 'queued')) {
4082: my %partstatus = ();
4083: if (ref($parts) eq 'ARRAY') {
4084: foreach my $apart (@{$parts}) {
4085: my ($part,$type) = &split_part_type($apart);
4086: my ($status,undef) = split(/_/,$record{"resource.$part.solved"},2);
4087: $status = 'nothing' if ($status eq '');
4088: $partstatus{$part} = $status;
4089: my $subkey = "resource.$part.submitted_by";
4090: $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
4091: }
4092: my $submitted = 0;
4093: my $graded = 0;
4094: my $incorrect = 0;
4095: foreach my $key (keys(%partstatus)) {
4096: $submitted = 1 if ($partstatus{$key} ne 'nothing');
4097: $graded = 1 if ($partstatus{$key} =~ /^ungraded/);
4098: $incorrect = 1 if ($partstatus{$key} =~ /^incorrect/);
4099:
4100: my $partid = (split(/\./,$key))[1];
4101: if ($partstatus{'resource.'.$partid.'.'.$key.'.submitted_by'} ne '') {
4102: $submitted = 0;
4103: }
4104: }
4105: return if (!$submitted && ($submitonly eq 'yes' ||
4106: $submitonly eq 'incorrect' ||
4107: $submitonly eq 'graded'));
4108: return if (!$graded && ($submitonly eq 'graded'));
4109: return if (!$incorrect && $submitonly eq 'incorrect');
4110: }
4111: }
4112: if ($submitonly eq 'queued') {
4113: my ($cdom,$cnum) = split(/_/,$courseid);
4114: my %queue_status =
4115: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
4116: $udom,$uname);
4117: return if (!defined($queue_status{'gradingqueue'}));
4118: }
4119: $$ctr++;
4120: my %aggregates = ();
4121: my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
4122: '<input type="hidden" name="ctr'.($$ctr-1).'" value="'.$student.'" />'.
4123: "\n".$$ctr.' </td><td> '.
4124: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
4125: '\');" target="_self">'.$fullname.'</a> '.
4126: '<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
4127: $student=~s/:/_/; # colon doen't work in javascript for names
4128: foreach my $apart (@$parts) {
4129: my ($part,$type) = &split_part_type($apart);
4130: my $score=$record{"resource.$part.$type"};
4131: $result.='<td align="center">';
4132: my ($aggtries,$totaltries);
4133: unless (exists($aggregates{$part})) {
4134: $totaltries = $record{'resource.'.$part.'.tries'};
4135:
4136: $aggtries = $totaltries;
4137: if ($$last_resets{$part}) {
4138: $aggtries = &get_num_tries(\%record,$$last_resets{$part},
4139: $part);
4140: }
4141: $result.='<input type="hidden" name="'.
4142: 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
4143: $result.='<input type="hidden" name="'.
4144: 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
4145: $aggregates{$part} = 1;
4146: }
4147: if ($type eq 'awarded') {
4148: my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
4149: $result.='<input type="hidden" name="'.
4150: 'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
4151: $result.='<input type="text" name="'.
4152: 'GD_'.$student.'_'.$part.'_awarded" '.
4153: 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
4154: '\')" value="'.$pts.'" size="4" /></td>'."\n";
4155: } elsif ($type eq 'solved') {
4156: my ($status,$foo)=split(/_/,$score,2);
4157: $status = 'nothing' if ($status eq '');
4158: $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
4159: $part.'_solved_s" value="'.$status.'" />'."\n";
4160: $result.=' <select name="'.
4161: 'GD_'.$student.'_'.$part.'_solved" '.
4162: 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
4163: $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>'
4164: : '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
4165: $result.='<option value="reset status">'.&mt('reset status').'</option>';
4166: $result.="</select> </td>\n";
4167: } else {
4168: $result.='<input type="hidden" name="'.
4169: 'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
4170: "\n";
4171: $result.='<input type="text" name="'.
4172: 'GD_'.$student.'_'.$part.'_'.$type.'" '.
4173: 'value="'.$score.'" size="4" /></td>'."\n";
4174: }
4175: }
4176: $result.=&Apache::loncommon::end_data_table_row();
4177: return $result;
4178: }
4179:
4180: #--- change scores for all the students in a section/class
4181: # record does not get update if unchanged
4182: sub editgrades {
4183: my ($request) = @_;
4184:
4185: my ($symb)=&get_symb($request);
4186: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
4187: my $title='<h2>'.&mt('Current Grade Status').'</h2>';
4188: $title.='<h4><b>'.&mt('Current Resource').':</b> '.$env{'form.probTitle'}.'</h4>'."\n";
4189: $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
4190:
4191: my $result= &Apache::loncommon::start_data_table().
4192: &Apache::loncommon::start_data_table_header_row().
4193: '<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
4194: '<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
4195: my %scoreptr = (
4196: 'correct' =>'correct_by_override',
4197: 'incorrect'=>'incorrect_by_override',
4198: 'excused' =>'excused',
4199: 'ungraded' =>'ungraded_attempted',
4200: 'credited' =>'credit_attempted',
4201: 'nothing' => '',
4202: );
4203: my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
4204:
4205: my (@partid);
4206: my %weight = ();
4207: my %columns = ();
4208: my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
4209:
4210: my $partserror;
4211: my (@parts) = sort(&getpartlist($symb,\$partserror));
4212: if ($partserror) {
4213: return &navmap_errormsg();
4214: }
4215: my $header;
4216: while ($ctr < $env{'form.totalparts'}) {
4217: my $partid = $env{'form.partid_'.$ctr};
4218: push(@partid,$partid);
4219: $weight{$partid} = $env{'form.weight_'.$partid};
4220: $ctr++;
4221: }
4222: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
4223: my $totcolspan = 0;
4224: foreach my $partid (@partid) {
4225: $header .= '<th align="center">'.&mt('Old Score').'</th>'.
4226: '<th align="center">'.&mt('New Score').'</th>';
4227: $columns{$partid}=2;
4228: foreach my $stores (@parts) {
4229: my ($part,$type) = &split_part_type($stores);
4230: if ($part !~ m/^\Q$partid\E/) { next;}
4231: if ($type eq 'awarded' || $type eq 'solved') { next; }
4232: my $display=&Apache::lonnet::metadata($url,$stores.'.display');
4233: $display =~ s/\[Part: \Q$part\E\]//;
4234: my $narrowtext = &mt('Tries');
4235: $display =~ s/Number of Attempts/$narrowtext/;
4236: $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
4237: '<th align="center">'.&mt('New').' '.$display.'</th>';
4238: $columns{$partid}+=2;
4239: }
4240: $totcolspan += $columns{$partid};
4241: }
4242: foreach my $partid (@partid) {
4243: my $display_part=&get_display_part($partid,$symb);
4244: $result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
4245: &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
4246: '</th>';
4247:
4248: }
4249: $result .= &Apache::loncommon::end_data_table_header_row().
4250: &Apache::loncommon::start_data_table_header_row().
4251: $header.
4252: &Apache::loncommon::end_data_table_header_row();
4253: my @noupdate;
4254: my ($updateCtr,$noupdateCtr) = (1,1);
4255: for ($i=0; $i<$env{'form.total'}; $i++) {
4256: my $user = $env{'form.ctr'.$i};
4257: my ($uname,$udom)=split(/:/,$user);
4258: my %newrecord;
4259: my $updateflag = 0;
4260: my $usec=$classlist->{"$uname:$udom"}[5];
4261: my $canmodify = &canmodify($usec);
4262: my $line = '<td'.($canmodify?'':' colspan="2"').'>'.
4263: &nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
4264: if (!$canmodify) {
4265: push(@noupdate,
4266: $line."<td colspan=\"$totcolspan\"><span class=\"LC_warning\">".
4267: &mt('Not allowed to modify student')."</span></td>");
4268: next;
4269: }
4270: my %aggregate = ();
4271: my $aggregateflag = 0;
4272: $user=~s/:/_/; # colon doen't work in javascript for names
4273: foreach (@partid) {
4274: my $old_aw = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
4275: my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
4276: my $old_part = $old_aw eq '' ? '' : $old_part_pcr;
4277: my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
4278: my $awarded = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
4279: my $pcr = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
4280: my $partial = $awarded eq '' ? '' : $pcr;
4281: my $score;
4282: if ($partial eq '') {
4283: $score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
4284: } elsif ($partial > 0) {
4285: $score = 'correct_by_override';
4286: } elsif ($partial == 0) {
4287: $score = 'incorrect_by_override';
4288: }
4289: my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
4290: $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
4291:
4292: $newrecord{'resource.'.$_.'.regrader'}=
4293: "$env{'user.name'}:$env{'user.domain'}";
4294: if ($dropMenu eq 'reset status' &&
4295: $old_score ne '') { # ignore if no previous attempts => nothing to reset
4296: $newrecord{'resource.'.$_.'.tries'} = '';
4297: $newrecord{'resource.'.$_.'.solved'} = '';
4298: $newrecord{'resource.'.$_.'.award'} = '';
4299: $newrecord{'resource.'.$_.'.awarded'} = '';
4300: $updateflag = 1;
4301: if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
4302: my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
4303: my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
4304: my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
4305: &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
4306: $aggregateflag = 1;
4307: }
4308: } elsif (!($old_part eq $partial && $old_score eq $score)) {
4309: $updateflag = 1;
4310: $newrecord{'resource.'.$_.'.awarded'} = $partial if $partial ne '';
4311: $newrecord{'resource.'.$_.'.solved'} = $score;
4312: $rec_update++;
4313: }
4314:
4315: $line .= '<td align="center">'.$old_aw.' </td>'.
4316: '<td align="center">'.$awarded.
4317: ($score eq 'excused' ? $score : '').' </td>';
4318:
4319:
4320: my $partid=$_;
4321: foreach my $stores (@parts) {
4322: my ($part,$type) = &split_part_type($stores);
4323: if ($part !~ m/^\Q$partid\E/) { next;}
4324: if ($type eq 'awarded' || $type eq 'solved') { next; }
4325: my $old_aw = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
4326: my $awarded = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
4327: if ($awarded ne '' && $awarded ne $old_aw) {
4328: $newrecord{'resource.'.$part.'.'.$type}= $awarded;
4329: $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
4330: $updateflag=1;
4331: }
4332: $line .= '<td align="center">'.$old_aw.' </td>'.
4333: '<td align="center">'.$awarded.' </td>';
4334: }
4335: }
4336: $line.="\n";
4337:
4338: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4339: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4340:
4341: if ($updateflag) {
4342: $count++;
4343: &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
4344: $udom,$uname);
4345:
4346: if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
4347: $cnum,$udom,$uname)) {
4348: # need to figure out if should be in queue.
4349: my %record =
4350: &Apache::lonnet::restore($symb,$env{'request.course.id'},
4351: $udom,$uname);
4352: my $all_graded = 1;
4353: my $none_graded = 1;
4354: foreach my $part (@parts) {
4355: if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
4356: $all_graded = 0;
4357: } else {
4358: $none_graded = 0;
4359: }
4360: }
4361:
4362: if ($all_graded || $none_graded) {
4363: &Apache::bridgetask::remove_from_queue('gradingqueue',
4364: $symb,$cdom,$cnum,
4365: $udom,$uname);
4366: }
4367: }
4368:
4369: $result.=&Apache::loncommon::start_data_table_row().
4370: '<td align="right"> '.$updateCtr.' </td>'.$line.
4371: &Apache::loncommon::end_data_table_row();
4372: $updateCtr++;
4373: } else {
4374: push(@noupdate,
4375: '<td align="right"> '.$noupdateCtr.' </td>'.$line);
4376: $noupdateCtr++;
4377: }
4378: if ($aggregateflag) {
4379: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
4380: $cdom,$cnum);
4381: }
4382: }
4383: if (@noupdate) {
4384: my $numcols=$totcolspan+2;
4385: $result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
4386: '<td align="center" colspan="'.$numcols.'">'.
4387: &mt('No Changes Occurred For the Students Below').
4388: '</td>'.
4389: &Apache::loncommon::end_data_table_row();
4390: foreach my $line (@noupdate) {
4391: $result.=
4392: &Apache::loncommon::start_data_table_row().
4393: $line.
4394: &Apache::loncommon::end_data_table_row();
4395: }
4396: }
4397: $result .= &Apache::loncommon::end_data_table().
4398: &show_grading_menu_form($symb);
4399: my $msg = '<p><b>'.
4400: &mt('Number of records updated = [_1] for [quant,_2,student].',
4401: $rec_update,$count).'</b><br />'.
4402: '<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
4403: '</b></p>';
4404: return $title.$msg.$result;
4405: }
4406:
4407: sub split_part_type {
4408: my ($partstr) = @_;
4409: my ($temp,@allparts)=split(/_/,$partstr);
4410: my $type=pop(@allparts);
4411: my $part=join('_',@allparts);
4412: return ($part,$type);
4413: }
4414:
4415: #------------- end of section for handling grading by section/class ---------
4416: #
4417: #----------------------------------------------------------------------------
4418:
4419:
4420: #----------------------------------------------------------------------------
4421: #
4422: #-------------------------- Next few routines handles grading by csv upload
4423: #
4424: #--- Javascript to handle csv upload
4425: sub csvupload_javascript_reverse_associate {
4426: my $error1=&mt('You need to specify the username or the student/employee ID');
4427: my $error2=&mt('You need to specify at least one grading field');
4428: &js_escape(\$error1);
4429: &js_escape(\$error2);
4430: return(<<ENDPICK);
4431: function verify(vf) {
4432: var foundsomething=0;
4433: var founduname=0;
4434: var foundID=0;
4435: for (i=0;i<=vf.nfields.value;i++) {
4436: tw=eval('vf.f'+i+'.selectedIndex');
4437: if (i==0 && tw!=0) { foundID=1; }
4438: if (i==1 && tw!=0) { founduname=1; }
4439: if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
4440: }
4441: if (founduname==0 && foundID==0) {
4442: alert('$error1');
4443: return;
4444: }
4445: if (foundsomething==0) {
4446: alert('$error2');
4447: return;
4448: }
4449: vf.submit();
4450: }
4451: function flip(vf,tf) {
4452: var nw=eval('vf.f'+tf+'.selectedIndex');
4453: var i;
4454: for (i=0;i<=vf.nfields.value;i++) {
4455: //can not pick the same destination field for both name and domain
4456: if (((i ==0)||(i ==1)) &&
4457: ((tf==0)||(tf==1)) &&
4458: (i!=tf) &&
4459: (eval('vf.f'+i+'.selectedIndex')==nw)) {
4460: eval('vf.f'+i+'.selectedIndex=0;')
4461: }
4462: }
4463: }
4464: ENDPICK
4465: }
4466:
4467: sub csvupload_javascript_forward_associate {
4468: my $error1=&mt('You need to specify the username or the student/employee ID');
4469: my $error2=&mt('You need to specify at least one grading field');
4470: &js_escape(\$error1);
4471: &js_escape(\$error2);
4472: return(<<ENDPICK);
4473: function verify(vf) {
4474: var foundsomething=0;
4475: var founduname=0;
4476: var foundID=0;
4477: for (i=0;i<=vf.nfields.value;i++) {
4478: tw=eval('vf.f'+i+'.selectedIndex');
4479: if (tw==1) { foundID=1; }
4480: if (tw==2) { founduname=1; }
4481: if (tw>3) { foundsomething=1; }
4482: }
4483: if (founduname==0 && foundID==0) {
4484: alert('$error1');
4485: return;
4486: }
4487: if (foundsomething==0) {
4488: alert('$error2');
4489: return;
4490: }
4491: vf.submit();
4492: }
4493: function flip(vf,tf) {
4494: var nw=eval('vf.f'+tf+'.selectedIndex');
4495: var i;
4496: //can not pick the same destination field twice
4497: for (i=0;i<=vf.nfields.value;i++) {
4498: if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
4499: eval('vf.f'+i+'.selectedIndex=0;')
4500: }
4501: }
4502: }
4503: ENDPICK
4504: }
4505:
4506: sub csvuploadmap_header {
4507: my ($request,$symb,$datatoken,$distotal)= @_;
4508: my $javascript;
4509: if ($env{'form.upfile_associate'} eq 'reverse') {
4510: $javascript=&csvupload_javascript_reverse_associate();
4511: } else {
4512: $javascript=&csvupload_javascript_forward_associate();
4513: }
4514:
4515: my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
4516: my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
4517: my $ignore=&mt('Ignore First Line');
4518: $symb = &Apache::lonenc::check_encrypt($symb);
4519: $request->print(<<ENDPICK);
4520: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
4521: <h3><span class="LC_info">Uploading Class Grades</span></h3>
4522: $result
4523: <hr />
4524: <h3>Identify fields</h3>
4525: Total number of records found in file: $distotal <hr />
4526: Enter as many fields as you can. The system will inform you and bring you back
4527: to this page if the data selected is insufficient to run your class.<hr />
4528: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
4529: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
4530: <input type="hidden" name="associate" value="" />
4531: <input type="hidden" name="phase" value="three" />
4532: <input type="hidden" name="datatoken" value="$datatoken" />
4533: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
4534: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
4535: <input type="hidden" name="upfile_associate"
4536: value="$env{'form.upfile_associate'}" />
4537: <input type="hidden" name="symb" value="$symb" />
4538: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
4539: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
4540: <input type="hidden" name="command" value="csvuploadoptions" />
4541: <hr />
4542: <script type="text/javascript" language="Javascript">
4543: $javascript
4544: </script>
4545: ENDPICK
4546: return '';
4547:
4548: }
4549:
4550: sub csvupload_fields {
4551: my ($symb,$errorref) = @_;
4552: my (@parts) = &getpartlist($symb,$errorref);
4553: if (ref($errorref)) {
4554: if ($$errorref) {
4555: return;
4556: }
4557: }
4558:
4559: my @fields=(['ID','Student/Employee ID'],
4560: ['username','Student Username'],
4561: ['domain','Student Domain']);
4562: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
4563: foreach my $part (sort(@parts)) {
4564: my @datum;
4565: my $display=&Apache::lonnet::metadata($url,$part.'.display');
4566: my $name=$part;
4567: if (!$display) { $display = $name; }
4568: @datum=($name,$display);
4569: if ($name=~/^stores_(.*)_awarded/) {
4570: push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
4571: }
4572: push(@fields,\@datum);
4573: }
4574: return (@fields);
4575: }
4576:
4577: sub csvuploadmap_footer {
4578: my ($request,$i,$keyfields) =@_;
4579: my $buttontext = &mt('Assign Grades');
4580: $request->print(<<ENDPICK);
4581: </table>
4582: <input type="hidden" name="nfields" value="$i" />
4583: <input type="hidden" name="keyfields" value="$keyfields" />
4584: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
4585: </form>
4586: ENDPICK
4587: }
4588:
4589: sub checkforfile_js {
4590: my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
4591: &js_escape(\$alertmsg);
4592: my $result =<<CSVFORMJS;
4593: <script type="text/javascript" language="javascript">
4594: function checkUpload(formname) {
4595: if (formname.upfile.value == "") {
4596: alert("$alertmsg");
4597: return false;
4598: }
4599: formname.submit();
4600: }
4601: </script>
4602: CSVFORMJS
4603: return $result;
4604: }
4605:
4606: sub upcsvScores_form {
4607: my ($request) = shift;
4608: my ($symb)=&get_symb($request);
4609: if (!$symb) {return '';}
4610: my $result=&checkforfile_js();
4611: $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
4612: my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
4613: $result.=$table;
4614: $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
4615: $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
4616: $result.=' <b>'.&mt('Specify a file containing the class scores for current resource.').
4617: '</b></td></tr>'."\n";
4618: $result.='<tr bgcolor="#ffffe6"><td>'."\n";
4619: my $upload=&mt("Upload Scores");
4620: my $upfile_select=&Apache::loncommon::upfile_select_html();
4621: my $ignore=&mt('Ignore First Line');
4622: $symb = &Apache::lonenc::check_encrypt($symb);
4623: $result.=<<ENDUPFORM;
4624: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
4625: <input type="hidden" name="symb" value="$symb" />
4626: <input type="hidden" name="command" value="csvuploadmap" />
4627: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
4628: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
4629: $upfile_select
4630: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
4631: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
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></tr></table>'."\n";
4637: $result.='</td></tr></table><br /><br />'."\n";
4638: $result.=&show_grading_menu_form($symb);
4639: return $result;
4640: }
4641:
4642:
4643: sub csvuploadmap {
4644: my ($request)= @_;
4645: my ($symb)=&get_symb($request);
4646: if (!$symb) {return '';}
4647:
4648: my $datatoken;
4649: if (!$env{'form.datatoken'}) {
4650: $datatoken=&Apache::loncommon::upfile_store($request);
4651: } else {
4652: $datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
4653: if ($datatoken ne '') {
4654: &Apache::loncommon::load_tmp_file($request,$datatoken);
4655: }
4656: }
4657: my @records=&Apache::loncommon::upfile_record_sep();
4658: if ($env{'form.noFirstLine'}) { shift(@records); }
4659: &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
4660: my ($i,$keyfields);
4661: if (@records) {
4662: my $fieldserror;
4663: my @fields=&csvupload_fields($symb,\$fieldserror);
4664: if ($fieldserror) {
4665: $request->print(&navmap_errormsg());
4666: return;
4667: }
4668: if ($env{'form.upfile_associate'} eq 'reverse') {
4669: &Apache::loncommon::csv_print_samples($request,\@records);
4670: $i=&Apache::loncommon::csv_print_select_table($request,\@records,
4671: \@fields);
4672: foreach (@fields) { $keyfields.=$_->[0].','; }
4673: chop($keyfields);
4674: } else {
4675: unshift(@fields,['none','']);
4676: $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
4677: \@fields);
4678: foreach my $rec (@records) {
4679: my %temp = &Apache::loncommon::record_sep($rec);
4680: if (%temp) {
4681: $keyfields=join(',',sort(keys(%temp)));
4682: last;
4683: }
4684: }
4685: }
4686: }
4687: &csvuploadmap_footer($request,$i,$keyfields);
4688: $request->print(&show_grading_menu_form($symb));
4689:
4690: return '';
4691: }
4692:
4693: sub csvuploadoptions {
4694: my ($request)= @_;
4695: my ($symb)=&get_symb($request);
4696: my $checked=(($env{'form.noFirstLine'})?'1':'0');
4697: my $ignore=&mt('Ignore First Line');
4698: $request->print(<<ENDPICK);
4699: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
4700: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
4701: <input type="hidden" name="command" value="csvuploadassign" />
4702: <!--
4703: <p>
4704: <label>
4705: <input type="checkbox" name="show_full_results" />
4706: Show a table of all changes
4707: </label>
4708: </p>
4709: -->
4710: <p>
4711: <label>
4712: <input type="checkbox" name="overwite_scores" checked="checked" />
4713: Overwrite any existing score
4714: </label>
4715: </p>
4716: ENDPICK
4717: my %fields=&get_fields();
4718: if (!defined($fields{'domain'})) {
4719: my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
4720: $request->print("\n<p> Users are in domain: ".$domform."</p>\n");
4721: }
4722: foreach my $key (sort(keys(%env))) {
4723: if ($key !~ /^form\.(.*)$/) { next; }
4724: my $cleankey=$1;
4725: if ($cleankey eq 'command') { next; }
4726: $request->print('<input type="hidden" name="'.$cleankey.
4727: '" value="'.$env{$key}.'" />'."\n");
4728: }
4729: # FIXME do a check for any duplicated user ids...
4730: # FIXME do a check for any invalid user ids?...
4731: $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
4732: <hr /></form>'."\n");
4733: $request->print(&show_grading_menu_form($symb));
4734: return '';
4735: }
4736:
4737: sub get_fields {
4738: my %fields;
4739: my @keyfields = split(/\,/,$env{'form.keyfields'});
4740: for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
4741: if ($env{'form.upfile_associate'} eq 'reverse') {
4742: if ($env{'form.f'.$i} ne 'none') {
4743: $fields{$keyfields[$i]}=$env{'form.f'.$i};
4744: }
4745: } else {
4746: if ($env{'form.f'.$i} ne 'none') {
4747: $fields{$env{'form.f'.$i}}=$keyfields[$i];
4748: }
4749: }
4750: }
4751: return %fields;
4752: }
4753:
4754: sub csvuploadassign {
4755: my ($request)= @_;
4756: my ($symb)=&get_symb($request);
4757: if (!$symb) {return '';}
4758: my $error_msg = '';
4759: my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
4760: if ($datatoken ne '') {
4761: &Apache::loncommon::load_tmp_file($request,$datatoken);
4762: }
4763: my @gradedata = &Apache::loncommon::upfile_record_sep();
4764: if ($env{'form.noFirstLine'}) { shift(@gradedata); }
4765: my %fields=&get_fields();
4766: $request->print('<h3>Assigning Grades</h3>');
4767: my $courseid=$env{'request.course.id'};
4768: my ($classlist) = &getclasslist('all',0);
4769: my @notallowed;
4770: my @skipped;
4771: my @warnings;
4772: my $countdone=0;
4773: foreach my $grade (@gradedata) {
4774: my %entries=&Apache::loncommon::record_sep($grade);
4775: my $domain;
4776: if ($entries{$fields{'domain'}}) {
4777: $domain=$entries{$fields{'domain'}};
4778: } else {
4779: $domain=$env{'form.default_domain'};
4780: }
4781: $domain=~s/\s//g;
4782: my $username=$entries{$fields{'username'}};
4783: $username=~s/\s//g;
4784: if (!$username) {
4785: my $id=$entries{$fields{'ID'}};
4786: $id=~s/\s//g;
4787: my %ids=&Apache::lonnet::idget($domain,$id);
4788: $username=$ids{$id};
4789: }
4790: if (!exists($$classlist{"$username:$domain"})) {
4791: my $id=$entries{$fields{'ID'}};
4792: $id=~s/\s//g;
4793: if ($id) {
4794: push(@skipped,"$id:$domain");
4795: } else {
4796: push(@skipped,"$username:$domain");
4797: }
4798: next;
4799: }
4800: my $usec=$classlist->{"$username:$domain"}[5];
4801: if (!&canmodify($usec)) {
4802: push(@notallowed,"$username:$domain");
4803: next;
4804: }
4805: my %points;
4806: my %grades;
4807: foreach my $dest (keys(%fields)) {
4808: if ($dest eq 'ID' || $dest eq 'username' ||
4809: $dest eq 'domain') { next; }
4810: if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
4811: if ($dest=~/stores_(.*)_points/) {
4812: my $part=$1;
4813: my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
4814: $symb,$domain,$username);
4815: if ($wgt) {
4816: $entries{$fields{$dest}}=~s/\s//g;
4817: my $pcr=$entries{$fields{$dest}} / $wgt;
4818: my $award=($pcr == 0) ? 'incorrect_by_override'
4819: : 'correct_by_override';
4820: if ($pcr>1) {
4821: push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
4822: }
4823: $grades{"resource.$part.awarded"}=$pcr;
4824: $grades{"resource.$part.solved"}=$award;
4825: $points{$part}=1;
4826: } else {
4827: $error_msg = "<br />" .
4828: &mt("Some point values were assigned"
4829: ." for problems with a weight "
4830: ."of zero. These values were "
4831: ."ignored.");
4832: }
4833: } else {
4834: if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
4835: if ($dest=~/stores_(.*)_solved/) { if ($points{$1}) {next;} }
4836: my $store_key=$dest;
4837: $store_key=~s/^stores/resource/;
4838: $store_key=~s/_/\./g;
4839: $grades{$store_key}=$entries{$fields{$dest}};
4840: }
4841: }
4842: if (! %grades) {
4843: push(@skipped,&mt("[_1]: no data to save","$username:$domain"));
4844: } else {
4845: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
4846: my $result=&Apache::lonnet::cstore(\%grades,$symb,
4847: $env{'request.course.id'},
4848: $domain,$username);
4849: if ($result eq 'ok') {
4850: $request->print('.');
4851: # Remove from grading queue
4852: &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
4853: $env{'course.'.$env{'request.course.id'}.'.domain'},
4854: $env{'course.'.$env{'request.course.id'}.'.num'},
4855: $domain,$username);
4856: } else {
4857: $request->print("<p><span class=\"LC_error\">".
4858: &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
4859: "$username:$domain",$result)."</span></p>");
4860: }
4861: $request->rflush();
4862: $countdone++;
4863: }
4864: }
4865: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
4866: if (@warnings) {
4867: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
4868: $request->print(join(', ',@warnings));
4869: }
4870: if (@skipped) {
4871: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
4872: $request->print(join(', ',@skipped));
4873: }
4874: if (@notallowed) {
4875: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
4876: $request->print(join(', ',@notallowed));
4877: }
4878: $request->print("<br />\n");
4879: $request->print(&show_grading_menu_form($symb));
4880: return $error_msg;
4881: }
4882: #------------- end of section for handling csv file upload ---------
4883: #
4884: #-------------------------------------------------------------------
4885: #
4886: #-------------- Next few routines handle grading by page/sequence
4887: #
4888: #--- Select a page/sequence and a student to grade
4889: sub pickStudentPage {
4890: my ($request) = shift;
4891:
4892: my $alertmsg = &mt('Please select the student you wish to grade.');
4893: &js_escape(\$alertmsg);
4894: $request->print(<<LISTJAVASCRIPT);
4895: <script type="text/javascript" language="javascript">
4896:
4897: function checkPickOne(formname) {
4898: if (radioSelection(formname.student) == null) {
4899: alert("$alertmsg");
4900: return;
4901: }
4902: ptr = pullDownSelection(formname.selectpage);
4903: formname.page.value = formname["page"+ptr].value;
4904: formname.title.value = formname["title"+ptr].value;
4905: formname.submit();
4906: }
4907:
4908: </script>
4909: LISTJAVASCRIPT
4910: &commonJSfunctions($request);
4911: my ($symb) = &get_symb($request);
4912: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4913: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4914: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4915: my $getgroup = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
4916:
4917: my $result='<h3><span class="LC_info"> '.
4918: &mt('Manual Grading by Page or Sequence').'</span></h3>';
4919:
4920: $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
4921: my $map_error;
4922: my ($titles,$symbx) = &getSymbMap($map_error);
4923: if ($map_error) {
4924: $request->print(&navmap_errormsg());
4925: return;
4926: }
4927: my ($curpage) =&Apache::lonnet::decode_symb($symb);
4928: # my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb);
4929: # my $type=($curpage =~ /\.(page|sequence)/);
4930: my $select = '<select name="selectpage">'."\n";
4931: my $ctr=0;
4932: foreach (@$titles) {
4933: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4934: $select.='<option value="'.$ctr.'" '.
4935: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
4936: '>'.$showtitle.'</option>'."\n";
4937: $ctr++;
4938: }
4939: $select.= '</select>';
4940: $result.=' <b>'.&mt('Problems from').':</b> '.$select."<br />\n";
4941:
4942: $ctr=0;
4943: foreach (@$titles) {
4944: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4945: $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
4946: $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
4947: $ctr++;
4948: }
4949: $result.='<input type="hidden" name="page" />'."\n".
4950: '<input type="hidden" name="title" />'."\n";
4951:
4952: my $options =
4953: '<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
4954: '<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
4955: $result.=' <b>'.&mt('View Problem Text').': </b>'.$options;
4956:
4957: $options =
4958: '<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
4959: '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
4960: '<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
4961: $result.=' <b>'.&mt('Submissions').': </b>'.$options;
4962:
4963: $result.=&build_section_inputs();
4964: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
4965: $result.='<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
4966: '<input type="hidden" name="command" value="displayPage" />'."\n".
4967: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
4968: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
4969:
4970: $result.=' <b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
4971:
4972: $result.=' <input type="button" '.
4973: 'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' →" /><br />'."\n";
4974:
4975: $request->print($result);
4976:
4977: my $studentTable.=' <b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
4978: &Apache::loncommon::start_data_table().
4979: &Apache::loncommon::start_data_table_header_row().
4980: '<th align="right"> '.&mt('No.').'</th>'.
4981: '<th>'.&nameUserString('header').'</th>'.
4982: '<th align="right"> '.&mt('No.').'</th>'.
4983: '<th>'.&nameUserString('header').'</th>'.
4984: &Apache::loncommon::end_data_table_header_row();
4985:
4986: my (undef,undef,$fullname) = &getclasslist($getsec,'1',$getgroup);
4987: my $ptr = 1;
4988: foreach my $student (sort
4989: {
4990: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
4991: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
4992: }
4993: return $a cmp $b;
4994: } (keys(%$fullname))) {
4995: my ($uname,$udom) = split(/:/,$student);
4996: $studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
4997: : '</td>');
4998: $studentTable.='<td align="right">'.$ptr.' </td>';
4999: $studentTable.='<td> <label><input type="radio" name="student" value="'.$student.'" /> '
5000: .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
5001: $studentTable.=
5002: ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row()
5003: : '');
5004: $ptr++;
5005: }
5006: if ($ptr%2 == 0) {
5007: $studentTable.='</td><td> </td><td> </td>'.
5008: &Apache::loncommon::end_data_table_row();
5009: }
5010: $studentTable.=&Apache::loncommon::end_data_table()."\n";
5011: $studentTable.='<input type="button" '.
5012: 'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' →" /></form>'."\n";
5013:
5014: $studentTable.=&show_grading_menu_form($symb);
5015: $request->print($studentTable);
5016:
5017: return '';
5018: }
5019:
5020: sub getSymbMap {
5021: my ($map_error) = @_;
5022: my $navmap = Apache::lonnavmaps::navmap->new();
5023: unless (ref($navmap)) {
5024: if (ref($map_error)) {
5025: $$map_error = 'navmap';
5026: }
5027: return;
5028: }
5029: my %symbx = ();
5030: my @titles = ();
5031: my $minder = 0;
5032:
5033: # Gather every sequence that has problems.
5034: my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
5035: 1,0,1);
5036: for my $sequence ($navmap->getById('0.0'), @sequences) {
5037: if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
5038: my $title = $minder.'.'.
5039: &HTML::Entities::encode($sequence->compTitle(),'"\'&');
5040: push(@titles, $title); # minder in case two titles are identical
5041: $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
5042: $minder++;
5043: }
5044: }
5045: return \@titles,\%symbx;
5046: }
5047:
5048: #
5049: #--- Displays a page/sequence w/wo problems, w/wo submissions
5050: sub displayPage {
5051: my ($request) = shift;
5052:
5053: my ($symb) = &get_symb($request);
5054: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
5055: my $cnum = $env{"course.$env{'request.course.id'}.num"};
5056: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
5057: my $pageTitle = $env{'form.page'};
5058: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
5059: my ($uname,$udom) = split(/:/,$env{'form.student'});
5060: my $usec=$classlist->{$env{'form.student'}}[5];
5061:
5062: #need to make sure we have the correct data for later EXT calls,
5063: #thus invalidate the cache
5064: &Apache::lonnet::devalidatecourseresdata(
5065: $env{'course.'.$env{'request.course.id'}.'.num'},
5066: $env{'course.'.$env{'request.course.id'}.'.domain'});
5067: &Apache::lonnet::clear_EXT_cache_status();
5068:
5069: if (!&canview($usec)) {
5070: $request->print('<span class="LC_warning">'.
5071: &mt('Unable to view requested student. ([_1])',
5072: $env{'form.student'}).
5073: '</span>');
5074: $request->print(&show_grading_menu_form($symb));
5075: return;
5076: }
5077: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
5078: $result.='<h3> '.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
5079: '</h3>'."\n";
5080: $env{'form.CODE'} = uc($env{'form.CODE'});
5081: if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
5082: $result.='<h3> '.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
5083: } else {
5084: delete($env{'form.CODE'});
5085: }
5086: &sub_page_js($request);
5087: $request->print($result);
5088:
5089: my $navmap = Apache::lonnavmaps::navmap->new();
5090: unless (ref($navmap)) {
5091: $request->print(&navmap_errormsg());
5092: $request->print(&show_grading_menu_form($symb));
5093: return;
5094: }
5095: my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
5096: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
5097: if (!$map) {
5098: $request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
5099: $request->print(&show_grading_menu_form($symb));
5100: return;
5101: }
5102: my $iterator = $navmap->getIterator($map->map_start(),
5103: $map->map_finish());
5104:
5105: my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
5106: '<input type="hidden" name="command" value="gradeByPage" />'."\n".
5107: '<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
5108: '<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
5109: '<input type="hidden" name="page" value="'.$pageTitle.'" />'."\n".
5110: '<input type="hidden" name="title" value="'.$env{'form.title'}.'" />'."\n".
5111: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
5112: '<input type="hidden" name="overRideScore" value="no" />'."\n".
5113: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
5114:
5115: if (defined($env{'form.CODE'})) {
5116: $studentTable.=
5117: '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
5118: }
5119: my $checkIcon = '<img alt="'.&mt('Check Mark').
5120: '" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
5121:
5122: $studentTable.=' <span class="LC_info">'.
5123: &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
5124: '</span>'."\n".
5125: &Apache::loncommon::start_data_table().
5126: &Apache::loncommon::start_data_table_header_row().
5127: '<th align="center"> Prob. </th>'.
5128: '<th> '.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
5129: &Apache::loncommon::end_data_table_header_row();
5130:
5131: &Apache::lonxml::clear_problem_counter();
5132: my ($depth,$question,$prob) = (1,1,1);
5133: $iterator->next(); # skip the first BEGIN_MAP
5134: my $curRes = $iterator->next(); # for "current resource"
5135: while ($depth > 0) {
5136: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
5137: if($curRes == $iterator->END_MAP) { $depth--; }
5138:
5139: if (ref($curRes) && $curRes->is_problem()) {
5140: my $parts = $curRes->parts();
5141: my $title = $curRes->compTitle();
5142: my $symbx = $curRes->symb();
5143: $studentTable.=
5144: &Apache::loncommon::start_data_table_row().
5145: '<td align="center" valign="top" >'.$prob.
5146: (scalar(@{$parts}) == 1 ? ''
5147: : '<br />('.&mt('[_1]parts',
5148: scalar(@{$parts}).' ').')'
5149: ).
5150: '</td>';
5151: $studentTable.='<td valign="top">';
5152: my %form = ('CODE' => $env{'form.CODE'},);
5153: if ($env{'form.vProb'} eq 'yes' ) {
5154: $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
5155: undef,'both',\%form);
5156: } else {
5157: my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
5158: $companswer =~ s|<form(.*?)>||g;
5159: $companswer =~ s|</form>||g;
5160: # while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
5161: # $companswer =~ s/$1/ /ms;
5162: # $request->print('match='.$1."<br />\n");
5163: # }
5164: # $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
5165: $studentTable.=' <b>'.$title.'</b> <br /> <b>'.&mt('Correct answer').':</b><br />'.$companswer;
5166: }
5167:
5168: my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
5169:
5170: if ($env{'form.lastSub'} eq 'datesub') {
5171: if ($record{'version'} eq '') {
5172: $studentTable.='<br /> <span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
5173: } else {
5174: my %responseType = ();
5175: foreach my $partid (@{$parts}) {
5176: my @responseIds =$curRes->responseIds($partid);
5177: my @responseType =$curRes->responseType($partid);
5178: my %responseIds;
5179: for (my $i=0;$i<=$#responseIds;$i++) {
5180: $responseIds{$responseIds[$i]}=$responseType[$i];
5181: }
5182: $responseType{$partid} = \%responseIds;
5183: }
5184: $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
5185:
5186: }
5187: } elsif ($env{'form.lastSub'} eq 'all') {
5188: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
5189: my $identifier = (&canmodify($usec)? $prob : '');
5190: $studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
5191: $env{'request.course.id'},
5192: '','.submission',undef,
5193: $usec,$identifier);
5194:
5195: }
5196: if (&canmodify($usec)) {
5197: $studentTable.=&gradeBox_start();
5198: foreach my $partid (@{$parts}) {
5199: $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
5200: $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
5201: $question++;
5202: }
5203: $studentTable.=&gradeBox_end();
5204: $prob++;
5205: }
5206: $studentTable.='</td></tr>';
5207:
5208: }
5209: $curRes = $iterator->next();
5210: }
5211:
5212: $studentTable.=
5213: '</table>'."\n".
5214: '<input type="button" value="'.&mt('Save').'" '.
5215: 'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
5216: '</form>'."\n";
5217: $studentTable.=&show_grading_menu_form($symb);
5218: $request->print($studentTable);
5219:
5220: return '';
5221: }
5222:
5223: sub displaySubByDates {
5224: my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
5225: my $isCODE=0;
5226: my $isTask = ($symb =~/\.task$/);
5227: if (exists($record->{'resource.CODE'})) { $isCODE=1; }
5228: my $studentTable=&Apache::loncommon::start_data_table().
5229: &Apache::loncommon::start_data_table_header_row().
5230: '<th>'.&mt('Date/Time').'</th>'.
5231: ($isCODE?'<th>'.&mt('CODE').'</th>':'').
5232: ($isTask?'<th>'.&mt('Version').'</th>':'').
5233: '<th>'.&mt('Submission').'</th>'.
5234: '<th>'.&mt('Status').'</th>'.
5235: &Apache::loncommon::end_data_table_header_row();
5236: my ($version);
5237: my %mark;
5238: my %orders;
5239: $mark{'correct_by_student'} = $checkIcon;
5240: if (!exists($$record{'1:timestamp'})) {
5241: return '<br /> <span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
5242: }
5243:
5244: my $interaction;
5245: my $no_increment = 1;
5246: my (%lastrndseed,%lasttype);
5247: for ($version=1;$version<=$$record{'version'};$version++) {
5248: my $timestamp =
5249: &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
5250: if (exists($$record{$version.':resource.0.version'})) {
5251: $interaction = $$record{$version.':resource.0.version'};
5252: }
5253: if ($isTask && $env{'form.previousversion'}) {
5254: next unless ($interaction == $env{'form.previousversion'});
5255: }
5256: my $where = ($isTask ? "$version:resource.$interaction"
5257: : "$version:resource");
5258: $studentTable.=&Apache::loncommon::start_data_table_row().
5259: '<td>'.$timestamp.'</td>';
5260: if ($isCODE) {
5261: $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
5262: }
5263: if ($isTask) {
5264: $studentTable.='<td>'.$interaction.'</td>';
5265: }
5266: my @versionKeys = split(/\:/,$$record{$version.':keys'});
5267: my @displaySub = ();
5268: foreach my $partid (@{$parts}) {
5269: my ($hidden,$type);
5270: $type = $$record{$version.':resource.'.$partid.'.type'};
5271: if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
5272: $hidden = 1;
5273: }
5274: my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
5275: : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
5276:
5277: # next if ($$record{"$version:resource.$partid.solved"} eq '');
5278: my $display_part=&get_display_part($partid,$symb);
5279: foreach my $matchKey (@matchKey) {
5280: if (exists($$record{$version.':'.$matchKey}) &&
5281: $$record{$version.':'.$matchKey} ne '') {
5282:
5283: my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
5284: : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
5285: $displaySub[0].='<span class="LC_nobreak">';
5286: $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
5287: .' <span class="LC_internal_info">'
5288: .'('.&mt('Response ID: [_1]',$responseId).')'
5289: .'</span>'
5290: .' <b>';
5291: if ($hidden) {
5292: $displaySub[0].= &mt('Anonymous Survey').'</b>';
5293: } else {
5294: my ($trial,$rndseed,$newvariation);
5295: if ($type eq 'randomizetry') {
5296: $trial = $$record{"$where.$partid.tries"};
5297: $rndseed = $$record{"$where.$partid.rndseed"};
5298: }
5299: if ($$record{"$where.$partid.tries"} eq '') {
5300: $displaySub[0].=&mt('Trial not counted');
5301: } else {
5302: $displaySub[0].=&mt('Trial: [_1]',
5303: $$record{"$where.$partid.tries"});
5304: if (($rndseed ne '') && ($lastrndseed{$partid} ne '')) {
5305: if (($rndseed ne $lastrndseed{$partid}) &&
5306: (($type eq 'randomizetry') || ($lasttype{$partid} eq 'randomizetry'))) {
5307: $newvariation = ' ('.&mt('New variation this try').')';
5308: }
5309: }
5310: $lastrndseed{$partid} = $rndseed;
5311: $lasttype{$partid} = $type;
5312: }
5313: my $responseType=($isTask ? 'Task'
5314: : $responseType->{$partid}->{$responseId});
5315: if (!exists($orders{$partid})) { $orders{$partid}={}; }
5316: if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
5317: $orders{$partid}->{$responseId}=
5318: &get_order($partid,$responseId,$symb,$uname,$udom,
5319: $no_increment,$type,$trial,$rndseed);
5320: }
5321: $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
5322: $displaySub[0].=' '.
5323: &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
5324: }
5325: }
5326: }
5327: if (exists($$record{"$where.$partid.checkedin"})) {
5328: $displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
5329: $$record{"$where.$partid.checkedin"},
5330: $$record{"$where.$partid.checkedin.slot"}).
5331: '<br />';
5332: }
5333: if (exists $$record{"$where.$partid.award"}) {
5334: $displaySub[1].='<b>'.&mt('Part:').'</b> '.$display_part.' '.
5335: lc($$record{"$where.$partid.award"}).' '.
5336: $mark{$$record{"$where.$partid.solved"}}.
5337: '<br />';
5338: }
5339: if (exists $$record{"$where.$partid.regrader"}) {
5340: $displaySub[2].=$$record{"$where.$partid.regrader"}.
5341: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
5342: } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
5343: $displaySub[2].=
5344: $$record{"$version:resource.$partid.regrader"}.
5345: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
5346: }
5347: }
5348: # needed because old essay regrader has not parts info
5349: if (exists $$record{"$version:resource.regrader"}) {
5350: $displaySub[2].=$$record{"$version:resource.regrader"};
5351: }
5352: $studentTable.='<td>'.$displaySub[0].' </td><td>'.$displaySub[1];
5353: if ($displaySub[2]) {
5354: $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
5355: }
5356: $studentTable.=' </td>'.
5357: &Apache::loncommon::end_data_table_row();
5358: }
5359: $studentTable.=&Apache::loncommon::end_data_table();
5360: return $studentTable;
5361: }
5362:
5363: sub updateGradeByPage {
5364: my ($request) = shift;
5365:
5366: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
5367: my $cnum = $env{"course.$env{'request.course.id'}.num"};
5368: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
5369: my $pageTitle = $env{'form.page'};
5370: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
5371: my ($uname,$udom) = split(/:/,$env{'form.student'});
5372: my $usec=$classlist->{$env{'form.student'}}[5];
5373: if (!&canmodify($usec)) {
5374: $request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
5375: $request->print(&show_grading_menu_form($env{'form.symb'}));
5376: return;
5377: }
5378: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
5379: $result.='<h3> '.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
5380: '</h3>'."\n";
5381:
5382: $request->print($result);
5383:
5384:
5385: my $navmap = Apache::lonnavmaps::navmap->new();
5386: unless (ref($navmap)) {
5387: $request->print(&navmap_errormsg());
5388: return;
5389: }
5390: my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
5391: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
5392: if (!$map) {
5393: $request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
5394: my ($symb)=&get_symb($request);
5395: $request->print(&show_grading_menu_form($symb));
5396: return;
5397: }
5398: my $iterator = $navmap->getIterator($map->map_start(),
5399: $map->map_finish());
5400:
5401: my $studentTable=
5402: &Apache::loncommon::start_data_table().
5403: &Apache::loncommon::start_data_table_header_row().
5404: '<th align="center"> '.&mt('Prob.').' </th>'.
5405: '<th> '.&mt('Title').' </th>'.
5406: '<th> '.&mt('Previous Score').' </th>'.
5407: '<th> '.&mt('New Score').' </th>'.
5408: &Apache::loncommon::end_data_table_header_row();
5409:
5410: $iterator->next(); # skip the first BEGIN_MAP
5411: my $curRes = $iterator->next(); # for "current resource"
5412: my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
5413: while ($depth > 0) {
5414: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
5415: if($curRes == $iterator->END_MAP) { $depth--; }
5416:
5417: if (ref($curRes) && $curRes->is_problem()) {
5418: my $parts = $curRes->parts();
5419: my $title = $curRes->compTitle();
5420: my $symbx = $curRes->symb();
5421: $studentTable.=
5422: &Apache::loncommon::start_data_table_row().
5423: '<td align="center" valign="top" >'.$prob.
5424: (scalar(@{$parts}) == 1 ? ''
5425: : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
5426: .')').'</td>';
5427: $studentTable.='<td valign="top"> <b>'.$title.'</b> </td>';
5428:
5429: my %newrecord=();
5430: my @displayPts=();
5431: my %aggregate = ();
5432: my $aggregateflag = 0;
5433: if ($env{'form.HIDE'.$prob}) {
5434: my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
5435: my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
5436: my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
5437: $hideflag += $numchgs;
5438: }
5439: foreach my $partid (@{$parts}) {
5440: my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
5441: my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
5442:
5443: my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ?
5444: $env{'form.WGT'.$question.'_'.$partid} : 1;
5445: my $partial = $newpts/$wgt;
5446: my $score;
5447: if ($partial > 0) {
5448: $score = 'correct_by_override';
5449: } elsif ($newpts ne '') { #empty is taken as 0
5450: $score = 'incorrect_by_override';
5451: }
5452: my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
5453: if ($dropMenu eq 'excused') {
5454: $partial = '';
5455: $score = 'excused';
5456: } elsif ($dropMenu eq 'reset status'
5457: && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
5458: $newrecord{'resource.'.$partid.'.tries'} = 0;
5459: $newrecord{'resource.'.$partid.'.solved'} = '';
5460: $newrecord{'resource.'.$partid.'.award'} = '';
5461: $newrecord{'resource.'.$partid.'.awarded'} = 0;
5462: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
5463: $changeflag++;
5464: $newpts = '';
5465:
5466: my $aggtries = $env{'form.aggtries'.$question.'_'.$partid};
5467: my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
5468: my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
5469: if ($aggtries > 0) {
5470: &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
5471: $aggregateflag = 1;
5472: }
5473: }
5474: my $display_part=&get_display_part($partid,$curRes->symb());
5475: my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
5476: $displayPts[0].=' <b>'.&mt('Part').':</b> '.$display_part.' = '.
5477: (($oldstatus eq 'excused') ? 'excused' : $oldpts).
5478: ' <br />';
5479: $displayPts[1].=' <b>'.&mt('Part').':</b> '.$display_part.' = '.
5480: (($score eq 'excused') ? 'excused' : $newpts).
5481: ' <br />';
5482: $question++;
5483: next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
5484:
5485: $newrecord{'resource.'.$partid.'.awarded'} = $partial if $partial ne '';
5486: $newrecord{'resource.'.$partid.'.solved'} = $score if $score ne '';
5487: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
5488: if (scalar(keys(%newrecord)) > 0);
5489:
5490: $changeflag++;
5491: }
5492: if (scalar(keys(%newrecord)) > 0) {
5493: my %record =
5494: &Apache::lonnet::restore($symbx,$env{'request.course.id'},
5495: $udom,$uname);
5496:
5497: if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
5498: $newrecord{'resource.CODE'} = $env{'form.CODE'};
5499: } elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
5500: $newrecord{'resource.CODE'} = '';
5501: }
5502: &Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
5503: $udom,$uname);
5504: %record = &Apache::lonnet::restore($symbx,
5505: $env{'request.course.id'},
5506: $udom,$uname);
5507: &check_and_remove_from_queue($parts,\%record,undef,$symbx,
5508: $cdom,$cnum,$udom,$uname);
5509: }
5510:
5511: if ($aggregateflag) {
5512: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
5513: $env{'course.'.$env{'request.course.id'}.'.domain'},
5514: $env{'course.'.$env{'request.course.id'}.'.num'});
5515: }
5516:
5517: $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
5518: '<td valign="top">'.$displayPts[1].'</td>'.
5519: &Apache::loncommon::end_data_table_row();
5520:
5521: $prob++;
5522: }
5523: $curRes = $iterator->next();
5524: }
5525:
5526: $studentTable.=&Apache::loncommon::end_data_table();
5527: $studentTable.=&show_grading_menu_form($env{'form.symb'});
5528: my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
5529: &mt('The scores were changed for [quant,_1,problem].',
5530: $changeflag).'<br />');
5531: my $hidemsg=($hideflag == 0 ? '' :
5532: &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
5533: $hideflag).'<br />');
5534: $request->print($hidemsg.$grademsg.$studentTable);
5535:
5536: return '';
5537: }
5538:
5539: #-------- end of section for handling grading by page/sequence ---------
5540: #
5541: #-------------------------------------------------------------------
5542:
5543: #-------------------- Bubblesheet (Scantron) Grading -------------------
5544: #
5545: #------ start of section for handling grading by page/sequence ---------
5546:
5547: =pod
5548:
5549: =head1 Bubble sheet grading routines
5550:
5551: For this documentation:
5552:
5553: 'scanline' refers to the full line of characters
5554: from the file that we are parsing that represents one entire sheet
5555:
5556: 'bubble line' refers to the data
5557: representing the line of bubbles that are on the physical bubblesheet
5558:
5559:
5560: The overall process is that a scanned in bubblesheet data is uploaded
5561: into a course. When a user wants to grade, they select a
5562: sequence/folder of resources, a file of bubblesheet info, and pick
5563: one of the predefined configurations for what each scanline looks
5564: like.
5565:
5566: Next each scanline is checked for any errors of either 'missing
5567: bubbles' (it's an error because it may have been mis-scanned
5568: because too light bubbling), 'double bubble' (each bubble line should
5569: have no more than one letter picked), invalid or duplicated CODE,
5570: invalid student/employee ID
5571:
5572: If the CODE option is used that determines the randomization of the
5573: homework problems, either way the student/employee ID is looked up into a
5574: username:domain.
5575:
5576: During the validation phase the instructor can choose to skip scanlines.
5577:
5578: After the validation phase, there are now 3 bubblesheet files
5579:
5580: scantron_original_filename (unmodified original file)
5581: scantron_corrected_filename (file where the corrected information has replaced the original information)
5582: scantron_skipped_filename (contains the exact text of scanlines that where skipped)
5583:
5584: Also there is a separate hash nohist_scantrondata that contains extra
5585: correction information that isn't representable in the bubblesheet
5586: file (see &scantron_getfile() for more information)
5587:
5588: After all scanlines are either valid, marked as valid or skipped, then
5589: foreach line foreach problem in the picked sequence, an ssi request is
5590: made that simulates a user submitting their selected letter(s) against
5591: the homework problem.
5592:
5593: =over 4
5594:
5595:
5596:
5597: =item defaultFormData
5598:
5599: Returns html hidden inputs used to hold context/default values.
5600:
5601: Arguments:
5602: $symb - $symb of the current resource
5603:
5604: =cut
5605:
5606: sub defaultFormData {
5607: my ($symb)=@_;
5608: return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
5609: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
5610: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
5611: }
5612:
5613:
5614: =pod
5615:
5616: =item getSequenceDropDown
5617:
5618: Return html dropdown of possible sequences to grade
5619:
5620: Arguments:
5621: $symb - $symb of the current resource
5622: $map_error - ref to scalar which will container error if
5623: $navmap object is unavailable in &getSymbMap().
5624:
5625: =cut
5626:
5627: sub getSequenceDropDown {
5628: my ($symb,$map_error)=@_;
5629: my $result='<select name="selectpage">'."\n";
5630: my ($titles,$symbx) = &getSymbMap($map_error);
5631: if (ref($map_error)) {
5632: return if ($$map_error);
5633: }
5634: my ($curpage)=&Apache::lonnet::decode_symb($symb);
5635: my $ctr=0;
5636: foreach (@$titles) {
5637: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
5638: $result.='<option value="'.$$symbx{$_}.'" '.
5639: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
5640: '>'.$showtitle.'</option>'."\n";
5641: $ctr++;
5642: }
5643: $result.= '</select>';
5644: return $result;
5645: }
5646:
5647: my %bubble_lines_per_response; # no. bubble lines for each response.
5648: # key is zero-based index - 0, 1, 2 ...
5649:
5650: my %first_bubble_line; # First bubble line no. for each bubble.
5651:
5652: my %subdivided_bubble_lines; # no. bubble lines for optionresponse,
5653: # matchresponse or rankresponse, where
5654: # an individual response can have multiple
5655: # lines
5656:
5657: my %responsetype_per_response; # responsetype for each response
5658:
5659: my %masterseq_id_responsenum; # src_id (e.g., 12.3_0.11 etc.) for each
5660: # numbered response. Needed when randomorder
5661: # or randompick are in use. Key is ID, value
5662: # is response number.
5663:
5664: # Save and restore the bubble lines array to the form env.
5665:
5666:
5667: sub save_bubble_lines {
5668: foreach my $line (keys(%bubble_lines_per_response)) {
5669: $env{"form.scantron.bubblelines.$line"} = $bubble_lines_per_response{$line};
5670: $env{"form.scantron.first_bubble_line.$line"} =
5671: $first_bubble_line{$line};
5672: $env{"form.scantron.sub_bubblelines.$line"} =
5673: $subdivided_bubble_lines{$line};
5674: $env{"form.scantron.responsetype.$line"} =
5675: $responsetype_per_response{$line};
5676: }
5677: foreach my $resid (keys(%masterseq_id_responsenum)) {
5678: my $line = $masterseq_id_responsenum{$resid};
5679: $env{"form.scantron.residpart.$line"} = $resid;
5680: }
5681: }
5682:
5683:
5684: sub restore_bubble_lines {
5685: my $line = 0;
5686: %bubble_lines_per_response = ();
5687: %masterseq_id_responsenum = ();
5688: while ($env{"form.scantron.bubblelines.$line"}) {
5689: my $value = $env{"form.scantron.bubblelines.$line"};
5690: $bubble_lines_per_response{$line} = $value;
5691: $first_bubble_line{$line} =
5692: $env{"form.scantron.first_bubble_line.$line"};
5693: $subdivided_bubble_lines{$line} =
5694: $env{"form.scantron.sub_bubblelines.$line"};
5695: $responsetype_per_response{$line} =
5696: $env{"form.scantron.responsetype.$line"};
5697: my $id = $env{"form.scantron.residpart.$line"};
5698: $masterseq_id_responsenum{$id} = $line;
5699: $line++;
5700: }
5701: }
5702:
5703: =pod
5704:
5705: =item scantron_filenames
5706:
5707: Returns a list of the scantron files in the current course
5708:
5709: =cut
5710:
5711: sub scantron_filenames {
5712: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5713: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5714: my $getpropath = 1;
5715: my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
5716: $cname,$getpropath);
5717: my @possiblenames;
5718: if (ref($dirlist) eq 'ARRAY') {
5719: foreach my $filename (sort(@{$dirlist})) {
5720: ($filename)=split(/&/,$filename);
5721: if ($filename!~/^scantron_orig_/) { next ; }
5722: $filename=~s/^scantron_orig_//;
5723: push(@possiblenames,$filename);
5724: }
5725: }
5726: return @possiblenames;
5727: }
5728:
5729: =pod
5730:
5731: =item scantron_uploads
5732:
5733: Returns html drop-down list of scantron files in current course.
5734:
5735: Arguments:
5736: $file2grade - filename to set as selected in the dropdown
5737:
5738: =cut
5739:
5740: sub scantron_uploads {
5741: my ($file2grade) = @_;
5742: my $result= '<select name="scantron_selectfile">';
5743: $result.="<option></option>";
5744: foreach my $filename (sort(&scantron_filenames())) {
5745: $result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
5746: }
5747: $result.="</select>";
5748: return $result;
5749: }
5750:
5751: =pod
5752:
5753: =item scantron_scantab
5754:
5755: Returns html drop down of the scantron formats in the scantronformat.tab
5756: file.
5757:
5758: =cut
5759:
5760: sub scantron_scantab {
5761: my $result='<select name="scantron_format">'."\n";
5762: $result.='<option></option>'."\n";
5763: my @lines = &Apache::lonnet::get_scantronformat_file();
5764: if (@lines > 0) {
5765: foreach my $line (@lines) {
5766: next if (($line =~ /^\#/) || ($line eq ''));
5767: my ($name,$descrip)=split(/:/,$line);
5768: $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
5769: }
5770: }
5771: $result.='</select>'."\n";
5772: return $result;
5773: }
5774:
5775: =pod
5776:
5777: =item scantron_CODElist
5778:
5779: Returns html drop down of the saved CODE lists from current course,
5780: generated from earlier printings.
5781:
5782: =cut
5783:
5784: sub scantron_CODElist {
5785: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5786: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5787: my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
5788: my $namechoice='<option></option>';
5789: foreach my $name (sort {uc($a) cmp uc($b)} @names) {
5790: if ($name =~ /^error: 2 /) { next; }
5791: if ($name =~ /^type\0/) { next; }
5792: $namechoice.='<option value="'.$name.'">'.$name.'</option>';
5793: }
5794: $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
5795: return $namechoice;
5796: }
5797:
5798: =pod
5799:
5800: =item scantron_CODEunique
5801:
5802: Returns the html for "Each CODE to be used once" radio.
5803:
5804: =cut
5805:
5806: sub scantron_CODEunique {
5807: my $result='<span class="LC_nobreak">
5808: <label><input type="radio" name="scantron_CODEunique"
5809: value="yes" checked="checked" />'.&mt('Yes').' </label>
5810: </span>
5811: <span class="LC_nobreak">
5812: <label><input type="radio" name="scantron_CODEunique"
5813: value="no" />'.&mt('No').' </label>
5814: </span>';
5815: return $result;
5816: }
5817:
5818: =pod
5819:
5820: =item scantron_selectphase
5821:
5822: Generates the initial screen to start the bubblesheet process.
5823: Allows for - starting a grading run.
5824: - downloading existing scan data (original, corrected
5825: or skipped info)
5826:
5827: - uploading new scan data
5828:
5829: Arguments:
5830: $r - The Apache request object
5831: $file2grade - name of the file that contain the scanned data to score
5832:
5833: =cut
5834:
5835: sub scantron_selectphase {
5836: my ($r,$file2grade) = @_;
5837: my ($symb)=&get_symb($r);
5838: if (!$symb) {return '';}
5839: my $map_error;
5840: my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
5841: if ($map_error) {
5842: $r->print('<br />'.&navmap_errormsg().'<br />');
5843: return;
5844: }
5845: my $default_form_data=&defaultFormData($symb);
5846: my $grading_menu_button=&show_grading_menu_form($symb);
5847: my $file_selector=&scantron_uploads($file2grade);
5848: my $format_selector=&scantron_scantab();
5849: my $CODE_selector=&scantron_CODElist();
5850: my $CODE_unique=&scantron_CODEunique();
5851: my $result;
5852:
5853: $ssi_error = 0;
5854:
5855: if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
5856: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
5857:
5858: # Chunk of form to prompt for a scantron file upload.
5859:
5860: $r->print('
5861: <br />');
5862: my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
5863: my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
5864: my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
5865: &js_escape(\$alertmsg);
5866: my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($cdom);
5867: $r->print(&Apache::lonhtmlcommon::scripttag('
5868: function checkUpload(formname) {
5869: if (formname.upfile.value == "") {
5870: alert("'.$alertmsg.'");
5871: return false;
5872: }
5873: formname.submit();
5874: }'."\n".$formatjs));
5875: $r->print('
5876: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
5877: '.$default_form_data.'
5878: <input name="courseid" type="hidden" value="'.$cnum.'" />
5879: <input name="domainid" type="hidden" value="'.$cdom.'" />
5880: <input name="command" value="scantronupload_save" type="hidden" />
5881: '.&Apache::loncommon::start_data_table('LC_scantron_action').'
5882: '.&Apache::loncommon::start_data_table_header_row().'
5883: <th>
5884: '.&mt('Specify a bubblesheet data file to upload.').'
5885: </th>
5886: '.&Apache::loncommon::end_data_table_header_row().'
5887: '.&Apache::loncommon::start_data_table_row().'
5888: <td>
5889: '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'<br />'."\n");
5890: if ($formatoptions) {
5891: $r->print('</td>
5892: '.&Apache::loncommon::end_data_table_row().'
5893: '.&Apache::loncommon::start_data_table_row().'
5894: <td>'.$formattitle.(' 'x2).$formatoptions.'
5895: </td>
5896: '.&Apache::loncommon::end_data_table_row().'
5897: '.&Apache::loncommon::start_data_table_row().'
5898: <td>'
5899: );
5900: } else {
5901: $r->print(' <br />');
5902: }
5903: $r->print('<input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
5904: </td>
5905: '.&Apache::loncommon::end_data_table_row().'
5906: '.&Apache::loncommon::end_data_table().'
5907: </form>'
5908: );
5909:
5910: }
5911:
5912: # Chunk of form to prompt for a file to grade and how:
5913:
5914: $result.= '
5915: <br />
5916: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
5917: <input type="hidden" name="command" value="scantron_warning" />
5918: '.$default_form_data.'
5919: '.&Apache::loncommon::start_data_table('LC_scantron_action').'
5920: '.&Apache::loncommon::start_data_table_header_row().'
5921: <th colspan="2">
5922: '.&mt('Specify file and which Folder/Sequence to grade').'
5923: </th>
5924: '.&Apache::loncommon::end_data_table_header_row().'
5925: '.&Apache::loncommon::start_data_table_row().'
5926: <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
5927: '.&Apache::loncommon::end_data_table_row().'
5928: '.&Apache::loncommon::start_data_table_row().'
5929: <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
5930: '.&Apache::loncommon::end_data_table_row().'
5931: '.&Apache::loncommon::start_data_table_row().'
5932: <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
5933: '.&Apache::loncommon::end_data_table_row().'
5934: '.&Apache::loncommon::start_data_table_row().'
5935: <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
5936: '.&Apache::loncommon::end_data_table_row().'
5937: '.&Apache::loncommon::start_data_table_row().'
5938: <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
5939: '.&Apache::loncommon::end_data_table_row().'
5940: '.&Apache::loncommon::start_data_table_row().'
5941: <td> '.&mt('Options:').' </td>
5942: <td>
5943: <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
5944: <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
5945: <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
5946: </td>
5947: '.&Apache::loncommon::end_data_table_row().'
5948: '.&Apache::loncommon::start_data_table_row().'
5949: <td colspan="2">
5950: <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
5951: </td>
5952: '.&Apache::loncommon::end_data_table_row().'
5953: '.&Apache::loncommon::end_data_table().'
5954: </form>
5955: ';
5956:
5957: $r->print($result);
5958:
5959: # Chunk of the form that prompts to view a scoring office file,
5960: # corrected file, skipped records in a file.
5961:
5962: $r->print('
5963: <br />
5964: <form action="/adm/grades" name="scantron_download">
5965: '.$default_form_data.'
5966: <input type="hidden" name="command" value="scantron_download" />
5967: '.&Apache::loncommon::start_data_table('LC_scantron_action').'
5968: '.&Apache::loncommon::start_data_table_header_row().'
5969: <th>
5970: '.&mt('Download a scoring office file').'
5971: </th>
5972: '.&Apache::loncommon::end_data_table_header_row().'
5973: '.&Apache::loncommon::start_data_table_row().'
5974: <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).'
5975: <br />
5976: <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
5977: '.&Apache::loncommon::end_data_table_row().'
5978: '.&Apache::loncommon::end_data_table().'
5979: </form>
5980: <br />
5981: ');
5982:
5983: &Apache::lonpickcode::code_list($r,2);
5984:
5985: $r->print('<br /><form method="post" name="checkscantron" action="">'.
5986: $default_form_data."\n".
5987: &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
5988: &Apache::loncommon::start_data_table_header_row()."\n".
5989: '<th colspan="2">
5990: '.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
5991: '</th>'."\n".
5992: &Apache::loncommon::end_data_table_header_row()."\n".
5993: &Apache::loncommon::start_data_table_row()."\n".
5994: '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
5995: '<td> '.$sequence_selector.' </td>'.
5996: &Apache::loncommon::end_data_table_row()."\n".
5997: &Apache::loncommon::start_data_table_row()."\n".
5998: '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
5999: '<td> '.$file_selector.' </td>'."\n".
6000: &Apache::loncommon::end_data_table_row()."\n".
6001: &Apache::loncommon::start_data_table_row()."\n".
6002: '<td> '.&mt('Format of data file:').' </td>'."\n".
6003: '<td> '.$format_selector.' </td>'."\n".
6004: &Apache::loncommon::end_data_table_row()."\n".
6005: &Apache::loncommon::start_data_table_row()."\n".
6006: '<td> '.&mt('Options').' </td>'."\n".
6007: '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
6008: &Apache::loncommon::end_data_table_row()."\n".
6009: &Apache::loncommon::start_data_table_row()."\n".
6010: '<td colspan="2">'."\n".
6011: '<input type="hidden" name="command" value="checksubmissions" />'."\n".
6012: '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
6013: '</td>'."\n".
6014: &Apache::loncommon::end_data_table_row()."\n".
6015: &Apache::loncommon::end_data_table()."\n".
6016: '</form><br />');
6017: $r->print($grading_menu_button);
6018: return;
6019: }
6020:
6021: =pod
6022:
6023: =item username_to_idmap
6024:
6025: creates a hash keyed by student/employee ID with values of the corresponding
6026: student username:domain.
6027:
6028: Arguments:
6029:
6030: $classlist - reference to the class list hash. This is a hash
6031: keyed by student name:domain whose elements are references
6032: to arrays containing various chunks of information
6033: about the student. (See loncoursedata for more info).
6034:
6035: Returns
6036: %idmap - the constructed hash
6037:
6038: =cut
6039:
6040: sub username_to_idmap {
6041: my ($classlist)= @_;
6042: my %idmap;
6043: foreach my $student (keys(%$classlist)) {
6044: my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
6045: unless ($id eq '') {
6046: if (!exists($idmap{$id})) {
6047: $idmap{$id} = $student;
6048: } else {
6049: my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
6050: if ($status eq 'Active') {
6051: $idmap{$id} = $student;
6052: }
6053: }
6054: }
6055: }
6056: return %idmap;
6057: }
6058:
6059: =pod
6060:
6061: =item scantron_fixup_scanline
6062:
6063: Process a requested correction to a scanline.
6064:
6065: Arguments:
6066: $scantron_config - hash from &Apache::lonnet::get_scantron_config()
6067: $scan_data - hash of correction information
6068: (see &scantron_getfile())
6069: $line - existing scanline
6070: $whichline - line number of the passed in scanline
6071: $field - type of change to process
6072: (either
6073: 'ID' -> correct the student/employee ID
6074: 'CODE' -> correct the CODE
6075: 'answer' -> fixup the submitted answers)
6076:
6077: $args - hash of additional info,
6078: - 'ID'
6079: 'newid' -> studentID to use in replacement
6080: of existing one
6081: - 'CODE'
6082: 'CODE_ignore_dup' - set to true if duplicates
6083: should be ignored.
6084: 'CODE' - is new code or 'use_unfound'
6085: if the existing unfound code should
6086: be used as is
6087: - 'answer'
6088: 'response' - new answer or 'none' if blank
6089: 'question' - the bubble line to change
6090: 'questionnum' - the question identifier,
6091: may include subquestion.
6092:
6093: Returns:
6094: $line - the modified scanline
6095:
6096: Side effects:
6097: $scan_data - may be updated
6098:
6099: =cut
6100:
6101:
6102: sub scantron_fixup_scanline {
6103: my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
6104: if ($field eq 'ID') {
6105: if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
6106: return ($line,1,'New value too large');
6107: }
6108: if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
6109: $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
6110: $args->{'newid'});
6111: }
6112: substr($line,$$scantron_config{'IDstart'}-1,
6113: $$scantron_config{'IDlength'})=$args->{'newid'};
6114: if ($args->{'newid'}=~/^\s*$/) {
6115: &scan_data($scan_data,"$whichline.user",
6116: $args->{'username'}.':'.$args->{'domain'});
6117: }
6118: } elsif ($field eq 'CODE') {
6119: if ($args->{'CODE_ignore_dup'}) {
6120: &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
6121: }
6122: &scan_data($scan_data,"$whichline.useCODE",'1');
6123: if ($args->{'CODE'} ne 'use_unfound') {
6124: if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
6125: return ($line,1,'New CODE value too large');
6126: }
6127: if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
6128: $args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
6129: }
6130: substr($line,$$scantron_config{'CODEstart'}-1,
6131: $$scantron_config{'CODElength'})=$args->{'CODE'};
6132: }
6133: } elsif ($field eq 'answer') {
6134: my $length=$scantron_config->{'Qlength'};
6135: my $off=$scantron_config->{'Qoff'};
6136: my $on=$scantron_config->{'Qon'};
6137: my $answer=${off}x$length;
6138: if ($args->{'response'} eq 'none') {
6139: &scan_data($scan_data,
6140: "$whichline.no_bubble.".$args->{'questionnum'},'1');
6141: } else {
6142: if ($on eq 'letter') {
6143: my @alphabet=('A'..'Z');
6144: $answer=$alphabet[$args->{'response'}];
6145: } elsif ($on eq 'number') {
6146: $answer=$args->{'response'}+1;
6147: if ($answer == 10) { $answer = '0'; }
6148: } else {
6149: substr($answer,$args->{'response'},1)=$on;
6150: }
6151: &scan_data($scan_data,
6152: "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
6153: }
6154: my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
6155: substr($line,$where-1,$length)=$answer;
6156: }
6157: return $line;
6158: }
6159:
6160: =pod
6161:
6162: =item scan_data
6163:
6164: Edit or look up an item in the scan_data hash.
6165:
6166: Arguments:
6167: $scan_data - The hash (see scantron_getfile)
6168: $key - shorthand of the key to edit (actual key is
6169: scantronfilename_key).
6170: $data - New value of the hash entry.
6171: $delete - If true, the entry is removed from the hash.
6172:
6173: Returns:
6174: The new value of the hash table field (undefined if deleted).
6175:
6176: =cut
6177:
6178:
6179: sub scan_data {
6180: my ($scan_data,$key,$value,$delete)=@_;
6181: my $filename=$env{'form.scantron_selectfile'};
6182: if (defined($value)) {
6183: $scan_data->{$filename.'_'.$key} = $value;
6184: }
6185: if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
6186: return $scan_data->{$filename.'_'.$key};
6187: }
6188:
6189: # ----- These first few routines are general use routines.----
6190:
6191: # Return the number of occurences of a pattern in a string.
6192:
6193: sub occurence_count {
6194: my ($string, $pattern) = @_;
6195:
6196: my @matches = ($string =~ /$pattern/g);
6197:
6198: return scalar(@matches);
6199: }
6200:
6201:
6202: # Take a string known to have digits and convert all the
6203: # digits into letters in the range J,A..I.
6204:
6205: sub digits_to_letters {
6206: my ($input) = @_;
6207:
6208: my @alphabet = ('J', 'A'..'I');
6209:
6210: my @input = split(//, $input);
6211: my $output ='';
6212: for (my $i = 0; $i < scalar(@input); $i++) {
6213: if ($input[$i] =~ /\d/) {
6214: $output .= $alphabet[$input[$i]];
6215: } else {
6216: $output .= $input[$i];
6217: }
6218: }
6219: return $output;
6220: }
6221:
6222: =pod
6223:
6224: =item scantron_parse_scanline
6225:
6226: Decodes a scanline from the selected scantron file
6227:
6228: Arguments:
6229: line - The text of the scantron file line to process
6230: whichline - Line number
6231: scantron_config - Hash describing the format of the scantron lines.
6232: scan_data - Hash of extra information about the scanline
6233: (see scantron_getfile for more information)
6234: just_header - True if should not process question answers but only
6235: the stuff to the left of the answers.
6236: randomorder - True if randomorder in use
6237: randompick - True if randompick in use
6238: sequence - Exam folder URL
6239: master_seq - Ref to array containing symbs in exam folder
6240: symb_to_resource - Ref to hash of symbs for resources in exam folder
6241: (corresponding values are resource objects)
6242: partids_by_symb - Ref to hash of symb -> array ref of partIDs
6243: orderedforcode - Ref to hash of arrays. keys are CODEs and values
6244: are refs to an array of resource objects, ordered
6245: according to order used for CODE, when randomorder
6246: and or randompick are in use.
6247: respnumlookup - Ref to hash mapping question numbers in bubble lines
6248: for current line to question number used for same question
6249: in "Master Sequence" (as seen by Course Coordinator).
6250: startline - Ref to hash where key is question number (0 is first)
6251: and value is number of first bubble line for current
6252: student or code-based randompick and/or randomorder.
6253: totalref - Ref of scalar used to score total number of bubble
6254: lines needed for responses in a scan line (used when
6255: randompick in use.
6256:
6257: Returns:
6258: Hash containing the result of parsing the scanline
6259:
6260: Keys are all proceeded by the string 'scantron.'
6261:
6262: CODE - the CODE in use for this scanline
6263: useCODE - 1 if the CODE is invalid but it usage has been forced
6264: by the operator
6265: CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
6266: CODEs were selected, but the usage has been
6267: forced by the operator
6268: ID - student/employee ID
6269: PaperID - if used, the ID number printed on the sheet when the
6270: paper was scanned
6271: FirstName - first name from the sheet
6272: LastName - last name from the sheet
6273:
6274: if just_header was not true these key may also exist
6275:
6276: missingerror - a list of bubble ranges that are considered to be answers
6277: to a single question that don't have any bubbles filled in.
6278: Of the form questionnumber:firstbubblenumber:count.
6279: doubleerror - a list of bubble ranges that are considered to be answers
6280: to a single question that have more than one bubble filled in.
6281: Of the form questionnumber::firstbubblenumber:count
6282:
6283: In the above, count is the number of bubble responses in the
6284: input line needed to represent the possible answers to the question.
6285: e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
6286: per line would have count = 2.
6287:
6288: maxquest - the number of the last bubble line that was parsed
6289:
6290: (<number> starts at 1)
6291: <number>.answer - zero or more letters representing the selected
6292: letters from the scanline for the bubble line
6293: <number>.
6294: if blank there was either no bubble or there where
6295: multiple bubbles, (consult the keys missingerror and
6296: doubleerror if this is an error condition)
6297:
6298: =cut
6299:
6300: sub scantron_parse_scanline {
6301: my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
6302: $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
6303: $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
6304:
6305: my %record;
6306: my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
6307: if (!($$scantron_config{'CODElocation'} eq 0 ||
6308: $$scantron_config{'CODElocation'} eq 'none')) {
6309: if ($$scantron_config{'CODElocation'} < 0 ||
6310: $$scantron_config{'CODElocation'} eq 'letter' ||
6311: $$scantron_config{'CODElocation'} eq 'number') {
6312: $record{'scantron.CODE'}=substr($data,
6313: $$scantron_config{'CODEstart'}-1,
6314: $$scantron_config{'CODElength'});
6315: if (&scan_data($scan_data,"$whichline.useCODE")) {
6316: $record{'scantron.useCODE'}=1;
6317: }
6318: if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
6319: $record{'scantron.CODE_ignore_dup'}=1;
6320: }
6321: } else {
6322: #FIXME interpret first N questions
6323: }
6324: }
6325: $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
6326: $$scantron_config{'IDlength'});
6327: $record{'scantron.PaperID'}=
6328: substr($data,$$scantron_config{'PaperID'}-1,
6329: $$scantron_config{'PaperIDlength'});
6330: $record{'scantron.FirstName'}=
6331: substr($data,$$scantron_config{'FirstName'}-1,
6332: $$scantron_config{'FirstNamelength'});
6333: $record{'scantron.LastName'}=
6334: substr($data,$$scantron_config{'LastName'}-1,
6335: $$scantron_config{'LastNamelength'});
6336: if ($just_header) { return \%record; }
6337:
6338: my @alphabet=('A'..'Z');
6339: my $questnum=0;
6340: my $ansnum =1; # Multiple 'answer lines'/question.
6341:
6342: my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
6343: if ($randompick || $randomorder) {
6344: my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
6345: $master_seq,$symb_to_resource,
6346: $partids_by_symb,$orderedforcode,
6347: $respnumlookup,$startline);
6348: if ($total) {
6349: $lastpos = $total*$$scantron_config{'Qlength'};
6350: }
6351: if (ref($totalref)) {
6352: $$totalref = $total;
6353: }
6354: }
6355: my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos); # Answers
6356: chomp($questions); # Get rid of any trailing \n.
6357: $questions =~ s/\r$//; # Get rid of trailing \r too (MAC or Win uploads).
6358: while (length($questions)) {
6359: my $answers_needed;
6360: if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
6361: $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
6362: } else {
6363: $answers_needed = $bubble_lines_per_response{$questnum};
6364: }
6365: my $answer_length = ($$scantron_config{'Qlength'} * $answers_needed)
6366: || 1;
6367: $questnum++;
6368: my $quest_id = $questnum;
6369: my $currentquest = substr($questions,0,$answer_length);
6370: $questions = substr($questions,$answer_length);
6371: if (length($currentquest) < $answer_length) { next; }
6372:
6373: my $subdivided;
6374: if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
6375: $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
6376: } else {
6377: $subdivided = $subdivided_bubble_lines{$questnum-1};
6378: }
6379: if ($subdivided =~ /,/) {
6380: my $subquestnum = 1;
6381: my $subquestions = $currentquest;
6382: my @subanswers_needed = split(/,/,$subdivided);
6383: foreach my $subans (@subanswers_needed) {
6384: my $subans_length =
6385: ($$scantron_config{'Qlength'} * $subans) || 1;
6386: my $currsubquest = substr($subquestions,0,$subans_length);
6387: $subquestions = substr($subquestions,$subans_length);
6388: $quest_id = "$questnum.$subquestnum";
6389: if (($$scantron_config{'Qon'} eq 'letter') ||
6390: ($$scantron_config{'Qon'} eq 'number')) {
6391: $ansnum = &scantron_validator_lettnum($ansnum,
6392: $questnum,$quest_id,$subans,$currsubquest,$whichline,
6393: \@alphabet,\%record,$scantron_config,$scan_data,
6394: $randomorder,$randompick,$respnumlookup);
6395: } else {
6396: $ansnum = &scantron_validator_positional($ansnum,
6397: $questnum,$quest_id,$subans,$currsubquest,$whichline,
6398: \@alphabet,\%record,$scantron_config,$scan_data,
6399: $randomorder,$randompick,$respnumlookup);
6400: }
6401: $subquestnum ++;
6402: }
6403: } else {
6404: if (($$scantron_config{'Qon'} eq 'letter') ||
6405: ($$scantron_config{'Qon'} eq 'number')) {
6406: $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
6407: $quest_id,$answers_needed,$currentquest,$whichline,
6408: \@alphabet,\%record,$scantron_config,$scan_data,
6409: $randomorder,$randompick,$respnumlookup);
6410: } else {
6411: $ansnum = &scantron_validator_positional($ansnum,$questnum,
6412: $quest_id,$answers_needed,$currentquest,$whichline,
6413: \@alphabet,\%record,$scantron_config,$scan_data,
6414: $randomorder,$randompick,$respnumlookup);
6415: }
6416: }
6417: }
6418: $record{'scantron.maxquest'}=$questnum;
6419: return \%record;
6420: }
6421:
6422: sub get_master_seq {
6423: my ($resources,$master_seq,$symb_to_resource) = @_;
6424: return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') &&
6425: (ref($symb_to_resource) eq 'HASH'));
6426: my $resource_error;
6427: foreach my $resource (@{$resources}) {
6428: my $ressymb;
6429: if (ref($resource)) {
6430: $ressymb = $resource->symb();
6431: push(@{$master_seq},$ressymb);
6432: $symb_to_resource->{$ressymb} = $resource;
6433: } else {
6434: $resource_error = 1;
6435: last;
6436: }
6437: }
6438: return $resource_error;
6439: }
6440:
6441: sub get_respnum_lookups {
6442: my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
6443: $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
6444: return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
6445: (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
6446: (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
6447: (ref($startline) eq 'HASH'));
6448: my ($user,$scancode);
6449: if ((exists($record->{'scantron.CODE'})) &&
6450: (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
6451: $scancode = $record->{'scantron.CODE'};
6452: } else {
6453: $user = &scantron_find_student($record,$scan_data,$idmap,$line);
6454: }
6455: my @mapresources =
6456: &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
6457: $orderedforcode);
6458: my $total = 0;
6459: my $count = 0;
6460: foreach my $resource (@mapresources) {
6461: my $id = $resource->id();
6462: my $symb = $resource->symb();
6463: if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
6464: foreach my $partid (@{$partids_by_symb->{$symb}}) {
6465: my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
6466: if ($respnum ne '') {
6467: $respnumlookup->{$count} = $respnum;
6468: $startline->{$count} = $total;
6469: $total += $bubble_lines_per_response{$respnum};
6470: $count ++;
6471: }
6472: }
6473: }
6474: }
6475: return $total;
6476: }
6477:
6478: sub scantron_validator_lettnum {
6479: my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
6480: $alphabet,$record,$scantron_config,$scan_data,$randomorder,
6481: $randompick,$respnumlookup) = @_;
6482:
6483: # Qon 'letter' implies for each slot in currquest we have:
6484: # ? or * for doubles, a letter in A-Z for a bubble, and
6485: # about anything else (esp. a value of Qoff) for missing
6486: # bubbles.
6487: #
6488: # Qon 'number' implies each slot gives a digit that indexes the
6489: # bubbles filled, or Qoff, or a non-number for unbubbled lines,
6490: # and * or ? for double bubbles on a single line.
6491: #
6492:
6493: my $matchon;
6494: if ($$scantron_config{'Qon'} eq 'letter') {
6495: $matchon = '[A-Z]';
6496: } elsif ($$scantron_config{'Qon'} eq 'number') {
6497: $matchon = '\d';
6498: }
6499: my $occurrences = 0;
6500: my $responsenum = $questnum-1;
6501: if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
6502: $responsenum = $respnumlookup->{$questnum-1}
6503: }
6504: if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
6505: ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
6506: ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
6507: ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
6508: ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
6509: ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
6510: my @singlelines = split('',$currquest);
6511: foreach my $entry (@singlelines) {
6512: $occurrences = &occurence_count($entry,$matchon);
6513: if ($occurrences > 1) {
6514: last;
6515: }
6516: }
6517: } else {
6518: $occurrences = &occurence_count($currquest,$matchon);
6519: }
6520: if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
6521: push(@{$record->{'scantron.doubleerror'}},$quest_id);
6522: for (my $ans=0; $ans<$answers_needed; $ans++) {
6523: my $bubble = substr($currquest,$ans,1);
6524: if ($bubble =~ /$matchon/ ) {
6525: if ($$scantron_config{'Qon'} eq 'number') {
6526: if ($bubble == 0) {
6527: $bubble = 10;
6528: }
6529: $record->{"scantron.$ansnum.answer"} =
6530: $alphabet->[$bubble-1];
6531: } else {
6532: $record->{"scantron.$ansnum.answer"} = $bubble;
6533: }
6534: } else {
6535: $record->{"scantron.$ansnum.answer"}='';
6536: }
6537: $ansnum++;
6538: }
6539: } elsif (!defined($currquest)
6540: || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
6541: || (&occurence_count($currquest,$matchon) == 0)) {
6542: for (my $ans=0; $ans<$answers_needed; $ans++ ) {
6543: $record->{"scantron.$ansnum.answer"}='';
6544: $ansnum++;
6545: }
6546: if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
6547: push(@{$record->{'scantron.missingerror'}},$quest_id);
6548: }
6549: } else {
6550: if ($$scantron_config{'Qon'} eq 'number') {
6551: $currquest = &digits_to_letters($currquest);
6552: }
6553: for (my $ans=0; $ans<$answers_needed; $ans++) {
6554: my $bubble = substr($currquest,$ans,1);
6555: $record->{"scantron.$ansnum.answer"} = $bubble;
6556: $ansnum++;
6557: }
6558: }
6559: return $ansnum;
6560: }
6561:
6562: sub scantron_validator_positional {
6563: my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
6564: $whichline,$alphabet,$record,$scantron_config,$scan_data,
6565: $randomorder,$randompick,$respnumlookup) = @_;
6566:
6567: # Otherwise there's a positional notation;
6568: # each bubble line requires Qlength items, and there are filled in
6569: # bubbles for each case where there 'Qon' characters.
6570: #
6571:
6572: my @array=split($$scantron_config{'Qon'},$currquest,-1);
6573:
6574: # If the split only gives us one element.. the full length of the
6575: # answer string, no bubbles are filled in:
6576:
6577: if ($answers_needed eq '') {
6578: return;
6579: }
6580:
6581: if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
6582: for (my $ans=0; $ans<$answers_needed; $ans++ ) {
6583: $record->{"scantron.$ansnum.answer"}='';
6584: $ansnum++;
6585: }
6586: if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
6587: push(@{$record->{"scantron.missingerror"}},$quest_id);
6588: }
6589: } elsif (scalar(@array) == 2) {
6590: my $location = length($array[0]);
6591: my $line_num = int($location / $$scantron_config{'Qlength'});
6592: my $bubble = $alphabet->[$location % $$scantron_config{'Qlength'}];
6593: for (my $ans=0; $ans<$answers_needed; $ans++) {
6594: if ($ans eq $line_num) {
6595: $record->{"scantron.$ansnum.answer"} = $bubble;
6596: } else {
6597: $record->{"scantron.$ansnum.answer"} = ' ';
6598: }
6599: $ansnum++;
6600: }
6601: } else {
6602: # If there's more than one instance of a bubble character
6603: # That's a double bubble; with positional notation we can
6604: # record all the bubbles filled in as well as the
6605: # fact this response consists of multiple bubbles.
6606: #
6607: my $responsenum = $questnum-1;
6608: if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
6609: $responsenum = $respnumlookup->{$questnum-1}
6610: }
6611: if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
6612: ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
6613: ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
6614: ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
6615: ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
6616: ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
6617: my $doubleerror = 0;
6618: while (($currquest >= $$scantron_config{'Qlength'}) &&
6619: (!$doubleerror)) {
6620: my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
6621: $currquest = substr($currquest,$$scantron_config{'Qlength'});
6622: my @currarray = split($$scantron_config{'Qon'},$currline,-1);
6623: if (length(@currarray) > 2) {
6624: $doubleerror = 1;
6625: }
6626: }
6627: if ($doubleerror) {
6628: push(@{$record->{'scantron.doubleerror'}},$quest_id);
6629: }
6630: } else {
6631: push(@{$record->{'scantron.doubleerror'}},$quest_id);
6632: }
6633: my $item = $ansnum;
6634: for (my $ans=0; $ans<$answers_needed; $ans++) {
6635: $record->{"scantron.$item.answer"} = '';
6636: $item ++;
6637: }
6638:
6639: my @ans=@array;
6640: my $i=0;
6641: my $increment = 0;
6642: while ($#ans) {
6643: $i+=length($ans[0]) + $increment;
6644: my $line = int($i/$$scantron_config{'Qlength'} + $ansnum);
6645: my $bubble = $i%$$scantron_config{'Qlength'};
6646: $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
6647: shift(@ans);
6648: $increment = 1;
6649: }
6650: $ansnum += $answers_needed;
6651: }
6652: return $ansnum;
6653: }
6654:
6655: =pod
6656:
6657: =item scantron_add_delay
6658:
6659: Adds an error message that occurred during the grading phase to a
6660: queue of messages to be shown after grading pass is complete
6661:
6662: Arguments:
6663: $delayqueue - arrary ref of hash ref of error messages
6664: $scanline - the scanline that caused the error
6665: $errormesage - the error message
6666: $errorcode - a numeric code for the error
6667:
6668: Side Effects:
6669: updates the $delayqueue to have a new hash ref of the error
6670:
6671: =cut
6672:
6673: sub scantron_add_delay {
6674: my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
6675: push(@$delayqueue,
6676: {'line' => $scanline, 'emsg' => $errormessage,
6677: 'ecode' => $errorcode }
6678: );
6679: }
6680:
6681: =pod
6682:
6683: =item scantron_find_student
6684:
6685: Finds the username for the current scanline
6686:
6687: Arguments:
6688: $scantron_record - hash result from scantron_parse_scanline
6689: $scan_data - hash of correction information
6690: (see &scantron_getfile() form more information)
6691: $idmap - hash from &username_to_idmap()
6692: $line - number of current scanline
6693:
6694: Returns:
6695: Either 'username:domain' or undef if unknown
6696:
6697: =cut
6698:
6699: sub scantron_find_student {
6700: my ($scantron_record,$scan_data,$idmap,$line)=@_;
6701: my $scanID=$$scantron_record{'scantron.ID'};
6702: if ($scanID =~ /^\s*$/) {
6703: return &scan_data($scan_data,"$line.user");
6704: }
6705: foreach my $id (keys(%$idmap)) {
6706: if (lc($id) eq lc($scanID)) {
6707: return $$idmap{$id};
6708: }
6709: }
6710: return undef;
6711: }
6712:
6713: =pod
6714:
6715: =item scantron_filter
6716:
6717: Filter sub for lonnavmaps, filters out hidden resources if ignore
6718: hidden resources was selected
6719:
6720: =cut
6721:
6722: sub scantron_filter {
6723: my ($curres)=@_;
6724:
6725: if (ref($curres) && $curres->is_problem()) {
6726: # if the user has asked to not have either hidden
6727: # or 'randomout' controlled resources to be graded
6728: # don't include them
6729: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
6730: && $curres->randomout) {
6731: return 0;
6732: }
6733: return 1;
6734: }
6735: return 0;
6736: }
6737:
6738: =pod
6739:
6740: =item scantron_process_corrections
6741:
6742: Gets correction information out of submitted form data and corrects
6743: the scanline
6744:
6745: =cut
6746:
6747: sub scantron_process_corrections {
6748: my ($r) = @_;
6749: my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
6750: my ($scanlines,$scan_data)=&scantron_getfile();
6751: my $classlist=&Apache::loncoursedata::get_classlist();
6752: my $which=$env{'form.scantron_line'};
6753: my $line=&scantron_get_line($scanlines,$scan_data,$which);
6754: my ($skip,$err,$errmsg);
6755: if ($env{'form.scantron_skip_record'}) {
6756: $skip=1;
6757: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
6758: my $newstudent=$env{'form.scantron_username'}.':'.
6759: $env{'form.scantron_domain'};
6760: my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
6761: ($line,$err,$errmsg)=
6762: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
6763: 'ID',{'newid'=>$newid,
6764: 'username'=>$env{'form.scantron_username'},
6765: 'domain'=>$env{'form.scantron_domain'}});
6766: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
6767: my $resolution=$env{'form.scantron_CODE_resolution'};
6768: my $newCODE;
6769: my %args;
6770: if ($resolution eq 'use_unfound') {
6771: $newCODE='use_unfound';
6772: } elsif ($resolution eq 'use_found') {
6773: $newCODE=$env{'form.scantron_CODE_selectedvalue'};
6774: } elsif ($resolution eq 'use_typed') {
6775: $newCODE=$env{'form.scantron_CODE_newvalue'};
6776: } elsif ($resolution =~ /^use_closest_(\d+)/) {
6777: $newCODE=$env{"form.scantron_CODE_closest_$1"};
6778: }
6779: if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
6780: $args{'CODE_ignore_dup'}=1;
6781: }
6782: $args{'CODE'}=$newCODE;
6783: ($line,$err,$errmsg)=
6784: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
6785: 'CODE',\%args);
6786: } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
6787: foreach my $question (split(',',$env{'form.scantron_questions'})) {
6788: ($line,$err,$errmsg)=
6789: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
6790: $which,'answer',
6791: { 'question'=>$question,
6792: 'response'=>$env{"form.scantron_correct_Q_$question"},
6793: 'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
6794: if ($err) { last; }
6795: }
6796: }
6797: if ($err) {
6798: $r->print(
6799: '<p class="LC_error">'
6800: .&mt('Unable to accept last correction, an error occurred: [_1]',
6801: $errmsg)
6802: .'</p>');
6803: } else {
6804: &scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
6805: &scantron_putfile($scanlines,$scan_data);
6806: }
6807: }
6808:
6809: =pod
6810:
6811: =item reset_skipping_status
6812:
6813: Forgets the current set of remember skipped scanlines (and thus
6814: reverts back to considering all lines in the
6815: scantron_skipped_<filename> file)
6816:
6817: =cut
6818:
6819: sub reset_skipping_status {
6820: my ($scanlines,$scan_data)=&scantron_getfile();
6821: &scan_data($scan_data,'remember_skipping',undef,1);
6822: &scantron_putfile(undef,$scan_data);
6823: }
6824:
6825: =pod
6826:
6827: =item start_skipping
6828:
6829: Marks a scanline to be skipped.
6830:
6831: =cut
6832:
6833: sub start_skipping {
6834: my ($scan_data,$i)=@_;
6835: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
6836: if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
6837: $remembered{$i}=2;
6838: } else {
6839: $remembered{$i}=1;
6840: }
6841: &scan_data($scan_data,'remember_skipping',join(':',%remembered));
6842: }
6843:
6844: =pod
6845:
6846: =item should_be_skipped
6847:
6848: Checks whether a scanline should be skipped.
6849:
6850: =cut
6851:
6852: sub should_be_skipped {
6853: my ($scanlines,$scan_data,$i)=@_;
6854: if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
6855: # not redoing old skips
6856: if ($scanlines->{'skipped'}[$i]) { return 1; }
6857: return 0;
6858: }
6859: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
6860:
6861: if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
6862: return 0;
6863: }
6864: return 1;
6865: }
6866:
6867: =pod
6868:
6869: =item remember_current_skipped
6870:
6871: Discovers what scanlines are in the scantron_skipped_<filename>
6872: file and remembers them into scan_data for later use.
6873:
6874: =cut
6875:
6876: sub remember_current_skipped {
6877: my ($scanlines,$scan_data)=&scantron_getfile();
6878: my %to_remember;
6879: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6880: if ($scanlines->{'skipped'}[$i]) {
6881: $to_remember{$i}=1;
6882: }
6883: }
6884:
6885: &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
6886: &scantron_putfile(undef,$scan_data);
6887: }
6888:
6889: =pod
6890:
6891: =item check_for_error
6892:
6893: Checks if there was an error when attempting to remove a specific
6894: scantron_.. bubblesheet data file. Prints out an error if
6895: something went wrong.
6896:
6897: =cut
6898:
6899: sub check_for_error {
6900: my ($r,$result)=@_;
6901: if ($result ne 'ok' && $result ne 'not_found' ) {
6902: $r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
6903: }
6904: }
6905:
6906: =pod
6907:
6908: =item scantron_warning_screen
6909:
6910: Interstitial screen to make sure the operator has selected the
6911: correct options before we start the validation phase.
6912:
6913: =cut
6914:
6915: sub scantron_warning_screen {
6916: my ($button_text)=@_;
6917: my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
6918: my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
6919: my $CODElist;
6920: if ($scantron_config{'CODElocation'} &&
6921: $scantron_config{'CODEstart'} &&
6922: $scantron_config{'CODElength'}) {
6923: $CODElist=$env{'form.scantron_CODElist'};
6924: if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
6925: $CODElist=
6926: '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
6927: $env{'form.scantron_CODElist'}.'</tt></td></tr>';
6928: }
6929: my $lastbubblepoints;
6930: if ($env{'form.scantron_lastbubblepoints'} ne '') {
6931: $lastbubblepoints =
6932: '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
6933: $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
6934: }
6935: return ('
6936: <p>
6937: <span class="LC_warning">
6938: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
6939: </p>
6940: <table>
6941: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
6942: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
6943: '.$CODElist.$lastbubblepoints.'
6944: </table>
6945: <br />
6946: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'</p>
6947: <p> '.&mt("If something is incorrect, please click the 'Grading Menu' button to start over.").'</p>
6948:
6949: <br />
6950: ');
6951: }
6952:
6953: =pod
6954:
6955: =item scantron_do_warning
6956:
6957: Check if the operator has picked something for all required
6958: fields. Error out if something is missing.
6959:
6960: =cut
6961:
6962: sub scantron_do_warning {
6963: my ($r)=@_;
6964: my ($symb)=&get_symb($r);
6965: if (!$symb) {return '';}
6966: my $default_form_data=&defaultFormData($symb);
6967: $r->print(&scantron_form_start().$default_form_data);
6968: if ( $env{'form.selectpage'} eq '' ||
6969: $env{'form.scantron_selectfile'} eq '' ||
6970: $env{'form.scantron_format'} eq '' ) {
6971: $r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
6972: if ( $env{'form.selectpage'} eq '') {
6973: $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
6974: }
6975: if ( $env{'form.scantron_selectfile'} eq '') {
6976: $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
6977: }
6978: if ( $env{'form.scantron_format'} eq '') {
6979: $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
6980: }
6981: } else {
6982: my $warning=&scantron_warning_screen('Grading: Validate Records');
6983: my $bubbledbyhand=&hand_bubble_option();
6984: $r->print('
6985: '.$warning.$bubbledbyhand.'
6986: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
6987: <input type="hidden" name="command" value="scantron_validate" />
6988: ');
6989: }
6990: $r->print("</form><br />".&show_grading_menu_form($symb));
6991: return '';
6992: }
6993:
6994: =pod
6995:
6996: =item scantron_form_start
6997:
6998: html hidden input for remembering all selected grading options
6999:
7000: =cut
7001:
7002: sub scantron_form_start {
7003: my ($max_bubble)=@_;
7004: my $result= <<SCANTRONFORM;
7005: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
7006: <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
7007: <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
7008: <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
7009: <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
7010: <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
7011: <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
7012: <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
7013: <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
7014: <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
7015: SCANTRONFORM
7016:
7017: my $line = 0;
7018: while (defined($env{"form.scantron.bubblelines.$line"})) {
7019: my $chunk =
7020: '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
7021: $chunk .=
7022: '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
7023: $chunk .=
7024: '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
7025: $chunk .=
7026: '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
7027: $chunk .=
7028: '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
7029: $result .= $chunk;
7030: $line++;
7031: }
7032: return $result;
7033: }
7034:
7035: =pod
7036:
7037: =item scantron_validate_file
7038:
7039: Dispatch routine for doing validation of a bubblesheet data file.
7040:
7041: Also processes any necessary information resets that need to
7042: occur before validation begins (ignore previous corrections,
7043: restarting the skipped records processing)
7044:
7045: =cut
7046:
7047: sub scantron_validate_file {
7048: my ($r) = @_;
7049: my ($symb)=&get_symb($r);
7050: if (!$symb) {return '';}
7051: my $default_form_data=&defaultFormData($symb);
7052:
7053: # do the detection of only doing skipped records first before we delete
7054: # them when doing the corrections reset
7055: if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
7056: &reset_skipping_status();
7057: }
7058: if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
7059: &remember_current_skipped();
7060: $env{'form.scantron_options_redo'}='redo_skipped_ready';
7061: }
7062:
7063: if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
7064: &check_for_error($r,&scantron_remove_file('corrected'));
7065: &check_for_error($r,&scantron_remove_file('skipped'));
7066: &check_for_error($r,&scantron_remove_scan_data());
7067: $env{'form.scantron_options_ignore'}='done';
7068: }
7069:
7070: if ($env{'form.scantron_corrections'}) {
7071: &scantron_process_corrections($r);
7072: }
7073: $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
7074: #get the student pick code ready
7075: $r->print(&Apache::loncommon::studentbrowser_javascript());
7076: my $nav_error;
7077: my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
7078: my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
7079: if ($nav_error) {
7080: $r->print(&navmap_errormsg());
7081: return '';
7082: }
7083: my $result=&scantron_form_start($max_bubble).$default_form_data;
7084: if ($env{'form.scantron_lastbubblepoints'} ne '') {
7085: $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
7086: }
7087: $r->print($result);
7088:
7089: my @validate_phases=( 'sequence',
7090: 'ID',
7091: 'CODE',
7092: 'doublebubble',
7093: 'missingbubbles');
7094: if (!$env{'form.validatepass'}) {
7095: $env{'form.validatepass'} = 0;
7096: }
7097: my $currentphase=$env{'form.validatepass'};
7098:
7099:
7100: my $stop=0;
7101: while (!$stop && $currentphase < scalar(@validate_phases)) {
7102: $r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
7103: $r->rflush();
7104:
7105: my $which="scantron_validate_".$validate_phases[$currentphase];
7106: {
7107: no strict 'refs';
7108: ($stop,$currentphase)=&$which($r,$currentphase);
7109: }
7110: }
7111: if (!$stop) {
7112: my $warning=&scantron_warning_screen('Start Grading');
7113: $r->print(&mt('Validation process complete.').'<br />'.
7114: $warning.
7115: &mt('Perform verification for each student after storage of submissions?').
7116: ' <span class="LC_nobreak"><label>'.
7117: '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
7118: (' 'x3).'<label>'.
7119: '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
7120: '</label></span><br />'.
7121: &mt('Grading will take longer if you use verification.').'<br />'.
7122: &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
7123: '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
7124: '<input type="hidden" name="command" value="scantron_process" />'."\n");
7125: } else {
7126: $r->print('<input type="hidden" name="command" value="scantron_validate" />');
7127: $r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
7128: }
7129: if ($stop) {
7130: if ($validate_phases[$currentphase] eq 'sequence') {
7131: $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' → " />');
7132: $r->print(' '.&mt('this error').' <br />');
7133:
7134: $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
7135: } else {
7136: if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
7137: $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' →" onclick="javascript:verify_bubble_radio(this.form)" />');
7138: } else {
7139: $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' →" />');
7140: }
7141: $r->print(' '.&mt('using corrected info').' <br />');
7142: $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
7143: $r->print(" ".&mt("this scanline saving it for later."));
7144: }
7145: }
7146: $r->print(" </form><br />".&show_grading_menu_form($symb));
7147: return '';
7148: }
7149:
7150:
7151: =pod
7152:
7153: =item scantron_remove_file
7154:
7155: Removes the requested bubblesheet data file, makes sure that
7156: scantron_original_<filename> is never removed
7157:
7158:
7159: =cut
7160:
7161: sub scantron_remove_file {
7162: my ($which)=@_;
7163: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7164: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7165: my $file='scantron_';
7166: if ($which eq 'corrected' || $which eq 'skipped') {
7167: $file.=$which.'_';
7168: } else {
7169: return 'refused';
7170: }
7171: $file.=$env{'form.scantron_selectfile'};
7172: return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
7173: }
7174:
7175:
7176: =pod
7177:
7178: =item scantron_remove_scan_data
7179:
7180: Removes all scan_data correction for the requested bubblesheet
7181: data file. (In the case that both the are doing skipped records we need
7182: to remember the old skipped lines for the time being so that element
7183: persists for a while.)
7184:
7185: =cut
7186:
7187: sub scantron_remove_scan_data {
7188: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7189: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7190: my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
7191: my @todelete;
7192: my $filename=$env{'form.scantron_selectfile'};
7193: foreach my $key (@keys) {
7194: if ($key=~/^\Q$filename\E_/) {
7195: if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
7196: $key=~/remember_skipping/) {
7197: next;
7198: }
7199: push(@todelete,$key);
7200: }
7201: }
7202: my $result;
7203: if (@todelete) {
7204: $result = &Apache::lonnet::del('nohist_scantrondata',
7205: \@todelete,$cdom,$cname);
7206: } else {
7207: $result = 'ok';
7208: }
7209: return $result;
7210: }
7211:
7212:
7213: =pod
7214:
7215: =item scantron_getfile
7216:
7217: Fetches the requested bubblesheet data file (all 3 versions), and
7218: the scan_data hash
7219:
7220: Arguments:
7221: None
7222:
7223: Returns:
7224: 2 hash references
7225:
7226: - first one has
7227: orig -
7228: corrected -
7229: skipped - each of which points to an array ref of the specified
7230: file broken up into individual lines
7231: count - number of scanlines
7232:
7233: - second is the scan_data hash possible keys are
7234: ($number refers to scanline numbered $number and thus the key affects
7235: only that scanline
7236: $bubline refers to the specific bubble line element and the aspects
7237: refers to that specific bubble line element)
7238:
7239: $number.user - username:domain to use
7240: $number.CODE_ignore_dup
7241: - ignore the duplicate CODE error
7242: $number.useCODE
7243: - use the CODE in the scanline as is
7244: $number.no_bubble.$bubline
7245: - it is valid that there is no bubbled in bubble
7246: at $number $bubline
7247: remember_skipping
7248: - a frozen hash containing keys of $number and values
7249: of either
7250: 1 - we are on a 'do skipped records pass' and plan
7251: on processing this line
7252: 2 - we are on a 'do skipped records pass' and this
7253: scanline has been marked to skip yet again
7254:
7255: =cut
7256:
7257: sub scantron_getfile {
7258: #FIXME really would prefer a scantron directory
7259: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7260: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7261: my $lines;
7262: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
7263: 'scantron_orig_'.$env{'form.scantron_selectfile'});
7264: my %scanlines;
7265: $scanlines{'orig'}=[(split("\n",$lines,-1))];
7266: my $temp=$scanlines{'orig'};
7267: $scanlines{'count'}=$#$temp;
7268:
7269: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
7270: 'scantron_corrected_'.$env{'form.scantron_selectfile'});
7271: if ($lines eq '-1') {
7272: $scanlines{'corrected'}=[];
7273: } else {
7274: $scanlines{'corrected'}=[(split("\n",$lines,-1))];
7275: }
7276: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
7277: 'scantron_skipped_'.$env{'form.scantron_selectfile'});
7278: if ($lines eq '-1') {
7279: $scanlines{'skipped'}=[];
7280: } else {
7281: $scanlines{'skipped'}=[(split("\n",$lines,-1))];
7282: }
7283: my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
7284: if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
7285: my %scan_data = @tmp;
7286: return (\%scanlines,\%scan_data);
7287: }
7288:
7289: =pod
7290:
7291: =item lonnet_putfile
7292:
7293: Wrapper routine to call &Apache::lonnet::finishuserfileupload
7294:
7295: Arguments:
7296: $contents - data to store
7297: $filename - filename to store $contents into
7298:
7299: Returns:
7300: result value from &Apache::lonnet::finishuserfileupload
7301:
7302: =cut
7303:
7304: sub lonnet_putfile {
7305: my ($contents,$filename)=@_;
7306: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
7307: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7308: $env{'form.sillywaytopassafilearound'}=$contents;
7309: &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
7310:
7311: }
7312:
7313: =pod
7314:
7315: =item scantron_putfile
7316:
7317: Stores the current version of the bubblesheet data files, and the
7318: scan_data hash. (Does not modify the original version only the
7319: corrected and skipped versions.
7320:
7321: Arguments:
7322: $scanlines - hash ref that looks like the first return value from
7323: &scantron_getfile()
7324: $scan_data - hash ref that looks like the second return value from
7325: &scantron_getfile()
7326:
7327: =cut
7328:
7329: sub scantron_putfile {
7330: my ($scanlines,$scan_data) = @_;
7331: #FIXME really would prefer a scantron directory
7332: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7333: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7334: if ($scanlines) {
7335: my $prefix='scantron_';
7336: # no need to update orig, shouldn't change
7337: # &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
7338: # $env{'form.scantron_selectfile'});
7339: &lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
7340: $prefix.'corrected_'.
7341: $env{'form.scantron_selectfile'});
7342: &lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
7343: $prefix.'skipped_'.
7344: $env{'form.scantron_selectfile'});
7345: }
7346: &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
7347: }
7348:
7349: =pod
7350:
7351: =item scantron_get_line
7352:
7353: Returns the correct version of the scanline
7354:
7355: Arguments:
7356: $scanlines - hash ref that looks like the first return value from
7357: &scantron_getfile()
7358: $scan_data - hash ref that looks like the second return value from
7359: &scantron_getfile()
7360: $i - number of the requested line (starts at 0)
7361:
7362: Returns:
7363: A scanline, (either the original or the corrected one if it
7364: exists), or undef if the requested scanline should be
7365: skipped. (Either because it's an skipped scanline, or it's an
7366: unskipped scanline and we are not doing a 'do skipped scanlines'
7367: pass.
7368:
7369: =cut
7370:
7371: sub scantron_get_line {
7372: my ($scanlines,$scan_data,$i)=@_;
7373: if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
7374: #if ($scanlines->{'skipped'}[$i]) { return undef; }
7375: if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
7376: return $scanlines->{'orig'}[$i];
7377: }
7378:
7379: =pod
7380:
7381: =item scantron_todo_count
7382:
7383: Counts the number of scanlines that need processing.
7384:
7385: Arguments:
7386: $scanlines - hash ref that looks like the first return value from
7387: &scantron_getfile()
7388: $scan_data - hash ref that looks like the second return value from
7389: &scantron_getfile()
7390:
7391: Returns:
7392: $count - number of scanlines to process
7393:
7394: =cut
7395:
7396: sub get_todo_count {
7397: my ($scanlines,$scan_data)=@_;
7398: my $count=0;
7399: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7400: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7401: if ($line=~/^[\s\cz]*$/) { next; }
7402: $count++;
7403: }
7404: return $count;
7405: }
7406:
7407: =pod
7408:
7409: =item scantron_put_line
7410:
7411: Updates the 'corrected' or 'skipped' versions of the bubblesheet
7412: data file.
7413:
7414: Arguments:
7415: $scanlines - hash ref that looks like the first return value from
7416: &scantron_getfile()
7417: $scan_data - hash ref that looks like the second return value from
7418: &scantron_getfile()
7419: $i - line number to update
7420: $newline - contents of the updated scanline
7421: $skip - if true make the line for skipping and update the
7422: 'skipped' file
7423:
7424: =cut
7425:
7426: sub scantron_put_line {
7427: my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
7428: if ($skip) {
7429: $scanlines->{'skipped'}[$i]=$newline;
7430: &start_skipping($scan_data,$i);
7431: return;
7432: }
7433: $scanlines->{'corrected'}[$i]=$newline;
7434: }
7435:
7436: =pod
7437:
7438: =item scantron_clear_skip
7439:
7440: Remove a line from the 'skipped' file
7441:
7442: Arguments:
7443: $scanlines - hash ref that looks like the first return value from
7444: &scantron_getfile()
7445: $scan_data - hash ref that looks like the second return value from
7446: &scantron_getfile()
7447: $i - line number to update
7448:
7449: =cut
7450:
7451: sub scantron_clear_skip {
7452: my ($scanlines,$scan_data,$i)=@_;
7453: if (exists($scanlines->{'skipped'}[$i])) {
7454: undef($scanlines->{'skipped'}[$i]);
7455: return 1;
7456: }
7457: return 0;
7458: }
7459:
7460: =pod
7461:
7462: =item scantron_filter_not_exam
7463:
7464: Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
7465: filter out resources that are not marked as 'exam' mode
7466:
7467: =cut
7468:
7469: sub scantron_filter_not_exam {
7470: my ($curres)=@_;
7471:
7472: if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
7473: # if the user has asked to not have either hidden
7474: # or 'randomout' controlled resources to be graded
7475: # don't include them
7476: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
7477: && $curres->randomout) {
7478: return 0;
7479: }
7480: return 1;
7481: }
7482: return 0;
7483: }
7484:
7485: =pod
7486:
7487: =item scantron_validate_sequence
7488:
7489: Validates the selected sequence, checking for resource that are
7490: not set to exam mode.
7491:
7492: =cut
7493:
7494: sub scantron_validate_sequence {
7495: my ($r,$currentphase) = @_;
7496:
7497: my $navmap=Apache::lonnavmaps::navmap->new();
7498: unless (ref($navmap)) {
7499: $r->print(&navmap_errormsg());
7500: return (1,$currentphase);
7501: }
7502: my (undef,undef,$sequence)=
7503: &Apache::lonnet::decode_symb($env{'form.selectpage'});
7504:
7505: my $map=$navmap->getResourceByUrl($sequence);
7506:
7507: $r->print('<input type="hidden" name="validate_sequence_exam"
7508: value="ignore" />');
7509: if ($env{'form.validate_sequence_exam'} ne 'ignore') {
7510: my @resources=
7511: $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
7512: if (@resources) {
7513: $r->print('<p class="LC_warning">'
7514: .&mt('Some resources in the sequence currently are not set to'
7515: .' exam mode. Grading these resources currently may not'
7516: .' work correctly.')
7517: .'</p>'
7518: );
7519: return (1,$currentphase);
7520: }
7521: }
7522:
7523: return (0,$currentphase+1);
7524: }
7525:
7526:
7527:
7528: sub scantron_validate_ID {
7529: my ($r,$currentphase) = @_;
7530:
7531: #get student info
7532: my $classlist=&Apache::loncoursedata::get_classlist();
7533: my %idmap=&username_to_idmap($classlist);
7534:
7535: #get scantron line setup
7536: my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
7537: my ($scanlines,$scan_data)=&scantron_getfile();
7538:
7539: my $nav_error;
7540: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
7541: if ($nav_error) {
7542: $r->print(&navmap_errormsg());
7543: return(1,$currentphase);
7544: }
7545:
7546: my %found=('ids'=>{},'usernames'=>{});
7547: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7548: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7549: if ($line=~/^[\s\cz]*$/) { next; }
7550: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7551: $scan_data);
7552: my $id=$$scan_record{'scantron.ID'};
7553: my $found;
7554: foreach my $checkid (keys(%idmap)) {
7555: if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
7556: }
7557: if ($found) {
7558: my $username=$idmap{$found};
7559: if ($found{'ids'}{$found}) {
7560: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
7561: $line,'duplicateID',$found);
7562: return(1,$currentphase);
7563: } elsif ($found{'usernames'}{$username}) {
7564: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
7565: $line,'duplicateID',$username);
7566: return(1,$currentphase);
7567: }
7568: #FIXME store away line we previously saw the ID on to use above
7569: $found{'ids'}{$found}++;
7570: $found{'usernames'}{$username}++;
7571: } else {
7572: if ($id =~ /^\s*$/) {
7573: my $username=&scan_data($scan_data,"$i.user");
7574: if (defined($username) && $found{'usernames'}{$username}) {
7575: &scantron_get_correction($r,$i,$scan_record,
7576: \%scantron_config,
7577: $line,'duplicateID',$username);
7578: return(1,$currentphase);
7579: } elsif (!defined($username)) {
7580: &scantron_get_correction($r,$i,$scan_record,
7581: \%scantron_config,
7582: $line,'incorrectID');
7583: return(1,$currentphase);
7584: }
7585: $found{'usernames'}{$username}++;
7586: } else {
7587: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
7588: $line,'incorrectID');
7589: return(1,$currentphase);
7590: }
7591: }
7592: }
7593:
7594: return (0,$currentphase+1);
7595: }
7596:
7597:
7598: sub scantron_get_correction {
7599: my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
7600: $randomorder,$randompick,$respnumlookup,$startline)=@_;
7601: #FIXME in the case of a duplicated ID the previous line, probably need
7602: #to show both the current line and the previous one and allow skipping
7603: #the previous one or the current one
7604:
7605: if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
7606: $r->print(
7607: '<p class="LC_warning">'
7608: .&mt('An error was detected ([_1]) for PaperID [_2]',
7609: "<b>$error</b>",
7610: '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
7611: ."</p> \n");
7612: } else {
7613: $r->print(
7614: '<p class="LC_warning">'
7615: .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
7616: "<b>$error</b>", $i, "<pre>$line</pre>")
7617: ."</p> \n");
7618: }
7619: my $message =
7620: '<p>'
7621: .&mt('The ID on the form is [_1]',
7622: "<tt>$$scan_record{'scantron.ID'}</tt>")
7623: .'<br />'
7624: .&mt('The name on the paper is [_1], [_2]',
7625: $$scan_record{'scantron.LastName'},
7626: $$scan_record{'scantron.FirstName'})
7627: .'</p>';
7628:
7629: $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
7630: $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
7631: # Array populated for doublebubble or
7632: my @lines_to_correct; # missingbubble errors to build javascript
7633: # to validate radio button checking
7634:
7635: if ($error =~ /ID$/) {
7636: if ($error eq 'incorrectID') {
7637: $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
7638: "</p>\n");
7639: } elsif ($error eq 'duplicateID') {
7640: $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
7641: }
7642: $r->print($message);
7643: $r->print("<p>".&mt("How should I handle this?")." <br /> \n");
7644: $r->print("\n<ul><li> ");
7645: #FIXME it would be nice if this sent back the user ID and
7646: #could do partial userID matches
7647: $r->print(&Apache::loncommon::selectstudent_link('scantronupload',
7648: 'scantron_username','scantron_domain'));
7649: $r->print(": <input type='text' name='scantron_username' value='' />");
7650: $r->print("\n:\n".
7651: &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
7652:
7653: $r->print('</li>');
7654: } elsif ($error =~ /CODE$/) {
7655: if ($error eq 'incorrectCODE') {
7656: $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
7657: } elsif ($error eq 'duplicateCODE') {
7658: $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");
7659: }
7660: $r->print("<p>".&mt('The CODE on the form is [_1]',
7661: "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
7662: ."</p>\n");
7663: $r->print($message);
7664: $r->print("<p>".&mt("How should I handle this?")."</p>\n");
7665: $r->print("\n<br /> ");
7666: my $i=0;
7667: if ($error eq 'incorrectCODE'
7668: && $$scan_record{'scantron.CODE'}=~/\S/ ) {
7669: my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
7670: if ($closest > 0) {
7671: foreach my $testcode (@{$closest}) {
7672: my $checked='';
7673: if (!$i) { $checked=' checked="checked"'; }
7674: $r->print("
7675: <label>
7676: <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
7677: ".&mt("Use the similar CODE [_1] instead.",
7678: "<b><tt>".$testcode."</tt></b>")."
7679: </label>
7680: <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
7681: $r->print("\n<br />");
7682: $i++;
7683: }
7684: }
7685: }
7686: if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
7687: my $checked; if (!$i) { $checked=' checked="checked"'; }
7688: $r->print("
7689: <label>
7690: <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
7691: ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
7692: "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
7693: </label>");
7694: $r->print("\n<br />");
7695: }
7696:
7697: $r->print(<<ENDSCRIPT);
7698: <script type="text/javascript">
7699: function change_radio(field) {
7700: var slct=document.scantronupload.scantron_CODE_resolution;
7701: var i;
7702: for (i=0;i<slct.length;i++) {
7703: if (slct[i].value==field) { slct[i].checked=true; }
7704: }
7705: }
7706: </script>
7707: ENDSCRIPT
7708: my $href="/adm/pickcode?".
7709: "form=".&escape("scantronupload").
7710: "&scantron_format=".&escape($env{'form.scantron_format'}).
7711: "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
7712: "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
7713: "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
7714: if ($env{'form.scantron_CODElist'} =~ /\S/) {
7715: $r->print("
7716: <label>
7717: <input type='radio' name='scantron_CODE_resolution' value='use_found' />
7718: ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
7719: "<a target='_blank' href='$href'>","</a>")."
7720: </label>
7721: ".&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\')" />'));
7722: $r->print("\n<br />");
7723: }
7724: $r->print("
7725: <label>
7726: <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
7727: ".&mt("Use [_1] as the CODE.",
7728: "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
7729: $r->print("\n<br /><br />");
7730: } elsif ($error eq 'doublebubble') {
7731: $r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
7732:
7733: # The form field scantron_questions is acutally a list of line numbers.
7734: # represented by this form so:
7735:
7736: my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
7737: $respnumlookup,$startline);
7738:
7739: $r->print('<input type="hidden" name="scantron_questions" value="'.
7740: $line_list.'" />');
7741: $r->print($message);
7742: $r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
7743: foreach my $question (@{$arg}) {
7744: my @linenums = &prompt_for_corrections($r,$question,$scan_config,
7745: $scan_record, $error,
7746: $randomorder,$randompick,
7747: $respnumlookup,$startline);
7748: push(@lines_to_correct,@linenums);
7749: }
7750: $r->print(&verify_bubbles_checked(@lines_to_correct));
7751: } elsif ($error eq 'missingbubble') {
7752: $r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
7753: $r->print($message);
7754: $r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
7755: $r->print(&mt("Some questions have no scanned bubbles.")."\n");
7756:
7757: # The form field scantron_questions is actually a list of line numbers not
7758: # a list of question numbers. Therefore:
7759: #
7760:
7761: my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
7762: $respnumlookup,$startline);
7763:
7764: $r->print('<input type="hidden" name="scantron_questions" value="'.
7765: $line_list.'" />');
7766: foreach my $question (@{$arg}) {
7767: my @linenums = &prompt_for_corrections($r,$question,$scan_config,
7768: $scan_record, $error,
7769: $randomorder,$randompick,
7770: $respnumlookup,$startline);
7771: push(@lines_to_correct,@linenums);
7772: }
7773: $r->print(&verify_bubbles_checked(@lines_to_correct));
7774: } else {
7775: $r->print("\n<ul>");
7776: }
7777: $r->print("\n</li></ul>");
7778: }
7779:
7780: sub verify_bubbles_checked {
7781: my (@ansnums) = @_;
7782: my $ansnumstr = join('","',@ansnums);
7783: my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
7784: &js_escape(\$warning);
7785: my $output = (<<ENDSCRIPT);
7786: <script type="text/javascript">
7787: function verify_bubble_radio(form) {
7788: var ansnumArray = new Array ("$ansnumstr");
7789: var need_bubble_count = 0;
7790: for (var i=0; i<ansnumArray.length; i++) {
7791: if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
7792: var bubble_picked = 0;
7793: for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
7794: if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
7795: bubble_picked = 1;
7796: }
7797: }
7798: if (bubble_picked == 0) {
7799: need_bubble_count ++;
7800: }
7801: }
7802: }
7803: if (need_bubble_count) {
7804: alert("$warning");
7805: return;
7806: }
7807: form.submit();
7808: }
7809: </script>
7810: ENDSCRIPT
7811: return $output;
7812: }
7813:
7814: =pod
7815:
7816: =item questions_to_line_list
7817:
7818: Converts a list of questions into a string of comma separated
7819: line numbers in the answer sheet used by the questions. This is
7820: used to fill in the scantron_questions form field.
7821:
7822: Arguments:
7823: questions - Reference to an array of questions.
7824: randomorder - True if randomorder in use.
7825: randompick - True if randompick in use.
7826: respnumlookup - Reference to HASH mapping question numbers in bubble lines
7827: for current line to question number used for same question
7828: in "Master Seqence" (as seen by Course Coordinator).
7829: startline - Reference to hash where key is question number (0 is first)
7830: and key is number of first bubble line for current student
7831: or code-based randompick and/or randomorder.
7832:
7833: =cut
7834:
7835:
7836: sub questions_to_line_list {
7837: my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
7838: my @lines;
7839:
7840: foreach my $item (@{$questions}) {
7841: my $question = $item;
7842: my ($first,$count,$last);
7843: if ($item =~ /^(\d+)\.(\d+)$/) {
7844: $question = $1;
7845: my $subquestion = $2;
7846: my $responsenum = $question-1;
7847: if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
7848: $responsenum = $respnumlookup->{$question-1};
7849: if (ref($startline) eq 'HASH') {
7850: $first = $startline->{$question-1} + 1;
7851: }
7852: } else {
7853: $first = $first_bubble_line{$responsenum} + 1;
7854: }
7855: my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
7856: my $subcount = 1;
7857: while ($subcount<$subquestion) {
7858: $first += $subans[$subcount-1];
7859: $subcount ++;
7860: }
7861: $count = $subans[$subquestion-1];
7862: } else {
7863: my $responsenum = $question-1;
7864: if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
7865: $responsenum = $respnumlookup->{$question-1};
7866: if (ref($startline) eq 'HASH') {
7867: $first = $startline->{$question-1} + 1;
7868: }
7869: } else {
7870: $first = $first_bubble_line{$responsenum} + 1;
7871: }
7872: $count = $bubble_lines_per_response{$responsenum};
7873: }
7874: $last = $first+$count-1;
7875: push(@lines, ($first..$last));
7876: }
7877: return join(',', @lines);
7878: }
7879:
7880: =pod
7881:
7882: =item prompt_for_corrections
7883:
7884: Prompts for a potentially multiline correction to the
7885: user's bubbling (factors out common code from scantron_get_correction
7886: for multi and missing bubble cases).
7887:
7888: Arguments:
7889: $r - Apache request object.
7890: $question - The question number to prompt for.
7891: $scan_config - The scantron file configuration hash.
7892: $scan_record - Reference to the hash that has the the parsed scanlines.
7893: $error - Type of error
7894: $randomorder - True if randomorder in use.
7895: $randompick - True if randompick in use.
7896: $respnumlookup - Reference to HASH mapping question numbers in bubble lines
7897: for current line to question number used for same question
7898: in "Master Seqence" (as seen by Course Coordinator).
7899: $startline - Reference to hash where key is question number (0 is first)
7900: and value is number of first bubble line for current student
7901: or code-based randompick and/or randomorder.
7902:
7903: Implicit inputs:
7904: %bubble_lines_per_response - Starting line numbers for each question.
7905: Numbered from 0 (but question numbers are from
7906: 1.
7907: %first_bubble_line - Starting bubble line for each question.
7908: %subdivided_bubble_lines - optionresponse, matchresponse and rankresponse
7909: type problems render as separate sub-questions,
7910: in exam mode. This hash contains a
7911: comma-separated list of the lines per
7912: sub-question.
7913: %responsetype_per_response - essayresponse, formularesponse,
7914: stringresponse, imageresponse, reactionresponse,
7915: and organicresponse type problem parts can have
7916: multiple lines per response if the weight
7917: assigned exceeds 10. In this case, only
7918: one bubble per line is permitted, but more
7919: than one line might contain bubbles, e.g.
7920: bubbling of: line 1 - J, line 2 - J,
7921: line 3 - B would assign 22 points.
7922:
7923: =cut
7924:
7925: sub prompt_for_corrections {
7926: my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
7927: $randompick, $respnumlookup, $startline) = @_;
7928: my ($current_line,$lines);
7929: my @linenums;
7930: my $questionnum = $question;
7931: my ($first,$responsenum);
7932: if ($question =~ /^(\d+)\.(\d+)$/) {
7933: $question = $1;
7934: my $subquestion = $2;
7935: if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
7936: $responsenum = $respnumlookup->{$question-1};
7937: if (ref($startline) eq 'HASH') {
7938: $first = $startline->{$question-1};
7939: }
7940: } else {
7941: $responsenum = $question-1;
7942: $first = $first_bubble_line{$responsenum};
7943: }
7944: $current_line = $first + 1 ;
7945: my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
7946: my $subcount = 1;
7947: while ($subcount<$subquestion) {
7948: $current_line += $subans[$subcount-1];
7949: $subcount ++;
7950: }
7951: $lines = $subans[$subquestion-1];
7952: } else {
7953: if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
7954: $responsenum = $respnumlookup->{$question-1};
7955: if (ref($startline) eq 'HASH') {
7956: $first = $startline->{$question-1};
7957: }
7958: } else {
7959: $responsenum = $question-1;
7960: $first = $first_bubble_line{$responsenum};
7961: }
7962: $current_line = $first + 1;
7963: $lines = $bubble_lines_per_response{$responsenum};
7964: }
7965: if ($lines > 1) {
7966: $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
7967: if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
7968: ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
7969: ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
7970: ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
7971: ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
7972: ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
7973: $r->print(&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).'<br /><br />'.&mt('A non-zero score can be assigned to the student during bubblesheet grading by selecting a bubble in at least one line.').'<br />'.&mt('The score for this question will be a sum of the numeric values for the selected bubbles from each line, where A=1 point, B=2 points etc.').'<br />'.&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.").'<br /><br />');
7974: } else {
7975: $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
7976: }
7977: }
7978: for (my $i =0; $i < $lines; $i++) {
7979: my $selected = $$scan_record{"scantron.$current_line.answer"};
7980: &scantron_bubble_selector($r,$scan_config,$current_line,
7981: $questionnum,$error,split('', $selected));
7982: push(@linenums,$current_line);
7983: $current_line++;
7984: }
7985: if ($lines > 1) {
7986: $r->print("<hr /><br />");
7987: }
7988: return @linenums;
7989: }
7990:
7991: =pod
7992:
7993: =item scantron_bubble_selector
7994:
7995: Generates the html radiobuttons to correct a single bubble line
7996: possibly showing the existing the selected bubbles if known
7997:
7998: Arguments:
7999: $r - Apache request object
8000: $scan_config - hash from &Apache::lonnet::get_scantron_config()
8001: $line - Number of the line being displayed.
8002: $questionnum - Question number (may include subquestion)
8003: $error - Type of error.
8004: @selected - Array of bubbles picked on this line.
8005:
8006: =cut
8007:
8008: sub scantron_bubble_selector {
8009: my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
8010: my $max=$$scan_config{'Qlength'};
8011:
8012: my $scmode=$$scan_config{'Qon'};
8013: if ($scmode eq 'number' || $scmode eq 'letter') {
8014: if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
8015: ($$scan_config{'BubblesPerRow'} > 0)) {
8016: $max=$$scan_config{'BubblesPerRow'};
8017: if (($scmode eq 'number') && ($max > 10)) {
8018: $max = 10;
8019: } elsif (($scmode eq 'letter') && $max > 26) {
8020: $max = 26;
8021: }
8022: } else {
8023: $max = 10;
8024: }
8025: }
8026:
8027: my @alphabet=('A'..'Z');
8028: $r->print(&Apache::loncommon::start_data_table().
8029: &Apache::loncommon::start_data_table_row());
8030: $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
8031: for (my $i=0;$i<$max+1;$i++) {
8032: $r->print("\n".'<td align="center">');
8033: if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
8034: else { $r->print(' '); }
8035: $r->print('</td>');
8036: }
8037: $r->print(&Apache::loncommon::end_data_table_row().
8038: &Apache::loncommon::start_data_table_row());
8039: for (my $i=0;$i<$max;$i++) {
8040: $r->print("\n".
8041: '<td><label><input type="radio" name="scantron_correct_Q_'.
8042: $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
8043: }
8044: my $nobub_checked = ' ';
8045: if ($error eq 'missingbubble') {
8046: $nobub_checked = ' checked = "checked" ';
8047: }
8048: $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
8049: $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
8050: '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
8051: $line.'" value="'.$questionnum.'" /></td>');
8052: $r->print(&Apache::loncommon::end_data_table_row().
8053: &Apache::loncommon::end_data_table());
8054: }
8055:
8056: =pod
8057:
8058: =item num_matches
8059:
8060: Counts the number of characters that are the same between the two arguments.
8061:
8062: Arguments:
8063: $orig - CODE from the scanline
8064: $code - CODE to match against
8065:
8066: Returns:
8067: $count - integer count of the number of same characters between the
8068: two arguments
8069:
8070: =cut
8071:
8072: sub num_matches {
8073: my ($orig,$code) = @_;
8074: my @code=split(//,$code);
8075: my @orig=split(//,$orig);
8076: my $same=0;
8077: for (my $i=0;$i<scalar(@code);$i++) {
8078: if ($code[$i] eq $orig[$i]) { $same++; }
8079: }
8080: return $same;
8081: }
8082:
8083: =pod
8084:
8085: =item scantron_get_closely_matching_CODEs
8086:
8087: Cycles through all CODEs and finds the set that has the greatest
8088: number of same characters as the provided CODE
8089:
8090: Arguments:
8091: $allcodes - hash ref returned by &get_codes()
8092: $CODE - CODE from the current scanline
8093:
8094: Returns:
8095: 2 element list
8096: - first elements is number of how closely matching the best fit is
8097: (5 means best set has 5 matching characters)
8098: - second element is an arrary ref containing the set of valid CODEs
8099: that best fit the passed in CODE
8100:
8101: =cut
8102:
8103: sub scantron_get_closely_matching_CODEs {
8104: my ($allcodes,$CODE)=@_;
8105: my @CODEs;
8106: foreach my $testcode (sort(keys(%{$allcodes}))) {
8107: push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
8108: }
8109:
8110: return ($#CODEs,$CODEs[-1]);
8111: }
8112:
8113: =pod
8114:
8115: =item get_codes
8116:
8117: Builds a hash which has keys of all of the valid CODEs from the selected
8118: set of remembered CODEs.
8119:
8120: Arguments:
8121: $old_name - name of the set of remembered CODEs
8122: $cdom - domain of the course
8123: $cnum - internal course name
8124:
8125: Returns:
8126: %allcodes - keys are the valid CODEs, values are all 1
8127:
8128: =cut
8129:
8130: sub get_codes {
8131: my ($old_name, $cdom, $cnum) = @_;
8132: if (!$old_name) {
8133: $old_name=$env{'form.scantron_CODElist'};
8134: }
8135: if (!$cdom) {
8136: $cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
8137: }
8138: if (!$cnum) {
8139: $cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
8140: }
8141: my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
8142: $cdom,$cnum);
8143: my %allcodes;
8144: if ($result{"type\0$old_name"} eq 'number') {
8145: %allcodes=map {($_,1)} split(',',$result{$old_name});
8146: } else {
8147: %allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
8148: }
8149: return %allcodes;
8150: }
8151:
8152: =pod
8153:
8154: =item scantron_validate_CODE
8155:
8156: Validates all scanlines in the selected file to not have any
8157: invalid or underspecified CODEs and that none of the codes are
8158: duplicated if this was requested.
8159:
8160: =cut
8161:
8162: sub scantron_validate_CODE {
8163: my ($r,$currentphase) = @_;
8164: my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
8165: if ($scantron_config{'CODElocation'} &&
8166: $scantron_config{'CODEstart'} &&
8167: $scantron_config{'CODElength'}) {
8168: if (!defined($env{'form.scantron_CODElist'})) {
8169: &FIXME_blow_up()
8170: }
8171: } else {
8172: return (0,$currentphase+1);
8173: }
8174:
8175: my %usedCODEs;
8176:
8177: my %allcodes=&get_codes();
8178:
8179: my $nav_error;
8180: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
8181: if ($nav_error) {
8182: $r->print(&navmap_errormsg());
8183: return(1,$currentphase);
8184: }
8185:
8186: my ($scanlines,$scan_data)=&scantron_getfile();
8187: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
8188: my $line=&scantron_get_line($scanlines,$scan_data,$i);
8189: if ($line=~/^[\s\cz]*$/) { next; }
8190: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
8191: $scan_data);
8192: my $CODE=$$scan_record{'scantron.CODE'};
8193: my $error=0;
8194: if (!&Apache::lonnet::validCODE($CODE)) {
8195: &scantron_get_correction($r,$i,$scan_record,
8196: \%scantron_config,
8197: $line,'incorrectCODE',\%allcodes);
8198: return(1,$currentphase);
8199: }
8200: if (%allcodes && !exists($allcodes{$CODE})
8201: && !$$scan_record{'scantron.useCODE'}) {
8202: &scantron_get_correction($r,$i,$scan_record,
8203: \%scantron_config,
8204: $line,'incorrectCODE',\%allcodes);
8205: return(1,$currentphase);
8206: }
8207: if (exists($usedCODEs{$CODE})
8208: && $env{'form.scantron_CODEunique'} eq 'yes'
8209: && !$$scan_record{'scantron.CODE_ignore_dup'}) {
8210: &scantron_get_correction($r,$i,$scan_record,
8211: \%scantron_config,
8212: $line,'duplicateCODE',$usedCODEs{$CODE});
8213: return(1,$currentphase);
8214: }
8215: push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
8216: }
8217: return (0,$currentphase+1);
8218: }
8219:
8220: =pod
8221:
8222: =item scantron_validate_doublebubble
8223:
8224: Validates all scanlines in the selected file to not have any
8225: bubble lines with multiple bubbles marked.
8226:
8227: =cut
8228:
8229: sub scantron_validate_doublebubble {
8230: my ($r,$currentphase) = @_;
8231: #get student info
8232: my $classlist=&Apache::loncoursedata::get_classlist();
8233: my %idmap=&username_to_idmap($classlist);
8234: my (undef,undef,$sequence)=
8235: &Apache::lonnet::decode_symb($env{'form.selectpage'});
8236:
8237: #get scantron line setup
8238: my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
8239: my ($scanlines,$scan_data)=&scantron_getfile();
8240:
8241: my $navmap = Apache::lonnavmaps::navmap->new();
8242: unless (ref($navmap)) {
8243: $r->print(&navmap_errormsg());
8244: return(1,$currentphase);
8245: }
8246: my $map=$navmap->getResourceByUrl($sequence);
8247: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
8248: my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
8249: %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
8250: my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
8251:
8252: my $nav_error;
8253: if (ref($map)) {
8254: $randomorder = $map->randomorder();
8255: $randompick = $map->randompick();
8256: if ($randomorder || $randompick) {
8257: $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
8258: if ($nav_error) {
8259: $r->print(&navmap_errormsg());
8260: return(1,$currentphase);
8261: }
8262: &graders_resources_pass(\@resources,\%grader_partids_by_symb,
8263: \%grader_randomlists_by_symb,$bubbles_per_row);
8264: }
8265: } else {
8266: $r->print(&navmap_errormsg());
8267: return(1,$currentphase);
8268: }
8269:
8270: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
8271: if ($nav_error) {
8272: $r->print(&navmap_errormsg());
8273: return(1,$currentphase);
8274: }
8275:
8276: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
8277: my $line=&scantron_get_line($scanlines,$scan_data,$i);
8278: if ($line=~/^[\s\cz]*$/) { next; }
8279: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
8280: $scan_data,undef,\%idmap,$randomorder,
8281: $randompick,$sequence,\@master_seq,
8282: \%symb_to_resource,\%grader_partids_by_symb,
8283: \%orderedforcode,\%respnumlookup,\%startline);
8284: if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
8285: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
8286: 'doublebubble',
8287: $$scan_record{'scantron.doubleerror'},
8288: $randomorder,$randompick,\%respnumlookup,\%startline);
8289: return (1,$currentphase);
8290: }
8291: return (0,$currentphase+1);
8292: }
8293:
8294:
8295: sub scantron_get_maxbubble {
8296: my ($nav_error,$scantron_config) = @_;
8297: if (defined($env{'form.scantron_maxbubble'}) &&
8298: $env{'form.scantron_maxbubble'}) {
8299: &restore_bubble_lines();
8300: return $env{'form.scantron_maxbubble'};
8301: }
8302:
8303: my (undef, undef, $sequence) =
8304: &Apache::lonnet::decode_symb($env{'form.selectpage'});
8305:
8306: my $navmap=Apache::lonnavmaps::navmap->new();
8307: unless (ref($navmap)) {
8308: if (ref($nav_error)) {
8309: $$nav_error = 1;
8310: }
8311: return;
8312: }
8313: my $map=$navmap->getResourceByUrl($sequence);
8314: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
8315: my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
8316:
8317: &Apache::lonxml::clear_problem_counter();
8318:
8319: my $uname = $env{'user.name'};
8320: my $udom = $env{'user.domain'};
8321: my $cid = $env{'request.course.id'};
8322: my $total_lines = 0;
8323: %bubble_lines_per_response = ();
8324: %first_bubble_line = ();
8325: %subdivided_bubble_lines = ();
8326: %responsetype_per_response = ();
8327: %masterseq_id_responsenum = ();
8328:
8329: my $response_number = 0;
8330: my $bubble_line = 0;
8331: foreach my $resource (@resources) {
8332: my $resid = $resource->id();
8333: my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
8334: $udom,undef,$bubbles_per_row);
8335: if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
8336: foreach my $part_id (@{$parts}) {
8337: my $lines;
8338:
8339: # TODO - make this a persistent hash not an array.
8340:
8341: # optionresponse, matchresponse and rankresponse type items
8342: # render as separate sub-questions in exam mode.
8343: if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
8344: ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
8345: ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
8346: my ($numbub,$numshown);
8347: if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
8348: if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
8349: $numbub = scalar(@{$analysis->{$part_id.'.options'}});
8350: }
8351: } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
8352: if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
8353: $numbub = scalar(@{$analysis->{$part_id.'.items'}});
8354: }
8355: } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
8356: if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
8357: $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
8358: }
8359: }
8360: if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
8361: $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
8362: }
8363: my $bubbles_per_row =
8364: &bubblesheet_bubbles_per_row($scantron_config);
8365: my $inner_bubble_lines = int($numbub/$bubbles_per_row);
8366: if (($numbub % $bubbles_per_row) != 0) {
8367: $inner_bubble_lines++;
8368: }
8369: for (my $i=0; $i<$numshown; $i++) {
8370: $subdivided_bubble_lines{$response_number} .=
8371: $inner_bubble_lines.',';
8372: }
8373: $subdivided_bubble_lines{$response_number} =~ s/,$//;
8374: $lines = $numshown * $inner_bubble_lines;
8375: } else {
8376: $lines = $analysis->{"$part_id.bubble_lines"};
8377: }
8378:
8379: $first_bubble_line{$response_number} = $bubble_line;
8380: $bubble_lines_per_response{$response_number} = $lines;
8381: $responsetype_per_response{$response_number} =
8382: $analysis->{$part_id.'.type'};
8383: $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;
8384: $response_number++;
8385:
8386: $bubble_line += $lines;
8387: $total_lines += $lines;
8388: }
8389: }
8390: }
8391: &Apache::lonnet::delenv('scantron.');
8392:
8393: &save_bubble_lines();
8394: $env{'form.scantron_maxbubble'} =
8395: $total_lines;
8396: return $env{'form.scantron_maxbubble'};
8397: }
8398:
8399: sub bubblesheet_bubbles_per_row {
8400: my ($scantron_config) = @_;
8401: my $bubbles_per_row;
8402: if (ref($scantron_config) eq 'HASH') {
8403: $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
8404: }
8405: if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
8406: $bubbles_per_row = 10;
8407: }
8408: return $bubbles_per_row;
8409: }
8410:
8411: sub scantron_validate_missingbubbles {
8412: my ($r,$currentphase) = @_;
8413: #get student info
8414: my $classlist=&Apache::loncoursedata::get_classlist();
8415: my %idmap=&username_to_idmap($classlist);
8416: my (undef,undef,$sequence)=
8417: &Apache::lonnet::decode_symb($env{'form.selectpage'});
8418:
8419: #get scantron line setup
8420: my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
8421: my ($scanlines,$scan_data)=&scantron_getfile();
8422:
8423: my $navmap = Apache::lonnavmaps::navmap->new();
8424: unless (ref($navmap)) {
8425: $r->print(&navmap_errormsg());
8426: return(1,$currentphase);
8427: }
8428:
8429: my $map=$navmap->getResourceByUrl($sequence);
8430: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
8431: my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
8432: %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
8433: my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
8434:
8435: my $nav_error;
8436: if (ref($map)) {
8437: $randomorder = $map->randomorder();
8438: $randompick = $map->randompick();
8439: if ($randomorder || $randompick) {
8440: $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
8441: if ($nav_error) {
8442: $r->print(&navmap_errormsg());
8443: return(1,$currentphase);
8444: }
8445: &graders_resources_pass(\@resources,\%grader_partids_by_symb,
8446: \%grader_randomlists_by_symb,$bubbles_per_row);
8447: }
8448: } else {
8449: $r->print(&navmap_errormsg());
8450: return(1,$currentphase);
8451: }
8452:
8453:
8454: my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
8455: if ($nav_error) {
8456: $r->print(&navmap_errormsg());
8457: return(1,$currentphase);
8458: }
8459:
8460: if (!$max_bubble) { $max_bubble=2**31; }
8461: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
8462: my $line=&scantron_get_line($scanlines,$scan_data,$i);
8463: if ($line=~/^[\s\cz]*$/) { next; }
8464: my $scan_record =
8465: &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
8466: $randomorder,$randompick,$sequence,\@master_seq,
8467: \%symb_to_resource,\%grader_partids_by_symb,
8468: \%orderedforcode,\%respnumlookup,\%startline);
8469: if (!defined($$scan_record{'scantron.missingerror'})) { next; }
8470: my @to_correct;
8471:
8472: # Probably here's where the error is...
8473:
8474: foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
8475: my $lastbubble;
8476: if ($missing =~ /^(\d+)\.(\d+)$/) {
8477: my $question = $1;
8478: my $subquestion = $2;
8479: my ($first,$responsenum);
8480: if ($randomorder || $randompick) {
8481: $responsenum = $respnumlookup{$question-1};
8482: $first = $startline{$question-1};
8483: } else {
8484: $responsenum = $question-1;
8485: $first = $first_bubble_line{$responsenum};
8486: }
8487: if (!defined($first)) { next; }
8488: my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
8489: my $subcount = 1;
8490: while ($subcount<$subquestion) {
8491: $first += $subans[$subcount-1];
8492: $subcount ++;
8493: }
8494: my $count = $subans[$subquestion-1];
8495: $lastbubble = $first + $count;
8496: } else {
8497: my ($first,$responsenum);
8498: if ($randomorder || $randompick) {
8499: $responsenum = $respnumlookup{$missing-1};
8500: $first = $startline{$missing-1};
8501: } else {
8502: $responsenum = $missing-1;
8503: $first = $first_bubble_line{$responsenum};
8504: }
8505: if (!defined($first)) { next; }
8506: $lastbubble = $first + $bubble_lines_per_response{$responsenum};
8507: }
8508: if ($lastbubble > $max_bubble) { next; }
8509: push(@to_correct,$missing);
8510: }
8511: if (@to_correct) {
8512: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
8513: $line,'missingbubble',\@to_correct,
8514: $randomorder,$randompick,\%respnumlookup,
8515: \%startline);
8516: return (1,$currentphase);
8517: }
8518:
8519: }
8520: return (0,$currentphase+1);
8521: }
8522:
8523: sub hand_bubble_option {
8524: my (undef, undef, $sequence) =
8525: &Apache::lonnet::decode_symb($env{'form.selectpage'});
8526: return if ($sequence eq '');
8527: my $navmap = Apache::lonnavmaps::navmap->new();
8528: unless (ref($navmap)) {
8529: return;
8530: }
8531: my $needs_hand_bubbles;
8532: my $map=$navmap->getResourceByUrl($sequence);
8533: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
8534: foreach my $res (@resources) {
8535: if (ref($res)) {
8536: if ($res->is_problem()) {
8537: my $partlist = $res->parts();
8538: foreach my $part (@{ $partlist }) {
8539: my @types = $res->responseType($part);
8540: if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
8541: $needs_hand_bubbles = 1;
8542: last;
8543: }
8544: }
8545: }
8546: }
8547: }
8548: if ($needs_hand_bubbles) {
8549: my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
8550: my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
8551: return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
8552: &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 />').
8553: '<label><input type="radio" name="scantron_lastbubblepoints" value="'.$bubbles_per_row.'" checked="checked" />'.&mt('[quant,_1,point]',$bubbles_per_row).'</label> '.&mt('or').' '.
8554: '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
8555: }
8556: return;
8557: }
8558:
8559: sub scantron_process_students {
8560: my ($r) = @_;
8561:
8562: my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
8563: my ($symb)=&get_symb($r);
8564: if (!$symb) {
8565: return '';
8566: }
8567: my $default_form_data=&defaultFormData($symb);
8568:
8569: my %scantron_config=&Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
8570: my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
8571: my ($scanlines,$scan_data)=&scantron_getfile();
8572: my $classlist=&Apache::loncoursedata::get_classlist();
8573: my %idmap=&username_to_idmap($classlist);
8574: my $navmap=Apache::lonnavmaps::navmap->new();
8575: unless (ref($navmap)) {
8576: $r->print(&navmap_errormsg());
8577: return '';
8578: }
8579: my $map=$navmap->getResourceByUrl($sequence);
8580: my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
8581: %grader_randomlists_by_symb);
8582: if (ref($map)) {
8583: $randomorder = $map->randomorder();
8584: $randompick = $map->randompick();
8585: } else {
8586: $r->print(&navmap_errormsg());
8587: return '';
8588: }
8589: my $nav_error;
8590: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
8591: if ($randomorder || $randompick) {
8592: $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
8593: if ($nav_error) {
8594: $r->print(&navmap_errormsg());
8595: return '';
8596: }
8597: }
8598: &graders_resources_pass(\@resources,\%grader_partids_by_symb,
8599: \%grader_randomlists_by_symb,$bubbles_per_row);
8600:
8601: my ($uname,$udom);
8602: my $result= <<SCANTRONFORM;
8603: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
8604: <input type="hidden" name="command" value="scantron_configphase" />
8605: $default_form_data
8606: SCANTRONFORM
8607: $r->print($result);
8608:
8609: my @delayqueue;
8610: my (%completedstudents,%scandata);
8611:
8612: my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
8613: my $count=&get_todo_count($scanlines,$scan_data);
8614: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
8615: &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
8616: 'Processing first student');
8617: $r->print('<br />');
8618: my $start=&Time::HiRes::time();
8619: my $i=-1;
8620: my $started;
8621:
8622: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
8623: if ($nav_error) {
8624: $r->print(&navmap_errormsg());
8625: return '';
8626: }
8627:
8628: # If an ssi failed in scantron_get_maxbubble, put an error message out to
8629: # the user and return.
8630:
8631: if ($ssi_error) {
8632: $r->print("</form>");
8633: &ssi_print_error($r);
8634: $r->print(&show_grading_menu_form($symb));
8635: &Apache::lonnet::remove_lock($lock);
8636: return ''; # Dunno why the other returns return '' rather than just returning.
8637: }
8638:
8639: my %lettdig = &Apache::lonnet::letter_to_digits();
8640: my $numletts = scalar(keys(%lettdig));
8641: my %orderedforcode;
8642:
8643: while ($i<$scanlines->{'count'}) {
8644: ($uname,$udom)=('','');
8645: $i++;
8646: my $line=&scantron_get_line($scanlines,$scan_data,$i);
8647: if ($line=~/^[\s\cz]*$/) { next; }
8648: if ($started) {
8649: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
8650: 'last student');
8651: }
8652: $started=1;
8653: my %respnumlookup = ();
8654: my %startline = ();
8655: my $total;
8656: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
8657: $scan_data,undef,\%idmap,$randomorder,
8658: $randompick,$sequence,\@master_seq,
8659: \%symb_to_resource,\%grader_partids_by_symb,
8660: \%orderedforcode,\%respnumlookup,\%startline,
8661: \$total);
8662: unless ($uname=&scantron_find_student($scan_record,$scan_data,
8663: \%idmap,$i)) {
8664: &scantron_add_delay(\@delayqueue,$line,
8665: 'Unable to find a student that matches',1);
8666: next;
8667: }
8668: if (exists $completedstudents{$uname}) {
8669: &scantron_add_delay(\@delayqueue,$line,
8670: 'Student '.$uname.' has multiple sheets',2);
8671: next;
8672: }
8673: my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
8674: my $user = $uname.':'.$usec;
8675: ($uname,$udom)=split(/:/,$uname);
8676:
8677: my $scancode;
8678: if ((exists($scan_record->{'scantron.CODE'})) &&
8679: (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
8680: $scancode = $scan_record->{'scantron.CODE'};
8681: } else {
8682: $scancode = '';
8683: }
8684:
8685: my @mapresources = @resources;
8686: if ($randomorder || $randompick) {
8687: @mapresources =
8688: &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
8689: \%orderedforcode);
8690: }
8691: my (%partids_by_symb,$res_error);
8692: foreach my $resource (@mapresources) {
8693: my $ressymb;
8694: if (ref($resource)) {
8695: $ressymb = $resource->symb();
8696: } else {
8697: $res_error = 1;
8698: last;
8699: }
8700: if ((exists($grader_randomlists_by_symb{$ressymb})) ||
8701: (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
8702: my $currcode;
8703: if (exists($grader_randomlists_by_symb{$ressymb})) {
8704: $currcode = $scancode;
8705: }
8706: my ($analysis,$parts) =
8707: &scantron_partids_tograde($resource,$env{'request.course.id'},
8708: $uname,$udom,undef,$bubbles_per_row,
8709: $currcode);
8710: $partids_by_symb{$ressymb} = $parts;
8711: } else {
8712: $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
8713: }
8714: }
8715:
8716: if ($res_error) {
8717: &scantron_add_delay(\@delayqueue,$line,
8718: 'An error occurred while grading student '.$uname,2);
8719: next;
8720: }
8721:
8722: &Apache::lonxml::clear_problem_counter();
8723: &Apache::lonnet::appenv($scan_record);
8724:
8725: if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
8726: &scantron_putfile($scanlines,$scan_data);
8727: }
8728:
8729: if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
8730: \@mapresources,\%partids_by_symb,
8731: $bubbles_per_row,$randomorder,$randompick,
8732: \%respnumlookup,\%startline)
8733: eq 'ssi_error') {
8734: $ssi_error = 0; # So end of handler error message does not trigger.
8735: $r->print("</form>");
8736: &ssi_print_error($r);
8737: $r->print(&show_grading_menu_form($symb));
8738: &Apache::lonnet::remove_lock($lock);
8739: return ''; # Why return ''? Beats me.
8740: }
8741:
8742: if (($scancode) && ($randomorder || $randompick)) {
8743: my $parmresult =
8744: &Apache::lonparmset::storeparm_by_symb($symb,
8745: '0_examcode',2,$scancode,
8746: 'string_examcode',$uname,
8747: $udom);
8748: }
8749: $completedstudents{$uname}={'line'=>$line};
8750: if ($env{'form.verifyrecord'}) {
8751: my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
8752: if ($randompick) {
8753: if ($total) {
8754: $lastpos = $total*$scantron_config{'Qlength'};
8755: }
8756: }
8757:
8758: my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
8759: chomp($studentdata);
8760: $studentdata =~ s/\r$//;
8761: my $studentrecord = '';
8762: my $counter = -1;
8763: foreach my $resource (@mapresources) {
8764: my $ressymb = $resource->symb();
8765: ($counter,my $recording) =
8766: &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
8767: $counter,$studentdata,$partids_by_symb{$ressymb},
8768: \%scantron_config,\%lettdig,$numletts,$randomorder,
8769: $randompick,\%respnumlookup,\%startline);
8770: $studentrecord .= $recording;
8771: }
8772: if ($studentrecord ne $studentdata) {
8773: &Apache::lonxml::clear_problem_counter();
8774: if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
8775: \@mapresources,\%partids_by_symb,
8776: $bubbles_per_row,$randomorder,$randompick,
8777: \%respnumlookup,\%startline)
8778: eq 'ssi_error') {
8779: $ssi_error = 0; # So end of handler error message does not trigger.
8780: $r->print("</form>");
8781: &ssi_print_error($r);
8782: $r->print(&show_grading_menu_form($symb));
8783: &Apache::lonnet::remove_lock($lock);
8784: delete($completedstudents{$uname});
8785: return '';
8786: }
8787: $counter = -1;
8788: $studentrecord = '';
8789: foreach my $resource (@mapresources) {
8790: my $ressymb = $resource->symb();
8791: ($counter,my $recording) =
8792: &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
8793: $counter,$studentdata,$partids_by_symb{$ressymb},
8794: \%scantron_config,\%lettdig,$numletts,
8795: $randomorder,$randompick,\%respnumlookup,
8796: \%startline);
8797: $studentrecord .= $recording;
8798: }
8799: if ($studentrecord ne $studentdata) {
8800: $r->print('<p><span class="LC_warning">');
8801: if ($scancode eq '') {
8802: $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
8803: $uname.':'.$udom,$scan_record->{'scantron.ID'}));
8804: } else {
8805: $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
8806: $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
8807: }
8808: $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
8809: &Apache::loncommon::start_data_table_header_row()."\n".
8810: '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
8811: &Apache::loncommon::end_data_table_header_row()."\n".
8812: &Apache::loncommon::start_data_table_row().
8813: '<td>'.&mt('Bubblesheet').'</td>'.
8814: '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
8815: &Apache::loncommon::end_data_table_row().
8816: &Apache::loncommon::start_data_table_row().
8817: '<td>'.&mt('Stored submissions').'</td>'.
8818: '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
8819: &Apache::loncommon::end_data_table_row().
8820: &Apache::loncommon::end_data_table().'</p>');
8821: } else {
8822: $r->print('<br /><span class="LC_warning">'.
8823: &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 />'.
8824: &mt("As a consequence, this user's submission history records two tries.").
8825: '</span><br />');
8826: }
8827: }
8828: }
8829: if (&Apache::loncommon::connection_aborted($r)) { last; }
8830: } continue {
8831: &Apache::lonxml::clear_problem_counter();
8832: &Apache::lonnet::delenv('scantron.');
8833: }
8834: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
8835: &Apache::lonnet::remove_lock($lock);
8836: # my $lasttime = &Time::HiRes::time()-$start;
8837: # $r->print("<p>took $lasttime</p>");
8838:
8839: $r->print("</form>");
8840: $r->print(&show_grading_menu_form($symb));
8841: return '';
8842: }
8843:
8844: sub graders_resources_pass {
8845: my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
8846: $bubbles_per_row) = @_;
8847: if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) &&
8848: (ref($grader_randomlists_by_symb) eq 'HASH')) {
8849: foreach my $resource (@{$resources}) {
8850: my $ressymb = $resource->symb();
8851: my ($analysis,$parts) =
8852: &scantron_partids_tograde($resource,$env{'request.course.id'},
8853: $env{'user.name'},$env{'user.domain'},
8854: 1,$bubbles_per_row);
8855: $grader_partids_by_symb->{$ressymb} = $parts;
8856: if (ref($analysis) eq 'HASH') {
8857: if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
8858: $grader_randomlists_by_symb->{$ressymb} =
8859: $analysis->{'parts_withrandomlist'};
8860: }
8861: }
8862: }
8863: }
8864: return;
8865: }
8866:
8867: =pod
8868:
8869: =item users_order
8870:
8871: Returns array of resources in current map, ordered based on either CODE,
8872: if this is a CODEd exam, or based on student's identity if this is a
8873: "NAMEd" exam.
8874:
8875: Should be used when randomorder and/or randompick applied when the
8876: corresponding exam was printed, prior to students completing bubblesheets
8877: for the version of the exam the student received.
8878:
8879: =cut
8880:
8881: sub users_order {
8882: my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
8883: my @mapresources;
8884: unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
8885: return @mapresources;
8886: }
8887: if ($scancode) {
8888: if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
8889: @mapresources = @{$orderedforcode->{$scancode}};
8890: } else {
8891: $env{'form.CODE'} = $scancode;
8892: my $actual_seq =
8893: &Apache::lonprintout::master_seq_to_person_seq($mapurl,
8894: $master_seq,
8895: $user,$scancode,1);
8896: if (ref($actual_seq) eq 'ARRAY') {
8897: @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
8898: if (ref($orderedforcode) eq 'HASH') {
8899: if (@mapresources > 0) {
8900: $orderedforcode->{$scancode} = \@mapresources;
8901: }
8902: }
8903: }
8904: delete($env{'form.CODE'});
8905: }
8906: } else {
8907: my $actual_seq =
8908: &Apache::lonprintout::master_seq_to_person_seq($mapurl,
8909: $master_seq,
8910: $user,undef,1);
8911: if (ref($actual_seq) eq 'ARRAY') {
8912: @mapresources =
8913: map { $symb_to_resource->{$_}; } @{$actual_seq};
8914: }
8915: }
8916: return @mapresources;
8917: }
8918:
8919: sub grade_student_bubbles {
8920: my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
8921: $randomorder,$randompick,$respnumlookup,$startline) = @_;
8922: my $uselookup = 0;
8923: if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
8924: (ref($startline) eq 'HASH')) {
8925: $uselookup = 1;
8926: }
8927:
8928: if (ref($resources) eq 'ARRAY') {
8929: my $count = 0;
8930: foreach my $resource (@{$resources}) {
8931: my $ressymb = $resource->symb();
8932: my %form = ('submitted' => 'scantron',
8933: 'grade_target' => 'grade',
8934: 'grade_username' => $uname,
8935: 'grade_domain' => $udom,
8936: 'grade_courseid' => $env{'request.course.id'},
8937: 'grade_symb' => $ressymb,
8938: 'CODE' => $scancode
8939: );
8940: if ($bubbles_per_row ne '') {
8941: $form{'bubbles_per_row'} = $bubbles_per_row;
8942: }
8943: if ($env{'form.scantron_lastbubblepoints'} ne '') {
8944: $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
8945: }
8946: if (ref($parts) eq 'HASH') {
8947: if (ref($parts->{$ressymb}) eq 'ARRAY') {
8948: foreach my $part (@{$parts->{$ressymb}}) {
8949: if ($uselookup) {
8950: $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
8951: } else {
8952: $form{'scantron_questnum_start.'.$part} =
8953: 1+$env{'form.scantron.first_bubble_line.'.$count};
8954: }
8955: $count++;
8956: }
8957: }
8958: }
8959: my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
8960: return 'ssi_error' if ($ssi_error);
8961: last if (&Apache::loncommon::connection_aborted($r));
8962: }
8963: }
8964: return;
8965: }
8966:
8967: sub scantron_upload_scantron_data {
8968: my ($r)=@_;
8969: my $dom = $env{'request.role.domain'};
8970: my ($formatoptions,$formattitle,$formatjs) = &scantron_upload_dataformat($dom);
8971: my $domdesc = &Apache::lonnet::domain($dom,'description');
8972: $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
8973: my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
8974: 'domainid',
8975: 'coursename',$dom);
8976: my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
8977: (' 'x2).&mt('(shows course personnel)');
8978: my ($symb) = &get_symb($r,1);
8979: my $default_form_data=&defaultFormData($symb);
8980: my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
8981: &js_escape(\$nofile_alert);
8982: 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.");
8983: &js_escape(\$nocourseid_alert);
8984: $r->print(&Apache::lonhtmlcommon::scripttag('
8985: function checkUpload(formname) {
8986: if (formname.upfile.value == "") {
8987: alert("'.$nofile_alert.'");
8988: return false;
8989: }
8990: if (formname.courseid.value == "") {
8991: alert("'.$nocourseid_alert.'");
8992: return false;
8993: }
8994: formname.submit();
8995: }
8996:
8997: function ToSyllabus() {
8998: var cdom = '."'$dom'".';
8999: var cnum = document.rules.courseid.value;
9000: if (cdom == "" || cdom == null) {
9001: return;
9002: }
9003: if (cnum == "" || cnum == null) {
9004: return;
9005: }
9006: syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
9007: "height=350,width=350,scrollbars=yes,menubar=no");
9008: return;
9009: }
9010:
9011: '.$formatjs.'
9012: '));
9013: $r->print('
9014: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
9015:
9016: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
9017: '.$default_form_data.
9018: &Apache::lonhtmlcommon::start_pick_box().
9019: &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
9020: '<input name="courseid" type="text" size="30" />'.$select_link.
9021: &Apache::lonhtmlcommon::row_closure().
9022: &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
9023: '<input name="coursename" type="text" size="30" />'.$syllabuslink.
9024: &Apache::lonhtmlcommon::row_closure().
9025: &Apache::lonhtmlcommon::row_title(&mt('Domain')).
9026: '<input name="domainid" type="hidden" />'.$domdesc.
9027: &Apache::lonhtmlcommon::row_closure());
9028: if ($formatoptions) {
9029: $r->print(&Apache::lonhtmlcommon::row_title($formattitle).$formatoptions.
9030: &Apache::lonhtmlcommon::row_closure());
9031: }
9032: $r->print(
9033: &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
9034: '<input type="file" name="upfile" size="50" />'.
9035: &Apache::lonhtmlcommon::row_closure(1).
9036: &Apache::lonhtmlcommon::end_pick_box().'<br />
9037:
9038: <input name="command" value="scantronupload_save" type="hidden" />
9039: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
9040: </form>
9041: ');
9042: return '';
9043: }
9044:
9045: sub scantron_upload_dataformat {
9046: my ($dom) = @_;
9047: my ($formatoptions,$formattitle,$formatjs);
9048: $formatjs = <<'END';
9049: function toggleScantab(form) {
9050: return;
9051: }
9052: END
9053: my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$dom);
9054: if (ref($domconfig{'scantron'}) eq 'HASH') {
9055: if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
9056: if (keys(%{$domconfig{'scantron'}{'config'}}) > 1) {
9057: if (($domconfig{'scantron'}{'config'}{'dat'}) &&
9058: (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH')) {
9059: if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
9060: if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
9061: my ($onclick,$formatextra,$singleline);
9062: my @lines = &Apache::lonnet::get_scantronformat_file();
9063: my $count = 0;
9064: foreach my $line (@lines) {
9065: next if ($line =~ /^#/);
9066: $singleline = $line;
9067: $count ++;
9068: }
9069: if ($count > 1) {
9070: $formatextra = '<div style="display:none" id="bubbletype">'.
9071: '<span class="LC_nobreak">'.
9072: &mt('Bubblesheet type:').' '.
9073: &scantron_scantab().'</span></div>';
9074: $onclick = ' onclick="toggleScantab(this.form);"';
9075: $formatjs = <<"END";
9076: function toggleScantab(form) {
9077: var divid = 'bubbletype';
9078: if (document.getElementById(divid)) {
9079: var radioname = 'fileformat';
9080: var num = form.elements[radioname].length;
9081: if (num) {
9082: for (var i=0; i<num; i++) {
9083: if (form.elements[radioname][i].checked) {
9084: var chosen = form.elements[radioname][i].value;
9085: if (chosen == 'dat') {
9086: document.getElementById(divid).style.display = 'none';
9087: } else if (chosen == 'csv') {
9088: document.getElementById(divid).style.display = 'block';
9089: }
9090: }
9091: }
9092: }
9093: }
9094: return;
9095: }
9096:
9097: END
9098: } elsif ($count == 1) {
9099: my $formatname = (split(/:/,$singleline,2))[0];
9100: $formatextra = '<input type="hidden" name="scantron_format" value="'.$formatname.'" />';
9101: }
9102: $formattitle = &mt('File format');
9103: $formatoptions = '<label><input name="fileformat" type="radio" value="dat" checked="checked"'.$onclick.' />'.
9104: &mt('Plain Text (no delimiters)').
9105: '</label>'.(' 'x2).
9106: '<label><input name="fileformat" type="radio" value="csv"'.$onclick.' />'.
9107: &mt('Comma separated values').'</label>'.$formatextra;
9108: }
9109: }
9110: }
9111: } elsif (keys(%{$domconfig{'scantron'}{'config'}}) == 1) {
9112: if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
9113: if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}})) {
9114: $formattitle = &mt('Bubblesheet type');
9115: $formatoptions = &scantron_scantab();
9116: }
9117: }
9118: }
9119: }
9120: }
9121: return ($formatoptions,$formattitle,$formatjs);
9122: }
9123:
9124: sub scantron_upload_scantron_data_save {
9125: my($r)=@_;
9126: my ($symb)=&get_symb($r,1);
9127: my $doanotherupload=
9128: '<br /><form action="/adm/grades" method="post">'."\n".
9129: '<input type="hidden" name="command" value="scantronupload" />'."\n".
9130: '<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
9131: '</form>'."\n";
9132: if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
9133: !&Apache::lonnet::allowed('usc',
9134: $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
9135: $r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
9136: if ($symb) {
9137: $r->print(&show_grading_menu_form($symb));
9138: } else {
9139: $r->print($doanotherupload);
9140: }
9141: return '';
9142: }
9143: my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
9144: my $uploadedfile;
9145: $r->print('<p>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</p>');
9146: if (length($env{'form.upfile'}) < 2) {
9147: $r->print(
9148: &Apache::lonhtmlcommon::confirm_success(
9149: &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
9150: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
9151: } else {
9152: my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$env{'form.domainid'});
9153: my $parser;
9154: if (ref($domconfig{'scantron'}) eq 'HASH') {
9155: if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
9156: my $is_csv;
9157: my @possibles = keys(%{$domconfig{'scantron'}{'config'}});
9158: if (@possibles > 1) {
9159: if ($env{'form.fileformat'} eq 'csv') {
9160: if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
9161: if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
9162: if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
9163: $is_csv = 1;
9164: }
9165: }
9166: }
9167: }
9168: } elsif (@possibles == 1) {
9169: if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
9170: if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
9171: if (keys(%{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}}) > 1) {
9172: $is_csv = 1;
9173: }
9174: }
9175: }
9176: }
9177: if ($is_csv) {
9178: $parser = $domconfig{'scantron'}{'config'}{'csv'};
9179: }
9180: }
9181: }
9182: my $result =
9183: &Apache::lonnet::userfileupload('upfile','scantron','scantron',$parser,'','',
9184: $env{'form.courseid'},$env{'form.domainid'});
9185: if ($result =~ m{^/uploaded/}) {
9186: $r->print(
9187: &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
9188: &mt('Uploaded [_1] bytes of data into location: [_2]',
9189: (length($env{'form.upfile'})-1),
9190: '<span class="LC_filename">'.$result.'</span>'));
9191: ($uploadedfile) = ($result =~ m{/([^/]+)$});
9192: $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
9193: $env{'form.courseid'},$uploadedfile));
9194: } else {
9195: $r->print(
9196: &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
9197: &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
9198: $result,
9199: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
9200: }
9201: }
9202: if ($symb) {
9203: $r->print(&scantron_selectphase($r,$uploadedfile));
9204: } else {
9205: $r->print($doanotherupload);
9206: }
9207: return '';
9208: }
9209:
9210: sub validate_uploaded_scantron_file {
9211: my ($cdom,$cname,$fname) = @_;
9212: my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
9213: my @lines;
9214: if ($scanlines ne '-1') {
9215: @lines=split("\n",$scanlines,-1);
9216: }
9217: my $output;
9218: if (@lines) {
9219: my (%counts,$max_match_format);
9220: my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
9221: my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
9222: my %idmap = &username_to_idmap($classlist);
9223: foreach my $key (keys(%idmap)) {
9224: my $lckey = lc($key);
9225: $idmap{$lckey} = $idmap{$key};
9226: }
9227: my %unique_formats;
9228: my @formatlines = &Apache::lonnet::get_scantronformat_file();
9229: foreach my $line (@formatlines) {
9230: chomp($line);
9231: my @config = split(/:/,$line);
9232: my $idstart = $config[5];
9233: my $idlength = $config[6];
9234: if (($idstart ne '') && ($idlength > 0)) {
9235: if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
9236: push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]);
9237: } else {
9238: $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
9239: }
9240: }
9241: }
9242: foreach my $key (keys(%unique_formats)) {
9243: my ($idstart,$idlength) = split(':',$key);
9244: %{$counts{$key}} = (
9245: 'found' => 0,
9246: 'total' => 0,
9247: );
9248: foreach my $line (@lines) {
9249: next if ($line =~ /^#/);
9250: next if ($line =~ /^[\s\cz]*$/);
9251: my $id = substr($line,$idstart-1,$idlength);
9252: $id = lc($id);
9253: if (exists($idmap{$id})) {
9254: $counts{$key}{'found'} ++;
9255: }
9256: $counts{$key}{'total'} ++;
9257: }
9258: if ($counts{$key}{'total'}) {
9259: my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
9260: if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
9261: $max_match_pct = $percent_match;
9262: $max_match_format = $key;
9263: $found_match_count = $counts{$key}{'found'};
9264: $max_match_count = $counts{$key}{'total'};
9265: }
9266: }
9267: }
9268: if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
9269: my $format_descs;
9270: my $numwithformat = @{$unique_formats{$max_match_format}};
9271: for (my $i=0; $i<$numwithformat; $i++) {
9272: my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
9273: if ($i<$numwithformat-2) {
9274: $format_descs .= '"<i>'.$desc.'</i>", ';
9275: } elsif ($i==$numwithformat-2) {
9276: $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
9277: } elsif ($i==$numwithformat-1) {
9278: $format_descs .= '"<i>'.$desc.'</i>"';
9279: }
9280: }
9281: my $showpct = sprintf("%.0f",$max_match_pct).'%';
9282: $output .= '<br />';
9283: if ($found_match_count == $max_match_count) {
9284: # 100% matching entries
9285: $output .= &Apache::lonhtmlcommon::confirm_success(
9286: &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
9287: '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
9288: &mt('Comparison of student IDs in the uploaded file with'.
9289: ' the course roster found matches for [_1] of the [_2] entries'.
9290: ' in the file (for the format defined for [_3]).',
9291: '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
9292: } else {
9293: # Not all entries matching? -> Show warning and additional info
9294: $output .=
9295: &Apache::lonhtmlcommon::confirm_success(
9296: &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
9297: '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
9298: &mt('Not all entries could be matched!'),1).'<br />'.
9299: &mt('Comparison of student IDs in the uploaded file with'.
9300: ' the course roster found matches for [_1] of the [_2] entries'.
9301: ' in the file (for the format defined for [_3]).',
9302: '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
9303: '<p class="LC_info">'.
9304: &mt('A low percentage of matches results from one of the following:').
9305: '</p><ul>'.
9306: '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
9307: '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
9308: '<i>'.$cdom.'</i>').'</li>'.
9309: '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
9310: '<li>'.&mt('The course roster is not up to date.').'</li>'.
9311: '</ul>';
9312: }
9313: }
9314: } else {
9315: $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
9316: }
9317: return $output;
9318: }
9319:
9320: sub valid_file {
9321: my ($requested_file)=@_;
9322: foreach my $filename (sort(&scantron_filenames())) {
9323: if ($requested_file eq $filename) { return 1; }
9324: }
9325: return 0;
9326: }
9327:
9328: sub scantron_download_scantron_data {
9329: my ($r)=@_;
9330: my ($symb) = &get_symb($r,1);
9331: my $default_form_data=&defaultFormData($symb);
9332: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
9333: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
9334: my $file=$env{'form.scantron_selectfile'};
9335: if (! &valid_file($file)) {
9336: $r->print('
9337: <p>
9338: '.&mt('The requested filename was invalid.').'
9339: </p>
9340: ');
9341: $r->print(&show_grading_menu_form($symb));
9342: return;
9343: }
9344: my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
9345: my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
9346: my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
9347: &Apache::lonnet::allowuploaded('/adm/grades',$orig);
9348: &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
9349: &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
9350: $r->print('
9351: <p>
9352: '.&mt('[_1]Original[_2] file as uploaded by bubblesheet scanning office.',
9353: '<a href="'.$orig.'">','</a>').'
9354: </p>
9355: <p>
9356: '.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
9357: '<a href="'.$corrected.'">','</a>').'
9358: </p>
9359: <p>
9360: '.&mt('[_1]Skipped[_2], a file of records that were skipped.',
9361: '<a href="'.$skipped.'">','</a>').'
9362: </p>
9363: ');
9364: $r->print(&show_grading_menu_form($symb));
9365: return '';
9366: }
9367:
9368: sub checkscantron_results {
9369: my ($r) = @_;
9370: my ($symb)=&get_symb($r);
9371: if (!$symb) {return '';}
9372: my $grading_menu_button=&show_grading_menu_form($symb);
9373: my $cid = $env{'request.course.id'};
9374: my %lettdig = &Apache::lonnet::letter_to_digits();
9375: my $numletts = scalar(keys(%lettdig));
9376: my $cnum = $env{'course.'.$cid.'.num'};
9377: my $cdom = $env{'course.'.$cid.'.domain'};
9378: my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
9379: my %record;
9380: my %scantron_config =
9381: &Apache::lonnet::get_scantron_config($env{'form.scantron_format'});
9382: my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
9383: my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
9384: my $classlist=&Apache::loncoursedata::get_classlist();
9385: my %idmap=&Apache::grades::username_to_idmap($classlist);
9386: my $navmap=Apache::lonnavmaps::navmap->new();
9387: unless (ref($navmap)) {
9388: $r->print(&navmap_errormsg());
9389: return '';
9390: }
9391: my $map=$navmap->getResourceByUrl($sequence);
9392: my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
9393: %grader_randomlists_by_symb,%orderedforcode);
9394: if (ref($map)) {
9395: $randomorder=$map->randomorder();
9396: $randompick=$map->randompick();
9397: }
9398: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
9399: my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
9400: if ($nav_error) {
9401: $r->print(&navmap_errormsg());
9402: return '';
9403: }
9404: &graders_resources_pass(\@resources,\%grader_partids_by_symb,
9405: \%grader_randomlists_by_symb,$bubbles_per_row);
9406: my ($uname,$udom);
9407: my (%scandata,%lastname,%bylast);
9408: $r->print('
9409: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
9410:
9411: my @delayqueue;
9412: my %completedstudents;
9413:
9414: my $count=&get_todo_count($scanlines,$scan_data);
9415: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
9416: my ($username,$domain,$started);
9417: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
9418: if ($nav_error) {
9419: $r->print(&navmap_errormsg());
9420: return '';
9421: }
9422:
9423: &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
9424: 'Processing first student');
9425: my $start=&Time::HiRes::time();
9426: my $i=-1;
9427:
9428: while ($i<$scanlines->{'count'}) {
9429: ($username,$domain,$uname)=('','','');
9430: $i++;
9431: my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
9432: if ($line=~/^[\s\cz]*$/) { next; }
9433: if ($started) {
9434: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
9435: 'last student');
9436: }
9437: $started=1;
9438: my $scan_record=
9439: &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
9440: $scan_data);
9441: unless ($uname=&scantron_find_student($scan_record,$scan_data,
9442: \%idmap,$i)) {
9443: &Apache::grades::scantron_add_delay(\@delayqueue,$line,
9444: 'Unable to find a student that matches',1);
9445: next;
9446: }
9447: if (exists $completedstudents{$uname}) {
9448: &Apache::grades::scantron_add_delay(\@delayqueue,$line,
9449: 'Student '.$uname.' has multiple sheets',2);
9450: next;
9451: }
9452: my $pid = $scan_record->{'scantron.ID'};
9453: $lastname{$pid} = $scan_record->{'scantron.LastName'};
9454: push(@{$bylast{$lastname{$pid}}},$pid);
9455: my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
9456: my $user = $uname.':'.$usec;
9457: ($username,$domain)=split(/:/,$uname);
9458:
9459: my $scancode;
9460: if ((exists($scan_record->{'scantron.CODE'})) &&
9461: (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
9462: $scancode = $scan_record->{'scantron.CODE'};
9463: } else {
9464: $scancode = '';
9465: }
9466:
9467: my @mapresources = @resources;
9468: my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
9469: my %respnumlookup=();
9470: my %startline=();
9471: if ($randomorder || $randompick) {
9472: @mapresources =
9473: &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
9474: \%orderedforcode);
9475: my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
9476: $scan_record,\@master_seq,\%symb_to_resource,
9477: \%grader_partids_by_symb,\%orderedforcode,
9478: \%respnumlookup,\%startline);
9479: if ($randompick && $total) {
9480: $lastpos = $total*$scantron_config{'Qlength'};
9481: }
9482: }
9483: $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
9484: chomp($scandata{$pid});
9485: $scandata{$pid} =~ s/\r$//;
9486:
9487: my $counter = -1;
9488: foreach my $resource (@mapresources) {
9489: my $parts;
9490: my $ressymb = $resource->symb();
9491: if ((exists($grader_randomlists_by_symb{$ressymb})) ||
9492: (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
9493: my $currcode;
9494: if (exists($grader_randomlists_by_symb{$ressymb})) {
9495: $currcode = $scancode;
9496: }
9497: (my $analysis,$parts) =
9498: &scantron_partids_tograde($resource,$env{'request.course.id'},
9499: $username,$domain,undef,
9500: $bubbles_per_row,$currcode);
9501: } else {
9502: $parts = $grader_partids_by_symb{$ressymb};
9503: }
9504: ($counter,my $recording) =
9505: &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
9506: $scandata{$pid},$parts,
9507: \%scantron_config,\%lettdig,$numletts,
9508: $randomorder,$randompick,
9509: \%respnumlookup,\%startline);
9510: $record{$pid} .= $recording;
9511: }
9512: }
9513: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
9514: $r->print('<br />');
9515: my ($okstudents,$badstudents,$numstudents,$passed,$failed);
9516: $passed = 0;
9517: $failed = 0;
9518: $numstudents = 0;
9519: foreach my $last (sort(keys(%bylast))) {
9520: if (ref($bylast{$last}) eq 'ARRAY') {
9521: foreach my $pid (sort(@{$bylast{$last}})) {
9522: my $showscandata = $scandata{$pid};
9523: my $showrecord = $record{$pid};
9524: $showscandata =~ s/\s/ /g;
9525: $showrecord =~ s/\s/ /g;
9526: if ($scandata{$pid} eq $record{$pid}) {
9527: my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
9528: $okstudents .= '<tr class="'.$css_class.'">'.
9529: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
9530: '</tr>'."\n".
9531: '<tr class="'.$css_class.'">'."\n".
9532: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
9533: $passed ++;
9534: } else {
9535: my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
9536: $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".
9537: '</tr>'."\n".
9538: '<tr class="'.$css_class.'">'."\n".
9539: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
9540: '</tr>'."\n";
9541: $failed ++;
9542: }
9543: $numstudents ++;
9544: }
9545: }
9546: }
9547: $r->print('<p>'.
9548: &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).',
9549: '<b>',
9550: $numstudents,
9551: '</b>',
9552: $env{'form.scantron_maxbubble'}).
9553: '</p>'
9554: );
9555: $r->print('<p>'
9556: .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
9557: .'<br />'
9558: .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
9559: .'</p>');
9560: if ($passed) {
9561: $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
9562: $r->print(&Apache::loncommon::start_data_table()."\n".
9563: &Apache::loncommon::start_data_table_header_row()."\n".
9564: '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
9565: &Apache::loncommon::end_data_table_header_row()."\n".
9566: $okstudents."\n".
9567: &Apache::loncommon::end_data_table().'<br />');
9568: }
9569: if ($failed) {
9570: $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
9571: $r->print(&Apache::loncommon::start_data_table()."\n".
9572: &Apache::loncommon::start_data_table_header_row()."\n".
9573: '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
9574: &Apache::loncommon::end_data_table_header_row()."\n".
9575: $badstudents."\n".
9576: &Apache::loncommon::end_data_table()).'<br />'.
9577: &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.');
9578: }
9579: $r->print('</form><br />'.$grading_menu_button);
9580: return;
9581: }
9582:
9583: sub verify_scantron_grading {
9584: my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
9585: $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
9586: $respnumlookup,$startline) = @_;
9587: my ($record,%expected,%startpos);
9588: return ($counter,$record) if (!ref($resource));
9589: return ($counter,$record) if (!$resource->is_problem());
9590: my $symb = $resource->symb();
9591: return ($counter,$record) if (ref($partids) ne 'ARRAY');
9592: foreach my $part_id (@{$partids}) {
9593: $counter ++;
9594: $expected{$part_id} = 0;
9595: my $respnum = $counter;
9596: if ($randomorder || $randompick) {
9597: $respnum = $respnumlookup->{$counter};
9598: $startpos{$part_id} = $startline->{$counter} + 1;
9599: } else {
9600: $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
9601: }
9602: if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
9603: my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
9604: foreach my $item (@sub_lines) {
9605: $expected{$part_id} += $item;
9606: }
9607: } else {
9608: $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
9609: }
9610: }
9611: if ($symb) {
9612: my %recorded;
9613: my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
9614: if ($returnhash{'version'}) {
9615: my %lasthash=();
9616: my $version;
9617: for ($version=1;$version<=$returnhash{'version'};$version++) {
9618: foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
9619: $lasthash{$key}=$returnhash{$version.':'.$key};
9620: }
9621: }
9622: foreach my $key (keys(%lasthash)) {
9623: if ($key =~ /\.scantron$/) {
9624: my $value = &unescape($lasthash{$key});
9625: my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
9626: if ($value eq '') {
9627: for (my $i=0; $i<$expected{$part_id}; $i++) {
9628: for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
9629: $recorded{$part_id} .= $scantron_config->{'Qoff'};
9630: }
9631: }
9632: } else {
9633: my @tocheck;
9634: my @items = split(//,$value);
9635: if (($scantron_config->{'Qon'} eq 'letter') ||
9636: ($scantron_config->{'Qon'} eq 'number')) {
9637: if (@items < $expected{$part_id}) {
9638: my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
9639: my @singles = split(//,$fragment);
9640: foreach my $pos (@singles) {
9641: if ($pos eq ' ') {
9642: push(@tocheck,$pos);
9643: } else {
9644: my $next = shift(@items);
9645: push(@tocheck,$next);
9646: }
9647: }
9648: } else {
9649: @tocheck = @items;
9650: }
9651: foreach my $letter (@tocheck) {
9652: if ($scantron_config->{'Qon'} eq 'letter') {
9653: if ($letter !~ /^[A-J]$/) {
9654: $letter = $scantron_config->{'Qoff'};
9655: }
9656: $recorded{$part_id} .= $letter;
9657: } elsif ($scantron_config->{'Qon'} eq 'number') {
9658: my $digit;
9659: if ($letter !~ /^[A-J]$/) {
9660: $digit = $scantron_config->{'Qoff'};
9661: } else {
9662: $digit = $lettdig->{$letter};
9663: }
9664: $recorded{$part_id} .= $digit;
9665: }
9666: }
9667: } else {
9668: @tocheck = @items;
9669: for (my $i=0; $i<$expected{$part_id}; $i++) {
9670: my $curr_sub = shift(@tocheck);
9671: my $digit;
9672: if ($curr_sub =~ /^[A-J]$/) {
9673: $digit = $lettdig->{$curr_sub}-1;
9674: }
9675: if ($curr_sub eq 'J') {
9676: $digit += scalar($numletts);
9677: }
9678: for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
9679: if ($j == $digit) {
9680: $recorded{$part_id} .= $scantron_config->{'Qon'};
9681: } else {
9682: $recorded{$part_id} .= $scantron_config->{'Qoff'};
9683: }
9684: }
9685: }
9686: }
9687: }
9688: }
9689: }
9690: }
9691: foreach my $part_id (@{$partids}) {
9692: if ($recorded{$part_id} eq '') {
9693: for (my $i=0; $i<$expected{$part_id}; $i++) {
9694: for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
9695: $recorded{$part_id} .= $scantron_config->{'Qoff'};
9696: }
9697: }
9698: }
9699: $record .= $recorded{$part_id};
9700: }
9701: }
9702: return ($counter,$record);
9703: }
9704:
9705: #-------- end of section for handling grading scantron forms -------
9706: #
9707: #-------------------------------------------------------------------
9708:
9709: #-------------------------- Menu interface -------------------------
9710: #
9711: #--- Show a Grading Menu button - Calls the next routine ---
9712: sub show_grading_menu_form {
9713: my ($symb)=@_;
9714: my $result.='<br /><form action="/adm/grades" method="post">'."\n".
9715: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
9716: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
9717: '<input type="hidden" name="command" value="gradingmenu" />'."\n".
9718: '<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
9719: '</form>'."\n";
9720: return $result;
9721: }
9722:
9723: # -- Retrieve choices for grading form
9724: sub savedState {
9725: my %savedState = ();
9726: if ($env{'form.saveState'}) {
9727: foreach (split(/:/,$env{'form.saveState'})) {
9728: my ($key,$value) = split(/=/,$_,2);
9729: $savedState{$key} = $value;
9730: }
9731: }
9732: return \%savedState;
9733: }
9734:
9735: #--- Href with symb and command ---
9736:
9737: sub href_symb_cmd {
9738: my ($symb,$cmd)=@_;
9739: return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&command='.$cmd;
9740: }
9741:
9742: sub grading_menu {
9743: my ($request) = @_;
9744: my ($symb)=&get_symb($request);
9745: if (!$symb) {return '';}
9746: my $probTitle = &Apache::lonnet::gettitle($symb);
9747: my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
9748:
9749: $request->print($table);
9750: my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
9751: 'handgrade'=>$hdgrade,
9752: 'probTitle'=>$probTitle,
9753: 'command'=>'submit_options',
9754: 'saveState'=>"",
9755: 'gradingMenu'=>1,
9756: 'showgrading'=>"yes");
9757:
9758: my $url1 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
9759:
9760: $fields{'command'} = 'csvform';
9761: my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
9762:
9763: $fields{'command'} = 'processclicker';
9764: my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
9765:
9766: $fields{'command'} = 'scantron_selectphase';
9767: my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
9768:
9769: my @menu = ({ categorytitle=>'Course Grading',
9770: items =>[
9771: { linktext => 'Manual Grading/View Submissions',
9772: url => $url1,
9773: permission => 'F',
9774: icon => 'edit-find-replace.png',
9775: linktitle => 'Start the process of hand grading submissions.'
9776: },
9777: { linktext => 'Upload Scores',
9778: url => $url2,
9779: permission => 'F',
9780: icon => 'uploadscores.png',
9781: linktitle => 'Specify a file containing the class scores for current resource.'
9782: },
9783: { linktext => 'Process Clicker',
9784: url => $url3,
9785: permission => 'F',
9786: icon => 'addClickerInfoFile.png',
9787: linktitle => 'Specify a file containing the clicker information for this resource.'
9788: },
9789: { linktext => 'Grade/Manage/Review Bubblesheets',
9790: url => $url4,
9791: permission => 'F',
9792: icon => 'stat.png',
9793: linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
9794: }
9795: ]
9796: });
9797:
9798: #$fields{'command'} = 'verify';
9799: #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
9800: #
9801: # Create the menu
9802: my $Str;
9803: # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
9804: $Str .= '<form method="post" action="" name="gradingMenu">';
9805: $Str .= '<input type="hidden" name="command" value="" />'.
9806: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
9807: '<input type="hidden" name="handgrade" value="'.$hdgrade.'" />'."\n".
9808: '<input type="hidden" name="probTitle" value="'.$probTitle.'" />'."\n".
9809: '<input type="hidden" name="saveState" value="" />'."\n".
9810: '<input type="hidden" name="gradingMenu" value="1" />'."\n".
9811: '<input type="hidden" name="showgrading" value="yes" />'."\n";
9812:
9813: $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
9814: #$menudata->{'jscript'}
9815: $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt No.').'" '.
9816: ' onclick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
9817: ' /> '.
9818: &Apache::lonnet::recprefix($env{'request.course.id'}).
9819: '-<input type="text" name="receipt" size="4" onchange="javascript:checkReceiptNo(this.form,\'OK\')" />';
9820:
9821: $Str .="</form>\n";
9822: my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
9823: $request->print(<<GRADINGMENUJS);
9824: <script type="text/javascript" language="javascript">
9825: function checkChoice(formname,val,cmdx) {
9826: if (val <= 2) {
9827: var cmd = radioSelection(formname.radioChoice);
9828: var cmdsave = cmd;
9829: } else {
9830: cmd = cmdx;
9831: cmdsave = 'submission';
9832: }
9833: formname.command.value = cmd;
9834: if (val < 5) formname.submit();
9835: if (val == 5) {
9836: if (!checkReceiptNo(formname,'notOK')) {
9837: return false;
9838: } else {
9839: formname.submit();
9840: }
9841: }
9842: }
9843:
9844: function checkReceiptNo(formname,nospace) {
9845: var receiptNo = formname.receipt.value;
9846: var checkOpt = false;
9847: if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
9848: if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
9849: if (checkOpt) {
9850: alert("$receiptalert");
9851: formname.receipt.value = "";
9852: formname.receipt.focus();
9853: return false;
9854: }
9855: return true;
9856: }
9857: </script>
9858: GRADINGMENUJS
9859: &commonJSfunctions($request);
9860: return $Str;
9861: }
9862:
9863:
9864: #--- Displays the submissions first page -------
9865: sub submit_options {
9866: my ($request) = @_;
9867: my ($symb)=&get_symb($request);
9868: if (!$symb) {return '';}
9869: my $probTitle = &Apache::lonnet::gettitle($symb);
9870:
9871: my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
9872: $request->print(<<GRADINGMENUJS);
9873: <script type="text/javascript" language="javascript">
9874: function checkChoice(formname,val,cmdx) {
9875: if (val <= 2) {
9876: var cmd = radioSelection(formname.radioChoice);
9877: var cmdsave = cmd;
9878: } else {
9879: cmd = cmdx;
9880: cmdsave = 'submission';
9881: }
9882: formname.command.value = cmd;
9883: formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
9884: ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
9885: if (val < 5) formname.submit();
9886: if (val == 5) {
9887: if (!checkReceiptNo(formname,'notOK')) { return false;}
9888: formname.submit();
9889: }
9890: if (val < 7) formname.submit();
9891: }
9892:
9893: function checkReceiptNo(formname,nospace) {
9894: var receiptNo = formname.receipt.value;
9895: var checkOpt = false;
9896: if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
9897: if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
9898: if (checkOpt) {
9899: alert("$receiptalert");
9900: formname.receipt.value = "";
9901: formname.receipt.focus();
9902: return false;
9903: }
9904: return true;
9905: }
9906: </script>
9907: GRADINGMENUJS
9908: &commonJSfunctions($request);
9909: my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
9910: my $result;
9911: my (undef,$sections) = &getclasslist('all','0');
9912: my $savedState = &savedState();
9913: my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
9914: my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
9915: my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
9916: my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
9917:
9918: # Preselect sections
9919: my $selsec="";
9920: if (ref($sections)) {
9921: foreach my $section (sort(@$sections)) {
9922: $selsec.='<option value="'.$section.'" '.
9923: ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
9924: }
9925: }
9926:
9927: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
9928: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
9929: '<input type="hidden" name="handgrade" value="'.$hdgrade.'" />'."\n".
9930: '<input type="hidden" name="probTitle" value="'.$probTitle.'" />'."\n".
9931: '<input type="hidden" name="command" value="" />'."\n".
9932: '<input type="hidden" name="saveState" value="" />'."\n".
9933: '<input type="hidden" name="gradingMenu" value="1" />'."\n".
9934: '<input type="hidden" name="showgrading" value="yes" />'."\n";
9935:
9936: $result.='
9937: <h2>
9938: '.&mt('Grade Current Resource').'
9939: </h2>
9940: <div>
9941: '.$table.'
9942: </div>
9943:
9944: <div class="LC_columnSection">
9945:
9946: <fieldset>
9947: <legend>
9948: '.&mt('Sections').'
9949: </legend>
9950: <select name="section" multiple="multiple" size="5">'."\n";
9951: $result.= $selsec;
9952: $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> ';
9953: $result.='
9954: </fieldset>
9955:
9956: <fieldset>
9957: <legend>
9958: '.&mt('Groups').'
9959: </legend>
9960: '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
9961: </fieldset>
9962:
9963: <fieldset>
9964: <legend>
9965: '.&mt('Access Status').'
9966: </legend>
9967: '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
9968: </fieldset>
9969:
9970: <fieldset>
9971: <legend>
9972: '.&mt('Submission Status').'
9973: </legend>
9974: <select name="submitonly" size="5">
9975: <option value="yes" '. ($saveSub eq 'yes' ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
9976: <option value="queued" '. ($saveSub eq 'queued' ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
9977: <option value="graded" '. ($saveSub eq 'graded' ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
9978: <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
9979: <option value="all" '. ($saveSub eq 'all' ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
9980: </select>
9981: </fieldset>
9982:
9983: </div>
9984:
9985: <br />
9986: <div>
9987: <div>
9988: <label>
9989: <input type="radio" name="radioChoice" value="submission" '.
9990: ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
9991: &mt('Select individual students to grade and view submissions.').'
9992: </label>
9993: </div>
9994: <div>
9995: <label>
9996: <input type="radio" name="radioChoice" value="viewgrades" '.
9997: ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
9998: &mt('Grade all selected students in a grading table.').'
9999: </label>
10000: </div>
10001: <div>
10002: <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' →" />
10003: </div>
10004: </div>
10005:
10006:
10007: <h2>
10008: '.&mt('Grade Complete Folder for One Student').'
10009: </h2>
10010: <div>
10011: <div>
10012: <label>
10013: <input type="radio" name="radioChoice" value="pickStudentPage" '.
10014: ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
10015: &mt('The <b>complete</b> page/sequence/folder: For one student').'
10016: </label>
10017: </div>
10018: <div>
10019: <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' →" />
10020: </div>
10021: </div>
10022: </form>';
10023: $result .= &show_grading_menu_form($symb);
10024: return $result;
10025: }
10026:
10027: sub substatus_options {
10028: return &Apache::lonlocal::texthash(
10029: 'yes' => 'with submissions',
10030: 'queued' => 'in grading queue',
10031: 'graded' => 'with ungraded submissions',
10032: 'incorrect' => 'with incorrect submissions',
10033: 'all' => 'with any status',
10034: );
10035: }
10036:
10037: sub reset_perm {
10038: undef(%perm);
10039: }
10040:
10041: sub init_perm {
10042: &reset_perm();
10043: foreach my $test_perm ('vgr','mgr','opa') {
10044:
10045: my $scope = $env{'request.course.id'};
10046: if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
10047:
10048: $scope .= '/'.$env{'request.course.sec'};
10049: if ( $perm{$test_perm}=
10050: &Apache::lonnet::allowed($test_perm,$scope)) {
10051: $perm{$test_perm.'_section'}=$env{'request.course.sec'};
10052: } else {
10053: delete($perm{$test_perm});
10054: }
10055: }
10056: }
10057: }
10058:
10059: sub init_old_essays {
10060: my ($symb,$apath,$adom,$aname) = @_;
10061: if ($symb ne '') {
10062: my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
10063: if (keys(%essays) > 0) {
10064: $old_essays{$symb} = \%essays;
10065: }
10066: }
10067: return;
10068: }
10069:
10070: sub reset_old_essays {
10071: undef(%old_essays);
10072: }
10073:
10074: sub gather_clicker_ids {
10075: my %clicker_ids;
10076:
10077: my $classlist = &Apache::loncoursedata::get_classlist();
10078:
10079: # Set up a couple variables.
10080: my $username_idx = &Apache::loncoursedata::CL_SNAME();
10081: my $domain_idx = &Apache::loncoursedata::CL_SDOM();
10082: my $status_idx = &Apache::loncoursedata::CL_STATUS();
10083:
10084: foreach my $student (keys(%$classlist)) {
10085: if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
10086: my $username = $classlist->{$student}->[$username_idx];
10087: my $domain = $classlist->{$student}->[$domain_idx];
10088: my $clickers =
10089: (&Apache::lonnet::userenvironment($domain,$username,'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}.=','.$username.':'.$domain;
10095: } else {
10096: $clicker_ids{$id}=$username.':'.$domain;
10097: }
10098: }
10099: }
10100: return %clicker_ids;
10101: }
10102:
10103: sub gather_adv_clicker_ids {
10104: my %clicker_ids;
10105: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
10106: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
10107: my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
10108: foreach my $element (sort(keys(%coursepersonnel))) {
10109: foreach my $person (split(/\,/,$coursepersonnel{$element})) {
10110: my ($puname,$pudom)=split(/\:/,$person);
10111: my $clickers =
10112: (&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
10113: foreach my $id (split(/\,/,$clickers)) {
10114: $id=~s/^[\#0]+//;
10115: $id=~s/[\-\:]//g;
10116: if (exists($clicker_ids{$id})) {
10117: $clicker_ids{$id}.=','.$puname.':'.$pudom;
10118: } else {
10119: $clicker_ids{$id}=$puname.':'.$pudom;
10120: }
10121: }
10122: }
10123: }
10124: return %clicker_ids;
10125: }
10126:
10127: sub clicker_grading_parameters {
10128: return ('gradingmechanism' => 'scalar',
10129: 'upfiletype' => 'scalar',
10130: 'specificid' => 'scalar',
10131: 'pcorrect' => 'scalar',
10132: 'pincorrect' => 'scalar');
10133: }
10134:
10135: sub process_clicker {
10136: my ($r)=@_;
10137: my ($symb)=&get_symb($r);
10138: if (!$symb) {return '';}
10139: my $result=&checkforfile_js();
10140: $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
10141: my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
10142: $result.=$table;
10143: $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
10144: $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
10145: $result.=' <b>'.&mt('Specify a file containing the clicker information for this resource.').
10146: '</b></td></tr>'."\n";
10147: $result.='<tr bgcolor="#ffffe6"><td>'."\n";
10148: # Attempt to restore parameters from last session, set defaults if not present
10149: my %Saveable_Parameters=&clicker_grading_parameters();
10150: &Apache::loncommon::restore_course_settings('grades_clicker',
10151: \%Saveable_Parameters);
10152: if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
10153: if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
10154: if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
10155: if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
10156:
10157: my %checked;
10158: foreach my $gradingmechanism ('attendance','personnel','specific','given') {
10159: if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
10160: $checked{$gradingmechanism}=' checked="checked"';
10161: }
10162: }
10163:
10164: my $upload=&mt("Upload File");
10165: my $type=&mt("Type");
10166: my $attendance=&mt("Award points just for participation");
10167: my $personnel=&mt("Correctness determined from response by course personnel");
10168: my $specific=&mt("Correctness determined from response with clicker ID(s)");
10169: my $given=&mt("Correctness determined from given list of answers").' '.
10170: '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
10171: my $pcorrect=&mt("Percentage points for correct solution");
10172: my $pincorrect=&mt("Percentage points for incorrect solution");
10173: my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
10174: {'iclicker' => 'i>clicker',
10175: 'interwrite' => 'interwrite PRS',
10176: 'turning' => 'Turning Technologies'});
10177: $symb = &Apache::lonenc::check_encrypt($symb);
10178: $result.=<<ENDUPFORM;
10179: <script type="text/javascript">
10180: function sanitycheck() {
10181: // Accept only integer percentages
10182: document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
10183: document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
10184: // Find out grading choice
10185: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10186: if (document.forms.gradesupload.gradingmechanism[i].checked) {
10187: gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
10188: }
10189: }
10190: // By default, new choice equals user selection
10191: newgradingchoice=gradingchoice;
10192: // Not good to give more points for false answers than correct ones
10193: if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
10194: document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
10195: }
10196: // If new choice is attendance only, and old choice was correctness-based, restore defaults
10197: if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
10198: document.forms.gradesupload.pcorrect.value=100;
10199: document.forms.gradesupload.pincorrect.value=100;
10200: }
10201: // If the values are different, cannot be attendance only
10202: if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
10203: (gradingchoice=='attendance')) {
10204: newgradingchoice='personnel';
10205: }
10206: // Change grading choice to new one
10207: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
10208: if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
10209: document.forms.gradesupload.gradingmechanism[i].checked=true;
10210: } else {
10211: document.forms.gradesupload.gradingmechanism[i].checked=false;
10212: }
10213: }
10214: // Remember the old state
10215: document.forms.gradesupload.waschecked.value=newgradingchoice;
10216: }
10217: </script>
10218: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
10219: <input type="hidden" name="symb" value="$symb" />
10220: <input type="hidden" name="command" value="processclickerfile" />
10221: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
10222: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
10223: <input type="file" name="upfile" size="50" />
10224: <br /><label>$type: $selectform</label>
10225: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
10226: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
10227: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
10228: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
10229: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
10230: <br />
10231: <input type="text" name="givenanswer" size="50" />
10232: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
10233: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
10234: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
10235: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
10236: </form>
10237: ENDUPFORM
10238: $result.='</td></tr></table>'."\n".
10239: '</td></tr></table><br /><br />'."\n";
10240: $result.=&show_grading_menu_form($symb);
10241: return $result;
10242: }
10243:
10244: sub process_clicker_file {
10245: my ($r)=@_;
10246: my ($symb)=&get_symb($r);
10247: if (!$symb) {return '';}
10248:
10249: my %Saveable_Parameters=&clicker_grading_parameters();
10250: &Apache::loncommon::store_course_settings('grades_clicker',
10251: \%Saveable_Parameters);
10252:
10253: my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
10254: if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
10255: $result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
10256: return $result.&show_grading_menu_form($symb);
10257: }
10258: if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
10259: $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
10260: return $result.&show_grading_menu_form($symb);
10261: }
10262: my $foundgiven=0;
10263: if ($env{'form.gradingmechanism'} eq 'given') {
10264: $env{'form.givenanswer'}=~s/^\s*//gs;
10265: $env{'form.givenanswer'}=~s/\s*$//gs;
10266: $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
10267: $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
10268: my @answers=split(/\,/,$env{'form.givenanswer'});
10269: $foundgiven=$#answers+1;
10270: }
10271: my %clicker_ids=&gather_clicker_ids();
10272: my %correct_ids;
10273: if ($env{'form.gradingmechanism'} eq 'personnel') {
10274: %correct_ids=&gather_adv_clicker_ids();
10275: }
10276: if ($env{'form.gradingmechanism'} eq 'specific') {
10277: foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
10278: $correct_id=~tr/a-z/A-Z/;
10279: $correct_id=~s/\s//gs;
10280: $correct_id=~s/^[\#0]+//;
10281: $correct_id=~s/[\-\:]//g;
10282: if ($correct_id) {
10283: $correct_ids{$correct_id}='specified';
10284: }
10285: }
10286: }
10287: if ($env{'form.gradingmechanism'} eq 'attendance') {
10288: $result.=&mt('Score based on attendance only');
10289: } elsif ($env{'form.gradingmechanism'} eq 'given') {
10290: $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
10291: } else {
10292: my $number=0;
10293: $result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
10294: foreach my $id (sort(keys(%correct_ids))) {
10295: $result.='<br /><tt>'.$id.'</tt> - ';
10296: if ($correct_ids{$id} eq 'specified') {
10297: $result.=&mt('specified');
10298: } else {
10299: my ($uname,$udom)=split(/\:/,$correct_ids{$id});
10300: $result.=&Apache::loncommon::plainname($uname,$udom);
10301: }
10302: $number++;
10303: }
10304: $result.="</p>\n";
10305: if ($number==0) {
10306: $result .=
10307: &Apache::lonhtmlcommon::confirm_success(
10308: &mt('No IDs found to determine correct answer'),1);
10309: return $result.&show_grading_menu_form($symb);
10310: }
10311: }
10312: if (length($env{'form.upfile'}) < 2) {
10313: $result .=
10314: &Apache::lonhtmlcommon::confirm_success(
10315: &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
10316: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
10317: return $result.&show_grading_menu_form($symb);
10318: }
10319: my $mimetype;
10320: if ($env{'form.upfiletype'} eq 'iclicker') {
10321: my $mm = new File::MMagic;
10322: $mimetype = $mm->checktype_contents($env{'form.upfile'});
10323: unless (($mimetype eq 'text/plain') || ($mimetype eq 'text/html')) {
10324: $result.= '<p>'.
10325: &Apache::lonhtmlcommon::confirm_success(
10326: &mt('File format is neither csv (iclicker 6) nor xml (iclicker 7)'),1).'</p>';
10327: return $result.&show_grading_menu_form($symb);
10328: }
10329: } elsif (($env{'form.upfiletype'} ne 'interwrite') && ($env{'form.upfiletype'} ne 'turning')) {
10330: $result .= '<p>'.
10331: &Apache::lonhtmlcommon::confirm_success(
10332: &mt('Invalid clicker type: choose one of: i>clicker, Interwrite PRS, or Turning Technologies.'),1).'</p>';
10333: return $result.&show_grading_menu_form($symb);
10334: }
10335:
10336: # Were able to get all the info needed, now analyze the file
10337:
10338: $result.=&Apache::loncommon::studentbrowser_javascript();
10339: $symb = &Apache::lonenc::check_encrypt($symb);
10340: my $heading=&mt('Scanning clicker file');
10341: $result.=(<<ENDHEADER);
10342: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
10343: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
10344: <b>$heading</b></td></tr><tr bgcolor="#ffffe6"><td>
10345: <form method="post" action="/adm/grades" name="clickeranalysis">
10346: <input type="hidden" name="symb" value="$symb" />
10347: <input type="hidden" name="command" value="assignclickergrades" />
10348: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
10349: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
10350: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
10351: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
10352: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
10353: ENDHEADER
10354: if ($env{'form.gradingmechanism'} eq 'given') {
10355: $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
10356: }
10357: my %responses;
10358: my @questiontitles;
10359: my $errormsg='';
10360: my $number=0;
10361: if ($env{'form.upfiletype'} eq 'iclicker') {
10362: if ($mimetype eq 'text/plain') {
10363: ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
10364: } elsif ($mimetype eq 'text/html') {
10365: ($errormsg,$number)=&iclickerxml_eval(\@questiontitles,\%responses);
10366: }
10367: } elsif ($env{'form.upfiletype'} eq 'interwrite') {
10368: ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
10369: } elsif ($env{'form.upfiletype'} eq 'turning') {
10370: ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
10371: }
10372: $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
10373: '<input type="hidden" name="number" value="'.$number.'" />'.
10374: &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
10375: $env{'form.pcorrect'},$env{'form.pincorrect'}).
10376: '<br />';
10377: if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
10378: $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
10379: return $result.&show_grading_menu_form($symb);
10380: }
10381: # Remember Question Titles
10382: # FIXME: Possibly need delimiter other than ":"
10383: for (my $i=0;$i<$number;$i++) {
10384: $result.='<input type="hidden" name="question:'.$i.'" value="'.
10385: &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
10386: }
10387: my $correct_count=0;
10388: my $student_count=0;
10389: my $unknown_count=0;
10390: # Match answers with usernames
10391: # FIXME: Possibly need delimiter other than ":"
10392: foreach my $id (keys(%responses)) {
10393: if ($correct_ids{$id}) {
10394: $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
10395: $correct_count++;
10396: } elsif ($clicker_ids{$id}) {
10397: if ($clicker_ids{$id}=~/\,/) {
10398: # More than one user with the same clicker!
10399: $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
10400: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10401: "<select name='multi".$id."'>";
10402: foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
10403: $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
10404: }
10405: $result.='</select>';
10406: $unknown_count++;
10407: } else {
10408: # Good: found one and only one user with the right clicker
10409: $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
10410: $student_count++;
10411: }
10412: } else {
10413: $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
10414: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10415: "\n".&mt("Username").": <input type='text' name='uname".$id."' /> ".
10416: "\n".&mt("Domain").": ".
10417: &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).' '.
10418: &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,'',$id);
10419: $unknown_count++;
10420: }
10421: }
10422: $result.='<hr />'.
10423: &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
10424: if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
10425: if ($correct_count==0) {
10426: $errormsg.="Found no correct answers for grading!";
10427: } elsif ($correct_count>1) {
10428: $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
10429: }
10430: }
10431: if ($number<1) {
10432: $errormsg.="Found no questions.";
10433: }
10434: if ($errormsg) {
10435: $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
10436: } else {
10437: $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
10438: }
10439: $result.='</form></td></tr></table>'."\n".
10440: '</td></tr></table><br /><br />'."\n";
10441: return $result.&show_grading_menu_form($symb);
10442: }
10443:
10444: sub iclicker_eval {
10445: my ($questiontitles,$responses)=@_;
10446: my $number=0;
10447: my $errormsg='';
10448: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10449: my %components=&Apache::loncommon::record_sep($line);
10450: my @entries=map {$components{$_}} (sort(keys(%components)));
10451: if ($entries[0] eq 'Question') {
10452: for (my $i=3;$i<$#entries;$i+=6) {
10453: $$questiontitles[$number]=$entries[$i];
10454: $number++;
10455: }
10456: }
10457: if ($entries[0]=~/^\#/) {
10458: my $id=$entries[0];
10459: my @idresponses;
10460: $id=~s/^[\#0]+//;
10461: for (my $i=0;$i<$number;$i++) {
10462: my $idx=3+$i*6;
10463: $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
10464: push(@idresponses,$entries[$idx]);
10465: }
10466: $$responses{$id}=join(',',@idresponses);
10467: }
10468: }
10469: return ($errormsg,$number);
10470: }
10471:
10472: sub iclickerxml_eval {
10473: my ($questiontitles,$responses)=@_;
10474: my $number=0;
10475: my $errormsg='';
10476: my @state;
10477: my %respbyid;
10478: my $p = HTML::Parser->new
10479: (
10480: xml_mode => 1,
10481: start_h =>
10482: [sub {
10483: my ($tagname,$attr) = @_;
10484: push(@state,$tagname);
10485: if ("@state" eq "ssn p") {
10486: my $title = $attr->{qn};
10487: $title =~ s/(^\s+|\s+$)//g;
10488: $questiontitles->[$number]=$title;
10489: } elsif ("@state" eq "ssn p v") {
10490: my $id = $attr->{id};
10491: my $entry = $attr->{ans};
10492: $id=~s/^[\#0]+//;
10493: $entry =~s/[^a-zA-Z0-9\.\*\-\+]+//g;
10494: $respbyid{$id}[$number] = $entry;
10495: }
10496: }, "tagname, attr"],
10497: end_h =>
10498: [sub {
10499: my ($tagname) = @_;
10500: if ("@state" eq "ssn p") {
10501: $number++;
10502: }
10503: pop(@state);
10504: }, "tagname"],
10505: );
10506:
10507: $p->parse($env{'form.upfile'});
10508: $p->eof;
10509: foreach my $id (keys(%respbyid)) {
10510: $responses->{$id}=join(',',@{$respbyid{$id}});
10511: }
10512: return ($errormsg,$number);
10513: }
10514:
10515: sub interwrite_eval {
10516: my ($questiontitles,$responses)=@_;
10517: my $number=0;
10518: my $errormsg='';
10519: my $skipline=1;
10520: my $questionnumber=0;
10521: my %idresponses=();
10522: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10523: my %components=&Apache::loncommon::record_sep($line);
10524: my @entries=map {$components{$_}} (sort(keys(%components)));
10525: if ($entries[1] eq 'Time') { $skipline=0; next; }
10526: if ($entries[1] eq 'Response') { $skipline=1; }
10527: next if $skipline;
10528: if ($entries[0]!=$questionnumber) {
10529: $questionnumber=$entries[0];
10530: $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
10531: $number++;
10532: }
10533: my $id=$entries[4];
10534: $id=~s/^[\#0]+//;
10535: $id=~s/^v\d*\://i;
10536: $id=~s/[\-\:]//g;
10537: $idresponses{$id}[$number]=$entries[6];
10538: }
10539: foreach my $id (keys(%idresponses)) {
10540: $$responses{$id}=join(',',@{$idresponses{$id}});
10541: $$responses{$id}=~s/^\s*\,//;
10542: }
10543: return ($errormsg,$number);
10544: }
10545:
10546: sub turning_eval {
10547: my ($questiontitles,$responses)=@_;
10548: my $number=0;
10549: my $errormsg='';
10550: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10551: my %components=&Apache::loncommon::record_sep($line);
10552: my @entries=map {$components{$_}} (sort(keys(%components)));
10553: if ($#entries>$number) { $number=$#entries; }
10554: my $id=$entries[0];
10555: my @idresponses;
10556: $id=~s/^[\#0]+//;
10557: unless ($id) { next; }
10558: for (my $idx=1;$idx<=$#entries;$idx++) {
10559: $entries[$idx]=~s/\,/\;/g;
10560: $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
10561: push(@idresponses,$entries[$idx]);
10562: }
10563: $$responses{$id}=join(',',@idresponses);
10564: }
10565: for (my $i=1; $i<=$number; $i++) {
10566: $$questiontitles[$i]=&mt('Question [_1]',$i);
10567: }
10568: return ($errormsg,$number);
10569: }
10570:
10571: sub assign_clicker_grades {
10572: my ($r)=@_;
10573: my ($symb)=&get_symb($r);
10574: if (!$symb) {return '';}
10575: # See which part we are saving to
10576: my $res_error;
10577: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
10578: if ($res_error) {
10579: return &navmap_errormsg();
10580: }
10581: # FIXME: This should probably look for the first handgradeable part
10582: my $part=$$partlist[0];
10583: # Start screen output
10584: my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
10585:
10586: $result .= '<br />'.
10587: &Apache::loncommon::start_data_table().
10588: &Apache::loncommon::start_data_table_header_row().
10589: '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
10590: &Apache::loncommon::end_data_table_header_row().
10591: &Apache::loncommon::start_data_table_row().'<td>';
10592:
10593: # Get correct result
10594: # FIXME: Possibly need delimiter other than ":"
10595: my @correct=();
10596: my $gradingmechanism=$env{'form.gradingmechanism'};
10597: my $number=$env{'form.number'};
10598: if ($gradingmechanism ne 'attendance') {
10599: foreach my $key (keys(%env)) {
10600: if ($key=~/^form\.correct\:/) {
10601: my @input=split(/\,/,$env{$key});
10602: for (my $i=0;$i<=$#input;$i++) {
10603: if (($correct[$i]) && ($input[$i]) &&
10604: ($correct[$i] ne $input[$i])) {
10605: $result.='<br /><span class="LC_warning">'.
10606: &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
10607: $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
10608: } elsif (($input[$i]) || ($input[$i] eq '0')) {
10609: $correct[$i]=$input[$i];
10610: }
10611: }
10612: }
10613: }
10614: for (my $i=0;$i<$number;$i++) {
10615: if ((!$correct[$i]) && ($correct[$i] ne '0')) {
10616: $result.='<br /><span class="LC_error">'.
10617: &mt('No correct result given for question "[_1]"!',
10618: $env{'form.question:'.$i}).'</span>';
10619: }
10620: }
10621: $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
10622: }
10623: # Start grading
10624: my $pcorrect=$env{'form.pcorrect'};
10625: my $pincorrect=$env{'form.pincorrect'};
10626: my $storecount=0;
10627: my %users=();
10628: foreach my $key (keys(%env)) {
10629: my $user='';
10630: if ($key=~/^form\.student\:(.*)$/) {
10631: $user=$1;
10632: }
10633: if ($key=~/^form\.unknown\:(.*)$/) {
10634: my $id=$1;
10635: if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
10636: $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
10637: } elsif ($env{'form.multi'.$id}) {
10638: $user=$env{'form.multi'.$id};
10639: }
10640: }
10641: if ($user) {
10642: if ($users{$user}) {
10643: $result.='<br /><span class="LC_warning">'.
10644: &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
10645: '</span><br />';
10646: }
10647: $users{$user}=1;
10648: my @answer=split(/\,/,$env{$key});
10649: my $sum=0;
10650: my $realnumber=$number;
10651: for (my $i=0;$i<$number;$i++) {
10652: if ($correct[$i] eq '-') {
10653: $realnumber--;
10654: } elsif ($answer[$i]) {
10655: if ($gradingmechanism eq 'attendance') {
10656: $sum+=$pcorrect;
10657: } elsif ($correct[$i] eq '*') {
10658: $sum+=$pcorrect;
10659: } else {
10660: # We actually grade if correct or not
10661: my $increment=$pincorrect;
10662: # Special case: numerical answer "0"
10663: if ($correct[$i] eq '0') {
10664: if ($answer[$i]=~/^[0\.]+$/) {
10665: $increment=$pcorrect;
10666: }
10667: # General numerical answer, both evaluate to something non-zero
10668: } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
10669: if (1.0*$correct[$i]==1.0*$answer[$i]) {
10670: $increment=$pcorrect;
10671: }
10672: # Must be just alphanumeric
10673: } elsif ($answer[$i] eq $correct[$i]) {
10674: $increment=$pcorrect;
10675: }
10676: $sum+=$increment;
10677: }
10678: }
10679: }
10680: my $ave=$sum/(100*$realnumber);
10681: # Store
10682: my ($username,$domain)=split(/\:/,$user);
10683: my %grades=();
10684: $grades{"resource.$part.solved"}='correct_by_override';
10685: $grades{"resource.$part.awarded"}=$ave;
10686: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
10687: my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
10688: $env{'request.course.id'},
10689: $domain,$username);
10690: if ($returncode ne 'ok') {
10691: $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
10692: } else {
10693: $storecount++;
10694: }
10695: }
10696: }
10697: # We are done
10698: $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
10699: '</td>'.
10700: &Apache::loncommon::end_data_table_row().
10701: &Apache::loncommon::end_data_table()."<br /><br />\n";
10702: return $result.&show_grading_menu_form($symb);
10703: }
10704:
10705: sub navmap_errormsg {
10706: return '<div class="LC_error">'.
10707: &mt('An error occurred retrieving information about resources in the course.').'<br />'.
10708: &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>').
10709: '</div>';
10710: }
10711:
10712: sub startpage {
10713: my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js,$onload) = @_;
10714: my %args;
10715: if ($onload) {
10716: my %loaditems = (
10717: 'onload' => $onload,
10718: );
10719: $args{'add_entries'} = \%loaditems;
10720: }
10721: if ($nomenu) {
10722: $args{'only_body'} = 1;
10723: $r->print(&Apache::loncommon::start_page("Student's Version",$js,\%args));
10724: } else {
10725: $args{'bread_crumbs'} = $crumbs;
10726: $r->print(&Apache::loncommon::start_page('Grading',$js,\%args));
10727: }
10728: unless ($nodisplayflag) {
10729: $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
10730: }
10731: }
10732:
10733: sub handler {
10734: my $request=$_[0];
10735: &reset_caches();
10736: if ($request->header_only) {
10737: &Apache::loncommon::content_type($request,'text/html');
10738: $request->send_http_header;
10739: return OK;
10740: }
10741: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
10742:
10743: my $symb=&get_symb($request,1);
10744: my @commands=&Apache::loncommon::get_env_multiple('form.command');
10745: my $command=$commands[0];
10746:
10747: if ($#commands > 0) {
10748: &Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
10749: }
10750:
10751: $ssi_error = 0;
10752: my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
10753: my $start_page = &Apache::loncommon::start_page('Grading',undef,
10754: {'bread_crumbs' => $brcrum});
10755: if ($symb eq '' && $command eq '') {
10756: if ($env{'user.adv'}) {
10757: &Apache::loncommon::content_type($request,'text/html');
10758: $request->send_http_header;
10759: $request->print($start_page);
10760: if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
10761: ($env{'form.codethree'})) {
10762: my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
10763: $env{'form.codethree'};
10764: my ($tsymb,$tuname,$tudom,$tcrsid)=
10765: &Apache::lonnet::checkin($token);
10766: if ($tsymb) {
10767: my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
10768: if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
10769: $request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
10770: ('grade_username' => $tuname,
10771: 'grade_domain' => $tudom,
10772: 'grade_courseid' => $tcrsid,
10773: 'grade_symb' => $tsymb)));
10774: } else {
10775: $request->print('<h3>Not authorized: '.$token.'</h3>');
10776: }
10777: } else {
10778: $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
10779: }
10780: } else {
10781: $request->print(&Apache::lonxml::tokeninputfield());
10782: }
10783: } elsif ($env{'request.course.id'}) {
10784: &init_perm();
10785: if (!%perm) {
10786: $request->internal_redirect('/adm/quickgrades');
10787: return OK;
10788: } else {
10789: &Apache::loncommon::content_type($request,'text/html');
10790: $request->send_http_header;
10791: $request->print($start_page);
10792: }
10793: }
10794: } else {
10795: &init_perm();
10796: if (!$env{'request.course.id'}) {
10797: unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
10798: ($command =~ /^scantronupload/)) {
10799: # Not in a course.
10800: $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
10801: return HTTP_NOT_ACCEPTABLE;
10802: }
10803: } elsif (!%perm) {
10804: $request->internal_redirect('/adm/quickgrades');
10805: }
10806: &Apache::loncommon::content_type($request,'text/html');
10807: $request->send_http_header;
10808: if (($command eq 'scantron_selectphase' && $perm{'mgr'}) ||
10809: (($command eq 'scantronupload') &&
10810: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
10811: &Apache::lonnet::allowed('usc',$env{'request.course.id'})))) {
10812: &startpage($request,$symb,[{href=>'/adm/grades', text=>"Grading"}],1,1,
10813: undef,undef,undef,undef,'toggleScantab(document.rules);');
10814: } else {
10815: unless ((($command eq 'submission' || $command eq 'versionsub')) && ($perm{'vgr'})) {
10816: $request->print($start_page);
10817: }
10818: }
10819: if ($command eq 'submission' && $perm{'vgr'}) {
10820: my ($stuvcurrent,$stuvdisp,$versionform,$js);
10821: if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
10822: ($stuvcurrent,$stuvdisp,$versionform,$js) =
10823: &choose_task_version_form($symb,$env{'form.student'},
10824: $env{'form.userdom'});
10825: }
10826: &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
10827: if ($versionform) {
10828: $request->print($versionform);
10829: }
10830: $request->print('<br clear="all" />');
10831: ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
10832: } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
10833: my ($stuvcurrent,$stuvdisp,$versionform,$js) =
10834: &choose_task_version_form($symb,$env{'form.student'},
10835: $env{'form.userdom'},
10836: $env{'form.inhibitmenu'});
10837: &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
10838: if ($versionform) {
10839: $request->print($versionform);
10840: }
10841: $request->print('<br clear="all" />');
10842: $request->print(&show_previous_task_version($request,$symb));
10843: } elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
10844: &pickStudentPage($request);
10845: } elsif ($command eq 'displayPage' && $perm{'vgr'}) {
10846: &displayPage($request);
10847: } elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
10848: &updateGradeByPage($request);
10849: } elsif ($command eq 'processGroup' && $perm{'vgr'}) {
10850: &processGroup($request);
10851: } elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
10852: $request->print(&grading_menu($request));
10853: } elsif ($command eq 'submit_options' && $perm{'vgr'}) {
10854: $request->print(&submit_options($request));
10855: } elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
10856: $request->print(&viewgrades($request));
10857: } elsif ($command eq 'handgrade' && $perm{'mgr'}) {
10858: $request->print(&processHandGrade($request));
10859: } elsif ($command eq 'editgrades' && $perm{'mgr'}) {
10860: $request->print(&editgrades($request));
10861: } elsif ($command eq 'verify' && $perm{'vgr'}) {
10862: $request->print(&verifyreceipt($request));
10863: } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
10864: $request->print(&process_clicker($request));
10865: } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
10866: $request->print(&process_clicker_file($request));
10867: } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
10868: $request->print(&assign_clicker_grades($request));
10869: } elsif ($command eq 'csvform' && $perm{'mgr'}) {
10870: $request->print(&upcsvScores_form($request));
10871: } elsif ($command eq 'csvupload' && $perm{'mgr'}) {
10872: $request->print(&csvupload($request));
10873: } elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
10874: $request->print(&csvuploadmap($request));
10875: } elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
10876: if ($env{'form.associate'} ne 'Reverse Association') {
10877: $request->print(&csvuploadoptions($request));
10878: } else {
10879: if ( $env{'form.upfile_associate'} ne 'reverse' ) {
10880: $env{'form.upfile_associate'} = 'reverse';
10881: } else {
10882: $env{'form.upfile_associate'} = 'forward';
10883: }
10884: $request->print(&csvuploadmap($request));
10885: }
10886: } elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
10887: $request->print(&csvuploadassign($request));
10888: } elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
10889: $request->print(&scantron_selectphase($request));
10890: } elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
10891: $request->print(&scantron_do_warning($request));
10892: } elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
10893: $request->print(&scantron_validate_file($request));
10894: } elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
10895: $request->print(&scantron_process_students($request));
10896: } elsif ($command eq 'scantronupload' &&
10897: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10898: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10899: $request->print(&scantron_upload_scantron_data($request));
10900: } elsif ($command eq 'scantronupload_save' &&
10901: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10902: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10903: $request->print(&scantron_upload_scantron_data_save($request));
10904: } elsif ($command eq 'scantron_download' &&
10905: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
10906: $request->print(&scantron_download_scantron_data($request));
10907: } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
10908: $request->print(&checkscantron_results($request));
10909: } elsif ($command) {
10910: $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
10911: }
10912: }
10913: if ($ssi_error) {
10914: &ssi_print_error($request);
10915: }
10916: $request->print(&Apache::loncommon::end_page());
10917: &reset_caches();
10918: return OK;
10919: }
10920:
10921: 1;
10922:
10923: __END__;
10924:
10925:
10926: =head1 NAME
10927:
10928: Apache::grades
10929:
10930: =head1 SYNOPSIS
10931:
10932: Handles the viewing of grades.
10933:
10934: This is part of the LearningOnline Network with CAPA project
10935: described at http://www.lon-capa.org.
10936:
10937: =head1 OVERVIEW
10938:
10939: Do an ssi with retries:
10940: While I'd love to factor out this with the vesrion in lonprintout,
10941: 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
10942: I'm not quite ready to invent (e.g. an ssi_with_retry object).
10943:
10944: At least the logic that drives this has been pulled out into loncommon.
10945:
10946:
10947:
10948: ssi_with_retries - Does the server side include of a resource.
10949: if the ssi call returns an error we'll retry it up to
10950: the number of times requested by the caller.
10951: If we still have a problem, no text is appended to the
10952: output and we set some global variables.
10953: to indicate to the caller an SSI error occurred.
10954: All of this is supposed to deal with the issues described
10955: in LON-CAPA BZ 5631 see:
10956: http://bugs.lon-capa.org/show_bug.cgi?id=5631
10957: by informing the user that this happened.
10958:
10959: Parameters:
10960: resource - The resource to include. This is passed directly, without
10961: interpretation to lonnet::ssi.
10962: form - The form hash parameters that guide the interpretation of the resource
10963:
10964: retries - Number of retries allowed before giving up completely.
10965: Returns:
10966: On success, returns the rendered resource identified by the resource parameter.
10967: Side Effects:
10968: The following global variables can be set:
10969: ssi_error - If an unrecoverable error occurred this becomes true.
10970: It is up to the caller to initialize this to false
10971: if desired.
10972: ssi_error_resource - If an unrecoverable error occurred, this is the value
10973: of the resource that could not be rendered by the ssi
10974: call.
10975: ssi_error_message - The error string fetched from the ssi response
10976: in the event of an error.
10977:
10978:
10979: =head1 HANDLER SUBROUTINE
10980:
10981: ssi_with_retries()
10982:
10983: =head1 SUBROUTINES
10984:
10985: =over
10986:
10987: =item scantron_get_correction() :
10988:
10989: Builds the interface screen to interact with the operator to fix a
10990: specific error condition in a specific scanline
10991:
10992: Arguments:
10993: $r - Apache request object
10994: $i - number of the current scanline
10995: $scan_record - hash ref as returned from &scantron_parse_scanline()
10996: $scan_config - hash ref as returned from &Apache::lonnet::get_scantron_config()
10997: $line - full contents of the current scanline
10998: $error - error condition, valid values are
10999: 'incorrectCODE', 'duplicateCODE',
11000: 'doublebubble', 'missingbubble',
11001: 'duplicateID', 'incorrectID'
11002: $arg - extra information needed
11003: For errors:
11004: - duplicateID - paper number that this studentID was seen before on
11005: - duplicateCODE - array ref of the paper numbers this CODE was
11006: seen on before
11007: - incorrectCODE - current incorrect CODE
11008: - doublebubble - array ref of the bubble lines that have double
11009: bubble errors
11010: - missingbubble - array ref of the bubble lines that have missing
11011: bubble errors
11012:
11013: $randomorder - True if exam folder has randomorder set
11014: $randompick - True if exam folder has randompick set
11015: $respnumlookup - Reference to HASH mapping question numbers in bubble lines
11016: for current line to question number used for same question
11017: in "Master Seqence" (as seen by Course Coordinator).
11018: $startline - Reference to hash where key is question number (0 is first)
11019: and value is number of first bubble line for current student
11020: or code-based randompick and/or randomorder.
11021:
11022:
11023: =item scantron_get_maxbubble() :
11024:
11025: Arguments:
11026: $nav_error - Reference to scalar which is a flag to indicate a
11027: failure to retrieve a navmap object.
11028: if $nav_error is set to 1 by scantron_get_maxbubble(), the
11029: calling routine should trap the error condition and display the warning
11030: found in &navmap_errormsg().
11031:
11032: $scantron_config - Reference to bubblesheet format configuration hash.
11033:
11034: Returns the maximum number of bubble lines that are expected to
11035: occur. Does this by walking the selected sequence rendering the
11036: resource and then checking &Apache::lonxml::get_problem_counter()
11037: for what the current value of the problem counter is.
11038:
11039: Caches the results to $env{'form.scantron_maxbubble'},
11040: $env{'form.scantron.bubble_lines.n'},
11041: $env{'form.scantron.first_bubble_line.n'} and
11042: $env{"form.scantron.sub_bubblelines.n"}
11043: which are the total number of bubble lines, the number of bubble
11044: lines for response n and number of the first bubble line for response n,
11045: and a comma separated list of numbers of bubble lines for sub-questions
11046: (for optionresponse, matchresponse, and rankresponse items), for response n.
11047:
11048:
11049: =item scantron_validate_missingbubbles() :
11050:
11051: Validates all scanlines in the selected file to not have any
11052: answers that don't have bubbles that have not been verified
11053: to be bubble free.
11054:
11055: =item scantron_process_students() :
11056:
11057: Routine that does the actual grading of the bubblesheet information.
11058:
11059: The parsed scanline hash is added to %env
11060:
11061: Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
11062: foreach resource , with the form data of
11063:
11064: 'submitted' =>'scantron'
11065: 'grade_target' =>'grade',
11066: 'grade_username'=> username of student
11067: 'grade_domain' => domain of student
11068: 'grade_courseid'=> of course
11069: 'grade_symb' => symb of resource to grade
11070:
11071: This triggers a grading pass. The problem grading code takes care
11072: of converting the bubbled letter information (now in %env) into a
11073: valid submission.
11074:
11075: =item scantron_upload_scantron_data() :
11076:
11077: Creates the screen for adding a new bubblesheet data file to a course.
11078:
11079: =item scantron_upload_scantron_data_save() :
11080:
11081: Adds a provided bubble information data file to the course if user
11082: has the correct privileges to do so.
11083:
11084: =item valid_file() :
11085:
11086: Validates that the requested bubble data file exists in the course.
11087:
11088: =item scantron_download_scantron_data() :
11089:
11090: Shows a list of the three internal files (original, corrected,
11091: skipped) for a specific bubblesheet data file that exists in the
11092: course.
11093:
11094: =item scantron_validate_ID() :
11095:
11096: Validates all scanlines in the selected file to not have any
11097: invalid or underspecified student/employee IDs
11098:
11099: =item navmap_errormsg() :
11100:
11101: Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
11102: Should be called whenever the request to instantiate a navmap object fails.
11103:
11104: =back
11105:
11106: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>