1: # The LearningOnline Network with CAPA
2: # The LON-CAPA Grading handler
3: #
4: # $Id: grades.pm,v 1.596.2.12.2.34 2015/03/17 12:37:40 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 String::Similarity;
48: use LONCAPA;
49:
50: use POSIX qw(floor);
51:
52:
53:
54: my %perm=();
55: my %old_essays=();
56:
57: # These variables are used to recover from ssi errors
58:
59: my $ssi_retries = 5;
60: my $ssi_error;
61: my $ssi_error_resource;
62: my $ssi_error_message;
63:
64:
65: sub ssi_with_retries {
66: my ($resource, $retries, %form) = @_;
67: my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
68: if ($response->is_error) {
69: $ssi_error = 1;
70: $ssi_error_resource = $resource;
71: $ssi_error_message = $response->code . " " . $response->message;
72: }
73:
74: return $content;
75:
76: }
77: #
78: # Prodcuces an ssi retry failure error message to the user:
79: #
80:
81: sub ssi_print_error {
82: my ($r) = @_;
83: my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
84: $r->print('
85: <br />
86: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
87: <p>
88: '.&mt('Unable to retrieve a resource from a server:').'<br />
89: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
90: '.&mt('Error:').' '.$ssi_error_message.'
91: </p>
92: <p>'.
93: &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 />'.
94: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
95: '</p>');
96: return;
97: }
98:
99: #
100: # --- Retrieve the parts from the metadata file.---
101: sub getpartlist {
102: my ($symb,$errorref) = @_;
103:
104: my $navmap = Apache::lonnavmaps::navmap->new();
105: unless (ref($navmap)) {
106: if (ref($errorref)) {
107: $$errorref = 'navmap';
108: return;
109: }
110: }
111: my $res = $navmap->getBySymb($symb);
112: my $partlist = $res->parts();
113: my $url = $res->src();
114: my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
115:
116: my @stores;
117: foreach my $part (@{ $partlist }) {
118: foreach my $key (@metakeys) {
119: if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
120: }
121: }
122: return @stores;
123: }
124:
125: # --- Get the symbolic name of a problem and the url
126: sub get_symb {
127: my ($request,$silent) = @_;
128: my $symb=$env{'form.symb'};
129: unless ($symb) {
130: (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
131: $symb = &Apache::lonnet::symbread($url);
132: if ($symb eq '') {
133: if (!$silent) {
134: $request->print(&mt("Unable to handle ambiguous references: [_1].",$url));
135: return ();
136: }
137: }
138: }
139: &Apache::lonenc::check_decrypt(\$symb);
140: return ($symb);
141: }
142:
143: #--- Format fullname, username:domain if different for display
144: #--- Use anywhere where the student names are listed
145: sub nameUserString {
146: my ($type,$fullname,$uname,$udom) = @_;
147: if ($type eq 'header') {
148: return '<b> '.&mt('Fullname').' </b><span class="LC_internal_info">('.&mt('Username').')</span>';
149: } else {
150: return ' '.$fullname.'<span class="LC_internal_info"> ('.$uname.
151: ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
152: }
153: }
154:
155: #--- Get the partlist and the response type for a given problem. ---
156: #--- Indicate if a response type is coded handgraded or not. ---
157: sub response_type {
158: my ($symb,$response_error) = @_;
159:
160: my $navmap = Apache::lonnavmaps::navmap->new();
161: unless (ref($navmap)) {
162: if (ref($response_error)) {
163: $$response_error = 1;
164: }
165: return;
166: }
167: my $res = $navmap->getBySymb($symb);
168: unless (ref($res)) {
169: $$response_error = 1;
170: return;
171: }
172: my $partlist = $res->parts();
173: my %vPart =
174: map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
175: my (%response_types,%handgrade);
176: foreach my $part (@{ $partlist }) {
177: next if (%vPart && !exists($vPart{$part}));
178:
179: my @types = $res->responseType($part);
180: my @ids = $res->responseIds($part);
181: for (my $i=0; $i < scalar(@ids); $i++) {
182: $response_types{$part}{$ids[$i]} = $types[$i];
183: $handgrade{$part.'_'.$ids[$i]} =
184: &Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
185: '.handgrade',$symb);
186: }
187: }
188: return ($partlist,\%handgrade,\%response_types);
189: }
190:
191: sub flatten_responseType {
192: my ($responseType) = @_;
193: my @part_response_id =
194: map {
195: my $part = $_;
196: map {
197: [$part,$_]
198: } sort(keys(%{ $responseType->{$part} }));
199: } sort(keys(%$responseType));
200: return @part_response_id;
201: }
202:
203: sub get_display_part {
204: my ($partID,$symb)=@_;
205: my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
206: if (defined($display) and $display ne '') {
207: $display.= ' (<span class="LC_internal_info">'
208: .&mt('Part ID: [_1]',$partID).'</span>)';
209: } else {
210: $display=$partID;
211: }
212: return $display;
213: }
214:
215: #--- Show resource title
216: #--- and parts and response type
217: sub showResourceInfo {
218: my ($symb,$probTitle,$checkboxes,$res_error) = @_;
219: my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
220: my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
221: if (ref($res_error)) {
222: if ($$res_error) {
223: return;
224: }
225: }
226: $result.=&Apache::loncommon::start_data_table()
227: .&Apache::loncommon::start_data_table_header_row();
228: if ($checkboxes) {
229: $result.='<th> </th>';
230: }
231: $result.='<th>'.&mt('Problem Part').'</th>'
232: .'<th>'.&mt('Res. ID').'</th>'
233: .'<th>'.&mt('Type').'</th>'
234: .&Apache::loncommon::end_data_table_header_row();
235: my %resptype = ();
236: my $hdgrade='no';
237: my %partsseen;
238: foreach my $partID (sort(keys(%$responseType))) {
239: foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
240: my $handgrade=$$handgrade{$partID.'_'.$resID};
241: my $responsetype = $responseType->{$partID}->{$resID};
242: $hdgrade = $handgrade if ($handgrade eq 'yes');
243: $result.=&Apache::loncommon::start_data_table_row();
244: if ($checkboxes) {
245: if (exists($partsseen{$partID})) {
246: $result.="<td> </td>";
247: } else {
248: $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
249: }
250: $partsseen{$partID}=1;
251: }
252: my $display_part=&get_display_part($partID,$symb);
253: $result.='<td>'.$display_part.'</td>'
254: .'<td>'.'<span class="LC_internal_info">'.$resID.'</span></td>'
255: .'<td>'.&mt($responsetype).'</td>'
256: # .'<td><b>'.&mt('Handgrade: [_1]',$handgrade).'</b></td>'
257: .&Apache::loncommon::end_data_table_row();
258: }
259: }
260: $result.=&Apache::loncommon::end_data_table();
261: return $result,$responseType,$hdgrade,$partlist,$handgrade;
262: }
263:
264: sub reset_caches {
265: &reset_analyze_cache();
266: &reset_perm();
267: &reset_old_essays();
268: }
269:
270: {
271: my %analyze_cache;
272: my %analyze_cache_formkeys;
273:
274: sub reset_analyze_cache {
275: undef(%analyze_cache);
276: undef(%analyze_cache_formkeys);
277: }
278:
279: sub get_analyze {
280: my ($symb,$uname,$udom,$no_increment,$add_to_hash,$type,$trial,$rndseed,$bubbles_per_row)=@_;
281: my $key = "$symb\0$uname\0$udom";
282: if ($type eq 'randomizetry') {
283: if ($trial ne '') {
284: $key .= "\0".$trial;
285: }
286: }
287: if (exists($analyze_cache{$key})) {
288: my $getupdate = 0;
289: if (ref($add_to_hash) eq 'HASH') {
290: foreach my $item (keys(%{$add_to_hash})) {
291: if (ref($analyze_cache_formkeys{$key}) eq 'HASH') {
292: if (!exists($analyze_cache_formkeys{$key}{$item})) {
293: $getupdate = 1;
294: last;
295: }
296: } else {
297: $getupdate = 1;
298: }
299: }
300: }
301: if (!$getupdate) {
302: return $analyze_cache{$key};
303: }
304: }
305:
306: my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
307: $url=&Apache::lonnet::clutter($url);
308: my %form = ('grade_target' => 'analyze',
309: 'grade_domain' => $udom,
310: 'grade_symb' => $symb,
311: 'grade_courseid' => $env{'request.course.id'},
312: 'grade_username' => $uname,
313: 'grade_noincrement' => $no_increment);
314: if ($bubbles_per_row ne '') {
315: $form{'bubbles_per_row'} = $bubbles_per_row;
316: }
317: if ($type eq 'randomizetry') {
318: $form{'grade_questiontype'} = $type;
319: if ($rndseed ne '') {
320: $form{'grade_rndseed'} = $rndseed;
321: }
322: }
323: if (ref($add_to_hash)) {
324: %form = (%form,%{$add_to_hash});
325: }
326: my $subresult=&ssi_with_retries($url, $ssi_retries,%form);
327: (undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
328: my %analyze=&Apache::lonnet::str2hash($subresult);
329: if (ref($add_to_hash) eq 'HASH') {
330: $analyze_cache_formkeys{$key} = $add_to_hash;
331: } else {
332: $analyze_cache_formkeys{$key} = {};
333: }
334: return $analyze_cache{$key} = \%analyze;
335: }
336:
337: sub get_order {
338: my ($partid,$respid,$symb,$uname,$udom,$no_increment,$type,$trial,$rndseed)=@_;
339: my $analyze = &get_analyze($symb,$uname,$udom,$no_increment,undef,$type,$trial,$rndseed);
340: return $analyze->{"$partid.$respid.shown"};
341: }
342:
343: sub get_radiobutton_correct_foil {
344: my ($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed)=@_;
345: my $analyze = &get_analyze($symb,$uname,$udom,undef,undef,$type,$trial,$rndseed);
346: my $foils = &get_order($partid,$respid,$symb,$uname,$udom,undef,$type,$trial,$rndseed);
347: if (ref($foils) eq 'ARRAY') {
348: foreach my $foil (@{$foils}) {
349: if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
350: return $foil;
351: }
352: }
353: }
354: }
355:
356: sub scantron_partids_tograde {
357: my ($resource,$cid,$uname,$udom,$check_for_randomlist,$bubbles_per_row) = @_;
358: my (%analysis,@parts);
359: if (ref($resource)) {
360: my $symb = $resource->symb();
361: my $add_to_form;
362: if ($check_for_randomlist) {
363: $add_to_form = { 'check_parts_withrandomlist' => 1,};
364: }
365: my $analyze =
366: &get_analyze($symb,$uname,$udom,undef,$add_to_form,
367: undef,undef,undef,$bubbles_per_row);
368: if (ref($analyze) eq 'HASH') {
369: %analysis = %{$analyze};
370: }
371: if (ref($analysis{'parts'}) eq 'ARRAY') {
372: foreach my $part (@{$analysis{'parts'}}) {
373: my ($id,$respid) = split(/\./,$part);
374: if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
375: push(@parts,$part);
376: }
377: }
378: }
379: }
380: return (\%analysis,\@parts);
381: }
382:
383: }
384:
385: #--- Clean response type for display
386: #--- Currently filters option/rank/radiobutton/match/essay/Task
387: # response types only.
388: sub cleanRecord {
389: my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
390: $uname,$udom,$type,$trial,$rndseed) = @_;
391: my $grayFont = '<span class="LC_internal_info">';
392: if ($response =~ /^(option|rank)$/) {
393: my %answer=&Apache::lonnet::str2hash($answer);
394: my @answer = %answer;
395: %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
396: my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
397: my ($toprow,$bottomrow);
398: foreach my $foil (@$order) {
399: if ($grading{$foil} == 1) {
400: $toprow.='<td><b>'.$answer{$foil}.' </b></td>';
401: } else {
402: $toprow.='<td><i>'.$answer{$foil}.' </i></td>';
403: }
404: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
405: }
406: return '<blockquote><table border="1">'.
407: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
408: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
409: $bottomrow.'</tr></table></blockquote>';
410: } elsif ($response eq 'match') {
411: my %answer=&Apache::lonnet::str2hash($answer);
412: my @answer = %answer;
413: %answer = map {&HTML::Entities::encode($_, '"<>&')} @answer;
414: my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
415: my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
416: my ($toprow,$middlerow,$bottomrow);
417: foreach my $foil (@$order) {
418: my $item=shift(@items);
419: if ($grading{$foil} == 1) {
420: $toprow.='<td><b>'.$item.' </b></td>';
421: $middlerow.='<td><b>'.$grayFont.$answer{$foil}.' </span></b></td>';
422: } else {
423: $toprow.='<td><i>'.$item.' </i></td>';
424: $middlerow.='<td><i>'.$grayFont.$answer{$foil}.' </span></i></td>';
425: }
426: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
427: }
428: return '<blockquote><table border="1">'.
429: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
430: '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
431: $middlerow.'</tr>'.
432: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
433: $bottomrow.'</tr></table></blockquote>';
434: } elsif ($response eq 'radiobutton') {
435: my %answer=&Apache::lonnet::str2hash($answer);
436: my ($toprow,$bottomrow);
437: my $correct =
438: &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom,$type,$trial,$rndseed);
439: foreach my $foil (@$order) {
440: if (exists($answer{$foil})) {
441: if ($foil eq $correct) {
442: $toprow.='<td><b>'.&mt('true').'</b></td>';
443: } else {
444: $toprow.='<td><i>'.&mt('true').'</i></td>';
445: }
446: } else {
447: $toprow.='<td>'.&mt('false').'</td>';
448: }
449: $bottomrow.='<td>'.$grayFont.$foil.'</span> </td>';
450: }
451: return '<blockquote><table border="1">'.
452: '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
453: '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
454: $bottomrow.'</tr></table></blockquote>';
455: } elsif ($response eq 'essay') {
456: if (! exists ($env{'form.'.$symb})) {
457: my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
458: $env{'course.'.$env{'request.course.id'}.'.domain'},
459: $env{'course.'.$env{'request.course.id'}.'.num'});
460:
461: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
462: $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
463: $env{'form.kwclr'} = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
464: $env{'form.kwsize'} = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
465: $env{'form.kwstyle'} = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
466: $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
467: }
468: return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
469: } elsif ( $response eq 'organic') {
470: my $result=&mt('Smile representation: [_1]',
471: '"<tt>'.&HTML::Entities::encode($answer, '"<>&').'</tt>"');
472: my $jme=$record->{$version."resource.$partid.$respid.molecule"};
473: $result.=&Apache::chemresponse::jme_img($jme,$answer,400);
474: return $result;
475: } elsif ( $response eq 'Task') {
476: if ( $answer eq 'SUBMITTED') {
477: my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
478: my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
479: return $result;
480: } elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
481: my @matches = grep(/^\Q$version\E.*?\.instance$/,
482: keys(%{$record}));
483: return join('<br />',($version,@matches));
484:
485:
486: } else {
487: my $result =
488: '<p>'
489: .&mt('Overall result: [_1]',
490: $record->{$version."resource.$respid.$partid.status"})
491: .'</p>';
492:
493: $result .= '<ul>';
494: my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
495: keys(%{$record}));
496: foreach my $grade (sort(@grade)) {
497: my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
498: $result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
499: $dim, $record->{$grade}).
500: '</li>';
501: }
502: $result.='</ul>';
503: return $result;
504: }
505: } elsif ( $response =~ m/(?:numerical|formula|custom)/) {
506: # Respect multiple input fields, see Bug #5409
507: $answer =
508: &Apache::loncommon::format_previous_attempt_value('submission',
509: $answer);
510: return $answer;
511: }
512: return &HTML::Entities::encode($answer, '"<>&');
513: }
514:
515: #-- A couple of common js functions
516: sub commonJSfunctions {
517: my $request = shift;
518: $request->print(<<COMMONJSFUNCTIONS);
519: <script type="text/javascript" language="javascript">
520: function radioSelection(radioButton) {
521: var selection=null;
522: if (radioButton.length > 1) {
523: for (var i=0; i<radioButton.length; i++) {
524: if (radioButton[i].checked) {
525: return radioButton[i].value;
526: }
527: }
528: } else {
529: if (radioButton.checked) return radioButton.value;
530: }
531: return selection;
532: }
533:
534: function pullDownSelection(selectOne) {
535: var selection="";
536: if (selectOne.length > 1) {
537: for (var i=0; i<selectOne.length; i++) {
538: if (selectOne[i].selected) {
539: return selectOne[i].value;
540: }
541: }
542: } else {
543: // only one value it must be the selected one
544: return selectOne.value;
545: }
546: }
547: </script>
548: COMMONJSFUNCTIONS
549: }
550:
551: #--- Dumps the class list with usernames,list of sections,
552: #--- section, ids and fullnames for each user.
553: sub getclasslist {
554: my ($getsec,$filterlist,$getgroup) = @_;
555: my @getsec;
556: my @getgroup;
557: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
558: if (!ref($getsec)) {
559: if ($getsec ne '' && $getsec ne 'all') {
560: @getsec=($getsec);
561: }
562: } else {
563: @getsec=@{$getsec};
564: }
565: if (grep(/^all$/,@getsec)) { undef(@getsec); }
566: if (!ref($getgroup)) {
567: if ($getgroup ne '' && $getgroup ne 'all') {
568: @getgroup=($getgroup);
569: }
570: } else {
571: @getgroup=@{$getgroup};
572: }
573: if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
574:
575: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
576: # Bail out if we were unable to get the classlist
577: return if (! defined($classlist));
578: &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
579: #
580: my %sections;
581: my %fullnames;
582: foreach my $student (keys(%$classlist)) {
583: my $end =
584: $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
585: my $start =
586: $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
587: my $id =
588: $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
589: my $section =
590: $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
591: my $fullname =
592: $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
593: my $status =
594: $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
595: my $group =
596: $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
597: # filter students according to status selected
598: if ($filterlist && (!($stu_status =~ /Any/))) {
599: if (!($stu_status =~ $status)) {
600: delete($classlist->{$student});
601: next;
602: }
603: }
604: # filter students according to groups selected
605: my @stu_groups = split(/,/,$group);
606: if (@getgroup) {
607: my $exclude = 1;
608: foreach my $grp (@getgroup) {
609: foreach my $stu_group (@stu_groups) {
610: if ($stu_group eq $grp) {
611: $exclude = 0;
612: }
613: }
614: if (($grp eq 'none') && !$group) {
615: $exclude = 0;
616: }
617: }
618: if ($exclude) {
619: delete($classlist->{$student});
620: }
621: }
622: $section = ($section ne '' ? $section : 'none');
623: if (&canview($section)) {
624: if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
625: $sections{$section}++;
626: if ($classlist->{$student}) {
627: $fullnames{$student}=$fullname;
628: }
629: } else {
630: delete($classlist->{$student});
631: }
632: } else {
633: delete($classlist->{$student});
634: }
635: }
636: my %seen = ();
637: my @sections = sort(keys(%sections));
638: return ($classlist,\@sections,\%fullnames);
639: }
640:
641: sub canmodify {
642: my ($sec)=@_;
643: if ($perm{'mgr'}) {
644: if (!defined($perm{'mgr_section'})) {
645: # can modify whole class
646: return 1;
647: } else {
648: if ($sec eq $perm{'mgr_section'}) {
649: #can modify the requested section
650: return 1;
651: } else {
652: # can't modify the request section
653: return 0;
654: }
655: }
656: }
657: #can't modify
658: return 0;
659: }
660:
661: sub canview {
662: my ($sec)=@_;
663: if ($perm{'vgr'}) {
664: if (!defined($perm{'vgr_section'})) {
665: # can modify whole class
666: return 1;
667: } else {
668: if ($sec eq $perm{'vgr_section'}) {
669: #can modify the requested section
670: return 1;
671: } else {
672: # can't modify the request section
673: return 0;
674: }
675: }
676: }
677: #can't modify
678: return 0;
679: }
680:
681: #--- Retrieve the grade status of a student for all the parts
682: sub student_gradeStatus {
683: my ($symb,$udom,$uname,$partlist) = @_;
684: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
685: my %partstatus = ();
686: foreach (@$partlist) {
687: my ($status,undef) = split(/_/,$record{"resource.$_.solved"},2);
688: $status = 'nothing' if ($status eq '');
689: $partstatus{$_} = $status;
690: my $subkey = "resource.$_.submitted_by";
691: $partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
692: }
693: return %partstatus;
694: }
695:
696: # hidden form and javascript that calls the form
697: # Use by verifyscript and viewgrades
698: # Shows a student's view of problem and submission
699: sub jscriptNform {
700: my ($symb) = @_;
701: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
702: my $jscript='<script type="text/javascript" language="javascript">'."\n".
703: ' function viewOneStudent(user,domain) {'."\n".
704: ' document.onestudent.student.value = user;'."\n".
705: ' document.onestudent.userdom.value = domain;'."\n".
706: ' document.onestudent.submit();'."\n".
707: ' }'."\n".
708: '</script>'."\n";
709: $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
710: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
711: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
712: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
713: '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
714: '<input type="hidden" name="command" value="submission" />'."\n".
715: '<input type="hidden" name="student" value="" />'."\n".
716: '<input type="hidden" name="userdom" value="" />'."\n".
717: '</form>'."\n";
718: return $jscript;
719: }
720:
721:
722:
723: # Given the score (as a number [0-1] and the weight) what is the final
724: # point value? This function will round to the nearest tenth, third,
725: # or quarter if one of those is within the tolerance of .00001.
726: sub compute_points {
727: my ($score, $weight) = @_;
728:
729: my $tolerance = .00001;
730: my $points = $score * $weight;
731:
732: # Check for nearness to 1/x.
733: my $check_for_nearness = sub {
734: my ($factor) = @_;
735: my $num = ($points * $factor) + $tolerance;
736: my $floored_num = floor($num);
737: if ($num - $floored_num < 2 * $tolerance * $factor) {
738: return $floored_num / $factor;
739: }
740: return $points;
741: };
742:
743: $points = $check_for_nearness->(10);
744: $points = $check_for_nearness->(3);
745: $points = $check_for_nearness->(4);
746:
747: return $points;
748: }
749:
750: #------------------ End of general use routines --------------------
751:
752: #
753: # Find most similar essay
754: #
755:
756: sub most_similar {
757: my ($uname,$udom,$symb,$uessay)=@_;
758:
759: unless ($symb) { return ''; }
760:
761: unless (ref($old_essays{$symb}) eq 'HASH') { return ''; }
762:
763: # ignore spaces and punctuation
764:
765: $uessay=~s/\W+/ /gs;
766:
767: # ignore empty submissions (occuring when only files are sent)
768:
769: unless ($uessay=~/\w+/s) { return ''; }
770:
771: # these will be returned. Do not care if not at least 50 percent similar
772: my $limit=0.6;
773: my $sname='';
774: my $sdom='';
775: my $scrsid='';
776: my $sessay='';
777: # go through all essays ...
778: foreach my $tkey (keys(%{$old_essays{$symb}})) {
779: my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
780: # ... except the same student
781: next if (($tname eq $uname) && ($tdom eq $udom));
782: my $tessay=$old_essays{$symb}{$tkey};
783: $tessay=~s/\W+/ /gs;
784: # String similarity gives up if not even limit
785: my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
786: # Found one
787: if ($tsimilar>$limit) {
788: $limit=$tsimilar;
789: $sname=$tname;
790: $sdom=$tdom;
791: $scrsid=$tcrsid;
792: $sessay=$old_essays{$symb}{$tkey};
793: }
794: }
795: if ($limit>0.6) {
796: return ($sname,$sdom,$scrsid,$sessay,$limit);
797: } else {
798: return ('','','','',0);
799: }
800: }
801:
802: #-------------------------------------------------------------------
803:
804: #------------------------------------ Receipt Verification Routines
805: #
806: #--- Check whether a receipt number is valid.---
807: sub verifyreceipt {
808: my $request = shift;
809:
810: my $courseid = $env{'request.course.id'};
811: my $receipt = &Apache::lonnet::recprefix($courseid).'-'.
812: $env{'form.receipt'};
813: $receipt =~ s/[^\-\d]//g;
814: my ($symb) = &get_symb($request);
815:
816: my $title.=
817: '<h3><span class="LC_info">'.
818: &mt('Verifying Receipt No. [_1]',$receipt).
819: '</span></h3>'."\n".
820: '<h4>'.&mt('[_1]Resource: [_2]','<b>','</b>'.$env{'form.probTitle'}).
821: '</h4>'."\n";
822:
823: my ($string,$contents,$matches) = ('','',0);
824: my (undef,undef,$fullname) = &getclasslist('all','0');
825:
826: my $receiptparts=0;
827: if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
828: $env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
829: my $parts=['0'];
830: if ($receiptparts) {
831: my $res_error;
832: ($parts)=&response_type($symb,\$res_error);
833: if ($res_error) {
834: return &navmap_errormsg();
835: }
836: }
837:
838: my $header =
839: &Apache::loncommon::start_data_table().
840: &Apache::loncommon::start_data_table_header_row().
841: '<th> '.&mt('Fullname').' </th>'."\n".
842: '<th> '.&mt('Username').' </th>'."\n".
843: '<th> '.&mt('Domain').' </th>';
844: if ($receiptparts) {
845: $header.='<th> '.&mt('Problem Part').' </th>';
846: }
847: $header.=
848: &Apache::loncommon::end_data_table_header_row();
849:
850: foreach (sort
851: {
852: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
853: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
854: }
855: return $a cmp $b;
856: } (keys(%$fullname))) {
857: my ($uname,$udom)=split(/\:/);
858: foreach my $part (@$parts) {
859: if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
860: $contents.=
861: &Apache::loncommon::start_data_table_row().
862: '<td> '."\n".
863: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
864: '\');" target="_self">'.$$fullname{$_}.'</a> </td>'."\n".
865: '<td> '.$uname.' </td>'.
866: '<td> '.$udom.' </td>';
867: if ($receiptparts) {
868: $contents.='<td> '.$part.' </td>';
869: }
870: $contents.=
871: &Apache::loncommon::end_data_table_row()."\n";
872:
873: $matches++;
874: }
875: }
876: }
877: if ($matches == 0) {
878: $string = $title
879: .'<p class="LC_warning">'
880: .&mt('No match found for the above receipt number.')
881: .'</p>';
882: } else {
883: $string = &jscriptNform($symb).$title.
884: '<p>'.
885: &mt('The above receipt number matches the following [quant,_1,student].',$matches).
886: '</p>'.
887: $header.
888: $contents.
889: &Apache::loncommon::end_data_table()."\n";
890: }
891: return $string.&show_grading_menu_form($symb);
892: }
893:
894: #--- This is called by a number of programs.
895: #--- Called from the Grading Menu - View/Grade an individual student
896: #--- Also called directly when one clicks on the subm button
897: # on the problem page.
898: sub listStudents {
899: my ($request) = shift;
900:
901: my ($symb) = &get_symb($request);
902: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
903: my $cnum = $env{"course.$env{'request.course.id'}.num"};
904: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
905: my $getgroup = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
906: my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
907: my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
908: $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ?
909: &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
910:
911: my $result='<h3><span class="LC_info"> '
912: .&mt("$viewgrade Submissions for a Student or a Group of Students")
913: .'</span></h3>';
914:
915: my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
916:
917: my %lt = &Apache::lonlocal::texthash (
918: 'multiple' => 'Please select a student or group of students before clicking on the Next button.',
919: 'single' => 'Please select the student before clicking on the Next button.',
920: );
921: $request->print(<<LISTJAVASCRIPT);
922: <script type="text/javascript" language="javascript">
923: function checkSelect(checkBox) {
924: var ctr=0;
925: var sense="";
926: if (checkBox.length > 1) {
927: for (var i=0; i<checkBox.length; i++) {
928: if (checkBox[i].checked) {
929: ctr++;
930: }
931: }
932: sense = '$lt{'multiple'}';
933: } else {
934: if (checkBox.checked) {
935: ctr = 1;
936: }
937: sense = '$lt{'single'}';
938: }
939: if (ctr == 0) {
940: alert(sense);
941: return false;
942: }
943: document.gradesub.submit();
944: }
945:
946: function reLoadList(formname) {
947: if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
948: formname.command.value = 'submission';
949: formname.submit();
950: }
951: </script>
952: LISTJAVASCRIPT
953:
954: &commonJSfunctions($request);
955: $request->print($result);
956:
957: my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
958: my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
959: my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
960: "\n".$table;
961:
962: $gradeTable .= &Apache::lonhtmlcommon::start_pick_box();
963: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Problem Text'))
964: .'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n"
965: .'<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n"
966: .'<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label><br />'."\n"
967: .&Apache::lonhtmlcommon::row_closure();
968: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('View Answer'))
969: .'<label><input type="radio" name="vAns" value="no" /> '.&mt('no').' </label>'."\n"
970: .'<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n"
971: .'<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label><br />'."\n"
972: .&Apache::lonhtmlcommon::row_closure();
973:
974: my $submission_options;
975: if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
976: $submission_options.=
977: '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
978: }
979: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
980: my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
981: $env{'form.Status'} = $saveStatus;
982: $submission_options.=
983: '<span class="LC_nobreak">'.
984: '<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.
985: &mt('last submission only').' </label></span>'."\n".
986: '<span class="LC_nobreak">'.
987: '<label><input type="radio" name="lastSub" value="last" /> '.
988: &mt('last submission & parts info').' </label></span>'."\n".
989: '<span class="LC_nobreak">'.
990: '<label><input type="radio" name="lastSub" value="datesub" /> '.
991: &mt('by dates and submissions').'</label></span>'."\n".
992: '<span class="LC_nobreak">'.
993: '<label><input type="radio" name="lastSub" value="all" /> '.
994: &mt('all details').'</label></span>';
995: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Submissions'))
996: .$submission_options
997: .&Apache::lonhtmlcommon::row_closure();
998:
999: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Grading Increments'))
1000: .'<select name="increment">'
1001: .'<option value="1">'.&mt('Whole Points').'</option>'
1002: .'<option value=".5">'.&mt('Half Points').'</option>'
1003: .'<option value=".25">'.&mt('Quarter Points').'</option>'
1004: .'<option value=".1">'.&mt('Tenths of a Point').'</option>'
1005: .'</select>'
1006: .&Apache::lonhtmlcommon::row_closure();
1007:
1008: $gradeTable .=
1009: &build_section_inputs().
1010: '<input type="hidden" name="submitonly" value="'.$submitonly.'" />'."\n".
1011: '<input type="hidden" name="handgrade" value="'.$env{'form.handgrade'}.'" /><br />'."\n".
1012: '<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
1013: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1014: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
1015: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1016: '<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
1017:
1018: if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
1019: $gradeTable .= '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n";
1020: } else {
1021: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Student Status'))
1022: .&Apache::lonhtmlcommon::StatusOptions(
1023: $saveStatus,undef,1,'javascript:reLoadList(this.form);')
1024: .&Apache::lonhtmlcommon::row_closure();
1025: }
1026:
1027: $gradeTable .= &Apache::lonhtmlcommon::row_title(&mt('Check For Plagiarism'))
1028: .'<input type="checkbox" name="checkPlag" checked="checked" />'
1029: .&Apache::lonhtmlcommon::row_closure(1)
1030: .&Apache::lonhtmlcommon::end_pick_box();
1031:
1032: $gradeTable .= '<p>'
1033: .&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"
1034: .'<input type="hidden" name="command" value="processGroup" />'
1035: .'</p>';
1036:
1037: # checkall buttons
1038: $gradeTable.=&check_script('gradesub', 'stuinfo');
1039: $gradeTable.='<input type="button" '."\n".
1040: 'onclick="javascript:checkSelect(this.form.stuinfo);" '."\n".
1041: 'value="'.&mt('Next').' →" /> <br />'."\n";
1042: $gradeTable.=&check_buttons();
1043: my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1044: $gradeTable.= &Apache::loncommon::start_data_table().
1045: &Apache::loncommon::start_data_table_header_row();
1046: my $loop = 0;
1047: while ($loop < 2) {
1048: $gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
1049: '<th>'.&nameUserString('header').' '.&mt('Section/Group').'</th>';
1050: if ($env{'form.showgrading'} eq 'yes'
1051: && $submitonly ne 'queued'
1052: && $submitonly ne 'all') {
1053: foreach my $part (sort(@$partlist)) {
1054: my $display_part=
1055: &get_display_part((split(/_/,$part))[0],$symb);
1056: $gradeTable.=
1057: '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1058: }
1059: } elsif ($submitonly eq 'queued') {
1060: $gradeTable.='<th>'.&mt('Queue Status').' </th>';
1061: }
1062: $loop++;
1063: # $gradeTable.='<td></td>' if ($loop%2 ==1);
1064: }
1065: $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1066:
1067: my $ctr = 0;
1068: foreach my $student (sort
1069: {
1070: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
1071: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
1072: }
1073: return $a cmp $b;
1074: }
1075: (keys(%$fullname))) {
1076: my ($uname,$udom) = split(/:/,$student);
1077:
1078: my %status = ();
1079:
1080: if ($submitonly eq 'queued') {
1081: my %queue_status =
1082: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
1083: $udom,$uname);
1084: next if (!defined($queue_status{'gradingqueue'}));
1085: $status{'gradingqueue'} = $queue_status{'gradingqueue'};
1086: }
1087:
1088: if ($env{'form.showgrading'} eq 'yes'
1089: && $submitonly ne 'queued'
1090: && $submitonly ne 'all') {
1091: (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1092: my $submitted = 0;
1093: my $graded = 0;
1094: my $incorrect = 0;
1095: foreach (keys(%status)) {
1096: $submitted = 1 if ($status{$_} ne 'nothing');
1097: $graded = 1 if ($status{$_} =~ /^ungraded/);
1098: $incorrect = 1 if ($status{$_} =~ /^incorrect/);
1099:
1100: my ($foo,$partid,$foo1) = split(/\./,$_);
1101: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1102: $submitted = 0;
1103: my ($part)=split(/\./,$partid);
1104: $gradeTable.='<input type="hidden" name="'.
1105: $student.':'.$part.':submitted_by" value="'.
1106: $status{'resource.'.$partid.'.submitted_by'}.'" />';
1107: }
1108: }
1109:
1110: next if (!$submitted && ($submitonly eq 'yes' ||
1111: $submitonly eq 'incorrect' ||
1112: $submitonly eq 'graded'));
1113: next if (!$graded && ($submitonly eq 'graded'));
1114: next if (!$incorrect && $submitonly eq 'incorrect');
1115: }
1116:
1117: $ctr++;
1118: my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1119: my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1120: if ( $perm{'vgr'} eq 'F' ) {
1121: if ($ctr%2 ==1) {
1122: $gradeTable.= &Apache::loncommon::start_data_table_row();
1123: }
1124: $gradeTable.='<td align="right">'.$ctr.' </td>'.
1125: '<td align="center"><label><input type="checkbox" name="stuinfo" value="'.
1126: $student.':'.$$fullname{$student}.':::SECTION'.$section.
1127: ') " /> </label></td>'."\n".'<td>'.
1128: &nameUserString(undef,$$fullname{$student},$uname,$udom).
1129: ' '.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1130:
1131: if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1132: foreach (sort(keys(%status))) {
1133: next if ($_ =~ /^resource.*?submitted_by$/);
1134: $gradeTable.='<td align="center"> '.&mt($status{$_}).' </td>'."\n";
1135: }
1136: }
1137: # $gradeTable.='<td></td>' if ($ctr%2 ==1);
1138: if ($ctr%2 ==0) {
1139: $gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
1140: }
1141: }
1142: }
1143: if ($ctr%2 ==1) {
1144: $gradeTable.='<td> </td><td> </td><td> </td>';
1145: if ($env{'form.showgrading'} eq 'yes'
1146: && $submitonly ne 'queued'
1147: && $submitonly ne 'all') {
1148: foreach (@$partlist) {
1149: $gradeTable.='<td> </td>';
1150: }
1151: } elsif ($submitonly eq 'queued') {
1152: $gradeTable.='<td> </td>';
1153: }
1154: $gradeTable.=&Apache::loncommon::end_data_table_row();
1155: }
1156:
1157: $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1158: '<input type="button" '.
1159: 'onclick="javascript:checkSelect(this.form.stuinfo);" '.
1160: 'value="'.&mt('Next').' →" /></form>'."\n";
1161: if ($ctr == 0) {
1162: my $num_students=(scalar(keys(%$fullname)));
1163: if ($num_students eq 0) {
1164: $gradeTable='<br /> <span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1165: } else {
1166: my $submissions='submissions';
1167: if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
1168: if ($submitonly eq 'graded' ) { $submissions = 'ungraded submissions'; }
1169: if ($submitonly eq 'queued' ) { $submissions = 'queued submissions'; }
1170: $gradeTable='<br /> <span class="LC_warning">'.
1171: &mt('No '.$submissions.' found for this resource for any students. ([quant,_1,student] checked for '.$submissions.')',
1172: $num_students).
1173: '</span><br />';
1174: }
1175: } elsif ($ctr == 1) {
1176: $gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1177: }
1178: $gradeTable.=&show_grading_menu_form($symb);
1179: $request->print($gradeTable);
1180: return '';
1181: }
1182:
1183: #---- Called from the listStudents routine
1184:
1185: sub check_script {
1186: my ($form, $type)=@_;
1187: my $chkallscript='<script type="text/javascript">
1188: function checkall() {
1189: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1190: ele = document.forms.'.$form.'.elements[i];
1191: if (ele.name == "'.$type.'") {
1192: document.forms.'.$form.'.elements[i].checked=true;
1193: }
1194: }
1195: }
1196:
1197: function checksec() {
1198: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1199: ele = document.forms.'.$form.'.elements[i];
1200: string = document.forms.'.$form.'.chksec.value;
1201: if
1202: (ele.value.indexOf(":::SECTION"+string)>0) {
1203: document.forms.'.$form.'.elements[i].checked=true;
1204: }
1205: }
1206: }
1207:
1208:
1209: function uncheckall() {
1210: for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
1211: ele = document.forms.'.$form.'.elements[i];
1212: if (ele.name == "'.$type.'") {
1213: document.forms.'.$form.'.elements[i].checked=false;
1214: }
1215: }
1216: }
1217:
1218: </script>'."\n";
1219: return $chkallscript;
1220: }
1221:
1222: sub check_buttons {
1223: my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
1224: $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" /> ';
1225: $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1226: $buttons.='<input type="text" size="5" name="chksec" /> ';
1227: return $buttons;
1228: }
1229:
1230: # Displays the submissions for one student or a group of students
1231: sub processGroup {
1232: my ($request) = shift;
1233: my $ctr = 0;
1234: my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1235: my $total = scalar(@stuchecked)-1;
1236:
1237: foreach my $student (@stuchecked) {
1238: my ($uname,$udom,$fullname) = split(/:/,$student);
1239: $env{'form.student'} = $uname;
1240: $env{'form.userdom'} = $udom;
1241: $env{'form.fullname'} = $fullname;
1242: &submission($request,$ctr,$total);
1243: $ctr++;
1244: }
1245: return '';
1246: }
1247:
1248: #------------------------------------------------------------------------------------
1249: #
1250: #-------------------------- Next few routines handles grading by student, essentially
1251: # handles essay response type problem/part
1252: #
1253: #--- Javascript to handle the submission page functionality ---
1254: sub sub_page_js {
1255: my $request = shift;
1256: my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
1257: $request->print(<<SUBJAVASCRIPT);
1258: <script type="text/javascript" language="javascript">
1259: function updateRadio(formname,id,weight) {
1260: var gradeBox = formname["GD_BOX"+id];
1261: var radioButton = formname["RADVAL"+id];
1262: var oldpts = formname["oldpts"+id].value;
1263: var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1264: gradeBox.value = pts;
1265: var resetbox = false;
1266: if (isNaN(pts) || pts < 0) {
1267: alert("$alertmsg"+pts);
1268: for (var i=0; i<radioButton.length; i++) {
1269: if (radioButton[i].checked) {
1270: gradeBox.value = i;
1271: resetbox = true;
1272: }
1273: }
1274: if (!resetbox) {
1275: formtextbox.value = "";
1276: }
1277: return;
1278: }
1279:
1280: if (pts > weight) {
1281: var resp = confirm("You entered a value ("+pts+
1282: ") greater than the weight for the part. Accept?");
1283: if (resp == false) {
1284: gradeBox.value = oldpts;
1285: return;
1286: }
1287: }
1288:
1289: for (var i=0; i<radioButton.length; i++) {
1290: radioButton[i].checked=false;
1291: if (pts == i && pts != "") {
1292: radioButton[i].checked=true;
1293: }
1294: }
1295: updateSelect(formname,id);
1296: formname["stores"+id].value = "0";
1297: }
1298:
1299: function writeBox(formname,id,pts) {
1300: var gradeBox = formname["GD_BOX"+id];
1301: if (checkSolved(formname,id) == 'update') {
1302: gradeBox.value = pts;
1303: } else {
1304: var oldpts = formname["oldpts"+id].value;
1305: gradeBox.value = oldpts;
1306: var radioButton = formname["RADVAL"+id];
1307: for (var i=0; i<radioButton.length; i++) {
1308: radioButton[i].checked=false;
1309: if (i == oldpts) {
1310: radioButton[i].checked=true;
1311: }
1312: }
1313: }
1314: formname["stores"+id].value = "0";
1315: updateSelect(formname,id);
1316: return;
1317: }
1318:
1319: function clearRadBox(formname,id) {
1320: if (checkSolved(formname,id) == 'noupdate') {
1321: updateSelect(formname,id);
1322: return;
1323: }
1324: gradeSelect = formname["GD_SEL"+id];
1325: for (var i=0; i<gradeSelect.length; i++) {
1326: if (gradeSelect[i].selected) {
1327: var selectx=i;
1328: }
1329: }
1330: var stores = formname["stores"+id];
1331: if (selectx == stores.value) { return };
1332: var gradeBox = formname["GD_BOX"+id];
1333: gradeBox.value = "";
1334: var radioButton = formname["RADVAL"+id];
1335: for (var i=0; i<radioButton.length; i++) {
1336: radioButton[i].checked=false;
1337: }
1338: stores.value = selectx;
1339: }
1340:
1341: function checkSolved(formname,id) {
1342: if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1343: var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
1344: if (!reply) {return "noupdate";}
1345: formname.overRideScore.value = 'yes';
1346: }
1347: return "update";
1348: }
1349:
1350: function updateSelect(formname,id) {
1351: formname["GD_SEL"+id][0].selected = true;
1352: return;
1353: }
1354:
1355: //=========== Check that a point is assigned for all the parts ============
1356: function checksubmit(formname,val,total,parttot) {
1357: formname.gradeOpt.value = val;
1358: if (val == "Save & Next") {
1359: for (i=0;i<=total;i++) {
1360: for (j=0;j<parttot;j++) {
1361: var partid = formname["partid"+i+"_"+j].value;
1362: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1363: var points = formname["GD_BOX"+i+"_"+partid].value;
1364: if (points == "") {
1365: var name = formname["name"+i].value;
1366: var studentID = (name != '' ? name : formname["unamedom"+i].value);
1367: var resp = confirm("You did not assign a score for "+studentID+
1368: ", part "+partid+". Continue?");
1369: if (resp == false) {
1370: formname["GD_BOX"+i+"_"+partid].focus();
1371: return false;
1372: }
1373: }
1374: }
1375: }
1376: }
1377: }
1378: if (val == "Grade Student") {
1379: formname.showgrading.value = "yes";
1380: if (formname.Status.value == "") {
1381: formname.Status.value = "Active";
1382: }
1383: formname.studentNo.value = total;
1384: }
1385: formname.submit();
1386: }
1387:
1388: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
1389: function checkSubmitPage(formname,total) {
1390: noscore = new Array(100);
1391: var ptr = 0;
1392: for (i=1;i<total;i++) {
1393: var partid = formname["q_"+i].value;
1394: if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1395: var points = formname["GD_BOX"+i+"_"+partid].value;
1396: var status = formname["solved"+i+"_"+partid].value;
1397: if (points == "" && status != "correct_by_student") {
1398: noscore[ptr] = i;
1399: ptr++;
1400: }
1401: }
1402: }
1403: if (ptr != 0) {
1404: var sense = ptr == 1 ? ": " : "s: ";
1405: var prolist = "";
1406: if (ptr == 1) {
1407: prolist = noscore[0];
1408: } else {
1409: var i = 0;
1410: while (i < ptr-1) {
1411: prolist += noscore[i]+", ";
1412: i++;
1413: }
1414: prolist += "and "+noscore[i];
1415: }
1416: var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
1417: if (resp == false) {
1418: return false;
1419: }
1420: }
1421:
1422: formname.submit();
1423: }
1424: </script>
1425: SUBJAVASCRIPT
1426: }
1427:
1428: #--- javascript for essay type problem --
1429: sub sub_page_kw_js {
1430: my $request = shift;
1431: my $iconpath = $request->dir_config('lonIconsURL');
1432: &commonJSfunctions($request);
1433:
1434: my $inner_js_msg_central=<<INNERJS;
1435: <script text="text/javascript">
1436: function checkInput() {
1437: opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
1438: var nmsg = opener.document.SCORE.savemsgN.value;
1439: var usrctr = document.msgcenter.usrctr.value;
1440: var newval = opener.document.SCORE["newmsg"+usrctr];
1441: newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
1442:
1443: var msgchk = "";
1444: if (document.msgcenter.subchk.checked) {
1445: msgchk = "msgsub,";
1446: }
1447: var includemsg = 0;
1448: for (var i=1; i<=nmsg; i++) {
1449: var opnmsg = opener.document.SCORE["savemsg"+i];
1450: var frmmsg = document.msgcenter["msg"+i];
1451: opnmsg.value = opener.checkEntities(frmmsg.value);
1452: var showflg = opener.document.SCORE["shownOnce"+i];
1453: showflg.value = "1";
1454: var chkbox = document.msgcenter["msgn"+i];
1455: if (chkbox.checked) {
1456: msgchk += "savemsg"+i+",";
1457: includemsg = 1;
1458: }
1459: }
1460: if (document.msgcenter.newmsgchk.checked) {
1461: msgchk += "newmsg"+usrctr;
1462: includemsg = 1;
1463: }
1464: imgformname = opener.document.SCORE["mailicon"+usrctr];
1465: imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
1466: var includemsg = opener.document.SCORE["includemsg"+usrctr];
1467: includemsg.value = msgchk;
1468:
1469: self.close()
1470:
1471: }
1472: </script>
1473: INNERJS
1474:
1475: my $inner_js_highlight_central=<<INNERJS;
1476: <script type="text/javascript">
1477: function updateChoice(flag) {
1478: opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
1479: opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
1480: opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
1481: opener.document.SCORE.refresh.value = "on";
1482: if (opener.document.SCORE.keywords.value!=""){
1483: opener.document.SCORE.submit();
1484: }
1485: self.close()
1486: }
1487: </script>
1488: INNERJS
1489:
1490: my $start_page_msg_central =
1491: &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
1492: {'js_ready' => 1,
1493: 'only_body' => 1,
1494: 'bgcolor' =>'#FFFFFF',});
1495: my $end_page_msg_central =
1496: &Apache::loncommon::end_page({'js_ready' => 1});
1497:
1498:
1499: my $start_page_highlight_central =
1500: &Apache::loncommon::start_page('Highlight Central',
1501: $inner_js_highlight_central,
1502: {'js_ready' => 1,
1503: 'only_body' => 1,
1504: 'bgcolor' =>'#FFFFFF',});
1505: my $end_page_highlight_central =
1506: &Apache::loncommon::end_page({'js_ready' => 1});
1507:
1508: my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1509: $docopen=~s/^document\.//;
1510: my %lt = &Apache::lonlocal::texthash(
1511: keyw => 'Keywords list, separated by a space. Add/delete to list if desired.',
1512: plse => 'Please select a word or group of words from document and then click this link.',
1513: adds => 'Add selection to keyword list? Edit if desired.',
1514: comp => 'Compose Message for: ',
1515: incl => 'Include',
1516: type => 'Type',
1517: subj => 'Subject',
1518: mesa => 'Message',
1519: new => 'New',
1520: save => 'Save',
1521: canc => 'Cancel',
1522: kehi => 'Keyword Highlight Options',
1523: txtc => 'Text Color',
1524: font => 'Font Size',
1525: fnst => 'Font Style',
1526: col1 => 'red',
1527: col2 => 'green',
1528: col3 => 'blue',
1529: siz1 => 'normal',
1530: siz2 => '+1',
1531: siz3 => '+2',
1532: sty1 => 'normal',
1533: sty2 => 'italic',
1534: sty3 => 'bold',
1535: );
1536: $request->print(<<SUBJAVASCRIPT);
1537: <script type="text/javascript" language="javascript">
1538:
1539: //===================== Show list of keywords ====================
1540: function keywords(formname) {
1541: var nret = prompt("$lt{'keyw'}",formname.keywords.value);
1542: if (nret==null) return;
1543: formname.keywords.value = nret;
1544:
1545: if (formname.keywords.value != "") {
1546: formname.refresh.value = "on";
1547: formname.submit();
1548: }
1549: return;
1550: }
1551:
1552: //===================== Script to view submitted by ==================
1553: function viewSubmitter(submitter) {
1554: document.SCORE.refresh.value = "on";
1555: document.SCORE.NCT.value = "1";
1556: document.SCORE.unamedom0.value = submitter;
1557: document.SCORE.submit();
1558: return;
1559: }
1560:
1561: //===================== Script to add keyword(s) ==================
1562: function getSel() {
1563: if (document.getSelection) txt = document.getSelection();
1564: else if (document.selection) txt = document.selection.createRange().text;
1565: else return;
1566: var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
1567: if (cleantxt=="") {
1568: alert("$lt{'plse'}");
1569: return;
1570: }
1571: var nret = prompt("$lt{'adds'}",cleantxt);
1572: if (nret==null) return;
1573: document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1574: if (document.SCORE.keywords.value != "") {
1575: document.SCORE.refresh.value = "on";
1576: document.SCORE.submit();
1577: }
1578: return;
1579: }
1580:
1581: //====================== Script for composing message ==============
1582: // preload images
1583: img1 = new Image();
1584: img1.src = "$iconpath/mailbkgrd.gif";
1585: img2 = new Image();
1586: img2.src = "$iconpath/mailto.gif";
1587:
1588: function msgCenter(msgform,usrctr,fullname) {
1589: var Nmsg = msgform.savemsgN.value;
1590: savedMsgHeader(Nmsg,usrctr,fullname);
1591: var subject = msgform.msgsub.value;
1592: var msgchk = document.SCORE["includemsg"+usrctr].value;
1593: re = /msgsub/;
1594: var shwsel = "";
1595: if (re.test(msgchk)) { shwsel = "checked" }
1596: subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
1597: displaySubject(checkEntities(subject),shwsel);
1598: for (var i=1; i<=Nmsg; i++) {
1599: var testmsg = "savemsg"+i+",";
1600: re = new RegExp(testmsg,"g");
1601: shwsel = "";
1602: if (re.test(msgchk)) { shwsel = "checked" }
1603: var message = document.SCORE["savemsg"+i].value;
1604: message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1605: displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
1606: //any < is already converted to <, etc. However, only once!!
1607: }
1608: newmsg = document.SCORE["newmsg"+usrctr].value;
1609: shwsel = "";
1610: re = /newmsg/;
1611: if (re.test(msgchk)) { shwsel = "checked" }
1612: newMsg(newmsg,shwsel);
1613: msgTail();
1614: return;
1615: }
1616:
1617: function checkEntities(strx) {
1618: if (strx.length == 0) return strx;
1619: var orgStr = ["&", "<", ">", '"'];
1620: var newStr = ["&", "<", ">", """];
1621: var counter = 0;
1622: while (counter < 4) {
1623: strx = strReplace(strx,orgStr[counter],newStr[counter]);
1624: counter++;
1625: }
1626: return strx;
1627: }
1628:
1629: function strReplace(strx, orgStr, newStr) {
1630: return strx.split(orgStr).join(newStr);
1631: }
1632:
1633: function savedMsgHeader(Nmsg,usrctr,fullname) {
1634: var height = 70*Nmsg+250;
1635: if (height > 600) {
1636: height = 600;
1637: }
1638: var xpos = (screen.width-600)/2;
1639: xpos = (xpos < 0) ? '0' : xpos;
1640: var ypos = (screen.height-height)/2-30;
1641: ypos = (ypos < 0) ? '0' : ypos;
1642:
1643: pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars=yes,screenx='+xpos+',screeny='+ypos+',width=700,height='+height);
1644: pWin.focus();
1645: pDoc = pWin.document;
1646: pDoc.$docopen;
1647: pDoc.write('$start_page_msg_central');
1648:
1649: pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
1650: pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1651: pDoc.write("<h3><span class=\\"LC_info\\"> $lt{'comp'}\"+fullname+\"<\\/span><\\/h3><br /><br />");
1652:
1653: pDoc.write('<table border="0" width="100%"><tr><td bgcolor="#777777">');
1654: pDoc.write('<table border="0" width="100%"><tr bgcolor="#DDFFFF">');
1655: pDoc.write("<td><b>$lt{'type'}<\\/b><\\/td><td><b>$lt{'incl'}<\\/b><\\/td><td><b>$lt{'mesa'}<\\/td><\\/tr>");
1656: }
1657: function displaySubject(msg,shwsel) {
1658: pDoc = pWin.document;
1659: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1660: pDoc.write("<td>$lt{'subj'}<\\/td>");
1661: pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1662: pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1663: }
1664:
1665: function displaySavedMsg(ctr,msg,shwsel) {
1666: pDoc = pWin.document;
1667: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1668: pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
1669: pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1670: pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1671: }
1672:
1673: function newMsg(newmsg,shwsel) {
1674: pDoc = pWin.document;
1675: pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1676: pDoc.write("<td align=\\"center\\">$lt{'new'}<\\/td>");
1677: pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
1678: pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1679: }
1680:
1681: function msgTail() {
1682: pDoc = pWin.document;
1683: pDoc.write("<\\/table>");
1684: pDoc.write("<\\/td><\\/tr><\\/table> ");
1685: pDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:checkInput()\\"> ");
1686: pDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\"><br /><br />");
1687: pDoc.write("<\\/form>");
1688: pDoc.write('$end_page_msg_central');
1689: pDoc.close();
1690: }
1691:
1692: //====================== Script for keyword highlight options ==============
1693: function kwhighlight() {
1694: var kwclr = document.SCORE.kwclr.value;
1695: var kwsize = document.SCORE.kwsize.value;
1696: var kwstyle = document.SCORE.kwstyle.value;
1697: var redsel = "";
1698: var grnsel = "";
1699: var blusel = "";
1700: var txtcol1 = "$lt{'col1'}";
1701: var txtcol2 = "$lt{'col2'}";
1702: var txtcol3 = "$lt{'col3'}";
1703: var txtsiz1 = "$lt{'siz1'}";
1704: var txtsiz2 = "$lt{'siz2'}";
1705: var txtsiz3 = "$lt{'siz3'}";
1706: var txtsty1 = "$lt{'sty1'}";
1707: var txtsty2 = "$lt{'sty2'}";
1708: var txtsty3 = "$lt{'sty3'}";
1709: if (kwclr=="red") {var redsel="checked='checked'"};
1710: if (kwclr=="green") {var grnsel="checked='checked'"};
1711: if (kwclr=="blue") {var blusel="checked='checked'"};
1712: var sznsel = "";
1713: var sz1sel = "";
1714: var sz2sel = "";
1715: if (kwsize=="0") {var sznsel="checked='checked'"};
1716: if (kwsize=="+1") {var sz1sel="checked='checked'"};
1717: if (kwsize=="+2") {var sz2sel="checked='checked'"};
1718: var synsel = "";
1719: var syisel = "";
1720: var sybsel = "";
1721: if (kwstyle=="") {var synsel="checked='checked'"};
1722: if (kwstyle=="<i>") {var syisel="checked='checked'"};
1723: if (kwstyle=="<b>") {var sybsel="checked='checked'"};
1724: highlightCentral();
1725: highlightbody('red',txtcol1,redsel,'0',txtsiz1,sznsel,'',txtsty1,synsel);
1726: highlightbody('green',txtcol2,grnsel,'+1',txtsiz2,sz1sel,'<i>',txtsty2,syisel);
1727: highlightbody('blue',txtcol3,blusel,'+2',txtsiz3,sz2sel,'<b>',txtsty3,sybsel);
1728: highlightend();
1729: return;
1730: }
1731:
1732: function highlightCentral() {
1733: // if (window.hwdWin) window.hwdWin.close();
1734: var xpos = (screen.width-400)/2;
1735: xpos = (xpos < 0) ? '0' : xpos;
1736: var ypos = (screen.height-330)/2-30;
1737: ypos = (ypos < 0) ? '0' : ypos;
1738:
1739: hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1740: hwdWin.focus();
1741: var hDoc = hwdWin.document;
1742: hDoc.$docopen;
1743: hDoc.write('$start_page_highlight_central');
1744: hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1745: hDoc.write("<h1>$lt{'kehi'}<\\/h1>");
1746:
1747: hDoc.write('<table border="0" width="100%"><tr style="background-color:#A1D676">');
1748: hDoc.write("<th>$lt{'txtc'}<\\/th><th>$lt{'font'}<\\/th><th>$lt{'fnst'}<\\/th><\\/tr>");
1749: }
1750:
1751: function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) {
1752: var hDoc = hwdWin.document;
1753: hDoc.write("<tr>");
1754: hDoc.write("<td align=\\"left\\">");
1755: hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+" \\/> "+clrtxt+"<\\/td>");
1756: hDoc.write("<td align=\\"left\\">");
1757: hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+" \\/> "+sztxt+"<\\/td>");
1758: hDoc.write("<td align=\\"left\\">");
1759: hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+" \\/> "+sytxt+"<\\/td>");
1760: hDoc.write("<\\/tr>");
1761: }
1762:
1763: function highlightend() {
1764: var hDoc = hwdWin.document;
1765: hDoc.write("<\\/table><br \\/>");
1766: hDoc.write("<input type=\\"button\\" value=\\"$lt{'save'}\\" onclick=\\"javascript:updateChoice(1)\\" \\/> ");
1767: hDoc.write("<input type=\\"button\\" value=\\"$lt{'canc'}\\" onclick=\\"self.close()\\" \\/><br /><br />");
1768: hDoc.write("<\\/form>");
1769: hDoc.write('$end_page_highlight_central');
1770: hDoc.close();
1771: }
1772:
1773: </script>
1774: SUBJAVASCRIPT
1775: }
1776:
1777: sub get_increment {
1778: my $increment = $env{'form.increment'};
1779: if ($increment != 1 && $increment != .5 && $increment != .25 &&
1780: $increment != .1) {
1781: $increment = 1;
1782: }
1783: return $increment;
1784: }
1785:
1786: sub gradeBox_start {
1787: return (
1788: &Apache::loncommon::start_data_table()
1789: .&Apache::loncommon::start_data_table_header_row()
1790: .'<th>'.&mt('Part').'</th>'
1791: .'<th>'.&mt('Points').'</th>'
1792: .'<th> </th>'
1793: .'<th>'.&mt('Assign Grade').'</th>'
1794: .'<th>'.&mt('Weight').'</th>'
1795: .'<th>'.&mt('Grade Status').'</th>'
1796: .&Apache::loncommon::end_data_table_header_row()
1797: );
1798: }
1799:
1800: sub gradeBox_end {
1801: return (
1802: &Apache::loncommon::end_data_table()
1803: );
1804: }
1805: #--- displays the grading box, used in essay type problem and grading by page/sequence
1806: sub gradeBox {
1807: my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1808: my $checkIcon = '<img alt="'.&mt('Check Mark').
1809: '" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1810: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1811: my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)')
1812: : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1813: $wgt = ($wgt > 0 ? $wgt : '1');
1814: my $score = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1815: '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1816: my $data_WGT='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1817: my $display_part= &get_display_part($partid,$symb);
1818: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
1819: [$partid]);
1820: my $aggtries = $$record{'resource.'.$partid.'.tries'};
1821: if ($last_resets{$partid}) {
1822: $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
1823: }
1824: my $result=&Apache::loncommon::start_data_table_row();
1825: my $ctr = 0;
1826: my $thisweight = 0;
1827: my $increment = &get_increment();
1828:
1829: my $radio.='<table border="0"><tr>'."\n"; # display radio buttons in a nice table 10 across
1830: while ($thisweight<=$wgt) {
1831: $radio.= '<td><span class="LC_nobreak"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1832: 'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1833: $thisweight.')" value="'.$thisweight.'" '.
1834: ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1835: $radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1836: $thisweight += $increment;
1837: $ctr++;
1838: }
1839: $radio.='</tr></table>';
1840:
1841: my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1842: ($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
1843: 'onchange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
1844: $wgt.')" /></td>'."\n";
1845: $line.='<td>/'.$wgt.' '.$wgtmsg.
1846: ($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? ' '.$checkIcon : '').
1847: ' </td>'."\n";
1848: $line.='<td><select name="GD_SEL'.$counter.'_'.$partid.'" '.
1849: 'onchange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
1850: if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1851: $line.='<option></option>'.
1852: '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1853: } else {
1854: $line.='<option selected="selected"></option>'.
1855: '<option value="excused" >'.&mt('excused').'</option>';
1856: }
1857: $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
1858:
1859:
1860: $result .=
1861: '<td>'.$data_WGT.$display_part.'</td><td>'.$radio.'</td><td>'.&mt('or').'</td><td>'.$line.'</td>';
1862: $result.=&Apache::loncommon::end_data_table_row().'<td colspan="6">';
1863: $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
1864: '<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
1865: '<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1866: $$record{'resource.'.$partid.'.solved'}.'" />'."\n".
1867: '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
1868: $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
1869: '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
1870: $aggtries.'" />'."\n";
1871: my $res_error;
1872: $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record,\$res_error);
1873: $result.='</td>'.&Apache::loncommon::end_data_table_row();
1874: if ($res_error) {
1875: return &navmap_errormsg();
1876: }
1877: return $result;
1878: }
1879:
1880: sub handback_box {
1881: my ($symb,$uname,$udom,$counter,$partid,$record,$res_error) = @_;
1882: my ($partlist,$handgrade,$responseType) = &response_type($symb,$res_error);
1883: my (@respids);
1884: my @part_response_id = &flatten_responseType($responseType);
1885: foreach my $part_response_id (@part_response_id) {
1886: my ($part,$resp) = @{ $part_response_id };
1887: if ($part eq $partid) {
1888: push(@respids,$resp);
1889: }
1890: }
1891: my $result;
1892: foreach my $respid (@respids) {
1893: my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
1894: my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
1895: next if (!@$files);
1896: my $file_counter = 0;
1897: foreach my $file (@$files) {
1898: if ($file =~ /\/portfolio\//) {
1899: $file_counter++;
1900: my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
1901: my ($name,$version,$ext) = &file_name_version_ext($file_disp);
1902: $file_disp = "$name.$ext";
1903: $file = $file_path.$file_disp;
1904: $result.=&mt('Return commented version of [_1] to student.',
1905: '<span class="LC_filename">'.$file_disp.'</span>');
1906: $result.='<input type="file" name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
1907: $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />'."\n";
1908: }
1909: }
1910: if ($file_counter) {
1911: $result .= '<input type="hidden" name="'.$prefix.'countreturndoc" value="'.$file_counter.'" />'."\n".
1912: '<span class="LC_info">'.
1913: '('.&mt('File(s) will be uploaded when you click on Save & Next below.',$file_counter).')</span><br /><br />';
1914: }
1915: }
1916: return $result;
1917: }
1918:
1919: sub show_problem {
1920: my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1921: my $rendered;
1922: my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1923: &Apache::lonxml::remember_problem_counter();
1924: if ($mode eq 'both' or $mode eq 'text') {
1925: $rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1926: $env{'request.course.id'},
1927: undef,\%form);
1928: }
1929: if ($removeform) {
1930: $rendered=~s|<form(.*?)>||g;
1931: $rendered=~s|</form>||g;
1932: $rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1933: }
1934: my $companswer;
1935: if ($mode eq 'both' or $mode eq 'answer') {
1936: &Apache::lonxml::restore_problem_counter();
1937: $companswer=
1938: &Apache::loncommon::get_student_answers($symb,$uname,$udom,
1939: $env{'request.course.id'},
1940: %form);
1941: }
1942: if ($removeform) {
1943: $companswer=~s|<form(.*?)>||g;
1944: $companswer=~s|</form>||g;
1945: $companswer=~s|name="submit"|name="would_have_been_submit"|g;
1946: }
1947: my $renderheading = &mt('View of the problem');
1948: my $answerheading = &mt('Correct answer');
1949: if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1950: my $stu_fullname = $env{'form.fullname'};
1951: if ($stu_fullname eq '') {
1952: $stu_fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
1953: }
1954: my $forwhom = &nameUserString(undef,$stu_fullname,$uname,$udom);
1955: if ($forwhom ne '') {
1956: $renderheading = &mt('View of the problem for[_1]',$forwhom);
1957: $answerheading = &mt('Correct answer for[_1]',$forwhom);
1958: }
1959: }
1960: $rendered=
1961: '<div class="LC_Box">'
1962: .'<h3 class="LC_hcell">'.$renderheading.'</h3>'
1963: .$rendered
1964: .'</div>';
1965: $companswer=
1966: '<div class="LC_Box">'
1967: .'<h3 class="LC_hcell">'.$answerheading.'</h3>'
1968: .$companswer
1969: .'</div>';
1970: my $result;
1971: if ($mode eq 'both') {
1972: $result=$rendered.$companswer;
1973: } elsif ($mode eq 'text') {
1974: $result=$rendered;
1975: } elsif ($mode eq 'answer') {
1976: $result=$companswer;
1977: }
1978: return $result;
1979: }
1980:
1981: sub files_exist {
1982: my ($r, $symb) = @_;
1983: my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1984:
1985: foreach my $student (@students) {
1986: my ($uname,$udom,$fullname) = split(/:/,$student);
1987: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
1988: $udom,$uname);
1989: my ($string,$timestamp)= &get_last_submission(\%record);
1990: foreach my $submission (@$string) {
1991: my ($partid,$respid) =
1992: ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1993: my $files=&get_submitted_files($udom,$uname,$partid,$respid,
1994: \%record);
1995: return 1 if (@$files);
1996: }
1997: }
1998: return 0;
1999: }
2000:
2001: sub download_all_link {
2002: my ($r,$symb) = @_;
2003: my $all_students =
2004: join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
2005:
2006: my $parts =
2007: join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
2008:
2009: my $identifier = &Apache::loncommon::get_cgi_id();
2010: &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
2011: 'cgi.'.$identifier.'.symb' => $symb,
2012: 'cgi.'.$identifier.'.parts' => $parts,});
2013: $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
2014: &mt('Download All Submitted Documents').'</a>');
2015: return
2016: }
2017:
2018: sub build_section_inputs {
2019: my $section_inputs;
2020: if ($env{'form.section'} eq '') {
2021: $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
2022: } else {
2023: my @sections = &Apache::loncommon::get_env_multiple('form.section');
2024: foreach my $section (@sections) {
2025: $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
2026: }
2027: }
2028: return $section_inputs;
2029: }
2030:
2031: # --------------------------- show submissions of a student, option to grade
2032: sub submission {
2033: my ($request,$counter,$total) = @_;
2034: my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
2035: $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
2036: my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
2037: $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
2038: my ($symb) = &get_symb($request);
2039: if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
2040:
2041: if (!&canview($usec)) {
2042: $request->print(
2043: '<span class="LC_warning">'.
2044: &mt('Unable to view requested student.').
2045: ' '.&mt('([_1] in section [_2] in course id [_3])',
2046: $uname.':'.$udom,$usec,$env{'request.course.id'}).
2047: '</span>');
2048: $request->print(&show_grading_menu_form($symb));
2049: return;
2050: }
2051:
2052: if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
2053: if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
2054: if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
2055: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
2056: my $checkIcon = '<img alt="'.&mt('Check Mark').
2057: '" src="'.$request->dir_config('lonIconsURL').
2058: '/check.gif" height="16" border="0" />';
2059:
2060: # header info
2061: if ($counter == 0) {
2062: &sub_page_js($request);
2063: &sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
2064: $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ?
2065: &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
2066: if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
2067: &download_all_link($request, $symb);
2068: }
2069: $request->print('<h3> <span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
2070: '<h4> '.&mt('[_1]Resource: [_2]','<b>','</b>'.$env{'form.probTitle'}).'</h4>'."\n");
2071:
2072: # option to display problem, only once else it cause problems
2073: # with the form later since the problem has a form.
2074: if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
2075: my $mode;
2076: if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
2077: $mode='both';
2078: } elsif ($env{'form.vProb'} eq 'yes') {
2079: $mode='text';
2080: } elsif ($env{'form.vAns'} eq 'yes') {
2081: $mode='answer';
2082: }
2083: &Apache::lonxml::clear_problem_counter();
2084: $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
2085: }
2086:
2087: # kwclr is the only variable that is guaranteed not to be blank
2088: # if this subroutine has been called once.
2089: my %keyhash = ();
2090: if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
2091: %keyhash = &Apache::lonnet::dump('nohist_handgrade',
2092: $env{'course.'.$env{'request.course.id'}.'.domain'},
2093: $env{'course.'.$env{'request.course.id'}.'.num'});
2094:
2095: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
2096: $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
2097: $env{'form.kwclr'} = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
2098: $env{'form.kwsize'} = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
2099: $env{'form.kwstyle'} = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
2100: $env{'form.msgsub'} = $keyhash{$symb.'_subject'} ne '' ?
2101: $keyhash{$symb.'_subject'} : $env{'form.probTitle'};
2102: $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
2103: }
2104: my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
2105: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
2106: $request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
2107: '<input type="hidden" name="command" value="handgrade" />'."\n".
2108: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
2109: '<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
2110: '<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
2111: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
2112: '<input type="hidden" name="refresh" value="off" />'."\n".
2113: '<input type="hidden" name="studentNo" value="" />'."\n".
2114: '<input type="hidden" name="gradeOpt" value="" />'."\n".
2115: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
2116: '<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
2117: '<input type="hidden" name="vProb" value="'.$env{'form.vProb'}.'" />'."\n".
2118: '<input type="hidden" name="vAns" value="'.$env{'form.vAns'}.'" />'."\n".
2119: '<input type="hidden" name="lastSub" value="'.$env{'form.lastSub'}.'" />'."\n".
2120: &build_section_inputs().
2121: '<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
2122: '<input type="hidden" name="handgrade" value="'.$env{'form.handgrade'}.'" />'."\n".
2123: '<input type="hidden" name="NCT"'.
2124: ' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
2125: if ($env{'form.handgrade'} eq 'yes') {
2126: $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
2127: '<input type="hidden" name="kwclr" value="'.$env{'form.kwclr'}.'" />'."\n".
2128: '<input type="hidden" name="kwsize" value="'.$env{'form.kwsize'}.'" />'."\n".
2129: '<input type="hidden" name="kwstyle" value="'.$env{'form.kwstyle'}.'" />'."\n".
2130: '<input type="hidden" name="msgsub" value="'.$env{'form.msgsub'}.'" />'."\n".
2131: '<input type="hidden" name="shownSub" value="0" />'."\n".
2132: '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
2133: foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
2134: $request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
2135: }
2136: }
2137:
2138: my ($cts,$prnmsg) = (1,'');
2139: while ($cts <= $env{'form.savemsgN'}) {
2140: $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
2141: (!exists($keyhash{$symb.'_savemsg'.$cts}) ?
2142: &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
2143: &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
2144: '" />'."\n".
2145: '<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
2146: $cts++;
2147: }
2148: $request->print($prnmsg);
2149:
2150: if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
2151:
2152: my %lt = &Apache::lonlocal::texthash(
2153: keyh => 'Keyword Highlighting for Essays',
2154: keyw => 'Keyword Options',
2155: list => 'List',
2156: past => 'Paste Selection to List',
2157: high => 'Highlight Attribute',
2158: );
2159: #
2160: # Print out the keyword options line
2161: #
2162: $request->print(
2163: '<div class="LC_columnSection">'
2164: .'<fieldset><legend>'.$lt{'keyh'}.'</legend>'
2165: .&Apache::lonhtmlcommon::funclist_from_array(
2166: ['<a href="javascript:keywords(document.SCORE);" target="_self">'.$lt{'list'}.'</a>',
2167: '<a href="#" onmousedown="javascript:getSel(); return false"
2168: class="page">'.$lt{'past'}.'</a>',
2169: '<a href="javascript:kwhighlight();" target="_self">'.$lt{'high'}.'</a>'],
2170: {legend => $lt{'keyw'}})
2171: .'</fieldset></div>'
2172: );
2173:
2174: #
2175: # Load the other essays for similarity check
2176: #
2177: my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
2178: my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
2179: $apath=&escape($apath);
2180: $apath=~s/\W/\_/gs;
2181: &init_old_essays($symb,$apath,$adom,$aname);
2182: }
2183: }
2184:
2185: # This is where output for one specific student would start
2186: my $add_class = ($counter%2) ? ' LC_grade_show_user_odd_row' : '';
2187: $request->print(
2188: "\n\n"
2189: .'<div class="LC_grade_show_user'.$add_class.'">'
2190: .'<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</h2>'
2191: ."\n"
2192: );
2193:
2194: # Show additional functions if allowed
2195: if ($perm{'vgr'}) {
2196: $request->print(
2197: &Apache::loncommon::track_student_link(
2198: 'View recent activity',
2199: $uname,$udom,'check')
2200: .' '
2201: );
2202: }
2203: if ($perm{'opa'}) {
2204: $request->print(
2205: &Apache::loncommon::pprmlink(
2206: &mt('Set/Change parameters'),
2207: $uname,$udom,$symb,'check'));
2208: }
2209:
2210: # Show Problem
2211: if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
2212: my $mode;
2213: if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
2214: $mode='both';
2215: } elsif ($env{'form.vProb'} eq 'all' ) {
2216: $mode='text';
2217: } elsif ($env{'form.vAns'} eq 'all') {
2218: $mode='answer';
2219: }
2220: &Apache::lonxml::clear_problem_counter();
2221: $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
2222: }
2223:
2224: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
2225: my $res_error;
2226: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
2227: if ($res_error) {
2228: $request->print(&navmap_errormsg());
2229: return;
2230: }
2231:
2232: # Display student info
2233: $request->print(($counter == 0 ? '' : '<br />'));
2234:
2235: my $result='<div class="LC_Box">'
2236: .'<h3 class="LC_hcell">'.&mt('Submissions').'</h3>';
2237: $result.='<input type="hidden" name="name'.$counter.
2238: '" value="'.$env{'form.fullname'}.'" />'."\n";
2239: if ($env{'form.handgrade'} eq 'no') {
2240: $result.='<p class="LC_info">'
2241: .&mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)
2242: ."</p>\n";
2243: }
2244:
2245: # If any part of the problem is an essay-response (handgraded), then check for collaborators
2246: my $fullname;
2247: my $col_fullnames = [];
2248: if ($env{'form.handgrade'} eq 'yes') {
2249: (my $sub_result,$fullname,$col_fullnames)=
2250: &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
2251: $counter);
2252: $result.=$sub_result;
2253: }
2254: $request->print($result."\n");
2255:
2256: # print student answer/submission
2257: # Options are (1) Handgraded submission only
2258: # (2) Last submission, includes submission that is not handgraded
2259: # (for multi-response type part)
2260: # (3) Last submission plus the parts info
2261: # (4) The whole record for this student
2262:
2263: my ($string,$timestamp)= &get_last_submission(\%record);
2264:
2265: my $lastsubonly;
2266:
2267: if ($$timestamp eq '') {
2268: $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>';
2269: } else {
2270: $lastsubonly =
2271: '<div class="LC_grade_submissions_body">'
2272: .'<b>'.&mt('Date Submitted:').'</b> '.$$timestamp."\n";
2273:
2274: my %seenparts;
2275: my @part_response_id = &flatten_responseType($responseType);
2276: foreach my $part (@part_response_id) {
2277: next if ($env{'form.lastSub'} eq 'hdgrade'
2278: && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
2279:
2280: my ($partid,$respid) = @{ $part };
2281: my $display_part=&get_display_part($partid,$symb);
2282: if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
2283: if (exists($seenparts{$partid})) { next; }
2284: $seenparts{$partid}=1;
2285: $request->print(
2286: '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
2287: ' <b>'.&mt('Collaborative submission by: [_1]',
2288: '<a href="javascript:viewSubmitter(\''.
2289: $env{"form.$uname:$udom:$partid:submitted_by"}.
2290: '\');" target="_self">'.
2291: $$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a>').
2292: '<br />');
2293: next;
2294: }
2295: my $responsetype = $responseType->{$partid}->{$respid};
2296: if (!exists($record{"resource.$partid.$respid.submission"})) {
2297: $lastsubonly.="\n".'<div class="LC_grade_submission_part">'.
2298: '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
2299: ' <span class="LC_internal_info">'.
2300: '('.&mt('Response ID: [_1]',$respid).')'.
2301: '</span> '.
2302: '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br /><br /></div>';
2303: next;
2304: }
2305: foreach my $submission (@$string) {
2306: my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
2307: if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
2308: my ($ressub,$hide,$draft,$subval) = split(/:/,$submission,4);
2309: # Similarity check
2310: my $similar='';
2311: my ($type,$trial,$rndseed);
2312: if ($hide eq 'rand') {
2313: $type = 'randomizetry';
2314: $trial = $record{"resource.$partid.tries"};
2315: $rndseed = $record{"resource.$partid.rndseed"};
2316: }
2317: if ($env{'form.checkPlag'}) {
2318: my ($oname,$odom,$ocrsid,$oessay,$osim)=
2319: &most_similar($uname,$udom,$symb,$subval);
2320: if ($osim) {
2321: $osim=int($osim*100.0);
2322: my %old_course_desc =
2323: &Apache::lonnet::coursedescription($ocrsid,
2324: {'one_time' => 1});
2325:
2326: if ($hide eq 'anon') {
2327: $similar='<hr /><span class="LC_warning">'.&mt("Essay was found to be similar to another essay submitted for this assignment.").'<br />'.
2328: &mt('As the current submission is for an anonymous survey, no other details are available.').'</span><hr />';
2329: } else {
2330: $similar="<hr /><h3><span class=\"LC_warning\">".
2331: &mt('Essay is [_1]% similar to an essay by [_2] in course [_3] (course id [_4]:[_5])',
2332: $osim,
2333: &Apache::loncommon::plainname($oname,$odom).' ('.$oname.':'.$odom.')',
2334: $old_course_desc{'description'},
2335: $old_course_desc{'num'},
2336: $old_course_desc{'domain'}).
2337: '</span></h3><blockquote><i>'.
2338: &keywords_highlight($oessay).
2339: '</i></blockquote><hr />';
2340: }
2341: }
2342: }
2343: my $order=&get_order($partid,$respid,$symb,$uname,$udom,
2344: undef,$type,$trial,$rndseed);
2345: if ($env{'form.lastSub'} eq 'lastonly' || $env{'form.lastSub'} eq 'datesub' || $env{'form.lastSub'} =~ /^(last|all)$/ || ($env{'form.lastSub'} eq 'hdgrade' &&
2346: $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
2347: my $display_part=&get_display_part($partid,$symb);
2348: $lastsubonly.='<div class="LC_grade_submission_part">'.
2349: '<b>'.&mt('Part: [_1]',$display_part).'</b>'.
2350: ' <span class="LC_internal_info">'.
2351: '('.&mt('Response ID: [_1]',$respid).')'.
2352: '</span> ';
2353: my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
2354: if (@$files) {
2355: if ($hide eq 'anon') {
2356: $lastsubonly.='<br />'.&mt('[quant,_1,file] uploaded to this anonymous survey',scalar(@{$files}));
2357: } else {
2358: $lastsubonly.='<br /><br />'.'<b>'.&mt('Submitted Files:').'</b>'
2359: .'<br /><span class="LC_warning">';
2360: if(@$files == 1) {
2361: $lastsubonly .= &mt('Like all files provided by users, this file may contain viruses!');
2362: } else {
2363: $lastsubonly .= &mt('Like all files provided by users, these files may contain viruses!');
2364: }
2365: $lastsubonly .= '</span>';
2366:
2367: foreach my $file (@$files) {
2368: &Apache::lonnet::allowuploaded('/adm/grades',$file);
2369: $lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0" alt="" /> '.$file.'</a>';
2370: }
2371: }
2372: $lastsubonly.='<br />';
2373: }
2374: if ($hide eq 'anon') {
2375: $lastsubonly.='<br /><b>'.&mt('Anonymous Survey').'</b>';
2376: } else {
2377: $lastsubonly.='<br /><b>'.&mt('Submitted Answer:').' </b>';
2378: if ($draft) {
2379: $lastsubonly.= ' <span class="LC_warning">'.&mt('Draft Copy').'</span>';
2380: }
2381: $subval =
2382: &cleanRecord($subval,$responsetype,$symb,$partid,
2383: $respid,\%record,$order,undef,$uname,$udom,$type,$trial,$rndseed);
2384: if ($responsetype eq 'essay') {
2385: $subval =~ s{\n}{<br />}g;
2386: }
2387: $lastsubonly.=$subval."\n";
2388: }
2389: if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
2390: $lastsubonly.='</div>';
2391: }
2392: }
2393: }
2394: $lastsubonly.='</div>'."\n"; # End: LC_grade_submissions_body
2395: }
2396: $request->print($lastsubonly);
2397: if ($env{'form.lastSub'} eq 'datesub') {
2398: my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
2399: $request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
2400: }
2401: if ($env{'form.lastSub'} =~ /^(last|all)$/) {
2402: my $identifier = (&canmodify($usec)? $counter : '');
2403: $request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
2404: $env{'request.course.id'},
2405: $last,'.submission',
2406: 'Apache::grades::keywords_highlight',
2407: $usec,$identifier));
2408: }
2409:
2410: $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
2411: .$udom.'" />'."\n");
2412: # return if view submission with no grading option
2413: if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
2414: my $toGrade.='<input type="button" value="Grade Student" '.
2415: 'onclick="javascript:checksubmit(this.form,\'Grade Student\',\''
2416: .$counter.'\');" target="_self" /> '."\n" if (&canmodify($usec));
2417: $toGrade.='</div>'."\n";
2418: if (($env{'form.command'} eq 'submission') ||
2419: ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
2420: $toGrade.='</form>'.&show_grading_menu_form($symb);
2421: }
2422: $request->print($toGrade);
2423: return;
2424: } else {
2425: $request->print('</div>'."\n");
2426: }
2427:
2428: # essay grading message center
2429: if ($env{'form.handgrade'} eq 'yes') {
2430: my $result='<div class="LC_grade_message_center">';
2431:
2432: $result.='<div class="LC_grade_message_center_header">'.
2433: &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
2434: my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
2435: my $msgfor = $givenn.' '.$lastname;
2436: if (scalar(@$col_fullnames) > 0) {
2437: my $lastone = pop(@$col_fullnames);
2438: $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
2439: }
2440: $msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
2441: $result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
2442: '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
2443: $result.=' <a href="javascript:msgCenter(document.SCORE,'.$counter.
2444: ',\''.$msgfor.'\');" target="_self">'.
2445: &mt('Compose message to student'.(scalar(@$col_fullnames) >= 1 ? 's' : '')).'</a><label> ('.
2446: &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
2447: ' <img src="'.$request->dir_config('lonIconsURL').
2448: '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
2449: '<br /> ('.
2450: &mt('Message will be sent when you click on Save & Next below.').")\n";
2451: $result.='</div></div>';
2452: $request->print($result);
2453: }
2454:
2455: my %seen = ();
2456: my @partlist;
2457: my @gradePartRespid;
2458: my @part_response_id = &flatten_responseType($responseType);
2459: $request->print(
2460: '<div class="LC_Box">'
2461: .'<h3 class="LC_hcell">'.&mt('Assign Grades').'</h3>'
2462: );
2463: $request->print(&gradeBox_start());
2464: foreach my $part_response_id (@part_response_id) {
2465: my ($partid,$respid) = @{ $part_response_id };
2466: my $part_resp = join('_',@{ $part_response_id });
2467: next if ($seen{$partid} > 0);
2468: $seen{$partid}++;
2469: next if ($$handgrade{$part_resp} ne 'yes'
2470: && $env{'form.lastSub'} eq 'hdgrade');
2471: push(@partlist,$partid);
2472: push(@gradePartRespid,$partid.'.'.$respid);
2473: $request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
2474: }
2475: $request->print(&gradeBox_end()); # </div>
2476: $request->print('</div>');
2477:
2478: $request->print('<div class="LC_grade_info_links">');
2479: $request->print('</div>');
2480:
2481: $result='<input type="hidden" name="partlist'.$counter.
2482: '" value="'.(join ":",@partlist).'" />'."\n";
2483: $result.='<input type="hidden" name="gradePartRespid'.
2484: '" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
2485: my $ctr = 0;
2486: while ($ctr < scalar(@partlist)) {
2487: $result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
2488: $partlist[$ctr].'" />'."\n";
2489: $ctr++;
2490: }
2491: $request->print($result.''."\n");
2492:
2493: # Done with printing info for one student
2494:
2495: $request->print('</div>');#LC_grade_show_user
2496:
2497:
2498: # print end of form
2499: if ($counter == $total) {
2500: my $endform='<br /><hr /><table border="0"><tr><td>'."\n";
2501: $endform.='<input type="button" value="'.&mt('Save & Next').'" '.
2502: 'onclick="javascript:checksubmit(this.form,\'Save & Next\','.
2503: $total.','.scalar(@partlist).');" target="_self" /> '."\n";
2504: my $ntstu ='<select name="NTSTU">'.
2505: '<option>1</option><option>2</option>'.
2506: '<option>3</option><option>5</option>'.
2507: '<option>7</option><option>10</option></select>'."\n";
2508: my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
2509: $ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
2510: $endform.=&mt('[_1]student(s)',$ntstu);
2511: $endform.=' <input type="button" value="'.&mt('Previous').'" '.
2512: 'onclick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> '."\n".
2513: '<input type="button" value="'.&mt('Next').'" '.
2514: 'onclick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> ';
2515: $endform.='<span class="LC_warning">'.
2516: &mt('(Next and Previous (student) do not save the scores.)').
2517: '</span>'."\n" ;
2518: $endform.="<input type='hidden' value='".&get_increment().
2519: "' name='increment' />";
2520: $endform.='</td></tr></table></form>';
2521: $endform.=&show_grading_menu_form($symb);
2522: $request->print($endform);
2523: }
2524: return '';
2525: }
2526:
2527: sub check_collaborators {
2528: my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
2529: my ($result,@col_fullnames);
2530: my ($classlist,undef,$fullname) = &getclasslist('all','0');
2531: foreach my $part (keys(%$handgrade)) {
2532: my $ncol = &Apache::lonnet::EXT('resource.'.$part.
2533: '.maxcollaborators',
2534: $symb,$udom,$uname);
2535: next if ($ncol <= 0);
2536: $part =~ s/\_/\./g;
2537: next if ($record->{'resource.'.$part.'.collaborators'} eq '');
2538: my (@good_collaborators, @bad_collaborators);
2539: foreach my $possible_collaborator
2540: (split(/[,;\s]+/,$record->{'resource.'.$part.'.collaborators'})) {
2541: $possible_collaborator =~ s/[\$\^\(\)]//g;
2542: next if ($possible_collaborator eq '');
2543: my ($co_name,$co_dom) = split(/:/,$possible_collaborator);
2544: $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
2545: next if ($co_name eq $uname && $co_dom eq $udom);
2546: # Doing this grep allows 'fuzzy' specification
2547: my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i,
2548: keys(%$classlist));
2549: if (! scalar(@matches)) {
2550: push(@bad_collaborators, $possible_collaborator);
2551: } else {
2552: push(@good_collaborators, @matches);
2553: }
2554: }
2555: if (scalar(@good_collaborators) != 0) {
2556: $result.='<br />'.&mt('Collaborators:').'<ol>';
2557: foreach my $name (@good_collaborators) {
2558: my ($lastname,$givenn) = split(/,/,$$fullname{$name});
2559: push(@col_fullnames, $givenn.' '.$lastname);
2560: $result.='<li>'.$fullname->{$name}.'</li>';
2561: }
2562: $result.='</ol><br />'."\n";
2563: my ($part)=split(/\./,$part);
2564: $result.='<input type="hidden" name="collaborator'.$counter.
2565: '" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
2566: "\n";
2567: }
2568: if (scalar(@bad_collaborators) > 0) {
2569: $result.='<div class="LC_warning">';
2570: $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
2571: $result .= '</div>';
2572: }
2573: if (scalar(@bad_collaborators > $ncol)) {
2574: $result .= '<div class="LC_warning">';
2575: $result .= &mt('This student has submitted too many '.
2576: 'collaborators. Maximum is [_1].',$ncol);
2577: $result .= '</div>';
2578: }
2579: }
2580: return ($result,$fullname,\@col_fullnames);
2581: }
2582:
2583: #--- Retrieve the last submission for all the parts
2584: sub get_last_submission {
2585: my ($returnhash)=@_;
2586: my (@string,$timestamp,%lasthidden);
2587: if ($$returnhash{'version'}) {
2588: my %lasthash=();
2589: my ($version);
2590: for ($version=1;$version<=$$returnhash{'version'};$version++) {
2591: foreach my $key (sort(split(/\:/,
2592: $$returnhash{$version.':keys'}))) {
2593: $lasthash{$key}=$$returnhash{$version.':'.$key};
2594: $timestamp =
2595: &Apache::lonlocal::locallocaltime($$returnhash{$version.':timestamp'});
2596: }
2597: }
2598: my (%typeparts,%randombytry);
2599: my $showsurv =
2600: &Apache::lonnet::allowed('vas',$env{'request.course.id'});
2601: foreach my $key (sort(keys(%lasthash))) {
2602: if ($key =~ /\.type$/) {
2603: if (($lasthash{$key} eq 'anonsurvey') ||
2604: ($lasthash{$key} eq 'anonsurveycred') ||
2605: ($lasthash{$key} eq 'randomizetry')) {
2606: my ($ign,@parts) = split(/\./,$key);
2607: pop(@parts);
2608: my $id = join('.',@parts);
2609: if ($lasthash{$key} eq 'randomizetry') {
2610: $randombytry{$ign.'.'.$id} = $lasthash{$key};
2611: } else {
2612: unless ($showsurv) {
2613: $typeparts{$ign.'.'.$id} = $lasthash{$key};
2614: }
2615: }
2616: delete($lasthash{$key});
2617: }
2618: }
2619: }
2620: my @hidden = keys(%typeparts);
2621: my @randomize = keys(%randombytry);
2622: foreach my $key (keys(%lasthash)) {
2623: next if ($key !~ /\.submission$/);
2624: my $hide;
2625: if (@hidden) {
2626: foreach my $id (@hidden) {
2627: if ($key =~ /^\Q$id\E/) {
2628: $hide = 'anon';
2629: last;
2630: }
2631: }
2632: }
2633: unless ($hide) {
2634: if (@randomize) {
2635: foreach my $id (@randomize) {
2636: if ($key =~ /^\Q$id\E/) {
2637: $hide = 'rand';
2638: last;
2639: }
2640: }
2641: }
2642: }
2643: my ($partid,$foo) = split(/submission$/,$key);
2644: my $draft = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ? 1: 0;
2645: push(@string, join(':', $key, $hide, $draft, (
2646: ref($lasthash{$key}) eq 'ARRAY' ?
2647: join(',', @{$lasthash{$key}}) : $lasthash{$key}) ));
2648: }
2649: }
2650: if (!@string) {
2651: $string[0] =
2652: '<span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span>';
2653: }
2654: return (\@string,\$timestamp);
2655: }
2656:
2657: #--- High light keywords, with style choosen by user.
2658: sub keywords_highlight {
2659: my $string = shift;
2660: my $size = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
2661: my $styleon = $env{'form.kwstyle'} eq '' ? '' : $env{'form.kwstyle'};
2662: (my $styleoff = $styleon) =~ s/\</\<\//;
2663: my @keylist = split(/[,\s+]/,$env{'form.keywords'});
2664: foreach my $keyword (@keylist) {
2665: $string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
2666: }
2667: return $string;
2668: }
2669:
2670: # For Tasks provide a mechanism to display previous version for one specific student
2671:
2672: sub show_previous_task_version {
2673: my ($request,$symb) = @_;
2674: if ($symb eq '') {
2675: $request->print(
2676: '<span class="LC_error">'.
2677: &mt('Unable to handle ambiguous references.').
2678: '</span>');
2679: return '';
2680: }
2681: my ($uname,$udom) = ($env{'form.student'},$env{'form.userdom'});
2682: my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
2683: if (!&canview($usec)) {
2684: $request->print('<span class="LC_warning">'.
2685: &mt('Unable to view previous version for requested student.').
2686: ' '.&mt('([_1] in section [_2] in course id [_3])',
2687: $uname.':'.$udom,$usec,$env{'request.course.id'}).
2688: '</span>');
2689: return;
2690: }
2691: my $mode = 'both';
2692: my $isTask = ($symb =~/\.task$/);
2693: if ($isTask) {
2694: if ($env{'form.previousversion'} =~ /^\d+$/) {
2695: if ($env{'form.fullname'} eq '') {
2696: $env{'form.fullname'} =
2697: &Apache::loncommon::plainname($uname,$udom,'lastname');
2698: }
2699: my $probtitle=&Apache::lonnet::gettitle($symb);
2700: $request->print("\n\n".
2701: '<div class="LC_grade_show_user">'.
2702: '<h2>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
2703: '</h2>'."\n");
2704: &Apache::lonxml::clear_problem_counter();
2705: $request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,
2706: {'previousversion' => $env{'form.previousversion'} }));
2707: $request->print("\n</div>");
2708: }
2709: }
2710: return;
2711: }
2712:
2713: sub choose_task_version_form {
2714: my ($symb,$uname,$udom,$nomenu) = @_;
2715: my $isTask = ($symb =~/\.task$/);
2716: my ($current,$version,$result,$js,$displayed,$rowtitle);
2717: if ($isTask) {
2718: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
2719: $udom,$uname);
2720: if (($record{'resource.0.version'} eq '') ||
2721: ($record{'resource.0.version'} < 2)) {
2722: return ($record{'resource.0.version'},
2723: $record{'resource.0.version'},$result,$js);
2724: } else {
2725: $current = $record{'resource.0.version'};
2726: }
2727: if ($env{'form.previousversion'}) {
2728: $displayed = $env{'form.previousversion'};
2729: $rowtitle = &mt('Choose another version:')
2730: } else {
2731: $displayed = $current;
2732: $rowtitle = &mt('Show earlier version:');
2733: }
2734: $result = '<div class="LC_left_float">';
2735: my $list;
2736: my $numversions = 0;
2737: for (my $i=1; $i<=$record{'resource.0.version'}; $i++) {
2738: if ($i == $current) {
2739: if (!$env{'form.previousversion'} || $nomenu) {
2740: next;
2741: } else {
2742: $list .= '<option value="'.$i.'">'.&mt('Current').'</option>'."\n";
2743: $numversions ++;
2744: }
2745: } elsif (defined($record{'resource.'.$i.'.0.status'})) {
2746: unless ($i == $env{'form.previousversion'}) {
2747: $numversions ++;
2748: }
2749: $list .= '<option value="'.$i.'">'.$i.'</option>'."\n";
2750: }
2751: }
2752: if ($numversions) {
2753: $symb = &HTML::Entities::encode($symb,'<>"&');
2754: $result .=
2755: '<form name="getprev" method="post" action=""'.
2756: ' onsubmit="return previousVersion('."'$uname','$udom','$symb','$displayed'".');">'.
2757: &Apache::loncommon::start_data_table().
2758: &Apache::loncommon::start_data_table_row().
2759: '<th align="left">'.$rowtitle.'</th>'.
2760: '<td><select name="version">'.
2761: '<option>'.&mt('Select').'</option>'.
2762: $list.
2763: '</select></td>'.
2764: &Apache::loncommon::end_data_table_row();
2765: unless ($nomenu) {
2766: $result .= &Apache::loncommon::start_data_table_row().
2767: '<th align="left">'.&mt('Open in new window').'</th>'.
2768: '<td><span class="LC_nobreak">'.
2769: '<label><input type="radio" name="prevwin" value="1" />'.
2770: &mt('Yes').'</label>'.
2771: '<label><input type="radio" name="prevwin" value="0" checked="checked" />'.&mt('No').'</label>'.
2772: '</span></td>'.
2773: &Apache::loncommon::end_data_table_row();
2774: }
2775: $result .=
2776: &Apache::loncommon::start_data_table_row().
2777: '<th align="left"> </th>'.
2778: '<td>'.
2779: '<input type="submit" name="prevsub" value="'.&mt('Display').'" />'.
2780: '</td>'.
2781: &Apache::loncommon::end_data_table_row().
2782: &Apache::loncommon::end_data_table().
2783: '</form>';
2784: $js = &previous_display_javascript($nomenu,$current);
2785: } elsif ($displayed && $nomenu) {
2786: $result .= '<a href="javascript:window.close()">'.&mt('Close window').'</a>';
2787: } else {
2788: $result .= &mt('No previous versions to show for this student');
2789: }
2790: $result .= '</div>';
2791: }
2792: return ($current,$displayed,$result,$js);
2793: }
2794:
2795: sub previous_display_javascript {
2796: my ($nomenu,$current) = @_;
2797: my $js = <<"JSONE";
2798: <script type="text/javascript">
2799: // <![CDATA[
2800: function previousVersion(uname,udom,symb) {
2801: var current = '$current';
2802: var version = document.getprev.version.options[document.getprev.version.selectedIndex].value;
2803: var prevstr = new RegExp("^\\\\d+\$");
2804: if (!prevstr.test(version)) {
2805: return false;
2806: }
2807: var url = '';
2808: if (version == current) {
2809: url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=submission';
2810: } else {
2811: url = '/adm/grades?student='+uname+'&userdom='+udom+'&symb='+symb+'&command=versionsub&previousversion='+version;
2812: }
2813: JSONE
2814: if ($nomenu) {
2815: $js .= <<"JSTWO";
2816: document.location.href = url;
2817: JSTWO
2818: } else {
2819: $js .= <<"JSTHREE";
2820: var newwin = 0;
2821: for (var i=0; i<document.getprev.prevwin.length; i++) {
2822: if (document.getprev.prevwin[i].checked == true) {
2823: newwin = document.getprev.prevwin[i].value;
2824: }
2825: }
2826: if (newwin == 1) {
2827: var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
2828: url = url+'&inhibitmenu=yes';
2829: if (typeof(previousWin) == 'undefined' || previousWin.closed) {
2830: previousWin = window.open(url,'',options,1);
2831: } else {
2832: previousWin.location.href = url;
2833: }
2834: previousWin.focus();
2835: return false;
2836: } else {
2837: document.location.href = url;
2838: return false;
2839: }
2840: JSTHREE
2841: }
2842: $js .= <<"ENDJS";
2843: return false;
2844: }
2845: // ]]>
2846: </script>
2847: ENDJS
2848:
2849: }
2850:
2851: #--- Called from submission routine
2852: sub processHandGrade {
2853: my ($request) = shift;
2854: my ($symb) = &get_symb($request);
2855: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
2856: my $button = $env{'form.gradeOpt'};
2857: my $ngrade = $env{'form.NCT'};
2858: my $ntstu = $env{'form.NTSTU'};
2859: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2860: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2861:
2862: if ($button eq 'Save & Next') {
2863: my $ctr = 0;
2864: while ($ctr < $ngrade) {
2865: my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
2866: my ($errorflag,$pts,$wgt,$numhidden) =
2867: &saveHandGrade($request,$symb,$uname,$udom,$ctr);
2868: if ($errorflag eq 'no_score') {
2869: $ctr++;
2870: next;
2871: }
2872: if ($errorflag eq 'not_allowed') {
2873: $request->print(
2874: '<span class="LC_error">'
2875: .&mt('Not allowed to modify grades for [_1]',"$uname:$udom")
2876: .'</span>');
2877: $ctr++;
2878: next;
2879: }
2880: if ($numhidden) {
2881: $request->print(
2882: '<span class="LC_info">'
2883: .&mt('For [_1]: [quant,_2,transaction] hidden',"$uname:$udom",$numhidden)
2884: .'</span><br />');
2885: }
2886: my $includemsg = $env{'form.includemsg'.$ctr};
2887: my ($subject,$message,$msgstatus) = ('','','');
2888: my $restitle = &Apache::lonnet::gettitle($symb);
2889: my ($feedurl,$showsymb) =
2890: &get_feedurl_and_symb($symb,$uname,$udom);
2891: my $messagetail;
2892: if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
2893: $subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
2894: unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
2895: $subject.=' ['.$restitle.']';
2896: my (@msgnum) = split(/,/,$includemsg);
2897: foreach (@msgnum) {
2898: $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
2899: }
2900: $message =&Apache::lonfeedback::clear_out_html($message);
2901: if ($env{'form.withgrades'.$ctr}) {
2902: $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
2903: $messagetail = " for <a href=\"".
2904: $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
2905: }
2906: $msgstatus =
2907: &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
2908: $message.$messagetail,
2909: undef,$feedurl,undef,
2910: undef,undef,$showsymb,
2911: $restitle);
2912: $request->print('<br />'.&mt('Sending message to [_1]',$uname.':'.$udom).': '.
2913: $msgstatus.'<br />');
2914: }
2915: if ($env{'form.collaborator'.$ctr}) {
2916: my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
2917: foreach my $collabstr (@collabstrs) {
2918: my ($part,@collaborators) = split(/:/,$collabstr);
2919: foreach my $collaborator (@collaborators) {
2920: my ($errorflag,$pts,$wgt) =
2921: &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
2922: $env{'form.unamedom'.$ctr},$part);
2923: if ($errorflag eq 'not_allowed') {
2924: $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
2925: next;
2926: } elsif ($message ne '') {
2927: my ($baseurl,$showsymb) =
2928: &get_feedurl_and_symb($symb,$collaborator,
2929: $udom);
2930: if ($env{'form.withgrades'.$ctr}) {
2931: $messagetail = " for <a href=\"".
2932: $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
2933: }
2934: $msgstatus =
2935: &Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
2936: }
2937: }
2938: }
2939: }
2940: $ctr++;
2941: }
2942: }
2943:
2944: if ($env{'form.handgrade'} eq 'yes') {
2945: # Keywords sorted in alphabatical order
2946: my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
2947: my %keyhash = ();
2948: $env{'form.keywords'} =~ s/,\s{0,}|\s+/ /g;
2949: $env{'form.keywords'} =~ s/^\s+|\s+$//;
2950: my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
2951: $env{'form.keywords'} = join(' ',@keywords);
2952: $keyhash{$symb.'_keywords'} = $env{'form.keywords'};
2953: $keyhash{$symb.'_subject'} = $env{'form.msgsub'};
2954: $keyhash{$loginuser.'_kwclr'} = $env{'form.kwclr'};
2955: $keyhash{$loginuser.'_kwsize'} = $env{'form.kwsize'};
2956: $keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
2957:
2958: # message center - Order of message gets changed. Blank line is eliminated.
2959: # New messages are saved in env for the next student.
2960: # All messages are saved in nohist_handgrade.db
2961: my ($ctr,$idx) = (1,1);
2962: while ($ctr <= $env{'form.savemsgN'}) {
2963: if ($env{'form.savemsg'.$ctr} ne '') {
2964: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
2965: $idx++;
2966: }
2967: $ctr++;
2968: }
2969: $ctr = 0;
2970: while ($ctr < $ngrade) {
2971: if ($env{'form.newmsg'.$ctr} ne '') {
2972: $keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2973: $env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
2974: $idx++;
2975: }
2976: $ctr++;
2977: }
2978: $env{'form.savemsgN'} = --$idx;
2979: $keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
2980: my $putresult = &Apache::lonnet::put
2981: ('nohist_handgrade',\%keyhash,$cdom,$cnum);
2982: }
2983: # Called by Save & Refresh from Highlight Attribute Window
2984: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
2985: if ($env{'form.refresh'} eq 'on') {
2986: my ($ctr,$total) = (0,0);
2987: while ($ctr < $ngrade) {
2988: $total++ if $env{'form.unamedom'.$ctr} ne '';
2989: $ctr++;
2990: }
2991: $env{'form.NTSTU'}=$ngrade;
2992: $ctr = 0;
2993: while ($ctr < $total) {
2994: my $processUser = $env{'form.unamedom'.$ctr};
2995: ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
2996: $env{'form.fullname'} = $$fullname{$processUser};
2997: &submission($request,$ctr,$total-1);
2998: $ctr++;
2999: }
3000: return '';
3001: }
3002:
3003: # Go directly to grade student - from submission or link from chart page
3004: if ($button eq 'Grade Student') {
3005: (undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
3006: my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
3007: ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
3008: $env{'form.fullname'} = $$fullname{$processUser};
3009: &submission($request,0,0);
3010: return '';
3011: }
3012:
3013: # Get the next/previous one or group of students
3014: my $firststu = $env{'form.unamedom0'};
3015: my $laststu = $env{'form.unamedom'.($ngrade-1)};
3016: my $ctr = 2;
3017: while ($laststu eq '') {
3018: $laststu = $env{'form.unamedom'.($ngrade-$ctr)};
3019: $ctr++;
3020: $laststu = $firststu if ($ctr > $ngrade);
3021: }
3022:
3023: my (@parsedlist,@nextlist);
3024: my ($nextflg) = 0;
3025: foreach my $item (sort
3026: {
3027: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
3028: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
3029: }
3030: return $a cmp $b;
3031: } (keys(%$fullname))) {
3032: if ($nextflg == 1 && $button =~ /Next$/) {
3033: push(@parsedlist,$item);
3034: }
3035: $nextflg = 1 if ($item eq $laststu);
3036: if ($button eq 'Previous') {
3037: last if ($item eq $firststu);
3038: push(@parsedlist,$item);
3039: }
3040: }
3041: $ctr = 0;
3042: @parsedlist = reverse @parsedlist if ($button eq 'Previous');
3043: my $res_error;
3044: my ($partlist) = &response_type($symb,\$res_error);
3045: if ($res_error) {
3046: $request->print(&navmap_errormsg());
3047: return;
3048: }
3049: foreach my $student (@parsedlist) {
3050: my $submitonly=$env{'form.submitonly'};
3051: my ($uname,$udom) = split(/:/,$student);
3052:
3053: if ($submitonly eq 'queued') {
3054: my %queue_status =
3055: &Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
3056: $udom,$uname);
3057: next if (!defined($queue_status{'gradingqueue'}));
3058: }
3059:
3060: if ($submitonly =~ /^(yes|graded|incorrect)$/) {
3061: # my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
3062: my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
3063: my $submitted = 0;
3064: my $ungraded = 0;
3065: my $incorrect = 0;
3066: foreach my $item (keys(%status)) {
3067: $submitted = 1 if ($status{$item} ne 'nothing');
3068: $ungraded = 1 if ($status{$item} =~ /^ungraded/);
3069: $incorrect = 1 if ($status{$item} =~ /^incorrect/);
3070: my ($foo,$partid,$foo1) = split(/\./,$item);
3071: if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
3072: $submitted = 0;
3073: }
3074: }
3075: next if (!$submitted && ($submitonly eq 'yes' ||
3076: $submitonly eq 'incorrect' ||
3077: $submitonly eq 'graded'));
3078: next if (!$ungraded && ($submitonly eq 'graded'));
3079: next if (!$incorrect && $submitonly eq 'incorrect');
3080: }
3081: push(@nextlist,$student) if ($ctr < $ntstu);
3082: last if ($ctr == $ntstu);
3083: $ctr++;
3084: }
3085:
3086: $ctr = 0;
3087: my $total = scalar(@nextlist)-1;
3088:
3089: foreach (sort(@nextlist)) {
3090: my ($uname,$udom,$submitter) = split(/:/);
3091: $env{'form.student'} = $uname;
3092: $env{'form.userdom'} = $udom;
3093: $env{'form.fullname'} = $$fullname{$_};
3094: &submission($request,$ctr,$total);
3095: $ctr++;
3096: }
3097: if ($total < 0) {
3098: my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
3099: $the_end.='<p>'.&mt('[_1]Message:[_2] No more students for this section or class.','<b>','</b>').'</p>'."\n";
3100: $the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
3101: $the_end.=&show_grading_menu_form($symb);
3102: $request->print($the_end);
3103: }
3104: return '';
3105: }
3106:
3107: #---- Save the score and award for each student, if changed
3108: sub saveHandGrade {
3109: my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
3110: my @version_parts;
3111: my $usec = &Apache::lonnet::getsection($domain,$stuname,
3112: $env{'request.course.id'});
3113: if (!&canmodify($usec)) { return('not_allowed'); }
3114: my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
3115: my @parts_graded;
3116: my %newrecord = ();
3117: my ($pts,$wgt,$totchg) = ('','',0);
3118: my %aggregate = ();
3119: my $aggregateflag = 0;
3120: if ($env{'form.HIDE'.$newflg}) {
3121: my ($version,$parts) = split(/:/,$env{'form.HIDE'.$newflg},2);
3122: my $numchgs = &makehidden($version,$parts,\%record,$symb,$domain,$stuname,1);
3123: $totchg += $numchgs;
3124: }
3125: my @parts = split(/:/,$env{'form.partlist'.$newflg});
3126: foreach my $new_part (@parts) {
3127: #collaborator ($submi may vary for different parts
3128: if ($submitter && $new_part ne $part) { next; }
3129: my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
3130: if ($dropMenu eq 'excused') {
3131: if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
3132: $newrecord{'resource.'.$new_part.'.solved'} = 'excused';
3133: if (exists($record{'resource.'.$new_part.'.awarded'})) {
3134: $newrecord{'resource.'.$new_part.'.awarded'} = '';
3135: }
3136: $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
3137: }
3138: } elsif ($dropMenu eq 'reset status'
3139: && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
3140: foreach my $key (keys(%record)) {
3141: if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
3142: }
3143: $newrecord{'resource.'.$new_part.'.regrader'}=
3144: "$env{'user.name'}:$env{'user.domain'}";
3145: my $totaltries = $record{'resource.'.$part.'.tries'};
3146:
3147: my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
3148: [$new_part]);
3149: my $aggtries =$totaltries;
3150: if ($last_resets{$new_part}) {
3151: $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
3152: $new_part);
3153: }
3154:
3155: my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
3156: if ($aggtries > 0) {
3157: &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
3158: $aggregateflag = 1;
3159: }
3160: } elsif ($dropMenu eq '') {
3161: $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ?
3162: $env{'form.GD_BOX'.$newflg.'_'.$new_part} :
3163: $env{'form.RADVAL'.$newflg.'_'.$new_part});
3164: if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
3165: next;
3166: }
3167: $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 :
3168: $env{'form.WGT'.$newflg.'_'.$new_part};
3169: my $partial= $pts/$wgt;
3170: if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
3171: #do not update score for part if not changed.
3172: &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
3173: next;
3174: } else {
3175: push(@parts_graded,$new_part);
3176: }
3177: if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
3178: $newrecord{'resource.'.$new_part.'.awarded'} = $partial;
3179: }
3180: my $reckey = 'resource.'.$new_part.'.solved';
3181: if ($partial == 0) {
3182: if ($record{$reckey} ne 'incorrect_by_override') {
3183: $newrecord{$reckey} = 'incorrect_by_override';
3184: }
3185: } else {
3186: if ($record{$reckey} ne 'correct_by_override') {
3187: $newrecord{$reckey} = 'correct_by_override';
3188: }
3189: }
3190: if ($submitter &&
3191: ($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
3192: $newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
3193: }
3194: $newrecord{'resource.'.$new_part.'.regrader'}=
3195: "$env{'user.name'}:$env{'user.domain'}";
3196: }
3197: # unless problem has been graded, set flag to version the submitted files
3198: unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/ ||
3199: $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
3200: $dropMenu eq 'reset status')
3201: {
3202: push(@version_parts,$new_part);
3203: }
3204: }
3205: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3206: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3207:
3208: if (%newrecord) {
3209: if (@version_parts) {
3210: my @changed_keys = &version_portfiles(\%record, \@parts_graded,
3211: $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
3212: @newrecord{@changed_keys} = @record{@changed_keys};
3213: foreach my $new_part (@version_parts) {
3214: &handback_files($request,$symb,$stuname,$domain,$newflg,
3215: $new_part,\%newrecord);
3216: }
3217: }
3218: &Apache::lonnet::cstore(\%newrecord,$symb,
3219: $env{'request.course.id'},$domain,$stuname);
3220: &check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
3221: $cdom,$cnum,$domain,$stuname);
3222: }
3223: if ($aggregateflag) {
3224: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
3225: $cdom,$cnum);
3226: }
3227: return ('',$pts,$wgt,$totchg);
3228: }
3229:
3230: sub makehidden {
3231: my ($version,$parts,$record,$symb,$domain,$stuname,$tolog) = @_;
3232: return unless (ref($record) eq 'HASH');
3233: my %modified;
3234: my $numchanged = 0;
3235: if (exists($record->{$version.':keys'})) {
3236: my $partsregexp = $parts;
3237: $partsregexp =~ s/,/|/g;
3238: foreach my $key (split(/\:/,$record->{$version.':keys'})) {
3239: if ($key =~ /^resource\.(?:$partsregexp)\.([^\.]+)$/) {
3240: my $item = $1;
3241: unless (($item eq 'solved') || ($item =~ /^award(|msg|ed)$/)) {
3242: $modified{$key} = $record->{$version.':'.$key};
3243: }
3244: } elsif ($key =~ m{^(resource\.(?:$partsregexp)\.[^\.]+\.)(.+)$}) {
3245: $modified{$1.'hidden'.$2} = $record->{$version.':'.$key};
3246: } elsif ($key =~ /^(ip|timestamp|host)$/) {
3247: $modified{$key} = $record->{$version.':'.$key};
3248: }
3249: }
3250: if (keys(%modified)) {
3251: if (&Apache::lonnet::putstore($env{'request.course.id'},$symb,$version,\%modified,
3252: $domain,$stuname,$tolog) eq 'ok') {
3253: $numchanged ++;
3254: }
3255: }
3256: }
3257: return $numchanged;
3258: }
3259:
3260: sub check_and_remove_from_queue {
3261: my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
3262: my @ungraded_parts;
3263: foreach my $part (@{$parts}) {
3264: if ( $record->{ 'resource.'.$part.'.awarded'} eq ''
3265: && $record->{ 'resource.'.$part.'.solved' } ne 'excused'
3266: && $newrecord->{'resource.'.$part.'.awarded'} eq ''
3267: && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
3268: ) {
3269: push(@ungraded_parts, $part);
3270: }
3271: }
3272: if ( !@ungraded_parts ) {
3273: &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
3274: $cnum,$domain,$stuname);
3275: }
3276: }
3277:
3278: sub handback_files {
3279: my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
3280: my $portfolio_root = '/userfiles/portfolio';
3281: my $res_error;
3282: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
3283: if ($res_error) {
3284: $request->print('<br />'.&navmap_errormsg().'<br />');
3285: return;
3286: }
3287: my @handedback;
3288: my $file_msg;
3289: my @part_response_id = &flatten_responseType($responseType);
3290: foreach my $part_response_id (@part_response_id) {
3291: my ($part_id,$resp_id) = @{ $part_response_id };
3292: my $part_resp = join('_',@{ $part_response_id });
3293: if (($env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'} =~ /^\d+$/) & ($new_part eq $part_id)) {
3294: for (my $counter=1; $counter<=$env{'form.'.$newflg.'_'.$part_resp.'_countreturndoc'}; $counter++) {
3295: # if multiple files are uploaded names will be 'returndoc2','returndoc3'
3296: if ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter}) {
3297: my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$counter.'.filename'};
3298: my ($directory,$answer_file) =
3299: ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$counter} =~ /^(.*?)([^\/]*)$/);
3300: my ($answer_name,$answer_ver,$answer_ext) =
3301: &file_name_version_ext($answer_file);
3302: my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
3303: my $getpropath = 1;
3304: my ($dir_list,$listerror) =
3305: &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,
3306: $domain,$stuname,$getpropath);
3307: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
3308: # fix filename
3309: my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
3310: my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
3311: $newflg.'_'.$part_resp.'_returndoc'.$counter,
3312: $save_file_name);
3313: if ($result !~ m|^/uploaded/|) {
3314: $request->print('<br /><span class="LC_error">'.
3315: &mt('An error occurred ([_1]) while trying to upload [_2].',
3316: $result,$newflg.'_'.$part_resp.'_returndoc'.$counter).
3317: '</span>');
3318: } else {
3319: # mark the file as read only
3320: push(@handedback,$save_file_name);
3321: if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
3322: $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
3323: }
3324: $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
3325: $file_msg.='<span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span> <br />";
3326:
3327: }
3328: $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>'));
3329: }
3330: }
3331: }
3332: }
3333: if (@handedback > 0) {
3334: $request->print('<br />');
3335: my @what = ($symb,$env{'request.course.id'},'handback');
3336: &Apache::lonnet::mark_as_readonly($domain,$stuname,\@handedback,\@what);
3337: my $user_lh = &Apache::loncommon::user_lang($stuname,$domain,$env{'request.course.id'});
3338: my ($subject,$message);
3339: if (scalar(@handedback) == 1) {
3340: $subject = &mt_user($user_lh,'File Handed Back by Instructor');
3341: } else {
3342: $subject = &mt_user($user_lh,'Files Handed Back by Instructor');
3343: $message = &mt_user($user_lh,'Files have been returned that were originally submitted in response to: ');
3344: }
3345: $message .= "<p><strong>".&Apache::lonnet::gettitle($symb)." </strong></p>";
3346: $message .= &mt_user($user_lh,'The returned file(s) are named: [_1]',"<br />$file_msg <br />").
3347: &mt_user($user_lh,'The file(s) can be found in your [_1]portfolio[_2].','<a href="/adm/portfolio">','</a>');
3348: my ($feedurl,$showsymb) =
3349: &get_feedurl_and_symb($symb,$domain,$stuname);
3350: my $restitle = &Apache::lonnet::gettitle($symb);
3351: $subject .= ' '.&mt_user($user_lh,'(File Returned)').' ['.$restitle.']';
3352: my $msgstatus =
3353: &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject,
3354: $message,undef,$feedurl,undef,undef,undef,$showsymb,
3355: $restitle);
3356: if ($msgstatus) {
3357: $request->print(&mt('Notification message status: [_1]','<span class="LC_info">'.$msgstatus.'</span>').'<br />');
3358: }
3359: }
3360: return;
3361: }
3362:
3363: sub get_feedurl_and_symb {
3364: my ($symb,$uname,$udom) = @_;
3365: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
3366: $url = &Apache::lonnet::clutter($url);
3367: my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
3368: $symb,$udom,$uname);
3369: if ($encrypturl =~ /^yes$/i) {
3370: &Apache::lonenc::encrypted(\$url,1);
3371: &Apache::lonenc::encrypted(\$symb,1);
3372: }
3373: return ($url,$symb);
3374: }
3375:
3376: sub get_submitted_files {
3377: my ($udom,$uname,$partid,$respid,$record) = @_;
3378: my @files;
3379: if ($$record{"resource.$partid.$respid.portfiles"}) {
3380: my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
3381: foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
3382: push(@files,$file_url.$file);
3383: }
3384: }
3385: if ($$record{"resource.$partid.$respid.uploadedurl"}) {
3386: push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
3387: }
3388: return (\@files);
3389: }
3390:
3391: # ----------- Provides number of tries since last reset.
3392: sub get_num_tries {
3393: my ($record,$last_reset,$part) = @_;
3394: my $timestamp = '';
3395: my $num_tries = 0;
3396: if ($$record{'version'}) {
3397: for (my $version=$$record{'version'};$version>=1;$version--) {
3398: if (exists($$record{$version.':resource.'.$part.'.solved'})) {
3399: $timestamp = $$record{$version.':timestamp'};
3400: if ($timestamp > $last_reset) {
3401: $num_tries ++;
3402: } else {
3403: last;
3404: }
3405: }
3406: }
3407: }
3408: return $num_tries;
3409: }
3410:
3411: # ----------- Determine decrements required in aggregate totals
3412: sub decrement_aggs {
3413: my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
3414: my %decrement = (
3415: attempts => 0,
3416: users => 0,
3417: correct => 0
3418: );
3419: $decrement{'attempts'} = $aggtries;
3420: if ($solvedstatus =~ /^correct/) {
3421: $decrement{'correct'} = 1;
3422: }
3423: if ($aggtries == $totaltries) {
3424: $decrement{'users'} = 1;
3425: }
3426: foreach my $type (keys(%decrement)) {
3427: $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
3428: }
3429: return;
3430: }
3431:
3432: # ----------- Determine timestamps for last reset of aggregate totals for parts
3433: sub get_last_resets {
3434: my ($symb,$courseid,$partids) =@_;
3435: my %last_resets;
3436: my $cdom = $env{'course.'.$courseid.'.domain'};
3437: my $cname = $env{'course.'.$courseid.'.num'};
3438: my @keys;
3439: foreach my $part (@{$partids}) {
3440: push(@keys,"$symb\0$part\0resettime");
3441: }
3442: my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
3443: $cdom,$cname);
3444: foreach my $part (@{$partids}) {
3445: $last_resets{$part}=$results{"$symb\0$part\0resettime"};
3446: }
3447: return %last_resets;
3448: }
3449:
3450: # ----------- Handles creating versions for portfolio files as answers
3451: sub version_portfiles {
3452: my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
3453: my $version_parts = join('|',@$v_flag);
3454: my @returned_keys;
3455: my $parts = join('|', @$parts_graded);
3456: my $portfolio_root = '/userfiles/portfolio';
3457: foreach my $key (keys(%$record)) {
3458: my $new_portfiles;
3459: if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
3460: my @versioned_portfiles;
3461: my @portfiles = split(/\s*,\s*/,$$record{$key});
3462: foreach my $file (@portfiles) {
3463: &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
3464: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
3465: my ($answer_name,$answer_ver,$answer_ext) =
3466: &file_name_version_ext($answer_file);
3467: my $getpropath = 1;
3468: my ($dir_list,$listerror) =
3469: &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,
3470: $stu_name,$getpropath);
3471: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
3472: my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
3473: if ($new_answer ne 'problem getting file') {
3474: push(@versioned_portfiles, $directory.$new_answer);
3475: &Apache::lonnet::mark_as_readonly($domain,$stu_name,
3476: [$directory.$new_answer],
3477: [$symb,$env{'request.course.id'},'graded']);
3478: }
3479: }
3480: $$record{$key} = join(',',@versioned_portfiles);
3481: push(@returned_keys,$key);
3482: }
3483: }
3484: return (@returned_keys);
3485: }
3486:
3487: sub get_next_version {
3488: my ($answer_name, $answer_ext, $dir_list) = @_;
3489: my $version;
3490: if (ref($dir_list) eq 'ARRAY') {
3491: foreach my $row (@{$dir_list}) {
3492: my ($file) = split(/\&/,$row,2);
3493: my ($file_name,$file_version,$file_ext) =
3494: &file_name_version_ext($file);
3495: if (($file_name eq $answer_name) &&
3496: ($file_ext eq $answer_ext)) {
3497: # gets here if filename and extension match,
3498: # regardless of version
3499: if ($file_version ne '') {
3500: # a versioned file is found so save it for later
3501: if ($file_version > $version) {
3502: $version = $file_version;
3503: }
3504: }
3505: }
3506: }
3507: }
3508: $version ++;
3509: return($version);
3510: }
3511:
3512: sub version_selected_portfile {
3513: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
3514: my ($answer_name,$answer_ver,$answer_ext) =
3515: &file_name_version_ext($file_name);
3516: my $new_answer;
3517: $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
3518: if($env{'form.copy'} eq '-1') {
3519: $new_answer = 'problem getting file';
3520: } else {
3521: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
3522: my $copy_result = &Apache::lonnet::finishuserfileupload(
3523: $stu_name,$domain,'copy',
3524: '/portfolio'.$directory.$new_answer);
3525: }
3526: return ($new_answer);
3527: }
3528:
3529: sub file_name_version_ext {
3530: my ($file)=@_;
3531: my @file_parts = split(/\./, $file);
3532: my ($name,$version,$ext);
3533: if (@file_parts > 1) {
3534: $ext=pop(@file_parts);
3535: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
3536: $version=pop(@file_parts);
3537: }
3538: $name=join('.',@file_parts);
3539: } else {
3540: $name=join('.',@file_parts);
3541: }
3542: return($name,$version,$ext);
3543: }
3544:
3545: #--------------------------------------------------------------------------------------
3546: #
3547: #-------------------------- Next few routines handles grading by section or whole class
3548: #
3549: #--- Javascript to handle grading by section or whole class
3550: sub viewgrades_js {
3551: my ($request) = shift;
3552:
3553: my $alertmsg = &mt('A number equal or greater than 0 is expected. Entered value = ');
3554: $request->print(<<VIEWJAVASCRIPT);
3555: <script type="text/javascript" language="javascript">
3556: function writePoint(partid,weight,point) {
3557: var radioButton = document.classgrade["RADVAL_"+partid];
3558: var textbox = document.classgrade["TEXTVAL_"+partid];
3559: if (point == "textval") {
3560: point = document.classgrade["TEXTVAL_"+partid].value;
3561: if (isNaN(point) || parseFloat(point) < 0) {
3562: alert("$alertmsg"+parseFloat(point));
3563: var resetbox = false;
3564: for (var i=0; i<radioButton.length; i++) {
3565: if (radioButton[i].checked) {
3566: textbox.value = i;
3567: resetbox = true;
3568: }
3569: }
3570: if (!resetbox) {
3571: textbox.value = "";
3572: }
3573: return;
3574: }
3575: if (parseFloat(point) > parseFloat(weight)) {
3576: var resp = confirm("You entered a value ("+parseFloat(point)+
3577: ") greater than the weight for the part. Accept?");
3578: if (resp == false) {
3579: textbox.value = "";
3580: return;
3581: }
3582: }
3583: for (var i=0; i<radioButton.length; i++) {
3584: radioButton[i].checked=false;
3585: if (parseFloat(point) == i) {
3586: radioButton[i].checked=true;
3587: }
3588: }
3589:
3590: } else {
3591: textbox.value = parseFloat(point);
3592: }
3593: for (i=0;i<document.classgrade.total.value;i++) {
3594: var user = document.classgrade["ctr"+i].value;
3595: user = user.replace(new RegExp(':', 'g'),"_");
3596: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3597: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3598: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3599: if (saveval != "correct") {
3600: scorename.value = point;
3601: if (selname[0].selected != true) {
3602: selname[0].selected = true;
3603: }
3604: }
3605: }
3606: document.classgrade["SELVAL_"+partid][0].selected = true;
3607: }
3608:
3609: function writeRadText(partid,weight) {
3610: var selval = document.classgrade["SELVAL_"+partid];
3611: var radioButton = document.classgrade["RADVAL_"+partid];
3612: var override = document.classgrade["FORCE_"+partid].checked;
3613: var textbox = document.classgrade["TEXTVAL_"+partid];
3614: if (selval[1].selected || selval[2].selected) {
3615: for (var i=0; i<radioButton.length; i++) {
3616: radioButton[i].checked=false;
3617:
3618: }
3619: textbox.value = "";
3620:
3621: for (i=0;i<document.classgrade.total.value;i++) {
3622: var user = document.classgrade["ctr"+i].value;
3623: user = user.replace(new RegExp(':', 'g'),"_");
3624: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3625: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3626: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3627: if ((saveval != "correct") || override) {
3628: scorename.value = "";
3629: if (selval[1].selected) {
3630: selname[1].selected = true;
3631: } else {
3632: selname[2].selected = true;
3633: if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value))
3634: {document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
3635: }
3636: }
3637: }
3638: } else {
3639: for (i=0;i<document.classgrade.total.value;i++) {
3640: var user = document.classgrade["ctr"+i].value;
3641: user = user.replace(new RegExp(':', 'g'),"_");
3642: var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3643: var saveval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3644: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3645: if ((saveval != "correct") || override) {
3646: scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
3647: selname[0].selected = true;
3648: }
3649: }
3650: }
3651: }
3652:
3653: function changeSelect(partid,user) {
3654: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
3655: var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
3656: var point = textbox.value;
3657: var weight = document.classgrade["weight_"+partid].value;
3658:
3659: if (isNaN(point) || parseFloat(point) < 0) {
3660: alert("$alertmsg"+parseFloat(point));
3661: textbox.value = "";
3662: return;
3663: }
3664: if (parseFloat(point) > parseFloat(weight)) {
3665: var resp = confirm("You entered a value ("+parseFloat(point)+
3666: ") greater than the weight of the part. Accept?");
3667: if (resp == false) {
3668: textbox.value = "";
3669: return;
3670: }
3671: }
3672: selval[0].selected = true;
3673: }
3674:
3675: function changeOneScore(partid,user) {
3676: var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
3677: if (selval[1].selected || selval[2].selected) {
3678: document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
3679: if (selval[2].selected) {
3680: document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
3681: }
3682: }
3683: }
3684:
3685: function resetEntry(numpart) {
3686: for (ctpart=0;ctpart<numpart;ctpart++) {
3687: var partid = document.classgrade["partid_"+ctpart].value;
3688: var radioButton = document.classgrade["RADVAL_"+partid];
3689: var textbox = document.classgrade["TEXTVAL_"+partid];
3690: var selval = document.classgrade["SELVAL_"+partid];
3691: for (var i=0; i<radioButton.length; i++) {
3692: radioButton[i].checked=false;
3693:
3694: }
3695: textbox.value = "";
3696: selval[0].selected = true;
3697:
3698: for (i=0;i<document.classgrade.total.value;i++) {
3699: var user = document.classgrade["ctr"+i].value;
3700: user = user.replace(new RegExp(':', 'g'),"_");
3701: var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
3702: resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
3703: var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
3704: resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
3705: var saveselval = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
3706: var selname = document.classgrade["GD_"+user+"_"+partid+"_solved"];
3707: if (saveselval == "excused") {
3708: if (selname[1].selected == false) { selname[1].selected = true;}
3709: } else {
3710: if (selname[0].selected == false) {selname[0].selected = true};
3711: }
3712: }
3713: }
3714: }
3715:
3716: </script>
3717: VIEWJAVASCRIPT
3718: }
3719:
3720: #--- show scores for a section or whole class w/ option to change/update a score
3721: sub viewgrades {
3722: my ($request) = shift;
3723: &viewgrades_js($request);
3724:
3725: my ($symb) = &get_symb($request);
3726: #need to make sure we have the correct data for later EXT calls,
3727: #thus invalidate the cache
3728: &Apache::lonnet::devalidatecourseresdata(
3729: $env{'course.'.$env{'request.course.id'}.'.num'},
3730: $env{'course.'.$env{'request.course.id'}.'.domain'});
3731: &Apache::lonnet::clear_EXT_cache_status();
3732:
3733: my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
3734: $result.='<h4><b>'.&mt('Current Resource').':</b> '.$env{'form.probTitle'}.'</h4>'."\n";
3735:
3736: #view individual student submission form - called using Javascript viewOneStudent
3737: $result.=&jscriptNform($symb);
3738:
3739: #beginning of class grading form
3740: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
3741: $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
3742: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
3743: '<input type="hidden" name="command" value="editgrades" />'."\n".
3744: &build_section_inputs().
3745: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
3746: '<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
3747: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
3748:
3749: my ($common_header,$specific_header);
3750: if ($env{'form.section'} eq 'all') {
3751: $common_header = &mt('Assign Common Grade to Class');
3752: $specific_header = &mt('Assign Grade to Specific Students in Class');
3753: } elsif ($env{'form.section'} eq 'none') {
3754: $common_header = &mt('Assign Common Grade to Students in no Section');
3755: $specific_header = &mt('Assign Grade to Specific Students in no Section');
3756: } else {
3757: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3758: $common_header = &mt('Assign Common Grade to Students in Section(s) [_1]',$section_display);
3759: $specific_header = &mt('Assign Grade to Specific Students in Section(s) [_1]',$section_display);
3760: }
3761: $result.= '<h3>'.$common_header.'</h3>'.&Apache::loncommon::start_data_table();
3762: #radio buttons/text box for assigning points for a section or class.
3763: #handles different parts of a problem
3764: my $res_error;
3765: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
3766: if ($res_error) {
3767: return &navmap_errormsg();
3768: }
3769: my %weight = ();
3770: my $ctsparts = 0;
3771: my %seen = ();
3772: my @part_response_id = &flatten_responseType($responseType);
3773: foreach my $part_response_id (@part_response_id) {
3774: my ($partid,$respid) = @{ $part_response_id };
3775: my $part_resp = join('_',@{ $part_response_id });
3776: next if $seen{$partid};
3777: $seen{$partid}++;
3778: my $handgrade=$$handgrade{$part_resp};
3779: my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
3780: $weight{$partid} = $wgt eq '' ? '1' : $wgt;
3781:
3782: my $display_part=&get_display_part($partid,$symb);
3783: my $radio.='<table border="0"><tr>';
3784: my $ctr = 0;
3785: while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
3786: $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
3787: 'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
3788: ','.$ctr.')" />'.$ctr."</label></td>\n";
3789: $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
3790: $ctr++;
3791: }
3792: $radio.='</tr></table>';
3793: my $line = '<input type="text" name="TEXTVAL_'.
3794: $partid.'" size="4" '.'onchange="javascript:writePoint(\''.
3795: $partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
3796: $weight{$partid}.' '.&mt('(problem weight)').'</td>'."\n";
3797: $line.= '<td><b>'.&mt('Grade Status').':</b>'.
3798: '<select name="SELVAL_'.$partid.'" '.
3799: 'onchange="javascript:writeRadText(\''.$partid.'\','.
3800: $weight{$partid}.')"> '.
3801: '<option selected="selected"> </option>'.
3802: '<option value="excused">'.&mt('excused').'</option>'.
3803: '<option value="reset status">'.&mt('reset status').'</option>'.
3804: '</select></td>'.
3805: '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
3806: $line.='<input type="hidden" name="partid_'.
3807: $ctsparts.'" value="'.$partid.'" />'."\n";
3808: $line.='<input type="hidden" name="weight_'.
3809: $partid.'" value="'.$weight{$partid}.'" />'."\n";
3810:
3811: $result.=
3812: &Apache::loncommon::start_data_table_row()."\n".
3813: '<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>'.
3814: &Apache::loncommon::end_data_table_row()."\n";
3815: $ctsparts++;
3816: }
3817: $result.=&Apache::loncommon::end_data_table()."\n".
3818: '<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
3819: $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
3820: 'onclick="javascript:resetEntry('.$ctsparts.');" />';
3821:
3822: #table listing all the students in a section/class
3823: #header of table
3824: $result.= '<h3>'.$specific_header.'</h3>'.
3825: &Apache::loncommon::start_data_table().
3826: &Apache::loncommon::start_data_table_header_row().
3827: '<th>'.&mt('No.').'</th>'.
3828: '<th>'.&nameUserString('header')."</th>\n";
3829: my $partserror;
3830: my (@parts) = sort(&getpartlist($symb,\$partserror));
3831: if ($partserror) {
3832: return &navmap_errormsg();
3833: }
3834: my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
3835: my @partids = ();
3836: foreach my $part (@parts) {
3837: my $display=&Apache::lonnet::metadata($url,$part.'.display');
3838: my $narrowtext = &mt('Tries');
3839: $display =~ s|^Number of Attempts|$narrowtext <br />|; # makes the column narrower
3840: if (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
3841: my ($partid) = &split_part_type($part);
3842: push(@partids,$partid);
3843: my $display_part=&get_display_part($partid,$symb);
3844: if ($display =~ /^Partial Credit Factor/) {
3845: $result.='<th>'.
3846: &mt('Score Part: [_1][_2](weight = [_3])',
3847: $display_part,'<br />',$weight{$partid}).'</th>'."\n";
3848: next;
3849:
3850: } else {
3851: if ($display =~ /Problem Status/) {
3852: my $grade_status_mt = &mt('Grade Status');
3853: $display =~ s{Problem Status}{$grade_status_mt<br />};
3854: }
3855: my $part_mt = &mt('Part:');
3856: $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
3857: }
3858:
3859: $result.='<th>'.$display.'</th>'."\n";
3860: }
3861: $result.=&Apache::loncommon::end_data_table_header_row();
3862:
3863: my %last_resets =
3864: &get_last_resets($symb,$env{'request.course.id'},\@partids);
3865:
3866: #get info for each student
3867: #list all the students - with points and grade status
3868: my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
3869: my $ctr = 0;
3870: foreach (sort
3871: {
3872: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
3873: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
3874: }
3875: return $a cmp $b;
3876: } (keys(%$fullname))) {
3877: $ctr++;
3878: $result.=&viewstudentgrade($symb,$env{'request.course.id'},
3879: $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
3880: }
3881: $result.=&Apache::loncommon::end_data_table();
3882: $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
3883: $result.='<input type="button" value="'.&mt('Save').'" '.
3884: 'onclick="javascript:submit();" target="_self" /></form>'."\n";
3885: if (scalar(%$fullname) eq 0) {
3886: my $colspan=3+scalar(@parts);
3887: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3888: my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
3889: $result='<span class="LC_warning">'.
3890: &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
3891: $section_display, $stu_status).
3892: '</span>';
3893: }
3894: $result.=&show_grading_menu_form($symb);
3895: return $result;
3896: }
3897:
3898: #--- call by previous routine to display each student
3899: sub viewstudentgrade {
3900: my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
3901: my ($uname,$udom) = split(/:/,$student);
3902: my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
3903: my %aggregates = ();
3904: my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
3905: '<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
3906: "\n".$ctr.' </td><td> '.
3907: '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
3908: '\');" target="_self">'.$fullname.'</a> '.
3909: '<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
3910: $student=~s/:/_/; # colon doen't work in javascript for names
3911: foreach my $apart (@$parts) {
3912: my ($part,$type) = &split_part_type($apart);
3913: my $score=$record{"resource.$part.$type"};
3914: $result.='<td align="center">';
3915: my ($aggtries,$totaltries);
3916: unless (exists($aggregates{$part})) {
3917: $totaltries = $record{'resource.'.$part.'.tries'};
3918:
3919: $aggtries = $totaltries;
3920: if ($$last_resets{$part}) {
3921: $aggtries = &get_num_tries(\%record,$$last_resets{$part},
3922: $part);
3923: }
3924: $result.='<input type="hidden" name="'.
3925: 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
3926: $result.='<input type="hidden" name="'.
3927: 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
3928: $aggregates{$part} = 1;
3929: }
3930: if ($type eq 'awarded') {
3931: my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
3932: $result.='<input type="hidden" name="'.
3933: 'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
3934: $result.='<input type="text" name="'.
3935: 'GD_'.$student.'_'.$part.'_awarded" '.
3936: 'onchange="javascript:changeSelect(\''.$part.'\',\''.$student.
3937: '\')" value="'.$pts.'" size="4" /></td>'."\n";
3938: } elsif ($type eq 'solved') {
3939: my ($status,$foo)=split(/_/,$score,2);
3940: $status = 'nothing' if ($status eq '');
3941: $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
3942: $part.'_solved_s" value="'.$status.'" />'."\n";
3943: $result.=' <select name="'.
3944: 'GD_'.$student.'_'.$part.'_solved" '.
3945: 'onchange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
3946: $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>'
3947: : '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
3948: $result.='<option value="reset status">'.&mt('reset status').'</option>';
3949: $result.="</select> </td>\n";
3950: } else {
3951: $result.='<input type="hidden" name="'.
3952: 'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
3953: "\n";
3954: $result.='<input type="text" name="'.
3955: 'GD_'.$student.'_'.$part.'_'.$type.'" '.
3956: 'value="'.$score.'" size="4" /></td>'."\n";
3957: }
3958: }
3959: $result.=&Apache::loncommon::end_data_table_row();
3960: return $result;
3961: }
3962:
3963: #--- change scores for all the students in a section/class
3964: # record does not get update if unchanged
3965: sub editgrades {
3966: my ($request) = @_;
3967:
3968: my ($symb)=&get_symb($request);
3969: my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
3970: my $title='<h2>'.&mt('Current Grade Status').'</h2>';
3971: $title.='<h4><b>'.&mt('Current Resource').':</b> '.$env{'form.probTitle'}.'</h4>'."\n";
3972: $title.='<h4><b>'.&mt('Section:').'</b> '.$section_display.'</h4>'."\n";
3973:
3974: my $result= &Apache::loncommon::start_data_table().
3975: &Apache::loncommon::start_data_table_header_row().
3976: '<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
3977: '<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
3978: my %scoreptr = (
3979: 'correct' =>'correct_by_override',
3980: 'incorrect'=>'incorrect_by_override',
3981: 'excused' =>'excused',
3982: 'ungraded' =>'ungraded_attempted',
3983: 'credited' =>'credit_attempted',
3984: 'nothing' => '',
3985: );
3986: my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
3987:
3988: my (@partid);
3989: my %weight = ();
3990: my %columns = ();
3991: my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
3992:
3993: my $partserror;
3994: my (@parts) = sort(&getpartlist($symb,\$partserror));
3995: if ($partserror) {
3996: return &navmap_errormsg();
3997: }
3998: my $header;
3999: while ($ctr < $env{'form.totalparts'}) {
4000: my $partid = $env{'form.partid_'.$ctr};
4001: push(@partid,$partid);
4002: $weight{$partid} = $env{'form.weight_'.$partid};
4003: $ctr++;
4004: }
4005: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
4006: foreach my $partid (@partid) {
4007: $header .= '<th align="center">'.&mt('Old Score').'</th>'.
4008: '<th align="center">'.&mt('New Score').'</th>';
4009: $columns{$partid}=2;
4010: foreach my $stores (@parts) {
4011: my ($part,$type) = &split_part_type($stores);
4012: if ($part !~ m/^\Q$partid\E/) { next;}
4013: if ($type eq 'awarded' || $type eq 'solved') { next; }
4014: my $display=&Apache::lonnet::metadata($url,$stores.'.display');
4015: $display =~ s/\[Part: \Q$part\E\]//;
4016: my $narrowtext = &mt('Tries');
4017: $display =~ s/Number of Attempts/$narrowtext/;
4018: $header .= '<th align="center">'.&mt('Old').' '.$display.'</th>'.
4019: '<th align="center">'.&mt('New').' '.$display.'</th>';
4020: $columns{$partid}+=2;
4021: }
4022: }
4023: foreach my $partid (@partid) {
4024: my $display_part=&get_display_part($partid,$symb);
4025: $result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
4026: &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
4027: '</th>';
4028:
4029: }
4030: $result .= &Apache::loncommon::end_data_table_header_row().
4031: &Apache::loncommon::start_data_table_header_row().
4032: $header.
4033: &Apache::loncommon::end_data_table_header_row();
4034: my @noupdate;
4035: my ($updateCtr,$noupdateCtr) = (1,1);
4036: for ($i=0; $i<$env{'form.total'}; $i++) {
4037: my $line;
4038: my $user = $env{'form.ctr'.$i};
4039: my ($uname,$udom)=split(/:/,$user);
4040: my %newrecord;
4041: my $updateflag = 0;
4042: $line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
4043: my $usec=$classlist->{"$uname:$udom"}[5];
4044: if (!&canmodify($usec)) {
4045: my $numcols=scalar(@partid)*4+2;
4046: push(@noupdate,
4047: $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
4048: &mt('Not allowed to modify student')."</span></td></tr>");
4049: next;
4050: }
4051: my %aggregate = ();
4052: my $aggregateflag = 0;
4053: $user=~s/:/_/; # colon doen't work in javascript for names
4054: foreach (@partid) {
4055: my $old_aw = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
4056: my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
4057: my $old_part = $old_aw eq '' ? '' : $old_part_pcr;
4058: my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
4059: my $awarded = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
4060: my $pcr = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
4061: my $partial = $awarded eq '' ? '' : $pcr;
4062: my $score;
4063: if ($partial eq '') {
4064: $score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
4065: } elsif ($partial > 0) {
4066: $score = 'correct_by_override';
4067: } elsif ($partial == 0) {
4068: $score = 'incorrect_by_override';
4069: }
4070: my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
4071: $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
4072:
4073: $newrecord{'resource.'.$_.'.regrader'}=
4074: "$env{'user.name'}:$env{'user.domain'}";
4075: if ($dropMenu eq 'reset status' &&
4076: $old_score ne '') { # ignore if no previous attempts => nothing to reset
4077: $newrecord{'resource.'.$_.'.tries'} = '';
4078: $newrecord{'resource.'.$_.'.solved'} = '';
4079: $newrecord{'resource.'.$_.'.award'} = '';
4080: $newrecord{'resource.'.$_.'.awarded'} = '';
4081: $updateflag = 1;
4082: if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
4083: my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
4084: my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
4085: my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
4086: &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
4087: $aggregateflag = 1;
4088: }
4089: } elsif (!($old_part eq $partial && $old_score eq $score)) {
4090: $updateflag = 1;
4091: $newrecord{'resource.'.$_.'.awarded'} = $partial if $partial ne '';
4092: $newrecord{'resource.'.$_.'.solved'} = $score;
4093: $rec_update++;
4094: }
4095:
4096: $line .= '<td align="center">'.$old_aw.' </td>'.
4097: '<td align="center">'.$awarded.
4098: ($score eq 'excused' ? $score : '').' </td>';
4099:
4100:
4101: my $partid=$_;
4102: foreach my $stores (@parts) {
4103: my ($part,$type) = &split_part_type($stores);
4104: if ($part !~ m/^\Q$partid\E/) { next;}
4105: if ($type eq 'awarded' || $type eq 'solved') { next; }
4106: my $old_aw = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
4107: my $awarded = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
4108: if ($awarded ne '' && $awarded ne $old_aw) {
4109: $newrecord{'resource.'.$part.'.'.$type}= $awarded;
4110: $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
4111: $updateflag=1;
4112: }
4113: $line .= '<td align="center">'.$old_aw.' </td>'.
4114: '<td align="center">'.$awarded.' </td>';
4115: }
4116: }
4117: $line.="\n";
4118:
4119: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4120: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4121:
4122: if ($updateflag) {
4123: $count++;
4124: &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
4125: $udom,$uname);
4126:
4127: if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
4128: $cnum,$udom,$uname)) {
4129: # need to figure out if should be in queue.
4130: my %record =
4131: &Apache::lonnet::restore($symb,$env{'request.course.id'},
4132: $udom,$uname);
4133: my $all_graded = 1;
4134: my $none_graded = 1;
4135: foreach my $part (@parts) {
4136: if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
4137: $all_graded = 0;
4138: } else {
4139: $none_graded = 0;
4140: }
4141: }
4142:
4143: if ($all_graded || $none_graded) {
4144: &Apache::bridgetask::remove_from_queue('gradingqueue',
4145: $symb,$cdom,$cnum,
4146: $udom,$uname);
4147: }
4148: }
4149:
4150: $result.=&Apache::loncommon::start_data_table_row().
4151: '<td align="right"> '.$updateCtr.' </td>'.$line.
4152: &Apache::loncommon::end_data_table_row();
4153: $updateCtr++;
4154: } else {
4155: push(@noupdate,
4156: '<td align="right"> '.$noupdateCtr.' </td>'.$line);
4157: $noupdateCtr++;
4158: }
4159: if ($aggregateflag) {
4160: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
4161: $cdom,$cnum);
4162: }
4163: }
4164: if (@noupdate) {
4165: # my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
4166: my $numcols=scalar(@partid)*4+2;
4167: $result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
4168: '<td align="center" colspan="'.$numcols.'">'.
4169: &mt('No Changes Occurred For the Students Below').
4170: '</td>'.
4171: &Apache::loncommon::end_data_table_row();
4172: foreach my $line (@noupdate) {
4173: $result.=
4174: &Apache::loncommon::start_data_table_row().
4175: $line.
4176: &Apache::loncommon::end_data_table_row();
4177: }
4178: }
4179: $result .= &Apache::loncommon::end_data_table().
4180: &show_grading_menu_form($symb);
4181: my $msg = '<p><b>'.
4182: &mt('Number of records updated = [_1] for [quant,_2,student].',
4183: $rec_update,$count).'</b><br />'.
4184: '<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
4185: '</b></p>';
4186: return $title.$msg.$result;
4187: }
4188:
4189: sub split_part_type {
4190: my ($partstr) = @_;
4191: my ($temp,@allparts)=split(/_/,$partstr);
4192: my $type=pop(@allparts);
4193: my $part=join('_',@allparts);
4194: return ($part,$type);
4195: }
4196:
4197: #------------- end of section for handling grading by section/class ---------
4198: #
4199: #----------------------------------------------------------------------------
4200:
4201:
4202: #----------------------------------------------------------------------------
4203: #
4204: #-------------------------- Next few routines handles grading by csv upload
4205: #
4206: #--- Javascript to handle csv upload
4207: sub csvupload_javascript_reverse_associate {
4208: my $error1=&mt('You need to specify the username or the student/employee ID');
4209: my $error2=&mt('You need to specify at least one grading field');
4210: return(<<ENDPICK);
4211: function verify(vf) {
4212: var foundsomething=0;
4213: var founduname=0;
4214: var foundID=0;
4215: for (i=0;i<=vf.nfields.value;i++) {
4216: tw=eval('vf.f'+i+'.selectedIndex');
4217: if (i==0 && tw!=0) { foundID=1; }
4218: if (i==1 && tw!=0) { founduname=1; }
4219: if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
4220: }
4221: if (founduname==0 && foundID==0) {
4222: alert('$error1');
4223: return;
4224: }
4225: if (foundsomething==0) {
4226: alert('$error2');
4227: return;
4228: }
4229: vf.submit();
4230: }
4231: function flip(vf,tf) {
4232: var nw=eval('vf.f'+tf+'.selectedIndex');
4233: var i;
4234: for (i=0;i<=vf.nfields.value;i++) {
4235: //can not pick the same destination field for both name and domain
4236: if (((i ==0)||(i ==1)) &&
4237: ((tf==0)||(tf==1)) &&
4238: (i!=tf) &&
4239: (eval('vf.f'+i+'.selectedIndex')==nw)) {
4240: eval('vf.f'+i+'.selectedIndex=0;')
4241: }
4242: }
4243: }
4244: ENDPICK
4245: }
4246:
4247: sub csvupload_javascript_forward_associate {
4248: my $error1=&mt('You need to specify the username or the student/employee ID');
4249: my $error2=&mt('You need to specify at least one grading field');
4250: return(<<ENDPICK);
4251: function verify(vf) {
4252: var foundsomething=0;
4253: var founduname=0;
4254: var foundID=0;
4255: for (i=0;i<=vf.nfields.value;i++) {
4256: tw=eval('vf.f'+i+'.selectedIndex');
4257: if (tw==1) { foundID=1; }
4258: if (tw==2) { founduname=1; }
4259: if (tw>3) { foundsomething=1; }
4260: }
4261: if (founduname==0 && foundID==0) {
4262: alert('$error1');
4263: return;
4264: }
4265: if (foundsomething==0) {
4266: alert('$error2');
4267: return;
4268: }
4269: vf.submit();
4270: }
4271: function flip(vf,tf) {
4272: var nw=eval('vf.f'+tf+'.selectedIndex');
4273: var i;
4274: //can not pick the same destination field twice
4275: for (i=0;i<=vf.nfields.value;i++) {
4276: if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
4277: eval('vf.f'+i+'.selectedIndex=0;')
4278: }
4279: }
4280: }
4281: ENDPICK
4282: }
4283:
4284: sub csvuploadmap_header {
4285: my ($request,$symb,$datatoken,$distotal)= @_;
4286: my $javascript;
4287: if ($env{'form.upfile_associate'} eq 'reverse') {
4288: $javascript=&csvupload_javascript_reverse_associate();
4289: } else {
4290: $javascript=&csvupload_javascript_forward_associate();
4291: }
4292:
4293: my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
4294: my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
4295: my $ignore=&mt('Ignore First Line');
4296: $symb = &Apache::lonenc::check_encrypt($symb);
4297: $request->print(<<ENDPICK);
4298: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
4299: <h3><span class="LC_info">Uploading Class Grades</span></h3>
4300: $result
4301: <hr />
4302: <h3>Identify fields</h3>
4303: Total number of records found in file: $distotal <hr />
4304: Enter as many fields as you can. The system will inform you and bring you back
4305: to this page if the data selected is insufficient to run your class.<hr />
4306: <input type="button" value="Reverse Association" onclick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
4307: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
4308: <input type="hidden" name="associate" value="" />
4309: <input type="hidden" name="phase" value="three" />
4310: <input type="hidden" name="datatoken" value="$datatoken" />
4311: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
4312: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
4313: <input type="hidden" name="upfile_associate"
4314: value="$env{'form.upfile_associate'}" />
4315: <input type="hidden" name="symb" value="$symb" />
4316: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
4317: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
4318: <input type="hidden" name="command" value="csvuploadoptions" />
4319: <hr />
4320: <script type="text/javascript" language="Javascript">
4321: $javascript
4322: </script>
4323: ENDPICK
4324: return '';
4325:
4326: }
4327:
4328: sub csvupload_fields {
4329: my ($symb,$errorref) = @_;
4330: my (@parts) = &getpartlist($symb,$errorref);
4331: if (ref($errorref)) {
4332: if ($$errorref) {
4333: return;
4334: }
4335: }
4336:
4337: my @fields=(['ID','Student/Employee ID'],
4338: ['username','Student Username'],
4339: ['domain','Student Domain']);
4340: my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
4341: foreach my $part (sort(@parts)) {
4342: my @datum;
4343: my $display=&Apache::lonnet::metadata($url,$part.'.display');
4344: my $name=$part;
4345: if (!$display) { $display = $name; }
4346: @datum=($name,$display);
4347: if ($name=~/^stores_(.*)_awarded/) {
4348: push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
4349: }
4350: push(@fields,\@datum);
4351: }
4352: return (@fields);
4353: }
4354:
4355: sub csvuploadmap_footer {
4356: my ($request,$i,$keyfields) =@_;
4357: my $buttontext = &mt('Assign Grades');
4358: $request->print(<<ENDPICK);
4359: </table>
4360: <input type="hidden" name="nfields" value="$i" />
4361: <input type="hidden" name="keyfields" value="$keyfields" />
4362: <input type="button" onclick="javascript:verify(this.form)" value="$buttontext" /><br />
4363: </form>
4364: ENDPICK
4365: }
4366:
4367: sub checkforfile_js {
4368: my $alertmsg = &mt('Please use the browse button to select a file from your local directory.');
4369: my $result =<<CSVFORMJS;
4370: <script type="text/javascript" language="javascript">
4371: function checkUpload(formname) {
4372: if (formname.upfile.value == "") {
4373: alert("$alertmsg");
4374: return false;
4375: }
4376: formname.submit();
4377: }
4378: </script>
4379: CSVFORMJS
4380: return $result;
4381: }
4382:
4383: sub upcsvScores_form {
4384: my ($request) = shift;
4385: my ($symb)=&get_symb($request);
4386: if (!$symb) {return '';}
4387: my $result=&checkforfile_js();
4388: $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
4389: my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
4390: $result.=$table;
4391: $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
4392: $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
4393: $result.=' <b>'.&mt('Specify a file containing the class scores for current resource.').
4394: '</b></td></tr>'."\n";
4395: $result.='<tr bgcolor="#ffffe6"><td>'."\n";
4396: my $upload=&mt("Upload Scores");
4397: my $upfile_select=&Apache::loncommon::upfile_select_html();
4398: my $ignore=&mt('Ignore First Line');
4399: $symb = &Apache::lonenc::check_encrypt($symb);
4400: $result.=<<ENDUPFORM;
4401: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
4402: <input type="hidden" name="symb" value="$symb" />
4403: <input type="hidden" name="command" value="csvuploadmap" />
4404: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
4405: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
4406: $upfile_select
4407: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
4408: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
4409: </form>
4410: ENDUPFORM
4411: $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
4412: &mt("How do I create a CSV file from a spreadsheet"))
4413: .'</td></tr></table>'."\n";
4414: $result.='</td></tr></table><br /><br />'."\n";
4415: $result.=&show_grading_menu_form($symb);
4416: return $result;
4417: }
4418:
4419:
4420: sub csvuploadmap {
4421: my ($request)= @_;
4422: my ($symb)=&get_symb($request);
4423: if (!$symb) {return '';}
4424:
4425: my $datatoken;
4426: if (!$env{'form.datatoken'}) {
4427: $datatoken=&Apache::loncommon::upfile_store($request);
4428: } else {
4429: $datatoken=$env{'form.datatoken'};
4430: &Apache::loncommon::load_tmp_file($request);
4431: }
4432: my @records=&Apache::loncommon::upfile_record_sep();
4433: if ($env{'form.noFirstLine'}) { shift(@records); }
4434: &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
4435: my ($i,$keyfields);
4436: if (@records) {
4437: my $fieldserror;
4438: my @fields=&csvupload_fields($symb,\$fieldserror);
4439: if ($fieldserror) {
4440: $request->print(&navmap_errormsg());
4441: return;
4442: }
4443: if ($env{'form.upfile_associate'} eq 'reverse') {
4444: &Apache::loncommon::csv_print_samples($request,\@records);
4445: $i=&Apache::loncommon::csv_print_select_table($request,\@records,
4446: \@fields);
4447: foreach (@fields) { $keyfields.=$_->[0].','; }
4448: chop($keyfields);
4449: } else {
4450: unshift(@fields,['none','']);
4451: $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
4452: \@fields);
4453: foreach my $rec (@records) {
4454: my %temp = &Apache::loncommon::record_sep($rec);
4455: if (%temp) {
4456: $keyfields=join(',',sort(keys(%temp)));
4457: last;
4458: }
4459: }
4460: }
4461: }
4462: &csvuploadmap_footer($request,$i,$keyfields);
4463: $request->print(&show_grading_menu_form($symb));
4464:
4465: return '';
4466: }
4467:
4468: sub csvuploadoptions {
4469: my ($request)= @_;
4470: my ($symb)=&get_symb($request);
4471: my $checked=(($env{'form.noFirstLine'})?'1':'0');
4472: my $ignore=&mt('Ignore First Line');
4473: $request->print(<<ENDPICK);
4474: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
4475: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
4476: <input type="hidden" name="command" value="csvuploadassign" />
4477: <!--
4478: <p>
4479: <label>
4480: <input type="checkbox" name="show_full_results" />
4481: Show a table of all changes
4482: </label>
4483: </p>
4484: -->
4485: <p>
4486: <label>
4487: <input type="checkbox" name="overwite_scores" checked="checked" />
4488: Overwrite any existing score
4489: </label>
4490: </p>
4491: ENDPICK
4492: my %fields=&get_fields();
4493: if (!defined($fields{'domain'})) {
4494: my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
4495: $request->print("\n<p> Users are in domain: ".$domform."</p>\n");
4496: }
4497: foreach my $key (sort(keys(%env))) {
4498: if ($key !~ /^form\.(.*)$/) { next; }
4499: my $cleankey=$1;
4500: if ($cleankey eq 'command') { next; }
4501: $request->print('<input type="hidden" name="'.$cleankey.
4502: '" value="'.$env{$key}.'" />'."\n");
4503: }
4504: # FIXME do a check for any duplicated user ids...
4505: # FIXME do a check for any invalid user ids?...
4506: $request->print('<input type="submit" value="'.&mt('Assign Grades').'" /><br />
4507: <hr /></form>'."\n");
4508: $request->print(&show_grading_menu_form($symb));
4509: return '';
4510: }
4511:
4512: sub get_fields {
4513: my %fields;
4514: my @keyfields = split(/\,/,$env{'form.keyfields'});
4515: for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
4516: if ($env{'form.upfile_associate'} eq 'reverse') {
4517: if ($env{'form.f'.$i} ne 'none') {
4518: $fields{$keyfields[$i]}=$env{'form.f'.$i};
4519: }
4520: } else {
4521: if ($env{'form.f'.$i} ne 'none') {
4522: $fields{$env{'form.f'.$i}}=$keyfields[$i];
4523: }
4524: }
4525: }
4526: return %fields;
4527: }
4528:
4529: sub csvuploadassign {
4530: my ($request)= @_;
4531: my ($symb)=&get_symb($request);
4532: if (!$symb) {return '';}
4533: my $error_msg = '';
4534: &Apache::loncommon::load_tmp_file($request);
4535: my @gradedata = &Apache::loncommon::upfile_record_sep();
4536: if ($env{'form.noFirstLine'}) { shift(@gradedata); }
4537: my %fields=&get_fields();
4538: $request->print('<h3>Assigning Grades</h3>');
4539: my $courseid=$env{'request.course.id'};
4540: my ($classlist) = &getclasslist('all',0);
4541: my @notallowed;
4542: my @skipped;
4543: my @warnings;
4544: my $countdone=0;
4545: foreach my $grade (@gradedata) {
4546: my %entries=&Apache::loncommon::record_sep($grade);
4547: my $domain;
4548: if ($entries{$fields{'domain'}}) {
4549: $domain=$entries{$fields{'domain'}};
4550: } else {
4551: $domain=$env{'form.default_domain'};
4552: }
4553: $domain=~s/\s//g;
4554: my $username=$entries{$fields{'username'}};
4555: $username=~s/\s//g;
4556: if (!$username) {
4557: my $id=$entries{$fields{'ID'}};
4558: $id=~s/\s//g;
4559: my %ids=&Apache::lonnet::idget($domain,$id);
4560: $username=$ids{$id};
4561: }
4562: if (!exists($$classlist{"$username:$domain"})) {
4563: my $id=$entries{$fields{'ID'}};
4564: $id=~s/\s//g;
4565: if ($id) {
4566: push(@skipped,"$id:$domain");
4567: } else {
4568: push(@skipped,"$username:$domain");
4569: }
4570: next;
4571: }
4572: my $usec=$classlist->{"$username:$domain"}[5];
4573: if (!&canmodify($usec)) {
4574: push(@notallowed,"$username:$domain");
4575: next;
4576: }
4577: my %points;
4578: my %grades;
4579: foreach my $dest (keys(%fields)) {
4580: if ($dest eq 'ID' || $dest eq 'username' ||
4581: $dest eq 'domain') { next; }
4582: if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
4583: if ($dest=~/stores_(.*)_points/) {
4584: my $part=$1;
4585: my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
4586: $symb,$domain,$username);
4587: if ($wgt) {
4588: $entries{$fields{$dest}}=~s/\s//g;
4589: my $pcr=$entries{$fields{$dest}} / $wgt;
4590: my $award=($pcr == 0) ? 'incorrect_by_override'
4591: : 'correct_by_override';
4592: if ($pcr>1) {
4593: push(@warnings,&mt("[_1]: point value larger than weight","$username:$domain"));
4594: }
4595: $grades{"resource.$part.awarded"}=$pcr;
4596: $grades{"resource.$part.solved"}=$award;
4597: $points{$part}=1;
4598: } else {
4599: $error_msg = "<br />" .
4600: &mt("Some point values were assigned"
4601: ." for problems with a weight "
4602: ."of zero. These values were "
4603: ."ignored.");
4604: }
4605: } else {
4606: if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
4607: if ($dest=~/stores_(.*)_solved/) { if ($points{$1}) {next;} }
4608: my $store_key=$dest;
4609: $store_key=~s/^stores/resource/;
4610: $store_key=~s/_/\./g;
4611: $grades{$store_key}=$entries{$fields{$dest}};
4612: }
4613: }
4614: if (! %grades) {
4615: push(@skipped,&mt("[_1]: no data to save","$username:$domain"));
4616: } else {
4617: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
4618: my $result=&Apache::lonnet::cstore(\%grades,$symb,
4619: $env{'request.course.id'},
4620: $domain,$username);
4621: if ($result eq 'ok') {
4622: $request->print('.');
4623: # Remove from grading queue
4624: &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,
4625: $env{'course.'.$env{'request.course.id'}.'.domain'},
4626: $env{'course.'.$env{'request.course.id'}.'.num'},
4627: $domain,$username);
4628: } else {
4629: $request->print("<p><span class=\"LC_error\">".
4630: &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
4631: "$username:$domain",$result)."</span></p>");
4632: }
4633: $request->rflush();
4634: $countdone++;
4635: }
4636: }
4637: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt("Saved scores for [quant,_1,student]",$countdone),$countdone==0));
4638: if (@warnings) {
4639: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Warnings generated for the following saved scores:'),1).'<br />');
4640: $request->print(join(', ',@warnings));
4641: }
4642: if (@skipped) {
4643: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('No scores stored for the following username(s):'),1).'<br />');
4644: $request->print(join(', ',@skipped));
4645: }
4646: if (@notallowed) {
4647: $request->print('<br />'.&Apache::lonhtmlcommon::confirm_success(&mt('Modification of scores not allowed for the following username(s):'),1).'<br />');
4648: $request->print(join(', ',@notallowed));
4649: }
4650: $request->print("<br />\n");
4651: $request->print(&show_grading_menu_form($symb));
4652: return $error_msg;
4653: }
4654: #------------- end of section for handling csv file upload ---------
4655: #
4656: #-------------------------------------------------------------------
4657: #
4658: #-------------- Next few routines handle grading by page/sequence
4659: #
4660: #--- Select a page/sequence and a student to grade
4661: sub pickStudentPage {
4662: my ($request) = shift;
4663:
4664: my $alertmsg = &mt('Please select the student you wish to grade.');
4665: $request->print(<<LISTJAVASCRIPT);
4666: <script type="text/javascript" language="javascript">
4667:
4668: function checkPickOne(formname) {
4669: if (radioSelection(formname.student) == null) {
4670: alert("$alertmsg");
4671: return;
4672: }
4673: ptr = pullDownSelection(formname.selectpage);
4674: formname.page.value = formname["page"+ptr].value;
4675: formname.title.value = formname["title"+ptr].value;
4676: formname.submit();
4677: }
4678:
4679: </script>
4680: LISTJAVASCRIPT
4681: &commonJSfunctions($request);
4682: my ($symb) = &get_symb($request);
4683: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4684: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4685: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4686:
4687: my $result='<h3><span class="LC_info"> '.
4688: &mt('Manual Grading by Page or Sequence').'</span></h3>';
4689:
4690: $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
4691: my $map_error;
4692: my ($titles,$symbx) = &getSymbMap($map_error);
4693: if ($map_error) {
4694: $request->print(&navmap_errormsg());
4695: return;
4696: }
4697: my ($curpage) =&Apache::lonnet::decode_symb($symb);
4698: # my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb);
4699: # my $type=($curpage =~ /\.(page|sequence)/);
4700: my $select = '<select name="selectpage">'."\n";
4701: my $ctr=0;
4702: foreach (@$titles) {
4703: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4704: $select.='<option value="'.$ctr.'" '.
4705: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
4706: '>'.$showtitle.'</option>'."\n";
4707: $ctr++;
4708: }
4709: $select.= '</select>';
4710: $result.=' <b>'.&mt('Problems from').':</b> '.$select."<br />\n";
4711:
4712: $ctr=0;
4713: foreach (@$titles) {
4714: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
4715: $result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
4716: $result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
4717: $ctr++;
4718: }
4719: $result.='<input type="hidden" name="page" />'."\n".
4720: '<input type="hidden" name="title" />'."\n";
4721:
4722: my $options =
4723: '<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
4724: '<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
4725: $result.=' <b>'.&mt('View Problem Text').': </b>'.$options;
4726:
4727: $options =
4728: '<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
4729: '<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
4730: '<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
4731: $result.=' <b>'.&mt('Submissions').': </b>'.$options;
4732:
4733: $result.=&build_section_inputs();
4734: my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
4735: $result.='<input type="hidden" name="Status" value="'.$stu_status.'" />'."\n".
4736: '<input type="hidden" name="command" value="displayPage" />'."\n".
4737: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
4738: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
4739:
4740: $result.=' <b>'.&mt('Use CODE').': </b> <input type="text" name="CODE" value="" /> <br />'."\n";
4741:
4742: $result.=' <input type="button" '.
4743: 'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' →" /><br />'."\n";
4744:
4745: $request->print($result);
4746:
4747: my $studentTable.=' <b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
4748: &Apache::loncommon::start_data_table().
4749: &Apache::loncommon::start_data_table_header_row().
4750: '<th align="right"> '.&mt('No.').'</th>'.
4751: '<th>'.&nameUserString('header').'</th>'.
4752: '<th align="right"> '.&mt('No.').'</th>'.
4753: '<th>'.&nameUserString('header').'</th>'.
4754: &Apache::loncommon::end_data_table_header_row();
4755:
4756: my (undef,undef,$fullname) = &getclasslist($getsec,'1');
4757: my $ptr = 1;
4758: foreach my $student (sort
4759: {
4760: if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
4761: return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
4762: }
4763: return $a cmp $b;
4764: } (keys(%$fullname))) {
4765: my ($uname,$udom) = split(/:/,$student);
4766: $studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
4767: : '</td>');
4768: $studentTable.='<td align="right">'.$ptr.' </td>';
4769: $studentTable.='<td> <label><input type="radio" name="student" value="'.$student.'" /> '
4770: .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
4771: $studentTable.=
4772: ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row()
4773: : '');
4774: $ptr++;
4775: }
4776: if ($ptr%2 == 0) {
4777: $studentTable.='</td><td> </td><td> </td>'.
4778: &Apache::loncommon::end_data_table_row();
4779: }
4780: $studentTable.=&Apache::loncommon::end_data_table()."\n";
4781: $studentTable.='<input type="button" '.
4782: 'onclick="javascript:checkPickOne(this.form);" value="'.&mt('Next').' →" /></form>'."\n";
4783:
4784: $studentTable.=&show_grading_menu_form($symb);
4785: $request->print($studentTable);
4786:
4787: return '';
4788: }
4789:
4790: sub getSymbMap {
4791: my ($map_error) = @_;
4792: my $navmap = Apache::lonnavmaps::navmap->new();
4793: unless (ref($navmap)) {
4794: if (ref($map_error)) {
4795: $$map_error = 'navmap';
4796: }
4797: return;
4798: }
4799: my %symbx = ();
4800: my @titles = ();
4801: my $minder = 0;
4802:
4803: # Gather every sequence that has problems.
4804: my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
4805: 1,0,1);
4806: for my $sequence ($navmap->getById('0.0'), @sequences) {
4807: if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
4808: my $title = $minder.'.'.
4809: &HTML::Entities::encode($sequence->compTitle(),'"\'&');
4810: push(@titles, $title); # minder in case two titles are identical
4811: $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
4812: $minder++;
4813: }
4814: }
4815: return \@titles,\%symbx;
4816: }
4817:
4818: #
4819: #--- Displays a page/sequence w/wo problems, w/wo submissions
4820: sub displayPage {
4821: my ($request) = shift;
4822:
4823: my ($symb) = &get_symb($request);
4824: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
4825: my $cnum = $env{"course.$env{'request.course.id'}.num"};
4826: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
4827: my $pageTitle = $env{'form.page'};
4828: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
4829: my ($uname,$udom) = split(/:/,$env{'form.student'});
4830: my $usec=$classlist->{$env{'form.student'}}[5];
4831:
4832: #need to make sure we have the correct data for later EXT calls,
4833: #thus invalidate the cache
4834: &Apache::lonnet::devalidatecourseresdata(
4835: $env{'course.'.$env{'request.course.id'}.'.num'},
4836: $env{'course.'.$env{'request.course.id'}.'.domain'});
4837: &Apache::lonnet::clear_EXT_cache_status();
4838:
4839: if (!&canview($usec)) {
4840: $request->print('<span class="LC_warning">'.
4841: &mt('Unable to view requested student. ([_1])',
4842: $env{'form.student'}).
4843: '</span>');
4844: $request->print(&show_grading_menu_form($symb));
4845: return;
4846: }
4847: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
4848: $result.='<h3> '.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
4849: '</h3>'."\n";
4850: $env{'form.CODE'} = uc($env{'form.CODE'});
4851: if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
4852: $result.='<h3> '.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
4853: } else {
4854: delete($env{'form.CODE'});
4855: }
4856: &sub_page_js($request);
4857: $request->print($result);
4858:
4859: my $navmap = Apache::lonnavmaps::navmap->new();
4860: unless (ref($navmap)) {
4861: $request->print(&navmap_errormsg());
4862: $request->print(&show_grading_menu_form($symb));
4863: return;
4864: }
4865: my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
4866: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
4867: if (!$map) {
4868: $request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
4869: $request->print(&show_grading_menu_form($symb));
4870: return;
4871: }
4872: my $iterator = $navmap->getIterator($map->map_start(),
4873: $map->map_finish());
4874:
4875: my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
4876: '<input type="hidden" name="command" value="gradeByPage" />'."\n".
4877: '<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
4878: '<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
4879: '<input type="hidden" name="page" value="'.$pageTitle.'" />'."\n".
4880: '<input type="hidden" name="title" value="'.$env{'form.title'}.'" />'."\n".
4881: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
4882: '<input type="hidden" name="overRideScore" value="no" />'."\n".
4883: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
4884:
4885: if (defined($env{'form.CODE'})) {
4886: $studentTable.=
4887: '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
4888: }
4889: my $checkIcon = '<img alt="'.&mt('Check Mark').
4890: '" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
4891:
4892: $studentTable.=' <span class="LC_info">'.
4893: &mt('Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon).
4894: '</span>'."\n".
4895: &Apache::loncommon::start_data_table().
4896: &Apache::loncommon::start_data_table_header_row().
4897: '<th align="center"> Prob. </th>'.
4898: '<th> '.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
4899: &Apache::loncommon::end_data_table_header_row();
4900:
4901: &Apache::lonxml::clear_problem_counter();
4902: my ($depth,$question,$prob) = (1,1,1);
4903: $iterator->next(); # skip the first BEGIN_MAP
4904: my $curRes = $iterator->next(); # for "current resource"
4905: while ($depth > 0) {
4906: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
4907: if($curRes == $iterator->END_MAP) { $depth--; }
4908:
4909: if (ref($curRes) && $curRes->is_problem()) {
4910: my $parts = $curRes->parts();
4911: my $title = $curRes->compTitle();
4912: my $symbx = $curRes->symb();
4913: $studentTable.=
4914: &Apache::loncommon::start_data_table_row().
4915: '<td align="center" valign="top" >'.$prob.
4916: (scalar(@{$parts}) == 1 ? ''
4917: : '<br />('.&mt('[_1]parts',
4918: scalar(@{$parts}).' ').')'
4919: ).
4920: '</td>';
4921: $studentTable.='<td valign="top">';
4922: my %form = ('CODE' => $env{'form.CODE'},);
4923: if ($env{'form.vProb'} eq 'yes' ) {
4924: $studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
4925: undef,'both',\%form);
4926: } else {
4927: my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
4928: $companswer =~ s|<form(.*?)>||g;
4929: $companswer =~ s|</form>||g;
4930: # while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
4931: # $companswer =~ s/$1/ /ms;
4932: # $request->print('match='.$1."<br />\n");
4933: # }
4934: # $companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
4935: $studentTable.=' <b>'.$title.'</b> <br /> <b>'.&mt('Correct answer').':</b><br />'.$companswer;
4936: }
4937:
4938: my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
4939:
4940: if ($env{'form.lastSub'} eq 'datesub') {
4941: if ($record{'version'} eq '') {
4942: $studentTable.='<br /> <span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
4943: } else {
4944: my %responseType = ();
4945: foreach my $partid (@{$parts}) {
4946: my @responseIds =$curRes->responseIds($partid);
4947: my @responseType =$curRes->responseType($partid);
4948: my %responseIds;
4949: for (my $i=0;$i<=$#responseIds;$i++) {
4950: $responseIds{$responseIds[$i]}=$responseType[$i];
4951: }
4952: $responseType{$partid} = \%responseIds;
4953: }
4954: $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
4955:
4956: }
4957: } elsif ($env{'form.lastSub'} eq 'all') {
4958: my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
4959: my $identifier = (&canmodify($usec)? $prob : '');
4960: $studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
4961: $env{'request.course.id'},
4962: '','.submission',undef,
4963: $usec,$identifier);
4964:
4965: }
4966: if (&canmodify($usec)) {
4967: $studentTable.=&gradeBox_start();
4968: foreach my $partid (@{$parts}) {
4969: $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
4970: $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
4971: $question++;
4972: }
4973: $studentTable.=&gradeBox_end();
4974: $prob++;
4975: }
4976: $studentTable.='</td></tr>';
4977:
4978: }
4979: $curRes = $iterator->next();
4980: }
4981:
4982: $studentTable.=
4983: '</table>'."\n".
4984: '<input type="button" value="'.&mt('Save').'" '.
4985: 'onclick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
4986: '</form>'."\n";
4987: $studentTable.=&show_grading_menu_form($symb);
4988: $request->print($studentTable);
4989:
4990: return '';
4991: }
4992:
4993: sub displaySubByDates {
4994: my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
4995: my $isCODE=0;
4996: my $isTask = ($symb =~/\.task$/);
4997: if (exists($record->{'resource.CODE'})) { $isCODE=1; }
4998: my $studentTable=&Apache::loncommon::start_data_table().
4999: &Apache::loncommon::start_data_table_header_row().
5000: '<th>'.&mt('Date/Time').'</th>'.
5001: ($isCODE?'<th>'.&mt('CODE').'</th>':'').
5002: ($isTask?'<th>'.&mt('Version').'</th>':'').
5003: '<th>'.&mt('Submission').'</th>'.
5004: '<th>'.&mt('Status').'</th>'.
5005: &Apache::loncommon::end_data_table_header_row();
5006: my ($version);
5007: my %mark;
5008: my %orders;
5009: $mark{'correct_by_student'} = $checkIcon;
5010: if (!exists($$record{'1:timestamp'})) {
5011: return '<br /> <span class="LC_warning">'.&mt('Nothing submitted - no attempts.').'</span><br />';
5012: }
5013:
5014: my $interaction;
5015: my $no_increment = 1;
5016: my %lastrndseed;
5017: for ($version=1;$version<=$$record{'version'};$version++) {
5018: my $timestamp =
5019: &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
5020: if (exists($$record{$version.':resource.0.version'})) {
5021: $interaction = $$record{$version.':resource.0.version'};
5022: }
5023: if ($isTask && $env{'form.previousversion'}) {
5024: next unless ($interaction == $env{'form.previousversion'});
5025: }
5026: my $where = ($isTask ? "$version:resource.$interaction"
5027: : "$version:resource");
5028: $studentTable.=&Apache::loncommon::start_data_table_row().
5029: '<td>'.$timestamp.'</td>';
5030: if ($isCODE) {
5031: $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
5032: }
5033: if ($isTask) {
5034: $studentTable.='<td>'.$interaction.'</td>';
5035: }
5036: my @versionKeys = split(/\:/,$$record{$version.':keys'});
5037: my @displaySub = ();
5038: foreach my $partid (@{$parts}) {
5039: my ($hidden,$type);
5040: $type = $$record{$version.':resource.'.$partid.'.type'};
5041: if (($type eq 'anonsurvey') || ($type eq 'anonsurveycred')) {
5042: $hidden = 1;
5043: }
5044: my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
5045: : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
5046:
5047: # next if ($$record{"$version:resource.$partid.solved"} eq '');
5048: my $display_part=&get_display_part($partid,$symb);
5049: foreach my $matchKey (@matchKey) {
5050: if (exists($$record{$version.':'.$matchKey}) &&
5051: $$record{$version.':'.$matchKey} ne '') {
5052:
5053: my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
5054: : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
5055: $displaySub[0].='<span class="LC_nobreak">';
5056: $displaySub[0].='<b>'.&mt('Part: [_1]',$display_part).'</b>'
5057: .' <span class="LC_internal_info">'
5058: .'('.&mt('Response ID: [_1]',$responseId).')'
5059: .'</span>'
5060: .' <b>';
5061: if ($hidden) {
5062: $displaySub[0].= &mt('Anonymous Survey').'</b>';
5063: } else {
5064: my ($trial,$rndseed,$newvariation);
5065: if ($type eq 'randomizetry') {
5066: $trial = $$record{"$where.$partid.tries"};
5067: $rndseed = $$record{"$where.$partid.rndseed"};
5068: }
5069: if ($$record{"$where.$partid.tries"} eq '') {
5070: $displaySub[0].=&mt('Trial not counted');
5071: } else {
5072: $displaySub[0].=&mt('Trial: [_1]',
5073: $$record{"$where.$partid.tries"});
5074: if (($rndseed ne '') && ($lastrndseed{$partid} ne '')) {
5075: if ($rndseed ne $lastrndseed{$partid}) {
5076: $newvariation = ' ('.&mt('New variation this try').')';
5077: }
5078: }
5079: $lastrndseed{$partid} = $rndseed;
5080: }
5081: my $responseType=($isTask ? 'Task'
5082: : $responseType->{$partid}->{$responseId});
5083: if (!exists($orders{$partid})) { $orders{$partid}={}; }
5084: if ((!exists($orders{$partid}->{$responseId})) || ($trial)) {
5085: $orders{$partid}->{$responseId}=
5086: &get_order($partid,$responseId,$symb,$uname,$udom,
5087: $no_increment,$type,$trial,$rndseed);
5088: }
5089: $displaySub[0].='</b>'.$newvariation.'</span>'; # /nobreak
5090: $displaySub[0].=' '.
5091: &cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom,$type,$trial,$rndseed).'<br />';
5092: }
5093: }
5094: }
5095: if (exists($$record{"$where.$partid.checkedin"})) {
5096: $displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
5097: $$record{"$where.$partid.checkedin"},
5098: $$record{"$where.$partid.checkedin.slot"}).
5099: '<br />';
5100: }
5101: if (exists $$record{"$where.$partid.award"}) {
5102: $displaySub[1].='<b>'.&mt('Part:').'</b> '.$display_part.' '.
5103: lc($$record{"$where.$partid.award"}).' '.
5104: $mark{$$record{"$where.$partid.solved"}}.
5105: '<br />';
5106: }
5107: if (exists $$record{"$where.$partid.regrader"}) {
5108: $displaySub[2].=$$record{"$where.$partid.regrader"}.
5109: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
5110: } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
5111: $displaySub[2].=
5112: $$record{"$version:resource.$partid.regrader"}.
5113: ' (<b>'.&mt('Part').':</b> '.$display_part.')';
5114: }
5115: }
5116: # needed because old essay regrader has not parts info
5117: if (exists $$record{"$version:resource.regrader"}) {
5118: $displaySub[2].=$$record{"$version:resource.regrader"};
5119: }
5120: $studentTable.='<td>'.$displaySub[0].' </td><td>'.$displaySub[1];
5121: if ($displaySub[2]) {
5122: $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
5123: }
5124: $studentTable.=' </td>'.
5125: &Apache::loncommon::end_data_table_row();
5126: }
5127: $studentTable.=&Apache::loncommon::end_data_table();
5128: return $studentTable;
5129: }
5130:
5131: sub updateGradeByPage {
5132: my ($request) = shift;
5133:
5134: my $cdom = $env{"course.$env{'request.course.id'}.domain"};
5135: my $cnum = $env{"course.$env{'request.course.id'}.num"};
5136: my $getsec = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
5137: my $pageTitle = $env{'form.page'};
5138: my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
5139: my ($uname,$udom) = split(/:/,$env{'form.student'});
5140: my $usec=$classlist->{$env{'form.student'}}[5];
5141: if (!&canmodify($usec)) {
5142: $request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
5143: $request->print(&show_grading_menu_form($env{'form.symb'}));
5144: return;
5145: }
5146: my $result='<h3><span class="LC_info"> '.$env{'form.title'}.'</span></h3>';
5147: $result.='<h3> '.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
5148: '</h3>'."\n";
5149:
5150: $request->print($result);
5151:
5152:
5153: my $navmap = Apache::lonnavmaps::navmap->new();
5154: unless (ref($navmap)) {
5155: $request->print(&navmap_errormsg());
5156: return;
5157: }
5158: my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
5159: my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
5160: if (!$map) {
5161: $request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
5162: my ($symb)=&get_symb($request);
5163: $request->print(&show_grading_menu_form($symb));
5164: return;
5165: }
5166: my $iterator = $navmap->getIterator($map->map_start(),
5167: $map->map_finish());
5168:
5169: my $studentTable=
5170: &Apache::loncommon::start_data_table().
5171: &Apache::loncommon::start_data_table_header_row().
5172: '<th align="center"> '.&mt('Prob.').' </th>'.
5173: '<th> '.&mt('Title').' </th>'.
5174: '<th> '.&mt('Previous Score').' </th>'.
5175: '<th> '.&mt('New Score').' </th>'.
5176: &Apache::loncommon::end_data_table_header_row();
5177:
5178: $iterator->next(); # skip the first BEGIN_MAP
5179: my $curRes = $iterator->next(); # for "current resource"
5180: my ($depth,$question,$prob,$changeflag,$hideflag)= (1,1,1,0,0);
5181: while ($depth > 0) {
5182: if($curRes == $iterator->BEGIN_MAP) { $depth++; }
5183: if($curRes == $iterator->END_MAP) { $depth--; }
5184:
5185: if (ref($curRes) && $curRes->is_problem()) {
5186: my $parts = $curRes->parts();
5187: my $title = $curRes->compTitle();
5188: my $symbx = $curRes->symb();
5189: $studentTable.=
5190: &Apache::loncommon::start_data_table_row().
5191: '<td align="center" valign="top" >'.$prob.
5192: (scalar(@{$parts}) == 1 ? ''
5193: : '<br />('.&mt('[quant,_1,part]',scalar(@{$parts}))
5194: .')').'</td>';
5195: $studentTable.='<td valign="top"> <b>'.$title.'</b> </td>';
5196:
5197: my %newrecord=();
5198: my @displayPts=();
5199: my %aggregate = ();
5200: my $aggregateflag = 0;
5201: if ($env{'form.HIDE'.$prob}) {
5202: my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
5203: my ($version,$parts) = split(/:/,$env{'form.HIDE'.$prob},2);
5204: my $numchgs = &makehidden($version,$parts,\%record,$symbx,$udom,$uname,1);
5205: $hideflag += $numchgs;
5206: }
5207: foreach my $partid (@{$parts}) {
5208: my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
5209: my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
5210:
5211: my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ?
5212: $env{'form.WGT'.$question.'_'.$partid} : 1;
5213: my $partial = $newpts/$wgt;
5214: my $score;
5215: if ($partial > 0) {
5216: $score = 'correct_by_override';
5217: } elsif ($newpts ne '') { #empty is taken as 0
5218: $score = 'incorrect_by_override';
5219: }
5220: my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
5221: if ($dropMenu eq 'excused') {
5222: $partial = '';
5223: $score = 'excused';
5224: } elsif ($dropMenu eq 'reset status'
5225: && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
5226: $newrecord{'resource.'.$partid.'.tries'} = 0;
5227: $newrecord{'resource.'.$partid.'.solved'} = '';
5228: $newrecord{'resource.'.$partid.'.award'} = '';
5229: $newrecord{'resource.'.$partid.'.awarded'} = 0;
5230: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
5231: $changeflag++;
5232: $newpts = '';
5233:
5234: my $aggtries = $env{'form.aggtries'.$question.'_'.$partid};
5235: my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
5236: my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
5237: if ($aggtries > 0) {
5238: &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
5239: $aggregateflag = 1;
5240: }
5241: }
5242: my $display_part=&get_display_part($partid,$curRes->symb());
5243: my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
5244: $displayPts[0].=' <b>'.&mt('Part').':</b> '.$display_part.' = '.
5245: (($oldstatus eq 'excused') ? 'excused' : $oldpts).
5246: ' <br />';
5247: $displayPts[1].=' <b>'.&mt('Part').':</b> '.$display_part.' = '.
5248: (($score eq 'excused') ? 'excused' : $newpts).
5249: ' <br />';
5250: $question++;
5251: next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
5252:
5253: $newrecord{'resource.'.$partid.'.awarded'} = $partial if $partial ne '';
5254: $newrecord{'resource.'.$partid.'.solved'} = $score if $score ne '';
5255: $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
5256: if (scalar(keys(%newrecord)) > 0);
5257:
5258: $changeflag++;
5259: }
5260: if (scalar(keys(%newrecord)) > 0) {
5261: my %record =
5262: &Apache::lonnet::restore($symbx,$env{'request.course.id'},
5263: $udom,$uname);
5264:
5265: if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
5266: $newrecord{'resource.CODE'} = $env{'form.CODE'};
5267: } elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
5268: $newrecord{'resource.CODE'} = '';
5269: }
5270: &Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
5271: $udom,$uname);
5272: %record = &Apache::lonnet::restore($symbx,
5273: $env{'request.course.id'},
5274: $udom,$uname);
5275: &check_and_remove_from_queue($parts,\%record,undef,$symbx,
5276: $cdom,$cnum,$udom,$uname);
5277: }
5278:
5279: if ($aggregateflag) {
5280: &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
5281: $env{'course.'.$env{'request.course.id'}.'.domain'},
5282: $env{'course.'.$env{'request.course.id'}.'.num'});
5283: }
5284:
5285: $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
5286: '<td valign="top">'.$displayPts[1].'</td>'.
5287: &Apache::loncommon::end_data_table_row();
5288:
5289: $prob++;
5290: }
5291: $curRes = $iterator->next();
5292: }
5293:
5294: $studentTable.=&Apache::loncommon::end_data_table();
5295: $studentTable.=&show_grading_menu_form($env{'form.symb'});
5296: my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
5297: &mt('The scores were changed for [quant,_1,problem].',
5298: $changeflag).'<br />');
5299: my $hidemsg=($hideflag == 0 ? '' :
5300: &mt('Submissions were marked "hidden" for [quant,_1,transaction].',
5301: $hideflag).'<br />');
5302: $request->print($hidemsg.$grademsg.$studentTable);
5303:
5304: return '';
5305: }
5306:
5307: #-------- end of section for handling grading by page/sequence ---------
5308: #
5309: #-------------------------------------------------------------------
5310:
5311: #-------------------- Bubblesheet (Scantron) Grading -------------------
5312: #
5313: #------ start of section for handling grading by page/sequence ---------
5314:
5315: =pod
5316:
5317: =head1 Bubble sheet grading routines
5318:
5319: For this documentation:
5320:
5321: 'scanline' refers to the full line of characters
5322: from the file that we are parsing that represents one entire sheet
5323:
5324: 'bubble line' refers to the data
5325: representing the line of bubbles that are on the physical bubblesheet
5326:
5327:
5328: The overall process is that a scanned in bubblesheet data is uploaded
5329: into a course. When a user wants to grade, they select a
5330: sequence/folder of resources, a file of bubblesheet info, and pick
5331: one of the predefined configurations for what each scanline looks
5332: like.
5333:
5334: Next each scanline is checked for any errors of either 'missing
5335: bubbles' (it's an error because it may have been mis-scanned
5336: because too light bubbling), 'double bubble' (each bubble line should
5337: have no more than one letter picked), invalid or duplicated CODE,
5338: invalid student/employee ID
5339:
5340: If the CODE option is used that determines the randomization of the
5341: homework problems, either way the student/employee ID is looked up into a
5342: username:domain.
5343:
5344: During the validation phase the instructor can choose to skip scanlines.
5345:
5346: After the validation phase, there are now 3 bubblesheet files
5347:
5348: scantron_original_filename (unmodified original file)
5349: scantron_corrected_filename (file where the corrected information has replaced the original information)
5350: scantron_skipped_filename (contains the exact text of scanlines that where skipped)
5351:
5352: Also there is a separate hash nohist_scantrondata that contains extra
5353: correction information that isn't representable in the bubblesheet
5354: file (see &scantron_getfile() for more information)
5355:
5356: After all scanlines are either valid, marked as valid or skipped, then
5357: foreach line foreach problem in the picked sequence, an ssi request is
5358: made that simulates a user submitting their selected letter(s) against
5359: the homework problem.
5360:
5361: =over 4
5362:
5363:
5364:
5365: =item defaultFormData
5366:
5367: Returns html hidden inputs used to hold context/default values.
5368:
5369: Arguments:
5370: $symb - $symb of the current resource
5371:
5372: =cut
5373:
5374: sub defaultFormData {
5375: my ($symb)=@_;
5376: return '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
5377: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
5378: '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
5379: }
5380:
5381:
5382: =pod
5383:
5384: =item getSequenceDropDown
5385:
5386: Return html dropdown of possible sequences to grade
5387:
5388: Arguments:
5389: $symb - $symb of the current resource
5390: $map_error - ref to scalar which will container error if
5391: $navmap object is unavailable in &getSymbMap().
5392:
5393: =cut
5394:
5395: sub getSequenceDropDown {
5396: my ($symb,$map_error)=@_;
5397: my $result='<select name="selectpage">'."\n";
5398: my ($titles,$symbx) = &getSymbMap($map_error);
5399: if (ref($map_error)) {
5400: return if ($$map_error);
5401: }
5402: my ($curpage)=&Apache::lonnet::decode_symb($symb);
5403: my $ctr=0;
5404: foreach (@$titles) {
5405: my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
5406: $result.='<option value="'.$$symbx{$_}.'" '.
5407: ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
5408: '>'.$showtitle.'</option>'."\n";
5409: $ctr++;
5410: }
5411: $result.= '</select>';
5412: return $result;
5413: }
5414:
5415: my %bubble_lines_per_response; # no. bubble lines for each response.
5416: # key is zero-based index - 0, 1, 2 ...
5417:
5418: my %first_bubble_line; # First bubble line no. for each bubble.
5419:
5420: my %subdivided_bubble_lines; # no. bubble lines for optionresponse,
5421: # matchresponse or rankresponse, where
5422: # an individual response can have multiple
5423: # lines
5424:
5425: my %responsetype_per_response; # responsetype for each response
5426:
5427: my %masterseq_id_responsenum; # src_id (e.g., 12.3_0.11 etc.) for each
5428: # numbered response. Needed when randomorder
5429: # or randompick are in use. Key is ID, value
5430: # is response number.
5431:
5432: # Save and restore the bubble lines array to the form env.
5433:
5434:
5435: sub save_bubble_lines {
5436: foreach my $line (keys(%bubble_lines_per_response)) {
5437: $env{"form.scantron.bubblelines.$line"} = $bubble_lines_per_response{$line};
5438: $env{"form.scantron.first_bubble_line.$line"} =
5439: $first_bubble_line{$line};
5440: $env{"form.scantron.sub_bubblelines.$line"} =
5441: $subdivided_bubble_lines{$line};
5442: $env{"form.scantron.responsetype.$line"} =
5443: $responsetype_per_response{$line};
5444: }
5445: foreach my $resid (keys(%masterseq_id_responsenum)) {
5446: my $line = $masterseq_id_responsenum{$resid};
5447: $env{"form.scantron.residpart.$line"} = $resid;
5448: }
5449: }
5450:
5451:
5452: sub restore_bubble_lines {
5453: my $line = 0;
5454: %bubble_lines_per_response = ();
5455: %masterseq_id_responsenum = ();
5456: while ($env{"form.scantron.bubblelines.$line"}) {
5457: my $value = $env{"form.scantron.bubblelines.$line"};
5458: $bubble_lines_per_response{$line} = $value;
5459: $first_bubble_line{$line} =
5460: $env{"form.scantron.first_bubble_line.$line"};
5461: $subdivided_bubble_lines{$line} =
5462: $env{"form.scantron.sub_bubblelines.$line"};
5463: $responsetype_per_response{$line} =
5464: $env{"form.scantron.responsetype.$line"};
5465: my $id = $env{"form.scantron.residpart.$line"};
5466: $masterseq_id_responsenum{$id} = $line;
5467: $line++;
5468: }
5469: }
5470:
5471: =pod
5472:
5473: =item scantron_filenames
5474:
5475: Returns a list of the scantron files in the current course
5476:
5477: =cut
5478:
5479: sub scantron_filenames {
5480: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5481: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5482: my $getpropath = 1;
5483: my ($dirlist,$listerror) = &Apache::lonnet::dirlist('userfiles',$cdom,
5484: $cname,$getpropath);
5485: my @possiblenames;
5486: if (ref($dirlist) eq 'ARRAY') {
5487: foreach my $filename (sort(@{$dirlist})) {
5488: ($filename)=split(/&/,$filename);
5489: if ($filename!~/^scantron_orig_/) { next ; }
5490: $filename=~s/^scantron_orig_//;
5491: push(@possiblenames,$filename);
5492: }
5493: }
5494: return @possiblenames;
5495: }
5496:
5497: =pod
5498:
5499: =item scantron_uploads
5500:
5501: Returns html drop-down list of scantron files in current course.
5502:
5503: Arguments:
5504: $file2grade - filename to set as selected in the dropdown
5505:
5506: =cut
5507:
5508: sub scantron_uploads {
5509: my ($file2grade) = @_;
5510: my $result= '<select name="scantron_selectfile">';
5511: $result.="<option></option>";
5512: foreach my $filename (sort(&scantron_filenames())) {
5513: $result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
5514: }
5515: $result.="</select>";
5516: return $result;
5517: }
5518:
5519: =pod
5520:
5521: =item scantron_scantab
5522:
5523: Returns html drop down of the scantron formats in the scantronformat.tab
5524: file.
5525:
5526: =cut
5527:
5528: sub scantron_scantab {
5529: my $result='<select name="scantron_format">'."\n";
5530: $result.='<option></option>'."\n";
5531: my @lines = &get_scantronformat_file();
5532: if (@lines > 0) {
5533: foreach my $line (@lines) {
5534: next if (($line =~ /^\#/) || ($line eq ''));
5535: my ($name,$descrip)=split(/:/,$line);
5536: $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
5537: }
5538: }
5539: $result.='</select>'."\n";
5540: return $result;
5541: }
5542:
5543: =pod
5544:
5545: =item get_scantronformat_file
5546:
5547: Returns an array containing lines from the scantron format file for
5548: the domain of the course.
5549:
5550: If a url for a custom.tab file is listed in domain's configuration.db,
5551: lines are from this file.
5552:
5553: Otherwise, if a default.tab has been published in RES space by the
5554: domainconfig user, lines are from this file.
5555:
5556: Otherwise, fall back to getting lines from the legacy file on the
5557: local server: /home/httpd/lonTabs/default_scantronformat.tab
5558:
5559: =cut
5560:
5561: sub get_scantronformat_file {
5562: my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
5563: my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
5564: my $gottab = 0;
5565: my @lines;
5566: if (ref($domconfig{'scantron'}) eq 'HASH') {
5567: if ($domconfig{'scantron'}{'scantronformat'} ne '') {
5568: my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
5569: if ($formatfile ne '-1') {
5570: @lines = split("\n",$formatfile,-1);
5571: $gottab = 1;
5572: }
5573: }
5574: }
5575: if (!$gottab) {
5576: my $confname = $cdom.'-domainconfig';
5577: my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
5578: my $formatfile = &Apache::lonnet::getfile($default);
5579: if ($formatfile ne '-1') {
5580: @lines = split("\n",$formatfile,-1);
5581: $gottab = 1;
5582: }
5583: }
5584: if (!$gottab) {
5585: my @domains = &Apache::lonnet::current_machine_domains();
5586: if (grep(/^\Q$cdom\E$/,@domains)) {
5587: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
5588: @lines = <$fh>;
5589: close($fh);
5590: } else {
5591: my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
5592: @lines = <$fh>;
5593: close($fh);
5594: }
5595: }
5596: return @lines;
5597: }
5598:
5599: =pod
5600:
5601: =item scantron_CODElist
5602:
5603: Returns html drop down of the saved CODE lists from current course,
5604: generated from earlier printings.
5605:
5606: =cut
5607:
5608: sub scantron_CODElist {
5609: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5610: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5611: my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
5612: my $namechoice='<option></option>';
5613: foreach my $name (sort {uc($a) cmp uc($b)} @names) {
5614: if ($name =~ /^error: 2 /) { next; }
5615: if ($name =~ /^type\0/) { next; }
5616: $namechoice.='<option value="'.$name.'">'.$name.'</option>';
5617: }
5618: $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
5619: return $namechoice;
5620: }
5621:
5622: =pod
5623:
5624: =item scantron_CODEunique
5625:
5626: Returns the html for "Each CODE to be used once" radio.
5627:
5628: =cut
5629:
5630: sub scantron_CODEunique {
5631: my $result='<span class="LC_nobreak">
5632: <label><input type="radio" name="scantron_CODEunique"
5633: value="yes" checked="checked" />'.&mt('Yes').' </label>
5634: </span>
5635: <span class="LC_nobreak">
5636: <label><input type="radio" name="scantron_CODEunique"
5637: value="no" />'.&mt('No').' </label>
5638: </span>';
5639: return $result;
5640: }
5641:
5642: =pod
5643:
5644: =item scantron_selectphase
5645:
5646: Generates the initial screen to start the bubblesheet process.
5647: Allows for - starting a grading run.
5648: - downloading existing scan data (original, corrected
5649: or skipped info)
5650:
5651: - uploading new scan data
5652:
5653: Arguments:
5654: $r - The Apache request object
5655: $file2grade - name of the file that contain the scanned data to score
5656:
5657: =cut
5658:
5659: sub scantron_selectphase {
5660: my ($r,$file2grade) = @_;
5661: my ($symb)=&get_symb($r);
5662: if (!$symb) {return '';}
5663: my $map_error;
5664: my $sequence_selector=&getSequenceDropDown($symb,\$map_error);
5665: if ($map_error) {
5666: $r->print('<br />'.&navmap_errormsg().'<br />');
5667: return;
5668: }
5669: my $default_form_data=&defaultFormData($symb);
5670: my $grading_menu_button=&show_grading_menu_form($symb);
5671: my $file_selector=&scantron_uploads($file2grade);
5672: my $format_selector=&scantron_scantab();
5673: my $CODE_selector=&scantron_CODElist();
5674: my $CODE_unique=&scantron_CODEunique();
5675: my $result;
5676:
5677: $ssi_error = 0;
5678:
5679: if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
5680: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
5681:
5682: # Chunk of form to prompt for a scantron file upload.
5683:
5684: $r->print('
5685: <br />
5686: '.&Apache::loncommon::start_data_table('LC_scantron_action').'
5687: '.&Apache::loncommon::start_data_table_header_row().'
5688: <th>
5689: '.&mt('Specify a bubblesheet data file to upload.').'
5690: </th>
5691: '.&Apache::loncommon::end_data_table_header_row().'
5692: '.&Apache::loncommon::start_data_table_row().'
5693: <td>
5694: ');
5695: my $default_form_data=&defaultFormData(&get_symb($r,1));
5696: my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
5697: my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
5698: $r->print('
5699: <script type="text/javascript" language="javascript">
5700: function checkUpload(formname) {
5701: if (formname.upfile.value == "") {
5702: alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
5703: return false;
5704: }
5705: formname.submit();
5706: }
5707: </script>
5708:
5709: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
5710: '.$default_form_data.'
5711: <input name="courseid" type="hidden" value="'.$cnum.'" />
5712: <input name="domainid" type="hidden" value="'.$cdom.'" />
5713: <input name="command" value="scantronupload_save" type="hidden" />
5714: '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
5715: <br />
5716: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
5717: </form>
5718: ');
5719:
5720: $r->print('
5721: </td>
5722: '.&Apache::loncommon::end_data_table_row().'
5723: '.&Apache::loncommon::end_data_table().'
5724: ');
5725: }
5726:
5727: # Chunk of form to prompt for a file to grade and how:
5728:
5729: $result.= '
5730: <br />
5731: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
5732: <input type="hidden" name="command" value="scantron_warning" />
5733: '.$default_form_data.'
5734: '.&Apache::loncommon::start_data_table('LC_scantron_action').'
5735: '.&Apache::loncommon::start_data_table_header_row().'
5736: <th colspan="2">
5737: '.&mt('Specify file and which Folder/Sequence to grade').'
5738: </th>
5739: '.&Apache::loncommon::end_data_table_header_row().'
5740: '.&Apache::loncommon::start_data_table_row().'
5741: <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
5742: '.&Apache::loncommon::end_data_table_row().'
5743: '.&Apache::loncommon::start_data_table_row().'
5744: <td> '.&mt('Filename of bubblesheet data file:').' </td><td> '.$file_selector.' </td>
5745: '.&Apache::loncommon::end_data_table_row().'
5746: '.&Apache::loncommon::start_data_table_row().'
5747: <td> '.&mt('Format of bubblesheet data file:').' </td><td> '.$format_selector.' </td>
5748: '.&Apache::loncommon::end_data_table_row().'
5749: '.&Apache::loncommon::start_data_table_row().'
5750: <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
5751: '.&Apache::loncommon::end_data_table_row().'
5752: '.&Apache::loncommon::start_data_table_row().'
5753: <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
5754: '.&Apache::loncommon::end_data_table_row().'
5755: '.&Apache::loncommon::start_data_table_row().'
5756: <td> '.&mt('Options:').' </td>
5757: <td>
5758: <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
5759: <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
5760: <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
5761: </td>
5762: '.&Apache::loncommon::end_data_table_row().'
5763: '.&Apache::loncommon::start_data_table_row().'
5764: <td colspan="2">
5765: <input type="submit" value="'.&mt('Grading: Validate Bubblesheet Records').'" />
5766: </td>
5767: '.&Apache::loncommon::end_data_table_row().'
5768: '.&Apache::loncommon::end_data_table().'
5769: </form>
5770: ';
5771:
5772: $r->print($result);
5773:
5774: # Chunk of the form that prompts to view a scoring office file,
5775: # corrected file, skipped records in a file.
5776:
5777: $r->print('
5778: <br />
5779: <form action="/adm/grades" name="scantron_download">
5780: '.$default_form_data.'
5781: <input type="hidden" name="command" value="scantron_download" />
5782: '.&Apache::loncommon::start_data_table('LC_scantron_action').'
5783: '.&Apache::loncommon::start_data_table_header_row().'
5784: <th>
5785: '.&mt('Download a scoring office file').'
5786: </th>
5787: '.&Apache::loncommon::end_data_table_header_row().'
5788: '.&Apache::loncommon::start_data_table_row().'
5789: <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).'
5790: <br />
5791: <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
5792: '.&Apache::loncommon::end_data_table_row().'
5793: '.&Apache::loncommon::end_data_table().'
5794: </form>
5795: <br />
5796: ');
5797:
5798: &Apache::lonpickcode::code_list($r,2);
5799:
5800: $r->print('<br /><form method="post" name="checkscantron" action="">'.
5801: $default_form_data."\n".
5802: &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
5803: &Apache::loncommon::start_data_table_header_row()."\n".
5804: '<th colspan="2">
5805: '.&mt('Review bubblesheet data and submissions for a previously graded folder/sequence')."\n".
5806: '</th>'."\n".
5807: &Apache::loncommon::end_data_table_header_row()."\n".
5808: &Apache::loncommon::start_data_table_row()."\n".
5809: '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
5810: '<td> '.$sequence_selector.' </td>'.
5811: &Apache::loncommon::end_data_table_row()."\n".
5812: &Apache::loncommon::start_data_table_row()."\n".
5813: '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
5814: '<td> '.$file_selector.' </td>'."\n".
5815: &Apache::loncommon::end_data_table_row()."\n".
5816: &Apache::loncommon::start_data_table_row()."\n".
5817: '<td> '.&mt('Format of data file:').' </td>'."\n".
5818: '<td> '.$format_selector.' </td>'."\n".
5819: &Apache::loncommon::end_data_table_row()."\n".
5820: &Apache::loncommon::start_data_table_row()."\n".
5821: '<td> '.&mt('Options').' </td>'."\n".
5822: '<td> <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources').'</label></td>'.
5823: &Apache::loncommon::end_data_table_row()."\n".
5824: &Apache::loncommon::start_data_table_row()."\n".
5825: '<td colspan="2">'."\n".
5826: '<input type="hidden" name="command" value="checksubmissions" />'."\n".
5827: '<input type="submit" value="'.&mt('Review Bubblesheet Data and Submission Records').'" />'."\n".
5828: '</td>'."\n".
5829: &Apache::loncommon::end_data_table_row()."\n".
5830: &Apache::loncommon::end_data_table()."\n".
5831: '</form><br />');
5832: $r->print($grading_menu_button);
5833: return;
5834: }
5835:
5836: =pod
5837:
5838: =item get_scantron_config
5839:
5840: Parse and return the scantron configuration line selected as a
5841: hash of configuration file fields.
5842:
5843: Arguments:
5844: which - the name of the configuration to parse from the file.
5845:
5846:
5847: Returns:
5848: If the named configuration is not in the file, an empty
5849: hash is returned.
5850: a hash with the fields
5851: name - internal name for the this configuration setup
5852: description - text to display to operator that describes this config
5853: CODElocation - if 0 or the string 'none'
5854: - no CODE exists for this config
5855: if -1 || the string 'letter'
5856: - a CODE exists for this config and is
5857: a string of letters
5858: Unsupported value (but planned for future support)
5859: if a positive integer
5860: - The CODE exists as the first n items from
5861: the question section of the form
5862: if the string 'number'
5863: - The CODE exists for this config and is
5864: a string of numbers
5865: CODEstart - (only matter if a CODE exists) column in the line where
5866: the CODE starts
5867: CODElength - length of the CODE
5868: IDstart - column where the student/employee ID starts
5869: IDlength - length of the student/employee ID info
5870: Qstart - column where the information from the bubbled
5871: 'questions' start
5872: Qlength - number of columns comprising a single bubble line from
5873: the sheet. (usually either 1 or 10)
5874: Qon - either a single character representing the character used
5875: to signal a bubble was chosen in the positional setup, or
5876: the string 'letter' if the letter of the chosen bubble is
5877: in the final, or 'number' if a number representing the
5878: chosen bubble is in the file (1->A 0->J)
5879: Qoff - the character used to represent that a bubble was
5880: left blank
5881: PaperID - if the scanning process generates a unique number for each
5882: sheet scanned the column that this ID number starts in
5883: PaperIDlength - number of columns that comprise the unique ID number
5884: for the sheet of paper
5885: FirstName - column that the first name starts in
5886: FirstNameLength - number of columns that the first name spans
5887:
5888: LastName - column that the last name starts in
5889: LastNameLength - number of columns that the last name spans
5890: BubblesPerRow - number of bubbles available in each row used to
5891: bubble an answer. (If not specified, 10 assumed).
5892:
5893: =cut
5894:
5895: sub get_scantron_config {
5896: my ($which) = @_;
5897: my @lines = &get_scantronformat_file();
5898: my %config;
5899: #FIXME probably should move to XML it has already gotten a bit much now
5900: foreach my $line (@lines) {
5901: my ($name,$descrip)=split(/:/,$line);
5902: if ($name ne $which ) { next; }
5903: chomp($line);
5904: my @config=split(/:/,$line);
5905: $config{'name'}=$config[0];
5906: $config{'description'}=$config[1];
5907: $config{'CODElocation'}=$config[2];
5908: $config{'CODEstart'}=$config[3];
5909: $config{'CODElength'}=$config[4];
5910: $config{'IDstart'}=$config[5];
5911: $config{'IDlength'}=$config[6];
5912: $config{'Qstart'}=$config[7];
5913: $config{'Qlength'}=$config[8];
5914: $config{'Qoff'}=$config[9];
5915: $config{'Qon'}=$config[10];
5916: $config{'PaperID'}=$config[11];
5917: $config{'PaperIDlength'}=$config[12];
5918: $config{'FirstName'}=$config[13];
5919: $config{'FirstNamelength'}=$config[14];
5920: $config{'LastName'}=$config[15];
5921: $config{'LastNamelength'}=$config[16];
5922: $config{'BubblesPerRow'}=$config[17];
5923: last;
5924: }
5925: return %config;
5926: }
5927:
5928: =pod
5929:
5930: =item username_to_idmap
5931:
5932: creates a hash keyed by student/employee ID with values of the corresponding
5933: student username:domain.
5934:
5935: Arguments:
5936:
5937: $classlist - reference to the class list hash. This is a hash
5938: keyed by student name:domain whose elements are references
5939: to arrays containing various chunks of information
5940: about the student. (See loncoursedata for more info).
5941:
5942: Returns
5943: %idmap - the constructed hash
5944:
5945: =cut
5946:
5947: sub username_to_idmap {
5948: my ($classlist)= @_;
5949: my %idmap;
5950: foreach my $student (keys(%$classlist)) {
5951: my $id = $classlist->{$student}->[&Apache::loncoursedata::CL_ID];
5952: unless ($id eq '') {
5953: if (!exists($idmap{$id})) {
5954: $idmap{$id} = $student;
5955: } else {
5956: my $status = $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS];
5957: if ($status eq 'Active') {
5958: $idmap{$id} = $student;
5959: }
5960: }
5961: }
5962: }
5963: return %idmap;
5964: }
5965:
5966: =pod
5967:
5968: =item scantron_fixup_scanline
5969:
5970: Process a requested correction to a scanline.
5971:
5972: Arguments:
5973: $scantron_config - hash from &get_scantron_config()
5974: $scan_data - hash of correction information
5975: (see &scantron_getfile())
5976: $line - existing scanline
5977: $whichline - line number of the passed in scanline
5978: $field - type of change to process
5979: (either
5980: 'ID' -> correct the student/employee ID
5981: 'CODE' -> correct the CODE
5982: 'answer' -> fixup the submitted answers)
5983:
5984: $args - hash of additional info,
5985: - 'ID'
5986: 'newid' -> studentID to use in replacement
5987: of existing one
5988: - 'CODE'
5989: 'CODE_ignore_dup' - set to true if duplicates
5990: should be ignored.
5991: 'CODE' - is new code or 'use_unfound'
5992: if the existing unfound code should
5993: be used as is
5994: - 'answer'
5995: 'response' - new answer or 'none' if blank
5996: 'question' - the bubble line to change
5997: 'questionnum' - the question identifier,
5998: may include subquestion.
5999:
6000: Returns:
6001: $line - the modified scanline
6002:
6003: Side effects:
6004: $scan_data - may be updated
6005:
6006: =cut
6007:
6008:
6009: sub scantron_fixup_scanline {
6010: my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
6011: if ($field eq 'ID') {
6012: if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
6013: return ($line,1,'New value too large');
6014: }
6015: if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
6016: $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
6017: $args->{'newid'});
6018: }
6019: substr($line,$$scantron_config{'IDstart'}-1,
6020: $$scantron_config{'IDlength'})=$args->{'newid'};
6021: if ($args->{'newid'}=~/^\s*$/) {
6022: &scan_data($scan_data,"$whichline.user",
6023: $args->{'username'}.':'.$args->{'domain'});
6024: }
6025: } elsif ($field eq 'CODE') {
6026: if ($args->{'CODE_ignore_dup'}) {
6027: &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
6028: }
6029: &scan_data($scan_data,"$whichline.useCODE",'1');
6030: if ($args->{'CODE'} ne 'use_unfound') {
6031: if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
6032: return ($line,1,'New CODE value too large');
6033: }
6034: if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
6035: $args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
6036: }
6037: substr($line,$$scantron_config{'CODEstart'}-1,
6038: $$scantron_config{'CODElength'})=$args->{'CODE'};
6039: }
6040: } elsif ($field eq 'answer') {
6041: my $length=$scantron_config->{'Qlength'};
6042: my $off=$scantron_config->{'Qoff'};
6043: my $on=$scantron_config->{'Qon'};
6044: my $answer=${off}x$length;
6045: if ($args->{'response'} eq 'none') {
6046: &scan_data($scan_data,
6047: "$whichline.no_bubble.".$args->{'questionnum'},'1');
6048: } else {
6049: if ($on eq 'letter') {
6050: my @alphabet=('A'..'Z');
6051: $answer=$alphabet[$args->{'response'}];
6052: } elsif ($on eq 'number') {
6053: $answer=$args->{'response'}+1;
6054: if ($answer == 10) { $answer = '0'; }
6055: } else {
6056: substr($answer,$args->{'response'},1)=$on;
6057: }
6058: &scan_data($scan_data,
6059: "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
6060: }
6061: my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
6062: substr($line,$where-1,$length)=$answer;
6063: }
6064: return $line;
6065: }
6066:
6067: =pod
6068:
6069: =item scan_data
6070:
6071: Edit or look up an item in the scan_data hash.
6072:
6073: Arguments:
6074: $scan_data - The hash (see scantron_getfile)
6075: $key - shorthand of the key to edit (actual key is
6076: scantronfilename_key).
6077: $data - New value of the hash entry.
6078: $delete - If true, the entry is removed from the hash.
6079:
6080: Returns:
6081: The new value of the hash table field (undefined if deleted).
6082:
6083: =cut
6084:
6085:
6086: sub scan_data {
6087: my ($scan_data,$key,$value,$delete)=@_;
6088: my $filename=$env{'form.scantron_selectfile'};
6089: if (defined($value)) {
6090: $scan_data->{$filename.'_'.$key} = $value;
6091: }
6092: if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
6093: return $scan_data->{$filename.'_'.$key};
6094: }
6095:
6096: # ----- These first few routines are general use routines.----
6097:
6098: # Return the number of occurences of a pattern in a string.
6099:
6100: sub occurence_count {
6101: my ($string, $pattern) = @_;
6102:
6103: my @matches = ($string =~ /$pattern/g);
6104:
6105: return scalar(@matches);
6106: }
6107:
6108:
6109: # Take a string known to have digits and convert all the
6110: # digits into letters in the range J,A..I.
6111:
6112: sub digits_to_letters {
6113: my ($input) = @_;
6114:
6115: my @alphabet = ('J', 'A'..'I');
6116:
6117: my @input = split(//, $input);
6118: my $output ='';
6119: for (my $i = 0; $i < scalar(@input); $i++) {
6120: if ($input[$i] =~ /\d/) {
6121: $output .= $alphabet[$input[$i]];
6122: } else {
6123: $output .= $input[$i];
6124: }
6125: }
6126: return $output;
6127: }
6128:
6129: =pod
6130:
6131: =item scantron_parse_scanline
6132:
6133: Decodes a scanline from the selected scantron file
6134:
6135: Arguments:
6136: line - The text of the scantron file line to process
6137: whichline - Line number
6138: scantron_config - Hash describing the format of the scantron lines.
6139: scan_data - Hash of extra information about the scanline
6140: (see scantron_getfile for more information)
6141: just_header - True if should not process question answers but only
6142: the stuff to the left of the answers.
6143: randomorder - True if randomorder in use
6144: randompick - True if randompick in use
6145: sequence - Exam folder URL
6146: master_seq - Ref to array containing symbs in exam folder
6147: symb_to_resource - Ref to hash of symbs for resources in exam folder
6148: (corresponding values are resource objects)
6149: partids_by_symb - Ref to hash of symb -> array ref of partIDs
6150: orderedforcode - Ref to hash of arrays. keys are CODEs and values
6151: are refs to an array of resource objects, ordered
6152: according to order used for CODE, when randomorder
6153: and or randompick are in use.
6154: respnumlookup - Ref to hash mapping question numbers in bubble lines
6155: for current line to question number used for same question
6156: in "Master Sequence" (as seen by Course Coordinator).
6157: startline - Ref to hash where key is question number (0 is first)
6158: and value is number of first bubble line for current
6159: student or code-based randompick and/or randomorder.
6160: totalref - Ref of scalar used to score total number of bubble
6161: lines needed for responses in a scan line (used when
6162: randompick in use.
6163:
6164: Returns:
6165: Hash containing the result of parsing the scanline
6166:
6167: Keys are all proceeded by the string 'scantron.'
6168:
6169: CODE - the CODE in use for this scanline
6170: useCODE - 1 if the CODE is invalid but it usage has been forced
6171: by the operator
6172: CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
6173: CODEs were selected, but the usage has been
6174: forced by the operator
6175: ID - student/employee ID
6176: PaperID - if used, the ID number printed on the sheet when the
6177: paper was scanned
6178: FirstName - first name from the sheet
6179: LastName - last name from the sheet
6180:
6181: if just_header was not true these key may also exist
6182:
6183: missingerror - a list of bubble ranges that are considered to be answers
6184: to a single question that don't have any bubbles filled in.
6185: Of the form questionnumber:firstbubblenumber:count.
6186: doubleerror - a list of bubble ranges that are considered to be answers
6187: to a single question that have more than one bubble filled in.
6188: Of the form questionnumber::firstbubblenumber:count
6189:
6190: In the above, count is the number of bubble responses in the
6191: input line needed to represent the possible answers to the question.
6192: e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
6193: per line would have count = 2.
6194:
6195: maxquest - the number of the last bubble line that was parsed
6196:
6197: (<number> starts at 1)
6198: <number>.answer - zero or more letters representing the selected
6199: letters from the scanline for the bubble line
6200: <number>.
6201: if blank there was either no bubble or there where
6202: multiple bubbles, (consult the keys missingerror and
6203: doubleerror if this is an error condition)
6204:
6205: =cut
6206:
6207: sub scantron_parse_scanline {
6208: my ($line,$whichline,$scantron_config,$scan_data,$just_header,$idmap,
6209: $randomorder,$randompick,$sequence,$master_seq,$symb_to_resource,
6210: $partids_by_symb,$orderedforcode,$respnumlookup,$startline,$totalref)=@_;
6211:
6212: my %record;
6213: my $data=substr($line,0,$$scantron_config{'Qstart'}-1); # stuff before answers
6214: if (!($$scantron_config{'CODElocation'} eq 0 ||
6215: $$scantron_config{'CODElocation'} eq 'none')) {
6216: if ($$scantron_config{'CODElocation'} < 0 ||
6217: $$scantron_config{'CODElocation'} eq 'letter' ||
6218: $$scantron_config{'CODElocation'} eq 'number') {
6219: $record{'scantron.CODE'}=substr($data,
6220: $$scantron_config{'CODEstart'}-1,
6221: $$scantron_config{'CODElength'});
6222: if (&scan_data($scan_data,"$whichline.useCODE")) {
6223: $record{'scantron.useCODE'}=1;
6224: }
6225: if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
6226: $record{'scantron.CODE_ignore_dup'}=1;
6227: }
6228: } else {
6229: #FIXME interpret first N questions
6230: }
6231: }
6232: $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
6233: $$scantron_config{'IDlength'});
6234: $record{'scantron.PaperID'}=
6235: substr($data,$$scantron_config{'PaperID'}-1,
6236: $$scantron_config{'PaperIDlength'});
6237: $record{'scantron.FirstName'}=
6238: substr($data,$$scantron_config{'FirstName'}-1,
6239: $$scantron_config{'FirstNamelength'});
6240: $record{'scantron.LastName'}=
6241: substr($data,$$scantron_config{'LastName'}-1,
6242: $$scantron_config{'LastNamelength'});
6243: if ($just_header) { return \%record; }
6244:
6245: my @alphabet=('A'..'Z');
6246: my $questnum=0;
6247: my $ansnum =1; # Multiple 'answer lines'/question.
6248:
6249: my $lastpos = $env{'form.scantron_maxbubble'}*$$scantron_config{'Qlength'};
6250: if ($randompick || $randomorder) {
6251: my $total = &get_respnum_lookups($sequence,$scan_data,$idmap,$line,\%record,
6252: $master_seq,$symb_to_resource,
6253: $partids_by_symb,$orderedforcode,
6254: $respnumlookup,$startline);
6255: if ($total) {
6256: $lastpos = $total*$$scantron_config{'Qlength'};
6257: }
6258: if (ref($totalref)) {
6259: $$totalref = $total;
6260: }
6261: }
6262: my $questions=substr($line,$$scantron_config{'Qstart'}-1,$lastpos); # Answers
6263: chomp($questions); # Get rid of any trailing \n.
6264: $questions =~ s/\r$//; # Get rid of trailing \r too (MAC or Win uploads).
6265: while (length($questions)) {
6266: my $answers_needed;
6267: if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
6268: $answers_needed = $bubble_lines_per_response{$respnumlookup->{$questnum}};
6269: } else {
6270: $answers_needed = $bubble_lines_per_response{$questnum};
6271: }
6272: my $answer_length = ($$scantron_config{'Qlength'} * $answers_needed)
6273: || 1;
6274: $questnum++;
6275: my $quest_id = $questnum;
6276: my $currentquest = substr($questions,0,$answer_length);
6277: $questions = substr($questions,$answer_length);
6278: if (length($currentquest) < $answer_length) { next; }
6279:
6280: my $subdivided;
6281: if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
6282: $subdivided = $subdivided_bubble_lines{$respnumlookup->{$questnum-1}};
6283: } else {
6284: $subdivided = $subdivided_bubble_lines{$questnum-1};
6285: }
6286: if ($subdivided =~ /,/) {
6287: my $subquestnum = 1;
6288: my $subquestions = $currentquest;
6289: my @subanswers_needed = split(/,/,$subdivided);
6290: foreach my $subans (@subanswers_needed) {
6291: my $subans_length =
6292: ($$scantron_config{'Qlength'} * $subans) || 1;
6293: my $currsubquest = substr($subquestions,0,$subans_length);
6294: $subquestions = substr($subquestions,$subans_length);
6295: $quest_id = "$questnum.$subquestnum";
6296: if (($$scantron_config{'Qon'} eq 'letter') ||
6297: ($$scantron_config{'Qon'} eq 'number')) {
6298: $ansnum = &scantron_validator_lettnum($ansnum,
6299: $questnum,$quest_id,$subans,$currsubquest,$whichline,
6300: \@alphabet,\%record,$scantron_config,$scan_data,
6301: $randomorder,$randompick,$respnumlookup);
6302: } else {
6303: $ansnum = &scantron_validator_positional($ansnum,
6304: $questnum,$quest_id,$subans,$currsubquest,$whichline,
6305: \@alphabet,\%record,$scantron_config,$scan_data,
6306: $randomorder,$randompick,$respnumlookup);
6307: }
6308: $subquestnum ++;
6309: }
6310: } else {
6311: if (($$scantron_config{'Qon'} eq 'letter') ||
6312: ($$scantron_config{'Qon'} eq 'number')) {
6313: $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
6314: $quest_id,$answers_needed,$currentquest,$whichline,
6315: \@alphabet,\%record,$scantron_config,$scan_data,
6316: $randomorder,$randompick,$respnumlookup);
6317: } else {
6318: $ansnum = &scantron_validator_positional($ansnum,$questnum,
6319: $quest_id,$answers_needed,$currentquest,$whichline,
6320: \@alphabet,\%record,$scantron_config,$scan_data,
6321: $randomorder,$randompick,$respnumlookup);
6322: }
6323: }
6324: }
6325: $record{'scantron.maxquest'}=$questnum;
6326: return \%record;
6327: }
6328:
6329: sub get_master_seq {
6330: my ($resources,$master_seq,$symb_to_resource) = @_;
6331: return unless ((ref($resources) eq 'ARRAY') && (ref($master_seq) eq 'ARRAY') &&
6332: (ref($symb_to_resource) eq 'HASH'));
6333: my $resource_error;
6334: foreach my $resource (@{$resources}) {
6335: my $ressymb;
6336: if (ref($resource)) {
6337: $ressymb = $resource->symb();
6338: push(@{$master_seq},$ressymb);
6339: $symb_to_resource->{$ressymb} = $resource;
6340: } else {
6341: $resource_error = 1;
6342: last;
6343: }
6344: }
6345: return $resource_error;
6346: }
6347:
6348: sub get_respnum_lookups {
6349: my ($sequence,$scan_data,$idmap,$line,$record,$master_seq,$symb_to_resource,
6350: $partids_by_symb,$orderedforcode,$respnumlookup,$startline) = @_;
6351: return unless ((ref($record) eq 'HASH') && (ref($master_seq) eq 'ARRAY') &&
6352: (ref($symb_to_resource) eq 'HASH') && (ref($partids_by_symb) eq 'HASH') &&
6353: (ref($orderedforcode) eq 'HASH') && (ref($respnumlookup) eq 'HASH') &&
6354: (ref($startline) eq 'HASH'));
6355: my ($user,$scancode);
6356: if ((exists($record->{'scantron.CODE'})) &&
6357: (&Apache::lonnet::validCODE($record->{'scantron.CODE'}))) {
6358: $scancode = $record->{'scantron.CODE'};
6359: } else {
6360: $user = &scantron_find_student($record,$scan_data,$idmap,$line);
6361: }
6362: my @mapresources =
6363: &users_order($user,$scancode,$sequence,$master_seq,$symb_to_resource,
6364: $orderedforcode);
6365: my $total = 0;
6366: my $count = 0;
6367: foreach my $resource (@mapresources) {
6368: my $id = $resource->id();
6369: my $symb = $resource->symb();
6370: if (ref($partids_by_symb->{$symb}) eq 'ARRAY') {
6371: foreach my $partid (@{$partids_by_symb->{$symb}}) {
6372: my $respnum = $masterseq_id_responsenum{$id.'_'.$partid};
6373: if ($respnum ne '') {
6374: $respnumlookup->{$count} = $respnum;
6375: $startline->{$count} = $total;
6376: $total += $bubble_lines_per_response{$respnum};
6377: $count ++;
6378: }
6379: }
6380: }
6381: }
6382: return $total;
6383: }
6384:
6385: sub scantron_validator_lettnum {
6386: my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
6387: $alphabet,$record,$scantron_config,$scan_data,$randomorder,
6388: $randompick,$respnumlookup) = @_;
6389:
6390: # Qon 'letter' implies for each slot in currquest we have:
6391: # ? or * for doubles, a letter in A-Z for a bubble, and
6392: # about anything else (esp. a value of Qoff) for missing
6393: # bubbles.
6394: #
6395: # Qon 'number' implies each slot gives a digit that indexes the
6396: # bubbles filled, or Qoff, or a non-number for unbubbled lines,
6397: # and * or ? for double bubbles on a single line.
6398: #
6399:
6400: my $matchon;
6401: if ($$scantron_config{'Qon'} eq 'letter') {
6402: $matchon = '[A-Z]';
6403: } elsif ($$scantron_config{'Qon'} eq 'number') {
6404: $matchon = '\d';
6405: }
6406: my $occurrences = 0;
6407: my $responsenum = $questnum-1;
6408: if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
6409: $responsenum = $respnumlookup->{$questnum-1}
6410: }
6411: if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
6412: ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
6413: ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
6414: ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
6415: ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
6416: ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
6417: my @singlelines = split('',$currquest);
6418: foreach my $entry (@singlelines) {
6419: $occurrences = &occurence_count($entry,$matchon);
6420: if ($occurrences > 1) {
6421: last;
6422: }
6423: }
6424: } else {
6425: $occurrences = &occurence_count($currquest,$matchon);
6426: }
6427: if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
6428: push(@{$record->{'scantron.doubleerror'}},$quest_id);
6429: for (my $ans=0; $ans<$answers_needed; $ans++) {
6430: my $bubble = substr($currquest,$ans,1);
6431: if ($bubble =~ /$matchon/ ) {
6432: if ($$scantron_config{'Qon'} eq 'number') {
6433: if ($bubble == 0) {
6434: $bubble = 10;
6435: }
6436: $record->{"scantron.$ansnum.answer"} =
6437: $alphabet->[$bubble-1];
6438: } else {
6439: $record->{"scantron.$ansnum.answer"} = $bubble;
6440: }
6441: } else {
6442: $record->{"scantron.$ansnum.answer"}='';
6443: }
6444: $ansnum++;
6445: }
6446: } elsif (!defined($currquest)
6447: || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
6448: || (&occurence_count($currquest,$matchon) == 0)) {
6449: for (my $ans=0; $ans<$answers_needed; $ans++ ) {
6450: $record->{"scantron.$ansnum.answer"}='';
6451: $ansnum++;
6452: }
6453: if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
6454: push(@{$record->{'scantron.missingerror'}},$quest_id);
6455: }
6456: } else {
6457: if ($$scantron_config{'Qon'} eq 'number') {
6458: $currquest = &digits_to_letters($currquest);
6459: }
6460: for (my $ans=0; $ans<$answers_needed; $ans++) {
6461: my $bubble = substr($currquest,$ans,1);
6462: $record->{"scantron.$ansnum.answer"} = $bubble;
6463: $ansnum++;
6464: }
6465: }
6466: return $ansnum;
6467: }
6468:
6469: sub scantron_validator_positional {
6470: my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
6471: $whichline,$alphabet,$record,$scantron_config,$scan_data,
6472: $randomorder,$randompick,$respnumlookup) = @_;
6473:
6474: # Otherwise there's a positional notation;
6475: # each bubble line requires Qlength items, and there are filled in
6476: # bubbles for each case where there 'Qon' characters.
6477: #
6478:
6479: my @array=split($$scantron_config{'Qon'},$currquest,-1);
6480:
6481: # If the split only gives us one element.. the full length of the
6482: # answer string, no bubbles are filled in:
6483:
6484: if ($answers_needed eq '') {
6485: return;
6486: }
6487:
6488: if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
6489: for (my $ans=0; $ans<$answers_needed; $ans++ ) {
6490: $record->{"scantron.$ansnum.answer"}='';
6491: $ansnum++;
6492: }
6493: if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
6494: push(@{$record->{"scantron.missingerror"}},$quest_id);
6495: }
6496: } elsif (scalar(@array) == 2) {
6497: my $location = length($array[0]);
6498: my $line_num = int($location / $$scantron_config{'Qlength'});
6499: my $bubble = $alphabet->[$location % $$scantron_config{'Qlength'}];
6500: for (my $ans=0; $ans<$answers_needed; $ans++) {
6501: if ($ans eq $line_num) {
6502: $record->{"scantron.$ansnum.answer"} = $bubble;
6503: } else {
6504: $record->{"scantron.$ansnum.answer"} = ' ';
6505: }
6506: $ansnum++;
6507: }
6508: } else {
6509: # If there's more than one instance of a bubble character
6510: # That's a double bubble; with positional notation we can
6511: # record all the bubbles filled in as well as the
6512: # fact this response consists of multiple bubbles.
6513: #
6514: my $responsenum = $questnum-1;
6515: if (($randompick || $randomorder) && (ref($respnumlookup) eq 'HASH')) {
6516: $responsenum = $respnumlookup->{$questnum-1}
6517: }
6518: if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
6519: ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
6520: ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
6521: ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
6522: ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
6523: ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
6524: my $doubleerror = 0;
6525: while (($currquest >= $$scantron_config{'Qlength'}) &&
6526: (!$doubleerror)) {
6527: my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
6528: $currquest = substr($currquest,$$scantron_config{'Qlength'});
6529: my @currarray = split($$scantron_config{'Qon'},$currline,-1);
6530: if (length(@currarray) > 2) {
6531: $doubleerror = 1;
6532: }
6533: }
6534: if ($doubleerror) {
6535: push(@{$record->{'scantron.doubleerror'}},$quest_id);
6536: }
6537: } else {
6538: push(@{$record->{'scantron.doubleerror'}},$quest_id);
6539: }
6540: my $item = $ansnum;
6541: for (my $ans=0; $ans<$answers_needed; $ans++) {
6542: $record->{"scantron.$item.answer"} = '';
6543: $item ++;
6544: }
6545:
6546: my @ans=@array;
6547: my $i=0;
6548: my $increment = 0;
6549: while ($#ans) {
6550: $i+=length($ans[0]) + $increment;
6551: my $line = int($i/$$scantron_config{'Qlength'} + $ansnum);
6552: my $bubble = $i%$$scantron_config{'Qlength'};
6553: $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
6554: shift(@ans);
6555: $increment = 1;
6556: }
6557: $ansnum += $answers_needed;
6558: }
6559: return $ansnum;
6560: }
6561:
6562: =pod
6563:
6564: =item scantron_add_delay
6565:
6566: Adds an error message that occurred during the grading phase to a
6567: queue of messages to be shown after grading pass is complete
6568:
6569: Arguments:
6570: $delayqueue - arrary ref of hash ref of error messages
6571: $scanline - the scanline that caused the error
6572: $errormesage - the error message
6573: $errorcode - a numeric code for the error
6574:
6575: Side Effects:
6576: updates the $delayqueue to have a new hash ref of the error
6577:
6578: =cut
6579:
6580: sub scantron_add_delay {
6581: my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
6582: push(@$delayqueue,
6583: {'line' => $scanline, 'emsg' => $errormessage,
6584: 'ecode' => $errorcode }
6585: );
6586: }
6587:
6588: =pod
6589:
6590: =item scantron_find_student
6591:
6592: Finds the username for the current scanline
6593:
6594: Arguments:
6595: $scantron_record - hash result from scantron_parse_scanline
6596: $scan_data - hash of correction information
6597: (see &scantron_getfile() form more information)
6598: $idmap - hash from &username_to_idmap()
6599: $line - number of current scanline
6600:
6601: Returns:
6602: Either 'username:domain' or undef if unknown
6603:
6604: =cut
6605:
6606: sub scantron_find_student {
6607: my ($scantron_record,$scan_data,$idmap,$line)=@_;
6608: my $scanID=$$scantron_record{'scantron.ID'};
6609: if ($scanID =~ /^\s*$/) {
6610: return &scan_data($scan_data,"$line.user");
6611: }
6612: foreach my $id (keys(%$idmap)) {
6613: if (lc($id) eq lc($scanID)) {
6614: return $$idmap{$id};
6615: }
6616: }
6617: return undef;
6618: }
6619:
6620: =pod
6621:
6622: =item scantron_filter
6623:
6624: Filter sub for lonnavmaps, filters out hidden resources if ignore
6625: hidden resources was selected
6626:
6627: =cut
6628:
6629: sub scantron_filter {
6630: my ($curres)=@_;
6631:
6632: if (ref($curres) && $curres->is_problem()) {
6633: # if the user has asked to not have either hidden
6634: # or 'randomout' controlled resources to be graded
6635: # don't include them
6636: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
6637: && $curres->randomout) {
6638: return 0;
6639: }
6640: return 1;
6641: }
6642: return 0;
6643: }
6644:
6645: =pod
6646:
6647: =item scantron_process_corrections
6648:
6649: Gets correction information out of submitted form data and corrects
6650: the scanline
6651:
6652: =cut
6653:
6654: sub scantron_process_corrections {
6655: my ($r) = @_;
6656: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6657: my ($scanlines,$scan_data)=&scantron_getfile();
6658: my $classlist=&Apache::loncoursedata::get_classlist();
6659: my $which=$env{'form.scantron_line'};
6660: my $line=&scantron_get_line($scanlines,$scan_data,$which);
6661: my ($skip,$err,$errmsg);
6662: if ($env{'form.scantron_skip_record'}) {
6663: $skip=1;
6664: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
6665: my $newstudent=$env{'form.scantron_username'}.':'.
6666: $env{'form.scantron_domain'};
6667: my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
6668: ($line,$err,$errmsg)=
6669: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
6670: 'ID',{'newid'=>$newid,
6671: 'username'=>$env{'form.scantron_username'},
6672: 'domain'=>$env{'form.scantron_domain'}});
6673: } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
6674: my $resolution=$env{'form.scantron_CODE_resolution'};
6675: my $newCODE;
6676: my %args;
6677: if ($resolution eq 'use_unfound') {
6678: $newCODE='use_unfound';
6679: } elsif ($resolution eq 'use_found') {
6680: $newCODE=$env{'form.scantron_CODE_selectedvalue'};
6681: } elsif ($resolution eq 'use_typed') {
6682: $newCODE=$env{'form.scantron_CODE_newvalue'};
6683: } elsif ($resolution =~ /^use_closest_(\d+)/) {
6684: $newCODE=$env{"form.scantron_CODE_closest_$1"};
6685: }
6686: if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
6687: $args{'CODE_ignore_dup'}=1;
6688: }
6689: $args{'CODE'}=$newCODE;
6690: ($line,$err,$errmsg)=
6691: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
6692: 'CODE',\%args);
6693: } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
6694: foreach my $question (split(',',$env{'form.scantron_questions'})) {
6695: ($line,$err,$errmsg)=
6696: &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
6697: $which,'answer',
6698: { 'question'=>$question,
6699: 'response'=>$env{"form.scantron_correct_Q_$question"},
6700: 'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
6701: if ($err) { last; }
6702: }
6703: }
6704: if ($err) {
6705: $r->print(
6706: '<p class="LC_error">'
6707: .&mt('Unable to accept last correction, an error occurred: [_1]',
6708: $errmsg)
6709: .'</p>');
6710: } else {
6711: &scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
6712: &scantron_putfile($scanlines,$scan_data);
6713: }
6714: }
6715:
6716: =pod
6717:
6718: =item reset_skipping_status
6719:
6720: Forgets the current set of remember skipped scanlines (and thus
6721: reverts back to considering all lines in the
6722: scantron_skipped_<filename> file)
6723:
6724: =cut
6725:
6726: sub reset_skipping_status {
6727: my ($scanlines,$scan_data)=&scantron_getfile();
6728: &scan_data($scan_data,'remember_skipping',undef,1);
6729: &scantron_putfile(undef,$scan_data);
6730: }
6731:
6732: =pod
6733:
6734: =item start_skipping
6735:
6736: Marks a scanline to be skipped.
6737:
6738: =cut
6739:
6740: sub start_skipping {
6741: my ($scan_data,$i)=@_;
6742: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
6743: if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
6744: $remembered{$i}=2;
6745: } else {
6746: $remembered{$i}=1;
6747: }
6748: &scan_data($scan_data,'remember_skipping',join(':',%remembered));
6749: }
6750:
6751: =pod
6752:
6753: =item should_be_skipped
6754:
6755: Checks whether a scanline should be skipped.
6756:
6757: =cut
6758:
6759: sub should_be_skipped {
6760: my ($scanlines,$scan_data,$i)=@_;
6761: if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
6762: # not redoing old skips
6763: if ($scanlines->{'skipped'}[$i]) { return 1; }
6764: return 0;
6765: }
6766: my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
6767:
6768: if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
6769: return 0;
6770: }
6771: return 1;
6772: }
6773:
6774: =pod
6775:
6776: =item remember_current_skipped
6777:
6778: Discovers what scanlines are in the scantron_skipped_<filename>
6779: file and remembers them into scan_data for later use.
6780:
6781: =cut
6782:
6783: sub remember_current_skipped {
6784: my ($scanlines,$scan_data)=&scantron_getfile();
6785: my %to_remember;
6786: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
6787: if ($scanlines->{'skipped'}[$i]) {
6788: $to_remember{$i}=1;
6789: }
6790: }
6791:
6792: &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
6793: &scantron_putfile(undef,$scan_data);
6794: }
6795:
6796: =pod
6797:
6798: =item check_for_error
6799:
6800: Checks if there was an error when attempting to remove a specific
6801: scantron_.. bubblesheet data file. Prints out an error if
6802: something went wrong.
6803:
6804: =cut
6805:
6806: sub check_for_error {
6807: my ($r,$result)=@_;
6808: if ($result ne 'ok' && $result ne 'not_found' ) {
6809: $r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
6810: }
6811: }
6812:
6813: =pod
6814:
6815: =item scantron_warning_screen
6816:
6817: Interstitial screen to make sure the operator has selected the
6818: correct options before we start the validation phase.
6819:
6820: =cut
6821:
6822: sub scantron_warning_screen {
6823: my ($button_text)=@_;
6824: my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
6825: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6826: my $CODElist;
6827: if ($scantron_config{'CODElocation'} &&
6828: $scantron_config{'CODEstart'} &&
6829: $scantron_config{'CODElength'}) {
6830: $CODElist=$env{'form.scantron_CODElist'};
6831: if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">'.&mt('None').'</span>'; }
6832: $CODElist=
6833: '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
6834: $env{'form.scantron_CODElist'}.'</tt></td></tr>';
6835: }
6836: my $lastbubblepoints;
6837: if ($env{'form.scantron_lastbubblepoints'} ne '') {
6838: $lastbubblepoints =
6839: '<tr><td><b>'.&mt('Hand-graded items: points from last bubble in row').'</b></td><td><tt>'.
6840: $env{'form.scantron_lastbubblepoints'}.'</tt></td></tr>';
6841: }
6842: return ('
6843: <p>
6844: <span class="LC_warning">
6845: '.&mt("Please double check the information below before clicking on '[_1]'",&mt($button_text)).'</span>
6846: </p>
6847: <table>
6848: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
6849: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
6850: '.$CODElist.$lastbubblepoints.'
6851: </table>
6852: <br />
6853: <p> '.&mt("If this information is correct, please click on '[_1]'.",&mt($button_text)).'</p>
6854: <p> '.&mt("If something is incorrect, please click the 'Grading Menu' button to start over.").'</p>
6855:
6856: <br />
6857: ');
6858: }
6859:
6860: =pod
6861:
6862: =item scantron_do_warning
6863:
6864: Check if the operator has picked something for all required
6865: fields. Error out if something is missing.
6866:
6867: =cut
6868:
6869: sub scantron_do_warning {
6870: my ($r)=@_;
6871: my ($symb)=&get_symb($r);
6872: if (!$symb) {return '';}
6873: my $default_form_data=&defaultFormData($symb);
6874: $r->print(&scantron_form_start().$default_form_data);
6875: if ( $env{'form.selectpage'} eq '' ||
6876: $env{'form.scantron_selectfile'} eq '' ||
6877: $env{'form.scantron_format'} eq '' ) {
6878: $r->print("<p>".&mt('You have forgotten to specify some information. Please go Back and try again.')."</p>");
6879: if ( $env{'form.selectpage'} eq '') {
6880: $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
6881: }
6882: if ( $env{'form.scantron_selectfile'} eq '') {
6883: $r->print('<p><span class="LC_error">'.&mt("You have not selected a file that contains the student's response data.").'</span></p>');
6884: }
6885: if ( $env{'form.scantron_format'} eq '') {
6886: $r->print('<p><span class="LC_error">'.&mt("You have not selected the format of the student's response data.").'</span></p>');
6887: }
6888: } else {
6889: my $warning=&scantron_warning_screen('Grading: Validate Records');
6890: my $bubbledbyhand=&hand_bubble_option();
6891: $r->print('
6892: '.$warning.$bubbledbyhand.'
6893: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
6894: <input type="hidden" name="command" value="scantron_validate" />
6895: ');
6896: }
6897: $r->print("</form><br />".&show_grading_menu_form($symb));
6898: return '';
6899: }
6900:
6901: =pod
6902:
6903: =item scantron_form_start
6904:
6905: html hidden input for remembering all selected grading options
6906:
6907: =cut
6908:
6909: sub scantron_form_start {
6910: my ($max_bubble)=@_;
6911: my $result= <<SCANTRONFORM;
6912: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
6913: <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
6914: <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
6915: <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
6916: <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
6917: <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
6918: <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
6919: <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
6920: <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
6921: <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
6922: SCANTRONFORM
6923:
6924: my $line = 0;
6925: while (defined($env{"form.scantron.bubblelines.$line"})) {
6926: my $chunk =
6927: '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
6928: $chunk .=
6929: '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
6930: $chunk .=
6931: '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
6932: $chunk .=
6933: '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
6934: $chunk .=
6935: '<input type="hidden" name="scantron.residpart.'.$line.'" value="'.$env{"form.scantron.residpart.$line"}.'" />'."\n";
6936: $result .= $chunk;
6937: $line++;
6938: }
6939: return $result;
6940: }
6941:
6942: =pod
6943:
6944: =item scantron_validate_file
6945:
6946: Dispatch routine for doing validation of a bubblesheet data file.
6947:
6948: Also processes any necessary information resets that need to
6949: occur before validation begins (ignore previous corrections,
6950: restarting the skipped records processing)
6951:
6952: =cut
6953:
6954: sub scantron_validate_file {
6955: my ($r) = @_;
6956: my ($symb)=&get_symb($r);
6957: if (!$symb) {return '';}
6958: my $default_form_data=&defaultFormData($symb);
6959:
6960: # do the detection of only doing skipped records first before we delete
6961: # them when doing the corrections reset
6962: if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
6963: &reset_skipping_status();
6964: }
6965: if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
6966: &remember_current_skipped();
6967: $env{'form.scantron_options_redo'}='redo_skipped_ready';
6968: }
6969:
6970: if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
6971: &check_for_error($r,&scantron_remove_file('corrected'));
6972: &check_for_error($r,&scantron_remove_file('skipped'));
6973: &check_for_error($r,&scantron_remove_scan_data());
6974: $env{'form.scantron_options_ignore'}='done';
6975: }
6976:
6977: if ($env{'form.scantron_corrections'}) {
6978: &scantron_process_corrections($r);
6979: }
6980: $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
6981: #get the student pick code ready
6982: $r->print(&Apache::loncommon::studentbrowser_javascript());
6983: my $nav_error;
6984: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
6985: my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
6986: if ($nav_error) {
6987: $r->print(&navmap_errormsg());
6988: return '';
6989: }
6990: my $result=&scantron_form_start($max_bubble).$default_form_data;
6991: if ($env{'form.scantron_lastbubblepoints'} ne '') {
6992: $result .= '<input type="hidden" name="scantron_lastbubblepoints" value="'.$env{'form.scantron_lastbubblepoints'}.'" />';
6993: }
6994: $r->print($result);
6995:
6996: my @validate_phases=( 'sequence',
6997: 'ID',
6998: 'CODE',
6999: 'doublebubble',
7000: 'missingbubbles');
7001: if (!$env{'form.validatepass'}) {
7002: $env{'form.validatepass'} = 0;
7003: }
7004: my $currentphase=$env{'form.validatepass'};
7005:
7006:
7007: my $stop=0;
7008: while (!$stop && $currentphase < scalar(@validate_phases)) {
7009: $r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
7010: $r->rflush();
7011:
7012: my $which="scantron_validate_".$validate_phases[$currentphase];
7013: {
7014: no strict 'refs';
7015: ($stop,$currentphase)=&$which($r,$currentphase);
7016: }
7017: }
7018: if (!$stop) {
7019: my $warning=&scantron_warning_screen('Start Grading');
7020: $r->print(&mt('Validation process complete.').'<br />'.
7021: $warning.
7022: &mt('Perform verification for each student after storage of submissions?').
7023: ' <span class="LC_nobreak"><label>'.
7024: '<input type="radio" name="verifyrecord" value="1" />'.&mt('Yes').'</label>'.
7025: (' 'x3).'<label>'.
7026: '<input type="radio" name="verifyrecord" value="0" checked="checked" />'.&mt('No').
7027: '</label></span><br />'.
7028: &mt('Grading will take longer if you use verification.').'<br />'.
7029: &mt("Alternatively, the 'Review bubblesheet data' utility (see grading menu) can be used for all students after grading is complete.").'<br /><br />'.
7030: '<input type="submit" name="submit" value="'.&mt('Start Grading').'" />'.
7031: '<input type="hidden" name="command" value="scantron_process" />'."\n");
7032: } else {
7033: $r->print('<input type="hidden" name="command" value="scantron_validate" />');
7034: $r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
7035: }
7036: if ($stop) {
7037: if ($validate_phases[$currentphase] eq 'sequence') {
7038: $r->print('<input type="submit" name="submit" value="'.&mt('Ignore').' → " />');
7039: $r->print(' '.&mt('this error').' <br />');
7040:
7041: $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
7042: } else {
7043: if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
7044: $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue').' →" onclick="javascript:verify_bubble_radio(this.form)" />');
7045: } else {
7046: $r->print('<input type="submit" name="submit" value="'.&mt('Continue').' →" />');
7047: }
7048: $r->print(' '.&mt('using corrected info').' <br />');
7049: $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
7050: $r->print(" ".&mt("this scanline saving it for later."));
7051: }
7052: }
7053: $r->print(" </form><br />".&show_grading_menu_form($symb));
7054: return '';
7055: }
7056:
7057:
7058: =pod
7059:
7060: =item scantron_remove_file
7061:
7062: Removes the requested bubblesheet data file, makes sure that
7063: scantron_original_<filename> is never removed
7064:
7065:
7066: =cut
7067:
7068: sub scantron_remove_file {
7069: my ($which)=@_;
7070: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7071: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7072: my $file='scantron_';
7073: if ($which eq 'corrected' || $which eq 'skipped') {
7074: $file.=$which.'_';
7075: } else {
7076: return 'refused';
7077: }
7078: $file.=$env{'form.scantron_selectfile'};
7079: return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
7080: }
7081:
7082:
7083: =pod
7084:
7085: =item scantron_remove_scan_data
7086:
7087: Removes all scan_data correction for the requested bubblesheet
7088: data file. (In the case that both the are doing skipped records we need
7089: to remember the old skipped lines for the time being so that element
7090: persists for a while.)
7091:
7092: =cut
7093:
7094: sub scantron_remove_scan_data {
7095: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7096: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7097: my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
7098: my @todelete;
7099: my $filename=$env{'form.scantron_selectfile'};
7100: foreach my $key (@keys) {
7101: if ($key=~/^\Q$filename\E_/) {
7102: if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
7103: $key=~/remember_skipping/) {
7104: next;
7105: }
7106: push(@todelete,$key);
7107: }
7108: }
7109: my $result;
7110: if (@todelete) {
7111: $result = &Apache::lonnet::del('nohist_scantrondata',
7112: \@todelete,$cdom,$cname);
7113: } else {
7114: $result = 'ok';
7115: }
7116: return $result;
7117: }
7118:
7119:
7120: =pod
7121:
7122: =item scantron_getfile
7123:
7124: Fetches the requested bubblesheet data file (all 3 versions), and
7125: the scan_data hash
7126:
7127: Arguments:
7128: None
7129:
7130: Returns:
7131: 2 hash references
7132:
7133: - first one has
7134: orig -
7135: corrected -
7136: skipped - each of which points to an array ref of the specified
7137: file broken up into individual lines
7138: count - number of scanlines
7139:
7140: - second is the scan_data hash possible keys are
7141: ($number refers to scanline numbered $number and thus the key affects
7142: only that scanline
7143: $bubline refers to the specific bubble line element and the aspects
7144: refers to that specific bubble line element)
7145:
7146: $number.user - username:domain to use
7147: $number.CODE_ignore_dup
7148: - ignore the duplicate CODE error
7149: $number.useCODE
7150: - use the CODE in the scanline as is
7151: $number.no_bubble.$bubline
7152: - it is valid that there is no bubbled in bubble
7153: at $number $bubline
7154: remember_skipping
7155: - a frozen hash containing keys of $number and values
7156: of either
7157: 1 - we are on a 'do skipped records pass' and plan
7158: on processing this line
7159: 2 - we are on a 'do skipped records pass' and this
7160: scanline has been marked to skip yet again
7161:
7162: =cut
7163:
7164: sub scantron_getfile {
7165: #FIXME really would prefer a scantron directory
7166: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7167: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7168: my $lines;
7169: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
7170: 'scantron_orig_'.$env{'form.scantron_selectfile'});
7171: my %scanlines;
7172: $scanlines{'orig'}=[(split("\n",$lines,-1))];
7173: my $temp=$scanlines{'orig'};
7174: $scanlines{'count'}=$#$temp;
7175:
7176: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
7177: 'scantron_corrected_'.$env{'form.scantron_selectfile'});
7178: if ($lines eq '-1') {
7179: $scanlines{'corrected'}=[];
7180: } else {
7181: $scanlines{'corrected'}=[(split("\n",$lines,-1))];
7182: }
7183: $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
7184: 'scantron_skipped_'.$env{'form.scantron_selectfile'});
7185: if ($lines eq '-1') {
7186: $scanlines{'skipped'}=[];
7187: } else {
7188: $scanlines{'skipped'}=[(split("\n",$lines,-1))];
7189: }
7190: my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
7191: if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
7192: my %scan_data = @tmp;
7193: return (\%scanlines,\%scan_data);
7194: }
7195:
7196: =pod
7197:
7198: =item lonnet_putfile
7199:
7200: Wrapper routine to call &Apache::lonnet::finishuserfileupload
7201:
7202: Arguments:
7203: $contents - data to store
7204: $filename - filename to store $contents into
7205:
7206: Returns:
7207: result value from &Apache::lonnet::finishuserfileupload
7208:
7209: =cut
7210:
7211: sub lonnet_putfile {
7212: my ($contents,$filename)=@_;
7213: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
7214: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7215: $env{'form.sillywaytopassafilearound'}=$contents;
7216: &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
7217:
7218: }
7219:
7220: =pod
7221:
7222: =item scantron_putfile
7223:
7224: Stores the current version of the bubblesheet data files, and the
7225: scan_data hash. (Does not modify the original version only the
7226: corrected and skipped versions.
7227:
7228: Arguments:
7229: $scanlines - hash ref that looks like the first return value from
7230: &scantron_getfile()
7231: $scan_data - hash ref that looks like the second return value from
7232: &scantron_getfile()
7233:
7234: =cut
7235:
7236: sub scantron_putfile {
7237: my ($scanlines,$scan_data) = @_;
7238: #FIXME really would prefer a scantron directory
7239: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7240: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7241: if ($scanlines) {
7242: my $prefix='scantron_';
7243: # no need to update orig, shouldn't change
7244: # &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
7245: # $env{'form.scantron_selectfile'});
7246: &lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
7247: $prefix.'corrected_'.
7248: $env{'form.scantron_selectfile'});
7249: &lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
7250: $prefix.'skipped_'.
7251: $env{'form.scantron_selectfile'});
7252: }
7253: &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
7254: }
7255:
7256: =pod
7257:
7258: =item scantron_get_line
7259:
7260: Returns the correct version of the scanline
7261:
7262: Arguments:
7263: $scanlines - hash ref that looks like the first return value from
7264: &scantron_getfile()
7265: $scan_data - hash ref that looks like the second return value from
7266: &scantron_getfile()
7267: $i - number of the requested line (starts at 0)
7268:
7269: Returns:
7270: A scanline, (either the original or the corrected one if it
7271: exists), or undef if the requested scanline should be
7272: skipped. (Either because it's an skipped scanline, or it's an
7273: unskipped scanline and we are not doing a 'do skipped scanlines'
7274: pass.
7275:
7276: =cut
7277:
7278: sub scantron_get_line {
7279: my ($scanlines,$scan_data,$i)=@_;
7280: if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
7281: #if ($scanlines->{'skipped'}[$i]) { return undef; }
7282: if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
7283: return $scanlines->{'orig'}[$i];
7284: }
7285:
7286: =pod
7287:
7288: =item scantron_todo_count
7289:
7290: Counts the number of scanlines that need processing.
7291:
7292: Arguments:
7293: $scanlines - hash ref that looks like the first return value from
7294: &scantron_getfile()
7295: $scan_data - hash ref that looks like the second return value from
7296: &scantron_getfile()
7297:
7298: Returns:
7299: $count - number of scanlines to process
7300:
7301: =cut
7302:
7303: sub get_todo_count {
7304: my ($scanlines,$scan_data)=@_;
7305: my $count=0;
7306: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7307: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7308: if ($line=~/^[\s\cz]*$/) { next; }
7309: $count++;
7310: }
7311: return $count;
7312: }
7313:
7314: =pod
7315:
7316: =item scantron_put_line
7317:
7318: Updates the 'corrected' or 'skipped' versions of the bubblesheet
7319: data file.
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: $i - line number to update
7327: $newline - contents of the updated scanline
7328: $skip - if true make the line for skipping and update the
7329: 'skipped' file
7330:
7331: =cut
7332:
7333: sub scantron_put_line {
7334: my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
7335: if ($skip) {
7336: $scanlines->{'skipped'}[$i]=$newline;
7337: &start_skipping($scan_data,$i);
7338: return;
7339: }
7340: $scanlines->{'corrected'}[$i]=$newline;
7341: }
7342:
7343: =pod
7344:
7345: =item scantron_clear_skip
7346:
7347: Remove a line from the 'skipped' file
7348:
7349: Arguments:
7350: $scanlines - hash ref that looks like the first return value from
7351: &scantron_getfile()
7352: $scan_data - hash ref that looks like the second return value from
7353: &scantron_getfile()
7354: $i - line number to update
7355:
7356: =cut
7357:
7358: sub scantron_clear_skip {
7359: my ($scanlines,$scan_data,$i)=@_;
7360: if (exists($scanlines->{'skipped'}[$i])) {
7361: undef($scanlines->{'skipped'}[$i]);
7362: return 1;
7363: }
7364: return 0;
7365: }
7366:
7367: =pod
7368:
7369: =item scantron_filter_not_exam
7370:
7371: Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
7372: filter out resources that are not marked as 'exam' mode
7373:
7374: =cut
7375:
7376: sub scantron_filter_not_exam {
7377: my ($curres)=@_;
7378:
7379: if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
7380: # if the user has asked to not have either hidden
7381: # or 'randomout' controlled resources to be graded
7382: # don't include them
7383: if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
7384: && $curres->randomout) {
7385: return 0;
7386: }
7387: return 1;
7388: }
7389: return 0;
7390: }
7391:
7392: =pod
7393:
7394: =item scantron_validate_sequence
7395:
7396: Validates the selected sequence, checking for resource that are
7397: not set to exam mode.
7398:
7399: =cut
7400:
7401: sub scantron_validate_sequence {
7402: my ($r,$currentphase) = @_;
7403:
7404: my $navmap=Apache::lonnavmaps::navmap->new();
7405: unless (ref($navmap)) {
7406: $r->print(&navmap_errormsg());
7407: return (1,$currentphase);
7408: }
7409: my (undef,undef,$sequence)=
7410: &Apache::lonnet::decode_symb($env{'form.selectpage'});
7411:
7412: my $map=$navmap->getResourceByUrl($sequence);
7413:
7414: $r->print('<input type="hidden" name="validate_sequence_exam"
7415: value="ignore" />');
7416: if ($env{'form.validate_sequence_exam'} ne 'ignore') {
7417: my @resources=
7418: $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
7419: if (@resources) {
7420: $r->print('<p class="LC_warning">'
7421: .&mt('Some resources in the sequence currently are not set to'
7422: .' exam mode. Grading these resources currently may not'
7423: .' work correctly.')
7424: .'</p>'
7425: );
7426: return (1,$currentphase);
7427: }
7428: }
7429:
7430: return (0,$currentphase+1);
7431: }
7432:
7433:
7434:
7435: sub scantron_validate_ID {
7436: my ($r,$currentphase) = @_;
7437:
7438: #get student info
7439: my $classlist=&Apache::loncoursedata::get_classlist();
7440: my %idmap=&username_to_idmap($classlist);
7441:
7442: #get scantron line setup
7443: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
7444: my ($scanlines,$scan_data)=&scantron_getfile();
7445:
7446: my $nav_error;
7447: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble_lines.. array.
7448: if ($nav_error) {
7449: $r->print(&navmap_errormsg());
7450: return(1,$currentphase);
7451: }
7452:
7453: my %found=('ids'=>{},'usernames'=>{});
7454: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
7455: my $line=&scantron_get_line($scanlines,$scan_data,$i);
7456: if ($line=~/^[\s\cz]*$/) { next; }
7457: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
7458: $scan_data);
7459: my $id=$$scan_record{'scantron.ID'};
7460: my $found;
7461: foreach my $checkid (keys(%idmap)) {
7462: if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
7463: }
7464: if ($found) {
7465: my $username=$idmap{$found};
7466: if ($found{'ids'}{$found}) {
7467: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
7468: $line,'duplicateID',$found);
7469: return(1,$currentphase);
7470: } elsif ($found{'usernames'}{$username}) {
7471: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
7472: $line,'duplicateID',$username);
7473: return(1,$currentphase);
7474: }
7475: #FIXME store away line we previously saw the ID on to use above
7476: $found{'ids'}{$found}++;
7477: $found{'usernames'}{$username}++;
7478: } else {
7479: if ($id =~ /^\s*$/) {
7480: my $username=&scan_data($scan_data,"$i.user");
7481: if (defined($username) && $found{'usernames'}{$username}) {
7482: &scantron_get_correction($r,$i,$scan_record,
7483: \%scantron_config,
7484: $line,'duplicateID',$username);
7485: return(1,$currentphase);
7486: } elsif (!defined($username)) {
7487: &scantron_get_correction($r,$i,$scan_record,
7488: \%scantron_config,
7489: $line,'incorrectID');
7490: return(1,$currentphase);
7491: }
7492: $found{'usernames'}{$username}++;
7493: } else {
7494: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
7495: $line,'incorrectID');
7496: return(1,$currentphase);
7497: }
7498: }
7499: }
7500:
7501: return (0,$currentphase+1);
7502: }
7503:
7504:
7505: sub scantron_get_correction {
7506: my ($r,$i,$scan_record,$scan_config,$line,$error,$arg,
7507: $randomorder,$randompick,$respnumlookup,$startline)=@_;
7508: #FIXME in the case of a duplicated ID the previous line, probably need
7509: #to show both the current line and the previous one and allow skipping
7510: #the previous one or the current one
7511:
7512: if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
7513: $r->print(
7514: '<p class="LC_warning">'
7515: .&mt('An error was detected ([_1]) for PaperID [_2]',
7516: "<b>$error</b>",
7517: '<tt>'.$$scan_record{'scantron.PaperID'}.'</tt>')
7518: ."</p> \n");
7519: } else {
7520: $r->print(
7521: '<p class="LC_warning">'
7522: .&mt('An error was detected ([_1]) in scanline [_2] [_3]',
7523: "<b>$error</b>", $i, "<pre>$line</pre>")
7524: ."</p> \n");
7525: }
7526: my $message =
7527: '<p>'
7528: .&mt('The ID on the form is [_1]',
7529: "<tt>$$scan_record{'scantron.ID'}</tt>")
7530: .'<br />'
7531: .&mt('The name on the paper is [_1], [_2]',
7532: $$scan_record{'scantron.LastName'},
7533: $$scan_record{'scantron.FirstName'})
7534: .'</p>';
7535:
7536: $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
7537: $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
7538: # Array populated for doublebubble or
7539: my @lines_to_correct; # missingbubble errors to build javascript
7540: # to validate radio button checking
7541:
7542: if ($error =~ /ID$/) {
7543: if ($error eq 'incorrectID') {
7544: $r->print('<p class="LC_warning">'.&mt("The encoded ID is not in the classlist").
7545: "</p>\n");
7546: } elsif ($error eq 'duplicateID') {
7547: $r->print('<p class="LC_warning">'.&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
7548: }
7549: $r->print($message);
7550: $r->print("<p>".&mt("How should I handle this?")." <br /> \n");
7551: $r->print("\n<ul><li> ");
7552: #FIXME it would be nice if this sent back the user ID and
7553: #could do partial userID matches
7554: $r->print(&Apache::loncommon::selectstudent_link('scantronupload',
7555: 'scantron_username','scantron_domain'));
7556: $r->print(": <input type='text' name='scantron_username' value='' />");
7557: $r->print("\n:\n".
7558: &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
7559:
7560: $r->print('</li>');
7561: } elsif ($error =~ /CODE$/) {
7562: if ($error eq 'incorrectCODE') {
7563: $r->print('<p class="LC_warning">'.&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
7564: } elsif ($error eq 'duplicateCODE') {
7565: $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");
7566: }
7567: $r->print("<p>".&mt('The CODE on the form is [_1]',
7568: "<tt>'$$scan_record{'scantron.CODE'}'</tt>")
7569: ."</p>\n");
7570: $r->print($message);
7571: $r->print("<p>".&mt("How should I handle this?")."</p>\n");
7572: $r->print("\n<br /> ");
7573: my $i=0;
7574: if ($error eq 'incorrectCODE'
7575: && $$scan_record{'scantron.CODE'}=~/\S/ ) {
7576: my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
7577: if ($closest > 0) {
7578: foreach my $testcode (@{$closest}) {
7579: my $checked='';
7580: if (!$i) { $checked=' checked="checked"'; }
7581: $r->print("
7582: <label>
7583: <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i'$checked />
7584: ".&mt("Use the similar CODE [_1] instead.",
7585: "<b><tt>".$testcode."</tt></b>")."
7586: </label>
7587: <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
7588: $r->print("\n<br />");
7589: $i++;
7590: }
7591: }
7592: }
7593: if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
7594: my $checked; if (!$i) { $checked=' checked="checked"'; }
7595: $r->print("
7596: <label>
7597: <input type='radio' name='scantron_CODE_resolution' value='use_unfound'$checked />
7598: ".&mt("Use the CODE [_1] that was on the paper, ignoring the error.",
7599: "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
7600: </label>");
7601: $r->print("\n<br />");
7602: }
7603:
7604: $r->print(<<ENDSCRIPT);
7605: <script type="text/javascript">
7606: function change_radio(field) {
7607: var slct=document.scantronupload.scantron_CODE_resolution;
7608: var i;
7609: for (i=0;i<slct.length;i++) {
7610: if (slct[i].value==field) { slct[i].checked=true; }
7611: }
7612: }
7613: </script>
7614: ENDSCRIPT
7615: my $href="/adm/pickcode?".
7616: "form=".&escape("scantronupload").
7617: "&scantron_format=".&escape($env{'form.scantron_format'}).
7618: "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
7619: "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
7620: "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
7621: if ($env{'form.scantron_CODElist'} =~ /\S/) {
7622: $r->print("
7623: <label>
7624: <input type='radio' name='scantron_CODE_resolution' value='use_found' />
7625: ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
7626: "<a target='_blank' href='$href'>","</a>")."
7627: </label>
7628: ".&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\')" />'));
7629: $r->print("\n<br />");
7630: }
7631: $r->print("
7632: <label>
7633: <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
7634: ".&mt("Use [_1] as the CODE.",
7635: "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
7636: $r->print("\n<br /><br />");
7637: } elsif ($error eq 'doublebubble') {
7638: $r->print('<p class="LC_warning">'.&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
7639:
7640: # The form field scantron_questions is acutally a list of line numbers.
7641: # represented by this form so:
7642:
7643: my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
7644: $respnumlookup,$startline);
7645:
7646: $r->print('<input type="hidden" name="scantron_questions" value="'.
7647: $line_list.'" />');
7648: $r->print($message);
7649: $r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
7650: foreach my $question (@{$arg}) {
7651: my @linenums = &prompt_for_corrections($r,$question,$scan_config,
7652: $scan_record, $error,
7653: $randomorder,$randompick,
7654: $respnumlookup,$startline);
7655: push(@lines_to_correct,@linenums);
7656: }
7657: $r->print(&verify_bubbles_checked(@lines_to_correct));
7658: } elsif ($error eq 'missingbubble') {
7659: $r->print('<p class="LC_warning">'.&mt("There have been [_1]no[_2] bubbles scanned for some question(s)",'<b>','</b>')."</p>\n");
7660: $r->print($message);
7661: $r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
7662: $r->print(&mt("Some questions have no scanned bubbles.")."\n");
7663:
7664: # The form field scantron_questions is actually a list of line numbers not
7665: # a list of question numbers. Therefore:
7666: #
7667:
7668: my $line_list = &questions_to_line_list($arg,$randomorder,$randompick,
7669: $respnumlookup,$startline);
7670:
7671: $r->print('<input type="hidden" name="scantron_questions" value="'.
7672: $line_list.'" />');
7673: foreach my $question (@{$arg}) {
7674: my @linenums = &prompt_for_corrections($r,$question,$scan_config,
7675: $scan_record, $error,
7676: $randomorder,$randompick,
7677: $respnumlookup,$startline);
7678: push(@lines_to_correct,@linenums);
7679: }
7680: $r->print(&verify_bubbles_checked(@lines_to_correct));
7681: } else {
7682: $r->print("\n<ul>");
7683: }
7684: $r->print("\n</li></ul>");
7685: }
7686:
7687: sub verify_bubbles_checked {
7688: my (@ansnums) = @_;
7689: my $ansnumstr = join('","',@ansnums);
7690: my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
7691: my $output = (<<ENDSCRIPT);
7692: <script type="text/javascript">
7693: function verify_bubble_radio(form) {
7694: var ansnumArray = new Array ("$ansnumstr");
7695: var need_bubble_count = 0;
7696: for (var i=0; i<ansnumArray.length; i++) {
7697: if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
7698: var bubble_picked = 0;
7699: for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
7700: if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
7701: bubble_picked = 1;
7702: }
7703: }
7704: if (bubble_picked == 0) {
7705: need_bubble_count ++;
7706: }
7707: }
7708: }
7709: if (need_bubble_count) {
7710: alert("$warning");
7711: return;
7712: }
7713: form.submit();
7714: }
7715: </script>
7716: ENDSCRIPT
7717: return $output;
7718: }
7719:
7720: =pod
7721:
7722: =item questions_to_line_list
7723:
7724: Converts a list of questions into a string of comma separated
7725: line numbers in the answer sheet used by the questions. This is
7726: used to fill in the scantron_questions form field.
7727:
7728: Arguments:
7729: questions - Reference to an array of questions.
7730: randomorder - True if randomorder in use.
7731: randompick - True if randompick in use.
7732: respnumlookup - Reference to HASH mapping question numbers in bubble lines
7733: for current line to question number used for same question
7734: in "Master Seqence" (as seen by Course Coordinator).
7735: startline - Reference to hash where key is question number (0 is first)
7736: and key is number of first bubble line for current student
7737: or code-based randompick and/or randomorder.
7738:
7739: =cut
7740:
7741:
7742: sub questions_to_line_list {
7743: my ($questions,$randomorder,$randompick,$respnumlookup,$startline) = @_;
7744: my @lines;
7745:
7746: foreach my $item (@{$questions}) {
7747: my $question = $item;
7748: my ($first,$count,$last);
7749: if ($item =~ /^(\d+)\.(\d+)$/) {
7750: $question = $1;
7751: my $subquestion = $2;
7752: my $responsenum = $question-1;
7753: if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
7754: $responsenum = $respnumlookup->{$question-1};
7755: if (ref($startline) eq 'HASH') {
7756: $first = $startline->{$question-1} + 1;
7757: }
7758: } else {
7759: $first = $first_bubble_line{$responsenum} + 1;
7760: }
7761: my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
7762: my $subcount = 1;
7763: while ($subcount<$subquestion) {
7764: $first += $subans[$subcount-1];
7765: $subcount ++;
7766: }
7767: $count = $subans[$subquestion-1];
7768: } else {
7769: my $responsenum = $question-1;
7770: if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
7771: $responsenum = $respnumlookup->{$question-1};
7772: if (ref($startline) eq 'HASH') {
7773: $first = $startline->{$question-1} + 1;
7774: }
7775: } else {
7776: $first = $first_bubble_line{$responsenum} + 1;
7777: }
7778: $count = $bubble_lines_per_response{$responsenum};
7779: }
7780: $last = $first+$count-1;
7781: push(@lines, ($first..$last));
7782: }
7783: return join(',', @lines);
7784: }
7785:
7786: =pod
7787:
7788: =item prompt_for_corrections
7789:
7790: Prompts for a potentially multiline correction to the
7791: user's bubbling (factors out common code from scantron_get_correction
7792: for multi and missing bubble cases).
7793:
7794: Arguments:
7795: $r - Apache request object.
7796: $question - The question number to prompt for.
7797: $scan_config - The scantron file configuration hash.
7798: $scan_record - Reference to the hash that has the the parsed scanlines.
7799: $error - Type of error
7800: $randomorder - True if randomorder in use.
7801: $randompick - True if randompick in use.
7802: $respnumlookup - Reference to HASH mapping question numbers in bubble lines
7803: for current line to question number used for same question
7804: in "Master Seqence" (as seen by Course Coordinator).
7805: $startline - Reference to hash where key is question number (0 is first)
7806: and value is number of first bubble line for current student
7807: or code-based randompick and/or randomorder.
7808:
7809: Implicit inputs:
7810: %bubble_lines_per_response - Starting line numbers for each question.
7811: Numbered from 0 (but question numbers are from
7812: 1.
7813: %first_bubble_line - Starting bubble line for each question.
7814: %subdivided_bubble_lines - optionresponse, matchresponse and rankresponse
7815: type problems render as separate sub-questions,
7816: in exam mode. This hash contains a
7817: comma-separated list of the lines per
7818: sub-question.
7819: %responsetype_per_response - essayresponse, formularesponse,
7820: stringresponse, imageresponse, reactionresponse,
7821: and organicresponse type problem parts can have
7822: multiple lines per response if the weight
7823: assigned exceeds 10. In this case, only
7824: one bubble per line is permitted, but more
7825: than one line might contain bubbles, e.g.
7826: bubbling of: line 1 - J, line 2 - J,
7827: line 3 - B would assign 22 points.
7828:
7829: =cut
7830:
7831: sub prompt_for_corrections {
7832: my ($r, $question, $scan_config, $scan_record, $error, $randomorder,
7833: $randompick, $respnumlookup, $startline) = @_;
7834: my ($current_line,$lines);
7835: my @linenums;
7836: my $questionnum = $question;
7837: my ($first,$responsenum);
7838: if ($question =~ /^(\d+)\.(\d+)$/) {
7839: $question = $1;
7840: my $subquestion = $2;
7841: if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
7842: $responsenum = $respnumlookup->{$question-1};
7843: if (ref($startline) eq 'HASH') {
7844: $first = $startline->{$question-1};
7845: }
7846: } else {
7847: $responsenum = $question-1;
7848: $first = $first_bubble_line{$responsenum};
7849: }
7850: $current_line = $first + 1 ;
7851: my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
7852: my $subcount = 1;
7853: while ($subcount<$subquestion) {
7854: $current_line += $subans[$subcount-1];
7855: $subcount ++;
7856: }
7857: $lines = $subans[$subquestion-1];
7858: } else {
7859: if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH')) {
7860: $responsenum = $respnumlookup->{$question-1};
7861: if (ref($startline) eq 'HASH') {
7862: $first = $startline->{$question-1};
7863: }
7864: } else {
7865: $responsenum = $question-1;
7866: $first = $first_bubble_line{$responsenum};
7867: }
7868: $current_line = $first + 1;
7869: $lines = $bubble_lines_per_response{$responsenum};
7870: }
7871: if ($lines > 1) {
7872: $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
7873: if (($responsetype_per_response{$responsenum} eq 'essayresponse') ||
7874: ($responsetype_per_response{$responsenum} eq 'formularesponse') ||
7875: ($responsetype_per_response{$responsenum} eq 'stringresponse') ||
7876: ($responsetype_per_response{$responsenum} eq 'imageresponse') ||
7877: ($responsetype_per_response{$responsenum} eq 'reactionresponse') ||
7878: ($responsetype_per_response{$responsenum} eq 'organicresponse')) {
7879: $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 />');
7880: } else {
7881: $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
7882: }
7883: }
7884: for (my $i =0; $i < $lines; $i++) {
7885: my $selected = $$scan_record{"scantron.$current_line.answer"};
7886: &scantron_bubble_selector($r,$scan_config,$current_line,
7887: $questionnum,$error,split('', $selected));
7888: push(@linenums,$current_line);
7889: $current_line++;
7890: }
7891: if ($lines > 1) {
7892: $r->print("<hr /><br />");
7893: }
7894: return @linenums;
7895: }
7896:
7897: =pod
7898:
7899: =item scantron_bubble_selector
7900:
7901: Generates the html radiobuttons to correct a single bubble line
7902: possibly showing the existing the selected bubbles if known
7903:
7904: Arguments:
7905: $r - Apache request object
7906: $scan_config - hash from &get_scantron_config()
7907: $line - Number of the line being displayed.
7908: $questionnum - Question number (may include subquestion)
7909: $error - Type of error.
7910: @selected - Array of bubbles picked on this line.
7911:
7912: =cut
7913:
7914: sub scantron_bubble_selector {
7915: my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
7916: my $max=$$scan_config{'Qlength'};
7917:
7918: my $scmode=$$scan_config{'Qon'};
7919: if ($scmode eq 'number' || $scmode eq 'letter') {
7920: if (($$scan_config{'BubblesPerRow'} =~ /^\d+$/) &&
7921: ($$scan_config{'BubblesPerRow'} > 0)) {
7922: $max=$$scan_config{'BubblesPerRow'};
7923: if (($scmode eq 'number') && ($max > 10)) {
7924: $max = 10;
7925: } elsif (($scmode eq 'letter') && $max > 26) {
7926: $max = 26;
7927: }
7928: } else {
7929: $max = 10;
7930: }
7931: }
7932:
7933: my @alphabet=('A'..'Z');
7934: $r->print(&Apache::loncommon::start_data_table().
7935: &Apache::loncommon::start_data_table_row());
7936: $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
7937: for (my $i=0;$i<$max+1;$i++) {
7938: $r->print("\n".'<td align="center">');
7939: if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
7940: else { $r->print(' '); }
7941: $r->print('</td>');
7942: }
7943: $r->print(&Apache::loncommon::end_data_table_row().
7944: &Apache::loncommon::start_data_table_row());
7945: for (my $i=0;$i<$max;$i++) {
7946: $r->print("\n".
7947: '<td><label><input type="radio" name="scantron_correct_Q_'.
7948: $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
7949: }
7950: my $nobub_checked = ' ';
7951: if ($error eq 'missingbubble') {
7952: $nobub_checked = ' checked = "checked" ';
7953: }
7954: $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
7955: $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
7956: '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
7957: $line.'" value="'.$questionnum.'" /></td>');
7958: $r->print(&Apache::loncommon::end_data_table_row().
7959: &Apache::loncommon::end_data_table());
7960: }
7961:
7962: =pod
7963:
7964: =item num_matches
7965:
7966: Counts the number of characters that are the same between the two arguments.
7967:
7968: Arguments:
7969: $orig - CODE from the scanline
7970: $code - CODE to match against
7971:
7972: Returns:
7973: $count - integer count of the number of same characters between the
7974: two arguments
7975:
7976: =cut
7977:
7978: sub num_matches {
7979: my ($orig,$code) = @_;
7980: my @code=split(//,$code);
7981: my @orig=split(//,$orig);
7982: my $same=0;
7983: for (my $i=0;$i<scalar(@code);$i++) {
7984: if ($code[$i] eq $orig[$i]) { $same++; }
7985: }
7986: return $same;
7987: }
7988:
7989: =pod
7990:
7991: =item scantron_get_closely_matching_CODEs
7992:
7993: Cycles through all CODEs and finds the set that has the greatest
7994: number of same characters as the provided CODE
7995:
7996: Arguments:
7997: $allcodes - hash ref returned by &get_codes()
7998: $CODE - CODE from the current scanline
7999:
8000: Returns:
8001: 2 element list
8002: - first elements is number of how closely matching the best fit is
8003: (5 means best set has 5 matching characters)
8004: - second element is an arrary ref containing the set of valid CODEs
8005: that best fit the passed in CODE
8006:
8007: =cut
8008:
8009: sub scantron_get_closely_matching_CODEs {
8010: my ($allcodes,$CODE)=@_;
8011: my @CODEs;
8012: foreach my $testcode (sort(keys(%{$allcodes}))) {
8013: push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
8014: }
8015:
8016: return ($#CODEs,$CODEs[-1]);
8017: }
8018:
8019: =pod
8020:
8021: =item get_codes
8022:
8023: Builds a hash which has keys of all of the valid CODEs from the selected
8024: set of remembered CODEs.
8025:
8026: Arguments:
8027: $old_name - name of the set of remembered CODEs
8028: $cdom - domain of the course
8029: $cnum - internal course name
8030:
8031: Returns:
8032: %allcodes - keys are the valid CODEs, values are all 1
8033:
8034: =cut
8035:
8036: sub get_codes {
8037: my ($old_name, $cdom, $cnum) = @_;
8038: if (!$old_name) {
8039: $old_name=$env{'form.scantron_CODElist'};
8040: }
8041: if (!$cdom) {
8042: $cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
8043: }
8044: if (!$cnum) {
8045: $cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
8046: }
8047: my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
8048: $cdom,$cnum);
8049: my %allcodes;
8050: if ($result{"type\0$old_name"} eq 'number') {
8051: %allcodes=map {($_,1)} split(',',$result{$old_name});
8052: } else {
8053: %allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
8054: }
8055: return %allcodes;
8056: }
8057:
8058: =pod
8059:
8060: =item scantron_validate_CODE
8061:
8062: Validates all scanlines in the selected file to not have any
8063: invalid or underspecified CODEs and that none of the codes are
8064: duplicated if this was requested.
8065:
8066: =cut
8067:
8068: sub scantron_validate_CODE {
8069: my ($r,$currentphase) = @_;
8070: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
8071: if ($scantron_config{'CODElocation'} &&
8072: $scantron_config{'CODEstart'} &&
8073: $scantron_config{'CODElength'}) {
8074: if (!defined($env{'form.scantron_CODElist'})) {
8075: &FIXME_blow_up()
8076: }
8077: } else {
8078: return (0,$currentphase+1);
8079: }
8080:
8081: my %usedCODEs;
8082:
8083: my %allcodes=&get_codes();
8084:
8085: my $nav_error;
8086: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the lines per response array.
8087: if ($nav_error) {
8088: $r->print(&navmap_errormsg());
8089: return(1,$currentphase);
8090: }
8091:
8092: my ($scanlines,$scan_data)=&scantron_getfile();
8093: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
8094: my $line=&scantron_get_line($scanlines,$scan_data,$i);
8095: if ($line=~/^[\s\cz]*$/) { next; }
8096: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
8097: $scan_data);
8098: my $CODE=$$scan_record{'scantron.CODE'};
8099: my $error=0;
8100: if (!&Apache::lonnet::validCODE($CODE)) {
8101: &scantron_get_correction($r,$i,$scan_record,
8102: \%scantron_config,
8103: $line,'incorrectCODE',\%allcodes);
8104: return(1,$currentphase);
8105: }
8106: if (%allcodes && !exists($allcodes{$CODE})
8107: && !$$scan_record{'scantron.useCODE'}) {
8108: &scantron_get_correction($r,$i,$scan_record,
8109: \%scantron_config,
8110: $line,'incorrectCODE',\%allcodes);
8111: return(1,$currentphase);
8112: }
8113: if (exists($usedCODEs{$CODE})
8114: && $env{'form.scantron_CODEunique'} eq 'yes'
8115: && !$$scan_record{'scantron.CODE_ignore_dup'}) {
8116: &scantron_get_correction($r,$i,$scan_record,
8117: \%scantron_config,
8118: $line,'duplicateCODE',$usedCODEs{$CODE});
8119: return(1,$currentphase);
8120: }
8121: push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
8122: }
8123: return (0,$currentphase+1);
8124: }
8125:
8126: =pod
8127:
8128: =item scantron_validate_doublebubble
8129:
8130: Validates all scanlines in the selected file to not have any
8131: bubble lines with multiple bubbles marked.
8132:
8133: =cut
8134:
8135: sub scantron_validate_doublebubble {
8136: my ($r,$currentphase) = @_;
8137: #get student info
8138: my $classlist=&Apache::loncoursedata::get_classlist();
8139: my %idmap=&username_to_idmap($classlist);
8140: my (undef,undef,$sequence)=
8141: &Apache::lonnet::decode_symb($env{'form.selectpage'});
8142:
8143: #get scantron line setup
8144: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
8145: my ($scanlines,$scan_data)=&scantron_getfile();
8146:
8147: my $navmap = Apache::lonnavmaps::navmap->new();
8148: unless (ref($navmap)) {
8149: $r->print(&navmap_errormsg());
8150: return(1,$currentphase);
8151: }
8152: my $map=$navmap->getResourceByUrl($sequence);
8153: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
8154: my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
8155: %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
8156: my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
8157:
8158: my $nav_error;
8159: if (ref($map)) {
8160: $randomorder = $map->randomorder();
8161: $randompick = $map->randompick();
8162: if ($randomorder || $randompick) {
8163: $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
8164: if ($nav_error) {
8165: $r->print(&navmap_errormsg());
8166: return(1,$currentphase);
8167: }
8168: &graders_resources_pass(\@resources,\%grader_partids_by_symb,
8169: \%grader_randomlists_by_symb,$bubbles_per_row);
8170: }
8171: } else {
8172: $r->print(&navmap_errormsg());
8173: return(1,$currentphase);
8174: }
8175:
8176: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # parse needs the bubble line array.
8177: if ($nav_error) {
8178: $r->print(&navmap_errormsg());
8179: return(1,$currentphase);
8180: }
8181:
8182: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
8183: my $line=&scantron_get_line($scanlines,$scan_data,$i);
8184: if ($line=~/^[\s\cz]*$/) { next; }
8185: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
8186: $scan_data,undef,\%idmap,$randomorder,
8187: $randompick,$sequence,\@master_seq,
8188: \%symb_to_resource,\%grader_partids_by_symb,
8189: \%orderedforcode,\%respnumlookup,\%startline);
8190: if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
8191: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
8192: 'doublebubble',
8193: $$scan_record{'scantron.doubleerror'},
8194: $randomorder,$randompick,\%respnumlookup,\%startline);
8195: return (1,$currentphase);
8196: }
8197: return (0,$currentphase+1);
8198: }
8199:
8200:
8201: sub scantron_get_maxbubble {
8202: my ($nav_error,$scantron_config) = @_;
8203: if (defined($env{'form.scantron_maxbubble'}) &&
8204: $env{'form.scantron_maxbubble'}) {
8205: &restore_bubble_lines();
8206: return $env{'form.scantron_maxbubble'};
8207: }
8208:
8209: my (undef, undef, $sequence) =
8210: &Apache::lonnet::decode_symb($env{'form.selectpage'});
8211:
8212: my $navmap=Apache::lonnavmaps::navmap->new();
8213: unless (ref($navmap)) {
8214: if (ref($nav_error)) {
8215: $$nav_error = 1;
8216: }
8217: return;
8218: }
8219: my $map=$navmap->getResourceByUrl($sequence);
8220: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
8221: my $bubbles_per_row = &bubblesheet_bubbles_per_row($scantron_config);
8222:
8223: &Apache::lonxml::clear_problem_counter();
8224:
8225: my $uname = $env{'user.name'};
8226: my $udom = $env{'user.domain'};
8227: my $cid = $env{'request.course.id'};
8228: my $total_lines = 0;
8229: %bubble_lines_per_response = ();
8230: %first_bubble_line = ();
8231: %subdivided_bubble_lines = ();
8232: %responsetype_per_response = ();
8233: %masterseq_id_responsenum = ();
8234:
8235: my $response_number = 0;
8236: my $bubble_line = 0;
8237: foreach my $resource (@resources) {
8238: my $resid = $resource->id();
8239: my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,
8240: $udom,undef,$bubbles_per_row);
8241: if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
8242: foreach my $part_id (@{$parts}) {
8243: my $lines;
8244:
8245: # TODO - make this a persistent hash not an array.
8246:
8247: # optionresponse, matchresponse and rankresponse type items
8248: # render as separate sub-questions in exam mode.
8249: if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
8250: ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
8251: ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
8252: my ($numbub,$numshown);
8253: if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
8254: if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
8255: $numbub = scalar(@{$analysis->{$part_id.'.options'}});
8256: }
8257: } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
8258: if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
8259: $numbub = scalar(@{$analysis->{$part_id.'.items'}});
8260: }
8261: } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
8262: if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
8263: $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
8264: }
8265: }
8266: if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
8267: $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
8268: }
8269: my $bubbles_per_row =
8270: &bubblesheet_bubbles_per_row($scantron_config);
8271: my $inner_bubble_lines = int($numbub/$bubbles_per_row);
8272: if (($numbub % $bubbles_per_row) != 0) {
8273: $inner_bubble_lines++;
8274: }
8275: for (my $i=0; $i<$numshown; $i++) {
8276: $subdivided_bubble_lines{$response_number} .=
8277: $inner_bubble_lines.',';
8278: }
8279: $subdivided_bubble_lines{$response_number} =~ s/,$//;
8280: $lines = $numshown * $inner_bubble_lines;
8281: } else {
8282: $lines = $analysis->{"$part_id.bubble_lines"};
8283: }
8284:
8285: $first_bubble_line{$response_number} = $bubble_line;
8286: $bubble_lines_per_response{$response_number} = $lines;
8287: $responsetype_per_response{$response_number} =
8288: $analysis->{$part_id.'.type'};
8289: $masterseq_id_responsenum{$resid.'_'.$part_id} = $response_number;
8290: $response_number++;
8291:
8292: $bubble_line += $lines;
8293: $total_lines += $lines;
8294: }
8295: }
8296: }
8297: &Apache::lonnet::delenv('scantron.');
8298:
8299: &save_bubble_lines();
8300: $env{'form.scantron_maxbubble'} =
8301: $total_lines;
8302: return $env{'form.scantron_maxbubble'};
8303: }
8304:
8305: sub bubblesheet_bubbles_per_row {
8306: my ($scantron_config) = @_;
8307: my $bubbles_per_row;
8308: if (ref($scantron_config) eq 'HASH') {
8309: $bubbles_per_row = $scantron_config->{'BubblesPerRow'};
8310: }
8311: if ((!$bubbles_per_row) || ($bubbles_per_row < 1)) {
8312: $bubbles_per_row = 10;
8313: }
8314: return $bubbles_per_row;
8315: }
8316:
8317: sub scantron_validate_missingbubbles {
8318: my ($r,$currentphase) = @_;
8319: #get student info
8320: my $classlist=&Apache::loncoursedata::get_classlist();
8321: my %idmap=&username_to_idmap($classlist);
8322: my (undef,undef,$sequence)=
8323: &Apache::lonnet::decode_symb($env{'form.selectpage'});
8324:
8325: #get scantron line setup
8326: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
8327: my ($scanlines,$scan_data)=&scantron_getfile();
8328:
8329: my $navmap = Apache::lonnavmaps::navmap->new();
8330: unless (ref($navmap)) {
8331: $r->print(&navmap_errormsg());
8332: return(1,$currentphase);
8333: }
8334:
8335: my $map=$navmap->getResourceByUrl($sequence);
8336: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
8337: my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
8338: %grader_randomlists_by_symb,%orderedforcode,%respnumlookup,%startline);
8339: my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
8340:
8341: my $nav_error;
8342: if (ref($map)) {
8343: $randomorder = $map->randomorder();
8344: $randompick = $map->randompick();
8345: if ($randomorder || $randompick) {
8346: $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
8347: if ($nav_error) {
8348: $r->print(&navmap_errormsg());
8349: return(1,$currentphase);
8350: }
8351: &graders_resources_pass(\@resources,\%grader_partids_by_symb,
8352: \%grader_randomlists_by_symb,$bubbles_per_row);
8353: }
8354: } else {
8355: $r->print(&navmap_errormsg());
8356: return(1,$currentphase);
8357: }
8358:
8359:
8360: my $max_bubble=&scantron_get_maxbubble(\$nav_error,\%scantron_config);
8361: if ($nav_error) {
8362: $r->print(&navmap_errormsg());
8363: return(1,$currentphase);
8364: }
8365:
8366: if (!$max_bubble) { $max_bubble=2**31; }
8367: for (my $i=0;$i<=$scanlines->{'count'};$i++) {
8368: my $line=&scantron_get_line($scanlines,$scan_data,$i);
8369: if ($line=~/^[\s\cz]*$/) { next; }
8370: my $scan_record =
8371: &scantron_parse_scanline($line,$i,\%scantron_config,$scan_data,undef,\%idmap,
8372: $randomorder,$randompick,$sequence,\@master_seq,
8373: \%symb_to_resource,\%grader_partids_by_symb,
8374: \%orderedforcode,\%respnumlookup,\%startline);
8375: if (!defined($$scan_record{'scantron.missingerror'})) { next; }
8376: my @to_correct;
8377:
8378: # Probably here's where the error is...
8379:
8380: foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
8381: my $lastbubble;
8382: if ($missing =~ /^(\d+)\.(\d+)$/) {
8383: my $question = $1;
8384: my $subquestion = $2;
8385: my ($first,$responsenum);
8386: if ($randomorder || $randompick) {
8387: $responsenum = $respnumlookup{$question-1};
8388: $first = $startline{$question-1};
8389: } else {
8390: $responsenum = $question-1;
8391: $first = $first_bubble_line{$responsenum};
8392: }
8393: if (!defined($first)) { next; }
8394: my @subans = split(/,/,$subdivided_bubble_lines{$responsenum});
8395: my $subcount = 1;
8396: while ($subcount<$subquestion) {
8397: $first += $subans[$subcount-1];
8398: $subcount ++;
8399: }
8400: my $count = $subans[$subquestion-1];
8401: $lastbubble = $first + $count;
8402: } else {
8403: my ($first,$responsenum);
8404: if ($randomorder || $randompick) {
8405: $responsenum = $respnumlookup{$missing-1};
8406: $first = $startline{$missing-1};
8407: } else {
8408: $responsenum = $missing-1;
8409: $first = $first_bubble_line{$responsenum};
8410: }
8411: if (!defined($first)) { next; }
8412: $lastbubble = $first + $bubble_lines_per_response{$responsenum};
8413: }
8414: if ($lastbubble > $max_bubble) { next; }
8415: push(@to_correct,$missing);
8416: }
8417: if (@to_correct) {
8418: &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
8419: $line,'missingbubble',\@to_correct,
8420: $randomorder,$randompick,\%respnumlookup,
8421: \%startline);
8422: return (1,$currentphase);
8423: }
8424:
8425: }
8426: return (0,$currentphase+1);
8427: }
8428:
8429: sub hand_bubble_option {
8430: my (undef, undef, $sequence) =
8431: &Apache::lonnet::decode_symb($env{'form.selectpage'});
8432: return if ($sequence eq '');
8433: my $navmap = Apache::lonnavmaps::navmap->new();
8434: unless (ref($navmap)) {
8435: return;
8436: }
8437: my $needs_hand_bubbles;
8438: my $map=$navmap->getResourceByUrl($sequence);
8439: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
8440: foreach my $res (@resources) {
8441: if (ref($res)) {
8442: if ($res->is_problem()) {
8443: my $partlist = $res->parts();
8444: foreach my $part (@{ $partlist }) {
8445: my @types = $res->responseType($part);
8446: if (grep(/^(chem|essay|image|formula|math|string|functionplot)$/,@types)) {
8447: $needs_hand_bubbles = 1;
8448: last;
8449: }
8450: }
8451: }
8452: }
8453: }
8454: if ($needs_hand_bubbles) {
8455: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
8456: my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
8457: return &mt('The sequence to be graded contains response types which are handgraded.').'<p>'.
8458: &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 />').
8459: '<label><input type="radio" name="scantron_lastbubblepoints" value="'.$bubbles_per_row.'" checked="checked" />'.&mt('[quant,_1,point]',$bubbles_per_row).'</label> '.&mt('or').' '.
8460: '<label><input type="radio" name="scantron_lastbubblepoints" value="0" />'.&mt('0 points').'</label></p>';
8461: }
8462: return;
8463: }
8464:
8465: sub scantron_process_students {
8466: my ($r) = @_;
8467:
8468: my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
8469: my ($symb)=&get_symb($r);
8470: if (!$symb) {
8471: return '';
8472: }
8473: my $default_form_data=&defaultFormData($symb);
8474:
8475: my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
8476: my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
8477: my ($scanlines,$scan_data)=&scantron_getfile();
8478: my $classlist=&Apache::loncoursedata::get_classlist();
8479: my %idmap=&username_to_idmap($classlist);
8480: my $navmap=Apache::lonnavmaps::navmap->new();
8481: unless (ref($navmap)) {
8482: $r->print(&navmap_errormsg());
8483: return '';
8484: }
8485: my $map=$navmap->getResourceByUrl($sequence);
8486: my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
8487: %grader_randomlists_by_symb);
8488: if (ref($map)) {
8489: $randomorder = $map->randomorder();
8490: $randompick = $map->randompick();
8491: } else {
8492: $r->print(&navmap_errormsg());
8493: return '';
8494: }
8495: my $nav_error;
8496: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
8497: if ($randomorder || $randompick) {
8498: $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
8499: if ($nav_error) {
8500: $r->print(&navmap_errormsg());
8501: return '';
8502: }
8503: }
8504: &graders_resources_pass(\@resources,\%grader_partids_by_symb,
8505: \%grader_randomlists_by_symb,$bubbles_per_row);
8506:
8507: my ($uname,$udom);
8508: my $result= <<SCANTRONFORM;
8509: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
8510: <input type="hidden" name="command" value="scantron_configphase" />
8511: $default_form_data
8512: SCANTRONFORM
8513: $r->print($result);
8514:
8515: my @delayqueue;
8516: my (%completedstudents,%scandata);
8517:
8518: my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
8519: my $count=&get_todo_count($scanlines,$scan_data);
8520: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
8521: &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
8522: 'Processing first student');
8523: $r->print('<br />');
8524: my $start=&Time::HiRes::time();
8525: my $i=-1;
8526: my $started;
8527:
8528: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
8529: if ($nav_error) {
8530: $r->print(&navmap_errormsg());
8531: return '';
8532: }
8533:
8534: # If an ssi failed in scantron_get_maxbubble, put an error message out to
8535: # the user and return.
8536:
8537: if ($ssi_error) {
8538: $r->print("</form>");
8539: &ssi_print_error($r);
8540: $r->print(&show_grading_menu_form($symb));
8541: &Apache::lonnet::remove_lock($lock);
8542: return ''; # Dunno why the other returns return '' rather than just returning.
8543: }
8544:
8545: my %lettdig = &letter_to_digits();
8546: my $numletts = scalar(keys(%lettdig));
8547: my %orderedforcode;
8548:
8549: while ($i<$scanlines->{'count'}) {
8550: ($uname,$udom)=('','');
8551: $i++;
8552: my $line=&scantron_get_line($scanlines,$scan_data,$i);
8553: if ($line=~/^[\s\cz]*$/) { next; }
8554: if ($started) {
8555: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
8556: 'last student');
8557: }
8558: $started=1;
8559: my %respnumlookup = ();
8560: my %startline = ();
8561: my $total;
8562: my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
8563: $scan_data,undef,\%idmap,$randomorder,
8564: $randompick,$sequence,\@master_seq,
8565: \%symb_to_resource,\%grader_partids_by_symb,
8566: \%orderedforcode,\%respnumlookup,\%startline,
8567: \$total);
8568: unless ($uname=&scantron_find_student($scan_record,$scan_data,
8569: \%idmap,$i)) {
8570: &scantron_add_delay(\@delayqueue,$line,
8571: 'Unable to find a student that matches',1);
8572: next;
8573: }
8574: if (exists $completedstudents{$uname}) {
8575: &scantron_add_delay(\@delayqueue,$line,
8576: 'Student '.$uname.' has multiple sheets',2);
8577: next;
8578: }
8579: my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
8580: my $user = $uname.':'.$usec;
8581: ($uname,$udom)=split(/:/,$uname);
8582:
8583: my $scancode;
8584: if ((exists($scan_record->{'scantron.CODE'})) &&
8585: (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
8586: $scancode = $scan_record->{'scantron.CODE'};
8587: } else {
8588: $scancode = '';
8589: }
8590:
8591: my @mapresources = @resources;
8592: if ($randomorder || $randompick) {
8593: @mapresources =
8594: &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
8595: \%orderedforcode);
8596: }
8597: my (%partids_by_symb,$res_error);
8598: foreach my $resource (@mapresources) {
8599: my $ressymb;
8600: if (ref($resource)) {
8601: $ressymb = $resource->symb();
8602: } else {
8603: $res_error = 1;
8604: last;
8605: }
8606: if ((exists($grader_randomlists_by_symb{$ressymb})) ||
8607: (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
8608: my ($analysis,$parts) =
8609: &scantron_partids_tograde($resource,$env{'request.course.id'},
8610: $uname,$udom,undef,$bubbles_per_row);
8611: $partids_by_symb{$ressymb} = $parts;
8612: } else {
8613: $partids_by_symb{$ressymb} = $grader_partids_by_symb{$ressymb};
8614: }
8615: }
8616:
8617: if ($res_error) {
8618: &scantron_add_delay(\@delayqueue,$line,
8619: 'An error occurred while grading student '.$uname,2);
8620: next;
8621: }
8622:
8623: &Apache::lonxml::clear_problem_counter();
8624: &Apache::lonnet::appenv($scan_record);
8625:
8626: if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
8627: &scantron_putfile($scanlines,$scan_data);
8628: }
8629:
8630: if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
8631: \@mapresources,\%partids_by_symb,
8632: $bubbles_per_row,$randomorder,$randompick,
8633: \%respnumlookup,\%startline)
8634: eq 'ssi_error') {
8635: $ssi_error = 0; # So end of handler error message does not trigger.
8636: $r->print("</form>");
8637: &ssi_print_error($r);
8638: $r->print(&show_grading_menu_form($symb));
8639: &Apache::lonnet::remove_lock($lock);
8640: return ''; # Why return ''? Beats me.
8641: }
8642:
8643: if (($scancode) && ($randomorder || $randompick)) {
8644: my $parmresult =
8645: &Apache::lonparmset::storeparm_by_symb($symb,
8646: '0_examcode',2,$scancode,
8647: 'string_examcode',$uname,
8648: $udom);
8649: }
8650: $completedstudents{$uname}={'line'=>$line};
8651: if ($env{'form.verifyrecord'}) {
8652: my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
8653: if ($randompick) {
8654: if ($total) {
8655: $lastpos = $total*$scantron_config{'Qlength'};
8656: }
8657: }
8658:
8659: my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
8660: chomp($studentdata);
8661: $studentdata =~ s/\r$//;
8662: my $studentrecord = '';
8663: my $counter = -1;
8664: foreach my $resource (@mapresources) {
8665: my $ressymb = $resource->symb();
8666: ($counter,my $recording) =
8667: &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
8668: $counter,$studentdata,$partids_by_symb{$ressymb},
8669: \%scantron_config,\%lettdig,$numletts,$randomorder,
8670: $randompick,\%respnumlookup,\%startline);
8671: $studentrecord .= $recording;
8672: }
8673: if ($studentrecord ne $studentdata) {
8674: &Apache::lonxml::clear_problem_counter();
8675: if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
8676: \@mapresources,\%partids_by_symb,
8677: $bubbles_per_row,$randomorder,$randompick,
8678: \%respnumlookup,\%startline)
8679: eq 'ssi_error') {
8680: $ssi_error = 0; # So end of handler error message does not trigger.
8681: $r->print("</form>");
8682: &ssi_print_error($r);
8683: $r->print(&show_grading_menu_form($symb));
8684: &Apache::lonnet::remove_lock($lock);
8685: delete($completedstudents{$uname});
8686: return '';
8687: }
8688: $counter = -1;
8689: $studentrecord = '';
8690: foreach my $resource (@mapresources) {
8691: my $ressymb = $resource->symb();
8692: ($counter,my $recording) =
8693: &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
8694: $counter,$studentdata,$partids_by_symb{$ressymb},
8695: \%scantron_config,\%lettdig,$numletts,
8696: $randomorder,$randompick,\%respnumlookup,
8697: \%startline);
8698: $studentrecord .= $recording;
8699: }
8700: if ($studentrecord ne $studentdata) {
8701: $r->print('<p><span class="LC_warning">');
8702: if ($scancode eq '') {
8703: $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2].',
8704: $uname.':'.$udom,$scan_record->{'scantron.ID'}));
8705: } else {
8706: $r->print(&mt('Mismatch grading bubblesheet for user: [_1] with ID: [_2] and CODE: [_3].',
8707: $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
8708: }
8709: $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
8710: &Apache::loncommon::start_data_table_header_row()."\n".
8711: '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
8712: &Apache::loncommon::end_data_table_header_row()."\n".
8713: &Apache::loncommon::start_data_table_row().
8714: '<td>'.&mt('Bubblesheet').'</td>'.
8715: '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentdata.'</tt></span></td>'.
8716: &Apache::loncommon::end_data_table_row().
8717: &Apache::loncommon::start_data_table_row().
8718: '<td>'.&mt('Stored submissions').'</td>'.
8719: '<td><span class="LC_nobreak" style="white-space: pre;"><tt>'.$studentrecord.'</tt></span></td>'."\n".
8720: &Apache::loncommon::end_data_table_row().
8721: &Apache::loncommon::end_data_table().'</p>');
8722: } else {
8723: $r->print('<br /><span class="LC_warning">'.
8724: &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 />'.
8725: &mt("As a consequence, this user's submission history records two tries.").
8726: '</span><br />');
8727: }
8728: }
8729: }
8730: if (&Apache::loncommon::connection_aborted($r)) { last; }
8731: } continue {
8732: &Apache::lonxml::clear_problem_counter();
8733: &Apache::lonnet::delenv('scantron.');
8734: }
8735: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
8736: &Apache::lonnet::remove_lock($lock);
8737: # my $lasttime = &Time::HiRes::time()-$start;
8738: # $r->print("<p>took $lasttime</p>");
8739:
8740: $r->print("</form>");
8741: $r->print(&show_grading_menu_form($symb));
8742: return '';
8743: }
8744:
8745: sub graders_resources_pass {
8746: my ($resources,$grader_partids_by_symb,$grader_randomlists_by_symb,
8747: $bubbles_per_row) = @_;
8748: if ((ref($resources) eq 'ARRAY') && (ref($grader_partids_by_symb)) &&
8749: (ref($grader_randomlists_by_symb) eq 'HASH')) {
8750: foreach my $resource (@{$resources}) {
8751: my $ressymb = $resource->symb();
8752: my ($analysis,$parts) =
8753: &scantron_partids_tograde($resource,$env{'request.course.id'},
8754: $env{'user.name'},$env{'user.domain'},
8755: 1,$bubbles_per_row);
8756: $grader_partids_by_symb->{$ressymb} = $parts;
8757: if (ref($analysis) eq 'HASH') {
8758: if (ref($analysis->{'parts_withrandomlist'}) eq 'ARRAY') {
8759: $grader_randomlists_by_symb->{$ressymb} =
8760: $analysis->{'parts_withrandomlist'};
8761: }
8762: }
8763: }
8764: }
8765: return;
8766: }
8767:
8768: =pod
8769:
8770: =item users_order
8771:
8772: Returns array of resources in current map, ordered based on either CODE,
8773: if this is a CODEd exam, or based on student's identity if this is a
8774: "NAMEd" exam.
8775:
8776: Should be used when randomorder and/or randompick applied when the
8777: corresponding exam was printed, prior to students completing bubblesheets
8778: for the version of the exam the student received.
8779:
8780: =cut
8781:
8782: sub users_order {
8783: my ($user,$scancode,$mapurl,$master_seq,$symb_to_resource,$orderedforcode) = @_;
8784: my @mapresources;
8785: unless ((ref($master_seq) eq 'ARRAY') && (ref($symb_to_resource) eq 'HASH')) {
8786: return @mapresources;
8787: }
8788: if ($scancode) {
8789: if ((ref($orderedforcode) eq 'HASH') && (ref($orderedforcode->{$scancode}) eq 'ARRAY')) {
8790: @mapresources = @{$orderedforcode->{$scancode}};
8791: } else {
8792: $env{'form.CODE'} = $scancode;
8793: my $actual_seq =
8794: &Apache::lonprintout::master_seq_to_person_seq($mapurl,
8795: $master_seq,
8796: $user,$scancode,1);
8797: if (ref($actual_seq) eq 'ARRAY') {
8798: @mapresources = map { $symb_to_resource->{$_}; } @{$actual_seq};
8799: if (ref($orderedforcode) eq 'HASH') {
8800: if (@mapresources > 0) {
8801: $orderedforcode->{$scancode} = \@mapresources;
8802: }
8803: }
8804: }
8805: delete($env{'form.CODE'});
8806: }
8807: } else {
8808: my $actual_seq =
8809: &Apache::lonprintout::master_seq_to_person_seq($mapurl,
8810: $master_seq,
8811: $user,undef,1);
8812: if (ref($actual_seq) eq 'ARRAY') {
8813: @mapresources =
8814: map { $symb_to_resource->{$_}; } @{$actual_seq};
8815: }
8816: }
8817: return @mapresources;
8818: }
8819:
8820: sub grade_student_bubbles {
8821: my ($r,$uname,$udom,$scan_record,$scancode,$resources,$parts,$bubbles_per_row,
8822: $randomorder,$randompick,$respnumlookup,$startline) = @_;
8823: my $uselookup = 0;
8824: if (($randomorder || $randompick) && (ref($respnumlookup) eq 'HASH') &&
8825: (ref($startline) eq 'HASH')) {
8826: $uselookup = 1;
8827: }
8828:
8829: if (ref($resources) eq 'ARRAY') {
8830: my $count = 0;
8831: foreach my $resource (@{$resources}) {
8832: my $ressymb = $resource->symb();
8833: my %form = ('submitted' => 'scantron',
8834: 'grade_target' => 'grade',
8835: 'grade_username' => $uname,
8836: 'grade_domain' => $udom,
8837: 'grade_courseid' => $env{'request.course.id'},
8838: 'grade_symb' => $ressymb,
8839: 'CODE' => $scancode
8840: );
8841: if ($bubbles_per_row ne '') {
8842: $form{'bubbles_per_row'} = $bubbles_per_row;
8843: }
8844: if ($env{'form.scantron_lastbubblepoints'} ne '') {
8845: $form{'scantron_lastbubblepoints'} = $env{'form.scantron_lastbubblepoints'};
8846: }
8847: if (ref($parts) eq 'HASH') {
8848: if (ref($parts->{$ressymb}) eq 'ARRAY') {
8849: foreach my $part (@{$parts->{$ressymb}}) {
8850: if ($uselookup) {
8851: $form{'scantron_questnum_start.'.$part} = $startline->{$count} + 1;
8852: } else {
8853: $form{'scantron_questnum_start.'.$part} =
8854: 1+$env{'form.scantron.first_bubble_line.'.$count};
8855: }
8856: $count++;
8857: }
8858: }
8859: }
8860: my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
8861: return 'ssi_error' if ($ssi_error);
8862: last if (&Apache::loncommon::connection_aborted($r));
8863: }
8864: }
8865: return;
8866: }
8867:
8868: sub scantron_upload_scantron_data {
8869: my ($r)=@_;
8870: my $dom = $env{'request.role.domain'};
8871: my $domdesc = &Apache::lonnet::domain($dom,'description');
8872: $r->print(&Apache::loncommon::coursebrowser_javascript($dom));
8873: my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
8874: 'domainid',
8875: 'coursename',$dom);
8876: my $syllabuslink = '<a href="javascript:ToSyllabus();">'.&mt('Syllabus').'</a>'.
8877: (' 'x2).&mt('(shows course personnel)');
8878: my ($symb) = &get_symb($r,1);
8879: my $default_form_data=&defaultFormData($symb);
8880: my $nofile_alert = &mt('Please use the browse button to select a file from your local directory.');
8881: 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.");
8882: $r->print('
8883: <script type="text/javascript" language="javascript">
8884: function checkUpload(formname) {
8885: if (formname.upfile.value == "") {
8886: alert("'.$nofile_alert.'");
8887: return false;
8888: }
8889: if (formname.courseid.value == "") {
8890: alert("'.$nocourseid_alert.'");
8891: return false;
8892: }
8893: formname.submit();
8894: }
8895:
8896: function ToSyllabus() {
8897: var cdom = '."'$dom'".';
8898: var cnum = document.rules.courseid.value;
8899: if (cdom == "" || cdom == null) {
8900: return;
8901: }
8902: if (cnum == "" || cnum == null) {
8903: return;
8904: }
8905: syllwin=window.open("/public/"+cdom+"/"+cnum+"/syllabus","LONCAPASyllabus",
8906: "height=350,width=350,scrollbars=yes,menubar=no");
8907: return;
8908: }
8909:
8910: </script>
8911:
8912: <h3>'.&mt('Send bubblesheet data to a course').'</h3>
8913:
8914: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
8915: '.$default_form_data.
8916: &Apache::lonhtmlcommon::start_pick_box().
8917: &Apache::lonhtmlcommon::row_title(&mt('Course ID')).
8918: '<input name="courseid" type="text" size="30" />'.$select_link.
8919: &Apache::lonhtmlcommon::row_closure().
8920: &Apache::lonhtmlcommon::row_title(&mt('Course Name')).
8921: '<input name="coursename" type="text" size="30" />'.$syllabuslink.
8922: &Apache::lonhtmlcommon::row_closure().
8923: &Apache::lonhtmlcommon::row_title(&mt('Domain')).
8924: '<input name="domainid" type="hidden" />'.$domdesc.
8925: &Apache::lonhtmlcommon::row_closure().
8926: &Apache::lonhtmlcommon::row_title(&mt('File to upload')).
8927: '<input type="file" name="upfile" size="50" />'.
8928: &Apache::lonhtmlcommon::row_closure(1).
8929: &Apache::lonhtmlcommon::end_pick_box().'<br />
8930:
8931: <input name="command" value="scantronupload_save" type="hidden" />
8932: <input type="button" onclick="javascript:checkUpload(this.form);" value="'.&mt('Upload Bubblesheet Data').'" />
8933: </form>
8934: ');
8935: return '';
8936: }
8937:
8938:
8939: sub scantron_upload_scantron_data_save {
8940: my($r)=@_;
8941: my ($symb)=&get_symb($r,1);
8942: my $doanotherupload=
8943: '<br /><form action="/adm/grades" method="post">'."\n".
8944: '<input type="hidden" name="command" value="scantronupload" />'."\n".
8945: '<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
8946: '</form>'."\n";
8947: if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
8948: !&Apache::lonnet::allowed('usc',
8949: $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
8950: $r->print(&mt("You are not allowed to upload bubblesheet data to the requested course.")."<br />");
8951: if ($symb) {
8952: $r->print(&show_grading_menu_form($symb));
8953: } else {
8954: $r->print($doanotherupload);
8955: }
8956: return '';
8957: }
8958: my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
8959: my $uploadedfile;
8960: $r->print('<p>'.&mt("Uploading file to [_1]",$coursedata{'description'}).'</p>');
8961: if (length($env{'form.upfile'}) < 2) {
8962: $r->print(
8963: &Apache::lonhtmlcommon::confirm_success(
8964: &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
8965: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1));
8966: } else {
8967: my $result =
8968: &Apache::lonnet::userfileupload('upfile','','scantron','','','',
8969: $env{'form.courseid'},$env{'form.domainid'});
8970: if ($result =~ m{^/uploaded/}) {
8971: $r->print(
8972: &Apache::lonhtmlcommon::confirm_success(&mt('Upload successful')).'<br />'.
8973: &mt('Uploaded [_1] bytes of data into location: [_2]',
8974: (length($env{'form.upfile'})-1),
8975: '<span class="LC_filename">'.$result.'</span>'));
8976: ($uploadedfile) = ($result =~ m{/([^/]+)$});
8977: $r->print(&validate_uploaded_scantron_file($env{'form.domainid'},
8978: $env{'form.courseid'},$uploadedfile));
8979: } else {
8980: $r->print(
8981: &Apache::lonhtmlcommon::confirm_success(&mt('Upload failed'),1).'<br />'.
8982: &mt('An error ([_1]) occurred when attempting to upload the file: [_2]',
8983: $result,
8984: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'));
8985: }
8986: }
8987: if ($symb) {
8988: $r->print(&scantron_selectphase($r,$uploadedfile));
8989: } else {
8990: $r->print($doanotherupload);
8991: }
8992: return '';
8993: }
8994:
8995: sub validate_uploaded_scantron_file {
8996: my ($cdom,$cname,$fname) = @_;
8997: my $scanlines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.$fname);
8998: my @lines;
8999: if ($scanlines ne '-1') {
9000: @lines=split("\n",$scanlines,-1);
9001: }
9002: my $output;
9003: if (@lines) {
9004: my (%counts,$max_match_format);
9005: my ($found_match_count,$max_match_count,$max_match_pct) = (0,0,0);
9006: my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cname);
9007: my %idmap = &username_to_idmap($classlist);
9008: foreach my $key (keys(%idmap)) {
9009: my $lckey = lc($key);
9010: $idmap{$lckey} = $idmap{$key};
9011: }
9012: my %unique_formats;
9013: my @formatlines = &get_scantronformat_file();
9014: foreach my $line (@formatlines) {
9015: chomp($line);
9016: my @config = split(/:/,$line);
9017: my $idstart = $config[5];
9018: my $idlength = $config[6];
9019: if (($idstart ne '') && ($idlength > 0)) {
9020: if (ref($unique_formats{$idstart.':'.$idlength}) eq 'ARRAY') {
9021: push(@{$unique_formats{$idstart.':'.$idlength}},$config[0].':'.$config[1]);
9022: } else {
9023: $unique_formats{$idstart.':'.$idlength} = [$config[0].':'.$config[1]];
9024: }
9025: }
9026: }
9027: foreach my $key (keys(%unique_formats)) {
9028: my ($idstart,$idlength) = split(':',$key);
9029: %{$counts{$key}} = (
9030: 'found' => 0,
9031: 'total' => 0,
9032: );
9033: foreach my $line (@lines) {
9034: next if ($line =~ /^#/);
9035: next if ($line =~ /^[\s\cz]*$/);
9036: my $id = substr($line,$idstart-1,$idlength);
9037: $id = lc($id);
9038: if (exists($idmap{$id})) {
9039: $counts{$key}{'found'} ++;
9040: }
9041: $counts{$key}{'total'} ++;
9042: }
9043: if ($counts{$key}{'total'}) {
9044: my $percent_match = (100*$counts{$key}{'found'})/($counts{$key}{'total'});
9045: if (($max_match_format eq '') || ($percent_match > $max_match_pct)) {
9046: $max_match_pct = $percent_match;
9047: $max_match_format = $key;
9048: $found_match_count = $counts{$key}{'found'};
9049: $max_match_count = $counts{$key}{'total'};
9050: }
9051: }
9052: }
9053: if (ref($unique_formats{$max_match_format}) eq 'ARRAY') {
9054: my $format_descs;
9055: my $numwithformat = @{$unique_formats{$max_match_format}};
9056: for (my $i=0; $i<$numwithformat; $i++) {
9057: my ($name,$desc) = split(':',$unique_formats{$max_match_format}[$i]);
9058: if ($i<$numwithformat-2) {
9059: $format_descs .= '"<i>'.$desc.'</i>", ';
9060: } elsif ($i==$numwithformat-2) {
9061: $format_descs .= '"<i>'.$desc.'</i>" '.&mt('and').' ';
9062: } elsif ($i==$numwithformat-1) {
9063: $format_descs .= '"<i>'.$desc.'</i>"';
9064: }
9065: }
9066: my $showpct = sprintf("%.0f",$max_match_pct).'%';
9067: $output .= '<br />';
9068: if ($found_match_count == $max_match_count) {
9069: # 100% matching entries
9070: $output .= &Apache::lonhtmlcommon::confirm_success(
9071: &mt('Comparison of student IDs: [_1] matching ([quant,_2,entry,entries])',
9072: '<b>'.$showpct.'</b>',$found_match_count)).'<br />'.
9073: &mt('Comparison of student IDs in the uploaded file with'.
9074: ' the course roster found matches for [_1] of the [_2] entries'.
9075: ' in the file (for the format defined for [_3]).',
9076: '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs);
9077: } else {
9078: # Not all entries matching? -> Show warning and additional info
9079: $output .=
9080: &Apache::lonhtmlcommon::confirm_success(
9081: &mt('Comparison of student IDs: [_1] matching ([_2]/[quant,_3,entry,entries])',
9082: '<b>'.$showpct.'</b>',$found_match_count,$max_match_count).'<br />'.
9083: &mt('Not all entries could be matched!'),1).'<br />'.
9084: &mt('Comparison of student IDs in the uploaded file with'.
9085: ' the course roster found matches for [_1] of the [_2] entries'.
9086: ' in the file (for the format defined for [_3]).',
9087: '<b>'.$showpct.'</b>','<b>'.$max_match_count.'</b>',$format_descs).
9088: '<p class="LC_info">'.
9089: &mt('A low percentage of matches results from one of the following:').
9090: '</p><ul>'.
9091: '<li>'.&mt('The file was uploaded to the wrong course.').'</li>'.
9092: '<li>'.&mt('The data is not in the format expected for the domain: [_1]',
9093: '<i>'.$cdom.'</i>').'</li>'.
9094: '<li>'.&mt('Students did not bubble their IDs, or mis-bubbled them').'</li>'.
9095: '<li>'.&mt('The course roster is not up to date.').'</li>'.
9096: '</ul>';
9097: }
9098: }
9099: } else {
9100: $output = '<p class="LC_warning">'.&mt('Uploaded file contained no data').'</p>';
9101: }
9102: return $output;
9103: }
9104:
9105: sub valid_file {
9106: my ($requested_file)=@_;
9107: foreach my $filename (sort(&scantron_filenames())) {
9108: if ($requested_file eq $filename) { return 1; }
9109: }
9110: return 0;
9111: }
9112:
9113: sub scantron_download_scantron_data {
9114: my ($r)=@_;
9115: my ($symb) = &get_symb($r,1);
9116: my $default_form_data=&defaultFormData($symb);
9117: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
9118: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
9119: my $file=$env{'form.scantron_selectfile'};
9120: if (! &valid_file($file)) {
9121: $r->print('
9122: <p>
9123: '.&mt('The requested filename was invalid.').'
9124: </p>
9125: ');
9126: $r->print(&show_grading_menu_form($symb));
9127: return;
9128: }
9129: my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
9130: my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
9131: my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
9132: &Apache::lonnet::allowuploaded('/adm/grades',$orig);
9133: &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
9134: &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
9135: $r->print('
9136: <p>
9137: '.&mt('[_1]Original[_2] file as uploaded by bubblesheet scanning office.',
9138: '<a href="'.$orig.'">','</a>').'
9139: </p>
9140: <p>
9141: '.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
9142: '<a href="'.$corrected.'">','</a>').'
9143: </p>
9144: <p>
9145: '.&mt('[_1]Skipped[_2], a file of records that were skipped.',
9146: '<a href="'.$skipped.'">','</a>').'
9147: </p>
9148: ');
9149: $r->print(&show_grading_menu_form($symb));
9150: return '';
9151: }
9152:
9153: sub checkscantron_results {
9154: my ($r) = @_;
9155: my ($symb)=&get_symb($r);
9156: if (!$symb) {return '';}
9157: my $grading_menu_button=&show_grading_menu_form($symb);
9158: my $cid = $env{'request.course.id'};
9159: my %lettdig = &letter_to_digits();
9160: my $numletts = scalar(keys(%lettdig));
9161: my $cnum = $env{'course.'.$cid.'.num'};
9162: my $cdom = $env{'course.'.$cid.'.domain'};
9163: my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
9164: my %record;
9165: my %scantron_config =
9166: &Apache::grades::get_scantron_config($env{'form.scantron_format'});
9167: my $bubbles_per_row = &bubblesheet_bubbles_per_row(\%scantron_config);
9168: my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
9169: my $classlist=&Apache::loncoursedata::get_classlist();
9170: my %idmap=&Apache::grades::username_to_idmap($classlist);
9171: my $navmap=Apache::lonnavmaps::navmap->new();
9172: unless (ref($navmap)) {
9173: $r->print(&navmap_errormsg());
9174: return '';
9175: }
9176: my $map=$navmap->getResourceByUrl($sequence);
9177: my ($randomorder,$randompick,@master_seq,%symb_to_resource,%grader_partids_by_symb,
9178: %grader_randomlists_by_symb,%orderedforcode);
9179: if (ref($map)) {
9180: $randomorder=$map->randomorder();
9181: $randompick=$map->randompick();
9182: }
9183: my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
9184: my $nav_error = &get_master_seq(\@resources,\@master_seq,\%symb_to_resource);
9185: if ($nav_error) {
9186: $r->print(&navmap_errormsg());
9187: return '';
9188: }
9189: &graders_resources_pass(\@resources,\%grader_partids_by_symb,
9190: \%grader_randomlists_by_symb,$bubbles_per_row);
9191: my ($uname,$udom);
9192: my (%scandata,%lastname,%bylast);
9193: $r->print('
9194: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
9195:
9196: my @delayqueue;
9197: my %completedstudents;
9198:
9199: my $count=&get_todo_count($scanlines,$scan_data);
9200: my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,$count);
9201: my ($username,$domain,$started);
9202: &scantron_get_maxbubble(\$nav_error,\%scantron_config); # Need the bubble lines array to parse.
9203: if ($nav_error) {
9204: $r->print(&navmap_errormsg());
9205: return '';
9206: }
9207:
9208: &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
9209: 'Processing first student');
9210: my $start=&Time::HiRes::time();
9211: my $i=-1;
9212:
9213: while ($i<$scanlines->{'count'}) {
9214: ($username,$domain,$uname)=('','','');
9215: $i++;
9216: my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
9217: if ($line=~/^[\s\cz]*$/) { next; }
9218: if ($started) {
9219: &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
9220: 'last student');
9221: }
9222: $started=1;
9223: my $scan_record=
9224: &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
9225: $scan_data);
9226: unless ($uname=&scantron_find_student($scan_record,$scan_data,
9227: \%idmap,$i)) {
9228: &Apache::grades::scantron_add_delay(\@delayqueue,$line,
9229: 'Unable to find a student that matches',1);
9230: next;
9231: }
9232: if (exists $completedstudents{$uname}) {
9233: &Apache::grades::scantron_add_delay(\@delayqueue,$line,
9234: 'Student '.$uname.' has multiple sheets',2);
9235: next;
9236: }
9237: my $pid = $scan_record->{'scantron.ID'};
9238: $lastname{$pid} = $scan_record->{'scantron.LastName'};
9239: push(@{$bylast{$lastname{$pid}}},$pid);
9240: my $usec = $classlist->{$uname}->[&Apache::loncoursedata::CL_SECTION];
9241: my $user = $uname.':'.$usec;
9242: ($username,$domain)=split(/:/,$uname);
9243:
9244: my $scancode;
9245: if ((exists($scan_record->{'scantron.CODE'})) &&
9246: (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
9247: $scancode = $scan_record->{'scantron.CODE'};
9248: } else {
9249: $scancode = '';
9250: }
9251:
9252: my @mapresources = @resources;
9253: my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
9254: my %respnumlookup=();
9255: my %startline=();
9256: if ($randomorder || $randompick) {
9257: @mapresources =
9258: &users_order($user,$scancode,$sequence,\@master_seq,\%symb_to_resource,
9259: \%orderedforcode);
9260: my $total = &get_respnum_lookups($sequence,$scan_data,\%idmap,$line,
9261: $scan_record,\@master_seq,\%symb_to_resource,
9262: \%grader_partids_by_symb,\%orderedforcode,
9263: \%respnumlookup,\%startline);
9264: if ($randompick && $total) {
9265: $lastpos = $total*$scantron_config{'Qlength'};
9266: }
9267: }
9268: $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
9269: chomp($scandata{$pid});
9270: $scandata{$pid} =~ s/\r$//;
9271:
9272: my $counter = -1;
9273: foreach my $resource (@mapresources) {
9274: my $parts;
9275: my $ressymb = $resource->symb();
9276: if ((exists($grader_randomlists_by_symb{$ressymb})) ||
9277: (ref($grader_partids_by_symb{$ressymb}) ne 'ARRAY')) {
9278: (my $analysis,$parts) =
9279: &scantron_partids_tograde($resource,$env{'request.course.id'},
9280: $username,$domain,undef,
9281: $bubbles_per_row);
9282: } else {
9283: $parts = $grader_partids_by_symb{$ressymb};
9284: }
9285: ($counter,my $recording) =
9286: &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
9287: $scandata{$pid},$parts,
9288: \%scantron_config,\%lettdig,$numletts,
9289: $randomorder,$randompick,
9290: \%respnumlookup,\%startline);
9291: $record{$pid} .= $recording;
9292: }
9293: }
9294: &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
9295: $r->print('<br />');
9296: my ($okstudents,$badstudents,$numstudents,$passed,$failed);
9297: $passed = 0;
9298: $failed = 0;
9299: $numstudents = 0;
9300: foreach my $last (sort(keys(%bylast))) {
9301: if (ref($bylast{$last}) eq 'ARRAY') {
9302: foreach my $pid (sort(@{$bylast{$last}})) {
9303: my $showscandata = $scandata{$pid};
9304: my $showrecord = $record{$pid};
9305: $showscandata =~ s/\s/ /g;
9306: $showrecord =~ s/\s/ /g;
9307: if ($scandata{$pid} eq $record{$pid}) {
9308: my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
9309: $okstudents .= '<tr class="'.$css_class.'">'.
9310: '<td>'.&mt('Bubblesheet').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
9311: '</tr>'."\n".
9312: '<tr class="'.$css_class.'">'."\n".
9313: '<td>'.&mt('Submissions').'</td><td>'.$showrecord.'</td></tr>'."\n";
9314: $passed ++;
9315: } else {
9316: my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
9317: $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".
9318: '</tr>'."\n".
9319: '<tr class="'.$css_class.'">'."\n".
9320: '<td>'.&mt('Submissions').'</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
9321: '</tr>'."\n";
9322: $failed ++;
9323: }
9324: $numstudents ++;
9325: }
9326: }
9327: }
9328: $r->print('<p>'.
9329: &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).',
9330: '<b>',
9331: $numstudents,
9332: '</b>',
9333: $env{'form.scantron_maxbubble'}).
9334: '</p>'
9335: );
9336: $r->print('<p>'
9337: .&mt('Exact matches for [_1][quant,_2,student][_3].','<b>',$passed,'</b>')
9338: .'<br />'
9339: .&mt('Discrepancies detected for [_1][quant,_2,student][_3].','<b>',$failed,'</b>')
9340: .'</p>');
9341: if ($passed) {
9342: $r->print(&mt('Students with exact correspondence between bubblesheet data and submissions are as follows:').'<br /><br />');
9343: $r->print(&Apache::loncommon::start_data_table()."\n".
9344: &Apache::loncommon::start_data_table_header_row()."\n".
9345: '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
9346: &Apache::loncommon::end_data_table_header_row()."\n".
9347: $okstudents."\n".
9348: &Apache::loncommon::end_data_table().'<br />');
9349: }
9350: if ($failed) {
9351: $r->print(&mt('Students with differences between bubblesheet data and submissions are as follows:').'<br /><br />');
9352: $r->print(&Apache::loncommon::start_data_table()."\n".
9353: &Apache::loncommon::start_data_table_header_row()."\n".
9354: '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
9355: &Apache::loncommon::end_data_table_header_row()."\n".
9356: $badstudents."\n".
9357: &Apache::loncommon::end_data_table()).'<br />'.
9358: &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.');
9359: }
9360: $r->print('</form><br />'.$grading_menu_button);
9361: return;
9362: }
9363:
9364: sub verify_scantron_grading {
9365: my ($resource,$domain,$username,$cid,$counter,$scandata,$partids,
9366: $scantron_config,$lettdig,$numletts,$randomorder,$randompick,
9367: $respnumlookup,$startline) = @_;
9368: my ($record,%expected,%startpos);
9369: return ($counter,$record) if (!ref($resource));
9370: return ($counter,$record) if (!$resource->is_problem());
9371: my $symb = $resource->symb();
9372: return ($counter,$record) if (ref($partids) ne 'ARRAY');
9373: foreach my $part_id (@{$partids}) {
9374: $counter ++;
9375: $expected{$part_id} = 0;
9376: my $respnum = $counter;
9377: if ($randomorder || $randompick) {
9378: $respnum = $respnumlookup->{$counter};
9379: $startpos{$part_id} = $startline->{$counter} + 1;
9380: } else {
9381: $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
9382: }
9383: if ($env{"form.scantron.sub_bubblelines.$respnum"}) {
9384: my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$respnum"});
9385: foreach my $item (@sub_lines) {
9386: $expected{$part_id} += $item;
9387: }
9388: } else {
9389: $expected{$part_id} = $env{"form.scantron.bubblelines.$respnum"};
9390: }
9391: }
9392: if ($symb) {
9393: my %recorded;
9394: my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
9395: if ($returnhash{'version'}) {
9396: my %lasthash=();
9397: my $version;
9398: for ($version=1;$version<=$returnhash{'version'};$version++) {
9399: foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
9400: $lasthash{$key}=$returnhash{$version.':'.$key};
9401: }
9402: }
9403: foreach my $key (keys(%lasthash)) {
9404: if ($key =~ /\.scantron$/) {
9405: my $value = &unescape($lasthash{$key});
9406: my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
9407: if ($value eq '') {
9408: for (my $i=0; $i<$expected{$part_id}; $i++) {
9409: for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
9410: $recorded{$part_id} .= $scantron_config->{'Qoff'};
9411: }
9412: }
9413: } else {
9414: my @tocheck;
9415: my @items = split(//,$value);
9416: if (($scantron_config->{'Qon'} eq 'letter') ||
9417: ($scantron_config->{'Qon'} eq 'number')) {
9418: if (@items < $expected{$part_id}) {
9419: my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
9420: my @singles = split(//,$fragment);
9421: foreach my $pos (@singles) {
9422: if ($pos eq ' ') {
9423: push(@tocheck,$pos);
9424: } else {
9425: my $next = shift(@items);
9426: push(@tocheck,$next);
9427: }
9428: }
9429: } else {
9430: @tocheck = @items;
9431: }
9432: foreach my $letter (@tocheck) {
9433: if ($scantron_config->{'Qon'} eq 'letter') {
9434: if ($letter !~ /^[A-J]$/) {
9435: $letter = $scantron_config->{'Qoff'};
9436: }
9437: $recorded{$part_id} .= $letter;
9438: } elsif ($scantron_config->{'Qon'} eq 'number') {
9439: my $digit;
9440: if ($letter !~ /^[A-J]$/) {
9441: $digit = $scantron_config->{'Qoff'};
9442: } else {
9443: $digit = $lettdig->{$letter};
9444: }
9445: $recorded{$part_id} .= $digit;
9446: }
9447: }
9448: } else {
9449: @tocheck = @items;
9450: for (my $i=0; $i<$expected{$part_id}; $i++) {
9451: my $curr_sub = shift(@tocheck);
9452: my $digit;
9453: if ($curr_sub =~ /^[A-J]$/) {
9454: $digit = $lettdig->{$curr_sub}-1;
9455: }
9456: if ($curr_sub eq 'J') {
9457: $digit += scalar($numletts);
9458: }
9459: for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
9460: if ($j == $digit) {
9461: $recorded{$part_id} .= $scantron_config->{'Qon'};
9462: } else {
9463: $recorded{$part_id} .= $scantron_config->{'Qoff'};
9464: }
9465: }
9466: }
9467: }
9468: }
9469: }
9470: }
9471: }
9472: foreach my $part_id (@{$partids}) {
9473: if ($recorded{$part_id} eq '') {
9474: for (my $i=0; $i<$expected{$part_id}; $i++) {
9475: for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
9476: $recorded{$part_id} .= $scantron_config->{'Qoff'};
9477: }
9478: }
9479: }
9480: $record .= $recorded{$part_id};
9481: }
9482: }
9483: return ($counter,$record);
9484: }
9485:
9486: sub letter_to_digits {
9487: my %lettdig = (
9488: A => 1,
9489: B => 2,
9490: C => 3,
9491: D => 4,
9492: E => 5,
9493: F => 6,
9494: G => 7,
9495: H => 8,
9496: I => 9,
9497: J => 0,
9498: );
9499: return %lettdig;
9500: }
9501:
9502:
9503: #-------- end of section for handling grading scantron forms -------
9504: #
9505: #-------------------------------------------------------------------
9506:
9507: #-------------------------- Menu interface -------------------------
9508: #
9509: #--- Show a Grading Menu button - Calls the next routine ---
9510: sub show_grading_menu_form {
9511: my ($symb)=@_;
9512: my $result.='<br /><form action="/adm/grades" method="post">'."\n".
9513: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
9514: '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
9515: '<input type="hidden" name="command" value="gradingmenu" />'."\n".
9516: '<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
9517: '</form>'."\n";
9518: return $result;
9519: }
9520:
9521: # -- Retrieve choices for grading form
9522: sub savedState {
9523: my %savedState = ();
9524: if ($env{'form.saveState'}) {
9525: foreach (split(/:/,$env{'form.saveState'})) {
9526: my ($key,$value) = split(/=/,$_,2);
9527: $savedState{$key} = $value;
9528: }
9529: }
9530: return \%savedState;
9531: }
9532:
9533: #--- Href with symb and command ---
9534:
9535: sub href_symb_cmd {
9536: my ($symb,$cmd)=@_;
9537: return '/adm/grades?symb='.&HTML::Entities::encode(&Apache::lonenc::check_encrypt($symb),'<>&"').'&command='.$cmd;
9538: }
9539:
9540: sub grading_menu {
9541: my ($request) = @_;
9542: my ($symb)=&get_symb($request);
9543: if (!$symb) {return '';}
9544: my $probTitle = &Apache::lonnet::gettitle($symb);
9545: my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
9546:
9547: $request->print($table);
9548: my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
9549: 'handgrade'=>$hdgrade,
9550: 'probTitle'=>$probTitle,
9551: 'command'=>'submit_options',
9552: 'saveState'=>"",
9553: 'gradingMenu'=>1,
9554: 'showgrading'=>"yes");
9555:
9556: my $url1 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
9557:
9558: $fields{'command'} = 'csvform';
9559: my $url2 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
9560:
9561: $fields{'command'} = 'processclicker';
9562: my $url3 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
9563:
9564: $fields{'command'} = 'scantron_selectphase';
9565: my $url4 = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
9566:
9567: my @menu = ({ categorytitle=>'Course Grading',
9568: items =>[
9569: { linktext => 'Manual Grading/View Submissions',
9570: url => $url1,
9571: permission => 'F',
9572: icon => 'edit-find-replace.png',
9573: linktitle => 'Start the process of hand grading submissions.'
9574: },
9575: { linktext => 'Upload Scores',
9576: url => $url2,
9577: permission => 'F',
9578: icon => 'uploadscores.png',
9579: linktitle => 'Specify a file containing the class scores for current resource.'
9580: },
9581: { linktext => 'Process Clicker',
9582: url => $url3,
9583: permission => 'F',
9584: icon => 'addClickerInfoFile.png',
9585: linktitle => 'Specify a file containing the clicker information for this resource.'
9586: },
9587: { linktext => 'Grade/Manage/Review Bubblesheets',
9588: url => $url4,
9589: permission => 'F',
9590: icon => 'stat.png',
9591: linktitle => 'Grade bubblesheet exams, upload/download bubblesheet data files, and review previously graded bubblesheet exams.'
9592: }
9593: ]
9594: });
9595:
9596: #$fields{'command'} = 'verify';
9597: #$url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
9598: #
9599: # Create the menu
9600: my $Str;
9601: # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
9602: $Str .= '<form method="post" action="" name="gradingMenu">';
9603: $Str .= '<input type="hidden" name="command" value="" />'.
9604: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
9605: '<input type="hidden" name="handgrade" value="'.$hdgrade.'" />'."\n".
9606: '<input type="hidden" name="probTitle" value="'.$probTitle.'" />'."\n".
9607: '<input type="hidden" name="saveState" value="" />'."\n".
9608: '<input type="hidden" name="gradingMenu" value="1" />'."\n".
9609: '<input type="hidden" name="showgrading" value="yes" />'."\n";
9610:
9611: $Str .= Apache::lonhtmlcommon::generate_menu(@menu);
9612: #$menudata->{'jscript'}
9613: $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt No.').'" '.
9614: ' onclick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
9615: ' /> '.
9616: &Apache::lonnet::recprefix($env{'request.course.id'}).
9617: '-<input type="text" name="receipt" size="4" onchange="javascript:checkReceiptNo(this.form,\'OK\')" />';
9618:
9619: $Str .="</form>\n";
9620: my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
9621: $request->print(<<GRADINGMENUJS);
9622: <script type="text/javascript" language="javascript">
9623: function checkChoice(formname,val,cmdx) {
9624: if (val <= 2) {
9625: var cmd = radioSelection(formname.radioChoice);
9626: var cmdsave = cmd;
9627: } else {
9628: cmd = cmdx;
9629: cmdsave = 'submission';
9630: }
9631: formname.command.value = cmd;
9632: if (val < 5) formname.submit();
9633: if (val == 5) {
9634: if (!checkReceiptNo(formname,'notOK')) {
9635: return false;
9636: } else {
9637: formname.submit();
9638: }
9639: }
9640: }
9641:
9642: function checkReceiptNo(formname,nospace) {
9643: var receiptNo = formname.receipt.value;
9644: var checkOpt = false;
9645: if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
9646: if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
9647: if (checkOpt) {
9648: alert("$receiptalert");
9649: formname.receipt.value = "";
9650: formname.receipt.focus();
9651: return false;
9652: }
9653: return true;
9654: }
9655: </script>
9656: GRADINGMENUJS
9657: &commonJSfunctions($request);
9658: return $Str;
9659: }
9660:
9661:
9662: #--- Displays the submissions first page -------
9663: sub submit_options {
9664: my ($request) = @_;
9665: my ($symb)=&get_symb($request);
9666: if (!$symb) {return '';}
9667: my $probTitle = &Apache::lonnet::gettitle($symb);
9668:
9669: my $receiptalert = &mt("Please enter a receipt number given by a student in the receipt box.");
9670: $request->print(<<GRADINGMENUJS);
9671: <script type="text/javascript" language="javascript">
9672: function checkChoice(formname,val,cmdx) {
9673: if (val <= 2) {
9674: var cmd = radioSelection(formname.radioChoice);
9675: var cmdsave = cmd;
9676: } else {
9677: cmd = cmdx;
9678: cmdsave = 'submission';
9679: }
9680: formname.command.value = cmd;
9681: formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
9682: ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
9683: if (val < 5) formname.submit();
9684: if (val == 5) {
9685: if (!checkReceiptNo(formname,'notOK')) { return false;}
9686: formname.submit();
9687: }
9688: if (val < 7) formname.submit();
9689: }
9690:
9691: function checkReceiptNo(formname,nospace) {
9692: var receiptNo = formname.receipt.value;
9693: var checkOpt = false;
9694: if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
9695: if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
9696: if (checkOpt) {
9697: alert("$receiptalert");
9698: formname.receipt.value = "";
9699: formname.receipt.focus();
9700: return false;
9701: }
9702: return true;
9703: }
9704: </script>
9705: GRADINGMENUJS
9706: &commonJSfunctions($request);
9707: my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
9708: my $result;
9709: my (undef,$sections) = &getclasslist('all','0');
9710: my $savedState = &savedState();
9711: my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
9712: my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
9713: my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
9714: my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
9715:
9716: # Preselect sections
9717: my $selsec="";
9718: if (ref($sections)) {
9719: foreach my $section (sort(@$sections)) {
9720: $selsec.='<option value="'.$section.'" '.
9721: ($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
9722: }
9723: }
9724:
9725: $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
9726: '<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
9727: '<input type="hidden" name="handgrade" value="'.$hdgrade.'" />'."\n".
9728: '<input type="hidden" name="probTitle" value="'.$probTitle.'" />'."\n".
9729: '<input type="hidden" name="command" value="" />'."\n".
9730: '<input type="hidden" name="saveState" value="" />'."\n".
9731: '<input type="hidden" name="gradingMenu" value="1" />'."\n".
9732: '<input type="hidden" name="showgrading" value="yes" />'."\n";
9733:
9734: $result.='
9735: <h2>
9736: '.&mt('Grade Current Resource').'
9737: </h2>
9738: <div>
9739: '.$table.'
9740: </div>
9741:
9742: <div class="LC_columnSection">
9743:
9744: <fieldset>
9745: <legend>
9746: '.&mt('Sections').'
9747: </legend>
9748: <select name="section" multiple="multiple" size="5">'."\n";
9749: $result.= $selsec;
9750: $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> ';
9751: $result.='
9752: </fieldset>
9753:
9754: <fieldset>
9755: <legend>
9756: '.&mt('Groups').'
9757: </legend>
9758: '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
9759: </fieldset>
9760:
9761: <fieldset>
9762: <legend>
9763: '.&mt('Access Status').'
9764: </legend>
9765: '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
9766: </fieldset>
9767:
9768: <fieldset>
9769: <legend>
9770: '.&mt('Submission Status').'
9771: </legend>
9772: <select name="submitonly" size="5">
9773: <option value="yes" '. ($saveSub eq 'yes' ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
9774: <option value="queued" '. ($saveSub eq 'queued' ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
9775: <option value="graded" '. ($saveSub eq 'graded' ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
9776: <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
9777: <option value="all" '. ($saveSub eq 'all' ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
9778: </select>
9779: </fieldset>
9780:
9781: </div>
9782:
9783: <br />
9784: <div>
9785: <div>
9786: <label>
9787: <input type="radio" name="radioChoice" value="submission" '.
9788: ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
9789: &mt('Select individual students to grade and view submissions.').'
9790: </label>
9791: </div>
9792: <div>
9793: <label>
9794: <input type="radio" name="radioChoice" value="viewgrades" '.
9795: ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
9796: &mt('Grade all selected students in a grading table.').'
9797: </label>
9798: </div>
9799: <div>
9800: <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' →" />
9801: </div>
9802: </div>
9803:
9804:
9805: <h2>
9806: '.&mt('Grade Complete Folder for One Student').'
9807: </h2>
9808: <div>
9809: <div>
9810: <label>
9811: <input type="radio" name="radioChoice" value="pickStudentPage" '.
9812: ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
9813: &mt('The <b>complete</b> page/sequence/folder: For one student').'
9814: </label>
9815: </div>
9816: <div>
9817: <input type="button" onclick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next').' →" />
9818: </div>
9819: </div>
9820: </form>';
9821: $result .= &show_grading_menu_form($symb);
9822: return $result;
9823: }
9824:
9825: sub reset_perm {
9826: undef(%perm);
9827: }
9828:
9829: sub init_perm {
9830: &reset_perm();
9831: foreach my $test_perm ('vgr','mgr','opa') {
9832:
9833: my $scope = $env{'request.course.id'};
9834: if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
9835:
9836: $scope .= '/'.$env{'request.course.sec'};
9837: if ( $perm{$test_perm}=
9838: &Apache::lonnet::allowed($test_perm,$scope)) {
9839: $perm{$test_perm.'_section'}=$env{'request.course.sec'};
9840: } else {
9841: delete($perm{$test_perm});
9842: }
9843: }
9844: }
9845: }
9846:
9847: sub init_old_essays {
9848: my ($symb,$apath,$adom,$aname) = @_;
9849: if ($symb ne '') {
9850: my %essays = &Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
9851: if (keys(%essays) > 0) {
9852: $old_essays{$symb} = \%essays;
9853: }
9854: }
9855: return;
9856: }
9857:
9858: sub reset_old_essays {
9859: undef(%old_essays);
9860: }
9861:
9862: sub gather_clicker_ids {
9863: my %clicker_ids;
9864:
9865: my $classlist = &Apache::loncoursedata::get_classlist();
9866:
9867: # Set up a couple variables.
9868: my $username_idx = &Apache::loncoursedata::CL_SNAME();
9869: my $domain_idx = &Apache::loncoursedata::CL_SDOM();
9870: my $status_idx = &Apache::loncoursedata::CL_STATUS();
9871:
9872: foreach my $student (keys(%$classlist)) {
9873: if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
9874: my $username = $classlist->{$student}->[$username_idx];
9875: my $domain = $classlist->{$student}->[$domain_idx];
9876: my $clickers =
9877: (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
9878: foreach my $id (split(/\,/,$clickers)) {
9879: $id=~s/^[\#0]+//;
9880: $id=~s/[\-\:]//g;
9881: if (exists($clicker_ids{$id})) {
9882: $clicker_ids{$id}.=','.$username.':'.$domain;
9883: } else {
9884: $clicker_ids{$id}=$username.':'.$domain;
9885: }
9886: }
9887: }
9888: return %clicker_ids;
9889: }
9890:
9891: sub gather_adv_clicker_ids {
9892: my %clicker_ids;
9893: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
9894: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
9895: my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
9896: foreach my $element (sort(keys(%coursepersonnel))) {
9897: foreach my $person (split(/\,/,$coursepersonnel{$element})) {
9898: my ($puname,$pudom)=split(/\:/,$person);
9899: my $clickers =
9900: (&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
9901: foreach my $id (split(/\,/,$clickers)) {
9902: $id=~s/^[\#0]+//;
9903: $id=~s/[\-\:]//g;
9904: if (exists($clicker_ids{$id})) {
9905: $clicker_ids{$id}.=','.$puname.':'.$pudom;
9906: } else {
9907: $clicker_ids{$id}=$puname.':'.$pudom;
9908: }
9909: }
9910: }
9911: }
9912: return %clicker_ids;
9913: }
9914:
9915: sub clicker_grading_parameters {
9916: return ('gradingmechanism' => 'scalar',
9917: 'upfiletype' => 'scalar',
9918: 'specificid' => 'scalar',
9919: 'pcorrect' => 'scalar',
9920: 'pincorrect' => 'scalar');
9921: }
9922:
9923: sub process_clicker {
9924: my ($r)=@_;
9925: my ($symb)=&get_symb($r);
9926: if (!$symb) {return '';}
9927: my $result=&checkforfile_js();
9928: $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
9929: my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
9930: $result.=$table;
9931: $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
9932: $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
9933: $result.=' <b>'.&mt('Specify a file containing the clicker information for this resource.').
9934: '</b></td></tr>'."\n";
9935: $result.='<tr bgcolor="#ffffe6"><td>'."\n";
9936: # Attempt to restore parameters from last session, set defaults if not present
9937: my %Saveable_Parameters=&clicker_grading_parameters();
9938: &Apache::loncommon::restore_course_settings('grades_clicker',
9939: \%Saveable_Parameters);
9940: if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
9941: if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
9942: if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
9943: if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
9944:
9945: my %checked;
9946: foreach my $gradingmechanism ('attendance','personnel','specific','given') {
9947: if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
9948: $checked{$gradingmechanism}=' checked="checked"';
9949: }
9950: }
9951:
9952: my $upload=&mt("Upload File");
9953: my $type=&mt("Type");
9954: my $attendance=&mt("Award points just for participation");
9955: my $personnel=&mt("Correctness determined from response by course personnel");
9956: my $specific=&mt("Correctness determined from response with clicker ID(s)");
9957: my $given=&mt("Correctness determined from given list of answers").' '.
9958: '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
9959: my $pcorrect=&mt("Percentage points for correct solution");
9960: my $pincorrect=&mt("Percentage points for incorrect solution");
9961: my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
9962: {'iclicker' => 'i>clicker',
9963: 'interwrite' => 'interwrite PRS',
9964: 'turning' => 'Turning Technologies'});
9965: $symb = &Apache::lonenc::check_encrypt($symb);
9966: $result.=<<ENDUPFORM;
9967: <script type="text/javascript">
9968: function sanitycheck() {
9969: // Accept only integer percentages
9970: document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
9971: document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
9972: // Find out grading choice
9973: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
9974: if (document.forms.gradesupload.gradingmechanism[i].checked) {
9975: gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
9976: }
9977: }
9978: // By default, new choice equals user selection
9979: newgradingchoice=gradingchoice;
9980: // Not good to give more points for false answers than correct ones
9981: if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
9982: document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
9983: }
9984: // If new choice is attendance only, and old choice was correctness-based, restore defaults
9985: if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
9986: document.forms.gradesupload.pcorrect.value=100;
9987: document.forms.gradesupload.pincorrect.value=100;
9988: }
9989: // If the values are different, cannot be attendance only
9990: if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
9991: (gradingchoice=='attendance')) {
9992: newgradingchoice='personnel';
9993: }
9994: // Change grading choice to new one
9995: for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
9996: if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
9997: document.forms.gradesupload.gradingmechanism[i].checked=true;
9998: } else {
9999: document.forms.gradesupload.gradingmechanism[i].checked=false;
10000: }
10001: }
10002: // Remember the old state
10003: document.forms.gradesupload.waschecked.value=newgradingchoice;
10004: }
10005: </script>
10006: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
10007: <input type="hidden" name="symb" value="$symb" />
10008: <input type="hidden" name="command" value="processclickerfile" />
10009: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
10010: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
10011: <input type="file" name="upfile" size="50" />
10012: <br /><label>$type: $selectform</label>
10013: <br /><label><input type="radio" name="gradingmechanism" value="attendance"$checked{'attendance'} onclick="sanitycheck()" />$attendance </label>
10014: <br /><label><input type="radio" name="gradingmechanism" value="personnel"$checked{'personnel'} onclick="sanitycheck()" />$personnel</label>
10015: <br /><label><input type="radio" name="gradingmechanism" value="specific"$checked{'specific'} onclick="sanitycheck()" />$specific </label>
10016: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
10017: <br /><label><input type="radio" name="gradingmechanism" value="given"$checked{'given'} onclick="sanitycheck()" />$given </label>
10018: <br />
10019: <input type="text" name="givenanswer" size="50" />
10020: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
10021: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onchange="sanitycheck()" /></label>
10022: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onchange="sanitycheck()" /></label>
10023: <br /><input type="button" onclick="javascript:checkUpload(this.form);" value="$upload" />
10024: </form>
10025: ENDUPFORM
10026: $result.='</td></tr></table>'."\n".
10027: '</td></tr></table><br /><br />'."\n";
10028: $result.=&show_grading_menu_form($symb);
10029: return $result;
10030: }
10031:
10032: sub process_clicker_file {
10033: my ($r)=@_;
10034: my ($symb)=&get_symb($r);
10035: if (!$symb) {return '';}
10036:
10037: my %Saveable_Parameters=&clicker_grading_parameters();
10038: &Apache::loncommon::store_course_settings('grades_clicker',
10039: \%Saveable_Parameters);
10040:
10041: my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
10042: if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
10043: $result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
10044: return $result.&show_grading_menu_form($symb);
10045: }
10046: if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
10047: $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
10048: return $result.&show_grading_menu_form($symb);
10049: }
10050: my $foundgiven=0;
10051: if ($env{'form.gradingmechanism'} eq 'given') {
10052: $env{'form.givenanswer'}=~s/^\s*//gs;
10053: $env{'form.givenanswer'}=~s/\s*$//gs;
10054: $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-\+]+/\,/g;
10055: $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
10056: my @answers=split(/\,/,$env{'form.givenanswer'});
10057: $foundgiven=$#answers+1;
10058: }
10059: my %clicker_ids=&gather_clicker_ids();
10060: my %correct_ids;
10061: if ($env{'form.gradingmechanism'} eq 'personnel') {
10062: %correct_ids=&gather_adv_clicker_ids();
10063: }
10064: if ($env{'form.gradingmechanism'} eq 'specific') {
10065: foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
10066: $correct_id=~tr/a-z/A-Z/;
10067: $correct_id=~s/\s//gs;
10068: $correct_id=~s/^[\#0]+//;
10069: $correct_id=~s/[\-\:]//g;
10070: if ($correct_id) {
10071: $correct_ids{$correct_id}='specified';
10072: }
10073: }
10074: }
10075: if ($env{'form.gradingmechanism'} eq 'attendance') {
10076: $result.=&mt('Score based on attendance only');
10077: } elsif ($env{'form.gradingmechanism'} eq 'given') {
10078: $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
10079: } else {
10080: my $number=0;
10081: $result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
10082: foreach my $id (sort(keys(%correct_ids))) {
10083: $result.='<br /><tt>'.$id.'</tt> - ';
10084: if ($correct_ids{$id} eq 'specified') {
10085: $result.=&mt('specified');
10086: } else {
10087: my ($uname,$udom)=split(/\:/,$correct_ids{$id});
10088: $result.=&Apache::loncommon::plainname($uname,$udom);
10089: }
10090: $number++;
10091: }
10092: $result.="</p>\n";
10093: if ($number==0) {
10094: $result .=
10095: &Apache::lonhtmlcommon::confirm_success(
10096: &mt('No IDs found to determine correct answer'),1);
10097: return $result,.&show_grading_menu_form($symb);
10098: }
10099: }
10100: if (length($env{'form.upfile'}) < 2) {
10101: $result .=
10102: &Apache::lonhtmlcommon::confirm_success(
10103: &mt('The file: [_1] you attempted to upload contained no information. Please check that you entered the correct filename.',
10104: '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>'),1);
10105: return $result.&show_grading_menu_form($symb);
10106: }
10107:
10108: # Were able to get all the info needed, now analyze the file
10109:
10110: $result.=&Apache::loncommon::studentbrowser_javascript();
10111: $symb = &Apache::lonenc::check_encrypt($symb);
10112: my $heading=&mt('Scanning clicker file');
10113: $result.=(<<ENDHEADER);
10114: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
10115: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
10116: <b>$heading</b></td></tr><tr bgcolor="#ffffe6"><td>
10117: <form method="post" action="/adm/grades" name="clickeranalysis">
10118: <input type="hidden" name="symb" value="$symb" />
10119: <input type="hidden" name="command" value="assignclickergrades" />
10120: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
10121: <input type="hidden" name="saveState" value="$env{'form.saveState'}" />
10122: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
10123: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
10124: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
10125: ENDHEADER
10126: if ($env{'form.gradingmechanism'} eq 'given') {
10127: $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
10128: }
10129: my %responses;
10130: my @questiontitles;
10131: my $errormsg='';
10132: my $number=0;
10133: if ($env{'form.upfiletype'} eq 'iclicker') {
10134: ($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
10135: }
10136: if ($env{'form.upfiletype'} eq 'interwrite') {
10137: ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
10138: }
10139: if ($env{'form.upfiletype'} eq 'turning') {
10140: ($errormsg,$number)=&turning_eval(\@questiontitles,\%responses);
10141: }
10142: $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
10143: '<input type="hidden" name="number" value="'.$number.'" />'.
10144: &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
10145: $env{'form.pcorrect'},$env{'form.pincorrect'}).
10146: '<br />';
10147: if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
10148: $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
10149: return $result.&show_grading_menu_form($symb);
10150: }
10151: # Remember Question Titles
10152: # FIXME: Possibly need delimiter other than ":"
10153: for (my $i=0;$i<$number;$i++) {
10154: $result.='<input type="hidden" name="question:'.$i.'" value="'.
10155: &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
10156: }
10157: my $correct_count=0;
10158: my $student_count=0;
10159: my $unknown_count=0;
10160: # Match answers with usernames
10161: # FIXME: Possibly need delimiter other than ":"
10162: foreach my $id (keys(%responses)) {
10163: if ($correct_ids{$id}) {
10164: $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
10165: $correct_count++;
10166: } elsif ($clicker_ids{$id}) {
10167: if ($clicker_ids{$id}=~/\,/) {
10168: # More than one user with the same clicker!
10169: $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
10170: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10171: "<select name='multi".$id."'>";
10172: foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
10173: $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
10174: }
10175: $result.='</select>';
10176: $unknown_count++;
10177: } else {
10178: # Good: found one and only one user with the right clicker
10179: $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
10180: $student_count++;
10181: }
10182: } else {
10183: $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
10184: $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
10185: "\n".&mt("Username").": <input type='text' name='uname".$id."' /> ".
10186: "\n".&mt("Domain").": ".
10187: &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).' '.
10188: &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id,0,$id);
10189: $unknown_count++;
10190: }
10191: }
10192: $result.='<hr />'.
10193: &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
10194: if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
10195: if ($correct_count==0) {
10196: $errormsg.="Found no correct answers for grading!";
10197: } elsif ($correct_count>1) {
10198: $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
10199: }
10200: }
10201: if ($number<1) {
10202: $errormsg.="Found no questions.";
10203: }
10204: if ($errormsg) {
10205: $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
10206: } else {
10207: $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
10208: }
10209: $result.='</form></td></tr></table>'."\n".
10210: '</td></tr></table><br /><br />'."\n";
10211: return $result.&show_grading_menu_form($symb);
10212: }
10213:
10214: sub iclicker_eval {
10215: my ($questiontitles,$responses)=@_;
10216: my $number=0;
10217: my $errormsg='';
10218: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10219: my %components=&Apache::loncommon::record_sep($line);
10220: my @entries=map {$components{$_}} (sort(keys(%components)));
10221: if ($entries[0] eq 'Question') {
10222: for (my $i=3;$i<$#entries;$i+=6) {
10223: $$questiontitles[$number]=$entries[$i];
10224: $number++;
10225: }
10226: }
10227: if ($entries[0]=~/^\#/) {
10228: my $id=$entries[0];
10229: my @idresponses;
10230: $id=~s/^[\#0]+//;
10231: for (my $i=0;$i<$number;$i++) {
10232: my $idx=3+$i*6;
10233: $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+]+//g;
10234: push(@idresponses,$entries[$idx]);
10235: }
10236: $$responses{$id}=join(',',@idresponses);
10237: }
10238: }
10239: return ($errormsg,$number);
10240: }
10241:
10242: sub interwrite_eval {
10243: my ($questiontitles,$responses)=@_;
10244: my $number=0;
10245: my $errormsg='';
10246: my $skipline=1;
10247: my $questionnumber=0;
10248: my %idresponses=();
10249: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10250: my %components=&Apache::loncommon::record_sep($line);
10251: my @entries=map {$components{$_}} (sort(keys(%components)));
10252: if ($entries[1] eq 'Time') { $skipline=0; next; }
10253: if ($entries[1] eq 'Response') { $skipline=1; }
10254: next if $skipline;
10255: if ($entries[0]!=$questionnumber) {
10256: $questionnumber=$entries[0];
10257: $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
10258: $number++;
10259: }
10260: my $id=$entries[4];
10261: $id=~s/^[\#0]+//;
10262: $id=~s/^v\d*\://i;
10263: $id=~s/[\-\:]//g;
10264: $idresponses{$id}[$number]=$entries[6];
10265: }
10266: foreach my $id (keys(%idresponses)) {
10267: $$responses{$id}=join(',',@{$idresponses{$id}});
10268: $$responses{$id}=~s/^\s*\,//;
10269: }
10270: return ($errormsg,$number);
10271: }
10272:
10273: sub turning_eval {
10274: my ($questiontitles,$responses)=@_;
10275: my $number=0;
10276: my $errormsg='';
10277: foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
10278: my %components=&Apache::loncommon::record_sep($line);
10279: my @entries=map {$components{$_}} (sort(keys(%components)));
10280: if ($#entries>$number) { $number=$#entries; }
10281: my $id=$entries[0];
10282: my @idresponses;
10283: $id=~s/^[\#0]+//;
10284: unless ($id) { next; }
10285: for (my $idx=1;$idx<=$#entries;$idx++) {
10286: $entries[$idx]=~s/\,/\;/g;
10287: $entries[$idx]=~s/[^a-zA-Z0-9\.\*\-\+\;]+//g;
10288: push(@idresponses,$entries[$idx]);
10289: }
10290: $$responses{$id}=join(',',@idresponses);
10291: }
10292: for (my $i=1; $i<=$number; $i++) {
10293: $$questiontitles[$i]=&mt('Question [_1]',$i);
10294: }
10295: return ($errormsg,$number);
10296: }
10297:
10298: sub assign_clicker_grades {
10299: my ($r)=@_;
10300: my ($symb)=&get_symb($r);
10301: if (!$symb) {return '';}
10302: # See which part we are saving to
10303: my $res_error;
10304: my ($partlist,$handgrade,$responseType) = &response_type($symb,\$res_error);
10305: if ($res_error) {
10306: return &navmap_errormsg();
10307: }
10308: # FIXME: This should probably look for the first handgradeable part
10309: my $part=$$partlist[0];
10310: # Start screen output
10311: my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
10312:
10313: $result .= '<br />'.
10314: &Apache::loncommon::start_data_table().
10315: &Apache::loncommon::start_data_table_header_row().
10316: '<th>'.&mt('Assigning grades based on clicker file').'</th>'.
10317: &Apache::loncommon::end_data_table_header_row().
10318: &Apache::loncommon::start_data_table_row().'<td>';
10319:
10320: # Get correct result
10321: # FIXME: Possibly need delimiter other than ":"
10322: my @correct=();
10323: my $gradingmechanism=$env{'form.gradingmechanism'};
10324: my $number=$env{'form.number'};
10325: if ($gradingmechanism ne 'attendance') {
10326: foreach my $key (keys(%env)) {
10327: if ($key=~/^form\.correct\:/) {
10328: my @input=split(/\,/,$env{$key});
10329: for (my $i=0;$i<=$#input;$i++) {
10330: if (($correct[$i]) && ($input[$i]) &&
10331: ($correct[$i] ne $input[$i])) {
10332: $result.='<br /><span class="LC_warning">'.
10333: &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
10334: $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
10335: } elsif (($input[$i]) || ($input[$i] eq '0')) {
10336: $correct[$i]=$input[$i];
10337: }
10338: }
10339: }
10340: }
10341: for (my $i=0;$i<$number;$i++) {
10342: if ((!$correct[$i]) && ($correct[$i] ne '0')) {
10343: $result.='<br /><span class="LC_error">'.
10344: &mt('No correct result given for question "[_1]"!',
10345: $env{'form.question:'.$i}).'</span>';
10346: }
10347: }
10348: $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ((($_) || ($_ eq '0'))?$_:'-') } @correct));
10349: }
10350: # Start grading
10351: my $pcorrect=$env{'form.pcorrect'};
10352: my $pincorrect=$env{'form.pincorrect'};
10353: my $storecount=0;
10354: my %users=();
10355: foreach my $key (keys(%env)) {
10356: my $user='';
10357: if ($key=~/^form\.student\:(.*)$/) {
10358: $user=$1;
10359: }
10360: if ($key=~/^form\.unknown\:(.*)$/) {
10361: my $id=$1;
10362: if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
10363: $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
10364: } elsif ($env{'form.multi'.$id}) {
10365: $user=$env{'form.multi'.$id};
10366: }
10367: }
10368: if ($user) {
10369: if ($users{$user}) {
10370: $result.='<br /><span class="LC_warning">'.
10371: &mt('More than one entry found for [_1]!','<tt>'.$user.'</tt>').
10372: '</span><br />';
10373: }
10374: $users{$user}=1;
10375: my @answer=split(/\,/,$env{$key});
10376: my $sum=0;
10377: my $realnumber=$number;
10378: for (my $i=0;$i<$number;$i++) {
10379: if ($correct[$i] eq '-') {
10380: $realnumber--;
10381: } elsif ($answer[$i]) {
10382: if ($gradingmechanism eq 'attendance') {
10383: $sum+=$pcorrect;
10384: } elsif ($correct[$i] eq '*') {
10385: $sum+=$pcorrect;
10386: } else {
10387: # We actually grade if correct or not
10388: my $increment=$pincorrect;
10389: # Special case: numerical answer "0"
10390: if ($correct[$i] eq '0') {
10391: if ($answer[$i]=~/^[0\.]+$/) {
10392: $increment=$pcorrect;
10393: }
10394: # General numerical answer, both evaluate to something non-zero
10395: } elsif ((1.0*$correct[$i]!=0) && (1.0*$answer[$i]!=0)) {
10396: if (1.0*$correct[$i]==1.0*$answer[$i]) {
10397: $increment=$pcorrect;
10398: }
10399: # Must be just alphanumeric
10400: } elsif ($answer[$i] eq $correct[$i]) {
10401: $increment=$pcorrect;
10402: }
10403: $sum+=$increment;
10404: }
10405: }
10406: }
10407: my $ave=$sum/(100*$realnumber);
10408: # Store
10409: my ($username,$domain)=split(/\:/,$user);
10410: my %grades=();
10411: $grades{"resource.$part.solved"}='correct_by_override';
10412: $grades{"resource.$part.awarded"}=$ave;
10413: $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
10414: my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
10415: $env{'request.course.id'},
10416: $domain,$username);
10417: if ($returncode ne 'ok') {
10418: $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
10419: } else {
10420: $storecount++;
10421: }
10422: }
10423: }
10424: # We are done
10425: $result.='<br />'.&mt('Successfully stored grades for [quant,_1,student].',$storecount).
10426: '</td>'.
10427: &Apache::loncommon::end_data_table_row().
10428: &Apache::loncommon::end_data_table()."<br /><br />\n";
10429: return $result.&show_grading_menu_form($symb);
10430: }
10431:
10432: sub navmap_errormsg {
10433: return '<div class="LC_error">'.
10434: &mt('An error occurred retrieving information about resources in the course.').'<br />'.
10435: &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>').
10436: '</div>';
10437: }
10438:
10439: sub startpage {
10440: my ($r,$symb,$crumbs,$onlyfolderflag,$nodisplayflag,$stuvcurrent,$stuvdisp,$nomenu,$js) = @_;
10441: if ($nomenu) {
10442: $r->print(&Apache::loncommon::start_page("Student's Version",$js,{'only_body' => '1'}));
10443: } else {
10444: $r->print(&Apache::loncommon::start_page('Grading',$js,
10445: {'bread_crumbs' => $crumbs}));
10446: }
10447: unless ($nodisplayflag) {
10448: $r->print(&Apache::lonhtmlcommon::resource_info_box($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp));
10449: }
10450: }
10451:
10452: sub handler {
10453: my $request=$_[0];
10454: &reset_caches();
10455: if ($request->header_only) {
10456: &Apache::loncommon::content_type($request,'text/html');
10457: $request->send_http_header;
10458: return OK;
10459: }
10460: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
10461:
10462: my $symb=&get_symb($request,1);
10463: my @commands=&Apache::loncommon::get_env_multiple('form.command');
10464: my $command=$commands[0];
10465:
10466: if ($#commands > 0) {
10467: &Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
10468: }
10469:
10470: $ssi_error = 0;
10471: my $brcrum = [{href=>"/adm/grades",text=>"Grading"}];
10472: my $start_page = &Apache::loncommon::start_page('Grading',undef,
10473: {'bread_crumbs' => $brcrum});
10474: if ($symb eq '' && $command eq '') {
10475: if ($env{'user.adv'}) {
10476: &Apache::loncommon::content_type($request,'text/html');
10477: $request->send_http_header;
10478: $request->print($start_page);
10479: if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
10480: ($env{'form.codethree'})) {
10481: my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
10482: $env{'form.codethree'};
10483: my ($tsymb,$tuname,$tudom,$tcrsid)=
10484: &Apache::lonnet::checkin($token);
10485: if ($tsymb) {
10486: my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
10487: if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
10488: $request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
10489: ('grade_username' => $tuname,
10490: 'grade_domain' => $tudom,
10491: 'grade_courseid' => $tcrsid,
10492: 'grade_symb' => $tsymb)));
10493: } else {
10494: $request->print('<h3>Not authorized: '.$token.'</h3>');
10495: }
10496: } else {
10497: $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
10498: }
10499: } else {
10500: $request->print(&Apache::lonxml::tokeninputfield());
10501: }
10502: } elsif ($env{'request.course.id'}) {
10503: &init_perm();
10504: if (!%perm) {
10505: $request->internal_redirect('/adm/quickgrades');
10506: return OK;
10507: } else {
10508: &Apache::loncommon::content_type($request,'text/html');
10509: $request->send_http_header;
10510: $request->print($start_page);
10511: }
10512: }
10513: } else {
10514: &init_perm();
10515: if (!$env{'request.course.id'}) {
10516: unless ((&Apache::lonnet::allowed('usc',$env{'request.role.domain'})) &&
10517: ($command =~ /^scantronupload/)) {
10518: # Not in a course.
10519: $env{'user.error.msg'}="/adm/grades::vgr:0:0:Cannot display grades page outside course context";
10520: return HTTP_NOT_ACCEPTABLE;
10521: }
10522: } elsif (!%perm) {
10523: $request->internal_redirect('/adm/quickgrades');
10524: }
10525: &Apache::loncommon::content_type($request,'text/html');
10526: $request->send_http_header;
10527: unless ((($command eq 'submission' || $command eq 'versionsub')) && ($perm{'vgr'})) {
10528: $request->print($start_page);
10529: }
10530: if ($command eq 'submission' && $perm{'vgr'}) {
10531: my ($stuvcurrent,$stuvdisp,$versionform,$js);
10532: if (($env{'form.student'} ne '') && ($env{'form.userdom'} ne '')) {
10533: ($stuvcurrent,$stuvdisp,$versionform,$js) =
10534: &choose_task_version_form($symb,$env{'form.student'},
10535: $env{'form.userdom'});
10536: }
10537: &startpage($request,$symb,[{href=>"", text=>"Student Submissions"}],undef,undef,$stuvcurrent,$stuvdisp,undef,$js);
10538: if ($versionform) {
10539: $request->print($versionform);
10540: }
10541: $request->print('<br clear="all" />');
10542: ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
10543: } elsif ($command eq 'versionsub' && $perm{'vgr'}) {
10544: my ($stuvcurrent,$stuvdisp,$versionform,$js) =
10545: &choose_task_version_form($symb,$env{'form.student'},
10546: $env{'form.userdom'},
10547: $env{'form.inhibitmenu'});
10548: &startpage($request,$symb,[{href=>"", text=>"Previous Student Version"}],undef,undef,$stuvcurrent,$stuvdisp,$env{'form.inhibitmenu'},$js);
10549: if ($versionform) {
10550: $request->print($versionform);
10551: }
10552: $request->print('<br clear="all" />');
10553: $request->print(&show_previous_task_version($request,$symb));
10554: } elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
10555: &pickStudentPage($request);
10556: } elsif ($command eq 'displayPage' && $perm{'vgr'}) {
10557: &displayPage($request);
10558: } elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
10559: &updateGradeByPage($request);
10560: } elsif ($command eq 'processGroup' && $perm{'vgr'}) {
10561: &processGroup($request);
10562: } elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
10563: $request->print(&grading_menu($request));
10564: } elsif ($command eq 'submit_options' && $perm{'vgr'}) {
10565: $request->print(&submit_options($request));
10566: } elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
10567: $request->print(&viewgrades($request));
10568: } elsif ($command eq 'handgrade' && $perm{'mgr'}) {
10569: $request->print(&processHandGrade($request));
10570: } elsif ($command eq 'editgrades' && $perm{'mgr'}) {
10571: $request->print(&editgrades($request));
10572: } elsif ($command eq 'verify' && $perm{'vgr'}) {
10573: $request->print(&verifyreceipt($request));
10574: } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
10575: $request->print(&process_clicker($request));
10576: } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
10577: $request->print(&process_clicker_file($request));
10578: } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
10579: $request->print(&assign_clicker_grades($request));
10580: } elsif ($command eq 'csvform' && $perm{'mgr'}) {
10581: $request->print(&upcsvScores_form($request));
10582: } elsif ($command eq 'csvupload' && $perm{'mgr'}) {
10583: $request->print(&csvupload($request));
10584: } elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
10585: $request->print(&csvuploadmap($request));
10586: } elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
10587: if ($env{'form.associate'} ne 'Reverse Association') {
10588: $request->print(&csvuploadoptions($request));
10589: } else {
10590: if ( $env{'form.upfile_associate'} ne 'reverse' ) {
10591: $env{'form.upfile_associate'} = 'reverse';
10592: } else {
10593: $env{'form.upfile_associate'} = 'forward';
10594: }
10595: $request->print(&csvuploadmap($request));
10596: }
10597: } elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
10598: $request->print(&csvuploadassign($request));
10599: } elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
10600: $request->print(&scantron_selectphase($request));
10601: } elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
10602: $request->print(&scantron_do_warning($request));
10603: } elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
10604: $request->print(&scantron_validate_file($request));
10605: } elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
10606: $request->print(&scantron_process_students($request));
10607: } elsif ($command eq 'scantronupload' &&
10608: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10609: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10610: $request->print(&scantron_upload_scantron_data($request));
10611: } elsif ($command eq 'scantronupload_save' &&
10612: (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
10613: &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
10614: $request->print(&scantron_upload_scantron_data_save($request));
10615: } elsif ($command eq 'scantron_download' &&
10616: &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
10617: $request->print(&scantron_download_scantron_data($request));
10618: } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
10619: $request->print(&checkscantron_results($request));
10620: } elsif ($command) {
10621: $request->print('<p class="LC_error">'.&mt('Access Denied ([_1])',$command).'</p>');
10622: }
10623: }
10624: if ($ssi_error) {
10625: &ssi_print_error($request);
10626: }
10627: $request->print(&Apache::loncommon::end_page());
10628: &reset_caches();
10629: return OK;
10630: }
10631:
10632: 1;
10633:
10634: __END__;
10635:
10636:
10637: =head1 NAME
10638:
10639: Apache::grades
10640:
10641: =head1 SYNOPSIS
10642:
10643: Handles the viewing of grades.
10644:
10645: This is part of the LearningOnline Network with CAPA project
10646: described at http://www.lon-capa.org.
10647:
10648: =head1 OVERVIEW
10649:
10650: Do an ssi with retries:
10651: While I'd love to factor out this with the vesrion in lonprintout,
10652: 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
10653: I'm not quite ready to invent (e.g. an ssi_with_retry object).
10654:
10655: At least the logic that drives this has been pulled out into loncommon.
10656:
10657:
10658:
10659: ssi_with_retries - Does the server side include of a resource.
10660: if the ssi call returns an error we'll retry it up to
10661: the number of times requested by the caller.
10662: If we still have a problem, no text is appended to the
10663: output and we set some global variables.
10664: to indicate to the caller an SSI error occurred.
10665: All of this is supposed to deal with the issues described
10666: in LON-CAPA BZ 5631 see:
10667: http://bugs.lon-capa.org/show_bug.cgi?id=5631
10668: by informing the user that this happened.
10669:
10670: Parameters:
10671: resource - The resource to include. This is passed directly, without
10672: interpretation to lonnet::ssi.
10673: form - The form hash parameters that guide the interpretation of the resource
10674:
10675: retries - Number of retries allowed before giving up completely.
10676: Returns:
10677: On success, returns the rendered resource identified by the resource parameter.
10678: Side Effects:
10679: The following global variables can be set:
10680: ssi_error - If an unrecoverable error occurred this becomes true.
10681: It is up to the caller to initialize this to false
10682: if desired.
10683: ssi_error_resource - If an unrecoverable error occurred, this is the value
10684: of the resource that could not be rendered by the ssi
10685: call.
10686: ssi_error_message - The error string fetched from the ssi response
10687: in the event of an error.
10688:
10689:
10690: =head1 HANDLER SUBROUTINE
10691:
10692: ssi_with_retries()
10693:
10694: =head1 SUBROUTINES
10695:
10696: =over
10697:
10698: =item scantron_get_correction() :
10699:
10700: Builds the interface screen to interact with the operator to fix a
10701: specific error condition in a specific scanline
10702:
10703: Arguments:
10704: $r - Apache request object
10705: $i - number of the current scanline
10706: $scan_record - hash ref as returned from &scantron_parse_scanline()
10707: $scan_config - hash ref as returned from &get_scantron_config()
10708: $line - full contents of the current scanline
10709: $error - error condition, valid values are
10710: 'incorrectCODE', 'duplicateCODE',
10711: 'doublebubble', 'missingbubble',
10712: 'duplicateID', 'incorrectID'
10713: $arg - extra information needed
10714: For errors:
10715: - duplicateID - paper number that this studentID was seen before on
10716: - duplicateCODE - array ref of the paper numbers this CODE was
10717: seen on before
10718: - incorrectCODE - current incorrect CODE
10719: - doublebubble - array ref of the bubble lines that have double
10720: bubble errors
10721: - missingbubble - array ref of the bubble lines that have missing
10722: bubble errors
10723:
10724: $randomorder - True if exam folder has randomorder set
10725: $randompick - True if exam folder has randompick set
10726: $respnumlookup - Reference to HASH mapping question numbers in bubble lines
10727: for current line to question number used for same question
10728: in "Master Seqence" (as seen by Course Coordinator).
10729: $startline - Reference to hash where key is question number (0 is first)
10730: and value is number of first bubble line for current student
10731: or code-based randompick and/or randomorder.
10732:
10733:
10734: =item scantron_get_maxbubble() :
10735:
10736: Arguments:
10737: $nav_error - Reference to scalar which is a flag to indicate a
10738: failure to retrieve a navmap object.
10739: if $nav_error is set to 1 by scantron_get_maxbubble(), the
10740: calling routine should trap the error condition and display the warning
10741: found in &navmap_errormsg().
10742:
10743: $scantron_config - Reference to bubblesheet format configuration hash.
10744:
10745: Returns the maximum number of bubble lines that are expected to
10746: occur. Does this by walking the selected sequence rendering the
10747: resource and then checking &Apache::lonxml::get_problem_counter()
10748: for what the current value of the problem counter is.
10749:
10750: Caches the results to $env{'form.scantron_maxbubble'},
10751: $env{'form.scantron.bubble_lines.n'},
10752: $env{'form.scantron.first_bubble_line.n'} and
10753: $env{"form.scantron.sub_bubblelines.n"}
10754: which are the total number of bubble lines, the number of bubble
10755: lines for response n and number of the first bubble line for response n,
10756: and a comma separated list of numbers of bubble lines for sub-questions
10757: (for optionresponse, matchresponse, and rankresponse items), for response n.
10758:
10759:
10760: =item scantron_validate_missingbubbles() :
10761:
10762: Validates all scanlines in the selected file to not have any
10763: answers that don't have bubbles that have not been verified
10764: to be bubble free.
10765:
10766: =item scantron_process_students() :
10767:
10768: Routine that does the actual grading of the bubblesheet information.
10769:
10770: The parsed scanline hash is added to %env
10771:
10772: Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
10773: foreach resource , with the form data of
10774:
10775: 'submitted' =>'scantron'
10776: 'grade_target' =>'grade',
10777: 'grade_username'=> username of student
10778: 'grade_domain' => domain of student
10779: 'grade_courseid'=> of course
10780: 'grade_symb' => symb of resource to grade
10781:
10782: This triggers a grading pass. The problem grading code takes care
10783: of converting the bubbled letter information (now in %env) into a
10784: valid submission.
10785:
10786: =item scantron_upload_scantron_data() :
10787:
10788: Creates the screen for adding a new bubblesheet data file to a course.
10789:
10790: =item scantron_upload_scantron_data_save() :
10791:
10792: Adds a provided bubble information data file to the course if user
10793: has the correct privileges to do so.
10794:
10795: =item valid_file() :
10796:
10797: Validates that the requested bubble data file exists in the course.
10798:
10799: =item scantron_download_scantron_data() :
10800:
10801: Shows a list of the three internal files (original, corrected,
10802: skipped) for a specific bubblesheet data file that exists in the
10803: course.
10804:
10805: =item scantron_validate_ID() :
10806:
10807: Validates all scanlines in the selected file to not have any
10808: invalid or underspecified student/employee IDs
10809:
10810: =item navmap_errormsg() :
10811:
10812: Returns HTML mark-up inside a <div></div> with a link to re-initialize the course.
10813: Should be called whenever the request to instantiate a navmap object fails.
10814:
10815: =back
10816:
10817: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>